lang
stringclasses 1
value | license
stringclasses 13
values | stderr
stringlengths 0
350
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 7
45.1k
| new_contents
stringlengths 0
1.87M
| new_file
stringlengths 6
292
| old_contents
stringlengths 0
1.87M
| message
stringlengths 6
9.26k
| old_file
stringlengths 6
292
| subject
stringlengths 0
4.45k
|
---|---|---|---|---|---|---|---|---|---|---|---|
Java | apache-2.0 | 82048d04e77178635b2cf45a38b4923682c5018b | 0 | orhanobut/hawk,orhanobut/hawk,MaTriXy/hawk | package com.orhanobut.hawk;
import android.content.Context;
public final class Hawk {
static Hawk HAWK;
private final Storage storage;
private final Converter converter;
private final Encryption encryption;
private final LogLevel logLevel;
private Hawk(HawkBuilder builder) {
storage = builder.getStorage();
converter = builder.getConverter();
encryption = builder.getEncryption();
logLevel = builder.getLogLevel();
}
/**
* This will init the hawk without password protection.
*
* @param context is used to instantiate context based objects.
* ApplicationContext will be used
*/
public static HawkBuilder init(Context context) {
HawkUtils.checkNull("Context", context);
HAWK = null;
return new HawkBuilder(context);
}
static void build(HawkBuilder hawkBuilder) {
HAWK = new Hawk(hawkBuilder);
}
/**
* Saves every type of Objects. List, List<T>, primitives
*
* @param key is used to save the data
* @param value is the data that is gonna be saved. Value can be object, list type, primitives
*
* @return true if put is successful
*/
public static <T> boolean put(String key, T value) {
HawkUtils.checkNull("Key", key);
HawkUtils.validateBuild();
//if the value is null, simply delete it
if (value == null) {
return delete(key);
}
String encodedText = zip(key, value);
//if any exception occurs during encoding, encodedText will be null and thus operation is unsuccessful
return encodedText != null && HAWK.storage.put(key, encodedText);
}
/**
* @param key is used to get the saved data
*
* @return the saved object
*/
public static <T> T get(String key) {
HawkUtils.checkNull("Key", key);
HawkUtils.validateBuild();
String persistedText = HAWK.storage.get(key);
if (persistedText == null) {
return null;
}
DataInfo dataInfo = DataHelper.getDataInfo(persistedText);
String plainText = null;
try {
plainText = HAWK.encryption.decrypt(key, dataInfo.cipherText);
} catch (Exception e) {
e.printStackTrace();
}
if (plainText == null) {
return null;
}
try {
return HAWK.converter.fromString(plainText, dataInfo);
} catch (Exception e) {
Logger.d(e.getMessage());
}
return null;
}
/**
* Gets the saved data, if it is null, default value will be returned
*
* @param key is used to get the saved data
* @param defaultValue will be return if the response is null
*
* @return the saved object
*/
public static <T> T get(String key, T defaultValue) {
T t = get(key);
if (t == null) {
return defaultValue;
}
return t;
}
/**
* Size of the saved data. Each key will be counted as 1
*
* @return the size
*/
public static long count() {
HawkUtils.validateBuild();
return HAWK.storage.count();
}
/**
* Clears the storage, note that crypto data won't be deleted such as salt key etc.
* Use resetCrypto in order to clear crypto information
*
* @return true if clear is successful
*/
public static boolean clear() {
HawkUtils.validateBuild();
return HAWK.storage.clear();
}
/**
* Removes the given key/value from the storage
*
* @param key is used for removing related data from storage
*
* @return true if delete is successful
*/
public static boolean delete(String key) {
HawkUtils.validateBuild();
return HAWK.storage.delete(key);
}
/**
* Checks the given key whether it exists or not
*
* @param key is the key to check
*
* @return true if it exists in the storage
*/
public static boolean contains(String key) {
HawkUtils.validateBuild();
return HAWK.storage.contains(key);
}
/**
* Clears all saved data that is used for the crypto
*
* @return true if reset is successful
*/
public static boolean resetCrypto() {
HawkUtils.validateBuild();
return HAWK.encryption.reset();
}
public static LogLevel getLogLevel() {
if (HAWK == null) {
return LogLevel.NONE;
}
return HAWK.logLevel;
}
/**
* Use this method to verify if Hawk is ready to be used.
*
* @return true if correctly initialised and built. False otherwise.
*/
public static boolean isBuilt() {
return HAWK != null;
}
/**
* Encodes the given value as full text (cipher + data info)
*
* @param value is the given value to toString
*
* @return full text as string
*/
private static <T> String zip(String key, T value) {
HawkUtils.checkNull("Value", value);
String plainText = HAWK.converter.toString(value);
if (plainText == null) {
return null;
}
String cipherText = null;
try {
cipherText = HAWK.encryption.encrypt(key, plainText);
} catch (Exception e) {
e.printStackTrace();
}
if (cipherText == null) {
return null;
}
return DataHelper.addType(cipherText, value);
}
public static void destroy() {
HAWK = null;
}
}
| hawk/src/main/java/com/orhanobut/hawk/Hawk.java | package com.orhanobut.hawk;
import android.content.Context;
public final class Hawk {
static Hawk HAWK;
private final Storage storage;
private final Converter converter;
private final Encryption encryption;
private final LogLevel logLevel;
private Hawk(HawkBuilder builder) {
storage = builder.getStorage();
converter = builder.getConverter();
encryption = builder.getEncryption();
logLevel = builder.getLogLevel();
}
/**
* This will init the hawk without password protection.
*
* @param context is used to instantiate context based objects.
* ApplicationContext will be used
*/
public static HawkBuilder init(Context context) {
HawkUtils.checkNull("Context", context);
HAWK = null;
return new HawkBuilder(context);
}
static void build(HawkBuilder hawkBuilder) {
HAWK = new Hawk(hawkBuilder);
}
/**
* Saves every type of Objects. List, List<T>, primitives
*
* @param key is used to save the data
* @param value is the data that is gonna be saved. Value can be object, list type, primitives
*
* @return true if put is successful
*/
public static <T> boolean put(String key, T value) {
HawkUtils.checkNull("Key", key);
HawkUtils.validateBuild();
//if the value is null, simply delete it
if (value == null) {
return delete(key);
}
String encodedText = zip(key, value);
//if any exception occurs during encoding, encodedText will be null and thus operation is unsuccessful
return encodedText != null && HAWK.storage.put(key, encodedText);
}
/**
* @param key is used to get the saved data
*
* @return the saved object
*/
public static <T> T get(String key) {
HawkUtils.checkNull("Key", key);
HawkUtils.validateBuild();
String fullText = HAWK.storage.get(key);
if (fullText == null) {
return null;
}
DataInfo dataInfo = DataHelper.getDataInfo(fullText);
String decryptedValue = null;
try {
decryptedValue = HAWK.encryption.decrypt(key, dataInfo.cipherText);
} catch (Exception e) {
e.printStackTrace();
}
if (decryptedValue == null) {
return null;
}
try {
return HAWK.converter.fromString(decryptedValue, dataInfo);
} catch (Exception e) {
Logger.d(e.getMessage());
}
return null;
}
/**
* Gets the saved data, if it is null, default value will be returned
*
* @param key is used to get the saved data
* @param defaultValue will be return if the response is null
*
* @return the saved object
*/
public static <T> T get(String key, T defaultValue) {
T t = get(key);
if (t == null) {
return defaultValue;
}
return t;
}
/**
* Size of the saved data. Each key will be counted as 1
*
* @return the size
*/
public static long count() {
HawkUtils.validateBuild();
return HAWK.storage.count();
}
/**
* Clears the storage, note that crypto data won't be deleted such as salt key etc.
* Use resetCrypto in order to clear crypto information
*
* @return true if clear is successful
*/
public static boolean clear() {
HawkUtils.validateBuild();
return HAWK.storage.clear();
}
/**
* Removes the given key/value from the storage
*
* @param key is used for removing related data from storage
*
* @return true if delete is successful
*/
public static boolean delete(String key) {
HawkUtils.validateBuild();
return HAWK.storage.delete(key);
}
/**
* Checks the given key whether it exists or not
*
* @param key is the key to check
*
* @return true if it exists in the storage
*/
public static boolean contains(String key) {
HawkUtils.validateBuild();
return HAWK.storage.contains(key);
}
/**
* Clears all saved data that is used for the crypto
*
* @return true if reset is successful
*/
public static boolean resetCrypto() {
HawkUtils.validateBuild();
return HAWK.encryption.reset();
}
public static LogLevel getLogLevel() {
if (HAWK == null) {
return LogLevel.NONE;
}
return HAWK.logLevel;
}
/**
* Use this method to verify if Hawk is ready to be used.
*
* @return true if correctly initialised and built. False otherwise.
*/
public static boolean isBuilt() {
return HAWK != null;
}
/**
* Encodes the given value as full text (cipher + data info)
*
* @param value is the given value to toString
*
* @return full text as string
*/
private static <T> String zip(String key, T value) {
HawkUtils.checkNull("Value", value);
String encodedValue = HAWK.converter.toString(value);
if (encodedValue == null) {
return null;
}
String cipherText = null;
try {
cipherText = HAWK.encryption.encrypt(key, encodedValue);
} catch (Exception e) {
e.printStackTrace();
}
if (cipherText == null) {
return null;
}
return DataHelper.addType(cipherText, value);
}
public static void destroy() {
HAWK = null;
}
}
| Use the appropriate local names in Hawk
| hawk/src/main/java/com/orhanobut/hawk/Hawk.java | Use the appropriate local names in Hawk |
|
Java | apache-2.0 | 0efa77302a4bb1d8bf6cf0782e66ff0c6ea0ec0b | 0 | fzymek/FunWithAndroid | package pl.fzymek.permissions.activities;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import net.bozho.easycamera.DefaultEasyCamera;
import net.bozho.easycamera.EasyCamera;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import pl.fzymek.permissions.R;
import timber.log.Timber;
public class TakePictureActivity extends AppCompatActivity implements SurfaceHolder.Callback {
private static final int CAMERA_PERMISSION_REQUEST_CODE = 0x1;
@BindView(R.id.camera_surface)
SurfaceView cameraSurface;
@BindView(R.id.take_picture_fab)
FloatingActionButton takePicture;
EasyCamera camera;
EasyCamera.CameraActions cameraActions;
Unbinder unbinder;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Timber.d("onCreate");
setContentView(R.layout.activity_take_picture);
unbinder = ButterKnife.bind(this);
takePicture.setOnClickListener(view -> {
if (cameraActions == null) {
initCamera();
return;
}
cameraActions.takePicture(EasyCamera.Callbacks.create().withRestartPreviewAfterCallbacks(true)
.withJpegCallback(
(bytes, camAction) -> {
Timber.d("Take picture clicked");
File picture = savePicture(bytes);
Timber.d("Adding taken picture to media collection");
MediaScannerConnection.scanFile(TakePictureActivity.this, new String[]{picture.getAbsolutePath()}, new String[]{"image/jpg"}, (s, uri) -> {
Timber.d("Picture %s added to gallery under %s", s, uri);
Snackbar snackbar = Snackbar.make(view, "" +
"Picture saved", Snackbar.LENGTH_SHORT);
Intent viewIntent = new Intent(Intent.ACTION_VIEW);
viewIntent.setDataAndType(uri, "image/*");
List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(viewIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (resolveInfos.size() > 0) {
snackbar.setAction("Show", v -> {
Timber.d("Opening picture in gallery");
startActivity(viewIntent);
});
}
snackbar.show();
});
}));
});
initCamera();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
Timber.d("onRequestPermissionsResult() called with: requestCode = [%d], permissions = [%s], grantResults = [%s]", requestCode, Arrays.toString(permissions), Arrays.toString(grantResults));
switch (requestCode) {
case CAMERA_PERMISSION_REQUEST_CODE:
handleCameraPermissionResult(permissions, grantResults);
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void handleCameraPermissionResult(String[] permissions, int[] grantResults) {
Timber.d("handleCameraPermissionResult() called with: permissions = [%s], grantResults = [%s]", Arrays.toString(permissions), Arrays.toString(grantResults));
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Timber.d("Permission granted");
openCamera();
} else {
Timber.d("Permission denied");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
stopCameraPreview();
unbinder.unbind();
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
camera.stopPreview();
}
private void initCamera() {
if (!hasPermission(Manifest.permission.CAMERA)) {
requestPermission(Manifest.permission.CAMERA);
return;
}
openCamera();
}
private boolean hasPermission(@NonNull String permission) {
Timber.d("Checking for permission: %s", permission);
return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
}
private void requestPermission(@NonNull String permission) {
Timber.d("Requesting permission: %s", permission);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
//show permission explanation
Timber.d("Showing permissions rationale");
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle("Camera needed")
.setMessage("Camera permission is needed in order to take pictures.")
.setNeutralButton("Ok", (dialogInterface, i) -> {
dialogInterface.dismiss();
}).setOnDismissListener((dialogInterface -> {
ActivityCompat.requestPermissions(this, new String[]{permission}, CAMERA_PERMISSION_REQUEST_CODE);
}));
builder.show();
} else {
Timber.d("Requesting permissions");
ActivityCompat.requestPermissions(this, new String[]{permission}, CAMERA_PERMISSION_REQUEST_CODE);
}
}
private void openCamera() {
Timber.d("Opening camera");
if (camera == null) {
camera = DefaultEasyCamera.open();
camera.alignCameraAndDisplayOrientation(getWindowManager());
}
cameraSurface.getHolder().addCallback(this);
startCameraPreview();
}
private void startCameraPreview() {
try {
Timber.d("Starting camera preview");
cameraActions = camera.startPreview(cameraSurface.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopCameraPreview() {
cameraSurface.getHolder().removeCallback(this);
if (camera != null) {
camera.stopPreview();
camera.close();
camera = null;
}
}
@NonNull
private File savePicture(byte[] bytes) {
File picsDir = new File(Environment.getExternalStorageDirectory(), "PermissionsApp");
if (!picsDir.exists()) {
Timber.d("Creating directory %s ", picsDir.getAbsolutePath());
//noinspection ResultOfMethodCallIgnored
picsDir.mkdirs();
}
@SuppressLint("SimpleDateFormat")
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
File picture = new File(picsDir, "Pic_" + dateFormat.format(new Date()) + ".jpg");
try {
Timber.d("Saving file %s", picture.getAbsolutePath());
FileOutputStream os = new FileOutputStream(picture);
os.write(bytes);
os.close();
} catch (IOException e) {
Timber.e("Error saving picture");
e.printStackTrace();
}
return picture;
}
}
| Permissions/src/main/java/pl/fzymek/permissions/activities/TakePictureActivity.java | package pl.fzymek.permissions.activities;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import net.bozho.easycamera.DefaultEasyCamera;
import net.bozho.easycamera.EasyCamera;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import pl.fzymek.permissions.R;
import timber.log.Timber;
public class TakePictureActivity extends AppCompatActivity implements SurfaceHolder.Callback {
private static final int CAMERA_PERMISSION_REQUEST_CODE = 0x1;
@BindView(R.id.camera_surface)
SurfaceView cameraSurface;
@BindView(R.id.take_picture_fab)
FloatingActionButton takePicture;
EasyCamera camera;
EasyCamera.CameraActions cameraActions;
Unbinder unbinder;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_take_picture);
unbinder = ButterKnife.bind(this);
takePicture.setOnClickListener(view -> {
if (cameraActions == null) {
initCamera();
return;
}
cameraActions.takePicture(EasyCamera.Callbacks.create().withRestartPreviewAfterCallbacks(true)
.withJpegCallback(
(bytes, camAction) -> {
Timber.d("Take picture clicked");
File picture = savePicture(bytes);
Timber.d("Adding taken picture to media collection");
MediaScannerConnection.scanFile(TakePictureActivity.this, new String[]{picture.getAbsolutePath()}, new String[]{"image/jpg"}, (s, uri) -> {
Timber.d("Picture %s added to gallery under %s", s, uri);
Snackbar snackbar = Snackbar.make(view, "" +
"Picture saved", Snackbar.LENGTH_SHORT);
Intent viewIntent = new Intent(Intent.ACTION_VIEW);
viewIntent.setDataAndType(uri, "image/*");
List<ResolveInfo> resolveInfos = getPackageManager().queryIntentActivities(viewIntent, PackageManager.MATCH_DEFAULT_ONLY);
if (resolveInfos.size() > 0) {
snackbar.setAction("Show", v -> {
Timber.d("Opening picture in gallery");
startActivity(viewIntent);
});
}
snackbar.show();
});
}));
});
initCamera();
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
switch (requestCode) {
case CAMERA_PERMISSION_REQUEST_CODE:
handleCameraPermissionResult(permissions, grantResults);
break;
}
}
private void handleCameraPermissionResult(String[] permissions, int[] grantResults) {
Timber.d("handleCameraPermissionResult() called with: permissions = [%s], grantResults = [%s]", Arrays.toString(permissions), Arrays.toString(grantResults));
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Timber.d("Permission granted");
openCamera();
} else {
Timber.d("Permission denied");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
stopCameraPreview();
unbinder.unbind();
}
@Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
camera.stopPreview();
}
private void initCamera() {
if (!hasPermission(Manifest.permission.CAMERA)) {
requestPermission(Manifest.permission.CAMERA);
return;
}
openCamera();
}
private boolean hasPermission(@NonNull String permission) {
Timber.d("Checking for permission: %s", permission);
return ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_GRANTED;
}
private void requestPermission(@NonNull String permission) {
Timber.d("Requesting permission: %s", permission);
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_CONTACTS)) {
//show permission explanation
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle("Camera needed")
.setMessage("Camera permission is needed in order to take pictures.")
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.show();
} else {
ActivityCompat.requestPermissions(this, new String[]{permission}, CAMERA_PERMISSION_REQUEST_CODE);
}
}
private void openCamera() {
Timber.d("Opening camera");
if (camera == null) {
camera = DefaultEasyCamera.open();
camera.alignCameraAndDisplayOrientation(getWindowManager());
}
cameraSurface.getHolder().addCallback(this);
startCameraPreview();
}
private void startCameraPreview() {
try {
cameraActions = camera.startPreview(cameraSurface.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
private void stopCameraPreview() {
cameraSurface.getHolder().removeCallback(this);
if (camera != null) {
camera.stopPreview();
camera.close();
camera = null;
}
}
@NonNull
private File savePicture(byte[] bytes) {
File picsDir = new File(Environment.getExternalStorageDirectory(), "PermissionsApp");
if (!picsDir.exists()) {
Timber.d("Creating directory %s ", picsDir.getAbsolutePath());
//noinspection ResultOfMethodCallIgnored
picsDir.mkdirs();
}
@SuppressLint("SimpleDateFormat")
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
File picture = new File(picsDir, "Pic_" + dateFormat.format(new Date()) + ".jpg");
try {
Timber.d("Saving file %s", picture.getAbsolutePath());
FileOutputStream os = new FileOutputStream(picture);
os.write(bytes);
os.close();
} catch (IOException e) {
Timber.e("Error saving picture");
e.printStackTrace();
}
return picture;
}
}
| Improve permission handling
| Permissions/src/main/java/pl/fzymek/permissions/activities/TakePictureActivity.java | Improve permission handling |
|
Java | apache-2.0 | d1826d4c9387e9d07264f47ee6441ed1bd33f8e4 | 0 | junefun/rest-client,truvakitap/rest-client,ZacksTsang/rest-client,chinasunysh/rest-client,wiztools/rest-client,viks01/rest-client,dybdalk/rest-client,npsyche/rest-client,truvakitap/rest-client,vegeth1985/rest-client,junefun/rest-client,ocsbilisim/rest-client,ZacksTsang/rest-client,chinasunysh/rest-client,jmsosa/rest-client,erickgugo/rest-client,ahnbs82/rest-client,cotarola93/rest-client,jymsy/rest-client,rcanz/rest-client,seastar-ss/rest-client,sequethin/rest-client,ezbreaks/rest-client,mgraffx/rest-client,xxairwolf/xxknightrider-rest-client,abbasmajeed/rest-client,ahmeddrira/rest-client,ZacksTsang/rest-client,geub/rest-client,vegeth1985/rest-client,snitheesh/rest-client,npsyche/rest-client,minafaw/rest-client,hiro117/rest-client,dybdalk/rest-client,wenwei-dev/rest-client,msezgi/rest-client,geub/rest-client,snitheesh/rest-client,pavanreddyboppidi/rest-client,viks01/rest-client,npsyche/rest-client,vegeth1985/rest-client,ocsbilisim/rest-client,javierfileiv/rest-client,rcanz/rest-client,Hasimir/rest-client,chinasunysh/rest-client,rvkiran/rest-client,edwincalzada/rest-client,daocoder/rest-client,komadee/rest-client,edwincalzada/rest-client,cotarola93/rest-client,erickgugo/rest-client,ahmeddrira/rest-client,ahnbs82/rest-client,jymsy/rest-client,komadee/rest-client,ezbreaks/rest-client,wenwei-dev/rest-client,msezgi/rest-client,junefun/rest-client,SSYouknowit/rest-client,wenwei-dev/rest-client,pavanreddyboppidi/rest-client,sequethin/rest-client,xxairwolf/xxknightrider-rest-client,hiro117/rest-client,minafaw/rest-client,rvkiran/rest-client,edwincalzada/rest-client,cotarola93/rest-client,EonHa-Lee/rest-client,Hasimir/rest-client,yeradis/rest-client,seastar-ss/rest-client,EonHa-Lee/rest-client,xxairwolf/xxknightrider-rest-client,daocoder/rest-client,abhinav118/rest-client,pavanreddyboppidi/rest-client,SSYouknowit/rest-client,ezbreaks/rest-client,truvakitap/rest-client,ahnbs82/rest-client,mgraffx/rest-client,seastar-ss/rest-client,rvkiran/rest-client,hiro117/rest-client,vit256/rest-client,daocoder/rest-client,wiztools/rest-client,SSYouknowit/rest-client,abbasmajeed/rest-client,komadee/rest-client,msezgi/rest-client,EonHa-Lee/rest-client,yeradis/rest-client,erickgugo/rest-client,vit256/rest-client,ahmeddrira/rest-client,snitheesh/rest-client,dybdalk/rest-client,javierfileiv/rest-client,jmsosa/rest-client,sequethin/rest-client,minafaw/rest-client,abhinav118/rest-client,ocsbilisim/rest-client,rcanz/rest-client,vit256/rest-client,javierfileiv/rest-client,jmsosa/rest-client,abhinav118/rest-client,abbasmajeed/rest-client | package org.wiztools.restclient.ui.resbody;
import java.awt.Component;
import javax.swing.JPanel;
import org.wiztools.restclient.bean.ContentType;
/**
*
* @author subwiz
*/
public abstract class AbstractResBody extends JPanel implements ResBodyPanel {
protected byte[] body;
protected ContentType type;
@Override
public void setBody(byte[] body, ContentType type) {
this.body = body;
this.type = type;
}
@Override
public byte[] getBody() {
return body;
}
@Override
public Component getComponent() {
return this;
}
@Override
public final void clear() {
body = null;
clearUI();
}
public abstract void clearUI();
}
| restclient-ui/src/main/java/org/wiztools/restclient/ui/resbody/AbstractResBody.java | package org.wiztools.restclient.ui.resbody;
import java.awt.Component;
import javax.swing.JPanel;
import org.wiztools.restclient.bean.ContentType;
/**
*
* @author subwiz
*/
public abstract class AbstractResBody extends JPanel implements ResBodyPanel {
protected byte[] body;
protected ContentType type;
@Override
public void setBody(byte[] body, ContentType type) {
this.body = body;
}
@Override
public byte[] getBody() {
return body;
}
@Override
public Component getComponent() {
return this;
}
@Override
public final void clear() {
body = null;
clearUI();
}
public abstract void clearUI();
}
| type was not being saved--now fixed.
git-svn-id: bf7e6665a5fa9ed84da90b6cc1bef00f9ffe166f@761 08545216-953f-0410-99bf-93b34cd2520f
| restclient-ui/src/main/java/org/wiztools/restclient/ui/resbody/AbstractResBody.java | type was not being saved--now fixed. |
|
Java | apache-2.0 | 815a64d259c371dae6242a2f3e3ac01e515108ff | 0 | HHzzhz/drools,winklerm/drools,ThiagoGarciaAlves/drools,kevinpeterson/drools,psiroky/drools,droolsjbpm/drools,iambic69/drools,romartin/drools,vinodkiran/drools,kevinpeterson/drools,292388900/drools,mswiderski/drools,jomarko/drools,jomarko/drools,pperboires/PocDrools,liupugong/drools,liupugong/drools,mrietveld/drools,pperboires/PocDrools,292388900/drools,yurloc/drools,sotty/drools,ThomasLau/drools,jiripetrlik/drools,kedzie/drools-android,sotty/drools,droolsjbpm/drools,HHzzhz/drools,ThomasLau/drools,yurloc/drools,kevinpeterson/drools,psiroky/drools,sutaakar/drools,prabasn/drools,kedzie/drools-android,sutaakar/drools,kevinpeterson/drools,mrietveld/drools,manstis/drools,sutaakar/drools,ChallenHB/drools,lanceleverich/drools,reynoldsm88/drools,psiroky/drools,mswiderski/drools,reynoldsm88/drools,liupugong/drools,Buble1981/MyDroolsFork,liupugong/drools,psiroky/drools,prabasn/drools,reynoldsm88/drools,iambic69/drools,sutaakar/drools,ThiagoGarciaAlves/drools,ThiagoGarciaAlves/drools,jiripetrlik/drools,manstis/drools,kedzie/drools-android,ChallenHB/drools,jomarko/drools,mrrodriguez/drools,reynoldsm88/drools,rajashekharmunthakewill/drools,ngs-mtech/drools,manstis/drools,pperboires/PocDrools,ChallenHB/drools,ThiagoGarciaAlves/drools,ThomasLau/drools,OnePaaS/drools,TonnyFeng/drools,kevinpeterson/drools,ChallenHB/drools,manstis/drools,ThiagoGarciaAlves/drools,pwachira/droolsexamples,iambic69/drools,pperboires/PocDrools,mrrodriguez/drools,yurloc/drools,jomarko/drools,sotty/drools,lanceleverich/drools,mrietveld/drools,mrrodriguez/drools,droolsjbpm/drools,winklerm/drools,lanceleverich/drools,TonnyFeng/drools,292388900/drools,jiripetrlik/drools,sotty/drools,rajashekharmunthakewill/drools,kedzie/drools-android,HHzzhz/drools,prabasn/drools,rajashekharmunthakewill/drools,amckee23/drools,TonnyFeng/drools,amckee23/drools,ngs-mtech/drools,prabasn/drools,romartin/drools,Buble1981/MyDroolsFork,vinodkiran/drools,amckee23/drools,jomarko/drools,manstis/drools,Buble1981/MyDroolsFork,OnePaaS/drools,292388900/drools,lanceleverich/drools,ngs-mtech/drools,292388900/drools,romartin/drools,OnePaaS/drools,ngs-mtech/drools,droolsjbpm/drools,reynoldsm88/drools,romartin/drools,prabasn/drools,winklerm/drools,kedzie/drools-android,winklerm/drools,vinodkiran/drools,amckee23/drools,TonnyFeng/drools,sutaakar/drools,sotty/drools,mswiderski/drools,yurloc/drools,jiripetrlik/drools,droolsjbpm/drools,lanceleverich/drools,rajashekharmunthakewill/drools,liupugong/drools,OnePaaS/drools,amckee23/drools,ngs-mtech/drools,iambic69/drools,HHzzhz/drools,rajashekharmunthakewill/drools,vinodkiran/drools,jiripetrlik/drools,vinodkiran/drools,mrrodriguez/drools,mrietveld/drools,ChallenHB/drools,iambic69/drools,mrrodriguez/drools,ThomasLau/drools,ThomasLau/drools,romartin/drools,mrietveld/drools,OnePaaS/drools,HHzzhz/drools,Buble1981/MyDroolsFork,winklerm/drools,TonnyFeng/drools,mswiderski/drools | package org.drools.integrationtests;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.drools.ClockType;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseConfiguration;
import org.drools.KnowledgeBaseFactory;
import org.drools.SessionConfiguration;
import org.drools.WorkingMemory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.common.InternalRuleBase;
import org.drools.conf.EventProcessingOption;
import org.drools.definition.KnowledgePackage;
import org.drools.definitions.impl.KnowledgePackageImp;
import org.drools.impl.KnowledgeBaseImpl;
import org.drools.io.ResourceFactory;
import org.drools.marshalling.Marshaller;
import org.drools.marshalling.MarshallerFactory;
import org.drools.reteoo.MockTupleSource;
import org.drools.reteoo.ReteooRuleBase;
import org.drools.reteoo.RuleTerminalNode;
import org.drools.reteoo.builder.BuildContext;
import org.drools.rule.FixedDuration;
import org.drools.rule.Rule;
import org.drools.runtime.KnowledgeSessionConfiguration;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.spi.Consequence;
import org.drools.spi.KnowledgeHelper;
import org.drools.time.impl.DurationTimer;
import org.drools.time.impl.PseudoClockScheduler;
import org.junit.Ignore;
import org.junit.Test;
public class EventMarshallFailTest {
public static class A
implements
Serializable {
}
public static class B
implements
Serializable {
}
public static class C
implements
Serializable {
}
@Test
@Ignore
public void testMarshall() throws Exception {
String str =
"import org.drools.integrationtests.EventMarshallFailTest.*\n" +
"declare A\n" +
" @role( event )\n" +
" @expires( 10m )\n" +
"end\n" +
"declare B\n" +
" @role( event )\n" +
" @expires( 10m )\n" +
"end\n" +
"rule one\n" +
"when\n" +
" $a : A()\n" +
" B(this after $a)\n" +
"then\n" +
"insert(new C());" +
"end\n";
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ResourceFactory.newReaderResource( new StringReader( str ) ),
ResourceType.DRL );
if ( kbuilder.hasErrors() ) {
throw new RuntimeException( kbuilder.getErrors().toString() );
}
KnowledgeBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
config.setOption( EventProcessingOption.STREAM );
KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase( config );
knowledgeBase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
StatefulKnowledgeSession ksession = knowledgeBase.newStatefulKnowledgeSession();
ksession.insert( new A() );
ByteArrayOutputStream out = new ByteArrayOutputStream();
MarshallerFactory.newMarshaller( knowledgeBase ).marshall( out,
ksession );
ksession = MarshallerFactory.newMarshaller( knowledgeBase ).unmarshall( new ByteArrayInputStream( out.toByteArray() ) );
ksession.insert( new B() );
ksession.fireAllRules();
assertEquals( 3,
ksession.getObjects().size() );
}
@Test
public void testScheduledActivation() {
KnowledgeBaseImpl knowledgeBase = (KnowledgeBaseImpl) KnowledgeBaseFactory.newKnowledgeBase();
KnowledgePackageImp impl = new KnowledgePackageImp();
impl.pkg = new org.drools.rule.Package("test");
BuildContext buildContext = new BuildContext((InternalRuleBase) knowledgeBase.getRuleBase(), ((ReteooRuleBase) knowledgeBase.getRuleBase())
.getReteooBuilder().getIdGenerator());
//simple rule that fires after 10 seconds
final Rule rule = new Rule("test-rule");
new RuleTerminalNode(1,new MockTupleSource(2), rule, rule.getLhs(), buildContext);
final List<String> fired = new ArrayList<String>();
rule.setConsequence( new Consequence() {
public void evaluate(KnowledgeHelper knowledgeHelper,
WorkingMemory workingMemory) throws Exception {
fired.add("a");
}
public String getName() {
return "default";
}
} );
rule.setTimer( new DurationTimer( 10000 ) );
rule.setPackage("test");
impl.pkg.addRule(rule);
knowledgeBase.addKnowledgePackages(Collections.singleton((KnowledgePackage) impl));
SessionConfiguration config = new SessionConfiguration();
config.setClockType(ClockType.PSEUDO_CLOCK);
StatefulKnowledgeSession ksession = knowledgeBase.newStatefulKnowledgeSession(config, KnowledgeBaseFactory.newEnvironment());
PseudoClockScheduler scheduler = ksession.getSessionClock();
Marshaller marshaller = MarshallerFactory.newMarshaller(knowledgeBase);
ksession.insert("cheese");
assertTrue(fired.isEmpty());
//marshall, then unmarshall session
readWrite(knowledgeBase, ksession, config);
//the activations should fire after 10 seconds
assertTrue(fired.isEmpty());
scheduler.advanceTime(12, TimeUnit.SECONDS);
assertFalse(fired.isEmpty());
}
private void readWrite(KnowledgeBase knowledgeBase, StatefulKnowledgeSession ksession, KnowledgeSessionConfiguration config) {
try {
Marshaller marshaller = MarshallerFactory.newMarshaller(knowledgeBase);
ByteArrayOutputStream o = new ByteArrayOutputStream();
marshaller.marshall(o, ksession);
ksession = marshaller.unmarshall(new ByteArrayInputStream(o.toByteArray()), config, KnowledgeBaseFactory.newEnvironment());
ksession.fireAllRules();
//scheduler = ksession.getSessionClock();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| drools-compiler/src/test/java/org/drools/integrationtests/EventMarshallFailTest.java | package org.drools.integrationtests;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Serializable;
import java.io.StringReader;
import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseConfiguration;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.conf.EventProcessingOption;
import org.drools.io.ResourceFactory;
import org.drools.marshalling.MarshallerFactory;
import org.drools.runtime.StatefulKnowledgeSession;
import org.junit.Ignore;
import org.junit.Test;
public class EventMarshallFailTest {
public static class A
implements
Serializable {
}
public static class B
implements
Serializable {
}
public static class C
implements
Serializable {
}
@Test
@Ignore
public void testMarshall() throws Exception {
String str =
"import org.drools.integrationtests.EventMarshallFailTest.*\n" +
"declare A\n" +
" @role( event )\n" +
" @expires( 10m )\n" +
"end\n" +
"declare B\n" +
" @role( event )\n" +
" @expires( 10m )\n" +
"end\n" +
"rule one\n" +
"when\n" +
" $a : A()\n" +
" B(this after $a)\n" +
"then\n" +
"insert(new C());" +
"end\n";
KnowledgeBuilder kbuilder = KnowledgeBuilderFactory.newKnowledgeBuilder();
kbuilder.add( ResourceFactory.newReaderResource( new StringReader( str ) ),
ResourceType.DRL );
if ( kbuilder.hasErrors() ) {
throw new RuntimeException( kbuilder.getErrors().toString() );
}
KnowledgeBaseConfiguration config = KnowledgeBaseFactory.newKnowledgeBaseConfiguration();
config.setOption( EventProcessingOption.STREAM );
KnowledgeBase knowledgeBase = KnowledgeBaseFactory.newKnowledgeBase( config );
knowledgeBase.addKnowledgePackages( kbuilder.getKnowledgePackages() );
StatefulKnowledgeSession ksession = knowledgeBase.newStatefulKnowledgeSession();
ksession.insert( new A() );
ByteArrayOutputStream out = new ByteArrayOutputStream();
MarshallerFactory.newMarshaller( knowledgeBase ).marshall( out,
ksession );
ksession = MarshallerFactory.newMarshaller( knowledgeBase ).unmarshall( new ByteArrayInputStream( out.toByteArray() ) );
ksession.insert( new B() );
ksession.fireAllRules();
assertEquals( 3,
ksession.getObjects().size() );
}
}
| JBRULES-2318 (Un)Marshalling should respect times of scheduled activations
| drools-compiler/src/test/java/org/drools/integrationtests/EventMarshallFailTest.java | JBRULES-2318 (Un)Marshalling should respect times of scheduled activations |
|
Java | bsd-3-clause | e384dad1c082a8a0314975d5de929553c2b515fc | 0 | asamgir/openspecimen,krishagni/openspecimen,NCIP/catissue-core,krishagni/openspecimen,NCIP/catissue-core,krishagni/openspecimen,NCIP/catissue-core,asamgir/openspecimen,asamgir/openspecimen | /**
* <p>Title: SpecimenCollectionGroupAction Class>
* <p>Description: SpecimenCollectionGroupAction initializes the fields in the
* New Specimen Collection Group page.</p>
* Copyright: Copyright (c) year
* Company: Washington University, School of Medicine, St. Louis.
* @author Ajay Sharma
* @version 1.00
*/
package edu.wustl.catissuecore.action;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.actionForm.SpecimenCollectionGroupForm;
import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.CollectionProtocolEvent;
import edu.wustl.catissuecore.domain.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domain.Participant;
import edu.wustl.catissuecore.domain.ParticipantMedicalIdentifier;
import edu.wustl.catissuecore.domain.Site;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.Utility;
import edu.wustl.catissuecore.util.global.Variables;
import edu.wustl.common.action.SecureAction;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.bizlogic.AbstractBizLogic;
import edu.wustl.common.cde.CDEManager;
import edu.wustl.common.util.logger.Logger;
/**
* SpecimenCollectionGroupAction initializes the fields in the
* New Specimen Collection Group page.
* @author ajay_sharma
*/
public class SpecimenCollectionGroupAction extends SecureAction
{
/**
* Overrides the execute method of Action class.
*/
public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
SpecimenCollectionGroupForm specimenCollectionGroupForm = (SpecimenCollectionGroupForm)form;
Logger.out.debug("SCGA : " + specimenCollectionGroupForm.getSystemIdentifier() );
// set the menu selection
request.setAttribute(Constants.MENU_SELECTED, "14" );
//pageOf and operation attributes required for Advance Query Object view.
String pageOf = request.getParameter(Constants.PAGEOF);
//Gets the value of the operation parameter.
String operation = (String)request.getParameter(Constants.OPERATION);
//Sets the operation attribute to be used in the Edit/View Specimen Collection Group Page in Advance Search Object View.
request.setAttribute(Constants.OPERATION,operation);
if(operation.equalsIgnoreCase(Constants.ADD ) )
{
specimenCollectionGroupForm.setSystemIdentifier(0);
Logger.out.debug("SCGA : set to 0 "+ specimenCollectionGroupForm.getSystemIdentifier() );
}
boolean isOnChange = false;
String str = request.getParameter("isOnChange");
if(str!=null)
{
if(str.equals("true"))
isOnChange = true;
}
// get list of Protocol title.
AbstractBizLogic bizLogic = BizLogicFactory.getBizLogic(Constants.SPECIMEN_COLLECTION_GROUP_FORM_ID);
//populating protocolist bean.
String sourceObjectName = CollectionProtocol.class.getName();
String [] displayNameFields = {"title"};
String valueField = Constants.SYSTEM_IDENTIFIER;
List list = bizLogic.getList(sourceObjectName,displayNameFields,valueField, true);
request.setAttribute(Constants.PROTOCOL_LIST, list);
//Populating the Site Type bean
sourceObjectName = Site.class.getName();
String siteDisplaySiteFields[] = {"name"};
list = bizLogic.getList(sourceObjectName,siteDisplaySiteFields,valueField, true);
request.setAttribute(Constants.SITELIST, list);
//Populating the participants registered to a given protocol
loadPaticipants(specimenCollectionGroupForm.getCollectionProtocolId() , bizLogic, request);
//Populating the protocol participants id registered to a given protocol
loadPaticipantNumberList(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
//Populating the Collection Protocol Events
loadCollectionProtocolEvent(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
//Populating the participants Medical Identifier for a given participant
loadParticipantMedicalIdentifier(specimenCollectionGroupForm.getParticipantId(),bizLogic, request);
//Load Clinical status for a given study calander event point
List calendarEventPointList = bizLogic.retrieve(CollectionProtocolEvent.class.getName(),
Constants.SYSTEM_IDENTIFIER,
new Long(specimenCollectionGroupForm.getCollectionProtocolEventId()));
if(isOnChange && !calendarEventPointList.isEmpty())
{
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent)calendarEventPointList.get(0);
specimenCollectionGroupForm.setClinicalStatus(collectionProtocolEvent.getClinicalStatus());
}
// populating clinical Diagnosis field
List clinicalDiagnosisList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CLINICAL_DIAGNOSIS,null);
request.setAttribute(Constants.CLINICAL_DIAGNOSIS_LIST, clinicalDiagnosisList);
// populating clinical Status field
// NameValueBean undefinedVal = new NameValueBean(Constants.UNDEFINED,Constants.UNDEFINED);
List clinicalStatusList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CLINICAL_STATUS,null);
request.setAttribute(Constants.CLINICAL_STATUS_LIST, clinicalStatusList);
//Sets the activityStatusList attribute to be used in the Site Add/Edit Page.
request.setAttribute(Constants.ACTIVITYSTATUSLIST, Constants.ACTIVITY_STATUS_VALUES);
Logger.out.debug("CP ID in SCG Action======>"+specimenCollectionGroupForm.getCollectionProtocolId());
Logger.out.debug("Participant ID in SCG Action=====>"+specimenCollectionGroupForm.getParticipantId()+" "+specimenCollectionGroupForm.getProtocolParticipantIdentifier());
// -------called from Collection Protocol Registration start-------------------------------
if( (request.getAttribute(Constants.SUBMITTED_FOR) !=null) &&(request.getAttribute(Constants.SUBMITTED_FOR).equals("Default")))
{
Logger.out.debug("Populating CP and Participant in SCG ==== AddNew operation loop");
Long cprId =new Long(specimenCollectionGroupForm.getCollectionProtocolRegistrationId());
if(cprId != null)
{
List collectionProtocolRegistrationList = bizLogic.retrieve(CollectionProtocolRegistration.class.getName(),
Constants.SYSTEM_IDENTIFIER,cprId);
if(!collectionProtocolRegistrationList.isEmpty())
{
Object obj = collectionProtocolRegistrationList.get(0 );
CollectionProtocolRegistration cpr = (CollectionProtocolRegistration)obj;
long cpID = cpr.getCollectionProtocol().getSystemIdentifier().longValue();
long pID = cpr.getParticipant().getSystemIdentifier().longValue();
String ppID = cpr.getProtocolParticipantIdentifier();
Logger.out.debug("cpID : "+ cpID + " || pID : " + pID + " || ppID : " + ppID );
specimenCollectionGroupForm.setCollectionProtocolId(cpID);
//Populating the participants registered to a given protocol
loadPaticipants(cpID , bizLogic, request);
loadPaticipantNumberList(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
String firstName = Utility.toString(cpr.getParticipant().getFirstName());;
String lastName = Utility.toString(cpr.getParticipant().getLastName());
String birthDate = Utility.toString(cpr.getParticipant().getBirthDate());
String ssn = Utility.toString(cpr.getParticipant().getSocialSecurityNumber());
if(firstName.trim().length()>0 || lastName.trim().length()>0 || birthDate.trim().length()>0 || ssn.trim().length()>0)
{
specimenCollectionGroupForm.setParticipantId(pID );
specimenCollectionGroupForm.setCheckedButton(1);
}
//Populating the protocol participants id registered to a given protocol
else if(cpr.getProtocolParticipantIdentifier() != null)
{
specimenCollectionGroupForm.setProtocolParticipantIdentifier(ppID );
specimenCollectionGroupForm.setCheckedButton(2);
}
//Populating the Collection Protocol Events
loadCollectionProtocolEvent(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
//Load Clinical status for a given study calander event point
calendarEventPointList = bizLogic.retrieve(CollectionProtocolEvent.class.getName(),
Constants.SYSTEM_IDENTIFIER,
new Long(specimenCollectionGroupForm.getCollectionProtocolEventId()));
if(isOnChange && !calendarEventPointList.isEmpty())
{
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent)calendarEventPointList.get(0);
specimenCollectionGroupForm.setClinicalStatus(collectionProtocolEvent.getClinicalStatus());
}
}
}
request.setAttribute(Constants.SUBMITTED_FOR, "Default");
}
//************* ForwardTo implementation *************
HashMap forwardToHashMap=(HashMap)request.getAttribute("forwardToHashMap");
if(forwardToHashMap !=null)
{
Long collectionProtocolId = (Long)forwardToHashMap.get("collectionProtocolId");
Long participantId=(Long)forwardToHashMap.get("participantId");
String participantProtocolId = (String) forwardToHashMap.get("participantProtocolId");
specimenCollectionGroupForm.setCollectionProtocolId(collectionProtocolId.longValue());
if(participantId != null)
{
//Populating the participants registered to a given protocol
loadPaticipants(collectionProtocolId.longValue(), bizLogic, request);
loadPaticipantNumberList(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
specimenCollectionGroupForm.setParticipantId(participantId.longValue());
specimenCollectionGroupForm.setCheckedButton(1);
}
else if(participantProtocolId != null)
{
specimenCollectionGroupForm.setProtocolParticipantIdentifier(participantProtocolId);
specimenCollectionGroupForm.setCheckedButton(2);
}
//Bug 1915:SpecimenCollectionGroup.Study Calendar Event Point not populated when page is loaded through proceedTo
//Populating the Collection Protocol Events
loadCollectionProtocolEvent(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
//Load Clinical status for a given study calander event point
calendarEventPointList = bizLogic.retrieve(CollectionProtocolEvent.class.getName(),
Constants.SYSTEM_IDENTIFIER,
new Long(specimenCollectionGroupForm.getCollectionProtocolEventId()));
if(!calendarEventPointList.isEmpty())
{
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent)calendarEventPointList.get(0);
specimenCollectionGroupForm.setClinicalStatus(collectionProtocolEvent.getClinicalStatus());
}
Logger.out.debug("CollectionProtocolID found in forwardToHashMap========>>>>>>"+collectionProtocolId);
Logger.out.debug("ParticipantID found in forwardToHashMap========>>>>>>"+participantId);
Logger.out.debug("ParticipantProtocolID found in forwardToHashMap========>>>>>>"+participantProtocolId);
}
//************* ForwardTo implementation *************
request.setAttribute(Constants.PAGEOF,pageOf);
Logger.out.debug("page of in Specimen coll grp action:"+request.getParameter(Constants.PAGEOF));
// -------called from Collection Protocol Registration end -------------------------------
return mapping.findForward(pageOf);
}
private void loadPaticipants(long protocolID, AbstractBizLogic bizLogic, HttpServletRequest request) throws Exception
{
//get list of Participant's names
String sourceObjectName = CollectionProtocolRegistration.class.getName();
String [] displayParticipantFields = {"participant.systemIdentifier"};
String valueField = "participant."+Constants.SYSTEM_IDENTIFIER;
String whereColumnName[] = {"collectionProtocol."+Constants.SYSTEM_IDENTIFIER,"participant.systemIdentifier"};
String whereColumnCondition[];
Object[] whereColumnValue;
if(Variables.databaseName.equals(Constants.MYSQL_DATABASE))
{
whereColumnCondition = new String[]{"=","is not"};
whereColumnValue=new Object[]{new Long(protocolID),null};
}
else
{
// for ORACLE
whereColumnCondition = new String[]{"=","is not null"};
whereColumnValue=new Object[]{new Long(protocolID)};
}
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = ", ";
List list = bizLogic.getList(sourceObjectName, displayParticipantFields, valueField, whereColumnName,
whereColumnCondition, whereColumnValue, joinCondition, separatorBetweenFields, true);
//get list of Participant's names
valueField = Constants.SYSTEM_IDENTIFIER;
sourceObjectName = Participant.class.getName();
String[] participantsFields = {"lastName","firstName","birthDate","socialSecurityNumber"};
String[] whereColumnName2 = {"lastName","firstName","birthDate","socialSecurityNumber"};
String[] whereColumnCondition2 = {"!=","!=","is not","is not"};
Object[] whereColumnValue2 = {"","",null,null};
if(Variables.databaseName.equals(Constants.MYSQL_DATABASE))
{
whereColumnCondition2 = new String[]{"!=","!=","is not","is not"};
whereColumnValue2=new String[]{"","",null,null};
}
else
{
// for ORACLE
whereColumnCondition2 = new String[]{"is not null","is not null","is not null","is not null"};
whereColumnValue2=new String[]{};
}
String joinCondition2 = Constants.OR_JOIN_CONDITION;
String separatorBetweenFields2 = ", ";
List listOfParticipants = bizLogic.getList(sourceObjectName, participantsFields, valueField, whereColumnName2,
whereColumnCondition2, whereColumnValue2, joinCondition2, separatorBetweenFields, false);
// removing blank participants from the list of Participants
list=removeBlankParticipant(list, listOfParticipants);
//Mandar bug id:1628 :- sort participant dropdown list
Collections.sort(list );
Logger.out.debug("Paticipants List"+list);
request.setAttribute(Constants.PARTICIPANT_LIST, list);
}
private List removeBlankParticipant(List list, List listOfParticipants)
{
List listOfActiveParticipant=new ArrayList();
for(int i=0; i<list.size(); i++)
{
NameValueBean nameValueBean =(NameValueBean)list.get(i);
if(Long.parseLong(nameValueBean.getValue()) == -1)
{
listOfActiveParticipant.add(list.get(i));
continue;
}
for(int j=0; j<listOfParticipants.size(); j++)
{
if(Long.parseLong(((NameValueBean)listOfParticipants.get(j)).getValue()) == -1)
continue;
NameValueBean participantsBean = (NameValueBean)listOfParticipants.get(j);
if( nameValueBean.getValue().equals(participantsBean.getValue()) )
{
listOfActiveParticipant.add(listOfParticipants.get(j));
break;
}
}
}
Logger.out.debug("No.Of Active Participants Registered with Protocol~~~~~~~~~~~~~~~~~~~~~~~>"+listOfActiveParticipant.size());
return listOfActiveParticipant;
}
private void loadPaticipantNumberList(long protocolID, AbstractBizLogic bizLogic, HttpServletRequest request) throws Exception
{
//get list of Participant's names
String sourceObjectName = CollectionProtocolRegistration.class.getName();
String displayParticipantNumberFields[] = {"protocolParticipantIdentifier"};
String valueField = "protocolParticipantIdentifier";
String whereColumnName[] = {"collectionProtocol."+Constants.SYSTEM_IDENTIFIER, "protocolParticipantIdentifier"};
String whereColumnCondition[];// = {"=","!="};
Object[] whereColumnValue;// = {new Long(protocolID),"null"};
// if(Variables.databaseName.equals(Constants.MYSQL_DATABASE))
// {
whereColumnCondition = new String[]{"=","!="};
whereColumnValue = new Object[]{new Long(protocolID),"null"};
// }
// else
// {
// whereColumnCondition = new String[]{"=","!=null"};
// whereColumnValue = new Object[]{new Long(protocolID),""};
// }
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = "";
List list = bizLogic.getList(sourceObjectName, displayParticipantNumberFields, valueField, whereColumnName,
whereColumnCondition, whereColumnValue, joinCondition, separatorBetweenFields, true);
Logger.out.debug("Paticipant Number List"+list);
request.setAttribute(Constants.PROTOCOL_PARTICIPANT_NUMBER_LIST, list);
}
private void loadCollectionProtocolEvent(long protocolID, AbstractBizLogic bizLogic, HttpServletRequest request) throws Exception
{
String sourceObjectName = CollectionProtocolEvent.class.getName();
String displayEventFields[] = {"studyCalendarEventPoint"};
String valueField = "systemIdentifier";
String whereColumnName[] = {"collectionProtocol."+Constants.SYSTEM_IDENTIFIER};
String whereColumnCondition[] = {"="};
Object[] whereColumnValue = {new Long(protocolID)};
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = "";
List list = bizLogic.getList(sourceObjectName, displayEventFields, valueField, whereColumnName,
whereColumnCondition, whereColumnValue, joinCondition, separatorBetweenFields, false);
request.setAttribute(Constants.STUDY_CALENDAR_EVENT_POINT_LIST, list);
}
private void loadParticipantMedicalIdentifier(long participantID, AbstractBizLogic bizLogic, HttpServletRequest request) throws Exception
{
//get list of Participant's names
String sourceObjectName = ParticipantMedicalIdentifier.class.getName();
String displayEventFields[] = {"medicalRecordNumber"};
String valueField = Constants.SYSTEM_IDENTIFIER;
String whereColumnName[] = {"participant."+Constants.SYSTEM_IDENTIFIER, "medicalRecordNumber"};
String whereColumnCondition[] = {"=","!="};
Object[] whereColumnValue = {new Long(participantID),"null"};
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = "";
List list = bizLogic.getList(sourceObjectName, displayEventFields, valueField, whereColumnName,
whereColumnCondition, whereColumnValue, joinCondition, separatorBetweenFields, false);
request.setAttribute(Constants.PARTICIPANT_MEDICAL_IDNETIFIER_LIST, list);
}
} | WEB-INF/src/edu/wustl/catissuecore/action/SpecimenCollectionGroupAction.java | /**
* <p>Title: SpecimenCollectionGroupAction Class>
* <p>Description: SpecimenCollectionGroupAction initializes the fields in the
* New Specimen Collection Group page.</p>
* Copyright: Copyright (c) year
* Company: Washington University, School of Medicine, St. Louis.
* @author Ajay Sharma
* @version 1.00
*/
package edu.wustl.catissuecore.action;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import edu.wustl.catissuecore.actionForm.SpecimenCollectionGroupForm;
import edu.wustl.catissuecore.bizlogic.BizLogicFactory;
import edu.wustl.catissuecore.domain.CollectionProtocol;
import edu.wustl.catissuecore.domain.CollectionProtocolEvent;
import edu.wustl.catissuecore.domain.CollectionProtocolRegistration;
import edu.wustl.catissuecore.domain.Participant;
import edu.wustl.catissuecore.domain.ParticipantMedicalIdentifier;
import edu.wustl.catissuecore.domain.Site;
import edu.wustl.catissuecore.util.global.Constants;
import edu.wustl.catissuecore.util.global.Utility;
import edu.wustl.catissuecore.util.global.Variables;
import edu.wustl.common.action.SecureAction;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.bizlogic.AbstractBizLogic;
import edu.wustl.common.cde.CDEManager;
import edu.wustl.common.util.logger.Logger;
/**
* SpecimenCollectionGroupAction initializes the fields in the
* New Specimen Collection Group page.
* @author ajay_sharma
*/
public class SpecimenCollectionGroupAction extends SecureAction
{
/**
* Overrides the execute method of Action class.
*/
public ActionForward executeSecureAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
SpecimenCollectionGroupForm specimenCollectionGroupForm = (SpecimenCollectionGroupForm)form;
Logger.out.debug("SCGA : " + specimenCollectionGroupForm.getSystemIdentifier() );
// set the menu selection
request.setAttribute(Constants.MENU_SELECTED, "14" );
//pageOf and operation attributes required for Advance Query Object view.
String pageOf = request.getParameter(Constants.PAGEOF);
//Gets the value of the operation parameter.
String operation = (String)request.getParameter(Constants.OPERATION);
//Sets the operation attribute to be used in the Edit/View Specimen Collection Group Page in Advance Search Object View.
request.setAttribute(Constants.OPERATION,operation);
if(operation.equalsIgnoreCase(Constants.ADD ) )
{
specimenCollectionGroupForm.setSystemIdentifier(0);
Logger.out.debug("SCGA : set to 0 "+ specimenCollectionGroupForm.getSystemIdentifier() );
}
boolean isOnChange = false;
String str = request.getParameter("isOnChange");
if(str!=null)
{
if(str.equals("true"))
isOnChange = true;
}
// get list of Protocol title.
AbstractBizLogic bizLogic = BizLogicFactory.getBizLogic(Constants.SPECIMEN_COLLECTION_GROUP_FORM_ID);
//populating protocolist bean.
String sourceObjectName = CollectionProtocol.class.getName();
String [] displayNameFields = {"title"};
String valueField = Constants.SYSTEM_IDENTIFIER;
List list = bizLogic.getList(sourceObjectName,displayNameFields,valueField, true);
request.setAttribute(Constants.PROTOCOL_LIST, list);
//Populating the Site Type bean
sourceObjectName = Site.class.getName();
String siteDisplaySiteFields[] = {"name"};
list = bizLogic.getList(sourceObjectName,siteDisplaySiteFields,valueField, true);
request.setAttribute(Constants.SITELIST, list);
//Populating the participants registered to a given protocol
loadPaticipants(specimenCollectionGroupForm.getCollectionProtocolId() , bizLogic, request);
//Populating the protocol participants id registered to a given protocol
loadPaticipantNumberList(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
//Populating the Collection Protocol Events
loadCollectionProtocolEvent(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
//Populating the participants Medical Identifier for a given participant
loadParticipantMedicalIdentifier(specimenCollectionGroupForm.getParticipantId(),bizLogic, request);
//Load Clinical status for a given study calander event point
List calendarEventPointList = bizLogic.retrieve(CollectionProtocolEvent.class.getName(),
Constants.SYSTEM_IDENTIFIER,
new Long(specimenCollectionGroupForm.getCollectionProtocolEventId()));
if(isOnChange && !calendarEventPointList.isEmpty())
{
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent)calendarEventPointList.get(0);
specimenCollectionGroupForm.setClinicalStatus(collectionProtocolEvent.getClinicalStatus());
}
// populating clinical Diagnosis field
List clinicalDiagnosisList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CLINICAL_DIAGNOSIS,null);
request.setAttribute(Constants.CLINICAL_DIAGNOSIS_LIST, clinicalDiagnosisList);
// populating clinical Status field
// NameValueBean undefinedVal = new NameValueBean(Constants.UNDEFINED,Constants.UNDEFINED);
List clinicalStatusList = CDEManager.getCDEManager().getPermissibleValueList(Constants.CDE_NAME_CLINICAL_STATUS,null);
request.setAttribute(Constants.CLINICAL_STATUS_LIST, clinicalStatusList);
//Sets the activityStatusList attribute to be used in the Site Add/Edit Page.
request.setAttribute(Constants.ACTIVITYSTATUSLIST, Constants.ACTIVITY_STATUS_VALUES);
Logger.out.debug("CP ID in SCG Action======>"+specimenCollectionGroupForm.getCollectionProtocolId());
Logger.out.debug("Participant ID in SCG Action=====>"+specimenCollectionGroupForm.getParticipantId()+" "+specimenCollectionGroupForm.getProtocolParticipantIdentifier());
// -------called from Collection Protocol Registration start-------------------------------
if( (request.getAttribute(Constants.SUBMITTED_FOR) !=null) &&(request.getAttribute(Constants.SUBMITTED_FOR).equals("Default")))
{
Logger.out.debug("Populating CP and Participant in SCG ==== AddNew operation loop");
Long cprId =new Long(specimenCollectionGroupForm.getCollectionProtocolRegistrationId());
if(cprId != null)
{
List collectionProtocolRegistrationList = bizLogic.retrieve(CollectionProtocolRegistration.class.getName(),
Constants.SYSTEM_IDENTIFIER,cprId);
if(!collectionProtocolRegistrationList.isEmpty())
{
Object obj = collectionProtocolRegistrationList.get(0 );
CollectionProtocolRegistration cpr = (CollectionProtocolRegistration)obj;
long cpID = cpr.getCollectionProtocol().getSystemIdentifier().longValue();
long pID = cpr.getParticipant().getSystemIdentifier().longValue();
String ppID = cpr.getProtocolParticipantIdentifier();
Logger.out.debug("cpID : "+ cpID + " || pID : " + pID + " || ppID : " + ppID );
specimenCollectionGroupForm.setCollectionProtocolId(cpID);
//Populating the participants registered to a given protocol
loadPaticipants(cpID , bizLogic, request);
loadPaticipantNumberList(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
String firstName = Utility.toString(cpr.getParticipant().getFirstName());;
String lastName = Utility.toString(cpr.getParticipant().getLastName());
String birthDate = Utility.toString(cpr.getParticipant().getBirthDate());
String ssn = Utility.toString(cpr.getParticipant().getSocialSecurityNumber());
if(firstName.trim().length()>0 || lastName.trim().length()>0 || birthDate.trim().length()>0 || ssn.trim().length()>0)
{
specimenCollectionGroupForm.setParticipantId(pID );
specimenCollectionGroupForm.setCheckedButton(1);
}
//Populating the protocol participants id registered to a given protocol
else if(cpr.getProtocolParticipantIdentifier() != null)
{
specimenCollectionGroupForm.setProtocolParticipantIdentifier(ppID );
specimenCollectionGroupForm.setCheckedButton(2);
}
//Populating the Collection Protocol Events
loadCollectionProtocolEvent(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
//Load Clinical status for a given study calander event point
calendarEventPointList = bizLogic.retrieve(CollectionProtocolEvent.class.getName(),
Constants.SYSTEM_IDENTIFIER,
new Long(specimenCollectionGroupForm.getCollectionProtocolEventId()));
if(isOnChange && !calendarEventPointList.isEmpty())
{
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent)calendarEventPointList.get(0);
specimenCollectionGroupForm.setClinicalStatus(collectionProtocolEvent.getClinicalStatus());
}
}
}
request.setAttribute(Constants.SUBMITTED_FOR, "Default");
}
//************* ForwardTo implementation *************
HashMap forwardToHashMap=(HashMap)request.getAttribute("forwardToHashMap");
if(forwardToHashMap !=null)
{
Long collectionProtocolId = (Long)forwardToHashMap.get("collectionProtocolId");
Long participantId=(Long)forwardToHashMap.get("participantId");
String participantProtocolId = (String) forwardToHashMap.get("participantProtocolId");
specimenCollectionGroupForm.setCollectionProtocolId(collectionProtocolId.longValue());
if(participantId != null)
{
//Populating the participants registered to a given protocol
loadPaticipants(collectionProtocolId.longValue(), bizLogic, request);
loadPaticipantNumberList(specimenCollectionGroupForm.getCollectionProtocolId(),bizLogic,request);
specimenCollectionGroupForm.setParticipantId(participantId.longValue());
specimenCollectionGroupForm.setCheckedButton(1);
}
else if(participantProtocolId != null)
{
specimenCollectionGroupForm.setProtocolParticipantIdentifier(participantProtocolId);
specimenCollectionGroupForm.setCheckedButton(2);
}
//Load Clinical status for a given study calander event point
calendarEventPointList = bizLogic.retrieve(CollectionProtocolEvent.class.getName(),
Constants.SYSTEM_IDENTIFIER,
new Long(specimenCollectionGroupForm.getCollectionProtocolEventId()));
if(!calendarEventPointList.isEmpty())
{
CollectionProtocolEvent collectionProtocolEvent = (CollectionProtocolEvent)calendarEventPointList.get(0);
specimenCollectionGroupForm.setClinicalStatus(collectionProtocolEvent.getClinicalStatus());
}
Logger.out.debug("CollectionProtocolID found in forwardToHashMap========>>>>>>"+collectionProtocolId);
Logger.out.debug("ParticipantID found in forwardToHashMap========>>>>>>"+participantId);
Logger.out.debug("ParticipantProtocolID found in forwardToHashMap========>>>>>>"+participantProtocolId);
}
//************* ForwardTo implementation *************
request.setAttribute(Constants.PAGEOF,pageOf);
Logger.out.debug("page of in Specimen coll grp action:"+request.getParameter(Constants.PAGEOF));
// -------called from Collection Protocol Registration end -------------------------------
return mapping.findForward(pageOf);
}
private void loadPaticipants(long protocolID, AbstractBizLogic bizLogic, HttpServletRequest request) throws Exception
{
//get list of Participant's names
String sourceObjectName = CollectionProtocolRegistration.class.getName();
String [] displayParticipantFields = {"participant.systemIdentifier"};
String valueField = "participant."+Constants.SYSTEM_IDENTIFIER;
String whereColumnName[] = {"collectionProtocol."+Constants.SYSTEM_IDENTIFIER,"participant.systemIdentifier"};
String whereColumnCondition[];
Object[] whereColumnValue;
if(Variables.databaseName.equals(Constants.MYSQL_DATABASE))
{
whereColumnCondition = new String[]{"=","is not"};
whereColumnValue=new Object[]{new Long(protocolID),null};
}
else
{
// for ORACLE
whereColumnCondition = new String[]{"=","is not null"};
whereColumnValue=new Object[]{new Long(protocolID)};
}
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = ", ";
List list = bizLogic.getList(sourceObjectName, displayParticipantFields, valueField, whereColumnName,
whereColumnCondition, whereColumnValue, joinCondition, separatorBetweenFields, true);
//get list of Participant's names
valueField = Constants.SYSTEM_IDENTIFIER;
sourceObjectName = Participant.class.getName();
String[] participantsFields = {"lastName","firstName","birthDate","socialSecurityNumber"};
String[] whereColumnName2 = {"lastName","firstName","birthDate","socialSecurityNumber"};
String[] whereColumnCondition2 = {"!=","!=","is not","is not"};
Object[] whereColumnValue2 = {"","",null,null};
if(Variables.databaseName.equals(Constants.MYSQL_DATABASE))
{
whereColumnCondition2 = new String[]{"!=","!=","is not","is not"};
whereColumnValue2=new String[]{"","",null,null};
}
else
{
// for ORACLE
whereColumnCondition2 = new String[]{"is not null","is not null","is not null","is not null"};
whereColumnValue2=new String[]{};
}
String joinCondition2 = Constants.OR_JOIN_CONDITION;
String separatorBetweenFields2 = ", ";
List listOfParticipants = bizLogic.getList(sourceObjectName, participantsFields, valueField, whereColumnName2,
whereColumnCondition2, whereColumnValue2, joinCondition2, separatorBetweenFields, false);
// removing blank participants from the list of Participants
list=removeBlankParticipant(list, listOfParticipants);
//Mandar bug id:1628 :- sort participant dropdown list
Collections.sort(list );
Logger.out.debug("Paticipants List"+list);
request.setAttribute(Constants.PARTICIPANT_LIST, list);
}
private List removeBlankParticipant(List list, List listOfParticipants)
{
List listOfActiveParticipant=new ArrayList();
for(int i=0; i<list.size(); i++)
{
NameValueBean nameValueBean =(NameValueBean)list.get(i);
if(Long.parseLong(nameValueBean.getValue()) == -1)
{
listOfActiveParticipant.add(list.get(i));
continue;
}
for(int j=0; j<listOfParticipants.size(); j++)
{
if(Long.parseLong(((NameValueBean)listOfParticipants.get(j)).getValue()) == -1)
continue;
NameValueBean participantsBean = (NameValueBean)listOfParticipants.get(j);
if( nameValueBean.getValue().equals(participantsBean.getValue()) )
{
listOfActiveParticipant.add(listOfParticipants.get(j));
break;
}
}
}
Logger.out.debug("No.Of Active Participants Registered with Protocol~~~~~~~~~~~~~~~~~~~~~~~>"+listOfActiveParticipant.size());
return listOfActiveParticipant;
}
private void loadPaticipantNumberList(long protocolID, AbstractBizLogic bizLogic, HttpServletRequest request) throws Exception
{
//get list of Participant's names
String sourceObjectName = CollectionProtocolRegistration.class.getName();
String displayParticipantNumberFields[] = {"protocolParticipantIdentifier"};
String valueField = "protocolParticipantIdentifier";
String whereColumnName[] = {"collectionProtocol."+Constants.SYSTEM_IDENTIFIER, "protocolParticipantIdentifier"};
String whereColumnCondition[];// = {"=","!="};
Object[] whereColumnValue;// = {new Long(protocolID),"null"};
// if(Variables.databaseName.equals(Constants.MYSQL_DATABASE))
// {
whereColumnCondition = new String[]{"=","!="};
whereColumnValue = new Object[]{new Long(protocolID),"null"};
// }
// else
// {
// whereColumnCondition = new String[]{"=","!=null"};
// whereColumnValue = new Object[]{new Long(protocolID),""};
// }
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = "";
List list = bizLogic.getList(sourceObjectName, displayParticipantNumberFields, valueField, whereColumnName,
whereColumnCondition, whereColumnValue, joinCondition, separatorBetweenFields, true);
Logger.out.debug("Paticipant Number List"+list);
request.setAttribute(Constants.PROTOCOL_PARTICIPANT_NUMBER_LIST, list);
}
private void loadCollectionProtocolEvent(long protocolID, AbstractBizLogic bizLogic, HttpServletRequest request) throws Exception
{
String sourceObjectName = CollectionProtocolEvent.class.getName();
String displayEventFields[] = {"studyCalendarEventPoint"};
String valueField = "systemIdentifier";
String whereColumnName[] = {"collectionProtocol."+Constants.SYSTEM_IDENTIFIER};
String whereColumnCondition[] = {"="};
Object[] whereColumnValue = {new Long(protocolID)};
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = "";
List list = bizLogic.getList(sourceObjectName, displayEventFields, valueField, whereColumnName,
whereColumnCondition, whereColumnValue, joinCondition, separatorBetweenFields, false);
request.setAttribute(Constants.STUDY_CALENDAR_EVENT_POINT_LIST, list);
}
private void loadParticipantMedicalIdentifier(long participantID, AbstractBizLogic bizLogic, HttpServletRequest request) throws Exception
{
//get list of Participant's names
String sourceObjectName = ParticipantMedicalIdentifier.class.getName();
String displayEventFields[] = {"medicalRecordNumber"};
String valueField = Constants.SYSTEM_IDENTIFIER;
String whereColumnName[] = {"participant."+Constants.SYSTEM_IDENTIFIER, "medicalRecordNumber"};
String whereColumnCondition[] = {"=","!="};
Object[] whereColumnValue = {new Long(participantID),"null"};
String joinCondition = Constants.AND_JOIN_CONDITION;
String separatorBetweenFields = "";
List list = bizLogic.getList(sourceObjectName, displayEventFields, valueField, whereColumnName,
whereColumnCondition, whereColumnValue, joinCondition, separatorBetweenFields, false);
request.setAttribute(Constants.PARTICIPANT_MEDICAL_IDNETIFIER_LIST, list);
}
} | Bug 1915:set SpecimenCollectionGroup.Study Calendar Event Point when page is loaded through proceedTo
SVN-Revision: 3642
| WEB-INF/src/edu/wustl/catissuecore/action/SpecimenCollectionGroupAction.java | Bug 1915:set SpecimenCollectionGroup.Study Calendar Event Point when page is loaded through proceedTo |
|
Java | mit | 6e7b9fce2dab65683801f4d8bfd1bdc0aad663e5 | 0 | AddstarMC/Minigames | package au.com.mineauz.minigames;
import org.bukkit.Location;
import org.bukkit.World;
import java.util.*;
public class StoredPlayerCheckpoints {
private String uuid;
private Map<String, Location> checkpoints;
private Map<String, List<String>> flags;
private Map<String, Long> storedTime;
private Map<String, Integer> storedDeaths;
private Map<String, Integer> storedReverts;
private Location globalCheckpoint;
public StoredPlayerCheckpoints(String uuid){
this.uuid = uuid;
checkpoints = new HashMap<String, Location>();
flags = new HashMap<String, List<String>>();
storedTime = new HashMap<String, Long>();
storedDeaths = new HashMap<String, Integer>();
storedReverts = new HashMap<String, Integer>();
}
public void addCheckpoint(String minigame, Location checkpoint){
checkpoints.put(minigame, checkpoint);
}
public void removeCheckpoint(String minigame){
if(checkpoints.containsKey(minigame)){
checkpoints.remove(minigame);
}
}
public boolean hasCheckpoint(String minigame){
return checkpoints.containsKey(minigame);
}
public Location getCheckpoint(String minigame){
return checkpoints.get(minigame);
}
public boolean hasGlobalCheckpoint(){
return globalCheckpoint != null;
}
public Location getGlobalCheckpoint(){
return globalCheckpoint;
}
public void setGlobalCheckpoint(Location checkpoint){
globalCheckpoint = checkpoint;
}
public boolean hasNoCheckpoints(){
return checkpoints.isEmpty();
}
public boolean hasFlags(String minigame){
return flags.containsKey(minigame);
}
public void addFlags(String minigame, List<String> flagList){
flags.put(minigame, new ArrayList<String>(flagList));
}
public List<String> getFlags(String minigame){
return flags.get(minigame);
}
public void removeFlags(String minigame){
flags.remove(minigame);
}
public void addTime(String minigame, long time){
storedTime.put(minigame, time);
}
public Long getTime(String minigame){
return storedTime.get(minigame);
}
public boolean hasTime(String minigame){
return storedTime.containsKey(minigame);
}
public void removeTime(String minigame){
storedTime.remove(minigame);
}
public void addDeaths(String minigame, int deaths){
storedDeaths.put(minigame, deaths);
}
public Integer getDeaths(String minigame){
return storedDeaths.get(minigame);
}
public boolean hasDeaths(String minigame){
return storedDeaths.containsKey(minigame);
}
public void removeDeaths(String minigame){
storedDeaths.remove(minigame);
}
public void addReverts(String minigame, int reverts){
storedReverts.put(minigame, reverts);
}
public Integer getReverts(String minigame){
return storedReverts.get(minigame);
}
public boolean hasReverts(String minigame){
return storedReverts.containsKey(minigame);
}
public void removeReverts(String minigame){
storedReverts.remove(minigame);
}
public void saveCheckpoints(){
MinigameSave save = new MinigameSave("playerdata/checkpoints/" + uuid);
save.deleteFile();
if(hasNoCheckpoints()) return;
save = new MinigameSave("playerdata/checkpoints/" + uuid);
for(String mgm : checkpoints.keySet()){
MinigameUtils.debugMessage("Attempting to save checkpoint for " + mgm + "...");
try {
save.getConfig().set(mgm, null);
save.getConfig().set(mgm + ".x", checkpoints.get(mgm).getX());
save.getConfig().set(mgm + ".y", checkpoints.get(mgm).getY());
save.getConfig().set(mgm + ".z", checkpoints.get(mgm).getZ());
save.getConfig().set(mgm + ".yaw", checkpoints.get(mgm).getYaw());
save.getConfig().set(mgm + ".pitch", checkpoints.get(mgm).getPitch());
save.getConfig().set(mgm + ".world", checkpoints.get(mgm).getWorld().getName());
if (flags.containsKey(mgm))
save.getConfig().set(mgm + ".flags", getFlags(mgm));
if (storedTime.containsKey(mgm))
save.getConfig().set(mgm + ".time", getTime(mgm));
if (storedDeaths.containsKey(mgm))
save.getConfig().set(mgm + ".deaths", getDeaths(mgm));
if (storedReverts.containsKey(mgm))
save.getConfig().set(mgm + ".reverts", getReverts(mgm));
}
catch (Exception e) {
// When an error is detected, remove the stored erroneous checkpoint
Minigames.plugin.getLogger().warning("Unable to save checkpoint for " + mgm + "! It has been been removed.");
e.printStackTrace();
// Remove the checkpoint from memory so it doesn't cause an error again
save.getConfig().set(mgm, null);
checkpoints.remove(mgm);
flags.remove(mgm);
storedTime.remove(mgm);
storedDeaths.remove(mgm);
storedReverts.remove(mgm);
}
}
if(hasGlobalCheckpoint()){
try {
save.getConfig().set("globalcheckpoint.x", globalCheckpoint.getX());
save.getConfig().set("globalcheckpoint.y", globalCheckpoint.getY());
save.getConfig().set("globalcheckpoint.z", globalCheckpoint.getZ());
save.getConfig().set("globalcheckpoint.yaw", globalCheckpoint.getYaw());
save.getConfig().set("globalcheckpoint.pitch", globalCheckpoint.getPitch());
save.getConfig().set("globalcheckpoint.world", globalCheckpoint.getWorld().getName());
}
catch (Exception e) {
// When an error is detected, remove the global checkpoint
save.getConfig().set("globalcheckpoint", null);
Minigames.plugin.getLogger().warning("Unable to save global checkpoint!");
e.printStackTrace();
}
}
save.saveConfig();
}
public void loadCheckpoints(){
MinigameSave save = new MinigameSave("playerdata/checkpoints/" + uuid);
Set<String> mgms = save.getConfig().getKeys(false);
for(String mgm : mgms){
if(!mgm.equals("globalcheckpoint")){
MinigameUtils.debugMessage("Attempting to load checkpoint for " + mgm + "...");
try {
Double locx = (Double) save.getConfig().get(mgm + ".x");
Double locy = (Double) save.getConfig().get(mgm + ".y");
Double locz = (Double) save.getConfig().get(mgm + ".z");
Float yaw = new Float(save.getConfig().get(mgm + ".yaw", 0).toString());
Float pitch = new Float(save.getConfig().get(mgm + ".pitch", 0).toString());
String world = (String) save.getConfig().get(mgm + ".world");
if (world == null) {
Minigames.plugin.getLogger().warning("WARNING: Invalid world \"" + world + "\" found in checkpoint for " + mgm + "! Checkpoint has been removed.");
continue;
}
World w = Minigames.plugin.getServer().getWorld(world);
if (w == null) {
Minigames.plugin.getLogger().warning("WARNING: Invalid world \"" + world + "\" found in checkpoint for " + mgm + "! Checkpoint has been removed.");
continue;
}
Location loc = new Location(w, locx, locy, locz, yaw, pitch);
checkpoints.put(mgm, loc);
} catch (ClassCastException e) {
MinigameUtils.debugMessage("Checkpoint could not be loaded ... " + mgm + " xyz not double");
} catch (NullPointerException e) {
e.printStackTrace();
}
if(save.getConfig().contains(mgm + ".flags")){
flags.put(mgm, save.getConfig().getStringList(mgm + ".flags"));
}
if(save.getConfig().contains(mgm + ".time")){
storedTime.put(mgm, save.getConfig().getLong(mgm + ".time"));
}
if(save.getConfig().contains(mgm + ".deaths")){
storedDeaths.put(mgm, save.getConfig().getInt(mgm + ".deaths"));
}
if(save.getConfig().contains(mgm + ".reverts")){
storedReverts.put(mgm, save.getConfig().getInt(mgm + ".reverts"));
}
}
}
if(save.getConfig().contains("globalcheckpoint")){
double x = save.getConfig().getDouble("globalcheckpoint.x");
double y = save.getConfig().getDouble("globalcheckpoint.y");
double z = save.getConfig().getDouble("globalcheckpoint.z");
Float yaw = new Float(save.getConfig().get("globalcheckpoint.yaw").toString());
Float pitch = new Float(save.getConfig().get("globalcheckpoint.pitch").toString());
String world = save.getConfig().getString("globalcheckpoint.world");
World w = Minigames.plugin.getServer().getWorld(world);
if (w == null) {
Minigames.plugin.getLogger().warning("WARNING: Invalid world \"" + world + "\" found in global checkpoint! Checkpoint has been removed.");
} else {
globalCheckpoint = new Location(Minigames.plugin.getServer().getWorld(world), x, y, z, yaw, pitch);
}
}
}
}
| Minigames/src/main/java/au/com/mineauz/minigames/StoredPlayerCheckpoints.java | package au.com.mineauz.minigames;
import org.bukkit.Location;
import org.bukkit.World;
import java.util.*;
public class StoredPlayerCheckpoints {
private String uuid;
private Map<String, Location> checkpoints;
private Map<String, List<String>> flags;
private Map<String, Long> storedTime;
private Map<String, Integer> storedDeaths;
private Map<String, Integer> storedReverts;
private Location globalCheckpoint;
public StoredPlayerCheckpoints(String uuid){
this.uuid = uuid;
checkpoints = new HashMap<String, Location>();
flags = new HashMap<String, List<String>>();
storedTime = new HashMap<String, Long>();
storedDeaths = new HashMap<String, Integer>();
storedReverts = new HashMap<String, Integer>();
}
public void addCheckpoint(String minigame, Location checkpoint){
checkpoints.put(minigame, checkpoint);
}
public void removeCheckpoint(String minigame){
if(checkpoints.containsKey(minigame)){
checkpoints.remove(minigame);
}
}
public boolean hasCheckpoint(String minigame){
return checkpoints.containsKey(minigame);
}
public Location getCheckpoint(String minigame){
return checkpoints.get(minigame);
}
public boolean hasGlobalCheckpoint(){
return globalCheckpoint != null;
}
public Location getGlobalCheckpoint(){
return globalCheckpoint;
}
public void setGlobalCheckpoint(Location checkpoint){
globalCheckpoint = checkpoint;
}
public boolean hasNoCheckpoints(){
return checkpoints.isEmpty();
}
public boolean hasFlags(String minigame){
return flags.containsKey(minigame);
}
public void addFlags(String minigame, List<String> flagList){
flags.put(minigame, new ArrayList<String>(flagList));
}
public List<String> getFlags(String minigame){
return flags.get(minigame);
}
public void removeFlags(String minigame){
flags.remove(minigame);
}
public void addTime(String minigame, long time){
storedTime.put(minigame, time);
}
public Long getTime(String minigame){
return storedTime.get(minigame);
}
public boolean hasTime(String minigame){
return storedTime.containsKey(minigame);
}
public void removeTime(String minigame){
storedTime.remove(minigame);
}
public void addDeaths(String minigame, int deaths){
storedDeaths.put(minigame, deaths);
}
public Integer getDeaths(String minigame){
return storedDeaths.get(minigame);
}
public boolean hasDeaths(String minigame){
return storedDeaths.containsKey(minigame);
}
public void removeDeaths(String minigame){
storedDeaths.remove(minigame);
}
public void addReverts(String minigame, int reverts){
storedReverts.put(minigame, reverts);
}
public Integer getReverts(String minigame){
return storedReverts.get(minigame);
}
public boolean hasReverts(String minigame){
return storedReverts.containsKey(minigame);
}
public void removeReverts(String minigame){
storedReverts.remove(minigame);
}
public void saveCheckpoints(){
MinigameSave save = new MinigameSave("playerdata/checkpoints/" + uuid);
save.deleteFile();
if(hasNoCheckpoints()) return;
save = new MinigameSave("playerdata/checkpoints/" + uuid);
for(String mgm : checkpoints.keySet()){
MinigameUtils.debugMessage("Attempting to save checkpoint for " + mgm + "...");
try {
save.getConfig().set(mgm, null);
save.getConfig().set(mgm + ".x", checkpoints.get(mgm).getX());
save.getConfig().set(mgm + ".y", checkpoints.get(mgm).getY());
save.getConfig().set(mgm + ".z", checkpoints.get(mgm).getZ());
save.getConfig().set(mgm + ".yaw", checkpoints.get(mgm).getYaw());
save.getConfig().set(mgm + ".pitch", checkpoints.get(mgm).getPitch());
save.getConfig().set(mgm + ".world", checkpoints.get(mgm).getWorld().getName());
if (flags.containsKey(mgm))
save.getConfig().set(mgm + ".flags", getFlags(mgm));
if (storedTime.containsKey(mgm))
save.getConfig().set(mgm + ".time", getTime(mgm));
if (storedDeaths.containsKey(mgm))
save.getConfig().set(mgm + ".deaths", getDeaths(mgm));
if (storedReverts.containsKey(mgm))
save.getConfig().set(mgm + ".reverts", getReverts(mgm));
}
catch (Exception e) {
// When an error is detected, remove the stored erroneous checkpoint
Minigames.plugin.getLogger().warning("Unable to save checkpoint for " + mgm + "! It has been been removed.");
e.printStackTrace();
// Remove the checkpoint from memory so it doesn't cause an error again
save.getConfig().set(mgm, null);
checkpoints.remove(mgm);
flags.remove(mgm);
storedTime.remove(mgm);
storedDeaths.remove(mgm);
storedReverts.remove(mgm);
}
}
if(hasGlobalCheckpoint()){
try {
save.getConfig().set("globalcheckpoint.x", globalCheckpoint.getX());
save.getConfig().set("globalcheckpoint.y", globalCheckpoint.getY());
save.getConfig().set("globalcheckpoint.z", globalCheckpoint.getZ());
save.getConfig().set("globalcheckpoint.yaw", globalCheckpoint.getYaw());
save.getConfig().set("globalcheckpoint.pitch", globalCheckpoint.getPitch());
save.getConfig().set("globalcheckpoint.world", globalCheckpoint.getWorld().getName());
}
catch (Exception e) {
// When an error is detected, remove the global checkpoint
save.getConfig().set("globalcheckpoint", null);
Minigames.plugin.getLogger().warning("Unable to save global checkpoint!");
e.printStackTrace();
}
}
save.saveConfig();
}
public void loadCheckpoints(){
MinigameSave save = new MinigameSave("playerdata/checkpoints/" + uuid);
Set<String> mgms = save.getConfig().getKeys(false);
for(String mgm : mgms){
if(!mgm.equals("globalcheckpoint")){
MinigameUtils.debugMessage("Attempting to load checkpoint for " + mgm + "...");
try {
Double locx = (Double) save.getConfig().get(mgm + ".x");
Double locy = (Double) save.getConfig().get(mgm + ".y");
Double locz = (Double) save.getConfig().get(mgm + ".z");
Float yaw = new Float(save.getConfig().get(mgm + ".yaw", 0).toString());
Float pitch = new Float(save.getConfig().get(mgm + ".pitch", 0).toString());
String world = (String) save.getConfig().get(mgm + ".world");
World w = Minigames.plugin.getServer().getWorld(world);
if (w == null) {
Minigames.plugin.getLogger().warning("WARNING: Invalid world \"" + world + "\" found in checkpoint for " + mgm + "! Checkpoint has been removed.");
continue;
}
Location loc = new Location(w, locx, locy, locz, yaw, pitch);
checkpoints.put(mgm, loc);
} catch (ClassCastException e) {
MinigameUtils.debugMessage("Checkpoint could not be loaded ... " + mgm + " xyz not double");
} catch (NullPointerException e) {
e.printStackTrace();
}
if(save.getConfig().contains(mgm + ".flags")){
flags.put(mgm, save.getConfig().getStringList(mgm + ".flags"));
}
if(save.getConfig().contains(mgm + ".time")){
storedTime.put(mgm, save.getConfig().getLong(mgm + ".time"));
}
if(save.getConfig().contains(mgm + ".deaths")){
storedDeaths.put(mgm, save.getConfig().getInt(mgm + ".deaths"));
}
if(save.getConfig().contains(mgm + ".reverts")){
storedReverts.put(mgm, save.getConfig().getInt(mgm + ".reverts"));
}
}
}
if(save.getConfig().contains("globalcheckpoint")){
double x = save.getConfig().getDouble("globalcheckpoint.x");
double y = save.getConfig().getDouble("globalcheckpoint.y");
double z = save.getConfig().getDouble("globalcheckpoint.z");
Float yaw = new Float(save.getConfig().get("globalcheckpoint.yaw").toString());
Float pitch = new Float(save.getConfig().get("globalcheckpoint.pitch").toString());
String world = save.getConfig().getString("globalcheckpoint.world");
World w = Minigames.plugin.getServer().getWorld(world);
if (w == null) {
Minigames.plugin.getLogger().warning("WARNING: Invalid world \"" + world + "\" found in global checkpoint! Checkpoint has been removed.");
} else {
globalCheckpoint = new Location(Minigames.plugin.getServer().getWorld(world), x, y, z, yaw, pitch);
}
}
}
}
| Fix NPE on checkpoint loading
Signed-off-by: Narimm <[email protected]>
| Minigames/src/main/java/au/com/mineauz/minigames/StoredPlayerCheckpoints.java | Fix NPE on checkpoint loading |
|
Java | mit | 02e0c037db8e6a6c280386d05970fc47ebfc1785 | 0 | alecgorge/jsonapi,alecgorge/jsonapi,alecgorge/jsonapi,alecgorge/jsonapi,alecgorge/jsonapi,alecgorge/jsonapi,alecgorge/jsonapi | package com.ramblingwood.minecraft.jsonapi;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginLoader;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.config.Configuration;
import com.ramblingwood.minecraft.jsonapi.McRKit.api.RTKInterface;
import com.ramblingwood.minecraft.jsonapi.McRKit.api.RTKInterfaceException;
import com.ramblingwood.minecraft.jsonapi.McRKit.api.RTKListener;
import com.ramblingwood.minecraft.jsonapi.dynamic.APIWrapperMethods;
import com.ramblingwood.minecraft.jsonapi.streams.ConsoleHandler;
import com.ramblingwood.minecraft.jsonapi.util.PropertiesFile;
/**
*
* @author alecgorge
*/
public class JSONAPI extends JavaPlugin implements RTKListener {
public PluginLoader pluginLoader;
// private Server server;
public JSONServer jsonServer;
public JSONSocketServer jsonSocketServer;
public JSONWebSocketServer jsonWebSocketServer;
public boolean logging = false;
public String logFile = "false";
public String salt = "";
public int port = 20059;
public List<String> whitelist = new ArrayList<String>();
public List<String> method_noauth_whitelist = new ArrayList<String>();
private Logger log = Logger.getLogger("Minecraft");
private Logger outLog = Logger.getLogger("JSONAPI");
private PluginManager pm;
private Handler handler;
public RTKInterface rtkAPI;
// for dynamic access
public static JSONAPI instance;
protected void initalize(PluginLoader pluginLoader, Server instance, PluginDescriptionFile desc, File folder, File plugin, ClassLoader cLoader) {
this.pluginLoader = pluginLoader;
// server = instance;
}
public JSONAPI () {
super();
JSONAPI.instance = this;
}
public JSONServer getJSONServer () {
return jsonServer;
}
public void registerMethod(String method) {
getJSONServer().getCaller().loadString("["+method+"]");
}
public void registerMethods(String method) {
getJSONServer().getCaller().loadString(method);
}
private JSONAPIPlayerListener l = new JSONAPIPlayerListener(this);
public void onEnable() {
try {
HashMap<String, String> auth = new HashMap<String, String>();
if(!getDataFolder().exists()) {
getDataFolder().mkdir();
}
outLog = Logger.getLogger("JSONAPI");
File mainConfig = new File(getDataFolder(), "JSONAPI.properties");
File authfile = new File(getDataFolder(), "JSONAPIAuthentication.txt");
File authfile2 = new File(getDataFolder(), "JSONAPIMethodNoAuthWhitelist.txt");
File yamlFile = new File(getDataFolder(), "config.yml");
File methods = new File(getDataFolder(), "methods.json");
if(!methods.exists()) {
log.severe("[JSONAPI] plugins/JSONAPI/methods.json is missing!");
log.severe("[JSONAPI] JSONAPI not loaded!");
return;
}
if(!yamlFile.exists() && !mainConfig.exists()) {
log.severe("[JSONAPI] config.yml and JSONAPI.properties are both missing. You need at least one!");
log.severe("[JSONAPI] JSONAPI not loaded!");
return;
}
PropertiesFile options = null;
String ipWhitelist = "";
String reconstituted = "";
if(mainConfig.exists()) {
options = new PropertiesFile(mainConfig.getAbsolutePath());
logging = options.getBoolean("log-to-console", true);
logFile = options.getString("log-to-file", "false");
ipWhitelist = options.getString("ip-whitelist", "false");
salt = options.getString("salt", "");
reconstituted = "";
}
if(mainConfig.exists() && !yamlFile.exists()) {
// auto-migrate to yaml from properties and plain text files
yamlFile.createNewFile();
Configuration yamlConfig = new Configuration(yamlFile);
if(!ipWhitelist.trim().equals("false")) {
String[] ips = ipWhitelist.split(",");
StringBuffer t = new StringBuffer();
for(String ip : ips) {
t.append(ip.trim()+",");
whitelist.add(ip);
}
reconstituted = t.toString();
}
port = options.getInt("port", 20059);
try {
FileInputStream fstream;
try {
fstream = new FileInputStream(authfile);
}
catch (FileNotFoundException e) {
authfile.createNewFile();
fstream = new FileInputStream(authfile);
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
if(!line.startsWith("#")) {
String[] parts = line.trim().split(":");
if(parts.length == 2) {
auth.put(parts[0], parts[1]);
}
}
}
br.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileInputStream fstream;
try {
fstream = new FileInputStream(authfile2);
}
catch (FileNotFoundException e) {
authfile2.createNewFile();
fstream = new FileInputStream(authfile2);
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
if(!line.trim().startsWith("#")) {
method_noauth_whitelist.add(line.trim());
}
}
br.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
yamlConfig.setProperty("options.log-to-console", logging);
yamlConfig.setProperty("options.log-to-file", logFile);
yamlConfig.setProperty("options.ip-whitelist", whitelist);
yamlConfig.setProperty("options.salt", salt);
yamlConfig.setProperty("options.port", port);
yamlConfig.setProperty("method-whitelist", method_noauth_whitelist);
yamlConfig.setProperty("logins", auth);
yamlConfig.save();
mainConfig.delete();
authfile.delete();
authfile2.delete();
}
else if(yamlFile.exists()) {
Configuration yamlConfig = new Configuration(yamlFile);
yamlConfig.load(); // VERY IMPORTANT
logging = yamlConfig.getBoolean("options.log-to-console", true);
logFile = yamlConfig.getString("options.log-to-file", "false");
whitelist = yamlConfig.getStringList("options.ip-whitelist", new ArrayList<String>());
for(String ip : whitelist) {
reconstituted += ip + ",";
}
salt = yamlConfig.getString("options.salt", "");
port = yamlConfig.getInt("options.port", 20059);
method_noauth_whitelist = yamlConfig.getStringList("method-whitelist", new ArrayList<String>());
List<String> logins = yamlConfig.getKeys("logins");
for(String k : logins) {
auth.put(k, yamlConfig.getString("logins."+k));
}
}
Configuration yamlRTK = new Configuration(new File(getDataFolder(), "config_rtk.yml"));
try {
rtkAPI = RTKInterface.createRTKInterface(yamlRTK.getInt("RTK.port", 25561), "localhost", yamlRTK.getString("RTK.username", "user"), yamlRTK.getString("RTK.password", "pass"));
rtkAPI.registerRTKListener(this);
} catch (RTKInterfaceException e) {
e.printStackTrace();
}
if(!logging) {
for(Handler h : outLog.getHandlers()) {
outLog.removeHandler(h);
}
}
if(!logFile.equals("false") && !logFile.isEmpty()) {
FileHandler fh = new FileHandler(logFile);
fh.setFormatter(new SimpleFormatter());
outLog.addHandler(fh);
}
if(auth.size() == 0) {
log.severe("[JSONAPI] No valid logins for JSONAPI. Check config.yml");
return;
}
log.info("[JSONAPI] Logging to file: "+logFile);
log.info("[JSONAPI] Logging to console: "+String.valueOf(logging));
log.info("[JSONAPI] IP Whitelist = "+(reconstituted.equals("") ? "None, all requests are allowed." : reconstituted));
jsonServer = new JSONServer(auth, this);
// add console stream support
handler = new ConsoleHandler(jsonServer);
log.addHandler(handler);
if(logging) {
outLog.addHandler(handler);
}
jsonSocketServer = new JSONSocketServer(port + 1, jsonServer);
jsonWebSocketServer = new JSONWebSocketServer(port + 2, jsonServer);
jsonWebSocketServer.start();
initialiseListeners();
}
catch( IOException ioe ) {
log.severe( "[JSONAPI] Couldn't start server!\n");
ioe.printStackTrace();
//System.exit( -1 );
}
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (sender instanceof ConsoleCommandSender) {
if (cmd.getName().equals("reloadjsonapi")) {
if (sender instanceof ConsoleCommandSender) {
log.info("Reloading JSONAPI");
onDisable();
onEnable();
}
return true;
}
else if (cmd.getName().equals("jsonapi-list")) {
if (sender instanceof ConsoleCommandSender) {
for(String key : jsonServer.getCaller().methods.keySet()) {
StringBuilder sb = new StringBuilder((key.trim().equals("") ? "Default Namespace" : key.trim()) +": ");
for(String m : jsonServer.getCaller().methods.get(key).keySet()) {
sb.append(jsonServer.getCaller().methods.get(key).get(m).getName()).append(", ");
}
sender.sendMessage(sb.substring(0, sb.length()-2).toString()+"\n");
}
}
return true;
}
}
return false;
}
@Override
public void onDisable(){
if(jsonServer != null) {
try {
jsonServer.stop();
jsonSocketServer.stop();
jsonWebSocketServer.stop();
APIWrapperMethods.getInstance().disconnectAllFauxPlayers();
} catch (IOException e) {
e.printStackTrace();
}
log.removeHandler(handler);
}
}
private void initialiseListeners() {
pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.PLAYER_CHAT, l, Priority.Normal, this);
// pm.registerEvent(Event.Type.PLAYER_COMMAND_PREPROCESS, l, Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, l, Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_JOIN, l, Priority.Normal, this);
}
/**
* From a password, a number of iterations and a salt,
* returns the corresponding digest
* @param iterationNb int The number of iterations of the algorithm
* @param password String The password to encrypt
* @param salt byte[] The salt
* @return byte[] The digested password
* @throws NoSuchAlgorithmException If the algorithm doesn't exist
*/
public static String SHA256(String password) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
byte[] input = null;
try {
input = digest.digest(password.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for(int i = 0; i< input.length; i++) {
String hex = Integer.toHexString(0xFF & input[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "UnsupportedEncodingException";
}
public void disable() {
jsonServer.stop();
}
public static class JSONAPIPlayerListener extends PlayerListener {
JSONAPI p;
// This controls the accessibility of functions / variables from the main class.
public JSONAPIPlayerListener(JSONAPI plugin) {
p = plugin;
}
public void onPlayerChat(PlayerChatEvent event) {
p.jsonServer.logChat(event.getPlayer().getName(),event.getMessage());
}
public void onPlayerJoin(PlayerJoinEvent event) {
APIWrapperMethods.getInstance().manager = ((CraftPlayer)event.getPlayer()).getHandle().netServerHandler.networkManager;
p.jsonServer.logConnected(event.getPlayer().getName());
}
public void onPlayerQuit(PlayerQuitEvent event) {
p.jsonServer.logDisconnected(event.getPlayer().getName());
}
}
@Override
public void onRTKStringReceived(String message) {
}
} | src/com/ramblingwood/minecraft/jsonapi/JSONAPI.java | package com.ramblingwood.minecraft.jsonapi;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.event.player.PlayerChatEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerListener;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginLoader;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.config.Configuration;
import com.ramblingwood.minecraft.jsonapi.McRKit.api.RTKInterface;
import com.ramblingwood.minecraft.jsonapi.McRKit.api.RTKInterfaceException;
import com.ramblingwood.minecraft.jsonapi.McRKit.api.RTKListener;
import com.ramblingwood.minecraft.jsonapi.dynamic.APIWrapperMethods;
import com.ramblingwood.minecraft.jsonapi.streams.ConsoleHandler;
import com.ramblingwood.minecraft.jsonapi.util.PropertiesFile;
/**
*
* @author alecgorge
*/
public class JSONAPI extends JavaPlugin implements RTKListener {
public PluginLoader pluginLoader;
// private Server server;
public JSONServer jsonServer;
public JSONSocketServer jsonSocketServer;
public JSONWebSocketServer jsonWebSocketServer;
public boolean logging = false;
public String logFile = "false";
public String salt = "";
public int port = 20059;
public List<String> whitelist = new ArrayList<String>();
public List<String> method_noauth_whitelist = new ArrayList<String>();
private Logger log = Logger.getLogger("Minecraft");
private Logger outLog = Logger.getLogger("JSONAPI");
private PluginManager pm;
private Handler handler;
public RTKInterface rtkAPI;
// for dynamic access
public static JSONAPI instance;
protected void initalize(PluginLoader pluginLoader, Server instance, PluginDescriptionFile desc, File folder, File plugin, ClassLoader cLoader) {
this.pluginLoader = pluginLoader;
// server = instance;
}
public JSONAPI () {
super();
JSONAPI.instance = this;
}
public JSONServer getJSONServer () {
return jsonServer;
}
public void registerMethod(String method) {
getJSONServer().getCaller().loadString("["+method+"]");
}
public void registerMethods(String method) {
getJSONServer().getCaller().loadString(method);
}
private JSONAPIPlayerListener l = new JSONAPIPlayerListener(this);
public void onEnable() {
try {
HashMap<String, String> auth = new HashMap<String, String>();
if(!getDataFolder().exists()) {
getDataFolder().mkdir();
}
outLog = Logger.getLogger("JSONAPI");
File mainConfig = new File(getDataFolder(), "JSONAPI.properties");
File authfile = new File(getDataFolder(), "JSONAPIAuthentication.txt");
File authfile2 = new File(getDataFolder(), "JSONAPIMethodNoAuthWhitelist.txt");
File yamlFile = new File(getDataFolder(), "config.yml");
File methods = new File(getDataFolder(), "methods.json");
if(!methods.exists()) {
log.severe("[JSONAPI] plugins/JSONAPI/methods.json is missing!");
log.severe("[JSONAPI] JSONAPI not loaded!");
return;
}
if(!yamlFile.exists() && !mainConfig.exists()) {
log.severe("[JSONAPI] config.yml and JSONAPI.properties are both missing. You need at least one!");
log.severe("[JSONAPI] JSONAPI not loaded!");
return;
}
PropertiesFile options = null;
String ipWhitelist = "";
String reconstituted = "";
if(mainConfig.exists()) {
options = new PropertiesFile(mainConfig.getAbsolutePath());
logging = options.getBoolean("log-to-console", true);
logFile = options.getString("log-to-file", "false");
ipWhitelist = options.getString("ip-whitelist", "false");
salt = options.getString("salt", "");
reconstituted = "";
}
if(mainConfig.exists() && !yamlFile.exists()) {
// auto-migrate to yaml from properties and plain text files
yamlFile.createNewFile();
Configuration yamlConfig = new Configuration(yamlFile);
if(!ipWhitelist.trim().equals("false")) {
String[] ips = ipWhitelist.split(",");
StringBuffer t = new StringBuffer();
for(String ip : ips) {
t.append(ip.trim()+",");
whitelist.add(ip);
}
reconstituted = t.toString();
}
port = options.getInt("port", 20059);
try {
FileInputStream fstream;
try {
fstream = new FileInputStream(authfile);
}
catch (FileNotFoundException e) {
authfile.createNewFile();
fstream = new FileInputStream(authfile);
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
if(!line.startsWith("#")) {
String[] parts = line.trim().split(":");
if(parts.length == 2) {
auth.put(parts[0], parts[1]);
}
}
}
br.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
FileInputStream fstream;
try {
fstream = new FileInputStream(authfile2);
}
catch (FileNotFoundException e) {
authfile2.createNewFile();
fstream = new FileInputStream(authfile2);
}
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
if(!line.trim().startsWith("#")) {
method_noauth_whitelist.add(line.trim());
}
}
br.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
yamlConfig.setProperty("options.log-to-console", logging);
yamlConfig.setProperty("options.log-to-file", logFile);
yamlConfig.setProperty("options.ip-whitelist", whitelist);
yamlConfig.setProperty("options.salt", salt);
yamlConfig.setProperty("options.port", port);
yamlConfig.setProperty("method-whitelist", method_noauth_whitelist);
yamlConfig.setProperty("logins", auth);
yamlConfig.save();
mainConfig.delete();
authfile.delete();
authfile2.delete();
}
else if(yamlFile.exists()) {
Configuration yamlConfig = new Configuration(yamlFile);
yamlConfig.load(); // VERY IMPORTANT
logging = yamlConfig.getBoolean("options.log-to-console", true);
logFile = yamlConfig.getString("options.log-to-file", "false");
whitelist = yamlConfig.getStringList("options.ip-whitelist", new ArrayList<String>());
for(String ip : whitelist) {
reconstituted += ip + ",";
}
salt = yamlConfig.getString("options.salt", "");
port = yamlConfig.getInt("options.port", 20059);
method_noauth_whitelist = yamlConfig.getStringList("method-whitelist", new ArrayList<String>());
List<String> logins = yamlConfig.getKeys("logins");
for(String k : logins) {
auth.put(k, yamlConfig.getString("logins."+k));
}
}
Configuration yamlRTK = new Configuration(new File(getDataFolder(), "config_rtk.yml"));
try {
rtkAPI = RTKInterface.createRTKInterface(yamlRTK.getInt("RTK.port", 25561), "localhost", yamlRTK.getString("RTK.username", "user"), yamlRTK.getString("RTK.password", "pass"));
rtkAPI.registerRTKListener(this);
} catch (RTKInterfaceException e) {
e.printStackTrace();
}
if(!logging) {
for(Handler h : outLog.getHandlers()) {
outLog.removeHandler(h);
}
}
if(!logFile.equals("false") && !logFile.isEmpty()) {
FileHandler fh = new FileHandler(logFile);
fh.setFormatter(new SimpleFormatter());
outLog.addHandler(fh);
}
if(auth.size() == 0) {
log.severe("[JSONAPI] No valid logins for JSONAPI. Check config.yml");
return;
}
log.info("[JSONAPI] Logging to file: "+logFile);
log.info("[JSONAPI] Logging to console: "+String.valueOf(logging));
log.info("[JSONAPI] IP Whitelist = "+(reconstituted.equals("") ? "None, all requests are allowed." : reconstituted));
jsonServer = new JSONServer(auth, this);
// add console stream support
handler = new ConsoleHandler(jsonServer);
log.addHandler(handler);
outLog.addHandler(handler);
jsonSocketServer = new JSONSocketServer(port + 1, jsonServer);
jsonWebSocketServer = new JSONWebSocketServer(port + 2, jsonServer);
jsonWebSocketServer.start();
initialiseListeners();
}
catch( IOException ioe ) {
log.severe( "[JSONAPI] Couldn't start server!\n");
ioe.printStackTrace();
//System.exit( -1 );
}
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (sender instanceof ConsoleCommandSender) {
if (cmd.getName().equals("reloadjsonapi")) {
if (sender instanceof ConsoleCommandSender) {
log.info("Reloading JSONAPI");
onDisable();
onEnable();
}
return true;
}
else if (cmd.getName().equals("jsonapi-list")) {
if (sender instanceof ConsoleCommandSender) {
for(String key : jsonServer.getCaller().methods.keySet()) {
StringBuilder sb = new StringBuilder((key.trim().equals("") ? "Default Namespace" : key.trim()) +": ");
for(String m : jsonServer.getCaller().methods.get(key).keySet()) {
sb.append(jsonServer.getCaller().methods.get(key).get(m).getName()).append(", ");
}
sender.sendMessage(sb.substring(0, sb.length()-2).toString()+"\n");
}
}
return true;
}
}
return false;
}
@Override
public void onDisable(){
if(jsonServer != null) {
try {
jsonServer.stop();
jsonSocketServer.stop();
jsonWebSocketServer.stop();
APIWrapperMethods.getInstance().disconnectAllFauxPlayers();
} catch (IOException e) {
e.printStackTrace();
}
log.removeHandler(handler);
}
}
private void initialiseListeners() {
pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.PLAYER_CHAT, l, Priority.Normal, this);
// pm.registerEvent(Event.Type.PLAYER_COMMAND_PREPROCESS, l, Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, l, Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_JOIN, l, Priority.Normal, this);
}
/**
* From a password, a number of iterations and a salt,
* returns the corresponding digest
* @param iterationNb int The number of iterations of the algorithm
* @param password String The password to encrypt
* @param salt byte[] The salt
* @return byte[] The digested password
* @throws NoSuchAlgorithmException If the algorithm doesn't exist
*/
public static String SHA256(String password) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
digest.reset();
byte[] input = null;
try {
input = digest.digest(password.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for(int i = 0; i< input.length; i++) {
String hex = Integer.toHexString(0xFF & input[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "UnsupportedEncodingException";
}
public void disable() {
jsonServer.stop();
}
public static class JSONAPIPlayerListener extends PlayerListener {
JSONAPI p;
// This controls the accessibility of functions / variables from the main class.
public JSONAPIPlayerListener(JSONAPI plugin) {
p = plugin;
}
public void onPlayerChat(PlayerChatEvent event) {
p.jsonServer.logChat(event.getPlayer().getName(),event.getMessage());
}
public void onPlayerJoin(PlayerJoinEvent event) {
APIWrapperMethods.getInstance().manager = ((CraftPlayer)event.getPlayer()).getHandle().netServerHandler.networkManager;
p.jsonServer.logConnected(event.getPlayer().getName());
}
public void onPlayerQuit(PlayerQuitEvent event) {
p.jsonServer.logDisconnected(event.getPlayer().getName());
}
}
@Override
public void onRTKStringReceived(String message) {
}
} | honor the log to console option in the console stream
| src/com/ramblingwood/minecraft/jsonapi/JSONAPI.java | honor the log to console option in the console stream |
|
Java | mit | 46421f22371a9969ab40646eca993a88779a4ab5 | 0 | t3ddftw/DroidIBus | package net.littlebigisland.droidibus.ibus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class SteeringWheelSystemCommand extends IBusSystemCommand{
private Map<Byte, IBusSystemCommand> IBusMFSWMap = new HashMap<Byte, IBusSystemCommand>();
class Radio extends IBusSystemCommand{
public void mapReceived(ArrayList<Byte> msg) {
currentMessage = msg;
if(currentMessage.get(4) == 0x3B){
switch(currentMessage.get(4)){
case 0x21: //Fwds Btn
if(mCallbackReceiver != null)
mCallbackReceiver.onTrackFwd();
break;
case 0x28: //Prev Btn
if(mCallbackReceiver != null)
mCallbackReceiver.onTrackPrev();
break;
}
}
}
}
public void mapReceived(ArrayList<Byte> msg) {
if(IBusMFSWMap.isEmpty()){
IBusMFSWMap.put(DeviceAddress.Radio.toByte(), new Radio());
}
try{
IBusMFSWMap.get((byte) msg.get(2)).mapReceived(msg);
}catch(NullPointerException npe){
// Things not in the map throw a NullPointerException
}
}
}
| src/net/littlebigisland/droidibus/ibus/SteeringWheelSystemCommand.java | package net.littlebigisland.droidibus.ibus;
import java.util.ArrayList;
public class SteeringWheelSystemCommand extends IBusSystemCommand{
public void mapReceived(ArrayList<Byte> msg) {
// TODO Auto-generated method stub
}
}
| Fwd/Prev button steering wheel button tracking
| src/net/littlebigisland/droidibus/ibus/SteeringWheelSystemCommand.java | Fwd/Prev button steering wheel button tracking |
|
Java | mit | c7a3b6ce0cafbcd368befe50a531581280849938 | 0 | trendrr/java-oss-lib,MarkG/java-oss-lib | /**
*
*/
package com.trendrr.oss;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.io.*;
import java.util.zip.*;
/**
* @author dustin
*
*/
public class FileHelper {
public static boolean LINUX = System.getProperty("os.name").toLowerCase().contains("linux");
public static boolean WINDOWS = System.getProperty("os.name").toLowerCase().contains("windows");
public static boolean MAC = System.getProperty("os.name").toLowerCase().contains("mac");
public static double bytesToGigs(long bytes) {
return bytes / 1073741824l;
}
public static double bytesToMegs(long bytes) {
return bytes / 1048576l;
}
/**
* converts from gigabytes to bytes
* @return
*/
public static long gigsToBytes(int gigs) {
return gigs * 1073741824l;
}
public static long megsToBytes(int megs) {
return megs * 1048576l;
}
/**
* Gets a filestream for the passed in filename.
* will try to get it from within a jar if available.
* else will load relative to cwd.
*
* @param filename
* @return
*/
public static InputStream fileStream(String filename) throws Exception {
filename = toSystemDependantFilename(filename);
//try to load it from the jar.
InputStream stream = ClassLoader.getSystemResourceAsStream(filename);
if (stream == null) {
//else load from the filesystem.
stream = new FileInputStream(filename);
}
return stream;
}
public static String toSystemDependantFilename(String filename) {
return filename.replace('/', File.separatorChar);
}
public static String unzip(String filename,String zip_extension,String file_extension){
FileInputStream instream;
try {
instream = new FileInputStream(filename + "." + file_extension + "." + zip_extension);
GZIPInputStream ginstream =new GZIPInputStream(instream);
FileOutputStream outstream = new FileOutputStream(filename + "." + file_extension);
byte[] buf = new byte[1024];
int len=0;
while ((len = ginstream.read(buf)) > 0)
{
outstream.write(buf, 0, len);
}
ginstream.close();
outstream.close();
return filename + "." + file_extension;
}catch(EOFException e){
System.out.println("File is ended");
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO Errors");
e.printStackTrace();
}
return null;
}
/**
* zips the file and save as filename +".zip".
*
* returns the filename of the newly created zip
* @param filename
*/
public static String zip(String filename) throws Exception{
int BUFFER = 2048;
String fname = toSystemDependantFilename(filename);
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(fname + ".zip");
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
//out.setMethod(ZipOutputStream.DEFLATED);
byte data[] = new byte[BUFFER];
// get a list of files from current directory
File in = new File(fname);
FileInputStream fi = new FileInputStream(in);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(in.getName());
out.putNextEntry(entry);
int count;
while((count = origin.read(data, 0,
BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
out.close();
return fname + ".zip";
}
/**
* cleans up any illegal characters for windows
* @param filename
* @return
*/
public static String toWindowsFilename(String filename) {
return StringHelper.removeAll(filename, ':', '\"', '|', '<', '>', '?', '*');
}
public static String getAbsoluteFilename(File file) {
return file.getPath();
}
/**
* returns a list of the files within this directory
* @param dir
* @return
* @throws Exception
*/
public static List<File> listDirectory(File dir, boolean recur) throws Exception {
File[] fileList = dir.listFiles();
List<File> files = new ArrayList<File>();
if (fileList == null)
return files;
for (File file : fileList) {
if (file.isDirectory()) {
if (recur) {
files.addAll(listDirectory(file, recur));
}
} else {
files.add(file);
}
}
return files;
}
/**
* same as listDirectory but only returns the simple filename (not complete path).
* @param dir
* @param recure
* @return
* @throws Exception
*/
public static List<String> listFilenames(String directory, boolean recur) throws Exception {
List<File> files = listDirectory(new File(directory), recur);
List<String> filenames = new ArrayList<String>();
for (File file : files) {
String filename = file.getName();
filenames.add(filename);
}
return filenames;
}
/**
* returns filenames within this directory. only returns files, not directories
* @param directory
* @return
* @throws Exception
*/
public static List<String> listDirectory(String directory, boolean recur) throws Exception {
if (directory == null || directory.isEmpty()) {
directory = "./";
}
List<File> files = listDirectory(new File(directory), recur);
List<String> filenames = new ArrayList<String>();
for (File file : files) {
String filename = getAbsoluteFilename(file);
filenames.add(filename);
}
return filenames;
}
/**
* Creates directories if necessarry
* @param filename
*/
public static void createDirectories(String filename) throws Exception {
if (filename.indexOf(File.separator) == -1) {
return;
}
File file = new File(filename.substring(0, filename.lastIndexOf(File.separator)));
if (!file.exists())
file.mkdirs();
}
public static File createNewFile(String filename) throws Exception {
filename = toSystemDependantFilename(filename);
createDirectories(filename);
File file = new File(filename);
file.createNewFile();
return file;
}
public static void saveBytes(String filename, byte[] bytes) throws Exception {
File file = FileHelper.createNewFile(filename);
FileOutputStream os = new FileOutputStream(filename);
os.write(bytes);
os.close();
}
public static void saveString(String filename, String text) throws Exception {
saveBytes(filename, text.getBytes("utf-8"));
}
public static byte[] loadBytes(String filename) throws Exception {
InputStream in = FileHelper.fileStream(filename);
byte [] bytes = new byte[in.available()];
in.read(bytes);
in.close();
return bytes;
}
public static String loadString(String filename) throws Exception {
byte[] bytes = loadBytes(filename);
return new String(bytes, "utf-8");
}
public static Properties loadProperties(String filename) throws Exception {
InputStream filestream = null;
try {
filestream = fileStream(filename);
Properties properties = new Properties();
properties.load(filestream);
return properties;
} catch (Exception x) {
throw x;
} finally {
try {
filestream.close();
} catch (Exception x) {
}
}
}
/**
* loads a properties file as a dynmap.
*
* will load the files in cascading order. skipping any that result in null.
*
* returns null on error.
*
* @param filename
* @return
*/
public static DynMap loadPropertiesAsMap(String filename) {
try {
Properties prop = loadProperties(filename);
DynMap rets = new DynMap();
for (String key : prop.stringPropertyNames()) {
rets.put(key, prop.getProperty(key));
}
return rets;
} catch (Exception x) {
// log.info("Caught", x);
}
return null;
}
}
| src/main/com/trendrr/oss/FileHelper.java | /**
*
*/
package com.trendrr.oss;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.io.*;
import java.util.zip.*;
/**
* @author dustin
*
*/
public class FileHelper {
public static boolean LINUX = System.getProperty("os.name").toLowerCase().contains("linux");
public static boolean WINDOWS = System.getProperty("os.name").toLowerCase().contains("windows");
public static boolean MAC = System.getProperty("os.name").toLowerCase().contains("mac");
public static double bytesToGigs(long bytes) {
return bytes / 1073741824l;
}
public static double bytesToMegs(long bytes) {
return bytes / 1048576l;
}
/**
* converts from gigabytes to bytes
* @return
*/
public static long gigsToBytes(int gigs) {
return gigs * 1073741824l;
}
public static long megsToBytes(int megs) {
return megs * 1048576l;
}
/**
* Gets a filestream for the passed in filename.
* will try to get it from within a jar if available.
* else will load relative to cwd.
*
* @param filename
* @return
*/
public static InputStream fileStream(String filename) throws Exception {
filename = toSystemDependantFilename(filename);
//try to load it from the jar.
InputStream stream = ClassLoader.getSystemResourceAsStream(filename);
if (stream == null) {
//else load from the filesystem.
stream = new FileInputStream(filename);
}
return stream;
}
public static String toSystemDependantFilename(String filename) {
return filename.replace('/', File.separatorChar);
}
/**
* zips the file and save as filename +".zip".
*
* returns the filename of the newly created zip
* @param filename
*/
public static String zip(String filename) throws Exception{
int BUFFER = 2048;
String fname = toSystemDependantFilename(filename);
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(fname + ".zip");
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
//out.setMethod(ZipOutputStream.DEFLATED);
byte data[] = new byte[BUFFER];
// get a list of files from current directory
File in = new File(fname);
FileInputStream fi = new FileInputStream(in);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(in.getName());
out.putNextEntry(entry);
int count;
while((count = origin.read(data, 0,
BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
out.close();
return fname + ".zip";
}
/**
* cleans up any illegal characters for windows
* @param filename
* @return
*/
public static String toWindowsFilename(String filename) {
return StringHelper.removeAll(filename, ':', '\"', '|', '<', '>', '?', '*');
}
public static String getAbsoluteFilename(File file) {
return file.getPath();
}
/**
* returns a list of the files within this directory
* @param dir
* @return
* @throws Exception
*/
public static List<File> listDirectory(File dir, boolean recur) throws Exception {
File[] fileList = dir.listFiles();
List<File> files = new ArrayList<File>();
if (fileList == null)
return files;
for (File file : fileList) {
if (file.isDirectory()) {
if (recur) {
files.addAll(listDirectory(file, recur));
}
} else {
files.add(file);
}
}
return files;
}
/**
* same as listDirectory but only returns the simple filename (not complete path).
* @param dir
* @param recure
* @return
* @throws Exception
*/
public static List<String> listFilenames(String directory, boolean recur) throws Exception {
List<File> files = listDirectory(new File(directory), recur);
List<String> filenames = new ArrayList<String>();
for (File file : files) {
String filename = file.getName();
filenames.add(filename);
}
return filenames;
}
/**
* returns filenames within this directory. only returns files, not directories
* @param directory
* @return
* @throws Exception
*/
public static List<String> listDirectory(String directory, boolean recur) throws Exception {
if (directory == null || directory.isEmpty()) {
directory = "./";
}
List<File> files = listDirectory(new File(directory), recur);
List<String> filenames = new ArrayList<String>();
for (File file : files) {
String filename = getAbsoluteFilename(file);
filenames.add(filename);
}
return filenames;
}
/**
* Creates directories if necessarry
* @param filename
*/
public static void createDirectories(String filename) throws Exception {
if (filename.indexOf(File.separator) == -1) {
return;
}
File file = new File(filename.substring(0, filename.lastIndexOf(File.separator)));
if (!file.exists())
file.mkdirs();
}
public static File createNewFile(String filename) throws Exception {
filename = toSystemDependantFilename(filename);
createDirectories(filename);
File file = new File(filename);
file.createNewFile();
return file;
}
public static void saveBytes(String filename, byte[] bytes) throws Exception {
File file = FileHelper.createNewFile(filename);
FileOutputStream os = new FileOutputStream(filename);
os.write(bytes);
os.close();
}
public static void saveString(String filename, String text) throws Exception {
saveBytes(filename, text.getBytes("utf-8"));
}
public static byte[] loadBytes(String filename) throws Exception {
InputStream in = FileHelper.fileStream(filename);
byte [] bytes = new byte[in.available()];
in.read(bytes);
in.close();
return bytes;
}
public static String loadString(String filename) throws Exception {
byte[] bytes = loadBytes(filename);
return new String(bytes, "utf-8");
}
public static Properties loadProperties(String filename) throws Exception {
InputStream filestream = null;
try {
filestream = fileStream(filename);
Properties properties = new Properties();
properties.load(filestream);
return properties;
} catch (Exception x) {
throw x;
} finally {
try {
filestream.close();
} catch (Exception x) {
}
}
}
/**
* loads a properties file as a dynmap.
*
* will load the files in cascading order. skipping any that result in null.
*
* returns null on error.
*
* @param filename
* @return
*/
public static DynMap loadPropertiesAsMap(String filename) {
try {
Properties prop = loadProperties(filename);
DynMap rets = new DynMap();
for (String key : prop.stringPropertyNames()) {
rets.put(key, prop.getProperty(key));
}
return rets;
} catch (Exception x) {
// log.info("Caught", x);
}
return null;
}
}
| unzip method
| src/main/com/trendrr/oss/FileHelper.java | unzip method |
|
Java | mit | 0848d8f621b989062974df5f5384c12ffb891bd1 | 0 | ZherebtsovAlexandr/RealmRxNotifications | package mansonheart.com.realmrxnotifications.presenter;
import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.hannesdorfmann.mosby.mvp.MvpView;
import rx.subscriptions.CompositeSubscription;
/**
* Created by Zherebtsov Alexandr on 08.01.2016.
*/
public abstract class RxBasePresenter<V extends MvpView> extends MvpBasePresenter<V> {
CompositeSubscription compositeSubscription;
protected void unsubscribe() {
if (compositeSubscription != null && !compositeSubscription.isUnsubscribed()) {
compositeSubscription.unsubscribe();
}
compositeSubscription = null;
}
@Override
public void detachView(boolean retainInstance) {
super.detachView(retainInstance);
unsubscribe();
}
}
| app/src/main/java/mansonheart/com/realmrxnotifications/presenter/RxBasePresenter.java | package mansonheart.com.realmrxnotifications.presenter;
import com.hannesdorfmann.mosby.mvp.MvpBasePresenter;
import com.hannesdorfmann.mosby.mvp.MvpView;
import rx.subscriptions.CompositeSubscription;
/**
* Created by Zherebtsov Alexandr on 08.01.2016.
*/
public abstract class RxBasePresenter<V extends MvpView> extends MvpBasePresenter<V> {
CompositeSubscription subscription;
protected void unsubscribe() {
if (subscription != null && !subscription.isUnsubscribed()) {
subscription.unsubscribe();
}
subscription = null;
}
@Override
public void detachView(boolean retainInstance) {
super.detachView(retainInstance);
unsubscribe();
}
}
| Rename
| app/src/main/java/mansonheart/com/realmrxnotifications/presenter/RxBasePresenter.java | Rename |
|
Java | agpl-3.0 | 83c1ff15beb4c1cde5fd832112ddf960ae0420cf | 0 | mnlipp/jgrapes,mnlipp/jgrapes | /*
* JGrapes Event Driven Framework
* Copyright (C) 2016 Michael N. Lipp
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package org.jgrapes.core.internal;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import org.jgrapes.core.Channel;
import org.jgrapes.core.Eligible;
import org.jgrapes.core.Event;
import org.jgrapes.core.EventPipeline;
import org.jgrapes.core.Manager;
/**
* Provides the implementations of methods to class {@link Event} that
* need access to classes or methods that are visible in the implementation
* package only. The class is not intended to be used as base class
* for any other class.
*
* @param <T> the result type of the event. Use {@link Void} if handling
* the event does not produce a result
*/
public abstract class EventBase<T> implements Eligible, Future<T> {
/** The channels that this event is to be fired on if no
* channels are specified explicitly when firing. */
protected Channel[] channels = null;
/** The event that caused this event. */
private EventBase<?> generatedBy = null;
/** Number of events that have to be dispatched until completion.
* This is one for the event itself and one more for each event
* that has this event as its cause. */
private AtomicInteger openCount = new AtomicInteger(0);
/** The event to be fired upon completion. */
private Set<Event<?>> completedEvents = null;
/** Set when the event has been completed. */
private boolean completed = false;
/** Indicates that the event should not processed further. */
private boolean stopped = false;
/** The result of handling the event (if any). */
private AtomicReference<T> result;
/** Context data. */
private Map<Object,Object> contextData = null;
/**
* Returns the channels associated with the event. Before an
* event has been fired, this returns the channels set with
* {@link #setChannels(Channel[])}. After an event has been
* fired, this returns the channels that the event has
* effectively been fired on
* (see {@link Manager#fire(Event, Channel...)}).
*
* @return the channels
*/
public Channel[] channels() {
return channels;
}
/**
* Returns the subset of channels that are assignable to the given type.
*
* @param <C> the given type's class
* @param type the class to look for
* @return the filtered channels
* @see #channels()
*/
@SuppressWarnings("unchecked")
public <C> C[] channels(Class<C> type) {
return Arrays.stream(channels)
.filter(c -> type.isAssignableFrom(c.getClass())).toArray(
size -> (C[])Array.newInstance(type, size));
}
/**
* Execute the given handler for all channels of the given type.
*
* @param <E> the type of the event
* @param <C> the type of the channel
* @param type the channel type
* @param handler the handler
*/
@SuppressWarnings("unchecked")
public <E extends EventBase<?>, C extends Channel> void forChannels(
Class<C> type, BiConsumer<E, C> handler) {
Arrays.stream(channels)
.filter(c -> type.isAssignableFrom(c.getClass()))
.forEach(c -> handler.accept((E)this, (C)c));
}
/**
* Sets the channels that the event is fired on if no channels
* are specified explicitly when firing the event
* (see {@link org.jgrapes.core.Manager#fire(Event, Channel...)}).
*
* @param channels the channels to set
* @return the object for easy chaining
*
* @throws IllegalStateException if the method is called after
* this event has been fired
*/
public Event<T> setChannels(Channel... channels) {
if (enqueued()) {
throw new IllegalStateException(
"Channels cannot be changed after fire");
}
this.channels = channels;
return (Event<T>)this;
}
/**
* Returns <code>true</code> if the event has been enqueued in a pipeline.
*
* @return the result
*/
protected boolean enqueued() {
return openCount.get() > 0;
}
/**
* Sets the result of handling this event.
*
* @param result the result to set
* @return the object for easy chaining
*/
public Event<T> setResult(T result) {
if (this.result == null) {
this.result = new AtomicReference<T>(result);
return (Event<T>)this;
}
this.result.set(result);
return (Event<T>)this;
}
/**
* Allows access to the intermediate result before the
* completion of the event.
*
* @return the intermediate result
*/
protected T result() {
return result == null ? null : result.get();
}
/**
* Tie the result of this event to the result of the other event.
* Changes of either event's results will subsequently be applied
* to both events.
* <P>
* This is useful when an event is replaced by another event during
* handling like:
* {@code fire((new Event()).tieTo(oldEvent.stop()))}
*
* @param other the event to tie to
* @return the object for easy chaining
*/
public Event<T> tieTo(EventBase<T> other) {
if (other.result == null) {
other.result = new AtomicReference<T>(null);
}
result = other.result;
return (Event<T>)this;
}
/**
* Invoked when an exception occurs while invoking a handler for an event.
*
* @param eventProcessor the manager that has invoked the handler
* @param throwable the exception that has been thrown by the handler
*/
protected abstract void handlingError(
EventPipeline eventProcessor, Throwable throwable);
/**
* Can be called during the execution of an event handler to indicate
* that the event should not be processed further. All remaining
* handlers for this event will be skipped.
*
* @return the object for easy chaining
*/
public Event<T> stop() {
stopped = true;
return (Event<T>)this;
}
/**
* Returns <code>true</code> if {@link #stop} has been called.
*
* @return the stopped state
*/
public boolean isStopped() {
return stopped;
}
/**
* If an event is fired while processing another event, note
* the event being processed. This allows us to track the cause
* of events to the "initial" (externally) generated event that
* triggered everything.
*
* @param causingEvent the causing event to set
*/
void generatedBy(EventBase<?> causingEvent) {
openCount.incrementAndGet();
generatedBy = causingEvent;
if (causingEvent != null) {
causingEvent.openCount.incrementAndGet();
}
}
/**
* @param pipeline
*/
void decrementOpen(InternalEventPipeline pipeline) {
if (openCount.decrementAndGet() == 0 && !completed) {
synchronized (this) {
completed = true;
notifyAll();
}
if (completedEvents != null) {
for (Event<?> e: completedEvents) {
Channel[] completeChannels = e.channels();
if (completeChannels == null) {
// Note that channels cannot be null, as it is set
// when firing the event and an event is never fired
// on no channels.
completeChannels = channels;
e.setChannels(completeChannels);
}
pipeline.add(e, completeChannels);
}
}
if (generatedBy != null) {
generatedBy.decrementOpen(pipeline);
}
}
}
/**
* Returns the events to be thrown when this event and all events caused
* by it have been handled.
*
* @return the completed events
*/
@SuppressWarnings("unchecked")
public Set<Event<?>> completedEvents() {
return completedEvents == null ? (Set<Event<?>>)Collections.EMPTY_SET
: Collections.unmodifiableSet(completedEvents);
}
/**
* Adds the event to the events to be thrown when this event and all
* events caused by it have been handled.
*
* @param completedEvent the completedEvent to add
* @return the object for easy chaining
*/
public Event<T> addCompletedEvent(Event<?> completedEvent) {
if (completedEvents == null) {
completedEvents = new HashSet<>();
}
completedEvents.add(completedEvent);
return (Event<T>)this;
}
/**
* Check if this event has been completed.
*
* @return the completed state
*/
@Override
public boolean isDone() {
return completed;
}
/**
* Invoked after all handlers for the event have been executed.
* May be overridden by derived classes to cause some immediate effect
* (instead of e.g. waiting for the completion event). The default
* implementation does nothing. This method is invoked by the event
* handler thread and must not block.
*/
protected void handled() {
}
/**
* The cancel semantics of {@link Future}s do not apply to events.
*
* @param mayInterruptIfRunning ignored
* @return always {@code false} as event processing cannot be cancelled
* @see java.util.concurrent.Future#cancel(boolean)
*/
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
/**
* The cancel semantics of {@link Future}s do not apply to events.
*
* @return always {@code false} as event processing cannot be cancelled
* @see java.util.concurrent.Future#isCancelled()
*/
@Override
public boolean isCancelled() {
return false;
}
/* (non-Javadoc)
* @see java.util.concurrent.Future#get()
*/
@Override
public T get() throws InterruptedException {
while (true) {
synchronized(this) {
if (completed) {
return result == null ? null : result.get();
}
wait();
}
}
}
/**
* Causes the invoking thread to wait until the processing of the
* event has been completed or given timeout has expired.
*
* @see java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit)
*/
@Override
public T get(long timeout, TimeUnit unit)
throws InterruptedException, TimeoutException {
synchronized(this) {
if (completed) {
return result == null ? null : result.get();
}
wait(unit.toMillis(timeout));
}
if (completed) {
return result == null ? null : result.get();
}
throw new TimeoutException();
}
/**
* Establishes a "named" association to an associated object. Note that
* anything that represents an id can be used as value for
* parameter `name`, it does not necessarily have to be a string.
*
* @param by the "name"
* @param with the object to be associated
*/
public void setAssociated(Object by, Object with) {
if (contextData == null) {
contextData = new ConcurrentHashMap<>();
}
contextData.put(by, with);
}
/**
* Retrieves the associated object following the association
* with the given "name".
*
* @param by the name
* @return the associate, if any
*/
public Optional<? extends Object> associated(Object by) {
if (contextData == null) {
return Optional.empty();
}
return Optional.ofNullable(contextData.get(by));
}
}
| org.jgrapes.core/src/org/jgrapes/core/internal/EventBase.java | /*
* JGrapes Event Driven Framework
* Copyright (C) 2016 Michael N. Lipp
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package org.jgrapes.core.internal;
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import org.jgrapes.core.Channel;
import org.jgrapes.core.Eligible;
import org.jgrapes.core.Event;
import org.jgrapes.core.EventPipeline;
import org.jgrapes.core.Manager;
/**
* Provides the implementations of methods to class {@link Event} that
* need access to classes or methods that are visible in the implementation
* package only. The class is not intended to be used as base class
* for any other class.
*
* @param <T> the result type of the event. Use {@link Void} if handling
* the event does not produce a result
*/
public abstract class EventBase<T> implements Eligible, Future<T> {
/** The channels that this event is to be fired on if no
* channels are specified explicitly when firing. */
protected Channel[] channels = null;
/** The event that caused this event. */
private EventBase<?> generatedBy = null;
/** Number of events that have to be dispatched until completion.
* This is one for the event itself and one more for each event
* that has this event as its cause. */
private AtomicInteger openCount = new AtomicInteger(0);
/** The event to be fired upon completion. */
private Set<Event<?>> completedEvents = null;
/** Set when the event has been completed. */
private boolean completed = false;
/** Indicates that the event should not processed further. */
private boolean stopped = false;
/** The result of handling the event (if any). */
private AtomicReference<T> result;
/** Context data. */
private Map<Object,Object> contextData = null;
/**
* Returns the channels associated with the event. Before an
* event has been fired, this returns the channels set with
* {@link #setChannels(Channel[])}. After an event has been
* fired, this returns the channels that the event has
* effectively been fired on
* (see {@link Manager#fire(Event, Channel...)}).
*
* @return the channels
*/
public Channel[] channels() {
return channels;
}
/**
* Returns the subset of channels that are assignable to the given type.
*
* @param <C> the given type's class
* @param type the class to look for
* @return the filtered channels
* @see #channels()
*/
@SuppressWarnings("unchecked")
public <C> C[] channels(Class<C> type) {
return Arrays.stream(channels)
.filter(c -> type.isAssignableFrom(c.getClass())).toArray(
size -> (C[])Array.newInstance(type, size));
}
/**
* Execute the given handler for all channels of the given type.
*
* @param <E> the type of the event
* @param <C> the type of the channel
* @param type the channel type
* @param handler the handler
*/
@SuppressWarnings("unchecked")
public <E extends EventBase<?>, C extends Channel> void forChannels(
Class<C> type, BiConsumer<E, C> handler) {
Arrays.stream(channels)
.filter(c -> type.isAssignableFrom(c.getClass()))
.forEach(c -> handler.accept((E)this, (C)c));
}
/**
* Sets the channels that the event is fired on if no channels
* are specified explicitly when firing the event
* (see {@link org.jgrapes.core.Manager#fire(Event, Channel...)}).
*
* @param channels the channels to set
* @return the object for easy chaining
*
* @throws IllegalStateException if the method is called after
* this event has been fired
*/
public Event<T> setChannels(Channel... channels) {
if (enqueued()) {
throw new IllegalStateException(
"Channels cannot be changed after fire");
}
this.channels = channels;
return (Event<T>)this;
}
/**
* Returns <code>true</code> if the event has been enqueued in a pipeline.
*
* @return the result
*/
protected boolean enqueued() {
return openCount.get() > 0;
}
/**
* Sets the result of handling this event.
*
* @param result the result to set
* @return the object for easy chaining
*/
public Event<T> setResult(T result) {
if (this.result == null) {
this.result = new AtomicReference<T>(result);
return (Event<T>)this;
}
this.result.set(result);
return (Event<T>)this;
}
/**
* Allows access to the intermediate result before the
* completion of the event.
*
* @return the intermediate result
*/
protected T result() {
return result == null ? null : result.get();
}
/**
* Tie the result of this event to the result of the other event.
* Changes of either event's results will subsequently be applied
* to both events.
* <P>
* This is useful when an event is replaced by another event during
* handling like:
* {@code fire((new Event()).tieTo(oldEvent.stop()))}
*
* @param other the event to tie to
* @return the object for easy chaining
*/
public Event<T> tieTo(EventBase<T> other) {
if (other.result == null) {
other.result = new AtomicReference<T>(null);
}
result = other.result;
return (Event<T>)this;
}
/**
* Invoked when an exception occurs while invoking a handler for an event.
*
* @param eventProcessor the manager that has invoked the handler
* @param throwable the exception that has been thrown by the handler
*/
protected abstract void handlingError(
EventPipeline eventProcessor, Throwable throwable);
/**
* Can be called during the execution of an event handler to indicate
* that the event should not be processed further. All remaining
* handlers for this event will be skipped.
*
* @return the object for easy chaining
*/
public Event<T> stop() {
stopped = true;
return (Event<T>)this;
}
/**
* Returns <code>true</code> if {@link stop} has been called.
*
* @return the stopped state
*/
public boolean isStopped() {
return stopped;
}
/**
* If an event is fired while processing another event, note
* the event being processed. This allows us to track the cause
* of events to the "initial" (externally) generated event that
* triggered everything.
*
* @param causingEvent the causing event to set
*/
void generatedBy(EventBase<?> causingEvent) {
openCount.incrementAndGet();
generatedBy = causingEvent;
if (causingEvent != null) {
causingEvent.openCount.incrementAndGet();
}
}
/**
* @param pipeline
*/
void decrementOpen(InternalEventPipeline pipeline) {
if (openCount.decrementAndGet() == 0 && !completed) {
synchronized (this) {
completed = true;
notifyAll();
}
if (completedEvents != null) {
for (Event<?> e: completedEvents) {
Channel[] completeChannels = e.channels();
if (completeChannels == null) {
// Note that channels cannot be null, as it is set
// when firing the event and an event is never fired
// on no channels.
completeChannels = channels;
e.setChannels(completeChannels);
}
pipeline.add(e, completeChannels);
}
}
if (generatedBy != null) {
generatedBy.decrementOpen(pipeline);
}
}
}
/**
* Returns the events to be thrown when this event and all events caused
* by it have been handled.
*
* @return the completed events
*/
@SuppressWarnings("unchecked")
public Set<Event<?>> completedEvents() {
return completedEvents == null ? (Set<Event<?>>)Collections.EMPTY_SET
: Collections.unmodifiableSet(completedEvents);
}
/**
* Adds the event to the events to be thrown when this event and all
* events caused by it have been handled.
*
* @param completedEvent the completedEvent to add
* @return the object for easy chaining
*/
public Event<T> addCompletedEvent(Event<?> completedEvent) {
if (completedEvents == null) {
completedEvents = new HashSet<>();
}
completedEvents.add(completedEvent);
return (Event<T>)this;
}
/**
* Check if this event has been completed.
*
* @return the completed state
*/
@Override
public boolean isDone() {
return completed;
}
/**
* Invoked after all handlers for the event have been executed.
* May be overridden by derived classes to cause some immediate effect
* (instead of e.g. waiting for the completion event). The default
* implementation does nothing. This method is invoked by the event
* handler thread and must not block.
*/
protected void handled() {
}
/**
* The cancel semantics of {@link Future}s do not apply to events.
*
* @param mayInterruptIfRunning ignored
* @return always {@code false} as event processing cannot be cancelled
* @see java.util.concurrent.Future#cancel(boolean)
*/
@Override
public boolean cancel(boolean mayInterruptIfRunning) {
return false;
}
/**
* The cancel semantics of {@link Future}s do not apply to events.
*
* @return always {@code false} as event processing cannot be cancelled
* @see java.util.concurrent.Future#isCancelled()
*/
@Override
public boolean isCancelled() {
return false;
}
/* (non-Javadoc)
* @see java.util.concurrent.Future#get()
*/
@Override
public T get() throws InterruptedException {
while (true) {
synchronized(this) {
if (completed) {
return result == null ? null : result.get();
}
wait();
}
}
}
/**
* Causes the invoking thread to wait until the processing of the
* event has been completed or given timeout has expired.
*
* @see java.util.concurrent.Future#get(long, java.util.concurrent.TimeUnit)
*/
@Override
public T get(long timeout, TimeUnit unit)
throws InterruptedException, TimeoutException {
synchronized(this) {
if (completed) {
return result == null ? null : result.get();
}
wait(unit.toMillis(timeout));
}
if (completed) {
return result == null ? null : result.get();
}
throw new TimeoutException();
}
/**
* Establishes a "named" association to an associated object. Note that
* anything that represents an id can be used as value for
* parameter `name`, it does not necessarily have to be a string.
*
* @param by the "name"
* @param with the object to be associated
*/
public void setAssociated(Object by, Object with) {
if (contextData == null) {
contextData = new ConcurrentHashMap<>();
}
contextData.put(by, with);
}
/**
* Retrieves the associated object following the association
* with the given "name".
*
* @param by the name
* @return the associate, if any
*/
public Optional<? extends Object> associated(Object by) {
if (contextData == null) {
return Optional.empty();
}
return Optional.ofNullable(contextData.get(by));
}
}
| Javadoc fix. | org.jgrapes.core/src/org/jgrapes/core/internal/EventBase.java | Javadoc fix. |
|
Java | agpl-3.0 | 2fe3adffdf162e1df06cc7feb978e205731da549 | 0 | caiyingyuan/tigase-utils-71,caiyingyuan/tigase-utils-71 | /*
* Tigase Jabber/XMPP Server
* Copyright (C) 2004-2008 "Artur Hefczyc" <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. Look for COPYING file in the top folder.
* If not, see http://www.gnu.org/licenses/.
*
* $Rev$
* Last modified by $Author$
* $Date$
*/
package tigase.util;
//~--- JDK imports ------------------------------------------------------------
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
//~--- classes ----------------------------------------------------------------
/**
* This is a warpper for java.util.zip package and Deflater/Inflater classes
* specifically. This implementation allows for easy interaction between
* Deflater/Inflater and java.nio API which operates on ByteBuffer data.
* It also does some tricky stuff to flush Deflater without reseting it and allow
* a better compression ration on the data. <p/>
* There are a few convenience methods allowing to directly compress String to
* ByteBuffer and other way around - from ByteBuffer to String decompression.
* For these methods data are assumed to be UTF-8 character String.<p/>
*
* Created: Jul 30, 2009 11:46:55 AM
*
* @author <a href="mailto:[email protected]">Artur Hefczyc</a>
* @version $Rev$
*/
public class ZLibWrapper {
/**
* Variable <code>log</code> is a class logger.
*/
private static Logger log = Logger.getLogger(ZLibWrapper.class.getName());
/** Field description */
public static final int COMPRESSED_BUFF_SIZE = 512;
/** Field description */
public static final int DECOMPRESSED_BUFF_SIZE = 10 * COMPRESSED_BUFF_SIZE;
private static final byte[] EMPTYBYTEARRAY = new byte[0];
//~--- fields ---------------------------------------------------------------
private float average_compression_rate = 0f;
private float average_decompression_rate = 0f;
private byte[] compress_input = null;
private byte[] compress_output = null;
private Deflater compresser = null;
private byte[] decompress_input = null;
private byte[] decompress_output = null;
private Inflater decompresser = null;
private CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
private int decompressed_buff_size = DECOMPRESSED_BUFF_SIZE;
private CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
private int compression_level = Deflater.BEST_COMPRESSION;
private int compressed_buff_size = COMPRESSED_BUFF_SIZE;
private float last_compression_rate = 0f;
private float last_decompression_rate = 0f;
//~--- constructors ---------------------------------------------------------
/**
* Constructs ...
*
*/
public ZLibWrapper() {
this(Deflater.BEST_COMPRESSION, COMPRESSED_BUFF_SIZE);
}
/**
* Constructs ...
*
*
* @param level
*/
public ZLibWrapper(int level) {
this(level, COMPRESSED_BUFF_SIZE);
}
/**
* Constructs ...
*
*
* @param level
* @param comp_buff_size
*/
public ZLibWrapper(int level, int comp_buff_size) {
this.compression_level = level;
this.compressed_buff_size = comp_buff_size;
this.decompressed_buff_size = 10 * comp_buff_size;
this.compresser = new Deflater(compression_level, false);
this.decompresser = new Inflater(false);
compress_output = new byte[compressed_buff_size];
compress_input = new byte[decompressed_buff_size];
decompress_output = new byte[decompressed_buff_size];
decompress_input = new byte[compressed_buff_size];
}
//~--- methods --------------------------------------------------------------
/**
* Method description
*
*
* @param args
*
* @throws Exception
*/
public static void main(String[] args) throws Exception {
ZLibWrapper zlib = new ZLibWrapper(Deflater.BEST_COMPRESSION);
String[] inputs = {
"Stream compression implementation for The Tigase XMPP Server.",
"Stream compression implementation for The Tigase XMPP Server.",
"<message to='[email protected]' from='[email protected]'>" + "<thread>abcd</thread>"
+ "<subject>some subject</subject>" + "<body>This is a message body</body>"
+ "</message>",
"<presence to='[email protected]' from='[email protected]'>"
+ "<status>away</status>" + "<show>I am away</show>" + "</presence>",
"<message to='[email protected]' from='[email protected]'>" + "<thread>abcd</thread>"
+ "<subject>Another subject</subject>"
+ "<body>This is a message body sent to as</body>" + "</message>",
"<presence to='[email protected]' from='[email protected]'>" + "<status>dnd</status>"
+ "<show>I am working really hard</show>" + "</presence>",
"<message to='[email protected]' from='[email protected]'>" + "<thread>abcd</thread>"
+ "<subject>Christmass presents</subject>"
+ "<body>We need to have a chat about Christmas presents.</body>" + "</message>",
"<presence to='[email protected]' from='[email protected]'>"
+ "<status>away</status>" + "<show>I am away</show>" + "</presence>",
};
for (String input : inputs) {
System.out.println("INPUT[" + input.length() + "]: \n" + input);
ByteBuffer compressedBuffer = zlib.compress(input);
System.out.println(" CREATED, compressedBuffer capacity: "
+ compressedBuffer.capacity() + ", remaining: " + compressedBuffer.remaining()
+ ", position: " + compressedBuffer.position() + ", limit: "
+ compressedBuffer.limit());
// ByteBuffer decompressedBuffer = zlib.decompress(compressedBuffer);
// System.out.println(
// " decompressedBuffer capacity: " + decompressedBuffer.capacity() +
// ", remaining: " + decompressedBuffer.remaining() +
// ", position: " + decompressedBuffer.position() +
// ", limit: " + decompressedBuffer.limit());
// System.out.println(
// " AFTER DECOMP, compressedBuffer capacity: " + compressedBuffer.
// capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
// compressedBuffer.rewind();
// System.out.println(
// " REWIND, compressedBuffer capacity: " +
// compressedBuffer.capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
String output = zlib.decompressToString(compressedBuffer);
System.out.println("OUTPUT[" + output.length() + "]: \n" + output);
}
System.out.println("Compression rate: " + zlib.lastCompressionRate());
String inputstr = "";
for (String input : inputs) {
inputstr += input;
}
System.out.println("INPUT[" + inputstr.length() + "]: \n" + inputstr);
ByteBuffer compressedBuffer = zlib.compress(inputstr);
System.out.println(" CREATED, compressedBuffer capacity: " + compressedBuffer.capacity()
+ ", remaining: " + compressedBuffer.remaining() + ", position: "
+ compressedBuffer.position() + ", limit: " + compressedBuffer.limit());
// ByteBuffer decompressedBuffer = zlib.decompress(compressedBuffer);
// System.out.println(
// " decompressedBuffer capacity: " + decompressedBuffer.capacity() +
// ", remaining: " + decompressedBuffer.remaining() +
// ", position: " + decompressedBuffer.position() +
// ", limit: " + decompressedBuffer.limit());
// System.out.println(
// " AFTER DECOMP, compressedBuffer capacity: " + compressedBuffer.
// capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
// compressedBuffer.rewind();
// System.out.println(
// " REWIND, compressedBuffer capacity: " +
// compressedBuffer.capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
String output = zlib.decompressToString(compressedBuffer);
System.out.println("OUTPUT[" + output.length() + "]: \n" + output);
System.out.println("Compression rate: " + zlib.lastCompressionRate());
char[] chars = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'R', 'S', 'T', 'U', 'W', 'X', 'Y', 'Z'
};
StringBuilder sb = new StringBuilder();
for (char c : chars) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 100; j++) {
sb.append(c);
}
sb.append('\n');
}
}
String input = sb.toString();
System.out.println("INPUT[" + input.length() + "]: \n");
compressedBuffer = zlib.compress(input);
System.out.println(" CREATED, compressedBuffer capacity: " + compressedBuffer.capacity()
+ ", remaining: " + compressedBuffer.remaining() + ", position: "
+ compressedBuffer.position() + ", limit: " + compressedBuffer.limit());
// decompressedBuffer = zlib.decompress(compressedBuffer);
// System.out.println(
// " decompressedBuffer capacity: " + decompressedBuffer.capacity() +
// ", remaining: " + decompressedBuffer.remaining() +
// ", position: " + decompressedBuffer.position() +
// ", limit: " + decompressedBuffer.limit());
// System.out.println(
// " AFTER DECOMP, compressedBuffer capacity: " + compressedBuffer.
// capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
// compressedBuffer.rewind();
// System.out.println(
// " REWIND, compressedBuffer capacity: " + compressedBuffer.capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
output = zlib.decompressToString(compressedBuffer);
System.out.println("OUTPUT[" + output.length() + "]: \n");
System.out.println("Compression rate: " + zlib.lastCompressionRate());
compressedBuffer = zlib.compress(input);
System.out.println(" CREATED, compressedBuffer capacity: " + compressedBuffer.capacity()
+ ", remaining: " + compressedBuffer.remaining() + ", position: "
+ compressedBuffer.position() + ", limit: " + compressedBuffer.limit());
// decompressedBuffer = zlib.decompress(compressedBuffer);
// System.out.println(
// " decompressedBuffer capacity: " + decompressedBuffer.capacity() +
// ", remaining: " + decompressedBuffer.remaining() +
// ", position: " + decompressedBuffer.position() +
// ", limit: " + decompressedBuffer.limit());
// System.out.println(
// " AFTER DECOMP, compressedBuffer capacity: " + compressedBuffer.
// capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
// compressedBuffer.rewind();
// System.out.println(
// " REWIND, compressedBuffer capacity: " + compressedBuffer.capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
output = zlib.decompressToString(compressedBuffer);
System.out.println("OUTPUT[" + output.length() + "]: \n");
System.out.println("Compression rate: " + zlib.lastCompressionRate());
}
/**
* Method description
*
*
* @return
*/
public float averageCompressionRate() {
return average_compression_rate;
}
/**
* Method description
*
*
* @return
*/
public float averageDecompressionRate() {
return average_decompression_rate;
}
/**
*
* @param input
* @return
*/
public ByteBuffer compress(ByteBuffer input) {
// Arrays where all compressed bytes are saved.
byte[] result_arr = null;
// This is saved for compression rate calculation only
float before = input.remaining();
// Repeat compression procedure until the input buffer is empty
while (input.hasRemaining()) {
// ByteBuffer doesn't like calls with requested data size bigger than
// either remaining bytes in the buffer or input array size
int size = Math.min(compress_input.length, input.remaining());
input.get(compress_input, 0, size);
// From the Deflater source code it looks like each setInput() call
// overwrites previous data, so we have to run compression on each
// buffer separately.
compresser.setInput(compress_input, 0, size);
// Finish data preparation (from the Deflater source code it looks like
// this is really dummy call doing pretty much nothing)
// compresser.finish();
// While there are still data waiting for compression
while ( !compresser.needsInput()) {
result_arr = deflate(result_arr);
}
// We don't want to reset or finish the compresser to not loss the real
// compression benefits. Deflater however does not offer flushing so this
// is a workaround from:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4206909
// We force Deflater to flush by switching compression level
compresser.setInput(EMPTYBYTEARRAY, 0, 0);
compresser.setLevel(Deflater.NO_COMPRESSION);
result_arr = deflate(result_arr);
compresser.setLevel(compression_level);
// I am not really sure if this last call is needed, TODO: test it and remove it
// result_arr = deflate(result_arr);
}
// If the compressed_output array is smaller assign result to the output
// to make sure the next time there is enough space in the output array
// to limit memory allocation calls
if (result_arr.length > compress_output.length) {
compress_output = result_arr;
if (log.isLoggable(Level.FINEST)) {
log.finest("Increasing compress_output size to: " + compress_output.length);
}
}
// Calculate compression rate for statistics collection
last_compression_rate = (before - result_arr.length) / before;
average_compression_rate = (average_compression_rate + last_compression_rate) / 2;
// Create resulting buffer.
ByteBuffer result = ByteBuffer.wrap(result_arr);
return result;
}
/**
* Method description
*
*
* @param input
*
* @return
*
* @throws CharacterCodingException
*/
public ByteBuffer compress(String input) throws CharacterCodingException {
encoder.reset();
ByteBuffer dataBuffer = encoder.encode(CharBuffer.wrap(input));
encoder.flush(dataBuffer);
ByteBuffer compressedBuffer = compress(dataBuffer);
return compressedBuffer;
}
/**
* Method description
*
*
* @param input
*
* @return
*/
public ByteBuffer decompress(ByteBuffer input) {
// Arrays where decompressed bytes are stored
byte[] result_arr = null;
// this is saved for decompression rate calculation only
// Please note since compression and decompression are independent network
// streams the compression rate might be very different, interesting thing
// to investigate
float before = input.remaining();
// Repeat until the input buffer is empty
while (input.hasRemaining()) {
// ByteBuffer doesn't like calls with requested data size bigger than
// either remaining bytes in the buffer or input array size
int size = Math.min(decompress_input.length, input.remaining());
input.get(decompress_input, 0, size);
// From the Inflater source code it looks like each setInput() call
// overwrites previous data, so we have to run decompression on each
// buffer separately.
decompresser.setInput(decompress_input, 0, size);
int decompressed_size = 1;
// Normally we get much more decompressed data than input data and
// on a few first calls we can have more decompressed data than the output
// buffer size. In time the output buffer will adjust itself but initially we
// can expect a few calls in this loop before we get all data
while ( !decompresser.needsInput() || (decompressed_size > 0)) {
try {
decompressed_size = decompresser.inflate(decompress_output, 0,
decompress_output.length);
// We might get 0 decompressed_size in case not all data are ready yet
// probably more data are needed from the network
if (decompressed_size > 0) {
// Copy decompressed data to result array
if (result_arr == null) {
// On the first call just copy the array - data in the source array
// will be overwritten on the next call
result_arr = Arrays.copyOf(decompress_output, decompressed_size);
} else {
// If the method is called many times for a single input buffer
// we may need to resize the output array, in time however the
// output array size should automaticaly adjust to the data and
// resizing array should not be needed then
int old_size = result_arr.length;
result_arr = Arrays.copyOf(result_arr, old_size + decompressed_size);
System.arraycopy(decompress_output, 0, result_arr, old_size, decompressed_size);
}
}
} catch (DataFormatException ex) {
log.log(Level.INFO, "Stream decompression error: ", ex);
decompresser.reset();
}
}
}
ByteBuffer result = null;
// It may happen there is not enough data to decode full buffer, we return null
// in such a case and try next time
if (result_arr != null) {
// If the decompressed_output array is smaller assign result to the output
// to make sure the next time there is enough space in the output array
// to limit memory allocation calls
if (result_arr.length > decompress_output.length) {
decompress_output = result_arr;
if (log.isLoggable(Level.FINEST)) {
log.finest("Increasing compress_output size to: " + compress_output.length);
}
}
// Calculate decompression rate for statistics collection
last_decompression_rate = (result_arr.length - before) / result_arr.length;
average_decompression_rate = (average_decompression_rate + last_decompression_rate) / 2;
// Create resulting buffer.
result = ByteBuffer.wrap(result_arr);
}
return result;
}
/**
* Method description
*
*
* @param input
*
* @return
*
* @throws CharacterCodingException
*/
public String decompressToString(ByteBuffer input) throws CharacterCodingException {
ByteBuffer decompressed_buff = decompress(input);
CharBuffer cb = decoder.decode(decompressed_buff);
String output = new String(cb.array());
return output;
}
/**
* Method description
*
*/
public void end() {
this.compresser.end();
this.decompresser.end();
this.compress_output = null;
this.compress_input = null;
this.decompress_output = null;
this.decompress_input = null;
}
/**
* Method description
*
*
* @return
*/
public float lastCompressionRate() {
return last_compression_rate;
}
/**
* Method description
*
*
* @return
*/
public float lastDecompressionRate() {
return last_decompression_rate;
}
private byte[] deflate(byte[] input_arr) {
byte[] result_arr = input_arr;
// Compress data and take number of bytes ready
int compressed_size = compresser.deflate(compress_output, 0, compress_output.length);
// Beware, we can get 0 compressed_size quite frequently as the zlib
// library buffers data for a better compression ratio
if (compressed_size > 0) {
// Copy compressed data to result array
if (result_arr == null) {
// On the first call just copy the array - data in the source array
// will be overwritten on the next call
result_arr = Arrays.copyOf(compress_output, compressed_size);
} else {
// If the method is called many times for a single input buffer
// we may need to resize the output array, in time however the
// output array size should automaticaly adjust to the data and
// resizing array should not be needed then
int old_size = result_arr.length;
result_arr = Arrays.copyOf(result_arr, old_size + compressed_size);
System.arraycopy(compress_output, 0, result_arr, old_size, compressed_size);
}
}
return result_arr;
}
}
//~ Formatted in Sun Code Convention
//~ Formatted by Jindent --- http://www.jindent.com
| src/main/java/tigase/util/ZLibWrapper.java | /*
* Tigase Jabber/XMPP Server
* Copyright (C) 2004-2008 "Artur Hefczyc" <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. Look for COPYING file in the top folder.
* If not, see http://www.gnu.org/licenses/.
*
* $Rev$
* Last modified by $Author$
* $Date$
*/
package tigase.util;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
/**
* This is a warpper for java.util.zip package and Deflater/Inflater classes
* specifically. This implementation allows for easy interaction between
* Deflater/Inflater and java.nio API which operates on ByteBuffer data.
* It also does some tricky stuff to flush Deflater without reseting it and allow
* a better compression ration on the data. <p/>
* There are a few convenience methods allowing to directly compress String to
* ByteBuffer and other way around - from ByteBuffer to String decompression.
* For these methods data are assumed to be UTF-8 character String.<p/>
*
* Created: Jul 30, 2009 11:46:55 AM
*
* @author <a href="mailto:[email protected]">Artur Hefczyc</a>
* @version $Rev$
*/
public class ZLibWrapper {
/**
* Variable <code>log</code> is a class logger.
*/
private static Logger log = Logger.getLogger(ZLibWrapper.class.getName());
public static final int COMPRESSED_BUFF_SIZE = 512;
public static final int DECOMPRESSED_BUFF_SIZE = 10*COMPRESSED_BUFF_SIZE;
private static final byte[] EMPTYBYTEARRAY = new byte[0];
private CharsetEncoder encoder = Charset.forName("UTF-8").newEncoder();
private CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
private int compressed_buff_size = COMPRESSED_BUFF_SIZE;
private int decompressed_buff_size = DECOMPRESSED_BUFF_SIZE;
private int compression_level = Deflater.BEST_COMPRESSION;
private Deflater compresser = null;
private byte[] compress_output = null;
private byte[] compress_input = null;
private Inflater decompresser = null;
private byte[] decompress_output = null;
private byte[] decompress_input = null;
private float average_compression_rate = 0f;
private float average_decompression_rate = 0f;
private float last_compression_rate = 0f;
private float last_decompression_rate = 0f;
public ZLibWrapper(int level, int comp_buff_size) {
this.compression_level = level;
this.compressed_buff_size = comp_buff_size;
this.decompressed_buff_size = 10 * comp_buff_size;
this.compresser = new Deflater(compression_level, false);
this.decompresser = new Inflater(false);
compress_output = new byte[compressed_buff_size];
compress_input = new byte[decompressed_buff_size];
decompress_output = new byte[decompressed_buff_size];
decompress_input = new byte[compressed_buff_size];
}
public ZLibWrapper(int level) {
this(level, COMPRESSED_BUFF_SIZE);
}
public ZLibWrapper() {
this(Deflater.BEST_COMPRESSION, COMPRESSED_BUFF_SIZE);
}
public void end() {
this.compresser.end();
this.decompresser.end();
this.compress_output = null;
this.compress_input = null;
this.decompress_output = null;
this.decompress_input = null;
}
public float averageCompressionRate() {
return average_compression_rate;
}
public float averageDecompressionRate() {
return average_decompression_rate;
}
public float lastCompressionRate() {
return last_compression_rate;
}
public float lastDecompressionRate() {
return last_decompression_rate;
}
private byte[] deflate(byte[] input_arr) {
byte[] result_arr = input_arr;
// Compress data and take number of bytes ready
int compressed_size = compresser.deflate(compress_output, 0,
compress_output.length);
// Beware, we can get 0 compressed_size quite frequently as the zlib
// library buffers data for a better compression ratio
if (compressed_size > 0) {
// Copy compressed data to result array
if (result_arr == null) {
// On the first call just copy the array - data in the source array
// will be overwritten on the next call
result_arr = Arrays.copyOf(compress_output, compressed_size);
} else {
// If the method is called many times for a single input buffer
// we may need to resize the output array, in time however the
// output array size should automaticaly adjust to the data and
// resizing array should not be needed then
int old_size = result_arr.length;
result_arr = Arrays.copyOf(result_arr, old_size + compressed_size);
System.arraycopy(compress_output, 0, result_arr, old_size,
compressed_size);
}
}
return result_arr;
}
/**
*
* @param input
* @return
*/
public ByteBuffer compress(ByteBuffer input) {
// Arrays where all compressed bytes are saved.
byte[] result_arr = null;
// This is saved for compression rate calculation only
float before = input.remaining();
// Repeat compression procedure until the input buffer is empty
while (input.hasRemaining()) {
// ByteBuffer doesn't like calls with requested data size bigger than
// either remaining bytes in the buffer or input array size
int size = Math.min(compress_input.length, input.remaining());
input.get(compress_input, 0, size);
// From the Deflater source code it looks like each setInput() call
// overwrites previous data, so we have to run compression on each
// buffer separately.
compresser.setInput(compress_input, 0, size);
// Finish data preparation (from the Deflater source code it looks like
// this is really dummy call doing pretty much nothing)
//compresser.finish();
// While there are still data waiting for compression
while (!compresser.needsInput()) {
result_arr = deflate(result_arr);
}
}
// We don't want to reset or finish the compresser to not loss the real
// compression benefits. Deflater however does not offer flushing so this
// is a workaround from:
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4206909
// We force Deflater to flush by switching compression level
compresser.setInput(EMPTYBYTEARRAY, 0, 0);
compresser.setLevel(Deflater.NO_COMPRESSION);
result_arr = deflate(result_arr);
compresser.setLevel(compression_level);
// I am not really sure if this last call is needed, TODO: test it and remove it
result_arr = deflate(result_arr);
// If the compressed_output array is smaller assign result to the output
// to make sure the next time there is enough space in the output array
// to limit memory allocation calls
if (result_arr.length > compress_output.length) {
compress_output = result_arr;
if (log.isLoggable(Level.FINEST)) {
log.finest("Increasing compress_output size to: " +
compress_output.length);
}
}
// Calculate compression rate for statistics collection
last_compression_rate = (before - result_arr.length) / before;
average_compression_rate = (average_compression_rate + last_compression_rate) / 2;
// Create resulting buffer.
ByteBuffer result = ByteBuffer.wrap(result_arr);
return result;
}
public ByteBuffer decompress(ByteBuffer input) {
// Arrays where decompressed bytes are stored
byte[] result_arr = null;
// this is saved for decompression rate calculation only
// Please note since compression and decompression are independent network
// streams the compression rate might be very different, interesting thing
// to investigate
float before = input.remaining();
// Repeat until the input buffer is empty
while (input.hasRemaining()) {
// ByteBuffer doesn't like calls with requested data size bigger than
// either remaining bytes in the buffer or input array size
int size = Math.min(decompress_input.length, input.remaining());
input.get(decompress_input, 0, size);
// From the Inflater source code it looks like each setInput() call
// overwrites previous data, so we have to run decompression on each
// buffer separately.
decompresser.setInput(decompress_input, 0, size);
int decompressed_size = 1;
// Normally we get much more decompressed data than input data and
// on a few first calls we can have more decompressed data than the output
// buffer size. In time the output buffer will adjust itself but initially we
// can expect a few calls in this loop before we get all data
while (!decompresser.needsInput() || decompressed_size > 0) {
try {
decompressed_size =
decompresser.inflate(decompress_output, 0,
decompress_output.length);
// We might get 0 decompressed_size in case not all data are ready yet
// probably more data are needed from the network
if (decompressed_size > 0) {
// Copy decompressed data to result array
if (result_arr == null) {
// On the first call just copy the array - data in the source array
// will be overwritten on the next call
result_arr = Arrays.copyOf(decompress_output, decompressed_size);
} else {
// If the method is called many times for a single input buffer
// we may need to resize the output array, in time however the
// output array size should automaticaly adjust to the data and
// resizing array should not be needed then
int old_size = result_arr.length;
result_arr = Arrays.copyOf(result_arr, old_size +
decompressed_size);
System.arraycopy(decompress_output, 0, result_arr, old_size,
decompressed_size);
}
}
} catch (DataFormatException ex) {
log.log(Level.INFO, "Stream decompression error: ", ex);
decompresser.reset();
}
}
}
ByteBuffer result = null;
// It may happen there is not enough data to decode full buffer, we return null
// in such a case and try next time
if (result_arr != null) {
// If the decompressed_output array is smaller assign result to the output
// to make sure the next time there is enough space in the output array
// to limit memory allocation calls
if (result_arr.length > decompress_output.length) {
decompress_output = result_arr;
if (log.isLoggable(Level.FINEST)) {
log.finest("Increasing compress_output size to: " +
compress_output.length);
}
}
// Calculate decompression rate for statistics collection
last_decompression_rate = (result_arr.length - before) / result_arr.length;
average_decompression_rate = (average_decompression_rate +
last_decompression_rate) / 2;
// Create resulting buffer.
result = ByteBuffer.wrap(result_arr);
}
return result;
}
public ByteBuffer compress(String input) throws CharacterCodingException {
encoder.reset();
ByteBuffer dataBuffer = encoder.encode(CharBuffer.wrap(input));
encoder.flush(dataBuffer);
ByteBuffer compressedBuffer = compress(dataBuffer);
return compressedBuffer;
}
public String decompressToString(ByteBuffer input) throws CharacterCodingException {
ByteBuffer decompressed_buff = decompress(input);
CharBuffer cb = decoder.decode(decompressed_buff);
String output = new String(cb.array());
return output;
}
public static void main(String[] args) throws Exception {
ZLibWrapper zlib = new ZLibWrapper(Deflater.BEST_COMPRESSION);
String[] inputs = {
"Stream compression implementation for The Tigase XMPP Server.",
"Stream compression implementation for The Tigase XMPP Server.",
"<message to='[email protected]' from='[email protected]'>" +
"<thread>abcd</thread>" +
"<subject>some subject</subject>" +
"<body>This is a message body</body>" +
"</message>",
"<presence to='[email protected]' from='[email protected]'>" +
"<status>away</status>" +
"<show>I am away</show>" +
"</presence>",
"<message to='[email protected]' from='[email protected]'>" +
"<thread>abcd</thread>" +
"<subject>Another subject</subject>" +
"<body>This is a message body sent to as</body>" +
"</message>",
"<presence to='[email protected]' from='[email protected]'>" +
"<status>dnd</status>" +
"<show>I am working really hard</show>" +
"</presence>",
"<message to='[email protected]' from='[email protected]'>" +
"<thread>abcd</thread>" +
"<subject>Christmass presents</subject>" +
"<body>We need to have a chat about Christmas presents.</body>" +
"</message>",
"<presence to='[email protected]' from='[email protected]'>" +
"<status>away</status>" +
"<show>I am away</show>" +
"</presence>",
};
for (String input : inputs) {
System.out.println("INPUT[" + input.length() + "]: \n" + input);
ByteBuffer compressedBuffer = zlib.compress(input);
System.out.println(
" CREATED, compressedBuffer capacity: " +
compressedBuffer.capacity() +
", remaining: " + compressedBuffer.remaining() +
", position: " + compressedBuffer.position() +
", limit: " + compressedBuffer.limit());
// ByteBuffer decompressedBuffer = zlib.decompress(compressedBuffer);
// System.out.println(
// " decompressedBuffer capacity: " + decompressedBuffer.capacity() +
// ", remaining: " + decompressedBuffer.remaining() +
// ", position: " + decompressedBuffer.position() +
// ", limit: " + decompressedBuffer.limit());
// System.out.println(
// " AFTER DECOMP, compressedBuffer capacity: " + compressedBuffer.
// capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
// compressedBuffer.rewind();
// System.out.println(
// " REWIND, compressedBuffer capacity: " +
// compressedBuffer.capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
String output = zlib.decompressToString(compressedBuffer);
System.out.println("OUTPUT[" + output.length() + "]: \n" + output);
}
System.out.println("Compression rate: " + zlib.lastCompressionRate());
String inputstr = "";
for (String input : inputs) {
inputstr += input;
}
System.out.println("INPUT[" + inputstr.length() + "]: \n" + inputstr);
ByteBuffer compressedBuffer = zlib.compress(inputstr);
System.out.println(
" CREATED, compressedBuffer capacity: " +
compressedBuffer.capacity() +
", remaining: " + compressedBuffer.remaining() +
", position: " + compressedBuffer.position() +
", limit: " + compressedBuffer.limit());
// ByteBuffer decompressedBuffer = zlib.decompress(compressedBuffer);
// System.out.println(
// " decompressedBuffer capacity: " + decompressedBuffer.capacity() +
// ", remaining: " + decompressedBuffer.remaining() +
// ", position: " + decompressedBuffer.position() +
// ", limit: " + decompressedBuffer.limit());
// System.out.println(
// " AFTER DECOMP, compressedBuffer capacity: " + compressedBuffer.
// capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
// compressedBuffer.rewind();
// System.out.println(
// " REWIND, compressedBuffer capacity: " +
// compressedBuffer.capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
String output = zlib.decompressToString(compressedBuffer);
System.out.println("OUTPUT[" + output.length() + "]: \n" + output);
System.out.println("Compression rate: " + zlib.lastCompressionRate());
char[] chars = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
'P', 'R', 'S', 'T',
'U', 'W', 'X', 'Y', 'Z'};
StringBuilder sb = new StringBuilder();
for (char c : chars) {
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 100; j++) {
sb.append(c);
}
sb.append('\n');
}
}
String input = sb.toString();
System.out.println("INPUT[" + input.length() + "]: \n");
compressedBuffer = zlib.compress(input);
System.out.println(
" CREATED, compressedBuffer capacity: " + compressedBuffer.capacity() +
", remaining: " + compressedBuffer.remaining() +
", position: " + compressedBuffer.position() +
", limit: " + compressedBuffer.limit());
// decompressedBuffer = zlib.decompress(compressedBuffer);
// System.out.println(
// " decompressedBuffer capacity: " + decompressedBuffer.capacity() +
// ", remaining: " + decompressedBuffer.remaining() +
// ", position: " + decompressedBuffer.position() +
// ", limit: " + decompressedBuffer.limit());
// System.out.println(
// " AFTER DECOMP, compressedBuffer capacity: " + compressedBuffer.
// capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
// compressedBuffer.rewind();
// System.out.println(
// " REWIND, compressedBuffer capacity: " + compressedBuffer.capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
output = zlib.decompressToString(compressedBuffer);
System.out.println("OUTPUT[" + output.length() + "]: \n");
System.out.println("Compression rate: " + zlib.lastCompressionRate());
compressedBuffer = zlib.compress(input);
System.out.println(
" CREATED, compressedBuffer capacity: " + compressedBuffer.capacity() +
", remaining: " + compressedBuffer.remaining() +
", position: " + compressedBuffer.position() +
", limit: " + compressedBuffer.limit());
// decompressedBuffer = zlib.decompress(compressedBuffer);
// System.out.println(
// " decompressedBuffer capacity: " + decompressedBuffer.capacity() +
// ", remaining: " + decompressedBuffer.remaining() +
// ", position: " + decompressedBuffer.position() +
// ", limit: " + decompressedBuffer.limit());
// System.out.println(
// " AFTER DECOMP, compressedBuffer capacity: " + compressedBuffer.
// capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
// compressedBuffer.rewind();
// System.out.println(
// " REWIND, compressedBuffer capacity: " + compressedBuffer.capacity() +
// ", remaining: " + compressedBuffer.remaining() +
// ", position: " + compressedBuffer.position() +
// ", limit: " + compressedBuffer.limit());
output = zlib.decompressToString(compressedBuffer);
System.out.println("OUTPUT[" + output.length() + "]: \n");
System.out.println("Compression rate: " + zlib.lastCompressionRate());
}
}
| Changed compression logic, now large buffers are split into smaller buffers and then they are compressed, otherwise it takes unacceptable long time for large buffers to compress and send them over to the client.
git-svn-id: 78a0b1024db9beb524bc745052f6db0c395bb78f@597 20a39203-4b1a-0410-9ea8-f7f58976c10f
| src/main/java/tigase/util/ZLibWrapper.java | Changed compression logic, now large buffers are split into smaller buffers and then they are compressed, otherwise it takes unacceptable long time for large buffers to compress and send them over to the client. |
|
Java | lgpl-2.1 | 8820a52b64587abe7d5d00d3a65ff87a43f29248 | 0 | 4ment/beast-mcmc,beast-dev/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,4ment/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,4ment/beast-mcmc,adamallo/beast-mcmc,adamallo/beast-mcmc,adamallo/beast-mcmc,beast-dev/beast-mcmc,beast-dev/beast-mcmc | /*
* DataSimulationDelegate.java
*
* Copyright (c) 2002-2016 Alexei Drummond, Andrew Rambaut and Marc Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodel.treedatalikelihood.preorder;
import beagle.Beagle;
import beagle.InstanceDetails;
import dr.evolution.alignment.PatternList;
import dr.evolution.alignment.SitePatterns;
import dr.evolution.tree.*;
import dr.evomodel.siteratemodel.SiteRateModel;
import dr.evomodel.substmodel.SubstitutionModel;
import dr.evomodel.treedatalikelihood.*;
import dr.inference.model.Model;
import java.util.List;
import static dr.evolution.tree.TreeTrait.DA.factory;
/**
* AbstractDiscreteTraitDelegate - interface for a plugin delegate for data simulation on a tree.
*
* @author Xiang Ji
* @author Marc Suchard
*/
public class AbstractDiscreteTraitDelegate extends ProcessSimulationDelegate.AbstractDelegate
implements TreeTrait.TraitInfo<double[]> {
private final BeagleDataLikelihoodDelegate likelihoodDelegate;
private final Beagle beagle;
private final EvolutionaryProcessDelegate evolutionaryProcessDelegate;
private final SiteRateModel siteRateModel;
private final int preOrderPartialOffset;
public AbstractDiscreteTraitDelegate(String name,
Tree tree,
BeagleDataLikelihoodDelegate likelihoodDelegate) {
super(name, tree);
this.likelihoodDelegate = likelihoodDelegate;
this.beagle = likelihoodDelegate.getBeagleInstance();
assert(this.likelihoodDelegate.isUsePreOrder()); /// TODO: reinitialize beagle instance if usePreOrder = false
evolutionaryProcessDelegate = this.likelihoodDelegate.getEvolutionaryProcessDelegate();
siteRateModel = this.likelihoodDelegate.getSiteRateModel();
nodeCount = tree.getNodeCount();
tipCount = tree.getExternalNodeCount();
internalNodeCount = nodeCount - tipCount;
patternCount = likelihoodDelegate.getPatternList().getPatternCount();
stateCount = likelihoodDelegate.getPatternList().getDataType().getStateCount();
categoryCount = siteRateModel.getCategoryCount();
// one partials buffer for each tip and two for each internal node (for store restore)
partialBufferHelper = new BufferIndexHelper(nodeCount, tipCount);
// mirror the preOrderpartialBufferHelper in BeagleDataLikelihoodDelegate
// every node gets two partisl (store and restore) except for the root node
preOrderBufferHelper = new BufferIndexHelper(nodeCount, 1);
// put preOrder partials in the same order as defined in BufferIndexHelper right after postOrder partials
preOrderPartialOffset = partialBufferHelper.getBufferCount();
patternList = likelihoodDelegate.getPatternList();
}
@Override
public void simulate(final int[] operations, final int operationCount,
final int rootNodeNumber) {
//This function updates preOrder Partials for all nodes
if(DEBUG){
System.err.println("Setting Root preOrder partial.");
}
this.simulateRoot(rootNodeNumber); //set up pre-order partials at root node first
if(DEBUG){
System.err.println("Now update preOrder partials at all other nodes");
}
int[] beagleoperations = new int[operationCount * Beagle.OPERATION_TUPLE_SIZE];
int k = 0; int j = 0;
for(int i = 0; i < operationCount; ++i){
beagleoperations[k++] = getPreOrderPartialIndex(operations[j++]);
beagleoperations[k++] = Beagle.NONE;
beagleoperations[k++] = Beagle.NONE;
beagleoperations[k++] = getPreOrderPartialIndex(operations[j++]);
beagleoperations[k++] = evolutionaryProcessDelegate.getMatrixIndex(operations[j++]);
beagleoperations[k++] = partialBufferHelper.getOffsetIndex(operations[j++]);
beagleoperations[k++] = evolutionaryProcessDelegate.getMatrixIndex(operations[j++]);
}
beagle.updatePrePartials(beagleoperations, operationCount, Beagle.NONE); // Update all nodes with no rescaling
//super.simulate(operations, operationCount, rootNodeNumber); // TODO Should override this to compute pre-order partials
//TODO:error control
}
@Override
public void setupStatistics() {
throw new RuntimeException("Not used (?) with BEAGLE");
}
@Override
protected void simulateRoot(int rootNumber) {
//This function sets preOrderPartials at Root for now.
if (DEBUG) {
System.err.println("Simulate root node " + rootNumber);
}
int[] rootPreIndices = {getPreOrderPartialIndex(rootNumber)};
int[] rootFreqIndices = {0}; /// as in BeagleDataLikelihoodDelegate.calculateLikelihood()
InstanceDetails instanceDetails = beagle.getDetails();
beagle.setRootPrePartials(rootPreIndices, rootFreqIndices, 1);
//TODO: find the right error message for control
}
@Override
protected void simulateNode(int v0, int v1, int v2, int v3, int v4) {
throw new RuntimeException("Not used with BEAGLE");
}
@Override
protected void constructTraits(Helper treeTraitHelper) {
treeTraitHelper.addTrait(factory(this));
}
public static String getName(String name) {
return "derivative." + name;
}
@Override
public String getTraitName() {
return getName(name);
}
@Override
public TreeTrait.Intent getTraitIntent() {
return TreeTrait.Intent.NODE;
}
@Override
public Class getTraitClass() {
return double[].class;
}
@Override
public double[] getTrait(Tree tree, NodeRef node) {
assert (tree == this.tree);
assert (node == null); // Implies: get trait for all nodes at same time
//update all preOrder partials first
simulationProcess.cacheSimulatedTraits(node);
final double[] postOrderPartial = new double[stateCount * patternCount * categoryCount];
final double[] preOrderPartial = new double[stateCount * patternCount * categoryCount];
final double[] frequencies = evolutionaryProcessDelegate.getRootStateFrequencies();
final double[] rootPostOrderPartials = new double[stateCount * patternCount * categoryCount];
final double[] gradient = new double[patternList.getStateCount()];
//create a matrix for fetching the infinitesimal matrix Q
double [] Q = new double[stateCount * stateCount];
double[] clikelihood = new double[categoryCount * patternCount]; // likelihood for each category doesn't come in free.
beagle.getPartials(partialBufferHelper.getOffsetIndex(tree.getRoot().getNumber()), Beagle.NONE, rootPostOrderPartials);
double [] grand_denominator = new double[patternCount];
double [] grand_numerator = new double[patternCount];
int l, j, k, s, t, m, u;
for(m = 0; m < patternCount; ++m){
grand_denominator[m] = 0;
grand_numerator[m] = 0;
}
beagle.getPartials(partialBufferHelper.getOffsetIndex(node.getNumber()), Beagle.NONE, postOrderPartial);
beagle.getPartials(getPreOrderPartialIndex(node.getNumber()), Beagle.NONE, preOrderPartial);
evolutionaryProcessDelegate.getSubstitutionModel(node.getNumber()).getInfinitesimalMatrix(Q); //store the Q matrix
double[] tmpNumerator = new double[patternCount * categoryCount];
l = 0; j = 0;
for(s = 0; s < categoryCount; s++){
for(m = 0; m < patternCount; m++){
double clikelihood_tmp = 0;
for( k = 0; k < stateCount; k++){
clikelihood_tmp += frequencies[k] * rootPostOrderPartials[l++];
}
clikelihood[j++] = clikelihood_tmp;
}
}
//now calculate weights
t = 0; u = 0;
double denominator = 0;
double numerator = 0;
double tmp = 0;
double[] weights = siteRateModel.getCategoryProportions();
for(s = 0; s < categoryCount; s++){
double rs = siteRateModel.getRateForCategory(s);
double ws = weights[s];
for(m = 0; m < patternCount; m++){
l = 0;
numerator = 0;
denominator = 0;
for(k = 0; k < stateCount; k++){
tmp = 0;
for(j = 0; j < stateCount; j++){
tmp += Q[l++] * postOrderPartial[u + j];
}
numerator += tmp * preOrderPartial[u + k];
denominator += postOrderPartial[u + k] * preOrderPartial[u + k];
}
u += stateCount;
tmpNumerator[t] = ws * rs * numerator / denominator * clikelihood[t];
grand_numerator[m] += tmpNumerator[t];
grand_denominator[m] += ws * clikelihood[t];
t++;
}
}
for( m = 0; m < patternList.getStateCount(); m++){
int sitePatternIndex = ((SitePatterns) patternList).getPatternIndex(m);
gradient[m] = grand_numerator[sitePatternIndex] / grand_denominator[sitePatternIndex];
}
// TODO See TipGradientViaFullConditionalDelegate.getTrait() as an example of using post- and pre-order partials together
return gradient;
}
@Override
public boolean isTraitLoggable() {
return false;
}
@Override
public void modelChangedEvent(Model model, Object object, int index) {
// TODO
}
@Override
public void modelRestored(Model model) {
}
@Override
public int vectorizeNodeOperations(List<NodeOperation> nodeOperations, int[] operations) {
int k = 0;
for(int i = 0; i < nodeOperations.size(); ++i){
NodeOperation tmpNodeOperation = nodeOperations.get(i);
//nodeNumber = ParentNodeNumber, leftChild = nodeNumber, rightChild = siblingNodeNumber
operations[k++] = tmpNodeOperation.getLeftChild();
operations[k++] = tmpNodeOperation.getNodeNumber();
operations[k++] = tmpNodeOperation.getLeftChild();
operations[k++] = tmpNodeOperation.getRightChild();
operations[k++] = tmpNodeOperation.getRightChild();
}
flipBufferIndices(nodeOperations);
return nodeOperations.size();
}
//This function defines the mapping from nodeNum to its preorder partial index
final private int getPreOrderPartialIndex(final int i){
NodeRef nodeRef = tree.getNode(i);
if(tree.isRoot(nodeRef)){
return preOrderPartialOffset + 0;
}else{
return preOrderPartialOffset + preOrderBufferHelper.getOffsetIndex(i + 1);
}
}
final private void flipBufferIndices(List<NodeOperation> nodeOperations) {
// Flip all the buffers to be written to first...
for (int nodeNum = tipCount; nodeNum < nodeCount; ++nodeNum){
this.partialBufferHelper.flipOffset(nodeNum);
}
// Now root = 0 (stored as a tip in postOrder), all other nodeNum += 1
for (int nodeNum = 1; nodeNum < nodeCount; ++nodeNum){
this.preOrderBufferHelper.flipOffset(nodeNum);
}
}
// **************************************************************
// INSTANCE VARIABLES
// **************************************************************
private final int nodeCount;
private final int tipCount;
private final int internalNodeCount;
private final int patternCount;
private final int stateCount;
private final int categoryCount;
private final BufferIndexHelper partialBufferHelper;
private final BufferIndexHelper preOrderBufferHelper;
private final PatternList patternList;
private static final boolean DEBUG = true;
}
| src/dr/evomodel/treedatalikelihood/preorder/AbstractDiscreteTraitDelegate.java | /*
* DataSimulationDelegate.java
*
* Copyright (c) 2002-2016 Alexei Drummond, Andrew Rambaut and Marc Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.evomodel.treedatalikelihood.preorder;
import beagle.Beagle;
import beagle.InstanceDetails;
import dr.evolution.alignment.PatternList;
import dr.evolution.alignment.SitePatterns;
import dr.evolution.tree.*;
import dr.evomodel.siteratemodel.SiteRateModel;
import dr.evomodel.substmodel.SubstitutionModel;
import dr.evomodel.treedatalikelihood.*;
import dr.inference.model.Model;
import java.util.List;
import static dr.evolution.tree.TreeTrait.DA.factory;
/**
* AbstractDiscreteTraitDelegate - interface for a plugin delegate for data simulation on a tree.
*
* @author Xiang Ji
* @author Marc Suchard
*/
public class AbstractDiscreteTraitDelegate extends ProcessSimulationDelegate.AbstractDelegate
implements TreeTrait.TraitInfo<double[]> {
private final BeagleDataLikelihoodDelegate likelihoodDelegate;
private final Beagle beagle;
private final EvolutionaryProcessDelegate evolutionaryProcessDelegate;
private final SiteRateModel siteRateModel;
private final int preOrderPartialOffset;
public AbstractDiscreteTraitDelegate(String name,
Tree tree,
BeagleDataLikelihoodDelegate likelihoodDelegate) {
super(name, tree);
this.likelihoodDelegate = likelihoodDelegate;
this.beagle = likelihoodDelegate.getBeagleInstance();
assert(this.likelihoodDelegate.isUsePreOrder()); /// TODO: reinitialize beagle instance if usePreOrder = false
evolutionaryProcessDelegate = this.likelihoodDelegate.getEvolutionaryProcessDelegate();
siteRateModel = this.likelihoodDelegate.getSiteRateModel();
nodeCount = tree.getNodeCount();
tipCount = tree.getExternalNodeCount();
internalNodeCount = nodeCount - tipCount;
patternCount = likelihoodDelegate.getPatternList().getPatternCount();
stateCount = likelihoodDelegate.getPatternList().getDataType().getStateCount();
categoryCount = siteRateModel.getCategoryCount();
// one partials buffer for each tip and two for each internal node (for store restore)
partialBufferHelper = new BufferIndexHelper(nodeCount, tipCount);
// mirror the preOrderpartialBufferHelper in BeagleDataLikelihoodDelegate
// every node gets two partisl (store and restore) except for the root node
preOrderBufferHelper = new BufferIndexHelper(nodeCount, 1);
// put preOrder partials in the same order as defined in BufferIndexHelper right after postOrder partials
preOrderPartialOffset = partialBufferHelper.getBufferCount();
patternList = likelihoodDelegate.getPatternList();
}
@Override
public void simulate(final int[] operations, final int operationCount,
final int rootNodeNumber) {
//This function updates preOrder Partials for all nodes
if(DEBUG){
System.err.println("Setting Root preOrder partial.");
}
this.simulateRoot(rootNodeNumber); //set up pre-order partials at root node first
if(DEBUG){
System.err.println("Now update preOrder partials at all other nodes");
}
int[] beagleoperations = new int[operationCount * Beagle.OPERATION_TUPLE_SIZE];
int k = 0; int j = 0;
for(int i = 0; i < operationCount; ++i){
beagleoperations[k++] = getPreOrderPartialIndex(operations[j++]);
beagleoperations[k++] = Beagle.NONE;
beagleoperations[k++] = Beagle.NONE;
beagleoperations[k++] = getPreOrderPartialIndex(operations[j++]);
beagleoperations[k++] = evolutionaryProcessDelegate.getMatrixIndex(operations[j++]);
beagleoperations[k++] = partialBufferHelper.getOffsetIndex(operations[j++]);
beagleoperations[k++] = evolutionaryProcessDelegate.getMatrixIndex(operations[j++]);
}
beagle.updatePrePartials(beagleoperations, operationCount, Beagle.NONE); // Update all nodes with no rescaling
//super.simulate(operations, operationCount, rootNodeNumber); // TODO Should override this to compute pre-order partials
//TODO:error control
}
@Override
public void setupStatistics() {
throw new RuntimeException("Not used (?) with BEAGLE");
}
@Override
protected void simulateRoot(int rootNumber) {
//This function sets preOrderPartials at Root for now.
if (DEBUG) {
System.err.println("Simulate root node " + rootNumber);
}
int[] rootPreIndices = {getPreOrderPartialIndex(rootNumber)};
int[] rootFreqIndices = {0}; /// as in BeagleDataLikelihoodDelegate.calculateLikelihood()
InstanceDetails instanceDetails = beagle.getDetails();
beagle.setRootPrePartials(rootPreIndices, rootFreqIndices, 1);
//TODO: find the right error message for control
}
@Override
protected void simulateNode(int v0, int v1, int v2, int v3, int v4) {
throw new RuntimeException("Not used with BEAGLE");
}
@Override
protected void constructTraits(Helper treeTraitHelper) {
treeTraitHelper.addTrait(factory(this));
}
public static String getName(String name) {
return "derivative." + name;
}
@Override
public String getTraitName() {
return getName(name);
}
@Override
public TreeTrait.Intent getTraitIntent() {
return TreeTrait.Intent.NODE;
}
@Override
public Class getTraitClass() {
return double[].class;
}
@Override
public double[] getTrait(Tree tree, NodeRef node) {
assert (tree == this.tree);
assert (node == null); // Implies: get trait for all nodes at same time
//update all preOrder partials first
simulationProcess.cacheSimulatedTraits(node);
final double[] postOrderPartial = new double[stateCount * patternCount * categoryCount];
final double[] preOrderPartial = new double[stateCount * patternCount * categoryCount];
final double[] frequencies = evolutionaryProcessDelegate.getRootStateFrequencies();
final double[] rootPostOrderPartials = new double[stateCount * patternCount * categoryCount];
final double[] gradient = new double[patternList.getStateCount()];
//create a matrix for fetching the infinitesimal matrix Q
double [] Q = new double[stateCount * stateCount];
double[] clikelihood = new double[categoryCount * patternCount]; // likelihood for each category doesn't come in free.
beagle.getPartials(partialBufferHelper.getOffsetIndex(tree.getRoot().getNumber()), Beagle.NONE, rootPostOrderPartials);
double [] grand_denominator = new double[patternCount];
double [] grand_numerator = new double[patternCount];
int l, j, k, s, t, m, u;
for(m = 0; m < patternCount; ++m){
grand_denominator[m] = 0;
grand_numerator[m] = 0;
}
beagle.getPartials(partialBufferHelper.getOffsetIndex(node.getNumber()), Beagle.NONE, postOrderPartial);
beagle.getPartials(getPreOrderPartialIndex(node.getNumber()), Beagle.NONE, preOrderPartial);
evolutionaryProcessDelegate.getSubstitutionModel(node.getNumber()).getInfinitesimalMatrix(Q); //store the Q matrix
double[] tmpNumerator = new double[patternCount * categoryCount];
l = 0; j = 0;
for(s = 0; s < categoryCount; s++){
for(m = 0; m < patternCount; m++){
double clikelihood_tmp = 0;
for( k = 0; k < stateCount; k++){
clikelihood_tmp += frequencies[k] * rootPostOrderPartials[l++];
}
clikelihood[j++] = clikelihood_tmp;
}
}
//now calculate weights
t = 0;
double denominator = 0;
double numerator = 0;
double tmp = 0;
double[] weights = siteRateModel.getCategoryProportions();
for(s = 0; s < categoryCount; s++){
double rs = siteRateModel.getRateForCategory(s);
double ws = weights[s];
u = 0;
for(m = 0; m < patternCount; m++){
l = 0;
numerator = 0;
denominator = 0;
for(k = 0; k < stateCount; k++){
tmp = 0;
for(j = 0; j < stateCount; j++){
tmp += Q[l++] * postOrderPartial[u + j];
}
numerator += tmp * preOrderPartial[u + k];
denominator += postOrderPartial[u + k] * preOrderPartial[u + k];
}
u += stateCount;
tmpNumerator[t] = ws * rs * numerator / denominator * clikelihood[t];
grand_numerator[m] += tmpNumerator[t];
grand_denominator[m] += ws * clikelihood[t];
t++;
}
}
for( m = 0; m < patternList.getStateCount(); m++){
int sitePatternIndex = ((SitePatterns) patternList).getPatternIndex(m);
gradient[m] = grand_numerator[sitePatternIndex] / grand_denominator[sitePatternIndex];
}
// TODO See TipGradientViaFullConditionalDelegate.getTrait() as an example of using post- and pre-order partials together
return gradient;
}
@Override
public boolean isTraitLoggable() {
return false;
}
@Override
public void modelChangedEvent(Model model, Object object, int index) {
// TODO
}
@Override
public void modelRestored(Model model) {
}
@Override
public int vectorizeNodeOperations(List<NodeOperation> nodeOperations, int[] operations) {
int k = 0;
for(int i = 0; i < nodeOperations.size(); ++i){
NodeOperation tmpNodeOperation = nodeOperations.get(i);
//nodeNumber = ParentNodeNumber, leftChild = nodeNumber, rightChild = siblingNodeNumber
operations[k++] = tmpNodeOperation.getLeftChild();
operations[k++] = tmpNodeOperation.getNodeNumber();
operations[k++] = tmpNodeOperation.getLeftChild();
operations[k++] = tmpNodeOperation.getRightChild();
operations[k++] = tmpNodeOperation.getRightChild();
}
flipBufferIndices(nodeOperations);
return nodeOperations.size();
}
//This function defines the mapping from nodeNum to its preorder partial index
final private int getPreOrderPartialIndex(final int i){
NodeRef nodeRef = tree.getNode(i);
if(tree.isRoot(nodeRef)){
return preOrderPartialOffset + 0;
}else{
return preOrderPartialOffset + preOrderBufferHelper.getOffsetIndex(i + 1);
}
}
final private void flipBufferIndices(List<NodeOperation> nodeOperations) {
// Flip all the buffers to be written to first...
for (int nodeNum = tipCount; nodeNum < nodeCount; ++nodeNum){
this.partialBufferHelper.flipOffset(nodeNum);
}
// Now root = 0 (stored as a tip in postOrder), all other nodeNum += 1
for (int nodeNum = 1; nodeNum < nodeCount; ++nodeNum){
this.preOrderBufferHelper.flipOffset(nodeNum);
}
}
// **************************************************************
// INSTANCE VARIABLES
// **************************************************************
private final int nodeCount;
private final int tipCount;
private final int internalNodeCount;
private final int patternCount;
private final int stateCount;
private final int categoryCount;
private final BufferIndexHelper partialBufferHelper;
private final BufferIndexHelper preOrderBufferHelper;
private final PatternList patternList;
private static final boolean DEBUG = true;
}
| correct before anyone noticed
| src/dr/evomodel/treedatalikelihood/preorder/AbstractDiscreteTraitDelegate.java | correct before anyone noticed |
|
Java | lgpl-2.1 | 73fc7c398cd662a876e195fd0a1cf1450f5af6e1 | 0 | elsiklab/intermine,joshkh/intermine,drhee/toxoMine,justincc/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,kimrutherford/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,JoeCarlson/intermine,drhee/toxoMine,joshkh/intermine,joshkh/intermine,kimrutherford/intermine,justincc/intermine,tomck/intermine,zebrafishmine/intermine,tomck/intermine,drhee/toxoMine,joshkh/intermine,elsiklab/intermine,kimrutherford/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,elsiklab/intermine,drhee/toxoMine,JoeCarlson/intermine,zebrafishmine/intermine,justincc/intermine,joshkh/intermine,zebrafishmine/intermine,Arabidopsis-Information-Portal/intermine,tomck/intermine,elsiklab/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,joshkh/intermine,kimrutherford/intermine,justincc/intermine,JoeCarlson/intermine,drhee/toxoMine,zebrafishmine/intermine,zebrafishmine/intermine,drhee/toxoMine,zebrafishmine/intermine,drhee/toxoMine,tomck/intermine,drhee/toxoMine,joshkh/intermine,justincc/intermine,joshkh/intermine,elsiklab/intermine,kimrutherford/intermine,kimrutherford/intermine,zebrafishmine/intermine,zebrafishmine/intermine,tomck/intermine,justincc/intermine,tomck/intermine,kimrutherford/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,JoeCarlson/intermine,elsiklab/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,drhee/toxoMine,zebrafishmine/intermine,JoeCarlson/intermine,tomck/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,JoeCarlson/intermine,JoeCarlson/intermine,justincc/intermine,justincc/intermine | package org.intermine.bio.dataconversion;
/*
* Copyright (C) 2002-2008 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.intermine.bio.dataconversion.ChadoSequenceProcessor.FeatureData;
import org.intermine.bio.util.OrganismData;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.ReferenceList;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
import org.apache.commons.lang.StringUtils;
/**
* A ChadoProcessor for the chado stock module.
* @author Kim Rutherford
*/
public class StockProcessor extends ChadoProcessor
{
private static final Logger LOG = Logger.getLogger(ChadoSequenceProcessor.class);
private Map<String, Item> stockItems = new HashMap<String, Item>();
/**
* Create a new ChadoProcessor
* @param chadoDBConverter the Parent ChadoDBConverter
*/
public StockProcessor(ChadoDBConverter chadoDBConverter) {
super(chadoDBConverter);
}
/**
* {@inheritDoc}
*/
@Override
public void process(Connection connection) throws Exception {
processSocks(connection);
}
/**
* Process the stocks and genotypes tables in a chado database
* @param connection
*/
private void processSocks(Connection connection)
throws SQLException, ObjectStoreException {
Map<Integer, FeatureData> features = getFeatures();
ResultSet res = getStocksResultSet(connection);
int count = 0;
Integer lastFeatureId = null;
List<Item> stocks = new ArrayList<Item>();
while (res.next()) {
Integer featureId = new Integer(res.getInt("feature_id"));
if (!features.containsKey(featureId)) {
// probably an allele of an unlocated genes
continue;
}
String stockUniqueName = res.getString("stock_uniquename");
String stockDescription = res.getString("stock_description");
String stockCenterUniquename = res.getString("stock_center_uniquename");
String stockType = res.getString("stock_type_name");
Integer organismId = new Integer(res.getInt("stock_organism_id"));
OrganismData organismData =
getChadoDBConverter().getChadoIdToOrgDataMap().get(organismId);
if (organismData == null) {
throw new RuntimeException("can't get OrganismData for: " + organismId);
}
Item organismItem = getChadoDBConverter().getOrganismItem(organismData.getTaxonId());
Item stock = makeStock(stockUniqueName, stockDescription, stockType,
stockCenterUniquename);
stock.setReference("organism", organismItem);
stocks.add(stock);
if (lastFeatureId != null && !featureId.equals(lastFeatureId)) {
storeStocks(features, lastFeatureId, stocks);
stocks = new ArrayList<Item>();
}
lastFeatureId = featureId;
}
if (lastFeatureId != null) {
storeStocks(features, lastFeatureId, stocks);
}
LOG.info("created " + count + " stocks");
res.close();
}
private Map<Integer, FeatureData> getFeatures() {
Class<ChadoSequenceProcessor> seqProcessorClass = ChadoSequenceProcessor.class;
ChadoSequenceProcessor sequenceProcessor =
(ChadoSequenceProcessor) getChadoDBConverter().findProcessor(seqProcessorClass);
Map<Integer, FeatureData> features = sequenceProcessor.getFeatureMap();
return features;
}
private Item makeStock(String uniqueName, String description, String stockType,
String stockCenterUniqueName) throws ObjectStoreException {
if (stockItems.containsKey(uniqueName)) {
return stockItems.get(uniqueName);
} else {
Item stock = getChadoDBConverter().createItem("Stock");
stock.setAttribute("primaryIdentifier", uniqueName);
stock.setAttribute("secondaryIdentifier", description);
stock.setAttribute("type", stockType);
stock.setAttribute("stockCenter", stockCenterUniqueName);
getChadoDBConverter().store(stock);
stockItems.put(uniqueName, stock);
return stock;
}
}
private void storeStocks(Map<Integer, FeatureData> features, Integer lastFeatureId,
List<Item> stocks) throws ObjectStoreException {
FeatureData featureData = features.get(lastFeatureId);
if (featureData == null) {
throw new RuntimeException("can't find feature data for: " + lastFeatureId);
}
Integer intermineObjectId = featureData.getIntermineObjectId();
ReferenceList referenceList = new ReferenceList();
referenceList.setName("stocks");
for (Item stock: stocks) {
referenceList.addRefId(stock.getIdentifier());
}
getChadoDBConverter().store(referenceList, intermineObjectId);
}
/**
* Return the interesting rows from the features table.
* This is a protected method so that it can be overriden for testing
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getStocksResultSet(Connection connection)
throws SQLException {
String organismConstraint = getOrganismConstraint();
String orgConstraintForQuery = "";
if (!StringUtils.isEmpty(organismConstraint)) {
orgConstraintForQuery = " AND " + organismConstraint;
}
String query =
"SELECT feature.feature_id, stock.uniquename AS stock_uniquename, "
+ " stock.description AS stock_description, type_cvterm.name AS stock_type_name, "
+ " stock.organism_id AS stock_organism_id, "
+ " (SELECT stockcollection.uniquename "
+ " FROM stockcollection, stockcollection_stock join_table "
+ " WHERE stockcollection.stockcollection_id = join_table.stockcollection_id "
+ " AND join_table.stock_id = stock.stock_id) "
+ " AS stock_center_uniquename "
+ " FROM stock_genotype, feature, stock, feature_genotype, cvterm type_cvterm "
+ "WHERE stock.stock_id = stock_genotype.stock_id "
+ "AND feature_genotype.feature_id = feature.feature_id "
+ "AND feature_genotype.genotype_id = stock_genotype.genotype_id "
+ "AND feature.uniquename LIKE 'FBal%' "
+ "AND stock.type_id = type_cvterm.cvterm_id "
+ orgConstraintForQuery + " "
+ "AND stock.organism_id = feature.organism_id "
+ "ORDER BY feature.feature_id";
LOG.info("executing: " + query);
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
return res;
}
/**
* Return a comma separated string containing the organism_ids that with with to query from
* chado.
*/
private String getOrganismIdsString() {
return StringUtils.join(getChadoDBConverter().getChadoIdToOrgDataMap().keySet(), ", ");
}
/**
* Return some SQL that can be included in the WHERE part of query that restricts features
* by organism. "organism_id" must be selected.
* @return the SQL
*/
protected String getOrganismConstraint() {
String organismIdsString = getOrganismIdsString();
if (StringUtils.isEmpty(organismIdsString)) {
return "";
} else {
return "feature.organism_id IN (" + organismIdsString + ")";
}
}
}
| bio/sources/chado-db/main/src/org/intermine/bio/dataconversion/StockProcessor.java | package org.intermine.bio.dataconversion;
/*
* Copyright (C) 2002-2008 FlyMine
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. See the LICENSE file for more
* information or http://www.gnu.org/copyleft/lesser.html.
*
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.intermine.bio.dataconversion.ChadoSequenceProcessor.FeatureData;
import org.intermine.bio.util.OrganismData;
import org.intermine.objectstore.ObjectStoreException;
import org.intermine.xml.full.Item;
import org.intermine.xml.full.ReferenceList;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.log4j.Logger;
import org.apache.commons.lang.StringUtils;
/**
* A ChadoProcessor for the chado stock module.
* @author Kim Rutherford
*/
public class StockProcessor extends ChadoProcessor
{
private static final Logger LOG = Logger.getLogger(ChadoSequenceProcessor.class);
private Map<String, Item> stockItems = new HashMap<String, Item>();
/**
* Create a new ChadoProcessor
* @param chadoDBConverter the Parent ChadoDBConverter
*/
public StockProcessor(ChadoDBConverter chadoDBConverter) {
super(chadoDBConverter);
}
/**
* {@inheritDoc}
*/
@Override
public void process(Connection connection) throws Exception {
processSocks(connection);
}
/**
* Process the stocks and genotypes tables in a chado database
* @param connection
*/
private void processSocks(Connection connection)
throws SQLException, ObjectStoreException {
Map<Integer, FeatureData> features = getFeatures();
ResultSet res = getStocksResultSet(connection);
int count = 0;
Integer lastFeatureId = null;
List<Item> stocks = new ArrayList<Item>();
while (res.next()) {
Integer featureId = new Integer(res.getInt("feature_id"));
if (!features.containsKey(featureId)) {
// probably an allele of an unlocated genes
continue;
}
String stockUniqueName = res.getString("stock_uniquename");
String stockDescription = res.getString("stock_description");
String stockCenterUniquename = res.getString("stock_center_uniquename");
String stockType = res.getString("stock_type_name");
Integer organismId = new Integer(res.getInt("stock_organism_id"));
OrganismData organismData =
getChadoDBConverter().getChadoIdToOrgDataMap().get(organismId);
if (organismData == null) {
throw new RuntimeException("can't get OrganismData for: " + organismId);
}
Item organismItem = getChadoDBConverter().getOrganismItem(organismData.getTaxonId());
Item stock = makeStock(stockUniqueName, stockDescription, stockType,
stockCenterUniquename);
stock.setReference("organism", organismItem);
stocks.add(stock);
if (lastFeatureId != null && !featureId.equals(lastFeatureId)) {
storeStocks(features, lastFeatureId, stocks);
stocks = new ArrayList<Item>();
}
lastFeatureId = featureId;
}
if (lastFeatureId != null) {
storeStocks(features, lastFeatureId, stocks);
}
LOG.info("created " + count + " stocks");
res.close();
}
private Map<Integer, FeatureData> getFeatures() {
Class<ChadoSequenceProcessor> seqProcessorClass = ChadoSequenceProcessor.class;
ChadoSequenceProcessor sequenceProcessor =
(ChadoSequenceProcessor) getChadoDBConverter().findProcessor(seqProcessorClass);
Map<Integer, FeatureData> features = sequenceProcessor.getFeatureMap();
return features;
}
private Item makeStock(String uniqueName, String description, String stockType,
String stockCenterUniqueName) throws ObjectStoreException {
if (stockItems.containsKey(uniqueName)) {
return stockItems.get(uniqueName);
} else {
Item stock = getChadoDBConverter().createItem("Stock");
stock.setAttribute("primaryIdentifier", uniqueName);
stock.setAttribute("secondaryIdentifier", description);
stock.setAttribute("type", stockType);
stock.setAttribute("stockCenter", stockCenterUniqueName);
getChadoDBConverter().store(stock);
stockItems.put(uniqueName, stock);
return stock;
}
}
private void storeStocks(Map<Integer, FeatureData> features, Integer lastFeatureId,
List<Item> stocks) throws ObjectStoreException {
FeatureData featureData = features.get(lastFeatureId);
if (featureData == null) {
throw new RuntimeException("can't find feature data for: " + lastFeatureId);
}
Integer intermineObjectId = featureData.getIntermineObjectId();
ReferenceList referenceList = new ReferenceList();
referenceList.setName("stocks");
for (Item stock: stocks) {
referenceList.addRefId(stock.getIdentifier());
}
getChadoDBConverter().store(referenceList, intermineObjectId);
}
/**
* Return the interesting rows from the features table.
* This is a protected method so that it can be overriden for testing
* @param connection the db connection
* @return the SQL result set
* @throws SQLException if a database problem occurs
*/
protected ResultSet getStocksResultSet(Connection connection)
throws SQLException {
String organismConstraint = getOrganismConstraint();
String orgConstraintForQuery = "";
if (!StringUtils.isEmpty(organismConstraint)) {
orgConstraintForQuery = " AND " + organismConstraint;
}
String query =
"SELECT feature.feature_id, stock.uniquename AS stock_uniquename, "
+ " stock.description AS stock_description, type_cvterm.name AS stock_type_name, "
+ " stock.organism_id AS stock_organism_id, "
+ " (SELECT stockcollection.uniquename "
+ " FROM stockcollection, stockcollection_stock join_table "
+ " WHERE stockcollection.stockcollection_id = join_table.stockcollection_id "
+ " AND join_table.stock_id = stock.stock_id) "
+ " AS stock_center_uniquename "
+ " FROM stock_genotype, feature, stock, feature_genotype, cvterm type_cvterm "
+ "WHERE stock.stock_id = stock_genotype.stock_id "
+ "AND feature_genotype.feature_id = feature.feature_id "
+ "AND feature_genotype.genotype_id = stock_genotype.genotype_id "
+ "AND feature.uniquename LIKE 'FBal%' "
+ "AND stock.type_id = type_cvterm.cvterm_id "
+ orgConstraintForQuery + " "
+ "ORDER BY feature.feature_id";
LOG.info("executing: " + query);
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(query);
return res;
}
/**
* Return a comma separated string containing the organism_ids that with with to query from
* chado.
*/
private String getOrganismIdsString() {
return StringUtils.join(getChadoDBConverter().getChadoIdToOrgDataMap().keySet(), ", ");
}
/**
* Return some SQL that can be included in the WHERE part of query that restricts features
* by organism. "organism_id" must be selected.
* @return the SQL
*/
protected String getOrganismConstraint() {
String organismIdsString = getOrganismIdsString();
if (StringUtils.isEmpty(organismIdsString)) {
return "";
} else {
return "feature.organism_id IN (" + organismIdsString + ")";
}
}
}
| Fix sock query to ignore stocks where the organism_id of the stock is
different to the organism_id of the feature.
Refs #1865.
| bio/sources/chado-db/main/src/org/intermine/bio/dataconversion/StockProcessor.java | Fix sock query to ignore stocks where the organism_id of the stock is different to the organism_id of the feature. Refs #1865. |
|
Java | lgpl-2.1 | 0344eb9951b3ee3732b321724468f62d3236639a | 0 | mdekstrand/grapht,mdekstrand/grapht | /*
* Grapht, an open source dependency injector.
* Copyright 2010-2012 Regents of the University of Minnesota and contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.grouplens.grapht.util;
import javax.annotation.Nullable;
import java.io.InvalidObjectException;
import java.io.ObjectStreamException;
import java.io.Serializable;
/**
* InstanceProvider is a simple Provider that always provides the same instance.
*
* @author <a href="http://grouplens.org">GroupLens Research</a>
* @param <T>
*/
public class InstanceProvider<T> implements TypedProvider<T>, Serializable {
private static final long serialVersionUID = -1L;
private final Class<?> providedType;
private final T instance;
/**
* Construct a new instance provider.
* @param instance The instance.
* @deprecated Use {@link Providers#of(Object)} instead.
*/
@Deprecated
public InstanceProvider(T instance) {
this(instance, instance == null ? Object.class : instance.getClass());
}
InstanceProvider(@Nullable T instance, Class<?> type) {
if (instance != null && !type.isInstance(instance)) {
throw new IllegalArgumentException("instance not of specified type");
}
this.instance = instance;
providedType = type;
}
@Override
public Class<?> getProvidedType() {
return providedType;
}
@Override
public T get() {
return instance;
}
@Override
public String toString() {
if (instance == null) {
return "InstanceProvider{null<" + providedType.getName() + ">}";
} else {
return "InstanceProvider{" + instance + "}";
}
}
private Object writeReplace() {
return new SerialProxy(providedType, instance);
}
private Object readObject() throws ObjectStreamException {
throw new InvalidObjectException("must use serialization proxy");
}
private static class SerialProxy implements Serializable {
private static final long serialVersionUID = 1L;
private ClassProxy type;
private Object instance;
public SerialProxy(Class<?> t, Object i) {
type = ClassProxy.of(t);
instance = i;
}
@SuppressWarnings("unchecked")
private Object readResolve() throws ObjectStreamException {
Class<?> cls = null;
try {
cls = type.resolve();
} catch (ClassNotFoundException e) {
InvalidObjectException ex = new InvalidObjectException("class not found");
ex.initCause(e);
throw ex;
}
if (instance != null && !cls.isInstance(instance)) {
throw new InvalidObjectException("instance is not of expected type");
}
return new InstanceProvider(instance, cls);
}
}
}
| src/main/java/org/grouplens/grapht/util/InstanceProvider.java | /*
* Grapht, an open source dependency injector.
* Copyright 2010-2012 Regents of the University of Minnesota and contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.grouplens.grapht.util;
import javax.annotation.Nullable;
import java.io.InvalidObjectException;
import java.io.ObjectStreamException;
import java.io.Serializable;
/**
* InstanceProvider is a simple Provider that always provides the same instance.
*
* @author <a href="http://grouplens.org">GroupLens Research</a>
* @param <T>
*/
public class InstanceProvider<T> implements TypedProvider<T>, Serializable {
private static final long serialVersionUID = -1L;
private final Class<?> providedType;
private final T instance;
/**
* Construct a new instance provider.
* @param instance The instance.
* @deprecated Use {@link Providers#of(Object)} instead.
*/
@Deprecated
public InstanceProvider(T instance) {
this(instance, instance == null ? Object.class : instance.getClass());
}
InstanceProvider(@Nullable T instance, Class<?> type) {
if (instance != null && !type.isInstance(instance)) {
throw new IllegalArgumentException("instance not of specified type");
}
this.instance = instance;
providedType = type;
}
@Override
public Class<?> getProvidedType() {
return providedType;
}
@Override
public T get() {
return instance;
}
private Object writeReplace() {
return new SerialProxy(providedType, instance);
}
private Object readObject() throws ObjectStreamException {
throw new InvalidObjectException("must use serialization proxy");
}
private static class SerialProxy implements Serializable {
private static final long serialVersionUID = 1L;
private ClassProxy type;
private Object instance;
public SerialProxy(Class<?> t, Object i) {
type = ClassProxy.of(t);
instance = i;
}
@SuppressWarnings("unchecked")
private Object readResolve() throws ObjectStreamException {
Class<?> cls = null;
try {
cls = type.resolve();
} catch (ClassNotFoundException e) {
InvalidObjectException ex = new InvalidObjectException("class not found");
ex.initCause(e);
throw ex;
}
if (instance != null && !cls.isInstance(instance)) {
throw new InvalidObjectException("instance is not of expected type");
}
return new InstanceProvider(instance, cls);
}
}
}
| Fix toString in InstanceProvider
| src/main/java/org/grouplens/grapht/util/InstanceProvider.java | Fix toString in InstanceProvider |
|
Java | apache-2.0 | f4fc99cb3a9dee1fded705f5e69eb6e548465564 | 0 | remkop/picocli,remkop/picocli,remkop/picocli,remkop/picocli | package picocli;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.ProvideSystemProperty;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.rules.TestRule;
import picocli.CommandLine.ArgGroup;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import picocli.CommandLine.Mixin;
import picocli.CommandLine.Help;
import picocli.CommandLine.ParseResult;
import picocli.CommandLine.InitializationException;
import picocli.CommandLine.DuplicateOptionAnnotationsException;
import picocli.CommandLine.ParameterException;
import picocli.CommandLine.MaxValuesExceededException;
import picocli.CommandLine.MissingParameterException;
import picocli.CommandLine.MutuallyExclusiveArgsException;
import picocli.CommandLine.Model.ArgGroupSpec;
import picocli.CommandLine.Model.ArgSpec;
import picocli.CommandLine.Model.CommandSpec;
import picocli.CommandLine.Model.OptionSpec;
import picocli.CommandLine.Model.PositionalParamSpec;
import picocli.CommandLine.ParseResult.GroupMatchContainer;
import picocli.CommandLine.ParseResult.GroupMatch;
import picocli.CommandLine.ParseResult.GroupValidationResult;
import picocli.CommandLine.Spec;
import picocli.CommandLine.UnmatchedArgumentException;
import picocli.test.Execution;
import picocli.test.Supplier;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import static org.junit.Assert.*;
import static picocli.ArgGroupTest.CommandMethodsWithGroupsAndMixins.InvokedSub.withMixin;
public class ArgGroupTest {
@Rule
public final ProvideSystemProperty ansiOFF = new ProvideSystemProperty("picocli.ansi", "false");
// allows tests to set any kind of properties they like, without having to individually roll them back
@Rule
public final TestRule restoreSystemProperties = new RestoreSystemProperties();
static final OptionSpec OPTION = OptionSpec.builder("-x").required(true).build();
static final OptionSpec OPTION_A = OptionSpec.builder("-a").required(true).build();
static final OptionSpec OPTION_B = OptionSpec.builder("-b").required(true).build();
static final OptionSpec OPTION_C = OptionSpec.builder("-c").required(true).build();
@Test
public void testArgSpecHaveNoGroupsByDefault() {
assertNull(OptionSpec.builder("-x").build().group());
assertNull(PositionalParamSpec.builder().build().group());
}
@Ignore
@Test
public void testArgSpecBuilderHasNoExcludesByDefault() {
// assertTrue(OptionSpec.builder("-x").excludes().isEmpty());
// assertTrue(PositionalParamSpec.builder().excludes().isEmpty());
fail(); // TODO
}
@Ignore
@Test
public void testOptionSpecBuilderExcludesMutable() {
// OptionSpec.Builder builder = OptionSpec.builder("-x");
// assertTrue(builder.excludes().isEmpty());
//
// builder.excludes("AAA").build();
// assertEquals(1, builder.excludes().size());
// assertEquals("AAA", builder.excludes().get(0));
fail(); // TODO
}
@Ignore
@Test
public void testPositionalParamSpecBuilderExcludesMutable() {
// PositionalParamSpec.Builder builder = PositionalParamSpec.builder();
// assertTrue(builder.excludes().isEmpty());
//
// builder.excludes("AAA").build();
// assertEquals(1, builder.excludes().size());
// assertEquals("AAA", builder.excludes().get(0));
fail();
}
@Test
public void testGroupSpecBuilderFromAnnotation() {
class Args {
@Option(names = "-x") int x;
}
class App {
@ArgGroup(exclusive = false, validate = false, multiplicity = "1",
headingKey = "headingKeyXXX", heading = "headingXXX", order = 123)
Args args;
}
CommandLine commandLine = new CommandLine(new App(), new InnerClassFactory(this));
assertEquals(1, commandLine.getCommandSpec().argGroups().size());
ArgGroupSpec group = commandLine.getCommandSpec().argGroups().get(0);
assertNotNull(group);
assertEquals(false, group.exclusive());
assertEquals(false, group.validate());
assertEquals(CommandLine.Range.valueOf("1"), group.multiplicity());
assertEquals("headingKeyXXX", group.headingKey());
assertEquals("headingXXX", group.heading());
assertEquals(123, group.order());
assertTrue(group.subgroups().isEmpty());
assertEquals(1, group.args().size());
OptionSpec option = (OptionSpec) group.args().iterator().next();
assertEquals("-x", option.shortestName());
assertSame(group, option.group());
assertSame(option, commandLine.getCommandSpec().findOption("-x"));
}
@Test
public void testGroupSpecBuilderExclusiveTrueByDefault() {
assertTrue(ArgGroupSpec.builder().exclusive());
}
@Test
public void testGroupSpecBuilderExclusiveMutable() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
assertTrue(builder.exclusive());
builder.exclusive(false);
assertFalse(builder.exclusive());
}
@Test
public void testGroupSpecBuilderRequiredFalseByDefault() {
assertEquals(CommandLine.Range.valueOf("0..1"), ArgGroupSpec.builder().multiplicity());
}
@Test
public void testGroupSpecBuilderRequiredMutable() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
assertEquals(CommandLine.Range.valueOf("0..1"), builder.multiplicity());
builder.multiplicity("1");
assertEquals(CommandLine.Range.valueOf("1"), builder.multiplicity());
}
@Test
public void testGroupSpecBuilderValidatesTrueByDefault() {
assertTrue(ArgGroupSpec.builder().validate());
}
@Test
public void testGroupSpecBuilderValidateMutable() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
assertTrue(builder.validate());
builder.validate(false);
assertFalse(builder.validate());
}
@Test
public void testGroupSpecBuilderSubgroupsEmptyByDefault() {
assertTrue(ArgGroupSpec.builder().subgroups().isEmpty());
}
@Test
public void testGroupSpecBuilderSubgroupsMutable() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
assertTrue(builder.subgroups().isEmpty());
ArgGroupSpec b = ArgGroupSpec.builder().addArg(PositionalParamSpec.builder().build()).build();
ArgGroupSpec c = ArgGroupSpec.builder().addArg(OptionSpec.builder("-t").build()).build();
builder.subgroups().add(b);
builder.subgroups().add(c);
assertEquals(Arrays.asList(b, c), builder.subgroups());
ArgGroupSpec x = ArgGroupSpec.builder().addArg(PositionalParamSpec.builder().build()).build();
ArgGroupSpec y = ArgGroupSpec.builder().addArg(OptionSpec.builder("-y").build()).build();
builder.subgroups().clear();
builder.addSubgroup(x).addSubgroup(y);
assertEquals(Arrays.asList(x, y), builder.subgroups());
}
@Test
public void testGroupSpecBuilderOrderMinusOneByDefault() {
assertEquals(ArgGroupSpec.DEFAULT_ORDER, ArgGroupSpec.builder().order());
}
@Test
public void testGroupSpecBuilderOrderMutable() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
assertEquals(ArgGroupSpec.DEFAULT_ORDER, builder.order());
builder.order(34);
assertEquals(34, builder.order());
}
@Test
public void testGroupSpecBuilderHeadingNullByDefault() {
assertNull(ArgGroupSpec.builder().heading());
}
@Test
public void testGroupSpecBuilderHeadingMutable() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
assertNull(builder.heading());
builder.heading("This is a header");
assertEquals("This is a header", builder.heading());
}
@Test
public void testGroupSpecBuilderHeadingKeyNullByDefault() {
assertNull(ArgGroupSpec.builder().headingKey());
}
@Test
public void testGroupSpecBuilderHeadingKeyMutable() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
assertNull(builder.headingKey());
builder.headingKey("KEY");
assertEquals("KEY", builder.headingKey());
}
@Test
public void testGroupSpecBuilderBuildDisallowsEmptyGroups() {
try {
ArgGroupSpec.builder().build();
} catch (InitializationException ok) {
assertEquals("ArgGroup has no options or positional parameters, and no subgroups: null in null", ok.getMessage());
}
}
@Test
public void testAnOptionCannotBeInMultipleGroups() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
builder.subgroups().add(ArgGroupSpec.builder().addArg(OPTION).build());
builder.subgroups().add(ArgGroupSpec.builder().multiplicity("1..*").addArg(OPTION).build());
ArgGroupSpec group = builder.build();
assertEquals(2, group.subgroups().size());
CommandSpec spec = CommandSpec.create();
try {
spec.addArgGroup(group);
fail("Expected exception");
} catch (CommandLine.DuplicateNameException ex) {
assertEquals("An option cannot be in multiple groups but -x is in (-x) and [-x]. " +
"Refactor to avoid this. For example, (-a | (-a -b)) can be rewritten " +
"as (-a [-b]), and (-a -b | -a -c) can be rewritten as (-a (-b | -c)).", ex.getMessage());
}
}
@Test
public void testGroupSpecBuilderBuildCopiesBuilderAttributes() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
builder.addArg(OPTION);
ArgGroupSpec group = builder.build();
assertTrue(group.exclusive());
assertEquals(builder.exclusive(), group.exclusive());
assertEquals(CommandLine.Range.valueOf("0..1"), group.multiplicity());
assertEquals(builder.multiplicity(), group.multiplicity());
assertTrue(group.validate());
assertEquals(builder.validate(), group.validate());
assertEquals(ArgGroupSpec.DEFAULT_ORDER, group.order());
assertEquals(builder.order(), group.order());
assertNull(group.heading());
assertEquals(builder.heading(), group.heading());
assertNull(group.headingKey());
assertEquals(builder.headingKey(), group.headingKey());
assertTrue(group.subgroups().isEmpty());
assertEquals(builder.subgroups(), group.subgroups());
assertNull(group.parentGroup());
}
@Test
public void testGroupSpecBuilderBuildCopiesBuilderAttributesNonDefault() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
builder.heading("my heading");
builder.headingKey("my headingKey");
builder.order(123);
builder.exclusive(false);
builder.validate(false);
builder.multiplicity("1");
builder.addSubgroup(ArgGroupSpec.builder().addArg(OPTION).build());
builder.addArg(OPTION);
ArgGroupSpec group = builder.build();
assertFalse(group.exclusive());
assertEquals(builder.exclusive(), group.exclusive());
assertEquals(CommandLine.Range.valueOf("1"), group.multiplicity());
assertEquals(builder.multiplicity(), group.multiplicity());
assertFalse(group.validate());
assertEquals(builder.validate(), group.validate());
assertEquals(123, group.order());
assertEquals(builder.order(), group.order());
assertEquals("my heading", group.heading());
assertEquals(builder.heading(), group.heading());
assertEquals("my headingKey", group.headingKey());
assertEquals(builder.headingKey(), group.headingKey());
assertEquals(1, group.subgroups().size());
assertEquals(builder.subgroups(), group.subgroups());
}
@Test
public void testGroupSpecToString() {
String expected = "ArgGroup[exclusive=true, multiplicity=0..1, validate=true, order=-1, args=[-x], headingKey=null, heading=null, subgroups=[]]";
ArgGroupSpec b = ArgGroupSpec.builder().addArg(OPTION).build();
assertEquals(expected, b.toString());
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
builder.heading("my heading");
builder.headingKey("my headingKey");
builder.order(123);
builder.exclusive(false);
builder.validate(false);
builder.multiplicity("1");
builder.addSubgroup(ArgGroupSpec.builder().addSubgroup(b).addArg(OPTION_A).build());
builder.addArg(PositionalParamSpec.builder().index("0..1").paramLabel("FILE").build());
String expected2 = "ArgGroup[exclusive=false, multiplicity=1, validate=false, order=123, args=[FILE], headingKey='my headingKey', heading='my heading'," +
" subgroups=[ArgGroup[exclusive=true, multiplicity=0..1, validate=true, order=-1, args=[-a], headingKey=null, heading=null," +
" subgroups=[ArgGroup[exclusive=true, multiplicity=0..1, validate=true, order=-1, args=[-x], headingKey=null, heading=null, subgroups=[]]]" +
"]]" +
"]";
assertEquals(expected2, builder.build().toString());
}
@Test
public void testGroupSpecEquals() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
builder.addArg(OPTION);
ArgGroupSpec a = builder.build();
assertEquals(a, a);
assertNotSame(a, ArgGroupSpec.builder().addArg(OPTION).build());
assertEquals(a, ArgGroupSpec.builder().addArg(OPTION).build());
OptionSpec otherOption = OptionSpec.builder("-y").build();
assertNotEquals(a, ArgGroupSpec.builder().addArg(OPTION).addArg(otherOption).build());
builder.heading("my heading");
assertNotEquals(a, builder.build());
assertEquals(builder.build(), builder.build());
builder.headingKey("my headingKey");
assertNotEquals(a, builder.build());
assertEquals(builder.build(), builder.build());
builder.order(123);
assertNotEquals(a, builder.build());
assertEquals(builder.build(), builder.build());
builder.exclusive(false);
assertNotEquals(a, builder.build());
assertEquals(builder.build(), builder.build());
builder.validate(false);
assertNotEquals(a, builder.build());
assertEquals(builder.build(), builder.build());
builder.multiplicity("1");
assertNotEquals(a, builder.build());
assertEquals(builder.build(), builder.build());
builder.addSubgroup(ArgGroupSpec.builder().addArg(OPTION).build());
assertNotEquals(a, builder.build());
assertEquals(builder.build(), builder.build());
}
@Test
public void testGroupSpecHashCode() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
builder.addArg(OPTION);
ArgGroupSpec a = builder.build();
assertEquals(a.hashCode(), a.hashCode());
assertEquals(a.hashCode(), ArgGroupSpec.builder().addArg(OPTION).build().hashCode());
OptionSpec otherOption = OptionSpec.builder("-y").build();
assertNotEquals(a.hashCode(), ArgGroupSpec.builder().addArg(OPTION).addArg(otherOption).build().hashCode());
builder.heading("my heading");
assertNotEquals(a.hashCode(), builder.build().hashCode());
assertEquals(builder.build().hashCode(), builder.build().hashCode());
builder.headingKey("my headingKey");
assertNotEquals(a.hashCode(), builder.build().hashCode());
assertEquals(builder.build().hashCode(), builder.build().hashCode());
builder.order(123);
assertNotEquals(a.hashCode(), builder.build().hashCode());
assertEquals(builder.build().hashCode(), builder.build().hashCode());
builder.exclusive(false);
assertNotEquals(a.hashCode(), builder.build().hashCode());
assertEquals(builder.build().hashCode(), builder.build().hashCode());
builder.validate(false);
assertNotEquals(a.hashCode(), builder.build().hashCode());
assertEquals(builder.build().hashCode(), builder.build().hashCode());
builder.multiplicity("1");
assertNotEquals(a.hashCode(), builder.build().hashCode());
assertEquals(builder.build().hashCode(), builder.build().hashCode());
builder.subgroups().add(ArgGroupSpec.builder().addArg(OPTION).build());
assertNotEquals(a.hashCode(), builder.build().hashCode());
assertEquals(builder.build().hashCode(), builder.build().hashCode());
}
@Test
public void testReflection() {
class All {
@Option(names = "-x", required = true) int x;
@Option(names = "-y", required = true) int y;
}
class App {
@ArgGroup All all;
}
CommandLine cmd = new CommandLine(new App(), new InnerClassFactory(this));
CommandSpec spec = cmd.getCommandSpec();
List<ArgGroupSpec> groups = spec.argGroups();
assertEquals(1, groups.size());
ArgGroupSpec group = groups.get(0);
assertNotNull(group);
List<ArgSpec> options = new ArrayList<ArgSpec>(group.args());
assertEquals(2, options.size());
assertEquals("-x", ((OptionSpec) options.get(0)).shortestName());
assertEquals("-y", ((OptionSpec) options.get(1)).shortestName());
assertNotNull(options.get(0).group());
assertSame(group, options.get(0).group());
assertNotNull(options.get(1).group());
assertSame(group, options.get(1).group());
}
@Test
public void testReflectionRequiresNonEmpty() {
class Invalid {}
class App {
@ArgGroup Invalid invalid;
}
App app = new App();
try {
new CommandLine(app, new InnerClassFactory(this));
fail("Expected exception");
} catch (InitializationException ex) {
assertEquals("ArgGroup has no options or positional parameters, and no subgroups: " +
"FieldBinding(" + Invalid.class.getName() + " " + app.getClass().getName() + ".invalid) in " +
app.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(app))
, ex.getMessage());
}
}
@Test
public void testProgrammatic() {
CommandSpec spec = CommandSpec.create();
ArgGroupSpec exclusiveSub = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-x").required(true).build())
.addArg(OptionSpec.builder("-y").required(true).build()).build();
ArgGroupSpec cooccur = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-z").required(true).build())
.addSubgroup(exclusiveSub).build();
spec.addArgGroup(cooccur);
assertNull(cooccur.parentGroup());
assertEquals(1, cooccur.subgroups().size());
assertSame(exclusiveSub, cooccur.subgroups().get(0));
assertEquals(1, cooccur.args().size());
assertNotNull(exclusiveSub.parentGroup());
assertSame(cooccur, exclusiveSub.parentGroup());
assertEquals(0, exclusiveSub.subgroups().size());
assertEquals(2, exclusiveSub.args().size());
ArgGroupSpec exclusive = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-a").required(true).build())
.addArg(OptionSpec.builder("-b").required(true).build()).build();
spec.addArgGroup(exclusive);
assertNull(exclusive.parentGroup());
assertTrue(exclusive.subgroups().isEmpty());
assertEquals(2, exclusive.args().size());
List<ArgGroupSpec> groups = spec.argGroups();
assertEquals(2, groups.size());
assertSame(cooccur, groups.get(0));
assertSame(exclusive, groups.get(1));
}
@Test
public void testCannotAddSubgroupToCommand() {
CommandSpec spec = CommandSpec.create();
ArgGroupSpec exclusiveSub = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-x").required(true).build())
.addArg(OptionSpec.builder("-y").required(true).build()).build();
ArgGroupSpec cooccur = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-z").required(true).build())
.addSubgroup(exclusiveSub).build();
try {
spec.addArgGroup(exclusiveSub);
fail("Expected exception");
} catch (InitializationException ex) {
assertEquals("Groups that are part of another group should not be added to a command. Add only the top-level group.", ex.getMessage());
}
}
@Test
public void testCannotAddSameGroupToCommandMultipleTimes() {
CommandSpec spec = CommandSpec.create();
ArgGroupSpec cooccur = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-z").required(true).build()).build();
spec.addArgGroup(cooccur);
try {
spec.addArgGroup(cooccur);
fail("Expected exception");
} catch (InitializationException ex) {
assertEquals("The specified group [-z] has already been added to the <main class> command.", ex.getMessage());
}
}
@Test
public void testIsSubgroupOf_FalseIfUnrelated() {
ArgGroupSpec other = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-z").required(true).build()).build();
ArgGroupSpec exclusiveSub = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-x").required(true).build())
.addArg(OptionSpec.builder("-y").required(true).build()).build();
ArgGroupSpec cooccur = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-z").required(true).build())
.addSubgroup(exclusiveSub).build();
assertFalse(other.isSubgroupOf(exclusiveSub));
assertFalse(other.isSubgroupOf(cooccur));
assertFalse(exclusiveSub.isSubgroupOf(other));
assertFalse(cooccur.isSubgroupOf(other));
}
@Test
public void testIsSubgroupOf_FalseIfSame() {
ArgGroupSpec other = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-z").required(true).build()).build();
assertFalse(other.isSubgroupOf(other));
}
@Test
public void testIsSubgroupOf_TrueIfChild() {
ArgGroupSpec subsub = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-a").required(true).build()).build();
ArgGroupSpec sub = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-x").required(true).build())
.addArg(OptionSpec.builder("-y").required(true).build())
.addSubgroup(subsub).build();
ArgGroupSpec top = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-z").required(true).build())
.addSubgroup(sub).build();
assertTrue(sub.isSubgroupOf(top));
assertTrue(subsub.isSubgroupOf(sub));
assertTrue(subsub.isSubgroupOf(top));
assertFalse(top.isSubgroupOf(sub));
assertFalse(top.isSubgroupOf(subsub));
assertFalse(sub.isSubgroupOf(subsub));
}
@Test
public void testValidationExclusiveMultiplicity0_1_ActualTwo() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
All all;
}
try {
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-a", "-b");
fail("Expected exception");
} catch (MutuallyExclusiveArgsException ex) {
assertEquals("Error: -a, -b are mutually exclusive (specify only one)", ex.getMessage());
}
}
@Test
public void testValidationGroups2Violation1ExclusiveMultiplicity0_1_ActualTwo() {
class Group1 {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
}
class Group2 {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
Group1 g1;
@ArgGroup(exclusive = true, multiplicity = "0..1")
Group2 g2;
}
try {
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-x", "-a", "-b");
fail("Expected exception");
} catch (MutuallyExclusiveArgsException ex) {
assertEquals("Error: -a, -b are mutually exclusive (specify only one)", ex.getMessage());
}
}
@Test
public void testValidationGroups2Violations2BothExclusiveMultiplicity0_1_ActualTwo() {
class Group1 {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
}
class Group2 {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
Group1 g1;
@ArgGroup(exclusive = true, multiplicity = "0..1")
Group2 g2;
}
try {
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-x", "-y", "-a", "-b");
fail("Expected exception");
} catch (MutuallyExclusiveArgsException ex) {
assertEquals("Error: -x, -y are mutually exclusive (specify only one)", ex.getMessage());
}
}
@Test
public void testValidationGroups2Violations0() {
class Group1 {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
}
class Group2 {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
Group1 g1;
@ArgGroup(exclusive = true, multiplicity = "0..1")
Group2 g2;
}
// no error
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-x", "-a");
}
@Test
public void testValidationExclusiveMultiplicity0_1_ActualZero() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
All all;
}
// no errors
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs();
}
@Test
public void testValidationExclusiveMultiplicity1_ActualZero() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "1")
All all;
}
try {
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs();
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument (specify one of these): (-a | -b)", ex.getMessage());
}
}
@Test
public void testValidationDependentAllRequiredMultiplicity0_1_All() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false)
All all;
}
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-a", "-b", "-c");
}
@Test
public void testValidationDependentSomeOptionalMultiplicity0_1_All() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = false) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false)
All all;
}
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-a", "-b", "-c");
}
@Test
public void testValidationDependentSomeOptionalMultiplicity0_1_OptionalOmitted() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = false) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false)
All all;
}
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-a", "-c");
}
@Test
public void testValidationDependentMultiplicity0_1_Partial() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false)
All all;
}
try {
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-a", "-b");
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): -c", ex.getMessage());
}
}
@Test
public void testValidationDependentMultiplicity0_1_Zero() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false)
All all;
}
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs();
}
@Test
public void testValidationDependentMultiplicity1_All() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "1")
All all;
}
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-a", "-b", "-c");
}
@Test
public void testValidationDependentMultiplicity1_Partial() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "1")
All all;
}
try {
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-b");
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): -a, -c", ex.getMessage());
}
}
@Test
public void testValidationDependentMultiplicity1_Zero() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "1")
All all;
}
try {
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs();
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): (-a -b -c)", ex.getMessage());
}
}
static class Excl {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
@Override
public boolean equals(Object obj) {
Excl other = (Excl) obj;
return x == other.x && y == other.y;
}
}
static class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
@Override
public boolean equals(Object obj) {
All other = (All) obj;
return a == other.a && b == other.b;
}
}
static class Composite {
@ArgGroup(exclusive = false, multiplicity = "0..1")
All all = new All();
@ArgGroup(exclusive = true, multiplicity = "1")
Excl excl = new Excl();
public Composite() {}
public Composite(boolean a, boolean b, boolean x, boolean y) {
this.all.a = a;
this.all.b = b;
this.excl.x = x;
this.excl.y = y;
}
@Override
public boolean equals(Object obj) {
Composite other = (Composite) obj;
return all.equals(other.all) && excl.equals(other.excl);
}
}
static class CompositeApp {
// SYNOPSIS: ([-a -b] | (-x | -y))
@ArgGroup(exclusive = true, multiplicity = "1")
Composite composite = new Composite();
}
static class OptionalCompositeApp {
@ArgGroup(exclusive = true, multiplicity = "0..1")
Composite composite = new Composite();
}
@Test
public void testValidationCompositeMultiplicity1() {
validateInput(new CompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -b", "-a");
validateInput(new CompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -a", "-b");
validateInput(new CompositeApp(), MaxValuesExceededException.class, "Error: expected only one match but got ([-a -b] | (-x | -y))={-x} and ([-a -b] | (-x | -y))={-y}", "-x", "-y");
validateInput(new CompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -b", "-x", "-a");
validateInput(new CompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -a", "-x", "-b");
validateInput(new CompositeApp(), MutuallyExclusiveArgsException.class, "Error: [-a -b] and (-x | -y) are mutually exclusive (specify only one)", "-a", "-x", "-b");
validateInput(new CompositeApp(), MutuallyExclusiveArgsException.class, "Error: [-a -b] and (-x | -y) are mutually exclusive (specify only one)", "-a", "-y", "-b");
// no input
validateInput(new CompositeApp(), MissingParameterException.class, "Error: Missing required argument (specify one of these): ([-a -b] | (-x | -y))");
// no error
validateInput(new CompositeApp(), null, null, "-a", "-b");
validateInput(new CompositeApp(), null, null, "-x");
validateInput(new CompositeApp(), null, null, "-y");
}
@Test
public void testValidationCompositeMultiplicity0_1() {
validateInput(new OptionalCompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -b", "-a");
validateInput(new OptionalCompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -a", "-b");
validateInput(new OptionalCompositeApp(), MaxValuesExceededException.class, "Error: expected only one match but got [[-a -b] | (-x | -y)]={-x} and [[-a -b] | (-x | -y)]={-y}", "-x", "-y");
validateInput(new OptionalCompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -b", "-x", "-a");
validateInput(new OptionalCompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -a", "-x", "-b");
validateInput(new OptionalCompositeApp(), MutuallyExclusiveArgsException.class, "Error: [-a -b] and (-x | -y) are mutually exclusive (specify only one)", "-a", "-x", "-b");
validateInput(new OptionalCompositeApp(), MutuallyExclusiveArgsException.class, "Error: [-a -b] and (-x | -y) are mutually exclusive (specify only one)", "-a", "-y", "-b");
// no input: ok because composite as a whole is optional
validateInput(new OptionalCompositeApp(), null, null);
// no error
validateInput(new OptionalCompositeApp(), null, null, "-a", "-b");
validateInput(new OptionalCompositeApp(), null, null, "-x");
validateInput(new OptionalCompositeApp(), null, null, "-y");
}
private void validateInput(Object userObject, Class<? extends Exception> exceptionClass, String errorMessage, String... args) {
try {
CommandLine.populateCommand(userObject, args);
if (exceptionClass != null) {
fail("Expected " + exceptionClass.getSimpleName() + " for " + Arrays.asList(args));
}
} catch (Exception ex) {
assertEquals(errorMessage, ex.getMessage());
assertEquals("Exception for input " + Arrays.asList(args), exceptionClass, ex.getClass());
}
}
@Test
public void testSynopsisOnlyOptions() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-a").required(true).build())
.addArg(OptionSpec.builder("-b").required(true).build())
.addArg(OptionSpec.builder("-c").required(true).build());
assertEquals("[-a | -b | -c]", builder.build().synopsis());
builder.multiplicity("1");
assertEquals("(-a | -b | -c)", builder.build().synopsis());
builder.multiplicity("2");
assertEquals("(-a | -b | -c) (-a | -b | -c)", builder.build().synopsis());
builder.multiplicity("1..3");
assertEquals("(-a | -b | -c) [-a | -b | -c] [-a | -b | -c]", builder.build().synopsis());
builder.multiplicity("1..*");
assertEquals("(-a | -b | -c)...", builder.build().synopsis());
builder.multiplicity("1");
builder.exclusive(false);
assertEquals("(-a -b -c)", builder.build().synopsis());
builder.multiplicity("0..1");
assertEquals("[-a -b -c]", builder.build().synopsis());
builder.multiplicity("0..2");
assertEquals("[-a -b -c] [-a -b -c]", builder.build().synopsis());
builder.multiplicity("0..3");
assertEquals("[-a -b -c] [-a -b -c] [-a -b -c]", builder.build().synopsis());
builder.multiplicity("0..*");
assertEquals("[-a -b -c]...", builder.build().synopsis());
}
@Test
public void testSynopsisOnlyPositionals() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder()
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG1").required(true).required(true).build())
.addArg(PositionalParamSpec.builder().index("1").paramLabel("ARG2").required(true).required(true).build())
.addArg(PositionalParamSpec.builder().index("2").paramLabel("ARG3").required(true).required(true).build());
assertEquals("[ARG1 | ARG2 | ARG3]", builder.build().synopsis());
builder.multiplicity("1");
assertEquals("(ARG1 | ARG2 | ARG3)", builder.build().synopsis());
builder.multiplicity("2");
assertEquals("(ARG1 | ARG2 | ARG3) (ARG1 | ARG2 | ARG3)", builder.build().synopsis());
builder.multiplicity("1..3");
assertEquals("(ARG1 | ARG2 | ARG3) [ARG1 | ARG2 | ARG3] [ARG1 | ARG2 | ARG3]", builder.build().synopsis());
builder.multiplicity("1..*");
assertEquals("(ARG1 | ARG2 | ARG3)...", builder.build().synopsis());
builder.multiplicity("1");
builder.exclusive(false);
assertEquals("(ARG1 ARG2 ARG3)", builder.build().synopsis());
builder.multiplicity("0..1");
assertEquals("[ARG1 ARG2 ARG3]", builder.build().synopsis());
builder.multiplicity("0..2");
assertEquals("[ARG1 ARG2 ARG3] [ARG1 ARG2 ARG3]", builder.build().synopsis());
builder.multiplicity("0..*");
assertEquals("[ARG1 ARG2 ARG3]...", builder.build().synopsis());
}
@Test
public void testSynopsisMixOptionsPositionals() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder()
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG1").required(true).build())
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG2").required(true).build())
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG3").required(true).build())
.addArg(OptionSpec.builder("-a").required(true).build())
.addArg(OptionSpec.builder("-b").required(true).build())
.addArg(OptionSpec.builder("-c").required(true).build());
assertEquals("[ARG1 | ARG2 | ARG3 | -a | -b | -c]", builder.build().synopsis());
builder.multiplicity("1");
assertEquals("(ARG1 | ARG2 | ARG3 | -a | -b | -c)", builder.build().synopsis());
builder.exclusive(false);
assertEquals("(ARG1 ARG2 ARG3 -a -b -c)", builder.build().synopsis());
builder.multiplicity("0..1");
assertEquals("[ARG1 ARG2 ARG3 -a -b -c]", builder.build().synopsis());
}
@Test
public void testSynopsisOnlyGroups() {
ArgGroupSpec.Builder b1 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-a").required(true).build())
.addArg(OptionSpec.builder("-b").required(true).build())
.addArg(OptionSpec.builder("-c").required(true).build());
ArgGroupSpec.Builder b2 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-e").required(true).build())
.addArg(OptionSpec.builder("-e").required(true).build())
.addArg(OptionSpec.builder("-f").required(true).build())
.multiplicity("1");
ArgGroupSpec.Builder b3 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-g").required(true).build())
.addArg(OptionSpec.builder("-h").required(true).build())
.addArg(OptionSpec.builder("-i").required(true).type(List.class).build())
.multiplicity("1")
.exclusive(false);
ArgGroupSpec.Builder composite = ArgGroupSpec.builder()
.addSubgroup(b1.build())
.addSubgroup(b2.build())
.addSubgroup(b3.build());
assertEquals("[[-a | -b | -c] | (-e | -f) | (-g -h -i=PARAM [-i=PARAM]...)]", composite.build().synopsis());
composite.multiplicity("1");
assertEquals("([-a | -b | -c] | (-e | -f) | (-g -h -i=PARAM [-i=PARAM]...))", composite.build().synopsis());
composite.multiplicity("1..*");
assertEquals("([-a | -b | -c] | (-e | -f) | (-g -h -i=PARAM [-i=PARAM]...))...", composite.build().synopsis());
composite.multiplicity("1");
composite.exclusive(false);
assertEquals("([-a | -b | -c] (-e | -f) (-g -h -i=PARAM [-i=PARAM]...))", composite.build().synopsis());
composite.multiplicity("0..1");
assertEquals("[[-a | -b | -c] (-e | -f) (-g -h -i=PARAM [-i=PARAM]...)]", composite.build().synopsis());
composite.multiplicity("0..*");
assertEquals("[[-a | -b | -c] (-e | -f) (-g -h -i=PARAM [-i=PARAM]...)]...", composite.build().synopsis());
}
@Test
public void testSynopsisMixGroupsOptions() {
ArgGroupSpec.Builder b1 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-a").required(true).build())
.addArg(OptionSpec.builder("-b").required(true).build())
.addArg(OptionSpec.builder("-c").required(true).build());
ArgGroupSpec.Builder b2 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-e").required(true).build())
.addArg(OptionSpec.builder("-e").required(true).build())
.addArg(OptionSpec.builder("-f").required(true).build())
.multiplicity("1");
ArgGroupSpec.Builder composite = ArgGroupSpec.builder()
.addSubgroup(b1.build())
.addSubgroup(b2.build())
.addArg(OptionSpec.builder("-x").required(true).build())
.addArg(OptionSpec.builder("-y").required(true).build())
.addArg(OptionSpec.builder("-z").required(true).build());
assertEquals("[-x | -y | -z | [-a | -b | -c] | (-e | -f)]", composite.build().synopsis());
composite.multiplicity("1");
assertEquals("(-x | -y | -z | [-a | -b | -c] | (-e | -f))", composite.build().synopsis());
composite.exclusive(false);
assertEquals("(-x -y -z [-a | -b | -c] (-e | -f))", composite.build().synopsis());
composite.multiplicity("0..1");
assertEquals("[-x -y -z [-a | -b | -c] (-e | -f)]", composite.build().synopsis());
}
@Test
public void testSynopsisMixGroupsPositionals() {
ArgGroupSpec.Builder b1 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-a").required(true).build())
.addArg(OptionSpec.builder("-b").required(false).build())
.addArg(OptionSpec.builder("-c").required(true).build());
ArgGroupSpec.Builder b2 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-e").required(false).build())
.addArg(OptionSpec.builder("-f").required(true).build())
.multiplicity("1");
ArgGroupSpec.Builder composite = ArgGroupSpec.builder()
.addSubgroup(b1.build())
.addSubgroup(b2.build())
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG1").required(true).build())
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG2").required(true).build())
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG3").required(true).build());
assertEquals("[ARG1 | ARG2 | ARG3 | [-a | -b | -c] | (-e | -f)]", composite.build().synopsis());
composite.multiplicity("1");
assertEquals("(ARG1 | ARG2 | ARG3 | [-a | -b | -c] | (-e | -f))", composite.build().synopsis());
composite.exclusive(false);
assertEquals("(ARG1 ARG2 ARG3 [-a | -b | -c] (-e | -f))", composite.build().synopsis());
composite.multiplicity("0..1");
assertEquals("[ARG1 ARG2 ARG3 [-a | -b | -c] (-e | -f)]", composite.build().synopsis());
}
@Test
public void testSynopsisMixGroupsOptionsPositionals() {
ArgGroupSpec.Builder b1 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-a").required(true).build())
.addArg(OptionSpec.builder("-b").required(true).build())
.addArg(OptionSpec.builder("-c").required(true).build());
ArgGroupSpec.Builder b2 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-e").required(true).build())
.addArg(OptionSpec.builder("-e").required(true).build())
.addArg(OptionSpec.builder("-f").required(true).build())
.multiplicity("1");
ArgGroupSpec.Builder composite = ArgGroupSpec.builder()
.addSubgroup(b1.build())
.addSubgroup(b2.build())
.addArg(OptionSpec.builder("-x").required(true).build())
.addArg(OptionSpec.builder("-y").required(true).build())
.addArg(OptionSpec.builder("-z").required(true).build())
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG1").required(true).build())
.addArg(PositionalParamSpec.builder().index("1").paramLabel("ARG2").required(true).build())
.addArg(PositionalParamSpec.builder().index("2").paramLabel("ARG3").required(true).build());
assertEquals("[-x | -y | -z | ARG1 | ARG2 | ARG3 | [-a | -b | -c] | (-e | -f)]", composite.build().synopsis());
composite.multiplicity("1");
assertEquals("(-x | -y | -z | ARG1 | ARG2 | ARG3 | [-a | -b | -c] | (-e | -f))", composite.build().synopsis());
composite.exclusive(false);
assertEquals("(-x -y -z ARG1 ARG2 ARG3 [-a | -b | -c] (-e | -f))", composite.build().synopsis());
composite.multiplicity("0..1");
assertEquals("[-x -y -z ARG1 ARG2 ARG3 [-a | -b | -c] (-e | -f)]", composite.build().synopsis());
}
static class BiGroup {
@Option(names = "-x") int x;
@Option(names = "-y") int y;
}
static class SetterMethodApp {
private BiGroup biGroup;
@ArgGroup(exclusive = false)
public void setBiGroup(BiGroup biGroup) {
this.biGroup = biGroup;
}
}
@Test
public void testGroupAnnotationOnSetterMethod() {
SetterMethodApp app = new SetterMethodApp();
CommandLine cmd = new CommandLine(app, new InnerClassFactory(this));
assertNull("before parsing", app.biGroup);
cmd.parseArgs("-x=1", "-y=2");
assertEquals(1, app.biGroup.x);
assertEquals(2, app.biGroup.y);
}
interface AnnotatedGetterInterface {
@ArgGroup(exclusive = false) BiGroup getGroup();
}
@Test
public void testGroupAnnotationOnGetterMethod() {
CommandLine cmd = new CommandLine(AnnotatedGetterInterface.class);
AnnotatedGetterInterface app = cmd.getCommand();
assertNull("before parsing", app.getGroup());
cmd.parseArgs("-x=1", "-y=2");
assertEquals(1, app.getGroup().x);
assertEquals(2, app.getGroup().y);
}
@Test
public void testUsageHelpRequiredExclusiveGroup() {
class Excl {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "1") Excl excl;
}
String expected = String.format("" +
"Usage: <main class> (-x | -y)%n" +
" -x%n" +
" -y%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testUsageHelpNonRequiredExclusiveGroup() {
class All {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
All all;
}
String expected = String.format("" +
"Usage: <main class> [-x | -y]%n" +
" -x%n" +
" -y%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testUsageHelpRequiredNonExclusiveGroup() {
class All {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "1")
All all;
}
String expected = String.format("" +
"Usage: <main class> (-x -y)%n" +
" -x%n" +
" -y%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testUsageHelpNonRequiredNonExclusiveGroup() {
class All {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "0..1")
All all;
}
String expected = String.format("" +
"Usage: <main class> [-x -y]%n" +
" -x%n" +
" -y%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testUsageHelpNonValidatingGroupDoesNotImpactSynopsis() {
class All {
@Option(names = "-x") boolean x;
@Option(names = "-y") boolean y;
}
class App {
@ArgGroup(validate = false)
All all;
}
String expected = String.format("" +
"Usage: <main class> [-xy]%n" +
" -x%n" +
" -y%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testCompositeGroupSynopsis() {
class IntXY {
@Option(names = "-x", required = true) int x;
@Option(names = "-y", required = true) int y;
}
class IntABC {
@Option(names = "-a", required = true) int a;
@Option(names = "-b", required = true) int b;
@Option(names = "-c", required = true) int c;
}
class Composite {
@ArgGroup(exclusive = false, multiplicity = "0..1")
IntABC all;
@ArgGroup(exclusive = true, multiplicity = "1")
IntXY excl;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
Composite composite;
}
String expected = String.format("" +
"Usage: <main class> [[-a=<a> -b=<b> -c=<c>] | (-x=<x> | -y=<y>)]%n" +
" -a=<a>%n" +
" -b=<b>%n" +
" -c=<c>%n" +
" -x=<x>%n" +
" -y=<y>%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testCompositeGroupSynopsisAnsi() {
class IntXY {
@Option(names = "-x", required = true) int x;
@Option(names = "-y", required = true) int y;
}
class IntABC {
@Option(names = "-a", required = true) int a;
@Option(names = "-b", required = true) int b;
@Option(names = "-c", required = true) int c;
}
class Composite {
@ArgGroup(exclusive = false, multiplicity = "0..1")
IntABC all;
@ArgGroup(exclusive = true, multiplicity = "1")
IntXY exclusive;
}
@Command
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
Composite composite;
}
String expected = String.format("" +
"Usage: @|bold <main class>|@ [[@|yellow -a|@=@|italic <a>|@ @|yellow -b|@=@|italic <b>|@ @|yellow -c|@=@|italic <c>|@] | (@|yellow -x|@=@|italic <x>|@ | @|yellow -y|@=@|italic <y>|@)]%n" +
"@|yellow |@ @|yellow -a|@=@|italic <a>|@%n" +
"@|yellow |@ @|yellow -b|@=@|italic <b>|@%n" +
"@|yellow |@ @|yellow -c|@=@|italic <c>|@%n" +
"@|yellow |@ @|yellow -x|@=@|italic <x>|@%n" +
"@|yellow |@ @|yellow -y|@=@|italic <y>|@%n");
expected = Help.Ansi.ON.string(expected);
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.ON);
assertEquals(expected, actual);
}
@Test
public void testGroupUsageHelpOptionListOptionsWithoutGroupsPrecedeGroups() {
class IntXY {
@Option(names = "-x", required = true) int x;
@Option(names = "-y", required = true) int y;
}
class IntABC {
@Option(names = "-a", required = true) int a;
@Option(names = "-b", required = true) int b;
@Option(names = "-c", required = true) int c;
}
class Composite {
@ArgGroup(exclusive = false, multiplicity = "0..1", order = 10,
heading = "Co-occurring options:%nThese options must appear together, or not at all.%n")
IntABC all;
@ArgGroup(exclusive = true, multiplicity = "1", order = 20, heading = "Exclusive options:%n")
IntXY excl;
}
class App {
@Option(names = "-A") int A;
@Option(names = "-B") boolean b;
@Option(names = "-C") boolean c;
@ArgGroup(exclusive = true, multiplicity = "0..1")
Composite composite;
@ArgGroup(validate = false, heading = "Remaining options:%n", order = 100)
Object remainder = new Object() {
@Option(names = "-D") int D;
@Option(names = "-E") boolean E;
@Option(names = "-F") boolean F;
};
}
String expected = String.format("" +
"Usage: <main class> [-BCEF] [-A=<A>] [-D=<D>] [[-a=<a> -b=<b> -c=<c>] | (-x=<x>%n" +
" | -y=<y>)]%n" +
" -A=<A>%n" +
" -B%n" +
" -C%n" +
"Co-occurring options:%n" +
"These options must appear together, or not at all.%n" +
" -a=<a>%n" +
" -b=<b>%n" +
" -c=<c>%n" +
"Exclusive options:%n" +
" -x=<x>%n" +
" -y=<y>%n" +
"Remaining options:%n" +
" -D=<D>%n" +
" -E%n" +
" -F%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Ignore("Requires support for positionals with same index in group and in command (outside the group)")
@Test
public void testGroupWithOptionsAndPositionals_multiplicity0_1() {
class Remainder {
@Option(names = "-a" , required = true) int a;
@Parameters(index = "0") File f0;
@Parameters(index = "1") File f1;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "0..1", order = 10,
heading = "Co-occurring args:%nThese options must appear together, or not at all.%n")
Remainder remainder = new Remainder();
@Parameters(index = "0") File f2;
}
String expected = String.format("" +
"Usage: <main class> [-a=<a> <f0> <f1>] <f2>%n" +
" <f2>%n" +
"Co-occurring args:%n" +
"These options must appear together, or not at all.%n" +
" <f0>%n" +
" <f1>%n" +
" -a=<a>%n");
//TestUtil.setTraceLevel("DEBUG");
CommandLine cmd = new CommandLine(new App(), new InnerClassFactory(this));
String actual = cmd.getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
ParseResult parseResult = cmd.parseArgs("FILE2");
assertTrue(parseResult.hasMatchedPositional(0));
assertEquals("<f2>", parseResult.matchedPositional(0).paramLabel());
}
@Ignore("Requires support for positionals with same index in group and in command (outside the group)")
@Test
public void testGroupWithOptionsAndPositionals_multiplicity1_2() {
class Remainder {
@Option(names = "-a" , required = true) int a;
@Parameters(index = "0") File f0;
@Parameters(index = "1") File f1;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "1..2", order = 10,
heading = "Co-occurring args:%nThese options must appear together, or not at all.%n")
Remainder remainder = new Remainder();
@Parameters(index = "0") File f2;
}
String expected = String.format("" +
"Usage: <main class> (-a=<a> <f0> <f1>) [-a=<a> <f0> <f1>] <f2>%n" +
" <f2>%n" +
"Co-occurring args:%n" +
"These options must appear together, or not at all.%n" +
" <f0>%n" +
" <f1>%n" +
" -a=<a>%n");
TestUtil.setTraceLevel("DEBUG");
CommandLine cmd = new CommandLine(new App(), new InnerClassFactory(this));
String actual = cmd.getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
ParseResult parseResult = cmd.parseArgs("-a=1", "F0", "F1", "FILE2");
assertTrue(parseResult.hasMatchedPositional(0));
assertEquals("<f2>", parseResult.matchedPositional(0).paramLabel());
}
@Ignore("This no longer works with #1027 improved support for repeatable ArgGroups with positional parameters")
@Test
public void testPositionalsInGroupAndInCommand() {
class Remainder {
@Option(names = "-a" , required = true) int a;
@Parameters(index = "0") File f0;
@Parameters(index = "1") File f1;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "1..2", order = 10,
heading = "Co-occurring args:%nThese options must appear together, or not at all.%n")
Remainder remainder = new Remainder();
@Parameters(index = "0..*") List<String> allPositionals;
}
String expected = String.format("" +
"Usage: <main class> (-a=<a> <f0> <f1>) [-a=<a> <f0> <f1>] [<allPositionals>...]%n" +
" [<allPositionals>...]%n%n" +
"Co-occurring args:%n" +
"These options must appear together, or not at all.%n" +
" <f0>%n" +
" <f1>%n" +
" -a=<a>%n");
//TestUtil.setTraceLevel("INFO");
CommandLine cmd = new CommandLine(new App(), new InnerClassFactory(this));
String actual = cmd.getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
ParseResult parseResult = cmd.parseArgs("-a=1", "F0", "F1", "FILE2");
assertTrue(parseResult.hasMatchedPositional(0));
assertEquals("<f0>", parseResult.matchedPositional(0).paramLabel());
//assertEquals("<f1>", parseResult.matchedPositional(1).paramLabel());
assertEquals("<allPositionals>", parseResult.matchedPositional(2).paramLabel());
CommandSpec spec = cmd.getCommandSpec();
PositionalParamSpec pos0 = spec.positionalParameters().get(0);
PositionalParamSpec pos1 = spec.positionalParameters().get(1);
PositionalParamSpec pos2 = spec.positionalParameters().get(2);
assertEquals("<f0>", pos0.paramLabel());
assertEquals("<allPositionals>", pos1.paramLabel());
assertEquals("<f1>", pos2.paramLabel());
assertEquals(Arrays.asList("F0", "F1", "FILE2"), pos1.stringValues());
}
@Test
public void testGroupWithMixedOptionsAndPositionals() {
class IntXY {
@Option(names = "-x", required = true) int x;
@Option(names = "-y", required = true) int y;
}
class IntABC {
@Option(names = "-a", required = true) int a;
@Parameters(index = "0") File f0;
@Parameters(index = "1") File f1;
}
class Composite {
@ArgGroup(exclusive = false, multiplicity = "0..2", order = 10,
heading = "Co-occurring options:%nThese options must appear together, or not at all.%n")
List<IntABC> all;
@ArgGroup(exclusive = true, multiplicity = "1", order = 20, heading = "Exclusive options:%n")
IntXY excl;
}
class App {
@Option(names = "-A") int A;
@Option(names = "-B") boolean B;
@Option(names = "-C") boolean C;
@ArgGroup(exclusive = true, multiplicity = "0..3")
Composite[] composite;
}
//TestUtil.setTraceLevel("DEBUG");
App app = new App();
CommandLine cmd = new CommandLine(app, new InnerClassFactory(this));
String synopsis = new Help(cmd.getCommandSpec(), Help.defaultColorScheme(Help.Ansi.OFF)).synopsis(0);
String expected = String.format("" +
"<main class> [-BC] [-A=<A>] [[-a=<a> <f0> <f1>] [-a=<a> <f0> <f1>] | (-x=<x> |%n" +
" -y=<y>)] [[-a=<a> <f0> <f1>] [-a=<a> <f0> <f1>] | (-x=<x> |%n" +
" -y=<y>)] [[-a=<a> <f0> <f1>] [-a=<a> <f0> <f1>] | (-x=<x> |%n" +
" -y=<y>)]");
assertEquals(expected, synopsis.trim());
try {
cmd.parseArgs("-x=1", "-a=1", "file0", "file1", "-y=2", "-x=3");
fail("Expected exception");
} catch (MutuallyExclusiveArgsException ex) {
assertEquals("Error: [-a=<a> <f0> <f1>] and (-x=<x> | -y=<y>) are mutually exclusive (specify only one)", ex.getMessage());
}
try {
cmd.parseArgs("-x=1", "-a=1", "file0", "file1", "-x=2", "-x=3");
fail("Expected exception");
//} catch (CommandLine.MaxValuesExceededException ex) {
//assertEquals("Error: Group: (-x=<x> | -y=<y>) can only be specified 1 times but was matched 3 times.", ex.getMessage());
} catch (MutuallyExclusiveArgsException ex) {
assertEquals("Error: [-a=<a> <f0> <f1>] and (-x=<x> | -y=<y>) are mutually exclusive (specify only one)", ex.getMessage());
}
try {
cmd.parseArgs("-x=1", "-a=1", "file0", "file1");
fail("Expected exception");
} catch (CommandLine.MutuallyExclusiveArgsException ex) {
assertEquals("Error: [-a=<a> <f0> <f1>] and (-x=<x> | -y=<y>) are mutually exclusive (specify only one)", ex.getMessage());
}
ArgGroupSpec topLevelGroup = cmd.getCommandSpec().argGroups().get(0);
assertEquals(Composite[].class, topLevelGroup.userObject().getClass());
assertSame(app.composite, topLevelGroup.userObject());
ParseResult parseResult = cmd.parseArgs("-a=1", "file0", "file1", "-a=2", "file2", "file3");
List<ParseResult.GroupMatch> multiples = parseResult.getGroupMatches();
assertEquals(1, multiples.size());
Map<ArgGroupSpec, GroupMatchContainer> matchedTopGroups = multiples.get(0).matchedSubgroups();
assertEquals(1, matchedTopGroups.size());
GroupMatchContainer topGroupMatch = matchedTopGroups.entrySet().iterator().next().getValue();
List<ParseResult.GroupMatch> topGroupMultiples = topGroupMatch.matches();
assertEquals(1, topGroupMultiples.size());
ParseResult.GroupMatch topGroupMultiple = topGroupMultiples.get(0);
Map<ArgGroupSpec, GroupMatchContainer> matchedSubGroups = topGroupMultiple.matchedSubgroups();
assertEquals(1, matchedSubGroups.size());
GroupMatchContainer subGroupMatch = matchedSubGroups.entrySet().iterator().next().getValue();
List<GroupMatch> subGroupMultiples = subGroupMatch.matches();
assertEquals(2, subGroupMultiples.size());
ParseResult.GroupMatch subMGM1 = subGroupMultiples.get(0);
assertFalse(subMGM1.isEmpty());
assertTrue(subMGM1.matchedSubgroups().isEmpty());
CommandSpec spec = cmd.getCommandSpec();
assertEquals(Arrays.asList(1), subMGM1.matchedValues(spec.findOption("-a")));
assertEquals(Arrays.asList(new File("file0")), subMGM1.matchedValues(spec.positionalParameters().get(0)));
assertEquals(Arrays.asList(new File("file1")), subMGM1.matchedValues(spec.positionalParameters().get(1)));
ParseResult.GroupMatch subMGM2 = subGroupMultiples.get(1);
assertFalse(subMGM2.isEmpty());
assertTrue(subMGM2.matchedSubgroups().isEmpty());
assertEquals(Arrays.asList(2), subMGM2.matchedValues(spec.findOption("-a")));
assertEquals(Arrays.asList(new File("file2")), subMGM2.matchedValues(spec.positionalParameters().get(0)));
assertEquals(Arrays.asList(new File("file3")), subMGM2.matchedValues(spec.positionalParameters().get(1)));
List<GroupMatchContainer> found = parseResult.findMatches(topLevelGroup);
assertSame(topGroupMatch, found.get(0));
ArgGroupSpec sub = topLevelGroup.subgroups().get(0);
assertEquals("Co-occurring options:%nThese options must appear together, or not at all.%n", sub.heading());
List<GroupMatchContainer> foundSub = parseResult.findMatches(sub);
assertEquals(1, foundSub.size());
}
@Test
public void testGroupUsageHelpOptionListOptionsGroupWithMixedOptionsAndPositionals() {
class IntXY {
@Option(names = "-x", required = true) int x;
@Option(names = "-y", required = true) int y;
}
class IntABC {
@Option(names = "-a", required = true) int a;
@Parameters(index = "0") File f0;
@Parameters(index = "1") File f1;
}
class Composite {
@ArgGroup(exclusive = false, multiplicity = "0..1", order = 10,
heading = "Co-occurring options:%nThese options must appear together, or not at all.%n")
IntABC all;
@ArgGroup(exclusive = true, multiplicity = "1", order = 20, heading = "Exclusive options:%n")
IntXY excl;
}
class App {
@Option(names = "-A") int A;
@Option(names = "-B") boolean B;
@Option(names = "-C") boolean C;
@Parameters(index = "2") File f2;
@ArgGroup(exclusive = true, multiplicity = "0..1")
Composite composite;
@ArgGroup(validate = false, heading = "Remaining options:%n", order = 100)
Object remainder = new Object() {
@Option(names = "-D") int D;
@Option(names = "-E") boolean E;
@Option(names = "-F") boolean F;
};
}
String expected = String.format("" +
"Usage: <main class> [-BCEF] [-A=<A>] [-D=<D>] [[-a=<a> <f0> <f1>] | (-x=<x> |%n" +
" -y=<y>)] <f2>%n" +
" <f2>%n" +
" -A=<A>%n" +
" -B%n" +
" -C%n" +
"Co-occurring options:%n" +
"These options must appear together, or not at all.%n" +
" <f0>%n" +
" <f1>%n" +
" -a=<a>%n" +
"Exclusive options:%n" +
" -x=<x>%n" +
" -y=<y>%n" +
"Remaining options:%n" +
" -D=<D>%n" +
" -E%n" +
" -F%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testRequiredArgsInAGroupAreNotValidated() {
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
Object exclusive = new Object() {
@Option(names = "-x", required = true) boolean x;
@ArgGroup(exclusive = false, multiplicity = "1")
Object all = new Object() {
@Option(names = "-a", required = true) int a;
@Parameters(index = "0") File f0;
};
};
}
String expected = String.format("" +
"Usage: <main class> [-x | (-a=<a> <f0>)]%n" +
" <f0>%n" +
" -a=<a>%n" +
" -x%n");
CommandLine cmd = new CommandLine(new App());
String actual = cmd.getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
cmd.parseArgs(); // no error
}
static class Mono {
@Option(names = "-a", required = true) int a;
}
static class RepeatingApp {
@ArgGroup(multiplicity = "2") List<Mono> monos;
}
@Test
public void testRepeatingGroupsSimple() {
RepeatingApp app = new RepeatingApp();
CommandLine cmd = new CommandLine(app);
ParseResult parseResult = cmd.parseArgs("-a", "1", "-a", "2");
assertEquals(2, app.monos.size());
assertEquals(1, app.monos.get(0).a);
assertEquals(2, app.monos.get(1).a);
GroupMatchContainer groupMatchContainer = parseResult.findMatches(cmd.getCommandSpec().argGroups().get(0)).get(0);
assertEquals(2, groupMatchContainer.matches().size());
ArgSpec a = cmd.getCommandSpec().findOption("-a");
ParseResult.GroupMatch multiple1 = groupMatchContainer.matches().get(0);
assertEquals(1, multiple1.matchCount(a));
List<Object> values1 = multiple1.matchedValues(a);
assertEquals(1, values1.size());
assertEquals(Integer.class, values1.get(0).getClass());
assertEquals(1, values1.get(0));
ParseResult.GroupMatch multiple2 = groupMatchContainer.matches().get(1);
assertEquals(1, multiple2.matchCount(a));
List<Object> values2 = multiple2.matchedValues(a);
assertEquals(1, values2.size());
assertEquals(Integer.class, values2.get(0).getClass());
assertEquals(2, values2.get(0));
}
@Test
public void testRepeatingGroupsValidation() {
//TestUtil.setTraceLevel("DEBUG");
RepeatingApp app = new RepeatingApp();
CommandLine cmd = new CommandLine(app);
try {
cmd.parseArgs("-a", "1");
fail("Expected exception");
} catch (CommandLine.ParameterException ex) {
assertEquals("Error: Group: (-a=<a>) must be specified 2 times but was matched 1 times", ex.getMessage());
}
}
static class RepeatingGroupWithOptionalElements635 {
@Option(names = {"-a", "--add-dataset"}, required = true) boolean add;
@Option(names = {"-d", "--dataset"} , required = true) String dataset;
@Option(names = {"-c", "--container"} , required = false) String container;
@Option(names = {"-t", "--type"} , required = false) String type;
}
@Command(name = "viewer", usageHelpWidth = 100)
static class RepeatingCompositeWithOptionalApp635 {
// SYNOPSIS: viewer (-a -d=DATASET [-c=CONTAINER] [-t=TYPE])... [-f=FALLBACK] <positional>
@ArgGroup(exclusive = false, multiplicity = "1..*")
List<RepeatingGroupWithOptionalElements635> composites;
@Option(names = "-f")
String fallback;
@Parameters(index = "0")
String positional;
}
@Test
public void testRepeatingCompositeGroupWithOptionalElements_Issue635() {
RepeatingCompositeWithOptionalApp635 app = new RepeatingCompositeWithOptionalApp635();
CommandLine cmd = new CommandLine(app);
String synopsis = new Help(cmd.getCommandSpec(), Help.defaultColorScheme(Help.Ansi.OFF)).synopsis(0);
assertEquals("viewer [-f=<fallback>] (-a -d=<dataset> [-c=<container>] [-t=<type>])... <positional>", synopsis.trim());
ParseResult parseResult = cmd.parseArgs("-a", "-d", "data1", "-a", "-d=data2", "-c=contain2", "-t=typ2", "pos", "-a", "-d=data3", "-c=contain3");
assertEquals("pos", parseResult.matchedPositionalValue(0, ""));
assertFalse(parseResult.hasMatchedOption("-f"));
GroupMatchContainer groupMatchContainer = parseResult.findMatches(cmd.getCommandSpec().argGroups().get(0)).get(0);
assertEquals(3, groupMatchContainer.matches().size());
CommandSpec spec = cmd.getCommandSpec();
List<String> data = Arrays.asList("data1", "data2", "data3");
List<String> contain = Arrays.asList(null, "contain2", "contain3");
List<String> type = Arrays.asList(null, "typ2", null);
for (int i = 0; i < 3; i++) {
ParseResult.GroupMatch multiple = groupMatchContainer.matches().get(i);
assertEquals(Arrays.asList(data.get(i)), multiple.matchedValues(spec.findOption("-d")));
if (contain.get(i) == null) {
assertEquals(Collections.emptyList(), multiple.matchedValues(spec.findOption("-c")));
} else {
assertEquals(Arrays.asList(contain.get(i)), multiple.matchedValues(spec.findOption("-c")));
}
if (type.get(i) == null) {
assertEquals(Collections.emptyList(), multiple.matchedValues(spec.findOption("-t")));
} else {
assertEquals(Arrays.asList(type.get(i)), multiple.matchedValues(spec.findOption("-t")));
}
}
assertEquals(3, app.composites.size());
for (int i = 0; i < 3; i++) {
assertEquals(data.get(i), app.composites.get(i).dataset);
assertEquals(contain.get(i), app.composites.get(i).container);
assertEquals(type.get(i), app.composites.get(i).type);
}
assertNull(app.fallback);
assertEquals("pos", app.positional);
}
static class RepeatingGroup635 {
@Option(names = {"-a", "--add-dataset"}, required = true) boolean add;
@Option(names = {"-c", "--container"} , required = true) String container;
@Option(names = {"-d", "--dataset"} , required = true) String dataset;
@Option(names = {"-t", "--type"} , required = true) String type;
}
@Command(name = "viewer", usageHelpWidth = 100)
static class RepeatingCompositeApp635 {
// SYNOPSIS: viewer (-a -d=DATASET -c=CONTAINER -t=TYPE)... [-f=FALLBACK] <positional>
@ArgGroup(exclusive = false, multiplicity = "1..*")
List<RepeatingGroup635> composites;
@Option(names = "-f")
String fallback;
@Parameters(index = "0")
String positional;
}
@Test
public void testRepeatingCompositeGroup_Issue635() {
RepeatingCompositeApp635 app = new RepeatingCompositeApp635();
CommandLine cmd = new CommandLine(app);
String synopsis = new Help(cmd.getCommandSpec(), Help.defaultColorScheme(Help.Ansi.OFF)).synopsis(0);
assertEquals("viewer [-f=<fallback>] (-a -c=<container> -d=<dataset> -t=<type>)... <positional>", synopsis.trim());
ParseResult parseResult = cmd.parseArgs("-a", "-d", "data1", "-c=contain1", "-t=typ1", "-a", "-d=data2", "-c=contain2", "-t=typ2", "pos", "-a", "-d=data3", "-c=contain3", "-t=type3");
assertEquals("pos", parseResult.matchedPositionalValue(0, ""));
assertFalse(parseResult.hasMatchedOption("-f"));
ParseResult.GroupMatchContainer groupMatchContainer = parseResult.findMatches(cmd.getCommandSpec().argGroups().get(0)).get(0);
assertEquals(3, groupMatchContainer.matches().size());
CommandSpec spec = cmd.getCommandSpec();
List<String> data = Arrays.asList("data1", "data2", "data3");
List<String> contain = Arrays.asList("contain1", "contain2", "contain3");
List<String> type = Arrays.asList("typ1", "typ2", "type3");
for (int i = 0; i < 3; i++) {
ParseResult.GroupMatch multiple = groupMatchContainer.matches().get(i);
assertEquals(Arrays.asList(data.get(i)), multiple.matchedValues(spec.findOption("-d")));
assertEquals(Arrays.asList(contain.get(i)), multiple.matchedValues(spec.findOption("-c")));
assertEquals(Arrays.asList(type.get(i)), multiple.matchedValues(spec.findOption("-t")));
}
assertEquals(3, app.composites.size());
for (int i = 0; i < 3; i++) {
assertEquals(data.get(i), app.composites.get(i).dataset);
assertEquals(contain.get(i), app.composites.get(i).container);
assertEquals(type.get(i), app.composites.get(i).type);
}
assertNull(app.fallback);
assertEquals("pos", app.positional);
}
@Command(name = "abc")
static class OptionPositionalCompositeApp {
@ArgGroup(exclusive = false, validate = true, multiplicity = "1..*",
heading = "This is the options list heading (See #450)", order = 1)
List<OptionPositionalComposite> compositeArguments;
}
static class OptionPositionalComposite {
@Option(names = "--mode", required = true) String mode;
@Parameters(index = "0") String file;
}
@Test
public void testOptionPositionalComposite() {
OptionPositionalCompositeApp app = new OptionPositionalCompositeApp();
CommandLine cmd = new CommandLine(app);
String synopsis = new Help(cmd.getCommandSpec(), Help.defaultColorScheme(Help.Ansi.OFF)).synopsis(0);
assertEquals("abc (--mode=<mode> <file>)...", synopsis.trim());
ParseResult parseResult = cmd.parseArgs("--mode", "mode1", "/file/1", "--mode", "mode2", "/file/2", "--mode=mode3", "/file/3");
List<String> data = Arrays.asList("mode1", "mode2", "mode3");
List<String> file = Arrays.asList("/file/1", "/file/2", "/file/3");
assertEquals(3, app.compositeArguments.size());
for (int i = 0; i < 3; i++) {
assertEquals(data.get(i), app.compositeArguments.get(i).mode);
assertEquals(file.get(i), app.compositeArguments.get(i).file);
}
ParseResult.GroupMatchContainer groupMatchContainer = parseResult.findMatches(cmd.getCommandSpec().argGroups().get(0)).get(0);
assertEquals(3, groupMatchContainer.matches().size());
CommandSpec spec = cmd.getCommandSpec();
for (int i = 0; i < 3; i++) {
assertEquals(Arrays.asList(data.get(i)), groupMatchContainer.matches().get(i).matchedValues(spec.findOption("--mode")));
assertEquals(Arrays.asList(file.get(i)), groupMatchContainer.matches().get(i).matchedValues(spec.positionalParameters().get(0)));
}
}
@Test
public void testMultipleGroups() {
class MultiGroup {
// SYNOPSIS: [--mode=<mode> <file>]...
@ArgGroup(exclusive = false, multiplicity = "*")
OptionPositionalComposite[] optPos;
// SYNOPSIS: [-a -d=DATASET -c=CONTAINER -t=TYPE]
@ArgGroup(exclusive = false)
List<RepeatingGroup635> composites;
}
MultiGroup app = new MultiGroup();
CommandLine cmd = new CommandLine(app);
String synopsis = new Help(cmd.getCommandSpec(), Help.defaultColorScheme(Help.Ansi.OFF)).synopsis(0);
String expectedSynopsis = String.format("" +
"<main class> [--mode=<mode> <file>]... [-a -c=<container> -d=<dataset>%n" +
" -t=<type>]");
assertEquals(expectedSynopsis, synopsis.trim());
ParseResult parseResult = cmd.parseArgs("--mode=mode1", "/file/1", "-a", "-d=data1", "-c=contain1", "-t=typ1", "--mode=mode2", "/file/2");
List<ParseResult.GroupMatch> multiples = parseResult.getGroupMatches();
assertEquals(1, multiples.size());
GroupMatch groupMatch = multiples.get(0);
assertEquals(2, groupMatch.matchedSubgroups().size());
List<ArgGroupSpec> argGroups = cmd.getCommandSpec().argGroups();
ArgGroupSpec modeGroup = argGroups.get(0);
ArgGroupSpec addDatasetGroup = argGroups.get(1);
GroupMatchContainer modeGroupMatchContainer = groupMatch.matchedSubgroups().get(modeGroup);
assertEquals(2, modeGroupMatchContainer.matches().size());
GroupMatchContainer addDatasetGroupMatchContainer = groupMatch.matchedSubgroups().get(addDatasetGroup);
assertEquals(1, addDatasetGroupMatchContainer.matches().size());
}
static class CompositeGroupDemo {
@ArgGroup(exclusive = false, multiplicity = "1..*")
List<Composite> composites;
static class Composite {
@ArgGroup(exclusive = false, multiplicity = "0..1")
Dependent dependent;
@ArgGroup(exclusive = true, multiplicity = "1")
Exclusive exclusive;
}
static class Dependent {
@Option(names = "-a", required = true)
int a;
@Option(names = "-b", required = true)
int b;
@Option(names = "-c", required = true)
int c;
}
static class Exclusive {
@Option(names = "-x", required = true)
boolean x;
@Option(names = "-y", required = true)
boolean y;
@Option(names = "-z", required = true)
boolean z;
}
}
@Test
public void testCompositeDemo() {
CompositeGroupDemo example = new CompositeGroupDemo();
CommandLine cmd = new CommandLine(example);
cmd.parseArgs("-x", "-a=1", "-b=1", "-c=1", "-a=2", "-b=2", "-c=2", "-y");
assertEquals(2, example.composites.size());
CompositeGroupDemo.Composite c1 = example.composites.get(0);
assertTrue(c1.exclusive.x);
assertEquals(1, c1.dependent.a);
assertEquals(1, c1.dependent.b);
assertEquals(1, c1.dependent.c);
CompositeGroupDemo.Composite c2 = example.composites.get(1);
assertTrue(c2.exclusive.y);
assertEquals(2, c2.dependent.a);
assertEquals(2, c2.dependent.b);
assertEquals(2, c2.dependent.c);
}
@Test
public void testIssue1053NPE() {
CompositeGroupDemo example = new CompositeGroupDemo();
CommandLine cmd = new CommandLine(example);
cmd.parseArgs("-a 1 -b 1 -c 1 -x -z".split(" "));
assertEquals(2, example.composites.size());
CompositeGroupDemo.Composite c1 = example.composites.get(0);
assertTrue(c1.exclusive.x);
assertFalse(c1.exclusive.y);
assertFalse(c1.exclusive.z);
assertEquals(1, c1.dependent.a);
assertEquals(1, c1.dependent.b);
assertEquals(1, c1.dependent.c);
CompositeGroupDemo.Composite c2 = example.composites.get(1);
assertFalse(c2.exclusive.x);
assertFalse(c2.exclusive.y);
assertTrue(c2.exclusive.z);
assertNull(c2.dependent);
}
static class Issue1054 {
@ArgGroup(exclusive = false, multiplicity = "1..*")
private List<Modification> modifications = null;
private static class Modification {
@Option(names = { "-f", "--find" }, required = true)
public Pattern findPattern = null;
@ArgGroup(exclusive = true, multiplicity = "1")
private Change change = null;
}
private static class Change {
@Option(names = { "-d", "--delete" }, required = true)
public boolean delete = false;
@Option(names = { "-w", "--replace-with" }, required = true)
public String replacement = null;
}
}
//@Ignore
@Test // https://github.com/remkop/picocli/issues/1054
public void testIssue1054() {
//-f pattern1 -f pattern2 -d --> accepted --> wrong: findPattern = "pattern2", "pattern1" is lost/ignored
try {
//TestUtil.setTraceLevel("DEBUG");
Issue1054 bean3 = new Issue1054();
new CommandLine(bean3).parseArgs("-f pattern1 -f pattern2 -d".split(" "));
//System.out.println(bean3);
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): (-d | -w=<replacement>)", ex.getMessage());
}
}
@Test
public void testIssue1054Variation() {
try {
Issue1054 bean3 = new Issue1054();
new CommandLine(bean3).parseArgs("-f pattern1 -f pattern2".split(" "));
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): (-d | -w=<replacement>)", ex.getMessage());
}
}
@Test // https://github.com/remkop/picocli/issues/1054
public void testIssue1054RegressionTest() {
//-f pattern -d --> accepted --> ok
Issue1054 bean1 = new Issue1054();
new CommandLine(bean1).parseArgs("-f pattern -d".split(" "));
assertEquals(1, bean1.modifications.size());
assertEquals("pattern", bean1.modifications.get(0).findPattern.pattern());
assertTrue(bean1.modifications.get(0).change.delete);
assertNull(bean1.modifications.get(0).change.replacement);
//-f pattern -w text --> accepted --> ok
Issue1054 bean2 = new Issue1054();
new CommandLine(bean2).parseArgs("-f pattern -w text".split(" ")); // also mentioned in #1055
assertEquals(1, bean2.modifications.size());
assertEquals("pattern", bean2.modifications.get(0).findPattern.pattern());
assertFalse(bean2.modifications.get(0).change.delete);
assertEquals("text", bean2.modifications.get(0).change.replacement);
//-f pattern -d -w text --> error --> ok
try {
new CommandLine(new Issue1054()).parseArgs("-f pattern -d -w text".split(" "));
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --find=<findPattern>", ex.getMessage());
}
//-d -f pattern -w text --> error --> ok
try {
new CommandLine(new Issue1054()).parseArgs("-d -f pattern -w text".split(" "));
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --find=<findPattern>", ex.getMessage());
}
}
@Test // https://github.com/remkop/picocli/issues/1055
public void testIssue1055Case1() {
//-f -f -w text --> accepted --> wrong: findPattern = "-f", means, the second -f is treated as an option-parameter for the first -f
try {
Issue1054 bean = new Issue1054();
new CommandLine(bean).parseArgs("-f -f -w text".split(" "));
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Expected parameter for option '--find' but found '-f'", ex.getMessage());
}
}
@Test // https://github.com/remkop/picocli/issues/1055
public void testIssue1055Case2() {
//-f pattern -w -d --> wrong: replacement = "-d", means -d is treated as an option-parameter for -w
try {
Issue1054 bean = new Issue1054();
new CommandLine(bean).parseArgs("-f pattern -w -d".split(" "));
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Expected parameter for option '--replace-with' but found '-d'", ex.getMessage());
}
}
static class CompositeGroupSynopsisDemo {
@ArgGroup(exclusive = false, multiplicity = "2..*")
List<Composite> composites;
static class Composite {
@ArgGroup(exclusive = false, multiplicity = "1")
Dependent dependent;
@ArgGroup(exclusive = true, multiplicity = "1")
Exclusive exclusive;
}
static class Dependent {
@Option(names = "-a", required = true)
int a;
@Option(names = "-b", required = true)
int b;
@Option(names = "-c", required = true)
int c;
}
static class Exclusive {
@Option(names = "-x", required = true)
boolean x;
@Option(names = "-y", required = true)
boolean y;
@Option(names = "-z", required = true)
boolean z;
}
}
@Test
public void testCompositeSynopsisDemo() {
CompositeGroupSynopsisDemo example = new CompositeGroupSynopsisDemo();
CommandLine cmd = new CommandLine(example);
String synopsis = cmd.getCommandSpec().argGroups().get(0).synopsis();
assertEquals("((-a=<a> -b=<b> -c=<c>) (-x | -y | -z)) ((-a=<a> -b=<b> -c=<c>) (-x | -y | -z))...", synopsis);
}
// https://github.com/remkop/picocli/issues/635
@Command(name = "test-composite")
static class TestComposite {
@ArgGroup(exclusive = false, multiplicity = "0..*")
List<OuterGroup> outerList;
static class OuterGroup {
@Option(names = "--add-group", required = true) boolean addGroup;
@ArgGroup(exclusive = false, multiplicity = "1")
Inner inner;
static class Inner {
@Option(names = "--option1", required = true) String option1;
@Option(names = "--option2", required = true) String option2;
}
}
}
@Test // https://github.com/remkop/picocli/issues/655
public void testCompositeValidation() {
TestComposite app = new TestComposite();
CommandLine cmd = new CommandLine(app);
try {
cmd.parseArgs("--add-group", "--option2=1");
fail("Expect exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --option1=<option1>", ex.getMessage());
}
try {
cmd.parseArgs("--add-group");
fail("Expect exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): (--option1=<option1> --option2=<option2>)", ex.getMessage());
}
try {
cmd.parseArgs("--add-group", "--option2=1", "--option2=1");
fail("Expect exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --option1=<option1>", ex.getMessage());
}
try {
cmd.parseArgs("--add-group", "--option2=1", "--option1=1", "--add-group", "--option2=1");
fail("Expect exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --option1=<option1>", ex.getMessage());
}
try {
ParseResult parseResult = cmd.parseArgs("--add-group", "--option2=1", "--option1=1", "--add-group");
fail("Expect exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): (--option1=<option1> --option2=<option2>)", ex.getMessage());
}
}
@Test
public void testHelp() {
@Command(name = "abc", mixinStandardHelpOptions = true)
class App {
@ArgGroup(multiplicity = "1")
Composite composite;
}
CommandLine commandLine = new CommandLine(new App());
ParseResult parseResult = commandLine.parseArgs("--help");
assertTrue(parseResult.isUsageHelpRequested());
}
@Command(name = "ArgGroupsTest", resourceBundle = "picocli.arggroup-localization")
static class LocalizedCommand {
@Option(names = {"-q", "--quiet"}, required = true)
static boolean quiet;
@ArgGroup(exclusive = true, multiplicity = "1", headingKey = "myKey")
LocalizedGroup datasource;
static class LocalizedGroup {
@Option(names = "-a", required = true)
static boolean isA;
@Option(names = "-b", required = true)
static File dataFile;
}
}
@Test
public void testArgGroupHeaderLocalization() {
CommandLine cmd = new CommandLine(new LocalizedCommand());
String expected = String.format("" +
"Usage: ArgGroupsTest -q (-a | -b=<dataFile>)%n" +
" -q, --quiet My description for option quiet%n" +
"My heading text%n" +
" -a My description for exclusive option a%n" +
" -b=<dataFile>%n");
String actual = cmd.getUsageMessage();
assertEquals(expected, actual);
}
@Command(name = "ArgGroupsTest")
static class TestCommand implements Runnable {
@ArgGroup( exclusive = true)
DataSource datasource;
static class DataSource {
@Option(names = "-a", required = true, defaultValue = "Strings.gxl")
static String aString;
}
public void run() { }
}
@Test
public void testIssue661StackOverflow() {
CommandLine cmd = new CommandLine(new TestCommand());
cmd.parseArgs("-a=Foo");
cmd.setExecutionStrategy(new CommandLine.RunAll()).execute();
}
// TODO add tests with positional interactive params in group
// TODO add tests with positional params in multiple groups
static class Issue722 {
static class Level1Argument {
@Option(names = "--level-1", required = true)
private String l1;
@ArgGroup(exclusive = false, multiplicity = "1")
private Level2aArgument level2a;
@ArgGroup(exclusive = false, multiplicity = "1")
private Level2bArgument level2b;
}
static class Level2aArgument {
@Option(names = "--level-2a", required = true)
private String l2a;
}
static class Level2bArgument {
@Option(names = "--level-2b", required = true)
private String l2b;
@ArgGroup(exclusive = false, multiplicity = "1")
private Level3aArgument level3a;
@ArgGroup(exclusive = false, multiplicity = "1")
private Level3bArgument level3b;
}
static class Level3aArgument {
@Option(names = "--level-3a", required = true)
private String l3a;
}
static class Level3bArgument {
@Option(names = { "--level-3b"}, required = true)
private String l3b;
}
@Command(name = "arg-group-test", separator = " ", subcommands = {CreateCommand.class, CommandLine.HelpCommand.class})
public static class ArgGroupCommand implements Runnable {
public void run() {
}
}
@Command(name = "create", separator = " ", helpCommand = true)
public static class CreateCommand implements Runnable {
@Option(names = "--level-0", required = true)
private String l0;
@ArgGroup(exclusive = false, multiplicity = "1")
private Level1Argument level1 = new Level1Argument();
public void run() {
}
}
}
// https://github.com/remkop/picocli/issues/722
@Test
public void testIssue722() {
String expected = String.format("" +
"create --level-0 <l0> (--level-1 <l1> (--level-2a <l2a>) (--level-2b <l2b>%n" +
" (--level-3a <l3a>) (--level-3b <l3b>)))%n");
CommandLine cmd = new CommandLine(new Issue722.CreateCommand());
Help help = new Help(cmd.getCommandSpec(), Help.defaultColorScheme(Help.Ansi.OFF));
String actual = help.synopsis(0);
assertEquals(expected, actual);
}
@Command(name = "ArgGroupsTest")
static class CommandWithSplitGroup {
@ArgGroup(exclusive = false)
DataSource datasource;
static class DataSource {
@Option(names = "-single", split = ",")
int single;
@Option(names = "-array", split = ",")
int[] array;
}
}
@Test
// https://github.com/remkop/picocli/issues/745
public void testIssue745SplitErrorMessageIfValidationDisabled() {
CommandWithSplitGroup bean = new CommandWithSplitGroup();
System.setProperty("picocli.ignore.invalid.split", "");
CommandLine cmd = new CommandLine(bean);
// split attribute is honoured if option type is multi-value (array, Collection, Map)
cmd.parseArgs("-array=1,2");
assertArrayEquals(new int[] {1, 2}, bean.datasource.array);
// split attribute is ignored if option type is single value
// error because value cannot be assigned to type `int`
try {
cmd.parseArgs("-single=1,2");
fail("Expected exception");
} catch (ParameterException ex) {
assertEquals("Invalid value for option '-single': '1,2' is not an int", ex.getMessage());
}
// split attribute ignored for simple commands without argument groups
try {
new CommandLine(new CommandWithSplitGroup.DataSource()).parseArgs("-single=1,2");
fail("Expected exception");
} catch (ParameterException ex) {
assertEquals("Invalid value for option '-single': '1,2' is not an int", ex.getMessage());
}
}
@Test
// https://github.com/remkop/picocli/issues/745
public void testIssue745SplitDisallowedForSingleValuedOption() {
CommandWithSplitGroup bean = new CommandWithSplitGroup();
try {
new CommandLine(bean);
fail("Expected exception");
} catch (InitializationException ex) {
assertEquals("Only multi-value options and positional parameters should have a split regex (this check can be disabled by setting system property 'picocli.ignore.invalid.split')", ex.getMessage());
}
try {
new CommandLine(new CommandWithSplitGroup.DataSource());
fail("Expected initialization exception");
} catch (InitializationException ex) {
assertEquals("Only multi-value options and positional parameters should have a split regex (this check can be disabled by setting system property 'picocli.ignore.invalid.split')", ex.getMessage());
}
}
@Command(name = "ArgGroupsTest")
static class CommandWithDefaultValue {
@ArgGroup(exclusive = false)
InitializedGroup initializedGroup = new InitializedGroup();
@ArgGroup(exclusive = false)
DeclaredGroup declaredGroup;
static class InitializedGroup {
@Option(names = "-staticX", arity = "0..1", defaultValue = "999", fallbackValue = "-88" )
static int staticX;
@Option(names = "-instanceX", arity = "0..1", defaultValue = "999", fallbackValue = "-88" )
int instanceX;
}
static class DeclaredGroup {
@Option(names = "-staticY", arity = "0..1", defaultValue = "999", fallbackValue = "-88" )
static Integer staticY;
@Option(names = "-instanceY", arity = "0..1", defaultValue = "999", fallbackValue = "-88" )
Integer instanceY;
}
}
@Test
// https://github.com/remkop/picocli/issues/746
public void test746DefaultValue() {
//TestUtil.setTraceLevel("DEBUG");
CommandWithDefaultValue bean = new CommandWithDefaultValue();
CommandLine cmd = new CommandLine(bean);
cmd.parseArgs();
assertEquals(999, bean.initializedGroup.instanceX);
assertEquals(999, CommandWithDefaultValue.InitializedGroup.staticX);
assertNull(bean.declaredGroup);
assertNull(CommandWithDefaultValue.DeclaredGroup.staticY);
}
static class Issue746 {
static class Level1Argument {
@Option(names = "--l1a", required = true, defaultValue = "l1a")
private String l1a;
@Option(names = "--l1b", required = true)
private String l1b;
@ArgGroup(exclusive = false, multiplicity = "1")
private Level2Argument level2;
}
static class Level2Argument {
@Option(names = "--l2a", required = true, defaultValue = "l2a")
private String l2a;
@Option(names = "--l2b", required = true)
private String l2b;
@ArgGroup(exclusive = false, multiplicity = "1")
private Level3Argument level3;
}
static class Level3Argument {
@Option(names = "--l3a", required = true)
private String l3a;
@Option(names = { "--l3b"}, required = true, defaultValue = "l3b")
private String l3b;
}
@Command(name = "arg-group-test", subcommands = {CreateCommand.class, CommandLine.HelpCommand.class})
public static class ArgGroupCommand implements Runnable {
public void run() { }
}
@Command(name = "create", helpCommand = true)
public static class CreateCommand implements Runnable {
@Option(names = "--l0", required = true, defaultValue = "l0")
private String l0;
@ArgGroup(exclusive = false, multiplicity = "0..1")
private Level1Argument level1 = new Level1Argument();
public void run() { }
}
}
@Test
// https://github.com/remkop/picocli/issues/746
public void testIssue746DefaultValueWithNestedArgGroups() {
Issue746.CreateCommand bean = new Issue746.CreateCommand();
CommandLine cmd = new CommandLine(bean);
cmd.parseArgs();
assertEquals("l0", bean.l0);
assertEquals("l1a", bean.level1.l1a);
assertNull(bean.level1.l1b);
assertNull(bean.level1.level2);
}
@Test
// https://github.com/remkop/picocli/issues/746
public void testIssue746ArgGroupWithDefaultValuesSynopsis() {
String expected = String.format("" +
"create [--l0=<l0>] [[--l1a=<l1a>] --l1b=<l1b> ([--l2a=<l2a>] --l2b=<l2b>%n" +
" (--l3a=<l3a> [--l3b=<l3b>]))]%n");
CommandLine cmd = new CommandLine(new Issue746.CreateCommand());
Help help = new Help(cmd.getCommandSpec(), Help.defaultColorScheme(Help.Ansi.OFF));
String actual = help.synopsis(0);
assertEquals(expected, actual);
}
@Test
// https://github.com/remkop/picocli/issues/746
public void testIssue746ArgGroupWithDefaultValuesParsing() {
Issue746.CreateCommand bean = new Issue746.CreateCommand();
CommandLine cmd = new CommandLine(bean);
cmd.parseArgs("--l1b=L1B --l2b=L2B --l3a=L3A".split(" "));
assertEquals("default value", "l0", bean.l0);
assertNotNull(bean.level1);
assertEquals("default value", "l1a", bean.level1.l1a);
assertEquals("specified value", "L1B", bean.level1.l1b);
assertNotNull(bean.level1.level2);
assertEquals("default value", "l2a", bean.level1.level2.l2a);
assertEquals("specified value", "L2B", bean.level1.level2.l2b);
assertNotNull(bean.level1.level2.level3);
assertEquals("default value", "l3b", bean.level1.level2.level3.l3b);
assertEquals("specified value", "L3A", bean.level1.level2.level3.l3a);
}
@Command(name = "Issue742")
static class Issue742 {
@ArgGroup(exclusive = false, multiplicity = "2")
List<DataSource> datasource;
static class DataSource {
@Option(names = "-g", required = true, defaultValue = "e")
String aString;
}
}
@Test
// https://github.com/remkop/picocli/issues/742
public void testIssue742FalseErrorMessage() {
//TestUtil.setTraceLevel("DEBUG");
CommandLine cmd = new CommandLine(new Issue742());
ParseResult parseResult = cmd.parseArgs("-g=2", "-g=3");
List<ParseResult.GroupMatch> multiples = parseResult.getGroupMatches();
assertEquals(1, multiples.size());
GroupMatch groupMatch = multiples.get(0);
assertEquals(1, groupMatch.matchedSubgroups().size());
ArgGroupSpec dsGroup = cmd.getCommandSpec().argGroups().get(0);
@SuppressWarnings("unchecked")
List<Issue742.DataSource> datasources = (List<Issue742.DataSource>) dsGroup.userObject();
assertEquals(2, datasources.size());
Issue742.DataSource ds1 = datasources.get(0);
assertEquals("2", ds1.aString);
Issue742.DataSource ds2 = datasources.get(1);
assertEquals("3", ds2.aString);
GroupMatchContainer modeGroupMatchContainer = groupMatch.matchedSubgroups().get(dsGroup);
assertEquals(2, modeGroupMatchContainer.matches().size());
GroupMatch dsGroupMatch1 = modeGroupMatchContainer.matches().get(0);
assertEquals(0, dsGroupMatch1.matchedSubgroups().size());
assertEquals(Arrays.asList("2"), dsGroupMatch1.matchedValues(dsGroup.args().iterator().next()));
GroupMatch dsGroupMatch2 = modeGroupMatchContainer.matches().get(1);
assertEquals(0, dsGroupMatch2.matchedSubgroups().size());
assertEquals(Arrays.asList("3"), dsGroupMatch2.matchedValues(dsGroup.args().iterator().next()));
}
@Command(name = "ExecuteTest")
static class Issue758 {
@ArgGroup(exclusive = false)
static D d;
static class D {
@Option(names = "p")
static int p1;
@Option(names = "p")
static int p2;
}
}
@Test
public void testIssue758() {
Issue758 app = new Issue758();
try {
new CommandLine(app);
} catch (DuplicateOptionAnnotationsException ex) {
String name = Issue758.D.class.getName();
String msg = "Option name 'p' is used by both field static int " + name + ".p2 and field static int " + name + ".p1";
assertEquals(msg, ex.getMessage());
}
}
static class Issue807Command {
@ArgGroup(validate = false, heading = "%nGlobal options:%n")
protected GlobalOptions globalOptions = new GlobalOptions();
static class GlobalOptions {
@Option(names = "-s", description = "ssss")
boolean slowClock = false;
@Option(names = "-v", description = "vvvv")
boolean verbose = false;
}
}
@Test
public void testIssue807Validation() {
// should not throw MutuallyExclusiveArgsException
new CommandLine(new Issue807Command()).parseArgs("-s", "-v");
}
static class Issue807SiblingCommand {
@ArgGroup(validate = true, heading = "%nValidating subgroup options:%n")
protected ValidatingOptions validatingOptions = new ValidatingOptions();
@ArgGroup(validate = false, heading = "%nGlobal options:%n")
protected Issue807Command globalOptions = new Issue807Command();
static class ValidatingOptions {
@Option(names = "-x", description = "xxx")
boolean x = false;
@Option(names = "-y", description = "yyy")
boolean y = false;
}
}
@Test
public void testIssue807SiblingValidation() {
try {
new CommandLine(new Issue807SiblingCommand()).parseArgs("-s", "-v", "-x", "-y");
fail("Expected mutually exclusive args exception");
} catch (MutuallyExclusiveArgsException ex) {
assertEquals("Error: -x, -y are mutually exclusive (specify only one)", ex.getMessage());
}
}
static class Issue807NestedCommand {
@ArgGroup(validate = false, heading = "%nNon-validating over-arching group:%n")
protected Combo nonValidating = new Combo();
static class Combo {
@ArgGroup(validate = true, heading = "%nValidating subgroup options:%n")
protected ValidatingOptions validatingOptions = new ValidatingOptions();
@ArgGroup(validate = true, heading = "%nGlobal options:%n")
protected Issue807Command globalOptions = new Issue807Command();
}
static class ValidatingOptions {
@Option(names = "-x", description = "xxx")
boolean x = false;
@Option(names = "-y", description = "yyy")
boolean y = false;
}
}
@Test
public void testIssue807NestedValidation() {
// should not throw MutuallyExclusiveArgsException
new CommandLine(new Issue807NestedCommand()).parseArgs("-s", "-v", "-x", "-y");
}
static class Issue829Group {
int x;
int y;
@Option(names = "-x") void x(int x) {this.x = x;}
@Option(names = "-y") void y(int y) {this.y = y;}
}
@Command(subcommands = Issue829Subcommand.class)
static class Issue829TopCommand {
@ArgGroup Issue829Group group;
@Command
void sub2(@ArgGroup Issue829Group group) {
assertEquals(0, group.x);
assertEquals(3, group.y);
}
}
@Command(name = "sub")
static class Issue829Subcommand {
@ArgGroup List<Issue829Group> group;
}
@Test
public void testIssue829NPE_inSubcommandWithArgGroup() {
//TestUtil.setTraceLevel("DEBUG");
ParseResult parseResult = new CommandLine(new Issue829TopCommand()).parseArgs("-x=1", "sub", "-y=2");
assertEquals(1, ((Issue829TopCommand)parseResult.commandSpec().userObject()).group.x);
Issue829Subcommand sub = (Issue829Subcommand) parseResult.subcommand().commandSpec().userObject();
assertEquals(0, sub.group.get(0).x);
assertEquals(2, sub.group.get(0).y);
new CommandLine(new Issue829TopCommand()).parseArgs("sub2", "-y=3");
}
static class Issue815Group {
@Option(names = {"--age"})
Integer age;
@Option(names = {"--id"})
List<String> id;
}
static class Issue815 {
@ArgGroup(exclusive = false, multiplicity = "1")
Issue815Group group;
}
@Test
public void testIssue815() {
//TestUtil.setTraceLevel("DEBUG");
Issue815 userObject = new Issue815();
new CommandLine(userObject).parseArgs("--id=123", "--id=456");
assertNotNull(userObject.group);
assertNull(userObject.group.age);
assertNotNull(userObject.group.id);
assertEquals(Arrays.asList("123", "456"), userObject.group.id);
}
static class Issue810Command {
@ArgGroup(validate = false, heading = "%nGrouped options:%n")
MyGroup myGroup = new MyGroup();
static class MyGroup {
@Option(names = "-s", description = "ssss", required = true, defaultValue = "false")
boolean s = false;
@Option(names = "-v", description = "vvvv", required = true, defaultValue = "false")
boolean v = false;
}
}
@Test
public void testIssue810Validation() {
// should not throw MutuallyExclusiveArgsException
Issue810Command app = new Issue810Command();
new CommandLine(app).parseArgs("-s", "-v");
assertTrue(app.myGroup.s);
assertTrue(app.myGroup.v);
// app = new Issue810Command();
new CommandLine(app).parseArgs("-s");
assertTrue(app.myGroup.s);
assertFalse(app.myGroup.v);
new CommandLine(app).parseArgs("-v");
assertFalse(app.myGroup.s);
assertTrue(app.myGroup.v);
}
static class Issue810WithExplicitExclusiveGroup {
@ArgGroup(exclusive = true, validate = false, heading = "%nGrouped options:%n")
MyGroup myGroup = new MyGroup();
static class MyGroup {
@Option(names = "-s", required = true)
boolean s = false;
@Option(names = "-v", required = true)
boolean v = false;
}
}
@Test
public void testNonValidatingOptionsAreNotExclusive() {
CommandSpec spec = CommandSpec.forAnnotatedObject(new Issue810Command());
assertFalse(spec.argGroups().get(0).exclusive());
CommandSpec spec2 = CommandSpec.forAnnotatedObject(new Issue810WithExplicitExclusiveGroup());
assertFalse(spec2.argGroups().get(0).exclusive());
}
static class Issue839Defaults {
@ArgGroup(validate = false)
Group group;
static class Group {
@Option(names = "-a", description = "a. Default-${DEFAULT-VALUE}")
String a = "aaa";
@Option(names = "-b", defaultValue = "bbb", description = "b. Default-${DEFAULT-VALUE}")
String b;
}
}
@Ignore
@Test
public void testIssue839Defaults() {
Issue839Defaults app = new Issue839Defaults();
String actual = new CommandLine(app).getUsageMessage(Help.Ansi.OFF);
String expected = String.format("" +
"Usage: <main class> [-a=<a>] [-b=<b>]%n" +
" -a=<a> a. Default-aaa%n" +
" -b=<b> b. Default-bbb%n");
assertEquals(expected, actual);
}
static class Issue870Group {
@Option(names = {"--group"}, required = true) String name;
@Option(names = {"--opt1"}) int opt1;
@Option(names = {"--opt2"}) String opt2;
}
static class Issue870App {
@ArgGroup(exclusive = false, multiplicity = "0..*")
List<Issue870Group> groups;
}
@Test
public void testIssue870RequiredOptionValidation() {
try {
new CommandLine(new Issue870App()).parseArgs("--opt1=1");
fail("Expected MissingParameterException");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --group=<name>", ex.getMessage());
}
}
static class ExclusiveBooleanGroup871 {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
//@Option(names = "--opt") String opt;
}
@Test
public void testMultivalueExclusiveBooleanGroup() {
class MyApp {
@ArgGroup(exclusive = true, multiplicity = "0..*")
List<ExclusiveBooleanGroup871> groups;
}
MyApp myApp = CommandLine.populateCommand(new MyApp(), "-a", "-b");
assertEquals(2, myApp.groups.size());
MyApp myApp2 = CommandLine.populateCommand(new MyApp(), "-b", "-a");
assertEquals(2, myApp2.groups.size());
}
static class ExclusiveStringOptionGroup871 {
@Option(names = "-a", required = false) String a;
@Option(names = "-b", required = true) String b;
@Option(names = "--opt") String opt;
}
@Test
public void testAllOptionsRequiredInExclusiveGroup() {
class MyApp {
@ArgGroup(exclusive = true)
ExclusiveStringOptionGroup871 group;
}
CommandLine cmd = new CommandLine(new MyApp());
List<ArgGroupSpec> argGroupSpecs = cmd.getCommandSpec().argGroups();
assertEquals(1, argGroupSpecs.size());
for (ArgSpec arg : argGroupSpecs.get(0).args()) {
assertTrue(arg.required());
}
}
@Test
public void testMultivalueExclusiveStringOptionGroup() {
class MyApp {
@ArgGroup(exclusive = true, multiplicity = "0..*")
List<ExclusiveStringOptionGroup871> groups;
}
MyApp myApp = CommandLine.populateCommand(new MyApp(), "-a=1", "-b=2");
assertEquals(2, myApp.groups.size());
MyApp myApp2 = CommandLine.populateCommand(new MyApp(), "-b=1", "-a=2");
assertEquals(2, myApp2.groups.size());
}
static class NonExclusiveGroup871 {
@Option(names = "-a", required = false) String a;
@Option(names = "-b", required = false) String b;
@Option(names = "-c") String c; // default is not required
public String toString() {
return String.format("a=%s, b=%s, c=%s", a, b, c);
}
}
@Ignore //https://github.com/remkop/picocli/issues/871
@Test
public void testNonExclusiveGroupMustHaveOneRequiredOption() {
class MyApp {
@ArgGroup(exclusive = false)
NonExclusiveGroup871 group;
}
CommandLine cmd = new CommandLine(new MyApp());
List<ArgGroupSpec> argGroupSpecs = cmd.getCommandSpec().argGroups();
assertEquals(1, argGroupSpecs.size());
int requiredCount = 0;
for (ArgSpec arg : argGroupSpecs.get(0).args()) {
if (arg.required()) {
requiredCount++;
}
}
assertTrue(requiredCount > 0);
}
@Test
public void testNonExclusiveGroupWithoutRequiredOption() {
class MyApp {
@ArgGroup(exclusive = false)
NonExclusiveGroup871 group;
}
CommandLine cmd = new CommandLine(new MyApp());
MyApp myApp1 = CommandLine.populateCommand(new MyApp(), "-a=1");
//System.out.println(myApp1.group);
assertEquals("1", myApp1.group.a);
assertNull(myApp1.group.b);
assertNull(myApp1.group.c);
MyApp myApp2 = CommandLine.populateCommand(new MyApp(), "-b=1", "-a=2");
//System.out.println(myApp2.group);
assertEquals("2", myApp2.group.a);
assertEquals("1", myApp2.group.b);
assertNull(myApp2.group.c);
MyApp myApp3 = CommandLine.populateCommand(new MyApp(), "-c=1", "-a=2");
//System.out.println(myApp3.group);
assertEquals("2", myApp3.group.a);
assertEquals("1", myApp3.group.c);
assertNull(myApp3.group.b);
MyApp myApp4 = CommandLine.populateCommand(new MyApp(), "-c=1", "-b=2");
//System.out.println(myApp4.group);
assertEquals("2", myApp4.group.b);
assertEquals("1", myApp4.group.c);
assertNull(myApp4.group.a);
MyApp myApp5 = CommandLine.populateCommand(new MyApp(), "-c=1");
//System.out.println(myApp5.group);
assertNull(myApp5.group.b);
assertEquals("1", myApp5.group.c);
assertNull(myApp5.group.a);
MyApp myApp6 = CommandLine.populateCommand(new MyApp());
//System.out.println(myApp6.group);
assertNull(myApp6.group);
}
static class Issue933 implements Runnable {
@ArgGroup(exclusive = true, multiplicity = "1")
private ExclusiveOption1 exclusiveOption1;
static class ExclusiveOption1 {
@Option(names = { "-a" })
private String optionA;
@Option(names = { "-b" })
private String optionB;
}
@ArgGroup(exclusive = true, multiplicity = "1")
private ExclusiveOption2 exclusiveOption2;
static class ExclusiveOption2 {
@Option(names = { "-c" })
private String optionC;
@Option(names = { "-d" })
private String optionD;
}
public static void main(String[] args) {
System.exit(new CommandLine(new Issue933()).execute(args));
}
public void run() {
System.out.println("TestBugCLI.run()");
}
}
@Test
public void testIssue933() {
//new CommandLine(new Issue933()).execute("-a A -b B -c C".split(" "));
//System.out.println("OK");
Supplier<CommandLine> supplier = new Supplier<CommandLine>() {
public CommandLine get() { return new CommandLine(new Issue933()); }};
Execution execution = Execution.builder(supplier).execute("-a A -c C -d D".split(" "));
String expected = String.format("" +
"Error: -c=<optionC>, -d=<optionD> are mutually exclusive (specify only one)%n" +
"Usage: <main class> (-a=<optionA> | -b=<optionB>) (-c=<optionC> | -d=<optionD>)%n" +
" -a=<optionA>%n" +
" -b=<optionB>%n" +
" -c=<optionC>%n" +
" -d=<optionD>%n");
execution.assertSystemErr(expected);
}
static class Issue938NestedMutualDependency {
static class OtherOptions {
@Option(
names = {"-o1", "--other-option-1"},
arity = "1",
required = true)
private String first;
@Option(
names = {"-o2", "--other-option-2"},
arity = "1",
required = true)
private String second;
}
static class MySwitchableOptions {
@Option(
names = {"-more", "--enable-more-options"},
arity = "0",
required = true)
private boolean tlsEnabled = false;
@ArgGroup(exclusive = false)
private OtherOptions options;
}
@Command(name = "mutual-dependency")
static class FullCommandLine {
@ArgGroup(exclusive = false)
private MySwitchableOptions switchableOptions;
}
}
@Test
public void testIssue938NestedMutualDependency() {
final CommandLine commandLine = new CommandLine(new Issue938NestedMutualDependency.FullCommandLine());
//commandLine.usage(System.out);
// Ideally this would PASS (and the switchableOptions would be null)
commandLine.parseArgs("--enable-more-options");
// Should fail as other-option-2 is not set (and defined as required)
try {
commandLine.parseArgs("--enable-more-options", "--other-option-1=firstString");
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --other-option-2=<second>", ex.getMessage());
}
try {
// Ideally this would FAIL (as the --enable-more-options is not set
commandLine.parseArgs("--other-option-1=firstString", "--other-option-2=secondString");
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --enable-more-options", ex.getMessage());
}
}
@Test
public void testGroupValidationResult_extractBlockingFailure() {
GroupValidationResult block = new GroupValidationResult(GroupValidationResult.Type.FAILURE_PRESENT);
List<GroupValidationResult> list = Arrays.asList(
GroupValidationResult.SUCCESS_PRESENT, GroupValidationResult.SUCCESS_ABSENT, block);
assertSame(block, GroupValidationResult.extractBlockingFailure(list));
assertNull(GroupValidationResult.extractBlockingFailure(Arrays.asList(
GroupValidationResult.SUCCESS_PRESENT, GroupValidationResult.SUCCESS_ABSENT)));
}
@Test
public void testGroupValidationResult_present() {
assertTrue(GroupValidationResult.SUCCESS_PRESENT.present());
assertFalse(GroupValidationResult.SUCCESS_ABSENT.present());
assertFalse(new GroupValidationResult(GroupValidationResult.Type.FAILURE_PRESENT).present());
assertFalse(new GroupValidationResult(GroupValidationResult.Type.FAILURE_ABSENT).present());
}
@Test
public void testGroupValidationResult_toString() {
assertEquals("SUCCESS_PRESENT", GroupValidationResult.SUCCESS_PRESENT.toString());
assertEquals("SUCCESS_ABSENT", GroupValidationResult.SUCCESS_ABSENT.toString());
assertEquals("FAILURE_PRESENT", new GroupValidationResult(GroupValidationResult.Type.FAILURE_PRESENT).toString());
assertEquals("FAILURE_ABSENT", new GroupValidationResult(GroupValidationResult.Type.FAILURE_ABSENT).toString());
CommandLine cmd = new CommandLine(CommandSpec.create());
ParameterException ex = new ParameterException(cmd, "hello");
assertEquals("FAILURE_ABSENT: hello", new GroupValidationResult(GroupValidationResult.Type.FAILURE_ABSENT, ex).toString());
}
@Command(name = "Issue940")
static class Issue940Command {
@ArgGroup MyArgGroup myArgGroup;// = new MyArgGroup();
private static class MyArgGroup {
@Option(names = {"--no-header"}, negatable = true)
boolean header;
}
}
@Test
public void testIssue940NegatableOptionInArgGroupGivesNPE() {
new CommandLine(new Issue940Command());
}
@Command(name = "974", mixinStandardHelpOptions = true, version = "1.0")
static class Issue974AnnotatedCommandMethod {
static class Exclusive {
@Option(names = "-a", description = "a", required = true) String a;
@Option(names = "-b", description = "b", required = true) String b;
}
int generateX;
int generateY;
Exclusive generateExclusive;
@Command(name = "generate", description = "Generate")
void generate(@Option(names = "-x", description = "x", required = true) int x,
@Option(names = "-y", description = "y", required = true) int y,
@ArgGroup Exclusive e) {
this.generateX = x;
this.generateY = y;
this.generateExclusive = e;
}
}
@Test
public void testIssue974CommandMethodWithoutGroup() {
String[] args = "generate -x=1 -y=2".split(" ");
Issue974AnnotatedCommandMethod bean = new Issue974AnnotatedCommandMethod();
new CommandLine(bean).execute(args);
assertEquals(1, bean.generateX);
assertEquals(2, bean.generateY);
assertNull(bean.generateExclusive);
}
@Test
public void testIssue974CommandMethodWithGroup() {
String[] args = "generate -x=1 -y=2 -a=xyz".split(" ");
Issue974AnnotatedCommandMethod bean = new Issue974AnnotatedCommandMethod();
new CommandLine(bean).execute(args);
assertEquals(1, bean.generateX);
assertEquals(2, bean.generateY);
assertNotNull(bean.generateExclusive);
assertEquals("xyz", bean.generateExclusive.a);
assertNull(bean.generateExclusive.b);
}
@Command static class SomeMixin {
@Option(names = "-i") int anInt;
@Option(names = "-L") long aLong;
public SomeMixin() {}
public SomeMixin(int i, long aLong) { this.anInt = i; this.aLong = aLong; }
@Override
public boolean equals(Object obj) {
SomeMixin other = (SomeMixin) obj;
return anInt == other.anInt && aLong == other.aLong;
}
}
@picocli.CommandLine.Command
static class CommandMethodsWithGroupsAndMixins {
enum InvokedSub { withMixin, posAndMixin, posAndOptAndMixin, groupFirst}
EnumSet<InvokedSub> invoked = EnumSet.noneOf(InvokedSub.class);
SomeMixin myMixin;
Composite myComposite;
int[] myPositionalInt;
String[] myStrings;
@Command(mixinStandardHelpOptions = true)
void withMixin(@Mixin SomeMixin mixin, @ArgGroup(multiplicity = "0..1") Composite composite) {
this.myMixin = mixin;
this.myComposite = composite;
invoked.add(withMixin);
}
@Command(mixinStandardHelpOptions = true)
void posAndMixin(int[] posInt, @ArgGroup(multiplicity = "0..1") Composite composite, @Mixin SomeMixin mixin) {
this.myMixin = mixin;
this.myComposite = composite;
this.myPositionalInt = posInt;
invoked.add(InvokedSub.posAndMixin);
}
@Command(mixinStandardHelpOptions = true)
void posAndOptAndMixin(int[] posInt, @Option(names = "-s") String[] strings, @Mixin SomeMixin mixin, @ArgGroup(multiplicity = "0..1") Composite composite) {
this.myMixin = mixin;
this.myComposite = composite;
this.myPositionalInt = posInt;
this.myStrings = strings;
invoked.add(InvokedSub.posAndOptAndMixin);
}
@Command(mixinStandardHelpOptions = true)
void groupFirst(@ArgGroup(multiplicity = "0..1") Composite composite, @Mixin SomeMixin mixin, int[] posInt, @Option(names = "-s") String[] strings) {
this.myMixin = mixin;
this.myComposite = composite;
this.myPositionalInt = posInt;
this.myStrings = strings;
invoked.add(InvokedSub.groupFirst);
}
}
@Test
public void testCommandMethod_withMixin_help() {
final CommandMethodsWithGroupsAndMixins bean = new CommandMethodsWithGroupsAndMixins();
Supplier<CommandLine> supplier = new Supplier<CommandLine>() {
public CommandLine get() { return new CommandLine(bean); }};
Execution execution = Execution.builder(supplier).execute("withMixin -h".split(" "));
execution.assertSystemOut(String.format("" +
"Usage: <main class> withMixin [-hV] [-i=<anInt>] [-L=<aLong>] [[-a -b] | (-x |%n" +
" -y)]%n" +
" -a%n" +
" -b%n" +
" -h, --help Show this help message and exit.%n" +
" -i=<anInt>%n" +
" -L=<aLong>%n" +
" -V, --version Print version information and exit.%n" +
" -x%n" +
" -y%n"));
}
@Test
public void testCommandMethod_posAndMixin_help() {
final CommandMethodsWithGroupsAndMixins bean = new CommandMethodsWithGroupsAndMixins();
Supplier<CommandLine> supplier = new Supplier<CommandLine>() {
public CommandLine get() { return new CommandLine(bean); }};
Execution execution = Execution.builder(supplier).execute("posAndMixin -h".split(" "));
execution.assertSystemOut(String.format("" +
"Usage: <main class> posAndMixin [-hV] [-i=<anInt>] [-L=<aLong>] [[-a -b] | (-x%n" +
" | -y)] [<arg0>...]%n" +
" [<arg0>...]%n" +
" -a%n" +
" -b%n" +
" -h, --help Show this help message and exit.%n" +
" -i=<anInt>%n" +
" -L=<aLong>%n" +
" -V, --version Print version information and exit.%n" +
" -x%n" +
" -y%n"));
}
@Test
public void testCommandMethod_posAndOptAndMixin_help() {
final CommandMethodsWithGroupsAndMixins bean = new CommandMethodsWithGroupsAndMixins();
Supplier<CommandLine> supplier = new Supplier<CommandLine>() {
public CommandLine get() { return new CommandLine(bean); }};
Execution execution = Execution.builder(supplier).execute("posAndOptAndMixin -h".split(" "));
execution.assertSystemOut(String.format("" +
"Usage: <main class> posAndOptAndMixin [-hV] [-i=<anInt>] [-L=<aLong>]%n" +
" [-s=<arg1>]... [[-a -b] | (-x | -y)]%n" +
" [<arg0>...]%n" +
" [<arg0>...]%n" +
" -a%n" +
" -b%n" +
" -h, --help Show this help message and exit.%n" +
" -i=<anInt>%n" +
" -L=<aLong>%n" +
" -s=<arg1>%n" +
" -V, --version Print version information and exit.%n" +
" -x%n" +
" -y%n"));
}
@Test
public void testCommandMethod_groupFirst_help() {
final CommandMethodsWithGroupsAndMixins bean = new CommandMethodsWithGroupsAndMixins();
Supplier<CommandLine> supplier = new Supplier<CommandLine>() {
public CommandLine get() { return new CommandLine(bean); }};
Execution execution = Execution.builder(supplier).execute("groupFirst -h".split(" "));
execution.assertSystemOut(String.format("" +
"Usage: <main class> groupFirst [-hV] [-i=<anInt>] [-L=<aLong>] [-s=<arg3>]...%n" +
" [[-a -b] | (-x | -y)] [<arg2>...]%n" +
" [<arg2>...]%n" +
" -a%n" +
" -b%n" +
" -h, --help Show this help message and exit.%n" +
" -i=<anInt>%n" +
" -L=<aLong>%n" +
" -s=<arg3>%n" +
" -V, --version Print version information and exit.%n" +
" -x%n" +
" -y%n"));
}
// TODO GroupMatch.container()
// TODO GroupMatch.matchedMaxElements()
// TODO GroupMatch.matchedFully()
@Command(name = "ami", description = "ami description", customSynopsis = "ami [OPTIONS]")
static class Issue988 {
@ArgGroup(exclusive = true, /*heading = "",*/ order = 9)
ProjectOrTreeOptions projectOrTreeOptions = new ProjectOrTreeOptions();
@ArgGroup(validate = false, heading = "General Options:%n", order = 30)
GeneralOptions generalOptions = new GeneralOptions();
static class ProjectOrTreeOptions {
@ArgGroup(exclusive = false, multiplicity = "0..1",
heading = "CProject Options:%n", order = 10)
CProjectOptions cProjectOptions = new CProjectOptions();
@ArgGroup(exclusive = false, multiplicity = "0..1",
heading = "CTree Options:%n", order = 20)
CTreeOptions cTreeOptions = new CTreeOptions();
}
static class CProjectOptions {
@Option(names = {"-p", "--cproject"}, paramLabel = "DIR",
description = "The CProject (directory) to process. The cProject name is the basename of the file."
)
protected String cProjectDirectory = null;
protected static class TreeOptions {
@Option(names = {"-r", "--includetree"}, paramLabel = "DIR", order = 12,
arity = "1..*",
description = "Include only the specified CTrees."
)
protected String[] includeTrees;
@Option(names = {"-R", "--excludetree"}, paramLabel = "DIR", order = 13,
arity = "1..*",
description = "Exclude the specified CTrees."
)
protected String[] excludeTrees;
}
@ArgGroup(exclusive = true, multiplicity = "0..1", order = 11/*, heading = ""*/)
TreeOptions treeOptions = new TreeOptions();
}
static class CTreeOptions {
@Option(names = {"-t", "--ctree"}, paramLabel = "DIR",
description = "The CTree (directory) to process. The cTree name is the basename of the file."
)
protected String cTreeDirectory = null;
protected static class BaseOptions {
@Option(names = {"-b", "--includebase"}, paramLabel = "PATH", order = 22,
arity = "1..*",
description = "Include child files of cTree (only works with --ctree)."
)
protected String[] includeBase;
@Option(names = {"-B", "--excludebase"}, paramLabel = "PATH",
order = 23,
arity = "1..*",
description = "Exclude child files of cTree (only works with --ctree)."
)
protected String[] excludeBase;
}
@ArgGroup(exclusive = true, multiplicity = "0..1", /*heading = "",*/ order = 21)
BaseOptions baseOptions = new BaseOptions();
}
static class GeneralOptions {
@Option(names = {"-i", "--input"}, paramLabel = "FILE",
description = "Input filename (no defaults)"
)
protected String input = null;
@Option(names = {"-n", "--inputname"}, paramLabel = "PATH",
description = "User's basename for input files (e.g. foo/bar/<basename>.png) or directories."
)
protected String inputBasename;
}
}
@Test //https://github.com/remkop/picocli/issues/988
public void testIssue988OptionGroupSectionsShouldIncludeSubgroupOptions() {
String expected = String.format("" +
"Usage: ami [OPTIONS]%n" +
"ami description%n" +
"CProject Options:%n" +
" -p, --cproject=DIR The CProject (directory) to process. The cProject%n" +
" name is the basename of the file.%n" +
" -r, --includetree=DIR... Include only the specified CTrees.%n" +
" -R, --excludetree=DIR... Exclude the specified CTrees.%n" +
"CTree Options:%n" +
" -b, --includebase=PATH... Include child files of cTree (only works with%n" +
" --ctree).%n" +
" -B, --excludebase=PATH... Exclude child files of cTree (only works with%n" +
" --ctree).%n" +
" -t, --ctree=DIR The CTree (directory) to process. The cTree name%n" +
" is the basename of the file.%n" +
"General Options:%n" +
" -i, --input=FILE Input filename (no defaults)%n" +
" -n, --inputname=PATH User's basename for input files (e.g.%n" +
" foo/bar/<basename>.png) or directories.%n");
assertEquals(expected, new CommandLine(new Issue988()).getUsageMessage());
}
static class StudentGrade {
@Parameters(index = "0") String name;
@Parameters(index = "1") BigDecimal grade;
public StudentGrade() {}
public StudentGrade(String name, String grade) {
this(name, new BigDecimal(grade));
}
public StudentGrade(String name, BigDecimal grade) {
this.name = name;
this.grade = grade;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StudentGrade that = (StudentGrade) o;
return name.equals(that.name) && grade.equals(that.grade);
}
@Override
public String toString() {
return "StudentGrade{" +
"name='" + name + '\'' +
", grade=" + grade +
'}';
}
}
@Test // https://github.com/remkop/picocli/issues/1027
public void testIssue1027RepeatingPositionalParams() {
class Issue1027 {
@ArgGroup(exclusive = false, multiplicity = "1..*")
List<StudentGrade> gradeList;
}
Issue1027 bean = new Issue1027();
new CommandLine(bean).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5 Danny 4.0".split(" "));
assertEquals(4, bean.gradeList.size());
assertEquals(new StudentGrade("Abby", "4.0"), bean.gradeList.get(0));
assertEquals(new StudentGrade("Billy", "3.5"), bean.gradeList.get(1));
assertEquals(new StudentGrade("Caily", "3.5"), bean.gradeList.get(2));
assertEquals(new StudentGrade("Danny", "4.0"), bean.gradeList.get(3));
}
@Test // https://github.com/remkop/picocli/issues/1027
public void testIssue1027RepeatingPositionalParamsEdgeCase1() {
class Issue1027 {
@ArgGroup(exclusive = false, multiplicity = "4..*")
List<StudentGrade> gradeList;
}
Issue1027 bean = new Issue1027();
new CommandLine(bean).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5 Danny 4.0".split(" "));
assertEquals(4, bean.gradeList.size());
assertEquals(new StudentGrade("Abby", "4.0"), bean.gradeList.get(0));
assertEquals(new StudentGrade("Billy", "3.5"), bean.gradeList.get(1));
assertEquals(new StudentGrade("Caily", "3.5"), bean.gradeList.get(2));
assertEquals(new StudentGrade("Danny", "4.0"), bean.gradeList.get(3));
}
@Test // https://github.com/remkop/picocli/issues/1027
public void testIssue1027RepeatingPositionalParamsEdgeCase2() {
class Issue1027 {
@ArgGroup(exclusive = false, multiplicity = "1..4")
List<StudentGrade> gradeList;
}
Issue1027 bean = new Issue1027();
new CommandLine(bean).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5 Danny 4.0".split(" "));
assertEquals(4, bean.gradeList.size());
assertEquals(new StudentGrade("Abby", "4.0"), bean.gradeList.get(0));
assertEquals(new StudentGrade("Billy", "3.5"), bean.gradeList.get(1));
assertEquals(new StudentGrade("Caily", "3.5"), bean.gradeList.get(2));
assertEquals(new StudentGrade("Danny", "4.0"), bean.gradeList.get(3));
}
@Test // https://github.com/remkop/picocli/issues/1027
public void testIssue1027RepeatingPositionalParamsWithMinMultiplicity() {
class Issue1027 {
@ArgGroup(exclusive = false, multiplicity = "4..*")
List<StudentGrade> gradeList;
}
Issue1027 bean = new Issue1027();
try {
new CommandLine(bean).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5".split(" "));
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Group: (<name> <grade>) must be specified 4 times but was matched 3 times", ex.getMessage());
}
}
@Test // https://github.com/remkop/picocli/issues/1027
public void testIssue1027RepeatingPositionalParamsWithMaxMultiplicity() {
class Issue1027 {
@ArgGroup(exclusive = false, multiplicity = "1..3")
List<StudentGrade> gradeList;
}
try {
new CommandLine(new Issue1027()).parseArgs();
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): (<name> <grade>)", ex.getMessage());
}
Issue1027 bean1 = new Issue1027();
new CommandLine(bean1).parseArgs("Abby 4.0".split(" "));
assertEquals(new StudentGrade("Abby", "4.0"), bean1.gradeList.get(0));
Issue1027 bean2 = new Issue1027();
new CommandLine(bean2).parseArgs("Abby 4.0 Billy 3.5".split(" "));
assertEquals(new StudentGrade("Abby", "4.0"), bean2.gradeList.get(0));
assertEquals(new StudentGrade("Billy", "3.5"), bean2.gradeList.get(1));
Issue1027 bean3 = new Issue1027();
new CommandLine(bean3).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5".split(" "));
assertEquals(new StudentGrade("Abby", "4.0"), bean3.gradeList.get(0));
assertEquals(new StudentGrade("Billy", "3.5"), bean3.gradeList.get(1));
assertEquals(new StudentGrade("Caily", "3.5"), bean3.gradeList.get(2));
Issue1027 bean4 = new Issue1027();
try {
new CommandLine(bean4).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5 Danny 4.0".split(" "));
fail("Expected exception");
} catch (MaxValuesExceededException ex) {
assertEquals("Error: expected only one match but got (<name> <grade>) [<name> <grade>] [<name> <grade>]="
+ "{params[0]=Abby params[1]=4.0 params[0]=Billy params[1]=3.5 params[0]=Caily params[1]=3.5} and (<name> <grade>) "
+ "[<name> <grade>] [<name> <grade>]={params[0]=Danny params[1]=4.0}", ex.getMessage());
} catch (UnmatchedArgumentException ex) {
assertEquals("Unmatched arguments from index 6: 'Danny', '4.0'", ex.getMessage());
}
}
@Test
public void testMultipleGroupsWithPositional() {
class Issue1027 {
@ArgGroup(exclusive = false, multiplicity = "1..4")
List<StudentGrade> gradeList;
@ArgGroup(exclusive = false, multiplicity = "1")
List<StudentGrade> anotherList;
}
Issue1027 bean4 = new Issue1027();
new CommandLine(bean4).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5 Danny 4.0".split(" "));
assertEquals(4, bean4.gradeList.size());
assertEquals(new StudentGrade("Abby", "4.0"), bean4.gradeList.get(0));
assertEquals(new StudentGrade("Billy", "3.5"), bean4.gradeList.get(1));
assertEquals(new StudentGrade("Caily", "3.5"), bean4.gradeList.get(2));
assertEquals(new StudentGrade("Danny", "4.0"), bean4.gradeList.get(3));
assertEquals(1, bean4.anotherList.size());
assertEquals(new StudentGrade("Abby", "4.0"), bean4.anotherList.get(0));
Issue1027 bean5 = new Issue1027();
try {
new CommandLine(bean5).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5 Danny 4.0 Egon 3.5".split(" "));
fail("Expected exception");
} catch (UnmatchedArgumentException ex) {
assertEquals("Unmatched arguments from index 8: 'Egon', '3.5'", ex.getMessage());
}
}
static class InnerPositional1027 {
@Parameters(index = "0") String param00;
@Parameters(index = "1") String param01;
public InnerPositional1027() {}
public InnerPositional1027(String param00, String param01) {
this.param00 = param00;
this.param01 = param01;
}
public boolean equals(Object obj) {
if (!(obj instanceof InnerPositional1027)) { return false; }
InnerPositional1027 other = (InnerPositional1027) obj;
return TestUtil.equals(this.param00, other.param00)
&& TestUtil.equals(this.param01, other.param01);
}
}
static class Inner1027 {
@Option(names = "-y", required = true) boolean y;
@ArgGroup(exclusive = false, multiplicity = "1")
InnerPositional1027 innerPositional;
public Inner1027() {}
public Inner1027(String param0, String param1) {
this.innerPositional = new InnerPositional1027(param0, param1);
}
public boolean equals(Object obj) {
if (!(obj instanceof Inner1027)) { return false; }
Inner1027 other = (Inner1027) obj;
return TestUtil.equals(this.innerPositional, other.innerPositional);
}
}
static class Outer1027 {
@Option(names = "-x", required = true) boolean x;
@Parameters(index = "0") String param0;
@Parameters(index = "1") String param1;
@ArgGroup(exclusive = false, multiplicity = "0..*")
List<Inner1027> inners;
public Outer1027() {}
public Outer1027(String param0, String param1, List<Inner1027> inners) {
this.param0 = param0;
this.param1 = param1;
this.inners = inners;
}
public boolean equals(Object obj) {
if (!(obj instanceof Outer1027)) { return false; }
Outer1027 other = (Outer1027) obj;
return TestUtil.equals(this.param0, other.param0)
&& TestUtil.equals(this.param1, other.param1)
&& TestUtil.equals(this.inners, other.inners)
;
}
}
@Ignore
@Test
public void testNestedPositionals() {
class Nested {
@ArgGroup(exclusive = false, multiplicity = "0..*")
List<Outer1027> outers;
}
Nested bean = new Nested();
new CommandLine(bean).parseArgs("-x 0 1 -x 00 11 -y 000 111 -y 0000 1111 -x 00000 11111".split(" "));
assertEquals(3, bean.outers.size());
assertEquals(new Outer1027("0", "1", null), bean.outers.get(0));
List<Inner1027> inners = Arrays.asList(new Inner1027("000", "111"), new Inner1027("0000", "1111"));
assertEquals(new Outer1027("00", "11", inners), bean.outers.get(1));
assertEquals(new Outer1027("00000", "11111", null), bean.outers.get(2));
}
@Command(name = "MyApp")
static class Issue1065 {
@ArgGroup(exclusive = false)
MyGroup myGroup;
static class MyGroup {
@Option(names="-A", paramLabel="N", split=",") List<Long> A;
}
}
//https://stackoverflow.com/questions/61964838/picocli-list-option-used-in-arggroup-duplicated-in-short-usage-string
@Test
public void testIssue1065DuplicateSynopsis() {
String expected = String.format("" +
"Usage: MyApp [[-A=N[,N...]]...]%n" +
" -A=N[,N...]%n");
String actual = new CommandLine(new Issue1065()).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Command(name = "MyApp")
static class Issue1065ExclusiveGroup {
@ArgGroup(exclusive = true)
MyGroup myGroup;
static class MyGroup {
@Option(names="-A", paramLabel="N", split=",") List<Long> A;
}
}
//https://stackoverflow.com/questions/61964838/picocli-list-option-used-in-arggroup-duplicated-in-short-usage-string
@Test
public void testIssue1065ExclusiveGroupDuplicateSynopsis() {
String expected = String.format("" +
"Usage: MyApp [-A=N[,N...] [-A=N[,N...]]...]%n" +
" -A=N[,N...]%n");
String actual = new CommandLine(new Issue1065ExclusiveGroup()).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Command(name = "MyApp")
static class Issue1065NoSplit {
@ArgGroup(exclusive = false)
MyGroup myGroup;
static class MyGroup {
@Option(names="-A", paramLabel="N") List<Long> A;
}
}
//https://stackoverflow.com/questions/61964838/picocli-list-option-used-in-arggroup-duplicated-in-short-usage-string
@Test
public void testIssue1065DuplicateSynopsisVariant() {
String expected = String.format("" +
"Usage: MyApp [[-A=N]...]%n" +
" -A=N%n");
String actual = new CommandLine(new Issue1065NoSplit()).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Command(name = "MyApp")
static class Issue1065ExclusiveGroupNoSplit {
@ArgGroup(exclusive = true)
MyGroup myGroup;
static class MyGroup {
@Option(names="-A", paramLabel="N") List<Long> A;
}
}
//https://stackoverflow.com/questions/61964838/picocli-list-option-used-in-arggroup-duplicated-in-short-usage-string
@Test
public void testIssue1065ExclusiveGroupNoSplitDuplicateSynopsisVariant() {
String expected = String.format("" +
"Usage: MyApp [-A=N [-A=N]...]%n" +
" -A=N%n");
String actual = new CommandLine(new Issue1065ExclusiveGroupNoSplit()).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testAllOptionsNested() {
class Nested {
@ArgGroup(exclusive = false, multiplicity = "0..*")
List<Outer1027> outers;
}
List<ArgGroupSpec> argGroupSpecs = new CommandLine(new Nested()).getCommandSpec().argGroups();
assertEquals(1, argGroupSpecs.size());
ArgGroupSpec group = argGroupSpecs.get(0);
List<OptionSpec> options = group.options();
assertEquals(1, options.size());
assertEquals("-x", options.get(0).shortestName());
List<OptionSpec> allOptions = group.allOptionsNested();
assertEquals(2, allOptions.size());
assertEquals("-x", allOptions.get(0).shortestName());
assertEquals("-y", allOptions.get(1).shortestName());
}
@Test
public void testAllOptionsNested2() {
List<ArgGroupSpec> argGroupSpecs = new CommandLine(new Issue988()).getCommandSpec().argGroups();
assertEquals(2, argGroupSpecs.size());
ArgGroupSpec projectOrTreeOptionsGroup = argGroupSpecs.get(0);
List<OptionSpec> options = projectOrTreeOptionsGroup.options();
assertEquals(0, options.size());
List<OptionSpec> allOptions = projectOrTreeOptionsGroup.allOptionsNested();
assertEquals(6, allOptions.size());
assertEquals("--cproject", allOptions.get(0).longestName());
assertEquals("--includetree", allOptions.get(1).longestName());
assertEquals("--excludetree", allOptions.get(2).longestName());
assertEquals("--ctree", allOptions.get(3).longestName());
assertEquals("--includebase", allOptions.get(4).longestName());
assertEquals("--excludebase", allOptions.get(5).longestName());
ArgGroupSpec generalOptionsGroup = argGroupSpecs.get(1);
assertEquals(2, generalOptionsGroup.options().size());
assertEquals(2, generalOptionsGroup.allOptionsNested().size());
}
@Test
public void testAllPositionalParametersNested() {
class Nested {
@ArgGroup(exclusive = false, multiplicity = "0..*")
List<Outer1027> outers;
}
List<ArgGroupSpec> argGroupSpecs = new CommandLine(new Nested()).getCommandSpec().argGroups();
assertEquals(1, argGroupSpecs.size());
ArgGroupSpec group = argGroupSpecs.get(0);
List<PositionalParamSpec> positionals = group.positionalParameters();
assertEquals(2, positionals.size());
assertEquals("<param0>", positionals.get(0).paramLabel());
List<PositionalParamSpec> allPositionals = group.allPositionalParametersNested();
assertEquals(4, allPositionals.size());
assertEquals("<param0>", allPositionals.get(0).paramLabel());
assertEquals("<param1>", allPositionals.get(1).paramLabel());
assertEquals("<param00>", allPositionals.get(2).paramLabel());
assertEquals("<param01>", allPositionals.get(3).paramLabel());
}
@Test // #1061
public void testHelpForGroupWithPositionalsAndOptionsAndEndOfOptions() {
@Command(mixinStandardHelpOptions = true, showEndOfOptionsDelimiterInUsageHelp = true)
class Nested {
@ArgGroup(exclusive = false, multiplicity = "0..*")
List<Outer1027> outers;
}
String expected = String.format("" +
"Usage: <main class> [-hV] [-x <param0> <param1> [-y (<param00>%n" +
" <param01>)]...]... [--]%n" +
" <param0>%n" +
" <param00>%n" +
" <param1>%n" +
" <param01>%n" +
" -h, --help Show this help message and exit.%n" +
" -V, --version Print version information and exit.%n" +
" -x%n" +
" -y%n" +
" -- This option can be used to separate command-line options from%n" +
" the list of positional parameters.%n");
assertEquals(expected, new CommandLine(new Nested()).getUsageMessage());
}
@Test // #1061
public void testHelpForGroupWithPositionalsAndEndOfOptions() {
@Command(mixinStandardHelpOptions = true, showEndOfOptionsDelimiterInUsageHelp = true)
class Group {
@ArgGroup InnerPositional1027 inner;
}
String expected = String.format("" +
"Usage: <main class> [-hV] [--] [<param00> | <param01>]%n" +
" <param00>%n" +
" <param01>%n" +
" -h, --help Show this help message and exit.%n" +
" -V, --version Print version information and exit.%n" +
" -- This option can be used to separate command-line options from%n" +
" the list of positional parameters.%n");
assertEquals(expected, new CommandLine(new Group()).getUsageMessage());
}
static class Issue1213Arithmetic {
@ArgGroup(exclusive = false, validate = false, heading = "scan source options%n")
SourceOptions sourceOptions;
static class SourceOptions {
@Parameters(paramLabel = "FILE")
List<File> reportFiles;
@Option(names = {"-b", "--build-id"}, paramLabel = "Build ID")
List<Integer> buildIds;
@Option(names = {"-a", "--app-name"}, paramLabel = "App Name")
List<String> appNames;
}
}
@Test
public void testArithmeticException1213() {
new CommandLine(new Issue1213Arithmetic()).parseArgs("a");
Issue1213Arithmetic bean = new Issue1213Arithmetic();
new CommandLine(bean).parseArgs("a", "b");
assertEquals(Arrays.asList(new File("a"), new File("b")), bean.sourceOptions.reportFiles);
}
public static class CriteriaWithEnvironment {
private static final List<String> DYNAMIC_LIST = Arrays.asList("FOO", "BAR");
private String environment;
@Spec CommandSpec spec;
@Option(names = {"-e", "--environment"})
public void setEnvironment(String environment) {
if (!DYNAMIC_LIST.contains(environment)) {
// Should throw a ParameterException
//throw new IllegalArgumentException("Should be one of...");
throw new ParameterException(spec.commandLine(), "should be one of " + DYNAMIC_LIST);
}
this.environment = environment;
}
public String getEnvironment() {
return environment;
}
}
@Test
public void testIssue1260ArgGroupWithSpec() {
@Command(name = "issue1260")
class App {
@ArgGroup CriteriaWithEnvironment criteria;
}
//TestUtil.setTraceLevel("DEBUG");
CommandLine cmd = new CommandLine(new App());
try {
cmd.parseArgs("-e", "X");
fail("Expected exception");
} catch (ParameterException pex) {
assertEquals("should be one of [FOO, BAR]", pex.getMessage());
assertSame(cmd, pex.getCommandLine());
}
}
static class Issue1260GetterMethod {
CommandSpec spec;
@Spec CommandSpec spec() {
return spec;
}
@Option(names = "-x") int x;
}
@Ignore("Getter method in ArgGroup does not work; on interface or class")
@Test
public void testIssue1260ArgGroupWithSpecGetterMethod() {
@Command(name = "issue1260a")
class App {
@ArgGroup
Issue1260GetterMethod group;
}
//TestUtil.setTraceLevel("DEBUG");
App app = new App();
CommandLine cmd = new CommandLine(app);
cmd.parseArgs("-x", "123");
assertNotNull(app.group);
assertEquals(123, app.group.x);
assertSame(cmd.getCommandSpec(), app.group.spec());
}
static class Issue1260SetterMethod {
CommandSpec spec;
int x;
@Spec
void spec(CommandSpec spec) {
this.spec = spec;
}
@Option(names = "-x")
void setX(int x) {
if (x < 0) throw new ParameterException(spec.commandLine(), "X must be positive");
this.x = x;
}
}
@Test
public void testIssue1260ArgGroupWithSpecSetterMethod() {
@Command(name = "issue1260b")
class App {
@ArgGroup
Issue1260SetterMethod group;
}
//TestUtil.setTraceLevel("DEBUG");
App app = new App();
CommandLine cmd = new CommandLine(app);
cmd.parseArgs("-x", "3");
assertNotNull(app.group);
assertEquals(3, app.group.x);
assertSame(cmd.getCommandSpec(), app.group.spec);
try {
cmd.parseArgs("-x", "-1");
fail("Expected exception");
} catch (ParameterException pex) {
assertEquals("X must be positive", pex.getMessage());
assertSame(cmd, pex.getCommandLine());
}
}
@Command(name = "list", version = "issue 1300 1.0",
mixinStandardHelpOptions = true,
description = "list all signals")
static class Issue1300 implements Runnable {
@ArgGroup(exclusive = true, multiplicity = "1")
SearchFilterArgs searchFilterArgs;
public void run() { }
static class SearchFilterArgs {
@Option(names = {"-A", "--all"}, required = true)
boolean getAllSignals;
@Option(names = {"-m", "--message-name"}, required = true)
String messageName;
}
}
@Test
public void testIssue1300BooleanInitialization() {
PrintStream err = System.err;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream capture = new PrintStream(baos, true);
System.setErr(capture);
//TestUtil.setTraceLevel("DEBUG");
CommandLine cmd = new CommandLine(new Issue1300());
cmd.getUsageMessage(); // this causes initial values of all options to be cached
//cmd.execute(); // this prints help, which also cause initial values to be cached
//System.err.println("===");
cmd.execute("-A");
capture.flush();
System.setErr(err);
assertEquals("", baos.toString());
}
@Command(name = "CLI Test 2", mixinStandardHelpOptions = true)
static class Issue1384 {
static class MyArgGroup {
@Parameters(index = "0", arity = "1", description = "parameter 0")
String param0;
@Parameters(index = "1", arity = "0..1", description = "parameter 1")
String param1;
@Parameters(index = "2", arity = "0..1", description = "parameter 2")
String param2;
}
@ArgGroup(order = 0, exclusive = false, multiplicity = "1")
MyArgGroup argGroup;
}
@Ignore
@Test
public void testIssue1384() {
Issue1384 obj = new Issue1384();
new CommandLine(obj).parseArgs("1", "a", "b");
assertEquals(obj.argGroup.param0, "1");
assertEquals(obj.argGroup.param1, "a");
assertEquals(obj.argGroup.param2, "b");
}
/**
* Tests issue 1409 https://github.com/remkop/picocli/issues/1409
* This specific test supplies values to the group one values, leaving
* the group two values uninitialized.
* <p>
* The test verifies that x, 1A, 1B, 2A, and 2B values are correct after
* building the command using CommandLine.java and parsing the arguments.
* @author remkop, madfoal
* @version 1
* @params null
* @returns null
*
*/
@Command(name = "Issue-1409")
static class Issue1409 {
@ArgGroup(exclusive = false, heading = "%nOptions to be used with group 1 OR group 2 options.%n")
OptXAndGroupOneOrGroupTwo optXAndGroupOneOrGroupTwo = new OptXAndGroupOneOrGroupTwo();
static class OptXAndGroupOneOrGroupTwo {
@Option(names = { "-x", "--option-x" }, required = true, defaultValue = "Default X", description = "option X")
String x;
@ArgGroup(exclusive = true)
OneOrTwo oneORtwo = new OneOrTwo();
}
static class OneOrTwo {
@ArgGroup(exclusive = false, heading = "%nGroup 1%n%n")
GroupOne one = new GroupOne();
@ArgGroup(exclusive = false, heading = "%nGroup 2%n%n")
GroupTwo two = new GroupTwo();
}
static class GroupOne {
@Option(names = { "-1a", "--option-1a" },required=true,description = "option A of group 1")
String _1a;
@Option(names = { "-1b", "--option-1b" },required=true,description = "option B of group 1")
String _1b;
}
static class GroupTwo {
@Option(names = { "-2a", "--option-2a" },required=true, defaultValue = "Default 2A", description = "option A of group 2")
private String _2a = "Default 2A";
@Option(names = { "-2b", "--option-2b" },required=true, defaultValue = "Default 2B", description = "option B of group 2")
private String _2b = "Default 2B";
}
}
/**
* Tests issue 1409 https://github.com/remkop/picocli/issues/1409
* This specific test supplies values to the group one values, leaving
* the group two values uninitialized.
* <p>
* The test verifies that x, 1A, 1B, 2A, and 2B values are correct after
* building the command using CommandLine.java and parsing the arguments.
* @author remkop, madfoal
* @version 1
* @params null
* @returns null
*
*/
@Test
public void testIssue1409() {
Issue1409 obj = new Issue1409();
new CommandLine(obj).parseArgs("-x", "ANOTHER_VALUE");
assertEquals("ANOTHER_VALUE", obj.optXAndGroupOneOrGroupTwo.x);
assertEquals(null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one._1a);
assertEquals(null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one._1b);
assertEquals("Default 2A", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two._2a);
assertEquals("Default 2B", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two._2b);
}
/**
* Tests issue 1409 https://github.com/remkop/picocli/issues/1409
* This specific test supplies values to the group one values, leaving
* the group two values uninitialized.
* <p>
* The test verifies that x, 1A, 1B, 2A, and 2B values are correct after
* building the command using CommandLine.java and parsing the arguments.
* @author madfoal
* @version 1
* @params null
* @returns null
*
*/
@Test
public void testIssue1409_INIT_1() {
Issue1409 obj = new Issue1409();
new CommandLine(obj).parseArgs("-x", "ANOTHER_VALUE", "-1a=x", "-1b=z");
assertEquals("ANOTHER_VALUE", obj.optXAndGroupOneOrGroupTwo.x);
assertEquals("x", obj.optXAndGroupOneOrGroupTwo.oneORtwo.one._1a);
assertEquals("z", obj.optXAndGroupOneOrGroupTwo.oneORtwo.one._1b);
assertEquals("Default 2A", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two._2a);
assertEquals("Default 2B", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two._2b);
}
/**
* Tests issue 1409 https://github.com/remkop/picocli/issues/1409
* This specific test supplies values to the group two values, leaving
* the group one values uninitialized.
* <p>
* The test verifies that x, 1A, 1B, 2A, and 2B values are correct after
* building the command using CommandLine.java and parsing the arguments.
* @author madfoal
* @version 1
* @params null
* @returns null
*
*/
@Test
public void testIssue1409_INIT_2() {
Issue1409 obj = new Issue1409();
new CommandLine(obj).parseArgs("-x", "ANOTHER_VALUE", "-2a=x", "-2b=z");
assertEquals("ANOTHER_VALUE", obj.optXAndGroupOneOrGroupTwo.x);
assertEquals(null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one._1a);
assertEquals(null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one._1b);
assertEquals("x", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two._2a);
assertEquals("z", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two._2b);
}
}
| src/test/java/picocli/ArgGroupTest.java | package picocli;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.ProvideSystemProperty;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.rules.TestRule;
import picocli.CommandLine.ArgGroup;
import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.Parameters;
import picocli.CommandLine.Mixin;
import picocli.CommandLine.Help;
import picocli.CommandLine.ParseResult;
import picocli.CommandLine.InitializationException;
import picocli.CommandLine.DuplicateOptionAnnotationsException;
import picocli.CommandLine.ParameterException;
import picocli.CommandLine.MaxValuesExceededException;
import picocli.CommandLine.MissingParameterException;
import picocli.CommandLine.MutuallyExclusiveArgsException;
import picocli.CommandLine.Model.ArgGroupSpec;
import picocli.CommandLine.Model.ArgSpec;
import picocli.CommandLine.Model.CommandSpec;
import picocli.CommandLine.Model.OptionSpec;
import picocli.CommandLine.Model.PositionalParamSpec;
import picocli.CommandLine.ParseResult.GroupMatchContainer;
import picocli.CommandLine.ParseResult.GroupMatch;
import picocli.CommandLine.ParseResult.GroupValidationResult;
import picocli.CommandLine.Spec;
import picocli.CommandLine.UnmatchedArgumentException;
import picocli.test.Execution;
import picocli.test.Supplier;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import static org.junit.Assert.*;
import static picocli.ArgGroupTest.CommandMethodsWithGroupsAndMixins.InvokedSub.withMixin;
public class ArgGroupTest {
@Rule
public final ProvideSystemProperty ansiOFF = new ProvideSystemProperty("picocli.ansi", "false");
// allows tests to set any kind of properties they like, without having to individually roll them back
@Rule
public final TestRule restoreSystemProperties = new RestoreSystemProperties();
static final OptionSpec OPTION = OptionSpec.builder("-x").required(true).build();
static final OptionSpec OPTION_A = OptionSpec.builder("-a").required(true).build();
static final OptionSpec OPTION_B = OptionSpec.builder("-b").required(true).build();
static final OptionSpec OPTION_C = OptionSpec.builder("-c").required(true).build();
@Test
public void testArgSpecHaveNoGroupsByDefault() {
assertNull(OptionSpec.builder("-x").build().group());
assertNull(PositionalParamSpec.builder().build().group());
}
@Ignore
@Test
public void testArgSpecBuilderHasNoExcludesByDefault() {
// assertTrue(OptionSpec.builder("-x").excludes().isEmpty());
// assertTrue(PositionalParamSpec.builder().excludes().isEmpty());
fail(); // TODO
}
@Ignore
@Test
public void testOptionSpecBuilderExcludesMutable() {
// OptionSpec.Builder builder = OptionSpec.builder("-x");
// assertTrue(builder.excludes().isEmpty());
//
// builder.excludes("AAA").build();
// assertEquals(1, builder.excludes().size());
// assertEquals("AAA", builder.excludes().get(0));
fail(); // TODO
}
@Ignore
@Test
public void testPositionalParamSpecBuilderExcludesMutable() {
// PositionalParamSpec.Builder builder = PositionalParamSpec.builder();
// assertTrue(builder.excludes().isEmpty());
//
// builder.excludes("AAA").build();
// assertEquals(1, builder.excludes().size());
// assertEquals("AAA", builder.excludes().get(0));
fail();
}
@Test
public void testGroupSpecBuilderFromAnnotation() {
class Args {
@Option(names = "-x") int x;
}
class App {
@ArgGroup(exclusive = false, validate = false, multiplicity = "1",
headingKey = "headingKeyXXX", heading = "headingXXX", order = 123)
Args args;
}
CommandLine commandLine = new CommandLine(new App(), new InnerClassFactory(this));
assertEquals(1, commandLine.getCommandSpec().argGroups().size());
ArgGroupSpec group = commandLine.getCommandSpec().argGroups().get(0);
assertNotNull(group);
assertEquals(false, group.exclusive());
assertEquals(false, group.validate());
assertEquals(CommandLine.Range.valueOf("1"), group.multiplicity());
assertEquals("headingKeyXXX", group.headingKey());
assertEquals("headingXXX", group.heading());
assertEquals(123, group.order());
assertTrue(group.subgroups().isEmpty());
assertEquals(1, group.args().size());
OptionSpec option = (OptionSpec) group.args().iterator().next();
assertEquals("-x", option.shortestName());
assertSame(group, option.group());
assertSame(option, commandLine.getCommandSpec().findOption("-x"));
}
@Test
public void testGroupSpecBuilderExclusiveTrueByDefault() {
assertTrue(ArgGroupSpec.builder().exclusive());
}
@Test
public void testGroupSpecBuilderExclusiveMutable() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
assertTrue(builder.exclusive());
builder.exclusive(false);
assertFalse(builder.exclusive());
}
@Test
public void testGroupSpecBuilderRequiredFalseByDefault() {
assertEquals(CommandLine.Range.valueOf("0..1"), ArgGroupSpec.builder().multiplicity());
}
@Test
public void testGroupSpecBuilderRequiredMutable() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
assertEquals(CommandLine.Range.valueOf("0..1"), builder.multiplicity());
builder.multiplicity("1");
assertEquals(CommandLine.Range.valueOf("1"), builder.multiplicity());
}
@Test
public void testGroupSpecBuilderValidatesTrueByDefault() {
assertTrue(ArgGroupSpec.builder().validate());
}
@Test
public void testGroupSpecBuilderValidateMutable() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
assertTrue(builder.validate());
builder.validate(false);
assertFalse(builder.validate());
}
@Test
public void testGroupSpecBuilderSubgroupsEmptyByDefault() {
assertTrue(ArgGroupSpec.builder().subgroups().isEmpty());
}
@Test
public void testGroupSpecBuilderSubgroupsMutable() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
assertTrue(builder.subgroups().isEmpty());
ArgGroupSpec b = ArgGroupSpec.builder().addArg(PositionalParamSpec.builder().build()).build();
ArgGroupSpec c = ArgGroupSpec.builder().addArg(OptionSpec.builder("-t").build()).build();
builder.subgroups().add(b);
builder.subgroups().add(c);
assertEquals(Arrays.asList(b, c), builder.subgroups());
ArgGroupSpec x = ArgGroupSpec.builder().addArg(PositionalParamSpec.builder().build()).build();
ArgGroupSpec y = ArgGroupSpec.builder().addArg(OptionSpec.builder("-y").build()).build();
builder.subgroups().clear();
builder.addSubgroup(x).addSubgroup(y);
assertEquals(Arrays.asList(x, y), builder.subgroups());
}
@Test
public void testGroupSpecBuilderOrderMinusOneByDefault() {
assertEquals(ArgGroupSpec.DEFAULT_ORDER, ArgGroupSpec.builder().order());
}
@Test
public void testGroupSpecBuilderOrderMutable() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
assertEquals(ArgGroupSpec.DEFAULT_ORDER, builder.order());
builder.order(34);
assertEquals(34, builder.order());
}
@Test
public void testGroupSpecBuilderHeadingNullByDefault() {
assertNull(ArgGroupSpec.builder().heading());
}
@Test
public void testGroupSpecBuilderHeadingMutable() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
assertNull(builder.heading());
builder.heading("This is a header");
assertEquals("This is a header", builder.heading());
}
@Test
public void testGroupSpecBuilderHeadingKeyNullByDefault() {
assertNull(ArgGroupSpec.builder().headingKey());
}
@Test
public void testGroupSpecBuilderHeadingKeyMutable() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
assertNull(builder.headingKey());
builder.headingKey("KEY");
assertEquals("KEY", builder.headingKey());
}
@Test
public void testGroupSpecBuilderBuildDisallowsEmptyGroups() {
try {
ArgGroupSpec.builder().build();
} catch (InitializationException ok) {
assertEquals("ArgGroup has no options or positional parameters, and no subgroups: null in null", ok.getMessage());
}
}
@Test
public void testAnOptionCannotBeInMultipleGroups() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
builder.subgroups().add(ArgGroupSpec.builder().addArg(OPTION).build());
builder.subgroups().add(ArgGroupSpec.builder().multiplicity("1..*").addArg(OPTION).build());
ArgGroupSpec group = builder.build();
assertEquals(2, group.subgroups().size());
CommandSpec spec = CommandSpec.create();
try {
spec.addArgGroup(group);
fail("Expected exception");
} catch (CommandLine.DuplicateNameException ex) {
assertEquals("An option cannot be in multiple groups but -x is in (-x) and [-x]. " +
"Refactor to avoid this. For example, (-a | (-a -b)) can be rewritten " +
"as (-a [-b]), and (-a -b | -a -c) can be rewritten as (-a (-b | -c)).", ex.getMessage());
}
}
@Test
public void testGroupSpecBuilderBuildCopiesBuilderAttributes() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
builder.addArg(OPTION);
ArgGroupSpec group = builder.build();
assertTrue(group.exclusive());
assertEquals(builder.exclusive(), group.exclusive());
assertEquals(CommandLine.Range.valueOf("0..1"), group.multiplicity());
assertEquals(builder.multiplicity(), group.multiplicity());
assertTrue(group.validate());
assertEquals(builder.validate(), group.validate());
assertEquals(ArgGroupSpec.DEFAULT_ORDER, group.order());
assertEquals(builder.order(), group.order());
assertNull(group.heading());
assertEquals(builder.heading(), group.heading());
assertNull(group.headingKey());
assertEquals(builder.headingKey(), group.headingKey());
assertTrue(group.subgroups().isEmpty());
assertEquals(builder.subgroups(), group.subgroups());
assertNull(group.parentGroup());
}
@Test
public void testGroupSpecBuilderBuildCopiesBuilderAttributesNonDefault() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
builder.heading("my heading");
builder.headingKey("my headingKey");
builder.order(123);
builder.exclusive(false);
builder.validate(false);
builder.multiplicity("1");
builder.addSubgroup(ArgGroupSpec.builder().addArg(OPTION).build());
builder.addArg(OPTION);
ArgGroupSpec group = builder.build();
assertFalse(group.exclusive());
assertEquals(builder.exclusive(), group.exclusive());
assertEquals(CommandLine.Range.valueOf("1"), group.multiplicity());
assertEquals(builder.multiplicity(), group.multiplicity());
assertFalse(group.validate());
assertEquals(builder.validate(), group.validate());
assertEquals(123, group.order());
assertEquals(builder.order(), group.order());
assertEquals("my heading", group.heading());
assertEquals(builder.heading(), group.heading());
assertEquals("my headingKey", group.headingKey());
assertEquals(builder.headingKey(), group.headingKey());
assertEquals(1, group.subgroups().size());
assertEquals(builder.subgroups(), group.subgroups());
}
@Test
public void testGroupSpecToString() {
String expected = "ArgGroup[exclusive=true, multiplicity=0..1, validate=true, order=-1, args=[-x], headingKey=null, heading=null, subgroups=[]]";
ArgGroupSpec b = ArgGroupSpec.builder().addArg(OPTION).build();
assertEquals(expected, b.toString());
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
builder.heading("my heading");
builder.headingKey("my headingKey");
builder.order(123);
builder.exclusive(false);
builder.validate(false);
builder.multiplicity("1");
builder.addSubgroup(ArgGroupSpec.builder().addSubgroup(b).addArg(OPTION_A).build());
builder.addArg(PositionalParamSpec.builder().index("0..1").paramLabel("FILE").build());
String expected2 = "ArgGroup[exclusive=false, multiplicity=1, validate=false, order=123, args=[FILE], headingKey='my headingKey', heading='my heading'," +
" subgroups=[ArgGroup[exclusive=true, multiplicity=0..1, validate=true, order=-1, args=[-a], headingKey=null, heading=null," +
" subgroups=[ArgGroup[exclusive=true, multiplicity=0..1, validate=true, order=-1, args=[-x], headingKey=null, heading=null, subgroups=[]]]" +
"]]" +
"]";
assertEquals(expected2, builder.build().toString());
}
@Test
public void testGroupSpecEquals() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
builder.addArg(OPTION);
ArgGroupSpec a = builder.build();
assertEquals(a, a);
assertNotSame(a, ArgGroupSpec.builder().addArg(OPTION).build());
assertEquals(a, ArgGroupSpec.builder().addArg(OPTION).build());
OptionSpec otherOption = OptionSpec.builder("-y").build();
assertNotEquals(a, ArgGroupSpec.builder().addArg(OPTION).addArg(otherOption).build());
builder.heading("my heading");
assertNotEquals(a, builder.build());
assertEquals(builder.build(), builder.build());
builder.headingKey("my headingKey");
assertNotEquals(a, builder.build());
assertEquals(builder.build(), builder.build());
builder.order(123);
assertNotEquals(a, builder.build());
assertEquals(builder.build(), builder.build());
builder.exclusive(false);
assertNotEquals(a, builder.build());
assertEquals(builder.build(), builder.build());
builder.validate(false);
assertNotEquals(a, builder.build());
assertEquals(builder.build(), builder.build());
builder.multiplicity("1");
assertNotEquals(a, builder.build());
assertEquals(builder.build(), builder.build());
builder.addSubgroup(ArgGroupSpec.builder().addArg(OPTION).build());
assertNotEquals(a, builder.build());
assertEquals(builder.build(), builder.build());
}
@Test
public void testGroupSpecHashCode() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder();
builder.addArg(OPTION);
ArgGroupSpec a = builder.build();
assertEquals(a.hashCode(), a.hashCode());
assertEquals(a.hashCode(), ArgGroupSpec.builder().addArg(OPTION).build().hashCode());
OptionSpec otherOption = OptionSpec.builder("-y").build();
assertNotEquals(a.hashCode(), ArgGroupSpec.builder().addArg(OPTION).addArg(otherOption).build().hashCode());
builder.heading("my heading");
assertNotEquals(a.hashCode(), builder.build().hashCode());
assertEquals(builder.build().hashCode(), builder.build().hashCode());
builder.headingKey("my headingKey");
assertNotEquals(a.hashCode(), builder.build().hashCode());
assertEquals(builder.build().hashCode(), builder.build().hashCode());
builder.order(123);
assertNotEquals(a.hashCode(), builder.build().hashCode());
assertEquals(builder.build().hashCode(), builder.build().hashCode());
builder.exclusive(false);
assertNotEquals(a.hashCode(), builder.build().hashCode());
assertEquals(builder.build().hashCode(), builder.build().hashCode());
builder.validate(false);
assertNotEquals(a.hashCode(), builder.build().hashCode());
assertEquals(builder.build().hashCode(), builder.build().hashCode());
builder.multiplicity("1");
assertNotEquals(a.hashCode(), builder.build().hashCode());
assertEquals(builder.build().hashCode(), builder.build().hashCode());
builder.subgroups().add(ArgGroupSpec.builder().addArg(OPTION).build());
assertNotEquals(a.hashCode(), builder.build().hashCode());
assertEquals(builder.build().hashCode(), builder.build().hashCode());
}
@Test
public void testReflection() {
class All {
@Option(names = "-x", required = true) int x;
@Option(names = "-y", required = true) int y;
}
class App {
@ArgGroup All all;
}
CommandLine cmd = new CommandLine(new App(), new InnerClassFactory(this));
CommandSpec spec = cmd.getCommandSpec();
List<ArgGroupSpec> groups = spec.argGroups();
assertEquals(1, groups.size());
ArgGroupSpec group = groups.get(0);
assertNotNull(group);
List<ArgSpec> options = new ArrayList<ArgSpec>(group.args());
assertEquals(2, options.size());
assertEquals("-x", ((OptionSpec) options.get(0)).shortestName());
assertEquals("-y", ((OptionSpec) options.get(1)).shortestName());
assertNotNull(options.get(0).group());
assertSame(group, options.get(0).group());
assertNotNull(options.get(1).group());
assertSame(group, options.get(1).group());
}
@Test
public void testReflectionRequiresNonEmpty() {
class Invalid {}
class App {
@ArgGroup Invalid invalid;
}
App app = new App();
try {
new CommandLine(app, new InnerClassFactory(this));
fail("Expected exception");
} catch (InitializationException ex) {
assertEquals("ArgGroup has no options or positional parameters, and no subgroups: " +
"FieldBinding(" + Invalid.class.getName() + " " + app.getClass().getName() + ".invalid) in " +
app.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(app))
, ex.getMessage());
}
}
@Test
public void testProgrammatic() {
CommandSpec spec = CommandSpec.create();
ArgGroupSpec exclusiveSub = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-x").required(true).build())
.addArg(OptionSpec.builder("-y").required(true).build()).build();
ArgGroupSpec cooccur = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-z").required(true).build())
.addSubgroup(exclusiveSub).build();
spec.addArgGroup(cooccur);
assertNull(cooccur.parentGroup());
assertEquals(1, cooccur.subgroups().size());
assertSame(exclusiveSub, cooccur.subgroups().get(0));
assertEquals(1, cooccur.args().size());
assertNotNull(exclusiveSub.parentGroup());
assertSame(cooccur, exclusiveSub.parentGroup());
assertEquals(0, exclusiveSub.subgroups().size());
assertEquals(2, exclusiveSub.args().size());
ArgGroupSpec exclusive = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-a").required(true).build())
.addArg(OptionSpec.builder("-b").required(true).build()).build();
spec.addArgGroup(exclusive);
assertNull(exclusive.parentGroup());
assertTrue(exclusive.subgroups().isEmpty());
assertEquals(2, exclusive.args().size());
List<ArgGroupSpec> groups = spec.argGroups();
assertEquals(2, groups.size());
assertSame(cooccur, groups.get(0));
assertSame(exclusive, groups.get(1));
}
@Test
public void testCannotAddSubgroupToCommand() {
CommandSpec spec = CommandSpec.create();
ArgGroupSpec exclusiveSub = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-x").required(true).build())
.addArg(OptionSpec.builder("-y").required(true).build()).build();
ArgGroupSpec cooccur = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-z").required(true).build())
.addSubgroup(exclusiveSub).build();
try {
spec.addArgGroup(exclusiveSub);
fail("Expected exception");
} catch (InitializationException ex) {
assertEquals("Groups that are part of another group should not be added to a command. Add only the top-level group.", ex.getMessage());
}
}
@Test
public void testCannotAddSameGroupToCommandMultipleTimes() {
CommandSpec spec = CommandSpec.create();
ArgGroupSpec cooccur = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-z").required(true).build()).build();
spec.addArgGroup(cooccur);
try {
spec.addArgGroup(cooccur);
fail("Expected exception");
} catch (InitializationException ex) {
assertEquals("The specified group [-z] has already been added to the <main class> command.", ex.getMessage());
}
}
@Test
public void testIsSubgroupOf_FalseIfUnrelated() {
ArgGroupSpec other = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-z").required(true).build()).build();
ArgGroupSpec exclusiveSub = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-x").required(true).build())
.addArg(OptionSpec.builder("-y").required(true).build()).build();
ArgGroupSpec cooccur = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-z").required(true).build())
.addSubgroup(exclusiveSub).build();
assertFalse(other.isSubgroupOf(exclusiveSub));
assertFalse(other.isSubgroupOf(cooccur));
assertFalse(exclusiveSub.isSubgroupOf(other));
assertFalse(cooccur.isSubgroupOf(other));
}
@Test
public void testIsSubgroupOf_FalseIfSame() {
ArgGroupSpec other = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-z").required(true).build()).build();
assertFalse(other.isSubgroupOf(other));
}
@Test
public void testIsSubgroupOf_TrueIfChild() {
ArgGroupSpec subsub = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-a").required(true).build()).build();
ArgGroupSpec sub = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-x").required(true).build())
.addArg(OptionSpec.builder("-y").required(true).build())
.addSubgroup(subsub).build();
ArgGroupSpec top = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-z").required(true).build())
.addSubgroup(sub).build();
assertTrue(sub.isSubgroupOf(top));
assertTrue(subsub.isSubgroupOf(sub));
assertTrue(subsub.isSubgroupOf(top));
assertFalse(top.isSubgroupOf(sub));
assertFalse(top.isSubgroupOf(subsub));
assertFalse(sub.isSubgroupOf(subsub));
}
@Test
public void testValidationExclusiveMultiplicity0_1_ActualTwo() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
All all;
}
try {
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-a", "-b");
fail("Expected exception");
} catch (MutuallyExclusiveArgsException ex) {
assertEquals("Error: -a, -b are mutually exclusive (specify only one)", ex.getMessage());
}
}
@Test
public void testValidationGroups2Violation1ExclusiveMultiplicity0_1_ActualTwo() {
class Group1 {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
}
class Group2 {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
Group1 g1;
@ArgGroup(exclusive = true, multiplicity = "0..1")
Group2 g2;
}
try {
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-x", "-a", "-b");
fail("Expected exception");
} catch (MutuallyExclusiveArgsException ex) {
assertEquals("Error: -a, -b are mutually exclusive (specify only one)", ex.getMessage());
}
}
@Test
public void testValidationGroups2Violations2BothExclusiveMultiplicity0_1_ActualTwo() {
class Group1 {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
}
class Group2 {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
Group1 g1;
@ArgGroup(exclusive = true, multiplicity = "0..1")
Group2 g2;
}
try {
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-x", "-y", "-a", "-b");
fail("Expected exception");
} catch (MutuallyExclusiveArgsException ex) {
assertEquals("Error: -x, -y are mutually exclusive (specify only one)", ex.getMessage());
}
}
@Test
public void testValidationGroups2Violations0() {
class Group1 {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
}
class Group2 {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
Group1 g1;
@ArgGroup(exclusive = true, multiplicity = "0..1")
Group2 g2;
}
// no error
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-x", "-a");
}
@Test
public void testValidationExclusiveMultiplicity0_1_ActualZero() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
All all;
}
// no errors
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs();
}
@Test
public void testValidationExclusiveMultiplicity1_ActualZero() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "1")
All all;
}
try {
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs();
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument (specify one of these): (-a | -b)", ex.getMessage());
}
}
@Test
public void testValidationDependentAllRequiredMultiplicity0_1_All() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false)
All all;
}
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-a", "-b", "-c");
}
@Test
public void testValidationDependentSomeOptionalMultiplicity0_1_All() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = false) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false)
All all;
}
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-a", "-b", "-c");
}
@Test
public void testValidationDependentSomeOptionalMultiplicity0_1_OptionalOmitted() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = false) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false)
All all;
}
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-a", "-c");
}
@Test
public void testValidationDependentMultiplicity0_1_Partial() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false)
All all;
}
try {
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-a", "-b");
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): -c", ex.getMessage());
}
}
@Test
public void testValidationDependentMultiplicity0_1_Zero() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false)
All all;
}
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs();
}
@Test
public void testValidationDependentMultiplicity1_All() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "1")
All all;
}
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-a", "-b", "-c");
}
@Test
public void testValidationDependentMultiplicity1_Partial() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "1")
All all;
}
try {
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs("-b");
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): -a, -c", ex.getMessage());
}
}
@Test
public void testValidationDependentMultiplicity1_Zero() {
class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
@Option(names = "-c", required = true) boolean c;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "1")
All all;
}
try {
new CommandLine(new App(), new InnerClassFactory(this)).parseArgs();
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): (-a -b -c)", ex.getMessage());
}
}
static class Excl {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
@Override
public boolean equals(Object obj) {
Excl other = (Excl) obj;
return x == other.x && y == other.y;
}
}
static class All {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
@Override
public boolean equals(Object obj) {
All other = (All) obj;
return a == other.a && b == other.b;
}
}
static class Composite {
@ArgGroup(exclusive = false, multiplicity = "0..1")
All all = new All();
@ArgGroup(exclusive = true, multiplicity = "1")
Excl excl = new Excl();
public Composite() {}
public Composite(boolean a, boolean b, boolean x, boolean y) {
this.all.a = a;
this.all.b = b;
this.excl.x = x;
this.excl.y = y;
}
@Override
public boolean equals(Object obj) {
Composite other = (Composite) obj;
return all.equals(other.all) && excl.equals(other.excl);
}
}
static class CompositeApp {
// SYNOPSIS: ([-a -b] | (-x | -y))
@ArgGroup(exclusive = true, multiplicity = "1")
Composite composite = new Composite();
}
static class OptionalCompositeApp {
@ArgGroup(exclusive = true, multiplicity = "0..1")
Composite composite = new Composite();
}
@Test
public void testValidationCompositeMultiplicity1() {
validateInput(new CompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -b", "-a");
validateInput(new CompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -a", "-b");
validateInput(new CompositeApp(), MaxValuesExceededException.class, "Error: expected only one match but got ([-a -b] | (-x | -y))={-x} and ([-a -b] | (-x | -y))={-y}", "-x", "-y");
validateInput(new CompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -b", "-x", "-a");
validateInput(new CompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -a", "-x", "-b");
validateInput(new CompositeApp(), MutuallyExclusiveArgsException.class, "Error: [-a -b] and (-x | -y) are mutually exclusive (specify only one)", "-a", "-x", "-b");
validateInput(new CompositeApp(), MutuallyExclusiveArgsException.class, "Error: [-a -b] and (-x | -y) are mutually exclusive (specify only one)", "-a", "-y", "-b");
// no input
validateInput(new CompositeApp(), MissingParameterException.class, "Error: Missing required argument (specify one of these): ([-a -b] | (-x | -y))");
// no error
validateInput(new CompositeApp(), null, null, "-a", "-b");
validateInput(new CompositeApp(), null, null, "-x");
validateInput(new CompositeApp(), null, null, "-y");
}
@Test
public void testValidationCompositeMultiplicity0_1() {
validateInput(new OptionalCompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -b", "-a");
validateInput(new OptionalCompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -a", "-b");
validateInput(new OptionalCompositeApp(), MaxValuesExceededException.class, "Error: expected only one match but got [[-a -b] | (-x | -y)]={-x} and [[-a -b] | (-x | -y)]={-y}", "-x", "-y");
validateInput(new OptionalCompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -b", "-x", "-a");
validateInput(new OptionalCompositeApp(), MissingParameterException.class, "Error: Missing required argument(s): -a", "-x", "-b");
validateInput(new OptionalCompositeApp(), MutuallyExclusiveArgsException.class, "Error: [-a -b] and (-x | -y) are mutually exclusive (specify only one)", "-a", "-x", "-b");
validateInput(new OptionalCompositeApp(), MutuallyExclusiveArgsException.class, "Error: [-a -b] and (-x | -y) are mutually exclusive (specify only one)", "-a", "-y", "-b");
// no input: ok because composite as a whole is optional
validateInput(new OptionalCompositeApp(), null, null);
// no error
validateInput(new OptionalCompositeApp(), null, null, "-a", "-b");
validateInput(new OptionalCompositeApp(), null, null, "-x");
validateInput(new OptionalCompositeApp(), null, null, "-y");
}
private void validateInput(Object userObject, Class<? extends Exception> exceptionClass, String errorMessage, String... args) {
try {
CommandLine.populateCommand(userObject, args);
if (exceptionClass != null) {
fail("Expected " + exceptionClass.getSimpleName() + " for " + Arrays.asList(args));
}
} catch (Exception ex) {
assertEquals(errorMessage, ex.getMessage());
assertEquals("Exception for input " + Arrays.asList(args), exceptionClass, ex.getClass());
}
}
@Test
public void testSynopsisOnlyOptions() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-a").required(true).build())
.addArg(OptionSpec.builder("-b").required(true).build())
.addArg(OptionSpec.builder("-c").required(true).build());
assertEquals("[-a | -b | -c]", builder.build().synopsis());
builder.multiplicity("1");
assertEquals("(-a | -b | -c)", builder.build().synopsis());
builder.multiplicity("2");
assertEquals("(-a | -b | -c) (-a | -b | -c)", builder.build().synopsis());
builder.multiplicity("1..3");
assertEquals("(-a | -b | -c) [-a | -b | -c] [-a | -b | -c]", builder.build().synopsis());
builder.multiplicity("1..*");
assertEquals("(-a | -b | -c)...", builder.build().synopsis());
builder.multiplicity("1");
builder.exclusive(false);
assertEquals("(-a -b -c)", builder.build().synopsis());
builder.multiplicity("0..1");
assertEquals("[-a -b -c]", builder.build().synopsis());
builder.multiplicity("0..2");
assertEquals("[-a -b -c] [-a -b -c]", builder.build().synopsis());
builder.multiplicity("0..3");
assertEquals("[-a -b -c] [-a -b -c] [-a -b -c]", builder.build().synopsis());
builder.multiplicity("0..*");
assertEquals("[-a -b -c]...", builder.build().synopsis());
}
@Test
public void testSynopsisOnlyPositionals() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder()
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG1").required(true).required(true).build())
.addArg(PositionalParamSpec.builder().index("1").paramLabel("ARG2").required(true).required(true).build())
.addArg(PositionalParamSpec.builder().index("2").paramLabel("ARG3").required(true).required(true).build());
assertEquals("[ARG1 | ARG2 | ARG3]", builder.build().synopsis());
builder.multiplicity("1");
assertEquals("(ARG1 | ARG2 | ARG3)", builder.build().synopsis());
builder.multiplicity("2");
assertEquals("(ARG1 | ARG2 | ARG3) (ARG1 | ARG2 | ARG3)", builder.build().synopsis());
builder.multiplicity("1..3");
assertEquals("(ARG1 | ARG2 | ARG3) [ARG1 | ARG2 | ARG3] [ARG1 | ARG2 | ARG3]", builder.build().synopsis());
builder.multiplicity("1..*");
assertEquals("(ARG1 | ARG2 | ARG3)...", builder.build().synopsis());
builder.multiplicity("1");
builder.exclusive(false);
assertEquals("(ARG1 ARG2 ARG3)", builder.build().synopsis());
builder.multiplicity("0..1");
assertEquals("[ARG1 ARG2 ARG3]", builder.build().synopsis());
builder.multiplicity("0..2");
assertEquals("[ARG1 ARG2 ARG3] [ARG1 ARG2 ARG3]", builder.build().synopsis());
builder.multiplicity("0..*");
assertEquals("[ARG1 ARG2 ARG3]...", builder.build().synopsis());
}
@Test
public void testSynopsisMixOptionsPositionals() {
ArgGroupSpec.Builder builder = ArgGroupSpec.builder()
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG1").required(true).build())
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG2").required(true).build())
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG3").required(true).build())
.addArg(OptionSpec.builder("-a").required(true).build())
.addArg(OptionSpec.builder("-b").required(true).build())
.addArg(OptionSpec.builder("-c").required(true).build());
assertEquals("[ARG1 | ARG2 | ARG3 | -a | -b | -c]", builder.build().synopsis());
builder.multiplicity("1");
assertEquals("(ARG1 | ARG2 | ARG3 | -a | -b | -c)", builder.build().synopsis());
builder.exclusive(false);
assertEquals("(ARG1 ARG2 ARG3 -a -b -c)", builder.build().synopsis());
builder.multiplicity("0..1");
assertEquals("[ARG1 ARG2 ARG3 -a -b -c]", builder.build().synopsis());
}
@Test
public void testSynopsisOnlyGroups() {
ArgGroupSpec.Builder b1 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-a").required(true).build())
.addArg(OptionSpec.builder("-b").required(true).build())
.addArg(OptionSpec.builder("-c").required(true).build());
ArgGroupSpec.Builder b2 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-e").required(true).build())
.addArg(OptionSpec.builder("-e").required(true).build())
.addArg(OptionSpec.builder("-f").required(true).build())
.multiplicity("1");
ArgGroupSpec.Builder b3 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-g").required(true).build())
.addArg(OptionSpec.builder("-h").required(true).build())
.addArg(OptionSpec.builder("-i").required(true).type(List.class).build())
.multiplicity("1")
.exclusive(false);
ArgGroupSpec.Builder composite = ArgGroupSpec.builder()
.addSubgroup(b1.build())
.addSubgroup(b2.build())
.addSubgroup(b3.build());
assertEquals("[[-a | -b | -c] | (-e | -f) | (-g -h -i=PARAM [-i=PARAM]...)]", composite.build().synopsis());
composite.multiplicity("1");
assertEquals("([-a | -b | -c] | (-e | -f) | (-g -h -i=PARAM [-i=PARAM]...))", composite.build().synopsis());
composite.multiplicity("1..*");
assertEquals("([-a | -b | -c] | (-e | -f) | (-g -h -i=PARAM [-i=PARAM]...))...", composite.build().synopsis());
composite.multiplicity("1");
composite.exclusive(false);
assertEquals("([-a | -b | -c] (-e | -f) (-g -h -i=PARAM [-i=PARAM]...))", composite.build().synopsis());
composite.multiplicity("0..1");
assertEquals("[[-a | -b | -c] (-e | -f) (-g -h -i=PARAM [-i=PARAM]...)]", composite.build().synopsis());
composite.multiplicity("0..*");
assertEquals("[[-a | -b | -c] (-e | -f) (-g -h -i=PARAM [-i=PARAM]...)]...", composite.build().synopsis());
}
@Test
public void testSynopsisMixGroupsOptions() {
ArgGroupSpec.Builder b1 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-a").required(true).build())
.addArg(OptionSpec.builder("-b").required(true).build())
.addArg(OptionSpec.builder("-c").required(true).build());
ArgGroupSpec.Builder b2 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-e").required(true).build())
.addArg(OptionSpec.builder("-e").required(true).build())
.addArg(OptionSpec.builder("-f").required(true).build())
.multiplicity("1");
ArgGroupSpec.Builder composite = ArgGroupSpec.builder()
.addSubgroup(b1.build())
.addSubgroup(b2.build())
.addArg(OptionSpec.builder("-x").required(true).build())
.addArg(OptionSpec.builder("-y").required(true).build())
.addArg(OptionSpec.builder("-z").required(true).build());
assertEquals("[-x | -y | -z | [-a | -b | -c] | (-e | -f)]", composite.build().synopsis());
composite.multiplicity("1");
assertEquals("(-x | -y | -z | [-a | -b | -c] | (-e | -f))", composite.build().synopsis());
composite.exclusive(false);
assertEquals("(-x -y -z [-a | -b | -c] (-e | -f))", composite.build().synopsis());
composite.multiplicity("0..1");
assertEquals("[-x -y -z [-a | -b | -c] (-e | -f)]", composite.build().synopsis());
}
@Test
public void testSynopsisMixGroupsPositionals() {
ArgGroupSpec.Builder b1 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-a").required(true).build())
.addArg(OptionSpec.builder("-b").required(false).build())
.addArg(OptionSpec.builder("-c").required(true).build());
ArgGroupSpec.Builder b2 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-e").required(false).build())
.addArg(OptionSpec.builder("-f").required(true).build())
.multiplicity("1");
ArgGroupSpec.Builder composite = ArgGroupSpec.builder()
.addSubgroup(b1.build())
.addSubgroup(b2.build())
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG1").required(true).build())
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG2").required(true).build())
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG3").required(true).build());
assertEquals("[ARG1 | ARG2 | ARG3 | [-a | -b | -c] | (-e | -f)]", composite.build().synopsis());
composite.multiplicity("1");
assertEquals("(ARG1 | ARG2 | ARG3 | [-a | -b | -c] | (-e | -f))", composite.build().synopsis());
composite.exclusive(false);
assertEquals("(ARG1 ARG2 ARG3 [-a | -b | -c] (-e | -f))", composite.build().synopsis());
composite.multiplicity("0..1");
assertEquals("[ARG1 ARG2 ARG3 [-a | -b | -c] (-e | -f)]", composite.build().synopsis());
}
@Test
public void testSynopsisMixGroupsOptionsPositionals() {
ArgGroupSpec.Builder b1 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-a").required(true).build())
.addArg(OptionSpec.builder("-b").required(true).build())
.addArg(OptionSpec.builder("-c").required(true).build());
ArgGroupSpec.Builder b2 = ArgGroupSpec.builder()
.addArg(OptionSpec.builder("-e").required(true).build())
.addArg(OptionSpec.builder("-e").required(true).build())
.addArg(OptionSpec.builder("-f").required(true).build())
.multiplicity("1");
ArgGroupSpec.Builder composite = ArgGroupSpec.builder()
.addSubgroup(b1.build())
.addSubgroup(b2.build())
.addArg(OptionSpec.builder("-x").required(true).build())
.addArg(OptionSpec.builder("-y").required(true).build())
.addArg(OptionSpec.builder("-z").required(true).build())
.addArg(PositionalParamSpec.builder().index("0").paramLabel("ARG1").required(true).build())
.addArg(PositionalParamSpec.builder().index("1").paramLabel("ARG2").required(true).build())
.addArg(PositionalParamSpec.builder().index("2").paramLabel("ARG3").required(true).build());
assertEquals("[-x | -y | -z | ARG1 | ARG2 | ARG3 | [-a | -b | -c] | (-e | -f)]", composite.build().synopsis());
composite.multiplicity("1");
assertEquals("(-x | -y | -z | ARG1 | ARG2 | ARG3 | [-a | -b | -c] | (-e | -f))", composite.build().synopsis());
composite.exclusive(false);
assertEquals("(-x -y -z ARG1 ARG2 ARG3 [-a | -b | -c] (-e | -f))", composite.build().synopsis());
composite.multiplicity("0..1");
assertEquals("[-x -y -z ARG1 ARG2 ARG3 [-a | -b | -c] (-e | -f)]", composite.build().synopsis());
}
static class BiGroup {
@Option(names = "-x") int x;
@Option(names = "-y") int y;
}
static class SetterMethodApp {
private BiGroup biGroup;
@ArgGroup(exclusive = false)
public void setBiGroup(BiGroup biGroup) {
this.biGroup = biGroup;
}
}
@Test
public void testGroupAnnotationOnSetterMethod() {
SetterMethodApp app = new SetterMethodApp();
CommandLine cmd = new CommandLine(app, new InnerClassFactory(this));
assertNull("before parsing", app.biGroup);
cmd.parseArgs("-x=1", "-y=2");
assertEquals(1, app.biGroup.x);
assertEquals(2, app.biGroup.y);
}
interface AnnotatedGetterInterface {
@ArgGroup(exclusive = false) BiGroup getGroup();
}
@Test
public void testGroupAnnotationOnGetterMethod() {
CommandLine cmd = new CommandLine(AnnotatedGetterInterface.class);
AnnotatedGetterInterface app = cmd.getCommand();
assertNull("before parsing", app.getGroup());
cmd.parseArgs("-x=1", "-y=2");
assertEquals(1, app.getGroup().x);
assertEquals(2, app.getGroup().y);
}
@Test
public void testUsageHelpRequiredExclusiveGroup() {
class Excl {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "1") Excl excl;
}
String expected = String.format("" +
"Usage: <main class> (-x | -y)%n" +
" -x%n" +
" -y%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testUsageHelpNonRequiredExclusiveGroup() {
class All {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
All all;
}
String expected = String.format("" +
"Usage: <main class> [-x | -y]%n" +
" -x%n" +
" -y%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testUsageHelpRequiredNonExclusiveGroup() {
class All {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "1")
All all;
}
String expected = String.format("" +
"Usage: <main class> (-x -y)%n" +
" -x%n" +
" -y%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testUsageHelpNonRequiredNonExclusiveGroup() {
class All {
@Option(names = "-x", required = true) boolean x;
@Option(names = "-y", required = true) boolean y;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "0..1")
All all;
}
String expected = String.format("" +
"Usage: <main class> [-x -y]%n" +
" -x%n" +
" -y%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testUsageHelpNonValidatingGroupDoesNotImpactSynopsis() {
class All {
@Option(names = "-x") boolean x;
@Option(names = "-y") boolean y;
}
class App {
@ArgGroup(validate = false)
All all;
}
String expected = String.format("" +
"Usage: <main class> [-xy]%n" +
" -x%n" +
" -y%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testCompositeGroupSynopsis() {
class IntXY {
@Option(names = "-x", required = true) int x;
@Option(names = "-y", required = true) int y;
}
class IntABC {
@Option(names = "-a", required = true) int a;
@Option(names = "-b", required = true) int b;
@Option(names = "-c", required = true) int c;
}
class Composite {
@ArgGroup(exclusive = false, multiplicity = "0..1")
IntABC all;
@ArgGroup(exclusive = true, multiplicity = "1")
IntXY excl;
}
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
Composite composite;
}
String expected = String.format("" +
"Usage: <main class> [[-a=<a> -b=<b> -c=<c>] | (-x=<x> | -y=<y>)]%n" +
" -a=<a>%n" +
" -b=<b>%n" +
" -c=<c>%n" +
" -x=<x>%n" +
" -y=<y>%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testCompositeGroupSynopsisAnsi() {
class IntXY {
@Option(names = "-x", required = true) int x;
@Option(names = "-y", required = true) int y;
}
class IntABC {
@Option(names = "-a", required = true) int a;
@Option(names = "-b", required = true) int b;
@Option(names = "-c", required = true) int c;
}
class Composite {
@ArgGroup(exclusive = false, multiplicity = "0..1")
IntABC all;
@ArgGroup(exclusive = true, multiplicity = "1")
IntXY exclusive;
}
@Command
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
Composite composite;
}
String expected = String.format("" +
"Usage: @|bold <main class>|@ [[@|yellow -a|@=@|italic <a>|@ @|yellow -b|@=@|italic <b>|@ @|yellow -c|@=@|italic <c>|@] | (@|yellow -x|@=@|italic <x>|@ | @|yellow -y|@=@|italic <y>|@)]%n" +
"@|yellow |@ @|yellow -a|@=@|italic <a>|@%n" +
"@|yellow |@ @|yellow -b|@=@|italic <b>|@%n" +
"@|yellow |@ @|yellow -c|@=@|italic <c>|@%n" +
"@|yellow |@ @|yellow -x|@=@|italic <x>|@%n" +
"@|yellow |@ @|yellow -y|@=@|italic <y>|@%n");
expected = Help.Ansi.ON.string(expected);
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.ON);
assertEquals(expected, actual);
}
@Test
public void testGroupUsageHelpOptionListOptionsWithoutGroupsPrecedeGroups() {
class IntXY {
@Option(names = "-x", required = true) int x;
@Option(names = "-y", required = true) int y;
}
class IntABC {
@Option(names = "-a", required = true) int a;
@Option(names = "-b", required = true) int b;
@Option(names = "-c", required = true) int c;
}
class Composite {
@ArgGroup(exclusive = false, multiplicity = "0..1", order = 10,
heading = "Co-occurring options:%nThese options must appear together, or not at all.%n")
IntABC all;
@ArgGroup(exclusive = true, multiplicity = "1", order = 20, heading = "Exclusive options:%n")
IntXY excl;
}
class App {
@Option(names = "-A") int A;
@Option(names = "-B") boolean b;
@Option(names = "-C") boolean c;
@ArgGroup(exclusive = true, multiplicity = "0..1")
Composite composite;
@ArgGroup(validate = false, heading = "Remaining options:%n", order = 100)
Object remainder = new Object() {
@Option(names = "-D") int D;
@Option(names = "-E") boolean E;
@Option(names = "-F") boolean F;
};
}
String expected = String.format("" +
"Usage: <main class> [-BCEF] [-A=<A>] [-D=<D>] [[-a=<a> -b=<b> -c=<c>] | (-x=<x>%n" +
" | -y=<y>)]%n" +
" -A=<A>%n" +
" -B%n" +
" -C%n" +
"Co-occurring options:%n" +
"These options must appear together, or not at all.%n" +
" -a=<a>%n" +
" -b=<b>%n" +
" -c=<c>%n" +
"Exclusive options:%n" +
" -x=<x>%n" +
" -y=<y>%n" +
"Remaining options:%n" +
" -D=<D>%n" +
" -E%n" +
" -F%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Ignore("Requires support for positionals with same index in group and in command (outside the group)")
@Test
public void testGroupWithOptionsAndPositionals_multiplicity0_1() {
class Remainder {
@Option(names = "-a" , required = true) int a;
@Parameters(index = "0") File f0;
@Parameters(index = "1") File f1;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "0..1", order = 10,
heading = "Co-occurring args:%nThese options must appear together, or not at all.%n")
Remainder remainder = new Remainder();
@Parameters(index = "0") File f2;
}
String expected = String.format("" +
"Usage: <main class> [-a=<a> <f0> <f1>] <f2>%n" +
" <f2>%n" +
"Co-occurring args:%n" +
"These options must appear together, or not at all.%n" +
" <f0>%n" +
" <f1>%n" +
" -a=<a>%n");
//TestUtil.setTraceLevel("DEBUG");
CommandLine cmd = new CommandLine(new App(), new InnerClassFactory(this));
String actual = cmd.getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
ParseResult parseResult = cmd.parseArgs("FILE2");
assertTrue(parseResult.hasMatchedPositional(0));
assertEquals("<f2>", parseResult.matchedPositional(0).paramLabel());
}
@Ignore("Requires support for positionals with same index in group and in command (outside the group)")
@Test
public void testGroupWithOptionsAndPositionals_multiplicity1_2() {
class Remainder {
@Option(names = "-a" , required = true) int a;
@Parameters(index = "0") File f0;
@Parameters(index = "1") File f1;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "1..2", order = 10,
heading = "Co-occurring args:%nThese options must appear together, or not at all.%n")
Remainder remainder = new Remainder();
@Parameters(index = "0") File f2;
}
String expected = String.format("" +
"Usage: <main class> (-a=<a> <f0> <f1>) [-a=<a> <f0> <f1>] <f2>%n" +
" <f2>%n" +
"Co-occurring args:%n" +
"These options must appear together, or not at all.%n" +
" <f0>%n" +
" <f1>%n" +
" -a=<a>%n");
TestUtil.setTraceLevel("DEBUG");
CommandLine cmd = new CommandLine(new App(), new InnerClassFactory(this));
String actual = cmd.getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
ParseResult parseResult = cmd.parseArgs("-a=1", "F0", "F1", "FILE2");
assertTrue(parseResult.hasMatchedPositional(0));
assertEquals("<f2>", parseResult.matchedPositional(0).paramLabel());
}
@Ignore("This no longer works with #1027 improved support for repeatable ArgGroups with positional parameters")
@Test
public void testPositionalsInGroupAndInCommand() {
class Remainder {
@Option(names = "-a" , required = true) int a;
@Parameters(index = "0") File f0;
@Parameters(index = "1") File f1;
}
class App {
@ArgGroup(exclusive = false, multiplicity = "1..2", order = 10,
heading = "Co-occurring args:%nThese options must appear together, or not at all.%n")
Remainder remainder = new Remainder();
@Parameters(index = "0..*") List<String> allPositionals;
}
String expected = String.format("" +
"Usage: <main class> (-a=<a> <f0> <f1>) [-a=<a> <f0> <f1>] [<allPositionals>...]%n" +
" [<allPositionals>...]%n%n" +
"Co-occurring args:%n" +
"These options must appear together, or not at all.%n" +
" <f0>%n" +
" <f1>%n" +
" -a=<a>%n");
//TestUtil.setTraceLevel("INFO");
CommandLine cmd = new CommandLine(new App(), new InnerClassFactory(this));
String actual = cmd.getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
ParseResult parseResult = cmd.parseArgs("-a=1", "F0", "F1", "FILE2");
assertTrue(parseResult.hasMatchedPositional(0));
assertEquals("<f0>", parseResult.matchedPositional(0).paramLabel());
//assertEquals("<f1>", parseResult.matchedPositional(1).paramLabel());
assertEquals("<allPositionals>", parseResult.matchedPositional(2).paramLabel());
CommandSpec spec = cmd.getCommandSpec();
PositionalParamSpec pos0 = spec.positionalParameters().get(0);
PositionalParamSpec pos1 = spec.positionalParameters().get(1);
PositionalParamSpec pos2 = spec.positionalParameters().get(2);
assertEquals("<f0>", pos0.paramLabel());
assertEquals("<allPositionals>", pos1.paramLabel());
assertEquals("<f1>", pos2.paramLabel());
assertEquals(Arrays.asList("F0", "F1", "FILE2"), pos1.stringValues());
}
@Test
public void testGroupWithMixedOptionsAndPositionals() {
class IntXY {
@Option(names = "-x", required = true) int x;
@Option(names = "-y", required = true) int y;
}
class IntABC {
@Option(names = "-a", required = true) int a;
@Parameters(index = "0") File f0;
@Parameters(index = "1") File f1;
}
class Composite {
@ArgGroup(exclusive = false, multiplicity = "0..2", order = 10,
heading = "Co-occurring options:%nThese options must appear together, or not at all.%n")
List<IntABC> all;
@ArgGroup(exclusive = true, multiplicity = "1", order = 20, heading = "Exclusive options:%n")
IntXY excl;
}
class App {
@Option(names = "-A") int A;
@Option(names = "-B") boolean B;
@Option(names = "-C") boolean C;
@ArgGroup(exclusive = true, multiplicity = "0..3")
Composite[] composite;
}
//TestUtil.setTraceLevel("DEBUG");
App app = new App();
CommandLine cmd = new CommandLine(app, new InnerClassFactory(this));
String synopsis = new Help(cmd.getCommandSpec(), Help.defaultColorScheme(Help.Ansi.OFF)).synopsis(0);
String expected = String.format("" +
"<main class> [-BC] [-A=<A>] [[-a=<a> <f0> <f1>] [-a=<a> <f0> <f1>] | (-x=<x> |%n" +
" -y=<y>)] [[-a=<a> <f0> <f1>] [-a=<a> <f0> <f1>] | (-x=<x> |%n" +
" -y=<y>)] [[-a=<a> <f0> <f1>] [-a=<a> <f0> <f1>] | (-x=<x> |%n" +
" -y=<y>)]");
assertEquals(expected, synopsis.trim());
try {
cmd.parseArgs("-x=1", "-a=1", "file0", "file1", "-y=2", "-x=3");
fail("Expected exception");
} catch (MutuallyExclusiveArgsException ex) {
assertEquals("Error: [-a=<a> <f0> <f1>] and (-x=<x> | -y=<y>) are mutually exclusive (specify only one)", ex.getMessage());
}
try {
cmd.parseArgs("-x=1", "-a=1", "file0", "file1", "-x=2", "-x=3");
fail("Expected exception");
//} catch (CommandLine.MaxValuesExceededException ex) {
//assertEquals("Error: Group: (-x=<x> | -y=<y>) can only be specified 1 times but was matched 3 times.", ex.getMessage());
} catch (MutuallyExclusiveArgsException ex) {
assertEquals("Error: [-a=<a> <f0> <f1>] and (-x=<x> | -y=<y>) are mutually exclusive (specify only one)", ex.getMessage());
}
try {
cmd.parseArgs("-x=1", "-a=1", "file0", "file1");
fail("Expected exception");
} catch (CommandLine.MutuallyExclusiveArgsException ex) {
assertEquals("Error: [-a=<a> <f0> <f1>] and (-x=<x> | -y=<y>) are mutually exclusive (specify only one)", ex.getMessage());
}
ArgGroupSpec topLevelGroup = cmd.getCommandSpec().argGroups().get(0);
assertEquals(Composite[].class, topLevelGroup.userObject().getClass());
assertSame(app.composite, topLevelGroup.userObject());
ParseResult parseResult = cmd.parseArgs("-a=1", "file0", "file1", "-a=2", "file2", "file3");
List<ParseResult.GroupMatch> multiples = parseResult.getGroupMatches();
assertEquals(1, multiples.size());
Map<ArgGroupSpec, GroupMatchContainer> matchedTopGroups = multiples.get(0).matchedSubgroups();
assertEquals(1, matchedTopGroups.size());
GroupMatchContainer topGroupMatch = matchedTopGroups.entrySet().iterator().next().getValue();
List<ParseResult.GroupMatch> topGroupMultiples = topGroupMatch.matches();
assertEquals(1, topGroupMultiples.size());
ParseResult.GroupMatch topGroupMultiple = topGroupMultiples.get(0);
Map<ArgGroupSpec, GroupMatchContainer> matchedSubGroups = topGroupMultiple.matchedSubgroups();
assertEquals(1, matchedSubGroups.size());
GroupMatchContainer subGroupMatch = matchedSubGroups.entrySet().iterator().next().getValue();
List<GroupMatch> subGroupMultiples = subGroupMatch.matches();
assertEquals(2, subGroupMultiples.size());
ParseResult.GroupMatch subMGM1 = subGroupMultiples.get(0);
assertFalse(subMGM1.isEmpty());
assertTrue(subMGM1.matchedSubgroups().isEmpty());
CommandSpec spec = cmd.getCommandSpec();
assertEquals(Arrays.asList(1), subMGM1.matchedValues(spec.findOption("-a")));
assertEquals(Arrays.asList(new File("file0")), subMGM1.matchedValues(spec.positionalParameters().get(0)));
assertEquals(Arrays.asList(new File("file1")), subMGM1.matchedValues(spec.positionalParameters().get(1)));
ParseResult.GroupMatch subMGM2 = subGroupMultiples.get(1);
assertFalse(subMGM2.isEmpty());
assertTrue(subMGM2.matchedSubgroups().isEmpty());
assertEquals(Arrays.asList(2), subMGM2.matchedValues(spec.findOption("-a")));
assertEquals(Arrays.asList(new File("file2")), subMGM2.matchedValues(spec.positionalParameters().get(0)));
assertEquals(Arrays.asList(new File("file3")), subMGM2.matchedValues(spec.positionalParameters().get(1)));
List<GroupMatchContainer> found = parseResult.findMatches(topLevelGroup);
assertSame(topGroupMatch, found.get(0));
ArgGroupSpec sub = topLevelGroup.subgroups().get(0);
assertEquals("Co-occurring options:%nThese options must appear together, or not at all.%n", sub.heading());
List<GroupMatchContainer> foundSub = parseResult.findMatches(sub);
assertEquals(1, foundSub.size());
}
@Test
public void testGroupUsageHelpOptionListOptionsGroupWithMixedOptionsAndPositionals() {
class IntXY {
@Option(names = "-x", required = true) int x;
@Option(names = "-y", required = true) int y;
}
class IntABC {
@Option(names = "-a", required = true) int a;
@Parameters(index = "0") File f0;
@Parameters(index = "1") File f1;
}
class Composite {
@ArgGroup(exclusive = false, multiplicity = "0..1", order = 10,
heading = "Co-occurring options:%nThese options must appear together, or not at all.%n")
IntABC all;
@ArgGroup(exclusive = true, multiplicity = "1", order = 20, heading = "Exclusive options:%n")
IntXY excl;
}
class App {
@Option(names = "-A") int A;
@Option(names = "-B") boolean B;
@Option(names = "-C") boolean C;
@Parameters(index = "2") File f2;
@ArgGroup(exclusive = true, multiplicity = "0..1")
Composite composite;
@ArgGroup(validate = false, heading = "Remaining options:%n", order = 100)
Object remainder = new Object() {
@Option(names = "-D") int D;
@Option(names = "-E") boolean E;
@Option(names = "-F") boolean F;
};
}
String expected = String.format("" +
"Usage: <main class> [-BCEF] [-A=<A>] [-D=<D>] [[-a=<a> <f0> <f1>] | (-x=<x> |%n" +
" -y=<y>)] <f2>%n" +
" <f2>%n" +
" -A=<A>%n" +
" -B%n" +
" -C%n" +
"Co-occurring options:%n" +
"These options must appear together, or not at all.%n" +
" <f0>%n" +
" <f1>%n" +
" -a=<a>%n" +
"Exclusive options:%n" +
" -x=<x>%n" +
" -y=<y>%n" +
"Remaining options:%n" +
" -D=<D>%n" +
" -E%n" +
" -F%n");
String actual = new CommandLine(new App(), new InnerClassFactory(this)).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testRequiredArgsInAGroupAreNotValidated() {
class App {
@ArgGroup(exclusive = true, multiplicity = "0..1")
Object exclusive = new Object() {
@Option(names = "-x", required = true) boolean x;
@ArgGroup(exclusive = false, multiplicity = "1")
Object all = new Object() {
@Option(names = "-a", required = true) int a;
@Parameters(index = "0") File f0;
};
};
}
String expected = String.format("" +
"Usage: <main class> [-x | (-a=<a> <f0>)]%n" +
" <f0>%n" +
" -a=<a>%n" +
" -x%n");
CommandLine cmd = new CommandLine(new App());
String actual = cmd.getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
cmd.parseArgs(); // no error
}
static class Mono {
@Option(names = "-a", required = true) int a;
}
static class RepeatingApp {
@ArgGroup(multiplicity = "2") List<Mono> monos;
}
@Test
public void testRepeatingGroupsSimple() {
RepeatingApp app = new RepeatingApp();
CommandLine cmd = new CommandLine(app);
ParseResult parseResult = cmd.parseArgs("-a", "1", "-a", "2");
assertEquals(2, app.monos.size());
assertEquals(1, app.monos.get(0).a);
assertEquals(2, app.monos.get(1).a);
GroupMatchContainer groupMatchContainer = parseResult.findMatches(cmd.getCommandSpec().argGroups().get(0)).get(0);
assertEquals(2, groupMatchContainer.matches().size());
ArgSpec a = cmd.getCommandSpec().findOption("-a");
ParseResult.GroupMatch multiple1 = groupMatchContainer.matches().get(0);
assertEquals(1, multiple1.matchCount(a));
List<Object> values1 = multiple1.matchedValues(a);
assertEquals(1, values1.size());
assertEquals(Integer.class, values1.get(0).getClass());
assertEquals(1, values1.get(0));
ParseResult.GroupMatch multiple2 = groupMatchContainer.matches().get(1);
assertEquals(1, multiple2.matchCount(a));
List<Object> values2 = multiple2.matchedValues(a);
assertEquals(1, values2.size());
assertEquals(Integer.class, values2.get(0).getClass());
assertEquals(2, values2.get(0));
}
@Test
public void testRepeatingGroupsValidation() {
//TestUtil.setTraceLevel("DEBUG");
RepeatingApp app = new RepeatingApp();
CommandLine cmd = new CommandLine(app);
try {
cmd.parseArgs("-a", "1");
fail("Expected exception");
} catch (CommandLine.ParameterException ex) {
assertEquals("Error: Group: (-a=<a>) must be specified 2 times but was matched 1 times", ex.getMessage());
}
}
static class RepeatingGroupWithOptionalElements635 {
@Option(names = {"-a", "--add-dataset"}, required = true) boolean add;
@Option(names = {"-d", "--dataset"} , required = true) String dataset;
@Option(names = {"-c", "--container"} , required = false) String container;
@Option(names = {"-t", "--type"} , required = false) String type;
}
@Command(name = "viewer", usageHelpWidth = 100)
static class RepeatingCompositeWithOptionalApp635 {
// SYNOPSIS: viewer (-a -d=DATASET [-c=CONTAINER] [-t=TYPE])... [-f=FALLBACK] <positional>
@ArgGroup(exclusive = false, multiplicity = "1..*")
List<RepeatingGroupWithOptionalElements635> composites;
@Option(names = "-f")
String fallback;
@Parameters(index = "0")
String positional;
}
@Test
public void testRepeatingCompositeGroupWithOptionalElements_Issue635() {
RepeatingCompositeWithOptionalApp635 app = new RepeatingCompositeWithOptionalApp635();
CommandLine cmd = new CommandLine(app);
String synopsis = new Help(cmd.getCommandSpec(), Help.defaultColorScheme(Help.Ansi.OFF)).synopsis(0);
assertEquals("viewer [-f=<fallback>] (-a -d=<dataset> [-c=<container>] [-t=<type>])... <positional>", synopsis.trim());
ParseResult parseResult = cmd.parseArgs("-a", "-d", "data1", "-a", "-d=data2", "-c=contain2", "-t=typ2", "pos", "-a", "-d=data3", "-c=contain3");
assertEquals("pos", parseResult.matchedPositionalValue(0, ""));
assertFalse(parseResult.hasMatchedOption("-f"));
GroupMatchContainer groupMatchContainer = parseResult.findMatches(cmd.getCommandSpec().argGroups().get(0)).get(0);
assertEquals(3, groupMatchContainer.matches().size());
CommandSpec spec = cmd.getCommandSpec();
List<String> data = Arrays.asList("data1", "data2", "data3");
List<String> contain = Arrays.asList(null, "contain2", "contain3");
List<String> type = Arrays.asList(null, "typ2", null);
for (int i = 0; i < 3; i++) {
ParseResult.GroupMatch multiple = groupMatchContainer.matches().get(i);
assertEquals(Arrays.asList(data.get(i)), multiple.matchedValues(spec.findOption("-d")));
if (contain.get(i) == null) {
assertEquals(Collections.emptyList(), multiple.matchedValues(spec.findOption("-c")));
} else {
assertEquals(Arrays.asList(contain.get(i)), multiple.matchedValues(spec.findOption("-c")));
}
if (type.get(i) == null) {
assertEquals(Collections.emptyList(), multiple.matchedValues(spec.findOption("-t")));
} else {
assertEquals(Arrays.asList(type.get(i)), multiple.matchedValues(spec.findOption("-t")));
}
}
assertEquals(3, app.composites.size());
for (int i = 0; i < 3; i++) {
assertEquals(data.get(i), app.composites.get(i).dataset);
assertEquals(contain.get(i), app.composites.get(i).container);
assertEquals(type.get(i), app.composites.get(i).type);
}
assertNull(app.fallback);
assertEquals("pos", app.positional);
}
static class RepeatingGroup635 {
@Option(names = {"-a", "--add-dataset"}, required = true) boolean add;
@Option(names = {"-c", "--container"} , required = true) String container;
@Option(names = {"-d", "--dataset"} , required = true) String dataset;
@Option(names = {"-t", "--type"} , required = true) String type;
}
@Command(name = "viewer", usageHelpWidth = 100)
static class RepeatingCompositeApp635 {
// SYNOPSIS: viewer (-a -d=DATASET -c=CONTAINER -t=TYPE)... [-f=FALLBACK] <positional>
@ArgGroup(exclusive = false, multiplicity = "1..*")
List<RepeatingGroup635> composites;
@Option(names = "-f")
String fallback;
@Parameters(index = "0")
String positional;
}
@Test
public void testRepeatingCompositeGroup_Issue635() {
RepeatingCompositeApp635 app = new RepeatingCompositeApp635();
CommandLine cmd = new CommandLine(app);
String synopsis = new Help(cmd.getCommandSpec(), Help.defaultColorScheme(Help.Ansi.OFF)).synopsis(0);
assertEquals("viewer [-f=<fallback>] (-a -c=<container> -d=<dataset> -t=<type>)... <positional>", synopsis.trim());
ParseResult parseResult = cmd.parseArgs("-a", "-d", "data1", "-c=contain1", "-t=typ1", "-a", "-d=data2", "-c=contain2", "-t=typ2", "pos", "-a", "-d=data3", "-c=contain3", "-t=type3");
assertEquals("pos", parseResult.matchedPositionalValue(0, ""));
assertFalse(parseResult.hasMatchedOption("-f"));
ParseResult.GroupMatchContainer groupMatchContainer = parseResult.findMatches(cmd.getCommandSpec().argGroups().get(0)).get(0);
assertEquals(3, groupMatchContainer.matches().size());
CommandSpec spec = cmd.getCommandSpec();
List<String> data = Arrays.asList("data1", "data2", "data3");
List<String> contain = Arrays.asList("contain1", "contain2", "contain3");
List<String> type = Arrays.asList("typ1", "typ2", "type3");
for (int i = 0; i < 3; i++) {
ParseResult.GroupMatch multiple = groupMatchContainer.matches().get(i);
assertEquals(Arrays.asList(data.get(i)), multiple.matchedValues(spec.findOption("-d")));
assertEquals(Arrays.asList(contain.get(i)), multiple.matchedValues(spec.findOption("-c")));
assertEquals(Arrays.asList(type.get(i)), multiple.matchedValues(spec.findOption("-t")));
}
assertEquals(3, app.composites.size());
for (int i = 0; i < 3; i++) {
assertEquals(data.get(i), app.composites.get(i).dataset);
assertEquals(contain.get(i), app.composites.get(i).container);
assertEquals(type.get(i), app.composites.get(i).type);
}
assertNull(app.fallback);
assertEquals("pos", app.positional);
}
@Command(name = "abc")
static class OptionPositionalCompositeApp {
@ArgGroup(exclusive = false, validate = true, multiplicity = "1..*",
heading = "This is the options list heading (See #450)", order = 1)
List<OptionPositionalComposite> compositeArguments;
}
static class OptionPositionalComposite {
@Option(names = "--mode", required = true) String mode;
@Parameters(index = "0") String file;
}
@Test
public void testOptionPositionalComposite() {
OptionPositionalCompositeApp app = new OptionPositionalCompositeApp();
CommandLine cmd = new CommandLine(app);
String synopsis = new Help(cmd.getCommandSpec(), Help.defaultColorScheme(Help.Ansi.OFF)).synopsis(0);
assertEquals("abc (--mode=<mode> <file>)...", synopsis.trim());
ParseResult parseResult = cmd.parseArgs("--mode", "mode1", "/file/1", "--mode", "mode2", "/file/2", "--mode=mode3", "/file/3");
List<String> data = Arrays.asList("mode1", "mode2", "mode3");
List<String> file = Arrays.asList("/file/1", "/file/2", "/file/3");
assertEquals(3, app.compositeArguments.size());
for (int i = 0; i < 3; i++) {
assertEquals(data.get(i), app.compositeArguments.get(i).mode);
assertEquals(file.get(i), app.compositeArguments.get(i).file);
}
ParseResult.GroupMatchContainer groupMatchContainer = parseResult.findMatches(cmd.getCommandSpec().argGroups().get(0)).get(0);
assertEquals(3, groupMatchContainer.matches().size());
CommandSpec spec = cmd.getCommandSpec();
for (int i = 0; i < 3; i++) {
assertEquals(Arrays.asList(data.get(i)), groupMatchContainer.matches().get(i).matchedValues(spec.findOption("--mode")));
assertEquals(Arrays.asList(file.get(i)), groupMatchContainer.matches().get(i).matchedValues(spec.positionalParameters().get(0)));
}
}
@Test
public void testMultipleGroups() {
class MultiGroup {
// SYNOPSIS: [--mode=<mode> <file>]...
@ArgGroup(exclusive = false, multiplicity = "*")
OptionPositionalComposite[] optPos;
// SYNOPSIS: [-a -d=DATASET -c=CONTAINER -t=TYPE]
@ArgGroup(exclusive = false)
List<RepeatingGroup635> composites;
}
MultiGroup app = new MultiGroup();
CommandLine cmd = new CommandLine(app);
String synopsis = new Help(cmd.getCommandSpec(), Help.defaultColorScheme(Help.Ansi.OFF)).synopsis(0);
String expectedSynopsis = String.format("" +
"<main class> [--mode=<mode> <file>]... [-a -c=<container> -d=<dataset>%n" +
" -t=<type>]");
assertEquals(expectedSynopsis, synopsis.trim());
ParseResult parseResult = cmd.parseArgs("--mode=mode1", "/file/1", "-a", "-d=data1", "-c=contain1", "-t=typ1", "--mode=mode2", "/file/2");
List<ParseResult.GroupMatch> multiples = parseResult.getGroupMatches();
assertEquals(1, multiples.size());
GroupMatch groupMatch = multiples.get(0);
assertEquals(2, groupMatch.matchedSubgroups().size());
List<ArgGroupSpec> argGroups = cmd.getCommandSpec().argGroups();
ArgGroupSpec modeGroup = argGroups.get(0);
ArgGroupSpec addDatasetGroup = argGroups.get(1);
GroupMatchContainer modeGroupMatchContainer = groupMatch.matchedSubgroups().get(modeGroup);
assertEquals(2, modeGroupMatchContainer.matches().size());
GroupMatchContainer addDatasetGroupMatchContainer = groupMatch.matchedSubgroups().get(addDatasetGroup);
assertEquals(1, addDatasetGroupMatchContainer.matches().size());
}
static class CompositeGroupDemo {
@ArgGroup(exclusive = false, multiplicity = "1..*")
List<Composite> composites;
static class Composite {
@ArgGroup(exclusive = false, multiplicity = "0..1")
Dependent dependent;
@ArgGroup(exclusive = true, multiplicity = "1")
Exclusive exclusive;
}
static class Dependent {
@Option(names = "-a", required = true)
int a;
@Option(names = "-b", required = true)
int b;
@Option(names = "-c", required = true)
int c;
}
static class Exclusive {
@Option(names = "-x", required = true)
boolean x;
@Option(names = "-y", required = true)
boolean y;
@Option(names = "-z", required = true)
boolean z;
}
}
@Test
public void testCompositeDemo() {
CompositeGroupDemo example = new CompositeGroupDemo();
CommandLine cmd = new CommandLine(example);
cmd.parseArgs("-x", "-a=1", "-b=1", "-c=1", "-a=2", "-b=2", "-c=2", "-y");
assertEquals(2, example.composites.size());
CompositeGroupDemo.Composite c1 = example.composites.get(0);
assertTrue(c1.exclusive.x);
assertEquals(1, c1.dependent.a);
assertEquals(1, c1.dependent.b);
assertEquals(1, c1.dependent.c);
CompositeGroupDemo.Composite c2 = example.composites.get(1);
assertTrue(c2.exclusive.y);
assertEquals(2, c2.dependent.a);
assertEquals(2, c2.dependent.b);
assertEquals(2, c2.dependent.c);
}
@Test
public void testIssue1053NPE() {
CompositeGroupDemo example = new CompositeGroupDemo();
CommandLine cmd = new CommandLine(example);
cmd.parseArgs("-a 1 -b 1 -c 1 -x -z".split(" "));
assertEquals(2, example.composites.size());
CompositeGroupDemo.Composite c1 = example.composites.get(0);
assertTrue(c1.exclusive.x);
assertFalse(c1.exclusive.y);
assertFalse(c1.exclusive.z);
assertEquals(1, c1.dependent.a);
assertEquals(1, c1.dependent.b);
assertEquals(1, c1.dependent.c);
CompositeGroupDemo.Composite c2 = example.composites.get(1);
assertFalse(c2.exclusive.x);
assertFalse(c2.exclusive.y);
assertTrue(c2.exclusive.z);
assertNull(c2.dependent);
}
static class Issue1054 {
@ArgGroup(exclusive = false, multiplicity = "1..*")
private List<Modification> modifications = null;
private static class Modification {
@Option(names = { "-f", "--find" }, required = true)
public Pattern findPattern = null;
@ArgGroup(exclusive = true, multiplicity = "1")
private Change change = null;
}
private static class Change {
@Option(names = { "-d", "--delete" }, required = true)
public boolean delete = false;
@Option(names = { "-w", "--replace-with" }, required = true)
public String replacement = null;
}
}
//@Ignore
@Test // https://github.com/remkop/picocli/issues/1054
public void testIssue1054() {
//-f pattern1 -f pattern2 -d --> accepted --> wrong: findPattern = "pattern2", "pattern1" is lost/ignored
try {
//TestUtil.setTraceLevel("DEBUG");
Issue1054 bean3 = new Issue1054();
new CommandLine(bean3).parseArgs("-f pattern1 -f pattern2 -d".split(" "));
//System.out.println(bean3);
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): (-d | -w=<replacement>)", ex.getMessage());
}
}
@Test
public void testIssue1054Variation() {
try {
Issue1054 bean3 = new Issue1054();
new CommandLine(bean3).parseArgs("-f pattern1 -f pattern2".split(" "));
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): (-d | -w=<replacement>)", ex.getMessage());
}
}
@Test // https://github.com/remkop/picocli/issues/1054
public void testIssue1054RegressionTest() {
//-f pattern -d --> accepted --> ok
Issue1054 bean1 = new Issue1054();
new CommandLine(bean1).parseArgs("-f pattern -d".split(" "));
assertEquals(1, bean1.modifications.size());
assertEquals("pattern", bean1.modifications.get(0).findPattern.pattern());
assertTrue(bean1.modifications.get(0).change.delete);
assertNull(bean1.modifications.get(0).change.replacement);
//-f pattern -w text --> accepted --> ok
Issue1054 bean2 = new Issue1054();
new CommandLine(bean2).parseArgs("-f pattern -w text".split(" ")); // also mentioned in #1055
assertEquals(1, bean2.modifications.size());
assertEquals("pattern", bean2.modifications.get(0).findPattern.pattern());
assertFalse(bean2.modifications.get(0).change.delete);
assertEquals("text", bean2.modifications.get(0).change.replacement);
//-f pattern -d -w text --> error --> ok
try {
new CommandLine(new Issue1054()).parseArgs("-f pattern -d -w text".split(" "));
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --find=<findPattern>", ex.getMessage());
}
//-d -f pattern -w text --> error --> ok
try {
new CommandLine(new Issue1054()).parseArgs("-d -f pattern -w text".split(" "));
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --find=<findPattern>", ex.getMessage());
}
}
@Test // https://github.com/remkop/picocli/issues/1055
public void testIssue1055Case1() {
//-f -f -w text --> accepted --> wrong: findPattern = "-f", means, the second -f is treated as an option-parameter for the first -f
try {
Issue1054 bean = new Issue1054();
new CommandLine(bean).parseArgs("-f -f -w text".split(" "));
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Expected parameter for option '--find' but found '-f'", ex.getMessage());
}
}
@Test // https://github.com/remkop/picocli/issues/1055
public void testIssue1055Case2() {
//-f pattern -w -d --> wrong: replacement = "-d", means -d is treated as an option-parameter for -w
try {
Issue1054 bean = new Issue1054();
new CommandLine(bean).parseArgs("-f pattern -w -d".split(" "));
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Expected parameter for option '--replace-with' but found '-d'", ex.getMessage());
}
}
static class CompositeGroupSynopsisDemo {
@ArgGroup(exclusive = false, multiplicity = "2..*")
List<Composite> composites;
static class Composite {
@ArgGroup(exclusive = false, multiplicity = "1")
Dependent dependent;
@ArgGroup(exclusive = true, multiplicity = "1")
Exclusive exclusive;
}
static class Dependent {
@Option(names = "-a", required = true)
int a;
@Option(names = "-b", required = true)
int b;
@Option(names = "-c", required = true)
int c;
}
static class Exclusive {
@Option(names = "-x", required = true)
boolean x;
@Option(names = "-y", required = true)
boolean y;
@Option(names = "-z", required = true)
boolean z;
}
}
@Test
public void testCompositeSynopsisDemo() {
CompositeGroupSynopsisDemo example = new CompositeGroupSynopsisDemo();
CommandLine cmd = new CommandLine(example);
String synopsis = cmd.getCommandSpec().argGroups().get(0).synopsis();
assertEquals("((-a=<a> -b=<b> -c=<c>) (-x | -y | -z)) ((-a=<a> -b=<b> -c=<c>) (-x | -y | -z))...", synopsis);
}
// https://github.com/remkop/picocli/issues/635
@Command(name = "test-composite")
static class TestComposite {
@ArgGroup(exclusive = false, multiplicity = "0..*")
List<OuterGroup> outerList;
static class OuterGroup {
@Option(names = "--add-group", required = true) boolean addGroup;
@ArgGroup(exclusive = false, multiplicity = "1")
Inner inner;
static class Inner {
@Option(names = "--option1", required = true) String option1;
@Option(names = "--option2", required = true) String option2;
}
}
}
@Test // https://github.com/remkop/picocli/issues/655
public void testCompositeValidation() {
TestComposite app = new TestComposite();
CommandLine cmd = new CommandLine(app);
try {
cmd.parseArgs("--add-group", "--option2=1");
fail("Expect exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --option1=<option1>", ex.getMessage());
}
try {
cmd.parseArgs("--add-group");
fail("Expect exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): (--option1=<option1> --option2=<option2>)", ex.getMessage());
}
try {
cmd.parseArgs("--add-group", "--option2=1", "--option2=1");
fail("Expect exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --option1=<option1>", ex.getMessage());
}
try {
cmd.parseArgs("--add-group", "--option2=1", "--option1=1", "--add-group", "--option2=1");
fail("Expect exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --option1=<option1>", ex.getMessage());
}
try {
ParseResult parseResult = cmd.parseArgs("--add-group", "--option2=1", "--option1=1", "--add-group");
fail("Expect exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): (--option1=<option1> --option2=<option2>)", ex.getMessage());
}
}
@Test
public void testHelp() {
@Command(name = "abc", mixinStandardHelpOptions = true)
class App {
@ArgGroup(multiplicity = "1")
Composite composite;
}
CommandLine commandLine = new CommandLine(new App());
ParseResult parseResult = commandLine.parseArgs("--help");
assertTrue(parseResult.isUsageHelpRequested());
}
@Command(name = "ArgGroupsTest", resourceBundle = "picocli.arggroup-localization")
static class LocalizedCommand {
@Option(names = {"-q", "--quiet"}, required = true)
static boolean quiet;
@ArgGroup(exclusive = true, multiplicity = "1", headingKey = "myKey")
LocalizedGroup datasource;
static class LocalizedGroup {
@Option(names = "-a", required = true)
static boolean isA;
@Option(names = "-b", required = true)
static File dataFile;
}
}
@Test
public void testArgGroupHeaderLocalization() {
CommandLine cmd = new CommandLine(new LocalizedCommand());
String expected = String.format("" +
"Usage: ArgGroupsTest -q (-a | -b=<dataFile>)%n" +
" -q, --quiet My description for option quiet%n" +
"My heading text%n" +
" -a My description for exclusive option a%n" +
" -b=<dataFile>%n");
String actual = cmd.getUsageMessage();
assertEquals(expected, actual);
}
@Command(name = "ArgGroupsTest")
static class TestCommand implements Runnable {
@ArgGroup( exclusive = true)
DataSource datasource;
static class DataSource {
@Option(names = "-a", required = true, defaultValue = "Strings.gxl")
static String aString;
}
public void run() { }
}
@Test
public void testIssue661StackOverflow() {
CommandLine cmd = new CommandLine(new TestCommand());
cmd.parseArgs("-a=Foo");
cmd.setExecutionStrategy(new CommandLine.RunAll()).execute();
}
// TODO add tests with positional interactive params in group
// TODO add tests with positional params in multiple groups
static class Issue722 {
static class Level1Argument {
@Option(names = "--level-1", required = true)
private String l1;
@ArgGroup(exclusive = false, multiplicity = "1")
private Level2aArgument level2a;
@ArgGroup(exclusive = false, multiplicity = "1")
private Level2bArgument level2b;
}
static class Level2aArgument {
@Option(names = "--level-2a", required = true)
private String l2a;
}
static class Level2bArgument {
@Option(names = "--level-2b", required = true)
private String l2b;
@ArgGroup(exclusive = false, multiplicity = "1")
private Level3aArgument level3a;
@ArgGroup(exclusive = false, multiplicity = "1")
private Level3bArgument level3b;
}
static class Level3aArgument {
@Option(names = "--level-3a", required = true)
private String l3a;
}
static class Level3bArgument {
@Option(names = { "--level-3b"}, required = true)
private String l3b;
}
@Command(name = "arg-group-test", separator = " ", subcommands = {CreateCommand.class, CommandLine.HelpCommand.class})
public static class ArgGroupCommand implements Runnable {
public void run() {
}
}
@Command(name = "create", separator = " ", helpCommand = true)
public static class CreateCommand implements Runnable {
@Option(names = "--level-0", required = true)
private String l0;
@ArgGroup(exclusive = false, multiplicity = "1")
private Level1Argument level1 = new Level1Argument();
public void run() {
}
}
}
// https://github.com/remkop/picocli/issues/722
@Test
public void testIssue722() {
String expected = String.format("" +
"create --level-0 <l0> (--level-1 <l1> (--level-2a <l2a>) (--level-2b <l2b>%n" +
" (--level-3a <l3a>) (--level-3b <l3b>)))%n");
CommandLine cmd = new CommandLine(new Issue722.CreateCommand());
Help help = new Help(cmd.getCommandSpec(), Help.defaultColorScheme(Help.Ansi.OFF));
String actual = help.synopsis(0);
assertEquals(expected, actual);
}
@Command(name = "ArgGroupsTest")
static class CommandWithSplitGroup {
@ArgGroup(exclusive = false)
DataSource datasource;
static class DataSource {
@Option(names = "-single", split = ",")
int single;
@Option(names = "-array", split = ",")
int[] array;
}
}
@Test
// https://github.com/remkop/picocli/issues/745
public void testIssue745SplitErrorMessageIfValidationDisabled() {
CommandWithSplitGroup bean = new CommandWithSplitGroup();
System.setProperty("picocli.ignore.invalid.split", "");
CommandLine cmd = new CommandLine(bean);
// split attribute is honoured if option type is multi-value (array, Collection, Map)
cmd.parseArgs("-array=1,2");
assertArrayEquals(new int[] {1, 2}, bean.datasource.array);
// split attribute is ignored if option type is single value
// error because value cannot be assigned to type `int`
try {
cmd.parseArgs("-single=1,2");
fail("Expected exception");
} catch (ParameterException ex) {
assertEquals("Invalid value for option '-single': '1,2' is not an int", ex.getMessage());
}
// split attribute ignored for simple commands without argument groups
try {
new CommandLine(new CommandWithSplitGroup.DataSource()).parseArgs("-single=1,2");
fail("Expected exception");
} catch (ParameterException ex) {
assertEquals("Invalid value for option '-single': '1,2' is not an int", ex.getMessage());
}
}
@Test
// https://github.com/remkop/picocli/issues/745
public void testIssue745SplitDisallowedForSingleValuedOption() {
CommandWithSplitGroup bean = new CommandWithSplitGroup();
try {
new CommandLine(bean);
fail("Expected exception");
} catch (InitializationException ex) {
assertEquals("Only multi-value options and positional parameters should have a split regex (this check can be disabled by setting system property 'picocli.ignore.invalid.split')", ex.getMessage());
}
try {
new CommandLine(new CommandWithSplitGroup.DataSource());
fail("Expected initialization exception");
} catch (InitializationException ex) {
assertEquals("Only multi-value options and positional parameters should have a split regex (this check can be disabled by setting system property 'picocli.ignore.invalid.split')", ex.getMessage());
}
}
@Command(name = "ArgGroupsTest")
static class CommandWithDefaultValue {
@ArgGroup(exclusive = false)
InitializedGroup initializedGroup = new InitializedGroup();
@ArgGroup(exclusive = false)
DeclaredGroup declaredGroup;
static class InitializedGroup {
@Option(names = "-staticX", arity = "0..1", defaultValue = "999", fallbackValue = "-88" )
static int staticX;
@Option(names = "-instanceX", arity = "0..1", defaultValue = "999", fallbackValue = "-88" )
int instanceX;
}
static class DeclaredGroup {
@Option(names = "-staticY", arity = "0..1", defaultValue = "999", fallbackValue = "-88" )
static Integer staticY;
@Option(names = "-instanceY", arity = "0..1", defaultValue = "999", fallbackValue = "-88" )
Integer instanceY;
}
}
@Test
// https://github.com/remkop/picocli/issues/746
public void test746DefaultValue() {
//TestUtil.setTraceLevel("DEBUG");
CommandWithDefaultValue bean = new CommandWithDefaultValue();
CommandLine cmd = new CommandLine(bean);
cmd.parseArgs();
assertEquals(999, bean.initializedGroup.instanceX);
assertEquals(999, CommandWithDefaultValue.InitializedGroup.staticX);
assertNull(bean.declaredGroup);
assertNull(CommandWithDefaultValue.DeclaredGroup.staticY);
}
static class Issue746 {
static class Level1Argument {
@Option(names = "--l1a", required = true, defaultValue = "l1a")
private String l1a;
@Option(names = "--l1b", required = true)
private String l1b;
@ArgGroup(exclusive = false, multiplicity = "1")
private Level2Argument level2;
}
static class Level2Argument {
@Option(names = "--l2a", required = true, defaultValue = "l2a")
private String l2a;
@Option(names = "--l2b", required = true)
private String l2b;
@ArgGroup(exclusive = false, multiplicity = "1")
private Level3Argument level3;
}
static class Level3Argument {
@Option(names = "--l3a", required = true)
private String l3a;
@Option(names = { "--l3b"}, required = true, defaultValue = "l3b")
private String l3b;
}
@Command(name = "arg-group-test", subcommands = {CreateCommand.class, CommandLine.HelpCommand.class})
public static class ArgGroupCommand implements Runnable {
public void run() { }
}
@Command(name = "create", helpCommand = true)
public static class CreateCommand implements Runnable {
@Option(names = "--l0", required = true, defaultValue = "l0")
private String l0;
@ArgGroup(exclusive = false, multiplicity = "0..1")
private Level1Argument level1 = new Level1Argument();
public void run() { }
}
}
@Test
// https://github.com/remkop/picocli/issues/746
public void testIssue746DefaultValueWithNestedArgGroups() {
Issue746.CreateCommand bean = new Issue746.CreateCommand();
CommandLine cmd = new CommandLine(bean);
cmd.parseArgs();
assertEquals("l0", bean.l0);
assertEquals("l1a", bean.level1.l1a);
assertNull(bean.level1.l1b);
assertNull(bean.level1.level2);
}
@Test
// https://github.com/remkop/picocli/issues/746
public void testIssue746ArgGroupWithDefaultValuesSynopsis() {
String expected = String.format("" +
"create [--l0=<l0>] [[--l1a=<l1a>] --l1b=<l1b> ([--l2a=<l2a>] --l2b=<l2b>%n" +
" (--l3a=<l3a> [--l3b=<l3b>]))]%n");
CommandLine cmd = new CommandLine(new Issue746.CreateCommand());
Help help = new Help(cmd.getCommandSpec(), Help.defaultColorScheme(Help.Ansi.OFF));
String actual = help.synopsis(0);
assertEquals(expected, actual);
}
@Test
// https://github.com/remkop/picocli/issues/746
public void testIssue746ArgGroupWithDefaultValuesParsing() {
Issue746.CreateCommand bean = new Issue746.CreateCommand();
CommandLine cmd = new CommandLine(bean);
cmd.parseArgs("--l1b=L1B --l2b=L2B --l3a=L3A".split(" "));
assertEquals("default value", "l0", bean.l0);
assertNotNull(bean.level1);
assertEquals("default value", "l1a", bean.level1.l1a);
assertEquals("specified value", "L1B", bean.level1.l1b);
assertNotNull(bean.level1.level2);
assertEquals("default value", "l2a", bean.level1.level2.l2a);
assertEquals("specified value", "L2B", bean.level1.level2.l2b);
assertNotNull(bean.level1.level2.level3);
assertEquals("default value", "l3b", bean.level1.level2.level3.l3b);
assertEquals("specified value", "L3A", bean.level1.level2.level3.l3a);
}
@Command(name = "Issue742")
static class Issue742 {
@ArgGroup(exclusive = false, multiplicity = "2")
List<DataSource> datasource;
static class DataSource {
@Option(names = "-g", required = true, defaultValue = "e")
String aString;
}
}
@Test
// https://github.com/remkop/picocli/issues/742
public void testIssue742FalseErrorMessage() {
//TestUtil.setTraceLevel("DEBUG");
CommandLine cmd = new CommandLine(new Issue742());
ParseResult parseResult = cmd.parseArgs("-g=2", "-g=3");
List<ParseResult.GroupMatch> multiples = parseResult.getGroupMatches();
assertEquals(1, multiples.size());
GroupMatch groupMatch = multiples.get(0);
assertEquals(1, groupMatch.matchedSubgroups().size());
ArgGroupSpec dsGroup = cmd.getCommandSpec().argGroups().get(0);
@SuppressWarnings("unchecked")
List<Issue742.DataSource> datasources = (List<Issue742.DataSource>) dsGroup.userObject();
assertEquals(2, datasources.size());
Issue742.DataSource ds1 = datasources.get(0);
assertEquals("2", ds1.aString);
Issue742.DataSource ds2 = datasources.get(1);
assertEquals("3", ds2.aString);
GroupMatchContainer modeGroupMatchContainer = groupMatch.matchedSubgroups().get(dsGroup);
assertEquals(2, modeGroupMatchContainer.matches().size());
GroupMatch dsGroupMatch1 = modeGroupMatchContainer.matches().get(0);
assertEquals(0, dsGroupMatch1.matchedSubgroups().size());
assertEquals(Arrays.asList("2"), dsGroupMatch1.matchedValues(dsGroup.args().iterator().next()));
GroupMatch dsGroupMatch2 = modeGroupMatchContainer.matches().get(1);
assertEquals(0, dsGroupMatch2.matchedSubgroups().size());
assertEquals(Arrays.asList("3"), dsGroupMatch2.matchedValues(dsGroup.args().iterator().next()));
}
@Command(name = "ExecuteTest")
static class Issue758 {
@ArgGroup(exclusive = false)
static D d;
static class D {
@Option(names = "p")
static int p1;
@Option(names = "p")
static int p2;
}
}
@Test
public void testIssue758() {
Issue758 app = new Issue758();
try {
new CommandLine(app);
} catch (DuplicateOptionAnnotationsException ex) {
String name = Issue758.D.class.getName();
String msg = "Option name 'p' is used by both field static int " + name + ".p2 and field static int " + name + ".p1";
assertEquals(msg, ex.getMessage());
}
}
static class Issue807Command {
@ArgGroup(validate = false, heading = "%nGlobal options:%n")
protected GlobalOptions globalOptions = new GlobalOptions();
static class GlobalOptions {
@Option(names = "-s", description = "ssss")
boolean slowClock = false;
@Option(names = "-v", description = "vvvv")
boolean verbose = false;
}
}
@Test
public void testIssue807Validation() {
// should not throw MutuallyExclusiveArgsException
new CommandLine(new Issue807Command()).parseArgs("-s", "-v");
}
static class Issue807SiblingCommand {
@ArgGroup(validate = true, heading = "%nValidating subgroup options:%n")
protected ValidatingOptions validatingOptions = new ValidatingOptions();
@ArgGroup(validate = false, heading = "%nGlobal options:%n")
protected Issue807Command globalOptions = new Issue807Command();
static class ValidatingOptions {
@Option(names = "-x", description = "xxx")
boolean x = false;
@Option(names = "-y", description = "yyy")
boolean y = false;
}
}
@Test
public void testIssue807SiblingValidation() {
try {
new CommandLine(new Issue807SiblingCommand()).parseArgs("-s", "-v", "-x", "-y");
fail("Expected mutually exclusive args exception");
} catch (MutuallyExclusiveArgsException ex) {
assertEquals("Error: -x, -y are mutually exclusive (specify only one)", ex.getMessage());
}
}
static class Issue807NestedCommand {
@ArgGroup(validate = false, heading = "%nNon-validating over-arching group:%n")
protected Combo nonValidating = new Combo();
static class Combo {
@ArgGroup(validate = true, heading = "%nValidating subgroup options:%n")
protected ValidatingOptions validatingOptions = new ValidatingOptions();
@ArgGroup(validate = true, heading = "%nGlobal options:%n")
protected Issue807Command globalOptions = new Issue807Command();
}
static class ValidatingOptions {
@Option(names = "-x", description = "xxx")
boolean x = false;
@Option(names = "-y", description = "yyy")
boolean y = false;
}
}
@Test
public void testIssue807NestedValidation() {
// should not throw MutuallyExclusiveArgsException
new CommandLine(new Issue807NestedCommand()).parseArgs("-s", "-v", "-x", "-y");
}
static class Issue829Group {
int x;
int y;
@Option(names = "-x") void x(int x) {this.x = x;}
@Option(names = "-y") void y(int y) {this.y = y;}
}
@Command(subcommands = Issue829Subcommand.class)
static class Issue829TopCommand {
@ArgGroup Issue829Group group;
@Command
void sub2(@ArgGroup Issue829Group group) {
assertEquals(0, group.x);
assertEquals(3, group.y);
}
}
@Command(name = "sub")
static class Issue829Subcommand {
@ArgGroup List<Issue829Group> group;
}
@Test
public void testIssue829NPE_inSubcommandWithArgGroup() {
//TestUtil.setTraceLevel("DEBUG");
ParseResult parseResult = new CommandLine(new Issue829TopCommand()).parseArgs("-x=1", "sub", "-y=2");
assertEquals(1, ((Issue829TopCommand)parseResult.commandSpec().userObject()).group.x);
Issue829Subcommand sub = (Issue829Subcommand) parseResult.subcommand().commandSpec().userObject();
assertEquals(0, sub.group.get(0).x);
assertEquals(2, sub.group.get(0).y);
new CommandLine(new Issue829TopCommand()).parseArgs("sub2", "-y=3");
}
static class Issue815Group {
@Option(names = {"--age"})
Integer age;
@Option(names = {"--id"})
List<String> id;
}
static class Issue815 {
@ArgGroup(exclusive = false, multiplicity = "1")
Issue815Group group;
}
@Test
public void testIssue815() {
//TestUtil.setTraceLevel("DEBUG");
Issue815 userObject = new Issue815();
new CommandLine(userObject).parseArgs("--id=123", "--id=456");
assertNotNull(userObject.group);
assertNull(userObject.group.age);
assertNotNull(userObject.group.id);
assertEquals(Arrays.asList("123", "456"), userObject.group.id);
}
static class Issue810Command {
@ArgGroup(validate = false, heading = "%nGrouped options:%n")
MyGroup myGroup = new MyGroup();
static class MyGroup {
@Option(names = "-s", description = "ssss", required = true, defaultValue = "false")
boolean s = false;
@Option(names = "-v", description = "vvvv", required = true, defaultValue = "false")
boolean v = false;
}
}
@Test
public void testIssue810Validation() {
// should not throw MutuallyExclusiveArgsException
Issue810Command app = new Issue810Command();
new CommandLine(app).parseArgs("-s", "-v");
assertTrue(app.myGroup.s);
assertTrue(app.myGroup.v);
// app = new Issue810Command();
new CommandLine(app).parseArgs("-s");
assertTrue(app.myGroup.s);
assertFalse(app.myGroup.v);
new CommandLine(app).parseArgs("-v");
assertFalse(app.myGroup.s);
assertTrue(app.myGroup.v);
}
static class Issue810WithExplicitExclusiveGroup {
@ArgGroup(exclusive = true, validate = false, heading = "%nGrouped options:%n")
MyGroup myGroup = new MyGroup();
static class MyGroup {
@Option(names = "-s", required = true)
boolean s = false;
@Option(names = "-v", required = true)
boolean v = false;
}
}
@Test
public void testNonValidatingOptionsAreNotExclusive() {
CommandSpec spec = CommandSpec.forAnnotatedObject(new Issue810Command());
assertFalse(spec.argGroups().get(0).exclusive());
CommandSpec spec2 = CommandSpec.forAnnotatedObject(new Issue810WithExplicitExclusiveGroup());
assertFalse(spec2.argGroups().get(0).exclusive());
}
static class Issue839Defaults {
@ArgGroup(validate = false)
Group group;
static class Group {
@Option(names = "-a", description = "a. Default-${DEFAULT-VALUE}")
String a = "aaa";
@Option(names = "-b", defaultValue = "bbb", description = "b. Default-${DEFAULT-VALUE}")
String b;
}
}
@Ignore
@Test
public void testIssue839Defaults() {
Issue839Defaults app = new Issue839Defaults();
String actual = new CommandLine(app).getUsageMessage(Help.Ansi.OFF);
String expected = String.format("" +
"Usage: <main class> [-a=<a>] [-b=<b>]%n" +
" -a=<a> a. Default-aaa%n" +
" -b=<b> b. Default-bbb%n");
assertEquals(expected, actual);
}
static class Issue870Group {
@Option(names = {"--group"}, required = true) String name;
@Option(names = {"--opt1"}) int opt1;
@Option(names = {"--opt2"}) String opt2;
}
static class Issue870App {
@ArgGroup(exclusive = false, multiplicity = "0..*")
List<Issue870Group> groups;
}
@Test
public void testIssue870RequiredOptionValidation() {
try {
new CommandLine(new Issue870App()).parseArgs("--opt1=1");
fail("Expected MissingParameterException");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --group=<name>", ex.getMessage());
}
}
static class ExclusiveBooleanGroup871 {
@Option(names = "-a", required = true) boolean a;
@Option(names = "-b", required = true) boolean b;
//@Option(names = "--opt") String opt;
}
@Test
public void testMultivalueExclusiveBooleanGroup() {
class MyApp {
@ArgGroup(exclusive = true, multiplicity = "0..*")
List<ExclusiveBooleanGroup871> groups;
}
MyApp myApp = CommandLine.populateCommand(new MyApp(), "-a", "-b");
assertEquals(2, myApp.groups.size());
MyApp myApp2 = CommandLine.populateCommand(new MyApp(), "-b", "-a");
assertEquals(2, myApp2.groups.size());
}
static class ExclusiveStringOptionGroup871 {
@Option(names = "-a", required = false) String a;
@Option(names = "-b", required = true) String b;
@Option(names = "--opt") String opt;
}
@Test
public void testAllOptionsRequiredInExclusiveGroup() {
class MyApp {
@ArgGroup(exclusive = true)
ExclusiveStringOptionGroup871 group;
}
CommandLine cmd = new CommandLine(new MyApp());
List<ArgGroupSpec> argGroupSpecs = cmd.getCommandSpec().argGroups();
assertEquals(1, argGroupSpecs.size());
for (ArgSpec arg : argGroupSpecs.get(0).args()) {
assertTrue(arg.required());
}
}
@Test
public void testMultivalueExclusiveStringOptionGroup() {
class MyApp {
@ArgGroup(exclusive = true, multiplicity = "0..*")
List<ExclusiveStringOptionGroup871> groups;
}
MyApp myApp = CommandLine.populateCommand(new MyApp(), "-a=1", "-b=2");
assertEquals(2, myApp.groups.size());
MyApp myApp2 = CommandLine.populateCommand(new MyApp(), "-b=1", "-a=2");
assertEquals(2, myApp2.groups.size());
}
static class NonExclusiveGroup871 {
@Option(names = "-a", required = false) String a;
@Option(names = "-b", required = false) String b;
@Option(names = "-c") String c; // default is not required
public String toString() {
return String.format("a=%s, b=%s, c=%s", a, b, c);
}
}
@Ignore //https://github.com/remkop/picocli/issues/871
@Test
public void testNonExclusiveGroupMustHaveOneRequiredOption() {
class MyApp {
@ArgGroup(exclusive = false)
NonExclusiveGroup871 group;
}
CommandLine cmd = new CommandLine(new MyApp());
List<ArgGroupSpec> argGroupSpecs = cmd.getCommandSpec().argGroups();
assertEquals(1, argGroupSpecs.size());
int requiredCount = 0;
for (ArgSpec arg : argGroupSpecs.get(0).args()) {
if (arg.required()) {
requiredCount++;
}
}
assertTrue(requiredCount > 0);
}
@Test
public void testNonExclusiveGroupWithoutRequiredOption() {
class MyApp {
@ArgGroup(exclusive = false)
NonExclusiveGroup871 group;
}
CommandLine cmd = new CommandLine(new MyApp());
MyApp myApp1 = CommandLine.populateCommand(new MyApp(), "-a=1");
//System.out.println(myApp1.group);
assertEquals("1", myApp1.group.a);
assertNull(myApp1.group.b);
assertNull(myApp1.group.c);
MyApp myApp2 = CommandLine.populateCommand(new MyApp(), "-b=1", "-a=2");
//System.out.println(myApp2.group);
assertEquals("2", myApp2.group.a);
assertEquals("1", myApp2.group.b);
assertNull(myApp2.group.c);
MyApp myApp3 = CommandLine.populateCommand(new MyApp(), "-c=1", "-a=2");
//System.out.println(myApp3.group);
assertEquals("2", myApp3.group.a);
assertEquals("1", myApp3.group.c);
assertNull(myApp3.group.b);
MyApp myApp4 = CommandLine.populateCommand(new MyApp(), "-c=1", "-b=2");
//System.out.println(myApp4.group);
assertEquals("2", myApp4.group.b);
assertEquals("1", myApp4.group.c);
assertNull(myApp4.group.a);
MyApp myApp5 = CommandLine.populateCommand(new MyApp(), "-c=1");
//System.out.println(myApp5.group);
assertNull(myApp5.group.b);
assertEquals("1", myApp5.group.c);
assertNull(myApp5.group.a);
MyApp myApp6 = CommandLine.populateCommand(new MyApp());
//System.out.println(myApp6.group);
assertNull(myApp6.group);
}
static class Issue933 implements Runnable {
@ArgGroup(exclusive = true, multiplicity = "1")
private ExclusiveOption1 exclusiveOption1;
static class ExclusiveOption1 {
@Option(names = { "-a" })
private String optionA;
@Option(names = { "-b" })
private String optionB;
}
@ArgGroup(exclusive = true, multiplicity = "1")
private ExclusiveOption2 exclusiveOption2;
static class ExclusiveOption2 {
@Option(names = { "-c" })
private String optionC;
@Option(names = { "-d" })
private String optionD;
}
public static void main(String[] args) {
System.exit(new CommandLine(new Issue933()).execute(args));
}
public void run() {
System.out.println("TestBugCLI.run()");
}
}
@Test
public void testIssue933() {
//new CommandLine(new Issue933()).execute("-a A -b B -c C".split(" "));
//System.out.println("OK");
Supplier<CommandLine> supplier = new Supplier<CommandLine>() {
public CommandLine get() { return new CommandLine(new Issue933()); }};
Execution execution = Execution.builder(supplier).execute("-a A -c C -d D".split(" "));
String expected = String.format("" +
"Error: -c=<optionC>, -d=<optionD> are mutually exclusive (specify only one)%n" +
"Usage: <main class> (-a=<optionA> | -b=<optionB>) (-c=<optionC> | -d=<optionD>)%n" +
" -a=<optionA>%n" +
" -b=<optionB>%n" +
" -c=<optionC>%n" +
" -d=<optionD>%n");
execution.assertSystemErr(expected);
}
static class Issue938NestedMutualDependency {
static class OtherOptions {
@Option(
names = {"-o1", "--other-option-1"},
arity = "1",
required = true)
private String first;
@Option(
names = {"-o2", "--other-option-2"},
arity = "1",
required = true)
private String second;
}
static class MySwitchableOptions {
@Option(
names = {"-more", "--enable-more-options"},
arity = "0",
required = true)
private boolean tlsEnabled = false;
@ArgGroup(exclusive = false)
private OtherOptions options;
}
@Command(name = "mutual-dependency")
static class FullCommandLine {
@ArgGroup(exclusive = false)
private MySwitchableOptions switchableOptions;
}
}
@Test
public void testIssue938NestedMutualDependency() {
final CommandLine commandLine = new CommandLine(new Issue938NestedMutualDependency.FullCommandLine());
//commandLine.usage(System.out);
// Ideally this would PASS (and the switchableOptions would be null)
commandLine.parseArgs("--enable-more-options");
// Should fail as other-option-2 is not set (and defined as required)
try {
commandLine.parseArgs("--enable-more-options", "--other-option-1=firstString");
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --other-option-2=<second>", ex.getMessage());
}
try {
// Ideally this would FAIL (as the --enable-more-options is not set
commandLine.parseArgs("--other-option-1=firstString", "--other-option-2=secondString");
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): --enable-more-options", ex.getMessage());
}
}
@Test
public void testGroupValidationResult_extractBlockingFailure() {
GroupValidationResult block = new GroupValidationResult(GroupValidationResult.Type.FAILURE_PRESENT);
List<GroupValidationResult> list = Arrays.asList(
GroupValidationResult.SUCCESS_PRESENT, GroupValidationResult.SUCCESS_ABSENT, block);
assertSame(block, GroupValidationResult.extractBlockingFailure(list));
assertNull(GroupValidationResult.extractBlockingFailure(Arrays.asList(
GroupValidationResult.SUCCESS_PRESENT, GroupValidationResult.SUCCESS_ABSENT)));
}
@Test
public void testGroupValidationResult_present() {
assertTrue(GroupValidationResult.SUCCESS_PRESENT.present());
assertFalse(GroupValidationResult.SUCCESS_ABSENT.present());
assertFalse(new GroupValidationResult(GroupValidationResult.Type.FAILURE_PRESENT).present());
assertFalse(new GroupValidationResult(GroupValidationResult.Type.FAILURE_ABSENT).present());
}
@Test
public void testGroupValidationResult_toString() {
assertEquals("SUCCESS_PRESENT", GroupValidationResult.SUCCESS_PRESENT.toString());
assertEquals("SUCCESS_ABSENT", GroupValidationResult.SUCCESS_ABSENT.toString());
assertEquals("FAILURE_PRESENT", new GroupValidationResult(GroupValidationResult.Type.FAILURE_PRESENT).toString());
assertEquals("FAILURE_ABSENT", new GroupValidationResult(GroupValidationResult.Type.FAILURE_ABSENT).toString());
CommandLine cmd = new CommandLine(CommandSpec.create());
ParameterException ex = new ParameterException(cmd, "hello");
assertEquals("FAILURE_ABSENT: hello", new GroupValidationResult(GroupValidationResult.Type.FAILURE_ABSENT, ex).toString());
}
@Command(name = "Issue940")
static class Issue940Command {
@ArgGroup MyArgGroup myArgGroup;// = new MyArgGroup();
private static class MyArgGroup {
@Option(names = {"--no-header"}, negatable = true)
boolean header;
}
}
@Test
public void testIssue940NegatableOptionInArgGroupGivesNPE() {
new CommandLine(new Issue940Command());
}
@Command(name = "974", mixinStandardHelpOptions = true, version = "1.0")
static class Issue974AnnotatedCommandMethod {
static class Exclusive {
@Option(names = "-a", description = "a", required = true) String a;
@Option(names = "-b", description = "b", required = true) String b;
}
int generateX;
int generateY;
Exclusive generateExclusive;
@Command(name = "generate", description = "Generate")
void generate(@Option(names = "-x", description = "x", required = true) int x,
@Option(names = "-y", description = "y", required = true) int y,
@ArgGroup Exclusive e) {
this.generateX = x;
this.generateY = y;
this.generateExclusive = e;
}
}
@Test
public void testIssue974CommandMethodWithoutGroup() {
String[] args = "generate -x=1 -y=2".split(" ");
Issue974AnnotatedCommandMethod bean = new Issue974AnnotatedCommandMethod();
new CommandLine(bean).execute(args);
assertEquals(1, bean.generateX);
assertEquals(2, bean.generateY);
assertNull(bean.generateExclusive);
}
@Test
public void testIssue974CommandMethodWithGroup() {
String[] args = "generate -x=1 -y=2 -a=xyz".split(" ");
Issue974AnnotatedCommandMethod bean = new Issue974AnnotatedCommandMethod();
new CommandLine(bean).execute(args);
assertEquals(1, bean.generateX);
assertEquals(2, bean.generateY);
assertNotNull(bean.generateExclusive);
assertEquals("xyz", bean.generateExclusive.a);
assertNull(bean.generateExclusive.b);
}
@Command static class SomeMixin {
@Option(names = "-i") int anInt;
@Option(names = "-L") long aLong;
public SomeMixin() {}
public SomeMixin(int i, long aLong) { this.anInt = i; this.aLong = aLong; }
@Override
public boolean equals(Object obj) {
SomeMixin other = (SomeMixin) obj;
return anInt == other.anInt && aLong == other.aLong;
}
}
@picocli.CommandLine.Command
static class CommandMethodsWithGroupsAndMixins {
enum InvokedSub { withMixin, posAndMixin, posAndOptAndMixin, groupFirst}
EnumSet<InvokedSub> invoked = EnumSet.noneOf(InvokedSub.class);
SomeMixin myMixin;
Composite myComposite;
int[] myPositionalInt;
String[] myStrings;
@Command(mixinStandardHelpOptions = true)
void withMixin(@Mixin SomeMixin mixin, @ArgGroup(multiplicity = "0..1") Composite composite) {
this.myMixin = mixin;
this.myComposite = composite;
invoked.add(withMixin);
}
@Command(mixinStandardHelpOptions = true)
void posAndMixin(int[] posInt, @ArgGroup(multiplicity = "0..1") Composite composite, @Mixin SomeMixin mixin) {
this.myMixin = mixin;
this.myComposite = composite;
this.myPositionalInt = posInt;
invoked.add(InvokedSub.posAndMixin);
}
@Command(mixinStandardHelpOptions = true)
void posAndOptAndMixin(int[] posInt, @Option(names = "-s") String[] strings, @Mixin SomeMixin mixin, @ArgGroup(multiplicity = "0..1") Composite composite) {
this.myMixin = mixin;
this.myComposite = composite;
this.myPositionalInt = posInt;
this.myStrings = strings;
invoked.add(InvokedSub.posAndOptAndMixin);
}
@Command(mixinStandardHelpOptions = true)
void groupFirst(@ArgGroup(multiplicity = "0..1") Composite composite, @Mixin SomeMixin mixin, int[] posInt, @Option(names = "-s") String[] strings) {
this.myMixin = mixin;
this.myComposite = composite;
this.myPositionalInt = posInt;
this.myStrings = strings;
invoked.add(InvokedSub.groupFirst);
}
}
@Test
public void testCommandMethod_withMixin_help() {
final CommandMethodsWithGroupsAndMixins bean = new CommandMethodsWithGroupsAndMixins();
Supplier<CommandLine> supplier = new Supplier<CommandLine>() {
public CommandLine get() { return new CommandLine(bean); }};
Execution execution = Execution.builder(supplier).execute("withMixin -h".split(" "));
execution.assertSystemOut(String.format("" +
"Usage: <main class> withMixin [-hV] [-i=<anInt>] [-L=<aLong>] [[-a -b] | (-x |%n" +
" -y)]%n" +
" -a%n" +
" -b%n" +
" -h, --help Show this help message and exit.%n" +
" -i=<anInt>%n" +
" -L=<aLong>%n" +
" -V, --version Print version information and exit.%n" +
" -x%n" +
" -y%n"));
}
@Test
public void testCommandMethod_posAndMixin_help() {
final CommandMethodsWithGroupsAndMixins bean = new CommandMethodsWithGroupsAndMixins();
Supplier<CommandLine> supplier = new Supplier<CommandLine>() {
public CommandLine get() { return new CommandLine(bean); }};
Execution execution = Execution.builder(supplier).execute("posAndMixin -h".split(" "));
execution.assertSystemOut(String.format("" +
"Usage: <main class> posAndMixin [-hV] [-i=<anInt>] [-L=<aLong>] [[-a -b] | (-x%n" +
" | -y)] [<arg0>...]%n" +
" [<arg0>...]%n" +
" -a%n" +
" -b%n" +
" -h, --help Show this help message and exit.%n" +
" -i=<anInt>%n" +
" -L=<aLong>%n" +
" -V, --version Print version information and exit.%n" +
" -x%n" +
" -y%n"));
}
@Test
public void testCommandMethod_posAndOptAndMixin_help() {
final CommandMethodsWithGroupsAndMixins bean = new CommandMethodsWithGroupsAndMixins();
Supplier<CommandLine> supplier = new Supplier<CommandLine>() {
public CommandLine get() { return new CommandLine(bean); }};
Execution execution = Execution.builder(supplier).execute("posAndOptAndMixin -h".split(" "));
execution.assertSystemOut(String.format("" +
"Usage: <main class> posAndOptAndMixin [-hV] [-i=<anInt>] [-L=<aLong>]%n" +
" [-s=<arg1>]... [[-a -b] | (-x | -y)]%n" +
" [<arg0>...]%n" +
" [<arg0>...]%n" +
" -a%n" +
" -b%n" +
" -h, --help Show this help message and exit.%n" +
" -i=<anInt>%n" +
" -L=<aLong>%n" +
" -s=<arg1>%n" +
" -V, --version Print version information and exit.%n" +
" -x%n" +
" -y%n"));
}
@Test
public void testCommandMethod_groupFirst_help() {
final CommandMethodsWithGroupsAndMixins bean = new CommandMethodsWithGroupsAndMixins();
Supplier<CommandLine> supplier = new Supplier<CommandLine>() {
public CommandLine get() { return new CommandLine(bean); }};
Execution execution = Execution.builder(supplier).execute("groupFirst -h".split(" "));
execution.assertSystemOut(String.format("" +
"Usage: <main class> groupFirst [-hV] [-i=<anInt>] [-L=<aLong>] [-s=<arg3>]...%n" +
" [[-a -b] | (-x | -y)] [<arg2>...]%n" +
" [<arg2>...]%n" +
" -a%n" +
" -b%n" +
" -h, --help Show this help message and exit.%n" +
" -i=<anInt>%n" +
" -L=<aLong>%n" +
" -s=<arg3>%n" +
" -V, --version Print version information and exit.%n" +
" -x%n" +
" -y%n"));
}
// TODO GroupMatch.container()
// TODO GroupMatch.matchedMaxElements()
// TODO GroupMatch.matchedFully()
@Command(name = "ami", description = "ami description", customSynopsis = "ami [OPTIONS]")
static class Issue988 {
@ArgGroup(exclusive = true, /*heading = "",*/ order = 9)
ProjectOrTreeOptions projectOrTreeOptions = new ProjectOrTreeOptions();
@ArgGroup(validate = false, heading = "General Options:%n", order = 30)
GeneralOptions generalOptions = new GeneralOptions();
static class ProjectOrTreeOptions {
@ArgGroup(exclusive = false, multiplicity = "0..1",
heading = "CProject Options:%n", order = 10)
CProjectOptions cProjectOptions = new CProjectOptions();
@ArgGroup(exclusive = false, multiplicity = "0..1",
heading = "CTree Options:%n", order = 20)
CTreeOptions cTreeOptions = new CTreeOptions();
}
static class CProjectOptions {
@Option(names = {"-p", "--cproject"}, paramLabel = "DIR",
description = "The CProject (directory) to process. The cProject name is the basename of the file."
)
protected String cProjectDirectory = null;
protected static class TreeOptions {
@Option(names = {"-r", "--includetree"}, paramLabel = "DIR", order = 12,
arity = "1..*",
description = "Include only the specified CTrees."
)
protected String[] includeTrees;
@Option(names = {"-R", "--excludetree"}, paramLabel = "DIR", order = 13,
arity = "1..*",
description = "Exclude the specified CTrees."
)
protected String[] excludeTrees;
}
@ArgGroup(exclusive = true, multiplicity = "0..1", order = 11/*, heading = ""*/)
TreeOptions treeOptions = new TreeOptions();
}
static class CTreeOptions {
@Option(names = {"-t", "--ctree"}, paramLabel = "DIR",
description = "The CTree (directory) to process. The cTree name is the basename of the file."
)
protected String cTreeDirectory = null;
protected static class BaseOptions {
@Option(names = {"-b", "--includebase"}, paramLabel = "PATH", order = 22,
arity = "1..*",
description = "Include child files of cTree (only works with --ctree)."
)
protected String[] includeBase;
@Option(names = {"-B", "--excludebase"}, paramLabel = "PATH",
order = 23,
arity = "1..*",
description = "Exclude child files of cTree (only works with --ctree)."
)
protected String[] excludeBase;
}
@ArgGroup(exclusive = true, multiplicity = "0..1", /*heading = "",*/ order = 21)
BaseOptions baseOptions = new BaseOptions();
}
static class GeneralOptions {
@Option(names = {"-i", "--input"}, paramLabel = "FILE",
description = "Input filename (no defaults)"
)
protected String input = null;
@Option(names = {"-n", "--inputname"}, paramLabel = "PATH",
description = "User's basename for input files (e.g. foo/bar/<basename>.png) or directories."
)
protected String inputBasename;
}
}
@Test //https://github.com/remkop/picocli/issues/988
public void testIssue988OptionGroupSectionsShouldIncludeSubgroupOptions() {
String expected = String.format("" +
"Usage: ami [OPTIONS]%n" +
"ami description%n" +
"CProject Options:%n" +
" -p, --cproject=DIR The CProject (directory) to process. The cProject%n" +
" name is the basename of the file.%n" +
" -r, --includetree=DIR... Include only the specified CTrees.%n" +
" -R, --excludetree=DIR... Exclude the specified CTrees.%n" +
"CTree Options:%n" +
" -b, --includebase=PATH... Include child files of cTree (only works with%n" +
" --ctree).%n" +
" -B, --excludebase=PATH... Exclude child files of cTree (only works with%n" +
" --ctree).%n" +
" -t, --ctree=DIR The CTree (directory) to process. The cTree name%n" +
" is the basename of the file.%n" +
"General Options:%n" +
" -i, --input=FILE Input filename (no defaults)%n" +
" -n, --inputname=PATH User's basename for input files (e.g.%n" +
" foo/bar/<basename>.png) or directories.%n");
assertEquals(expected, new CommandLine(new Issue988()).getUsageMessage());
}
static class StudentGrade {
@Parameters(index = "0") String name;
@Parameters(index = "1") BigDecimal grade;
public StudentGrade() {}
public StudentGrade(String name, String grade) {
this(name, new BigDecimal(grade));
}
public StudentGrade(String name, BigDecimal grade) {
this.name = name;
this.grade = grade;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
StudentGrade that = (StudentGrade) o;
return name.equals(that.name) && grade.equals(that.grade);
}
@Override
public String toString() {
return "StudentGrade{" +
"name='" + name + '\'' +
", grade=" + grade +
'}';
}
}
@Test // https://github.com/remkop/picocli/issues/1027
public void testIssue1027RepeatingPositionalParams() {
class Issue1027 {
@ArgGroup(exclusive = false, multiplicity = "1..*")
List<StudentGrade> gradeList;
}
Issue1027 bean = new Issue1027();
new CommandLine(bean).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5 Danny 4.0".split(" "));
assertEquals(4, bean.gradeList.size());
assertEquals(new StudentGrade("Abby", "4.0"), bean.gradeList.get(0));
assertEquals(new StudentGrade("Billy", "3.5"), bean.gradeList.get(1));
assertEquals(new StudentGrade("Caily", "3.5"), bean.gradeList.get(2));
assertEquals(new StudentGrade("Danny", "4.0"), bean.gradeList.get(3));
}
@Test // https://github.com/remkop/picocli/issues/1027
public void testIssue1027RepeatingPositionalParamsEdgeCase1() {
class Issue1027 {
@ArgGroup(exclusive = false, multiplicity = "4..*")
List<StudentGrade> gradeList;
}
Issue1027 bean = new Issue1027();
new CommandLine(bean).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5 Danny 4.0".split(" "));
assertEquals(4, bean.gradeList.size());
assertEquals(new StudentGrade("Abby", "4.0"), bean.gradeList.get(0));
assertEquals(new StudentGrade("Billy", "3.5"), bean.gradeList.get(1));
assertEquals(new StudentGrade("Caily", "3.5"), bean.gradeList.get(2));
assertEquals(new StudentGrade("Danny", "4.0"), bean.gradeList.get(3));
}
@Test // https://github.com/remkop/picocli/issues/1027
public void testIssue1027RepeatingPositionalParamsEdgeCase2() {
class Issue1027 {
@ArgGroup(exclusive = false, multiplicity = "1..4")
List<StudentGrade> gradeList;
}
Issue1027 bean = new Issue1027();
new CommandLine(bean).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5 Danny 4.0".split(" "));
assertEquals(4, bean.gradeList.size());
assertEquals(new StudentGrade("Abby", "4.0"), bean.gradeList.get(0));
assertEquals(new StudentGrade("Billy", "3.5"), bean.gradeList.get(1));
assertEquals(new StudentGrade("Caily", "3.5"), bean.gradeList.get(2));
assertEquals(new StudentGrade("Danny", "4.0"), bean.gradeList.get(3));
}
@Test // https://github.com/remkop/picocli/issues/1027
public void testIssue1027RepeatingPositionalParamsWithMinMultiplicity() {
class Issue1027 {
@ArgGroup(exclusive = false, multiplicity = "4..*")
List<StudentGrade> gradeList;
}
Issue1027 bean = new Issue1027();
try {
new CommandLine(bean).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5".split(" "));
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Group: (<name> <grade>) must be specified 4 times but was matched 3 times", ex.getMessage());
}
}
@Test // https://github.com/remkop/picocli/issues/1027
public void testIssue1027RepeatingPositionalParamsWithMaxMultiplicity() {
class Issue1027 {
@ArgGroup(exclusive = false, multiplicity = "1..3")
List<StudentGrade> gradeList;
}
try {
new CommandLine(new Issue1027()).parseArgs();
fail("Expected exception");
} catch (MissingParameterException ex) {
assertEquals("Error: Missing required argument(s): (<name> <grade>)", ex.getMessage());
}
Issue1027 bean1 = new Issue1027();
new CommandLine(bean1).parseArgs("Abby 4.0".split(" "));
assertEquals(new StudentGrade("Abby", "4.0"), bean1.gradeList.get(0));
Issue1027 bean2 = new Issue1027();
new CommandLine(bean2).parseArgs("Abby 4.0 Billy 3.5".split(" "));
assertEquals(new StudentGrade("Abby", "4.0"), bean2.gradeList.get(0));
assertEquals(new StudentGrade("Billy", "3.5"), bean2.gradeList.get(1));
Issue1027 bean3 = new Issue1027();
new CommandLine(bean3).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5".split(" "));
assertEquals(new StudentGrade("Abby", "4.0"), bean3.gradeList.get(0));
assertEquals(new StudentGrade("Billy", "3.5"), bean3.gradeList.get(1));
assertEquals(new StudentGrade("Caily", "3.5"), bean3.gradeList.get(2));
Issue1027 bean4 = new Issue1027();
try {
new CommandLine(bean4).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5 Danny 4.0".split(" "));
fail("Expected exception");
} catch (MaxValuesExceededException ex) {
assertEquals("Error: expected only one match but got (<name> <grade>) [<name> <grade>] [<name> <grade>]="
+ "{params[0]=Abby params[1]=4.0 params[0]=Billy params[1]=3.5 params[0]=Caily params[1]=3.5} and (<name> <grade>) "
+ "[<name> <grade>] [<name> <grade>]={params[0]=Danny params[1]=4.0}", ex.getMessage());
} catch (UnmatchedArgumentException ex) {
assertEquals("Unmatched arguments from index 6: 'Danny', '4.0'", ex.getMessage());
}
}
@Test
public void testMultipleGroupsWithPositional() {
class Issue1027 {
@ArgGroup(exclusive = false, multiplicity = "1..4")
List<StudentGrade> gradeList;
@ArgGroup(exclusive = false, multiplicity = "1")
List<StudentGrade> anotherList;
}
Issue1027 bean4 = new Issue1027();
new CommandLine(bean4).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5 Danny 4.0".split(" "));
assertEquals(4, bean4.gradeList.size());
assertEquals(new StudentGrade("Abby", "4.0"), bean4.gradeList.get(0));
assertEquals(new StudentGrade("Billy", "3.5"), bean4.gradeList.get(1));
assertEquals(new StudentGrade("Caily", "3.5"), bean4.gradeList.get(2));
assertEquals(new StudentGrade("Danny", "4.0"), bean4.gradeList.get(3));
assertEquals(1, bean4.anotherList.size());
assertEquals(new StudentGrade("Abby", "4.0"), bean4.anotherList.get(0));
Issue1027 bean5 = new Issue1027();
try {
new CommandLine(bean5).parseArgs("Abby 4.0 Billy 3.5 Caily 3.5 Danny 4.0 Egon 3.5".split(" "));
fail("Expected exception");
} catch (UnmatchedArgumentException ex) {
assertEquals("Unmatched arguments from index 8: 'Egon', '3.5'", ex.getMessage());
}
}
static class InnerPositional1027 {
@Parameters(index = "0") String param00;
@Parameters(index = "1") String param01;
public InnerPositional1027() {}
public InnerPositional1027(String param00, String param01) {
this.param00 = param00;
this.param01 = param01;
}
public boolean equals(Object obj) {
if (!(obj instanceof InnerPositional1027)) { return false; }
InnerPositional1027 other = (InnerPositional1027) obj;
return TestUtil.equals(this.param00, other.param00)
&& TestUtil.equals(this.param01, other.param01);
}
}
static class Inner1027 {
@Option(names = "-y", required = true) boolean y;
@ArgGroup(exclusive = false, multiplicity = "1")
InnerPositional1027 innerPositional;
public Inner1027() {}
public Inner1027(String param0, String param1) {
this.innerPositional = new InnerPositional1027(param0, param1);
}
public boolean equals(Object obj) {
if (!(obj instanceof Inner1027)) { return false; }
Inner1027 other = (Inner1027) obj;
return TestUtil.equals(this.innerPositional, other.innerPositional);
}
}
static class Outer1027 {
@Option(names = "-x", required = true) boolean x;
@Parameters(index = "0") String param0;
@Parameters(index = "1") String param1;
@ArgGroup(exclusive = false, multiplicity = "0..*")
List<Inner1027> inners;
public Outer1027() {}
public Outer1027(String param0, String param1, List<Inner1027> inners) {
this.param0 = param0;
this.param1 = param1;
this.inners = inners;
}
public boolean equals(Object obj) {
if (!(obj instanceof Outer1027)) { return false; }
Outer1027 other = (Outer1027) obj;
return TestUtil.equals(this.param0, other.param0)
&& TestUtil.equals(this.param1, other.param1)
&& TestUtil.equals(this.inners, other.inners)
;
}
}
@Ignore
@Test
public void testNestedPositionals() {
class Nested {
@ArgGroup(exclusive = false, multiplicity = "0..*")
List<Outer1027> outers;
}
Nested bean = new Nested();
new CommandLine(bean).parseArgs("-x 0 1 -x 00 11 -y 000 111 -y 0000 1111 -x 00000 11111".split(" "));
assertEquals(3, bean.outers.size());
assertEquals(new Outer1027("0", "1", null), bean.outers.get(0));
List<Inner1027> inners = Arrays.asList(new Inner1027("000", "111"), new Inner1027("0000", "1111"));
assertEquals(new Outer1027("00", "11", inners), bean.outers.get(1));
assertEquals(new Outer1027("00000", "11111", null), bean.outers.get(2));
}
@Command(name = "MyApp")
static class Issue1065 {
@ArgGroup(exclusive = false)
MyGroup myGroup;
static class MyGroup {
@Option(names="-A", paramLabel="N", split=",") List<Long> A;
}
}
//https://stackoverflow.com/questions/61964838/picocli-list-option-used-in-arggroup-duplicated-in-short-usage-string
@Test
public void testIssue1065DuplicateSynopsis() {
String expected = String.format("" +
"Usage: MyApp [[-A=N[,N...]]...]%n" +
" -A=N[,N...]%n");
String actual = new CommandLine(new Issue1065()).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Command(name = "MyApp")
static class Issue1065ExclusiveGroup {
@ArgGroup(exclusive = true)
MyGroup myGroup;
static class MyGroup {
@Option(names="-A", paramLabel="N", split=",") List<Long> A;
}
}
//https://stackoverflow.com/questions/61964838/picocli-list-option-used-in-arggroup-duplicated-in-short-usage-string
@Test
public void testIssue1065ExclusiveGroupDuplicateSynopsis() {
String expected = String.format("" +
"Usage: MyApp [-A=N[,N...] [-A=N[,N...]]...]%n" +
" -A=N[,N...]%n");
String actual = new CommandLine(new Issue1065ExclusiveGroup()).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Command(name = "MyApp")
static class Issue1065NoSplit {
@ArgGroup(exclusive = false)
MyGroup myGroup;
static class MyGroup {
@Option(names="-A", paramLabel="N") List<Long> A;
}
}
//https://stackoverflow.com/questions/61964838/picocli-list-option-used-in-arggroup-duplicated-in-short-usage-string
@Test
public void testIssue1065DuplicateSynopsisVariant() {
String expected = String.format("" +
"Usage: MyApp [[-A=N]...]%n" +
" -A=N%n");
String actual = new CommandLine(new Issue1065NoSplit()).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Command(name = "MyApp")
static class Issue1065ExclusiveGroupNoSplit {
@ArgGroup(exclusive = true)
MyGroup myGroup;
static class MyGroup {
@Option(names="-A", paramLabel="N") List<Long> A;
}
}
//https://stackoverflow.com/questions/61964838/picocli-list-option-used-in-arggroup-duplicated-in-short-usage-string
@Test
public void testIssue1065ExclusiveGroupNoSplitDuplicateSynopsisVariant() {
String expected = String.format("" +
"Usage: MyApp [-A=N [-A=N]...]%n" +
" -A=N%n");
String actual = new CommandLine(new Issue1065ExclusiveGroupNoSplit()).getUsageMessage(Help.Ansi.OFF);
assertEquals(expected, actual);
}
@Test
public void testAllOptionsNested() {
class Nested {
@ArgGroup(exclusive = false, multiplicity = "0..*")
List<Outer1027> outers;
}
List<ArgGroupSpec> argGroupSpecs = new CommandLine(new Nested()).getCommandSpec().argGroups();
assertEquals(1, argGroupSpecs.size());
ArgGroupSpec group = argGroupSpecs.get(0);
List<OptionSpec> options = group.options();
assertEquals(1, options.size());
assertEquals("-x", options.get(0).shortestName());
List<OptionSpec> allOptions = group.allOptionsNested();
assertEquals(2, allOptions.size());
assertEquals("-x", allOptions.get(0).shortestName());
assertEquals("-y", allOptions.get(1).shortestName());
}
@Test
public void testAllOptionsNested2() {
List<ArgGroupSpec> argGroupSpecs = new CommandLine(new Issue988()).getCommandSpec().argGroups();
assertEquals(2, argGroupSpecs.size());
ArgGroupSpec projectOrTreeOptionsGroup = argGroupSpecs.get(0);
List<OptionSpec> options = projectOrTreeOptionsGroup.options();
assertEquals(0, options.size());
List<OptionSpec> allOptions = projectOrTreeOptionsGroup.allOptionsNested();
assertEquals(6, allOptions.size());
assertEquals("--cproject", allOptions.get(0).longestName());
assertEquals("--includetree", allOptions.get(1).longestName());
assertEquals("--excludetree", allOptions.get(2).longestName());
assertEquals("--ctree", allOptions.get(3).longestName());
assertEquals("--includebase", allOptions.get(4).longestName());
assertEquals("--excludebase", allOptions.get(5).longestName());
ArgGroupSpec generalOptionsGroup = argGroupSpecs.get(1);
assertEquals(2, generalOptionsGroup.options().size());
assertEquals(2, generalOptionsGroup.allOptionsNested().size());
}
@Test
public void testAllPositionalParametersNested() {
class Nested {
@ArgGroup(exclusive = false, multiplicity = "0..*")
List<Outer1027> outers;
}
List<ArgGroupSpec> argGroupSpecs = new CommandLine(new Nested()).getCommandSpec().argGroups();
assertEquals(1, argGroupSpecs.size());
ArgGroupSpec group = argGroupSpecs.get(0);
List<PositionalParamSpec> positionals = group.positionalParameters();
assertEquals(2, positionals.size());
assertEquals("<param0>", positionals.get(0).paramLabel());
List<PositionalParamSpec> allPositionals = group.allPositionalParametersNested();
assertEquals(4, allPositionals.size());
assertEquals("<param0>", allPositionals.get(0).paramLabel());
assertEquals("<param1>", allPositionals.get(1).paramLabel());
assertEquals("<param00>", allPositionals.get(2).paramLabel());
assertEquals("<param01>", allPositionals.get(3).paramLabel());
}
@Test // #1061
public void testHelpForGroupWithPositionalsAndOptionsAndEndOfOptions() {
@Command(mixinStandardHelpOptions = true, showEndOfOptionsDelimiterInUsageHelp = true)
class Nested {
@ArgGroup(exclusive = false, multiplicity = "0..*")
List<Outer1027> outers;
}
String expected = String.format("" +
"Usage: <main class> [-hV] [-x <param0> <param1> [-y (<param00>%n" +
" <param01>)]...]... [--]%n" +
" <param0>%n" +
" <param00>%n" +
" <param1>%n" +
" <param01>%n" +
" -h, --help Show this help message and exit.%n" +
" -V, --version Print version information and exit.%n" +
" -x%n" +
" -y%n" +
" -- This option can be used to separate command-line options from%n" +
" the list of positional parameters.%n");
assertEquals(expected, new CommandLine(new Nested()).getUsageMessage());
}
@Test // #1061
public void testHelpForGroupWithPositionalsAndEndOfOptions() {
@Command(mixinStandardHelpOptions = true, showEndOfOptionsDelimiterInUsageHelp = true)
class Group {
@ArgGroup InnerPositional1027 inner;
}
String expected = String.format("" +
"Usage: <main class> [-hV] [--] [<param00> | <param01>]%n" +
" <param00>%n" +
" <param01>%n" +
" -h, --help Show this help message and exit.%n" +
" -V, --version Print version information and exit.%n" +
" -- This option can be used to separate command-line options from%n" +
" the list of positional parameters.%n");
assertEquals(expected, new CommandLine(new Group()).getUsageMessage());
}
static class Issue1213Arithmetic {
@ArgGroup(exclusive = false, validate = false, heading = "scan source options%n")
SourceOptions sourceOptions;
static class SourceOptions {
@Parameters(paramLabel = "FILE")
List<File> reportFiles;
@Option(names = {"-b", "--build-id"}, paramLabel = "Build ID")
List<Integer> buildIds;
@Option(names = {"-a", "--app-name"}, paramLabel = "App Name")
List<String> appNames;
}
}
@Test
public void testArithmeticException1213() {
new CommandLine(new Issue1213Arithmetic()).parseArgs("a");
Issue1213Arithmetic bean = new Issue1213Arithmetic();
new CommandLine(bean).parseArgs("a", "b");
assertEquals(Arrays.asList(new File("a"), new File("b")), bean.sourceOptions.reportFiles);
}
public static class CriteriaWithEnvironment {
private static final List<String> DYNAMIC_LIST = Arrays.asList("FOO", "BAR");
private String environment;
@Spec CommandSpec spec;
@Option(names = {"-e", "--environment"})
public void setEnvironment(String environment) {
if (!DYNAMIC_LIST.contains(environment)) {
// Should throw a ParameterException
//throw new IllegalArgumentException("Should be one of...");
throw new ParameterException(spec.commandLine(), "should be one of " + DYNAMIC_LIST);
}
this.environment = environment;
}
public String getEnvironment() {
return environment;
}
}
@Test
public void testIssue1260ArgGroupWithSpec() {
@Command(name = "issue1260")
class App {
@ArgGroup CriteriaWithEnvironment criteria;
}
//TestUtil.setTraceLevel("DEBUG");
CommandLine cmd = new CommandLine(new App());
try {
cmd.parseArgs("-e", "X");
fail("Expected exception");
} catch (ParameterException pex) {
assertEquals("should be one of [FOO, BAR]", pex.getMessage());
assertSame(cmd, pex.getCommandLine());
}
}
static class Issue1260GetterMethod {
CommandSpec spec;
@Spec CommandSpec spec() {
return spec;
}
@Option(names = "-x") int x;
}
@Ignore("Getter method in ArgGroup does not work; on interface or class")
@Test
public void testIssue1260ArgGroupWithSpecGetterMethod() {
@Command(name = "issue1260a")
class App {
@ArgGroup
Issue1260GetterMethod group;
}
//TestUtil.setTraceLevel("DEBUG");
App app = new App();
CommandLine cmd = new CommandLine(app);
cmd.parseArgs("-x", "123");
assertNotNull(app.group);
assertEquals(123, app.group.x);
assertSame(cmd.getCommandSpec(), app.group.spec());
}
static class Issue1260SetterMethod {
CommandSpec spec;
int x;
@Spec
void spec(CommandSpec spec) {
this.spec = spec;
}
@Option(names = "-x")
void setX(int x) {
if (x < 0) throw new ParameterException(spec.commandLine(), "X must be positive");
this.x = x;
}
}
@Test
public void testIssue1260ArgGroupWithSpecSetterMethod() {
@Command(name = "issue1260b")
class App {
@ArgGroup
Issue1260SetterMethod group;
}
//TestUtil.setTraceLevel("DEBUG");
App app = new App();
CommandLine cmd = new CommandLine(app);
cmd.parseArgs("-x", "3");
assertNotNull(app.group);
assertEquals(3, app.group.x);
assertSame(cmd.getCommandSpec(), app.group.spec);
try {
cmd.parseArgs("-x", "-1");
fail("Expected exception");
} catch (ParameterException pex) {
assertEquals("X must be positive", pex.getMessage());
assertSame(cmd, pex.getCommandLine());
}
}
@Command(name = "list", version = "issue 1300 1.0",
mixinStandardHelpOptions = true,
description = "list all signals")
static class Issue1300 implements Runnable {
@ArgGroup(exclusive = true, multiplicity = "1")
SearchFilterArgs searchFilterArgs;
public void run() { }
static class SearchFilterArgs {
@Option(names = {"-A", "--all"}, required = true)
boolean getAllSignals;
@Option(names = {"-m", "--message-name"}, required = true)
String messageName;
}
}
@Test
public void testIssue1300BooleanInitialization() {
PrintStream err = System.err;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream capture = new PrintStream(baos, true);
System.setErr(capture);
//TestUtil.setTraceLevel("DEBUG");
CommandLine cmd = new CommandLine(new Issue1300());
cmd.getUsageMessage(); // this causes initial values of all options to be cached
//cmd.execute(); // this prints help, which also cause initial values to be cached
//System.err.println("===");
cmd.execute("-A");
capture.flush();
System.setErr(err);
assertEquals("", baos.toString());
}
@Command(name = "CLI Test 2", mixinStandardHelpOptions = true)
static class Issue1384 {
static class MyArgGroup {
@Parameters(index = "0", arity = "1", description = "parameter 0")
String param0;
@Parameters(index = "1", arity = "0..1", description = "parameter 1")
String param1;
@Parameters(index = "2", arity = "0..1", description = "parameter 2")
String param2;
}
@ArgGroup(order = 0, exclusive = false, multiplicity = "1")
MyArgGroup argGroup;
}
@Ignore
@Test
public void testIssue1384() {
Issue1384 obj = new Issue1384();
new CommandLine(obj).parseArgs("1", "a", "b");
assertEquals(obj.argGroup.param0, "1");
assertEquals(obj.argGroup.param1, "a");
assertEquals(obj.argGroup.param2, "b");
}
@Command(name = "Issue-1409")
static class Issue1409 {
@ArgGroup(exclusive = false, heading = "%nOptions to be used with group 1 OR group 2 options.%n")
OptXAndGroupOneOrGroupTwo optXAndGroupOneOrGroupTwo = new OptXAndGroupOneOrGroupTwo();
static class OptXAndGroupOneOrGroupTwo {
@Option(names = { "-x", "--option-x" }, required = true, defaultValue = "Default X", description = "option X")
String x;
@ArgGroup(exclusive = true)
OneOrTwo oneORtwo = new OneOrTwo();
}
static class OneOrTwo {
public OneOrTwo() {
new Exception().printStackTrace();
}
@ArgGroup(exclusive = false, heading = "%nGroup 1%n%n")
GroupOne one = new GroupOne();
@ArgGroup(exclusive = false, heading = "%nGroup 2%n%n")
GroupTwo two = new GroupTwo();
}
static class GroupOne {
@Option(names = { "-1a", "--option-1a" },required=true,description = "option A of group 1")
String _1a;
@Option(names = { "-1b", "--option-1b" },required=true,description = "option B of group 1")
String _1b;
}
static class GroupTwo {
@Option(names = { "-2a", "--option-2a" },required=true, defaultValue = "Default 2A", description = "option A of group 2")
private String _2a;
@Option(names = { "-2b", "--option-2b" },required=true, defaultValue = "Default 2B", description = "option B of group 2")
private String _2b;
}
}
@Ignore
@Test
public void testIssue1409() {
Issue1409 obj = new Issue1409();
// new CommandLine(obj).parseArgs("-x", "ANOTHER_VALUE", "-2a=x", "-2b=z");
new CommandLine(obj).parseArgs("-x", "ANOTHER_VALUE");
assertEquals("ANOTHER_VALUE", obj.optXAndGroupOneOrGroupTwo.x);
assertEquals(null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one._1a);
assertEquals(null, obj.optXAndGroupOneOrGroupTwo.oneORtwo.one._1b);
assertEquals("Default 2A", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two._2a);
assertEquals("Default 2B", obj.optXAndGroupOneOrGroupTwo.oneORtwo.two._2b);
}
}
| Updated JUnit tests cases and documentation in ArgGroupTest.java
| src/test/java/picocli/ArgGroupTest.java | Updated JUnit tests cases and documentation in ArgGroupTest.java |
|
Java | apache-2.0 | 56ba3f74b70f520a85df614aa2870ac96f4108ee | 0 | UniTime/unitime,maciej-zygmunt/unitime,rafati/unitime,maciej-zygmunt/unitime,zuzanamullerova/unitime,rafati/unitime,UniTime/unitime,maciej-zygmunt/unitime,zuzanamullerova/unitime,UniTime/unitime,nikeshmhr/unitime,sktoo/timetabling-system-,zuzanamullerova/unitime,sktoo/timetabling-system-,nikeshmhr/unitime,sktoo/timetabling-system-,rafati/unitime,nikeshmhr/unitime | /*
* UniTime 3.2 (University Timetabling Application)
* Copyright (C) 2010, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.gwt.client.sectioning;
import java.util.ArrayList;
import org.unitime.timetable.gwt.client.Lookup;
import org.unitime.timetable.gwt.resources.StudentSectioningMessages;
import org.unitime.timetable.gwt.services.SectioningService;
import org.unitime.timetable.gwt.services.SectioningServiceAsync;
import org.unitime.timetable.gwt.shared.PersonInterface;
import org.unitime.timetable.gwt.shared.UserAuthenticationProvider;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* @author Tomas Muller
*/
public class UserAuthentication extends Composite implements UserAuthenticationProvider {
public static final StudentSectioningMessages MESSAGES = GWT.create(StudentSectioningMessages.class);
private Label iUserLabel;
private Label iHint;
private Button iLogIn, iSkip, iLookup;
private TextBox iUserName;
private PasswordTextBox iUserPassword;
private DialogBox iDialog;
private Label iError;
private ArrayList<UserAuthenticatedHandler> iUserAuthenticatedHandlers = new ArrayList<UserAuthenticatedHandler>();
private static final SectioningServiceAsync sSectioningService = GWT.create(SectioningService.class);
private static AsyncCallback<String> sAuthenticateCallback = null;
private boolean iLoggedIn = false;
private boolean iGuest = false;
private String iLastUser = null;
private boolean iAllowGuest = false;
private Command iOnLoginCommand = null;
private Lookup iLookupDialog = null;
public UserAuthentication(boolean allowGuest) {
iAllowGuest = allowGuest;
iUserLabel = new Label(MESSAGES.userNotAuthenticated(), false);
iUserLabel.setStyleName("unitime-SessionSelector");
VerticalPanel vertical = new VerticalPanel();
vertical.add(iUserLabel);
iHint = new Label(MESSAGES.userHint());
iHint.setStyleName("unitime-Hint");
vertical.add(iHint);
iDialog = new DialogBox();
iDialog.setText(MESSAGES.dialogAuthenticate());
iDialog.setAnimationEnabled(true);
iDialog.setAutoHideEnabled(false);
iDialog.setGlassEnabled(true);
iDialog.setModal(true);
iDialog.addCloseHandler(new CloseHandler<PopupPanel>() {
@Override
public void onClose(CloseEvent<PopupPanel> event) {
iUserName.setText("");
iUserPassword.setText("");
}
});
FlexTable grid = new FlexTable();
grid.setCellPadding(5);
grid.setCellSpacing(0);
grid.setText(0, 0, MESSAGES.username());
iUserName = new TextBox();
iUserName.setStyleName("gwt-SuggestBox");
grid.setWidget(0, 1, iUserName);
grid.setText(1, 0, MESSAGES.password());
iUserPassword = new PasswordTextBox();
iUserPassword.setStyleName("gwt-SuggestBox");
grid.setWidget(1, 1, iUserPassword);
iError = new Label();
iError.setStyleName("unitime-ErrorMessage");
iError.setVisible(false);
grid.getFlexCellFormatter().setColSpan(2, 0, 2);
grid.setWidget(2, 0, iError);
HorizontalPanel buttonPanelWithPad = new HorizontalPanel();
buttonPanelWithPad.setWidth("100%");
HorizontalPanel buttonPanel = new HorizontalPanel();
buttonPanel.setSpacing(5);
buttonPanelWithPad.add(buttonPanel);
buttonPanelWithPad.setCellHorizontalAlignment(buttonPanel, HasHorizontalAlignment.ALIGN_RIGHT);
grid.getFlexCellFormatter().setColSpan(3, 0, 2);
grid.setWidget(3, 0, buttonPanelWithPad);
iLogIn = new Button(MESSAGES.buttonUserLogin());
buttonPanel.add(iLogIn);
iSkip = new Button(MESSAGES.buttonUserSkip());
buttonPanel.add(iSkip);
iSkip.setVisible(iAllowGuest);
iLookupDialog = new Lookup();
iLookupDialog.setOptions("mustHaveExternalId,source=students");
iLookupDialog.addValueChangeHandler(new ValueChangeHandler<PersonInterface>() {
@Override
public void onValueChange(ValueChangeEvent<PersonInterface> event) {
if (event.getValue() != null)
sSectioningService.logIn("LOOKUP", event.getValue().getId(), sAuthenticateCallback);
}
});
iLookup = new Button(MESSAGES.buttonUserLookup());
buttonPanel.add(iLookup);
iLookup.setVisible(false);
iSkip.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
logIn(true);
}
});
iLogIn.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
logIn(false);
}
});
iLookup.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
iDialog.hide();
iLookupDialog.center();
}
});
iUserName.addKeyUpHandler(new KeyUpHandler() {
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
iUserPassword.selectAll();
iUserPassword.setFocus(true);
}
});
}
if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE && iAllowGuest) {
logIn(true);
}
}
});
iUserPassword.addKeyUpHandler(new KeyUpHandler() {
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
logIn(false);
}
if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE && iAllowGuest) {
logIn(true);
}
}
});
iDialog.add(grid);
ClickHandler ch = new ClickHandler() {
public void onClick(ClickEvent event) {
if (iLoggedIn) logOut();
else authenticate();
}
};
iUserLabel.addClickHandler(ch);
iHint.addClickHandler(ch);
initWidget(vertical);
sAuthenticateCallback = new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
iError.setText(caught.getMessage());
iError.setVisible(true);
iUserName.setEnabled(true);
iUserPassword.setEnabled(true);
iLogIn.setEnabled(true);
iSkip.setEnabled(true);
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
iUserName.selectAll();
iUserName.setFocus(true);
}
});
}
public void onSuccess(String result) {
iUserName.setEnabled(true);
iUserPassword.setEnabled(true);
iLogIn.setEnabled(true);
iSkip.setEnabled(true);
iError.setVisible(false);
iDialog.hide();
iUserLabel.setText(MESSAGES.userLabel(result));
iLastUser = result;
iHint.setText(MESSAGES.userHintLogout());
iLoggedIn = true;
iGuest = false;
UserAuthenticatedEvent e = new UserAuthenticatedEvent(iGuest);
for (UserAuthenticatedHandler h: iUserAuthenticatedHandlers)
h.onLogIn(e);
if (iOnLoginCommand != null) iOnLoginCommand.execute();
}
};
}
public void setLookupOptions(String options) { iLookupDialog.setOptions(options); }
public void setAllowLookup(boolean allow) {
iLookup.setVisible(allow);
}
public boolean isShowing() {
return iDialog.isShowing();
}
public void authenticate() {
iError.setVisible(false);
iDialog.center();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
iUserName.selectAll();
iUserName.setFocus(true);
}
});
}
public void authenticated(String user) {
if (iDialog.isShowing()) iDialog.hide();
iLoggedIn = true;
iGuest = MESSAGES.userGuest().equals(user);
iUserLabel.setText(MESSAGES.userLabel(user));
iLastUser = user;
iHint.setText(iGuest ? MESSAGES.userHintLogin() : MESSAGES.userHintLogout());
}
private void logIn(boolean guest) {
iError.setVisible(false);
if (guest) {
sSectioningService.logOut(new AsyncCallback<Boolean>() {
public void onFailure(Throwable caught) { }
public void onSuccess(Boolean result) {
iLoggedIn = true; iGuest = true;
iDialog.hide();
iUserLabel.setText(MESSAGES.userLabel(MESSAGES.userGuest()));
iHint.setText(MESSAGES.userHintLogin());
iLastUser = MESSAGES.userGuest();
UserAuthenticatedEvent e = new UserAuthenticatedEvent(iGuest);
for (UserAuthenticatedHandler h: iUserAuthenticatedHandlers)
h.onLogIn(e);
if (iOnLoginCommand != null) iOnLoginCommand.execute();
}
});
return;
}
iUserName.setEnabled(false);
iUserPassword.setEnabled(false);
iLogIn.setEnabled(false);
iSkip.setEnabled(false);
sSectioningService.logIn(iUserName.getText(), iUserPassword.getText(), sAuthenticateCallback);
}
public void logOut() {
sSectioningService.logOut(new AsyncCallback<Boolean>() {
public void onFailure(Throwable caught) { }
public void onSuccess(Boolean result) {
UserAuthenticatedEvent e = new UserAuthenticatedEvent(iGuest);
iHint.setText(MESSAGES.userHintClose());
iUserLabel.setText(MESSAGES.userNotAuthenticated());
iLastUser = null;
for (UserAuthenticatedHandler h: iUserAuthenticatedHandlers)
h.onLogOut(e);
iLoggedIn = false;
}
});
}
public String getUser() {
return iLastUser;
}
public void setUser(final String user, final AsyncCallback<Boolean> callback) {
iOnLoginCommand = null;
if (user == null) {
callback.onSuccess(false);
authenticate();
} else if (user.equals(iLastUser)) {
callback.onSuccess(true);
} else if (user.equals(MESSAGES.userGuest())) {
logIn(true);
callback.onSuccess(true);
} else {
iOnLoginCommand = new Command() {
public void execute() {
callback.onSuccess(user.equals(getUser()));
}
};
iUserLabel.setText(user);
authenticate();
}
}
public static class UserAuthenticatedEvent {
private boolean iGuest = false;
private UserAuthenticatedEvent(boolean guest) { iGuest = guest; }
public boolean isGuest() { return iGuest; }
}
public static interface UserAuthenticatedHandler {
public void onLogIn(UserAuthenticatedEvent event);
public void onLogOut(UserAuthenticatedEvent event);
}
public void addUserAuthenticatedHandler(UserAuthenticatedHandler h) {
iUserAuthenticatedHandlers.add(h);
}
public static void personFound(String externalUniqueId) {
sSectioningService.logIn("LOOKUP", externalUniqueId, sAuthenticateCallback);
}
private native JavaScriptObject createLookupCallback() /*-{
return function(person) {
@org.unitime.timetable.gwt.client.sectioning.UserAuthentication::personFound(Ljava/lang/String;)(person[0]);
};
}-*/;
}
| JavaSource/org/unitime/timetable/gwt/client/sectioning/UserAuthentication.java | /*
* UniTime 3.2 (University Timetabling Application)
* Copyright (C) 2010, UniTime LLC, and individual contributors
* as indicated by the @authors tag.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.unitime.timetable.gwt.client.sectioning;
import java.util.ArrayList;
import org.unitime.timetable.gwt.client.Lookup;
import org.unitime.timetable.gwt.resources.StudentSectioningMessages;
import org.unitime.timetable.gwt.services.SectioningService;
import org.unitime.timetable.gwt.services.SectioningServiceAsync;
import org.unitime.timetable.gwt.shared.PersonInterface;
import org.unitime.timetable.gwt.shared.UserAuthenticationProvider;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* @author Tomas Muller
*/
public class UserAuthentication extends Composite implements UserAuthenticationProvider {
public static final StudentSectioningMessages MESSAGES = GWT.create(StudentSectioningMessages.class);
private Label iUserLabel;
private Label iHint;
private Button iLogIn, iSkip, iLookup;
private TextBox iUserName;
private PasswordTextBox iUserPassword;
private DialogBox iDialog;
private Label iError;
private ArrayList<UserAuthenticatedHandler> iUserAuthenticatedHandlers = new ArrayList<UserAuthenticatedHandler>();
private static final SectioningServiceAsync sSectioningService = GWT.create(SectioningService.class);
private static AsyncCallback<String> sAuthenticateCallback = null;
private boolean iLoggedIn = false;
private boolean iGuest = false;
private String iLastUser = null;
private boolean iAllowGuest = false;
private Command iOnLoginCommand = null;
private Lookup iLookupDialog = null;
public UserAuthentication(boolean allowGuest) {
iAllowGuest = allowGuest;
iUserLabel = new Label(MESSAGES.userNotAuthenticated(), false);
iUserLabel.setStyleName("unitime-SessionSelector");
VerticalPanel vertical = new VerticalPanel();
vertical.add(iUserLabel);
iHint = new Label(MESSAGES.userHint());
iHint.setStyleName("unitime-Hint");
vertical.add(iHint);
iDialog = new DialogBox();
iDialog.setText(MESSAGES.dialogAuthenticate());
iDialog.setAnimationEnabled(true);
iDialog.setAutoHideEnabled(false);
iDialog.setGlassEnabled(true);
iDialog.setModal(true);
FlexTable grid = new FlexTable();
grid.setCellPadding(5);
grid.setCellSpacing(0);
grid.setText(0, 0, MESSAGES.username());
iUserName = new TextBox();
iUserName.setStyleName("gwt-SuggestBox");
grid.setWidget(0, 1, iUserName);
grid.setText(1, 0, MESSAGES.password());
iUserPassword = new PasswordTextBox();
iUserPassword.setStyleName("gwt-SuggestBox");
grid.setWidget(1, 1, iUserPassword);
iError = new Label();
iError.setStyleName("unitime-ErrorMessage");
iError.setVisible(false);
grid.getFlexCellFormatter().setColSpan(2, 0, 2);
grid.setWidget(2, 0, iError);
HorizontalPanel buttonPanelWithPad = new HorizontalPanel();
buttonPanelWithPad.setWidth("100%");
HorizontalPanel buttonPanel = new HorizontalPanel();
buttonPanel.setSpacing(5);
buttonPanelWithPad.add(buttonPanel);
buttonPanelWithPad.setCellHorizontalAlignment(buttonPanel, HasHorizontalAlignment.ALIGN_RIGHT);
grid.getFlexCellFormatter().setColSpan(3, 0, 2);
grid.setWidget(3, 0, buttonPanelWithPad);
iLogIn = new Button(MESSAGES.buttonUserLogin());
buttonPanel.add(iLogIn);
iSkip = new Button(MESSAGES.buttonUserSkip());
buttonPanel.add(iSkip);
iSkip.setVisible(iAllowGuest);
iLookupDialog = new Lookup();
iLookupDialog.setOptions("mustHaveExternalId,source=students");
iLookupDialog.addValueChangeHandler(new ValueChangeHandler<PersonInterface>() {
@Override
public void onValueChange(ValueChangeEvent<PersonInterface> event) {
if (event.getValue() != null)
sSectioningService.logIn("LOOKUP", event.getValue().getId(), sAuthenticateCallback);
}
});
iLookup = new Button(MESSAGES.buttonUserLookup());
buttonPanel.add(iLookup);
iLookup.setVisible(false);
iSkip.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
logIn(true);
}
});
iLogIn.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
logIn(false);
}
});
iLookup.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
iDialog.hide();
iLookupDialog.center();
}
});
iUserName.addKeyUpHandler(new KeyUpHandler() {
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
iUserPassword.selectAll();
iUserPassword.setFocus(true);
}
});
}
if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE && iAllowGuest) {
logIn(true);
}
}
});
iUserPassword.addKeyUpHandler(new KeyUpHandler() {
public void onKeyUp(KeyUpEvent event) {
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
logIn(false);
}
if (event.getNativeKeyCode() == KeyCodes.KEY_ESCAPE && iAllowGuest) {
logIn(true);
}
}
});
iDialog.add(grid);
ClickHandler ch = new ClickHandler() {
public void onClick(ClickEvent event) {
if (iLoggedIn) logOut();
else authenticate();
}
};
iUserLabel.addClickHandler(ch);
iHint.addClickHandler(ch);
initWidget(vertical);
sAuthenticateCallback = new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
iError.setText(caught.getMessage());
iError.setVisible(true);
iUserName.setEnabled(true);
iUserPassword.setEnabled(true);
iLogIn.setEnabled(true);
iSkip.setEnabled(true);
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
iUserName.selectAll();
iUserName.setFocus(true);
}
});
}
public void onSuccess(String result) {
iUserName.setEnabled(true);
iUserPassword.setEnabled(true);
iLogIn.setEnabled(true);
iSkip.setEnabled(true);
iError.setVisible(false);
iDialog.hide();
iUserLabel.setText(MESSAGES.userLabel(result));
iLastUser = result;
iHint.setText(MESSAGES.userHintLogout());
iLoggedIn = true;
iGuest = false;
UserAuthenticatedEvent e = new UserAuthenticatedEvent(iGuest);
for (UserAuthenticatedHandler h: iUserAuthenticatedHandlers)
h.onLogIn(e);
if (iOnLoginCommand != null) iOnLoginCommand.execute();
}
};
}
public void setLookupOptions(String options) { iLookupDialog.setOptions(options); }
public void setAllowLookup(boolean allow) {
iLookup.setVisible(allow);
}
public boolean isShowing() {
return iDialog.isShowing();
}
public void authenticate() {
iError.setVisible(false);
iDialog.center();
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
iUserName.selectAll();
iUserName.setFocus(true);
}
});
}
public void authenticated(String user) {
if (iDialog.isShowing()) iDialog.hide();
iLoggedIn = true;
iGuest = MESSAGES.userGuest().equals(user);
iUserLabel.setText(MESSAGES.userLabel(user));
iLastUser = user;
iHint.setText(iGuest ? MESSAGES.userHintLogin() : MESSAGES.userHintLogout());
}
private void logIn(boolean guest) {
iError.setVisible(false);
if (guest) {
sSectioningService.logOut(new AsyncCallback<Boolean>() {
public void onFailure(Throwable caught) { }
public void onSuccess(Boolean result) {
iLoggedIn = true; iGuest = true;
iDialog.hide();
iUserLabel.setText(MESSAGES.userLabel(MESSAGES.userGuest()));
iHint.setText(MESSAGES.userHintLogin());
iLastUser = MESSAGES.userGuest();
UserAuthenticatedEvent e = new UserAuthenticatedEvent(iGuest);
for (UserAuthenticatedHandler h: iUserAuthenticatedHandlers)
h.onLogIn(e);
if (iOnLoginCommand != null) iOnLoginCommand.execute();
}
});
return;
}
iUserName.setEnabled(false);
iUserPassword.setEnabled(false);
iLogIn.setEnabled(false);
iSkip.setEnabled(false);
sSectioningService.logIn(iUserName.getText(), iUserPassword.getText(), sAuthenticateCallback);
}
public void logOut() {
sSectioningService.logOut(new AsyncCallback<Boolean>() {
public void onFailure(Throwable caught) { }
public void onSuccess(Boolean result) {
UserAuthenticatedEvent e = new UserAuthenticatedEvent(iGuest);
iHint.setText(MESSAGES.userHintClose());
iUserLabel.setText(MESSAGES.userNotAuthenticated());
iLastUser = null;
for (UserAuthenticatedHandler h: iUserAuthenticatedHandlers)
h.onLogOut(e);
iLoggedIn = false;
}
});
}
public String getUser() {
return iLastUser;
}
public void setUser(final String user, final AsyncCallback<Boolean> callback) {
iOnLoginCommand = null;
if (user == null) {
callback.onSuccess(false);
authenticate();
} else if (user.equals(iLastUser)) {
callback.onSuccess(true);
} else if (user.equals(MESSAGES.userGuest())) {
logIn(true);
callback.onSuccess(true);
} else {
iOnLoginCommand = new Command() {
public void execute() {
callback.onSuccess(user.equals(getUser()));
}
};
iUserLabel.setText(user);
authenticate();
}
}
public static class UserAuthenticatedEvent {
private boolean iGuest = false;
private UserAuthenticatedEvent(boolean guest) { iGuest = guest; }
public boolean isGuest() { return iGuest; }
}
public static interface UserAuthenticatedHandler {
public void onLogIn(UserAuthenticatedEvent event);
public void onLogOut(UserAuthenticatedEvent event);
}
public void addUserAuthenticatedHandler(UserAuthenticatedHandler h) {
iUserAuthenticatedHandlers.add(h);
}
public static void personFound(String externalUniqueId) {
sSectioningService.logIn("LOOKUP", externalUniqueId, sAuthenticateCallback);
}
private native JavaScriptObject createLookupCallback() /*-{
return function(person) {
@org.unitime.timetable.gwt.client.sectioning.UserAuthentication::personFound(Ljava/lang/String;)(person[0]);
};
}-*/;
}
| Student Scheduling Assistant:
- authentication dialog: clear user name and password every time the dialog is closed
| JavaSource/org/unitime/timetable/gwt/client/sectioning/UserAuthentication.java | Student Scheduling Assistant: - authentication dialog: clear user name and password every time the dialog is closed |
|
Java | apache-2.0 | 42ee0a2a48f87922dc98f93abbe3394750b9c3f7 | 0 | xorware/android_build,xorware/android_build,ND-3500/platform_manifest,pranav01/platform_manifest,fallouttester/platform_manifest,RR-msm7x30/platform_manifest,hagar006/platform_manifest,xorware/android_build,see4ri/lolili,xorware/android_build,Hybrid-Power/startsync,knone1/platform_manifest,xorware/android_build | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.sun.javadoc.*;
import org.clearsilver.HDF;
import java.util.*;
import java.io.*;
import java.lang.reflect.Proxy;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class DroidDoc
{
private static final String SDK_CONSTANT_ANNOTATION = "android.annotation.SdkConstant";
private static final String SDK_CONSTANT_TYPE_ACTIVITY_ACTION = "android.annotation.SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION";
private static final String SDK_CONSTANT_TYPE_BROADCAST_ACTION = "android.annotation.SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION";
private static final String SDK_CONSTANT_TYPE_SERVICE_ACTION = "android.annotation.SdkConstant.SdkConstantType.SERVICE_INTENT_ACTION";
private static final String SDK_CONSTANT_TYPE_CATEGORY = "android.annotation.SdkConstant.SdkConstantType.INTENT_CATEGORY";
private static final String SDK_CONSTANT_TYPE_FEATURE = "android.annotation.SdkConstant.SdkConstantType.FEATURE";
private static final String SDK_WIDGET_ANNOTATION = "android.annotation.Widget";
private static final String SDK_LAYOUT_ANNOTATION = "android.annotation.Layout";
private static final int TYPE_NONE = 0;
private static final int TYPE_WIDGET = 1;
private static final int TYPE_LAYOUT = 2;
private static final int TYPE_LAYOUT_PARAM = 3;
public static final int SHOW_PUBLIC = 0x00000001;
public static final int SHOW_PROTECTED = 0x00000003;
public static final int SHOW_PACKAGE = 0x00000007;
public static final int SHOW_PRIVATE = 0x0000000f;
public static final int SHOW_HIDDEN = 0x0000001f;
public static int showLevel = SHOW_PROTECTED;
public static final String javadocDir = "reference/";
public static String htmlExtension;
public static RootDoc root;
public static ArrayList<String[]> mHDFData = new ArrayList<String[]>();
public static Map<Character,String> escapeChars = new HashMap<Character,String>();
public static String title = "";
public static SinceTagger sinceTagger = new SinceTagger();
private static boolean parseComments = false;
private static boolean generateDocs = true;
/**
* Returns true if we should parse javadoc comments,
* reporting errors in the process.
*/
public static boolean parseComments() {
return generateDocs || parseComments;
}
public static boolean checkLevel(int level)
{
return (showLevel & level) == level;
}
public static boolean checkLevel(boolean pub, boolean prot, boolean pkgp,
boolean priv, boolean hidden)
{
int level = 0;
if (hidden && !checkLevel(SHOW_HIDDEN)) {
return false;
}
if (pub && checkLevel(SHOW_PUBLIC)) {
return true;
}
if (prot && checkLevel(SHOW_PROTECTED)) {
return true;
}
if (pkgp && checkLevel(SHOW_PACKAGE)) {
return true;
}
if (priv && checkLevel(SHOW_PRIVATE)) {
return true;
}
return false;
}
public static boolean start(RootDoc r)
{
String keepListFile = null;
String proofreadFile = null;
String todoFile = null;
String sdkValuePath = null;
ArrayList<SampleCode> sampleCodes = new ArrayList<SampleCode>();
String stubsDir = null;
//Create the dependency graph for the stubs directory
boolean apiXML = false;
boolean offlineMode = false;
String apiFile = null;
String debugStubsFile = "";
HashSet<String> stubPackages = null;
root = r;
String[][] options = r.options();
for (String[] a: options) {
if (a[0].equals("-d")) {
ClearPage.outputDir = a[1];
}
else if (a[0].equals("-templatedir")) {
ClearPage.addTemplateDir(a[1]);
}
else if (a[0].equals("-hdf")) {
mHDFData.add(new String[] {a[1], a[2]});
}
else if (a[0].equals("-toroot")) {
ClearPage.toroot = a[1];
}
else if (a[0].equals("-samplecode")) {
sampleCodes.add(new SampleCode(a[1], a[2], a[3]));
}
else if (a[0].equals("-htmldir")) {
ClearPage.htmlDirs.add(a[1]);
}
else if (a[0].equals("-title")) {
DroidDoc.title = a[1];
}
else if (a[0].equals("-werror")) {
Errors.setWarningsAreErrors(true);
}
else if (a[0].equals("-error") || a[0].equals("-warning")
|| a[0].equals("-hide")) {
try {
int level = -1;
if (a[0].equals("-error")) {
level = Errors.ERROR;
}
else if (a[0].equals("-warning")) {
level = Errors.WARNING;
}
else if (a[0].equals("-hide")) {
level = Errors.HIDDEN;
}
Errors.setErrorLevel(Integer.parseInt(a[1]), level);
}
catch (NumberFormatException e) {
// already printed below
return false;
}
}
else if (a[0].equals("-keeplist")) {
keepListFile = a[1];
}
else if (a[0].equals("-proofread")) {
proofreadFile = a[1];
}
else if (a[0].equals("-todo")) {
todoFile = a[1];
}
else if (a[0].equals("-public")) {
showLevel = SHOW_PUBLIC;
}
else if (a[0].equals("-protected")) {
showLevel = SHOW_PROTECTED;
}
else if (a[0].equals("-package")) {
showLevel = SHOW_PACKAGE;
}
else if (a[0].equals("-private")) {
showLevel = SHOW_PRIVATE;
}
else if (a[0].equals("-hidden")) {
showLevel = SHOW_HIDDEN;
}
else if (a[0].equals("-stubs")) {
stubsDir = a[1];
}
else if (a[0].equals("-stubpackages")) {
stubPackages = new HashSet();
for (String pkg: a[1].split(":")) {
stubPackages.add(pkg);
}
}
else if (a[0].equals("-sdkvalues")) {
sdkValuePath = a[1];
}
else if (a[0].equals("-apixml")) {
apiXML = true;
apiFile = a[1];
}
else if (a[0].equals("-nodocs")) {
generateDocs = false;
}
else if (a[0].equals("-parsecomments")) {
parseComments = true;
}
else if (a[0].equals("-since")) {
sinceTagger.addVersion(a[1], a[2]);
}
else if (a[0].equals("-offlinemode")) {
offlineMode = true;
}
}
// read some prefs from the template
if (!readTemplateSettings()) {
return false;
}
// Set up the data structures
Converter.makeInfo(r);
if (generateDocs) {
long startTime = System.nanoTime();
// Apply @since tags from the XML file
sinceTagger.tagAll(Converter.rootClasses());
// Files for proofreading
if (proofreadFile != null) {
Proofread.initProofread(proofreadFile);
}
if (todoFile != null) {
TodoFile.writeTodoFile(todoFile);
}
// HTML Pages
if (!ClearPage.htmlDirs.isEmpty()) {
writeHTMLPages();
}
// Navigation tree
NavTree.writeNavTree(javadocDir);
// Packages Pages
writePackages(javadocDir
+ (!ClearPage.htmlDirs.isEmpty()
? "packages" + htmlExtension
: "index" + htmlExtension));
// Classes
writeClassLists();
writeClasses();
writeHierarchy();
// writeKeywords();
// Lists for JavaScript
writeLists();
if (keepListFile != null) {
writeKeepList(keepListFile);
}
// Sample Code
for (SampleCode sc: sampleCodes) {
sc.write(offlineMode);
}
// Index page
writeIndex();
Proofread.finishProofread(proofreadFile);
if (sdkValuePath != null) {
writeSdkValues(sdkValuePath);
}
long time = System.nanoTime() - startTime;
System.out.println("DroidDoc took " + (time / 1000000000) + " sec. to write docs to "
+ ClearPage.outputDir);
}
// Stubs
if (stubsDir != null) {
Stubs.writeStubs(stubsDir, apiXML, apiFile, stubPackages);
}
Errors.printErrors();
return !Errors.hadError;
}
private static void writeIndex() {
HDF data = makeHDF();
ClearPage.write(data, "index.cs", javadocDir + "index" + htmlExtension);
}
private static boolean readTemplateSettings()
{
HDF data = makeHDF();
htmlExtension = data.getValue("template.extension", ".html");
int i=0;
while (true) {
String k = data.getValue("template.escape." + i + ".key", "");
String v = data.getValue("template.escape." + i + ".value", "");
if ("".equals(k)) {
break;
}
if (k.length() != 1) {
System.err.println("template.escape." + i + ".key must have a length of 1: " + k);
return false;
}
escapeChars.put(k.charAt(0), v);
i++;
}
return true;
}
public static String escape(String s) {
if (escapeChars.size() == 0) {
return s;
}
StringBuffer b = null;
int begin = 0;
final int N = s.length();
for (int i=0; i<N; i++) {
char c = s.charAt(i);
String mapped = escapeChars.get(c);
if (mapped != null) {
if (b == null) {
b = new StringBuffer(s.length() + mapped.length());
}
if (begin != i) {
b.append(s.substring(begin, i));
}
b.append(mapped);
begin = i+1;
}
}
if (b != null) {
if (begin != N) {
b.append(s.substring(begin, N));
}
return b.toString();
}
return s;
}
public static void setPageTitle(HDF data, String title)
{
String s = title;
if (DroidDoc.title.length() > 0) {
s += " - " + DroidDoc.title;
}
data.setValue("page.title", s);
}
public static LanguageVersion languageVersion()
{
return LanguageVersion.JAVA_1_5;
}
public static int optionLength(String option)
{
if (option.equals("-d")) {
return 2;
}
if (option.equals("-templatedir")) {
return 2;
}
if (option.equals("-hdf")) {
return 3;
}
if (option.equals("-toroot")) {
return 2;
}
if (option.equals("-samplecode")) {
return 4;
}
if (option.equals("-htmldir")) {
return 2;
}
if (option.equals("-title")) {
return 2;
}
if (option.equals("-werror")) {
return 1;
}
if (option.equals("-hide")) {
return 2;
}
if (option.equals("-warning")) {
return 2;
}
if (option.equals("-error")) {
return 2;
}
if (option.equals("-keeplist")) {
return 2;
}
if (option.equals("-proofread")) {
return 2;
}
if (option.equals("-todo")) {
return 2;
}
if (option.equals("-public")) {
return 1;
}
if (option.equals("-protected")) {
return 1;
}
if (option.equals("-package")) {
return 1;
}
if (option.equals("-private")) {
return 1;
}
if (option.equals("-hidden")) {
return 1;
}
if (option.equals("-stubs")) {
return 2;
}
if (option.equals("-stubpackages")) {
return 2;
}
if (option.equals("-sdkvalues")) {
return 2;
}
if (option.equals("-apixml")) {
return 2;
}
if (option.equals("-nodocs")) {
return 1;
}
if (option.equals("-parsecomments")) {
return 1;
}
if (option.equals("-since")) {
return 3;
}
if (option.equals("-offlinemode")) {
return 1;
}
return 0;
}
public static boolean validOptions(String[][] options, DocErrorReporter r)
{
for (String[] a: options) {
if (a[0].equals("-error") || a[0].equals("-warning")
|| a[0].equals("-hide")) {
try {
Integer.parseInt(a[1]);
}
catch (NumberFormatException e) {
r.printError("bad -" + a[0] + " value must be a number: "
+ a[1]);
return false;
}
}
}
return true;
}
public static HDF makeHDF()
{
HDF data = new HDF();
for (String[] p: mHDFData) {
data.setValue(p[0], p[1]);
}
try {
for (String p: ClearPage.hdfFiles) {
data.readFile(p);
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
return data;
}
public static HDF makePackageHDF()
{
HDF data = makeHDF();
ClassInfo[] classes = Converter.rootClasses();
SortedMap<String, PackageInfo> sorted = new TreeMap<String, PackageInfo>();
for (ClassInfo cl: classes) {
PackageInfo pkg = cl.containingPackage();
String name;
if (pkg == null) {
name = "";
} else {
name = pkg.name();
}
sorted.put(name, pkg);
}
int i = 0;
for (String s: sorted.keySet()) {
PackageInfo pkg = sorted.get(s);
if (pkg.isHidden()) {
continue;
}
Boolean allHidden = true;
int pass = 0;
ClassInfo[] classesToCheck = null;
while (pass < 5 ) {
switch(pass) {
case 0:
classesToCheck = pkg.ordinaryClasses();
break;
case 1:
classesToCheck = pkg.enums();
break;
case 2:
classesToCheck = pkg.errors();
break;
case 3:
classesToCheck = pkg.exceptions();
break;
case 4:
classesToCheck = pkg.interfaces();
break;
default:
System.err.println("Error reading package: " + pkg.name());
break;
}
for (ClassInfo cl : classesToCheck) {
if (!cl.isHidden()) {
allHidden = false;
break;
}
}
if (!allHidden) {
break;
}
pass++;
}
if (allHidden) {
continue;
}
data.setValue("reference", "true");
data.setValue("docs.packages." + i + ".name", s);
data.setValue("docs.packages." + i + ".link", pkg.htmlPage());
data.setValue("docs.packages." + i + ".since", pkg.getSince());
TagInfo.makeHDF(data, "docs.packages." + i + ".shortDescr",
pkg.firstSentenceTags());
i++;
}
sinceTagger.writeVersionNames(data);
return data;
}
public static void writeDirectory(File dir, String relative)
{
File[] files = dir.listFiles();
int i, count = files.length;
for (i=0; i<count; i++) {
File f = files[i];
if (f.isFile()) {
String templ = relative + f.getName();
int len = templ.length();
if (len > 3 && ".cs".equals(templ.substring(len-3))) {
HDF data = makeHDF();
String filename = templ.substring(0,len-3) + htmlExtension;
ClearPage.write(data, templ, filename);
}
else if (len > 3 && ".jd".equals(templ.substring(len-3))) {
String filename = templ.substring(0,len-3) + htmlExtension;
DocFile.writePage(f.getAbsolutePath(), relative, filename);
}
else {
ClearPage.copyFile(f, templ);
}
}
else if (f.isDirectory()) {
writeDirectory(f, relative + f.getName() + "/");
}
}
}
public static void writeHTMLPages()
{
for (String htmlDir : ClearPage.htmlDirs) {
File f = new File(htmlDir);
if (!f.isDirectory()) {
System.err.println("htmlDir not a directory: " + htmlDir);
continue;
}
writeDirectory(f, "");
}
}
public static void writeLists()
{
HDF data = makeHDF();
ClassInfo[] classes = Converter.rootClasses();
SortedMap<String, Object> sorted = new TreeMap<String, Object>();
for (ClassInfo cl: classes) {
if (cl.isHidden()) {
continue;
}
sorted.put(cl.qualifiedName(), cl);
PackageInfo pkg = cl.containingPackage();
String name;
if (pkg == null) {
name = "";
} else {
name = pkg.name();
}
sorted.put(name, pkg);
}
int i = 0;
for (String s: sorted.keySet()) {
data.setValue("docs.pages." + i + ".id" , ""+i);
data.setValue("docs.pages." + i + ".label" , s);
Object o = sorted.get(s);
if (o instanceof PackageInfo) {
PackageInfo pkg = (PackageInfo)o;
data.setValue("docs.pages." + i + ".link" , pkg.htmlPage());
data.setValue("docs.pages." + i + ".type" , "package");
}
else if (o instanceof ClassInfo) {
ClassInfo cl = (ClassInfo)o;
data.setValue("docs.pages." + i + ".link" , cl.htmlPage());
data.setValue("docs.pages." + i + ".type" , "class");
}
i++;
}
ClearPage.write(data, "lists.cs", javadocDir + "lists.js");
}
public static void cantStripThis(ClassInfo cl, HashSet<ClassInfo> notStrippable) {
if (!notStrippable.add(cl)) {
// slight optimization: if it already contains cl, it already contains
// all of cl's parents
return;
}
ClassInfo supr = cl.superclass();
if (supr != null) {
cantStripThis(supr, notStrippable);
}
for (ClassInfo iface: cl.interfaces()) {
cantStripThis(iface, notStrippable);
}
}
private static String getPrintableName(ClassInfo cl) {
ClassInfo containingClass = cl.containingClass();
if (containingClass != null) {
// This is an inner class.
String baseName = cl.name();
baseName = baseName.substring(baseName.lastIndexOf('.') + 1);
return getPrintableName(containingClass) + '$' + baseName;
}
return cl.qualifiedName();
}
/**
* Writes the list of classes that must be present in order to
* provide the non-hidden APIs known to javadoc.
*
* @param filename the path to the file to write the list to
*/
public static void writeKeepList(String filename) {
HashSet<ClassInfo> notStrippable = new HashSet<ClassInfo>();
ClassInfo[] all = Converter.allClasses();
Arrays.sort(all); // just to make the file a little more readable
// If a class is public and not hidden, then it and everything it derives
// from cannot be stripped. Otherwise we can strip it.
for (ClassInfo cl: all) {
if (cl.isPublic() && !cl.isHidden()) {
cantStripThis(cl, notStrippable);
}
}
PrintStream stream = null;
try {
stream = new PrintStream(filename);
for (ClassInfo cl: notStrippable) {
stream.println(getPrintableName(cl));
}
}
catch (FileNotFoundException e) {
System.err.println("error writing file: " + filename);
}
finally {
if (stream != null) {
stream.close();
}
}
}
private static PackageInfo[] sVisiblePackages = null;
public static PackageInfo[] choosePackages() {
if (sVisiblePackages != null) {
return sVisiblePackages;
}
ClassInfo[] classes = Converter.rootClasses();
SortedMap<String, PackageInfo> sorted = new TreeMap<String, PackageInfo>();
for (ClassInfo cl: classes) {
PackageInfo pkg = cl.containingPackage();
String name;
if (pkg == null) {
name = "";
} else {
name = pkg.name();
}
sorted.put(name, pkg);
}
ArrayList<PackageInfo> result = new ArrayList();
for (String s: sorted.keySet()) {
PackageInfo pkg = sorted.get(s);
if (pkg.isHidden()) {
continue;
}
Boolean allHidden = true;
int pass = 0;
ClassInfo[] classesToCheck = null;
while (pass < 5 ) {
switch(pass) {
case 0:
classesToCheck = pkg.ordinaryClasses();
break;
case 1:
classesToCheck = pkg.enums();
break;
case 2:
classesToCheck = pkg.errors();
break;
case 3:
classesToCheck = pkg.exceptions();
break;
case 4:
classesToCheck = pkg.interfaces();
break;
default:
System.err.println("Error reading package: " + pkg.name());
break;
}
for (ClassInfo cl : classesToCheck) {
if (!cl.isHidden()) {
allHidden = false;
break;
}
}
if (!allHidden) {
break;
}
pass++;
}
if (allHidden) {
continue;
}
result.add(pkg);
}
sVisiblePackages = result.toArray(new PackageInfo[result.size()]);
return sVisiblePackages;
}
public static void writePackages(String filename)
{
HDF data = makePackageHDF();
int i = 0;
for (PackageInfo pkg: choosePackages()) {
writePackage(pkg);
data.setValue("docs.packages." + i + ".name", pkg.name());
data.setValue("docs.packages." + i + ".link", pkg.htmlPage());
TagInfo.makeHDF(data, "docs.packages." + i + ".shortDescr",
pkg.firstSentenceTags());
i++;
}
setPageTitle(data, "Package Index");
TagInfo.makeHDF(data, "root.descr",
Converter.convertTags(root.inlineTags(), null));
ClearPage.write(data, "packages.cs", filename);
ClearPage.write(data, "package-list.cs", javadocDir + "package-list");
Proofread.writePackages(filename,
Converter.convertTags(root.inlineTags(), null));
}
public static void writePackage(PackageInfo pkg)
{
// these this and the description are in the same directory,
// so it's okay
HDF data = makePackageHDF();
String name = pkg.name();
data.setValue("package.name", name);
data.setValue("package.since", pkg.getSince());
data.setValue("package.descr", "...description...");
makeClassListHDF(data, "package.interfaces",
ClassInfo.sortByName(pkg.interfaces()));
makeClassListHDF(data, "package.classes",
ClassInfo.sortByName(pkg.ordinaryClasses()));
makeClassListHDF(data, "package.enums",
ClassInfo.sortByName(pkg.enums()));
makeClassListHDF(data, "package.exceptions",
ClassInfo.sortByName(pkg.exceptions()));
makeClassListHDF(data, "package.errors",
ClassInfo.sortByName(pkg.errors()));
TagInfo.makeHDF(data, "package.shortDescr",
pkg.firstSentenceTags());
TagInfo.makeHDF(data, "package.descr", pkg.inlineTags());
String filename = pkg.htmlPage();
setPageTitle(data, name);
ClearPage.write(data, "package.cs", filename);
filename = pkg.fullDescriptionHtmlPage();
setPageTitle(data, name + " Details");
ClearPage.write(data, "package-descr.cs", filename);
Proofread.writePackage(filename, pkg.inlineTags());
}
public static void writeClassLists()
{
int i;
HDF data = makePackageHDF();
ClassInfo[] classes = PackageInfo.filterHidden(
Converter.convertClasses(root.classes()));
if (classes.length == 0) {
return ;
}
Sorter[] sorted = new Sorter[classes.length];
for (i=0; i<sorted.length; i++) {
ClassInfo cl = classes[i];
String name = cl.name();
sorted[i] = new Sorter(name, cl);
}
Arrays.sort(sorted);
// make a pass and resolve ones that have the same name
int firstMatch = 0;
String lastName = sorted[0].label;
for (i=1; i<sorted.length; i++) {
String s = sorted[i].label;
if (!lastName.equals(s)) {
if (firstMatch != i-1) {
// there were duplicates
for (int j=firstMatch; j<i; j++) {
PackageInfo pkg = ((ClassInfo)sorted[j].data).containingPackage();
if (pkg != null) {
sorted[j].label = sorted[j].label + " (" + pkg.name() + ")";
}
}
}
firstMatch = i;
lastName = s;
}
}
// and sort again
Arrays.sort(sorted);
for (i=0; i<sorted.length; i++) {
String s = sorted[i].label;
ClassInfo cl = (ClassInfo)sorted[i].data;
char first = Character.toUpperCase(s.charAt(0));
cl.makeShortDescrHDF(data, "docs.classes." + first + '.' + i);
}
setPageTitle(data, "Class Index");
ClearPage.write(data, "classes.cs", javadocDir + "classes" + htmlExtension);
}
// we use the word keywords because "index" means something else in html land
// the user only ever sees the word index
/* public static void writeKeywords()
{
ArrayList<KeywordEntry> keywords = new ArrayList<KeywordEntry>();
ClassInfo[] classes = PackageInfo.filterHidden(Converter.convertClasses(root.classes()));
for (ClassInfo cl: classes) {
cl.makeKeywordEntries(keywords);
}
HDF data = makeHDF();
Collections.sort(keywords);
int i=0;
for (KeywordEntry entry: keywords) {
String base = "keywords." + entry.firstChar() + "." + i;
entry.makeHDF(data, base);
i++;
}
setPageTitle(data, "Index");
ClearPage.write(data, "keywords.cs", javadocDir + "keywords" + htmlExtension);
} */
public static void writeHierarchy()
{
ClassInfo[] classes = Converter.rootClasses();
ArrayList<ClassInfo> info = new ArrayList<ClassInfo>();
for (ClassInfo cl: classes) {
if (!cl.isHidden()) {
info.add(cl);
}
}
HDF data = makePackageHDF();
Hierarchy.makeHierarchy(data, info.toArray(new ClassInfo[info.size()]));
setPageTitle(data, "Class Hierarchy");
ClearPage.write(data, "hierarchy.cs", javadocDir + "hierarchy" + htmlExtension);
}
public static void writeClasses()
{
ClassInfo[] classes = Converter.rootClasses();
for (ClassInfo cl: classes) {
HDF data = makePackageHDF();
if (!cl.isHidden()) {
writeClass(cl, data);
}
}
}
public static void writeClass(ClassInfo cl, HDF data)
{
cl.makeHDF(data);
setPageTitle(data, cl.name());
ClearPage.write(data, "class.cs", cl.htmlPage());
Proofread.writeClass(cl.htmlPage(), cl);
}
public static void makeClassListHDF(HDF data, String base,
ClassInfo[] classes)
{
for (int i=0; i<classes.length; i++) {
ClassInfo cl = classes[i];
if (!cl.isHidden()) {
cl.makeShortDescrHDF(data, base + "." + i);
}
}
}
public static String linkTarget(String source, String target)
{
String[] src = source.split("/");
String[] tgt = target.split("/");
int srclen = src.length;
int tgtlen = tgt.length;
int same = 0;
while (same < (srclen-1)
&& same < (tgtlen-1)
&& (src[same].equals(tgt[same]))) {
same++;
}
String s = "";
int up = srclen-same-1;
for (int i=0; i<up; i++) {
s += "../";
}
int N = tgtlen-1;
for (int i=same; i<N; i++) {
s += tgt[i] + '/';
}
s += tgt[tgtlen-1];
return s;
}
/**
* Returns true if the given element has an @hide or @pending annotation.
*/
private static boolean hasHideAnnotation(Doc doc) {
String comment = doc.getRawCommentText();
return comment.indexOf("@hide") != -1 || comment.indexOf("@pending") != -1;
}
/**
* Returns true if the given element is hidden.
*/
private static boolean isHidden(Doc doc) {
// Methods, fields, constructors.
if (doc instanceof MemberDoc) {
return hasHideAnnotation(doc);
}
// Classes, interfaces, enums, annotation types.
if (doc instanceof ClassDoc) {
ClassDoc classDoc = (ClassDoc) doc;
// Check the containing package.
if (hasHideAnnotation(classDoc.containingPackage())) {
return true;
}
// Check the class doc and containing class docs if this is a
// nested class.
ClassDoc current = classDoc;
do {
if (hasHideAnnotation(current)) {
return true;
}
current = current.containingClass();
} while (current != null);
}
return false;
}
/**
* Filters out hidden elements.
*/
private static Object filterHidden(Object o, Class<?> expected) {
if (o == null) {
return null;
}
Class type = o.getClass();
if (type.getName().startsWith("com.sun.")) {
// TODO: Implement interfaces from superclasses, too.
return Proxy.newProxyInstance(type.getClassLoader(),
type.getInterfaces(), new HideHandler(o));
} else if (o instanceof Object[]) {
Class<?> componentType = expected.getComponentType();
Object[] array = (Object[]) o;
List<Object> list = new ArrayList<Object>(array.length);
for (Object entry : array) {
if ((entry instanceof Doc) && isHidden((Doc) entry)) {
continue;
}
list.add(filterHidden(entry, componentType));
}
return list.toArray(
(Object[]) Array.newInstance(componentType, list.size()));
} else {
return o;
}
}
/**
* Filters hidden elements out of method return values.
*/
private static class HideHandler implements InvocationHandler {
private final Object target;
public HideHandler(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
String methodName = method.getName();
if (args != null) {
if (methodName.equals("compareTo") ||
methodName.equals("equals") ||
methodName.equals("overrides") ||
methodName.equals("subclassOf")) {
args[0] = unwrap(args[0]);
}
}
if (methodName.equals("getRawCommentText")) {
return filterComment((String) method.invoke(target, args));
}
// escape "&" in disjunctive types.
if (proxy instanceof Type && methodName.equals("toString")) {
return ((String) method.invoke(target, args))
.replace("&", "&");
}
try {
return filterHidden(method.invoke(target, args),
method.getReturnType());
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
private String filterComment(String s) {
if (s == null) {
return null;
}
s = s.trim();
// Work around off by one error
while (s.length() >= 5
&& s.charAt(s.length() - 5) == '{') {
s += " ";
}
return s;
}
private static Object unwrap(Object proxy) {
if (proxy instanceof Proxy)
return ((HideHandler)Proxy.getInvocationHandler(proxy)).target;
return proxy;
}
}
public static String scope(Scoped scoped) {
if (scoped.isPublic()) {
return "public";
}
else if (scoped.isProtected()) {
return "protected";
}
else if (scoped.isPackagePrivate()) {
return "";
}
else if (scoped.isPrivate()) {
return "private";
}
else {
throw new RuntimeException("invalid scope for object " + scoped);
}
}
/**
* Collect the values used by the Dev tools and write them in files packaged with the SDK
* @param output the ouput directory for the files.
*/
private static void writeSdkValues(String output) {
ArrayList<String> activityActions = new ArrayList<String>();
ArrayList<String> broadcastActions = new ArrayList<String>();
ArrayList<String> serviceActions = new ArrayList<String>();
ArrayList<String> categories = new ArrayList<String>();
ArrayList<String> features = new ArrayList<String>();
ArrayList<ClassInfo> layouts = new ArrayList<ClassInfo>();
ArrayList<ClassInfo> widgets = new ArrayList<ClassInfo>();
ArrayList<ClassInfo> layoutParams = new ArrayList<ClassInfo>();
ClassInfo[] classes = Converter.allClasses();
// Go through all the fields of all the classes, looking SDK stuff.
for (ClassInfo clazz : classes) {
// first check constant fields for the SdkConstant annotation.
FieldInfo[] fields = clazz.allSelfFields();
for (FieldInfo field : fields) {
Object cValue = field.constantValue();
if (cValue != null) {
AnnotationInstanceInfo[] annotations = field.annotations();
if (annotations.length > 0) {
for (AnnotationInstanceInfo annotation : annotations) {
if (SDK_CONSTANT_ANNOTATION.equals(annotation.type().qualifiedName())) {
AnnotationValueInfo[] values = annotation.elementValues();
if (values.length > 0) {
String type = values[0].valueString();
if (SDK_CONSTANT_TYPE_ACTIVITY_ACTION.equals(type)) {
activityActions.add(cValue.toString());
} else if (SDK_CONSTANT_TYPE_BROADCAST_ACTION.equals(type)) {
broadcastActions.add(cValue.toString());
} else if (SDK_CONSTANT_TYPE_SERVICE_ACTION.equals(type)) {
serviceActions.add(cValue.toString());
} else if (SDK_CONSTANT_TYPE_CATEGORY.equals(type)) {
categories.add(cValue.toString());
} else if (SDK_CONSTANT_TYPE_FEATURE.equals(type)) {
features.add(cValue.toString());
}
}
break;
}
}
}
}
}
// Now check the class for @Widget or if its in the android.widget package
// (unless the class is hidden or abstract, or non public)
if (clazz.isHidden() == false && clazz.isPublic() && clazz.isAbstract() == false) {
boolean annotated = false;
AnnotationInstanceInfo[] annotations = clazz.annotations();
if (annotations.length > 0) {
for (AnnotationInstanceInfo annotation : annotations) {
if (SDK_WIDGET_ANNOTATION.equals(annotation.type().qualifiedName())) {
widgets.add(clazz);
annotated = true;
break;
} else if (SDK_LAYOUT_ANNOTATION.equals(annotation.type().qualifiedName())) {
layouts.add(clazz);
annotated = true;
break;
}
}
}
if (annotated == false) {
// lets check if this is inside android.widget
PackageInfo pckg = clazz.containingPackage();
String packageName = pckg.name();
if ("android.widget".equals(packageName) ||
"android.view".equals(packageName)) {
// now we check what this class inherits either from android.view.ViewGroup
// or android.view.View, or android.view.ViewGroup.LayoutParams
int type = checkInheritance(clazz);
switch (type) {
case TYPE_WIDGET:
widgets.add(clazz);
break;
case TYPE_LAYOUT:
layouts.add(clazz);
break;
case TYPE_LAYOUT_PARAM:
layoutParams.add(clazz);
break;
}
}
}
}
}
// now write the files, whether or not the list are empty.
// the SDK built requires those files to be present.
Collections.sort(activityActions);
writeValues(output + "/activity_actions.txt", activityActions);
Collections.sort(broadcastActions);
writeValues(output + "/broadcast_actions.txt", broadcastActions);
Collections.sort(serviceActions);
writeValues(output + "/service_actions.txt", serviceActions);
Collections.sort(categories);
writeValues(output + "/categories.txt", categories);
Collections.sort(features);
writeValues(output + "/features.txt", features);
// before writing the list of classes, we do some checks, to make sure the layout params
// are enclosed by a layout class (and not one that has been declared as a widget)
for (int i = 0 ; i < layoutParams.size();) {
ClassInfo layoutParamClass = layoutParams.get(i);
ClassInfo containingClass = layoutParamClass.containingClass();
if (containingClass == null || layouts.indexOf(containingClass) == -1) {
layoutParams.remove(i);
} else {
i++;
}
}
writeClasses(output + "/widgets.txt", widgets, layouts, layoutParams);
}
/**
* Writes a list of values into a text files.
* @param pathname the absolute os path of the output file.
* @param values the list of values to write.
*/
private static void writeValues(String pathname, ArrayList<String> values) {
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(pathname, false);
bw = new BufferedWriter(fw);
for (String value : values) {
bw.append(value).append('\n');
}
} catch (IOException e) {
// pass for now
} finally {
try {
if (bw != null) bw.close();
} catch (IOException e) {
// pass for now
}
try {
if (fw != null) fw.close();
} catch (IOException e) {
// pass for now
}
}
}
/**
* Writes the widget/layout/layout param classes into a text files.
* @param pathname the absolute os path of the output file.
* @param widgets the list of widget classes to write.
* @param layouts the list of layout classes to write.
* @param layoutParams the list of layout param classes to write.
*/
private static void writeClasses(String pathname, ArrayList<ClassInfo> widgets,
ArrayList<ClassInfo> layouts, ArrayList<ClassInfo> layoutParams) {
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(pathname, false);
bw = new BufferedWriter(fw);
// write the 3 types of classes.
for (ClassInfo clazz : widgets) {
writeClass(bw, clazz, 'W');
}
for (ClassInfo clazz : layoutParams) {
writeClass(bw, clazz, 'P');
}
for (ClassInfo clazz : layouts) {
writeClass(bw, clazz, 'L');
}
} catch (IOException e) {
// pass for now
} finally {
try {
if (bw != null) bw.close();
} catch (IOException e) {
// pass for now
}
try {
if (fw != null) fw.close();
} catch (IOException e) {
// pass for now
}
}
}
/**
* Writes a class name and its super class names into a {@link BufferedWriter}.
* @param writer the BufferedWriter to write into
* @param clazz the class to write
* @param prefix the prefix to put at the beginning of the line.
* @throws IOException
*/
private static void writeClass(BufferedWriter writer, ClassInfo clazz, char prefix)
throws IOException {
writer.append(prefix).append(clazz.qualifiedName());
ClassInfo superClass = clazz;
while ((superClass = superClass.superclass()) != null) {
writer.append(' ').append(superClass.qualifiedName());
}
writer.append('\n');
}
/**
* Checks the inheritance of {@link ClassInfo} objects. This method return
* <ul>
* <li>{@link #TYPE_LAYOUT}: if the class extends <code>android.view.ViewGroup</code></li>
* <li>{@link #TYPE_WIDGET}: if the class extends <code>android.view.View</code></li>
* <li>{@link #TYPE_LAYOUT_PARAM}: if the class extends <code>android.view.ViewGroup$LayoutParams</code></li>
* <li>{@link #TYPE_NONE}: in all other cases</li>
* </ul>
* @param clazz the {@link ClassInfo} to check.
*/
private static int checkInheritance(ClassInfo clazz) {
if ("android.view.ViewGroup".equals(clazz.qualifiedName())) {
return TYPE_LAYOUT;
} else if ("android.view.View".equals(clazz.qualifiedName())) {
return TYPE_WIDGET;
} else if ("android.view.ViewGroup.LayoutParams".equals(clazz.qualifiedName())) {
return TYPE_LAYOUT_PARAM;
}
ClassInfo parent = clazz.superclass();
if (parent != null) {
return checkInheritance(parent);
}
return TYPE_NONE;
}
}
| tools/droiddoc/src/DroidDoc.java | /*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.sun.javadoc.*;
import org.clearsilver.HDF;
import java.util.*;
import java.io.*;
import java.lang.reflect.Proxy;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class DroidDoc
{
private static final String SDK_CONSTANT_ANNOTATION = "android.annotation.SdkConstant";
private static final String SDK_CONSTANT_TYPE_ACTIVITY_ACTION = "android.annotation.SdkConstant.SdkConstantType.ACTIVITY_INTENT_ACTION";
private static final String SDK_CONSTANT_TYPE_BROADCAST_ACTION = "android.annotation.SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION";
private static final String SDK_CONSTANT_TYPE_SERVICE_ACTION = "android.annotation.SdkConstant.SdkConstantType.SERVICE_INTENT_ACTION";
private static final String SDK_CONSTANT_TYPE_CATEGORY = "android.annotation.SdkConstant.SdkConstantType.INTENT_CATEGORY";
private static final String SDK_CONSTANT_TYPE_FEATURE = "android.annotation.SdkConstant.SdkConstantType.FEATURE";
private static final String SDK_WIDGET_ANNOTATION = "android.annotation.Widget";
private static final String SDK_LAYOUT_ANNOTATION = "android.annotation.Layout";
private static final int TYPE_NONE = 0;
private static final int TYPE_WIDGET = 1;
private static final int TYPE_LAYOUT = 2;
private static final int TYPE_LAYOUT_PARAM = 3;
public static final int SHOW_PUBLIC = 0x00000001;
public static final int SHOW_PROTECTED = 0x00000003;
public static final int SHOW_PACKAGE = 0x00000007;
public static final int SHOW_PRIVATE = 0x0000000f;
public static final int SHOW_HIDDEN = 0x0000001f;
public static int showLevel = SHOW_PROTECTED;
public static final String javadocDir = "reference/";
public static String htmlExtension;
public static RootDoc root;
public static ArrayList<String[]> mHDFData = new ArrayList<String[]>();
public static Map<Character,String> escapeChars = new HashMap<Character,String>();
public static String title = "";
public static SinceTagger sinceTagger = new SinceTagger();
private static boolean parseComments = false;
private static boolean generateDocs = true;
/**
* Returns true if we should parse javadoc comments,
* reporting errors in the process.
*/
public static boolean parseComments() {
return generateDocs || parseComments;
}
public static boolean checkLevel(int level)
{
return (showLevel & level) == level;
}
public static boolean checkLevel(boolean pub, boolean prot, boolean pkgp,
boolean priv, boolean hidden)
{
int level = 0;
if (hidden && !checkLevel(SHOW_HIDDEN)) {
return false;
}
if (pub && checkLevel(SHOW_PUBLIC)) {
return true;
}
if (prot && checkLevel(SHOW_PROTECTED)) {
return true;
}
if (pkgp && checkLevel(SHOW_PACKAGE)) {
return true;
}
if (priv && checkLevel(SHOW_PRIVATE)) {
return true;
}
return false;
}
public static boolean start(RootDoc r)
{
String keepListFile = null;
String proofreadFile = null;
String todoFile = null;
String sdkValuePath = null;
ArrayList<SampleCode> sampleCodes = new ArrayList<SampleCode>();
String stubsDir = null;
//Create the dependency graph for the stubs directory
boolean apiXML = false;
boolean offlineMode = false;
String apiFile = null;
String debugStubsFile = "";
HashSet<String> stubPackages = null;
root = r;
String[][] options = r.options();
for (String[] a: options) {
if (a[0].equals("-d")) {
ClearPage.outputDir = a[1];
}
else if (a[0].equals("-templatedir")) {
ClearPage.addTemplateDir(a[1]);
}
else if (a[0].equals("-hdf")) {
mHDFData.add(new String[] {a[1], a[2]});
}
else if (a[0].equals("-toroot")) {
ClearPage.toroot = a[1];
}
else if (a[0].equals("-samplecode")) {
sampleCodes.add(new SampleCode(a[1], a[2], a[3]));
}
else if (a[0].equals("-htmldir")) {
ClearPage.htmlDirs.add(a[1]);
}
else if (a[0].equals("-title")) {
DroidDoc.title = a[1];
}
else if (a[0].equals("-werror")) {
Errors.setWarningsAreErrors(true);
}
else if (a[0].equals("-error") || a[0].equals("-warning")
|| a[0].equals("-hide")) {
try {
int level = -1;
if (a[0].equals("-error")) {
level = Errors.ERROR;
}
else if (a[0].equals("-warning")) {
level = Errors.WARNING;
}
else if (a[0].equals("-hide")) {
level = Errors.HIDDEN;
}
Errors.setErrorLevel(Integer.parseInt(a[1]), level);
}
catch (NumberFormatException e) {
// already printed below
return false;
}
}
else if (a[0].equals("-keeplist")) {
keepListFile = a[1];
}
else if (a[0].equals("-proofread")) {
proofreadFile = a[1];
}
else if (a[0].equals("-todo")) {
todoFile = a[1];
}
else if (a[0].equals("-public")) {
showLevel = SHOW_PUBLIC;
}
else if (a[0].equals("-protected")) {
showLevel = SHOW_PROTECTED;
}
else if (a[0].equals("-package")) {
showLevel = SHOW_PACKAGE;
}
else if (a[0].equals("-private")) {
showLevel = SHOW_PRIVATE;
}
else if (a[0].equals("-hidden")) {
showLevel = SHOW_HIDDEN;
}
else if (a[0].equals("-stubs")) {
stubsDir = a[1];
}
else if (a[0].equals("-stubpackages")) {
stubPackages = new HashSet();
for (String pkg: a[1].split(":")) {
stubPackages.add(pkg);
}
}
else if (a[0].equals("-sdkvalues")) {
sdkValuePath = a[1];
}
else if (a[0].equals("-apixml")) {
apiXML = true;
apiFile = a[1];
}
else if (a[0].equals("-nodocs")) {
generateDocs = false;
}
else if (a[0].equals("-parsecomments")) {
parseComments = true;
}
else if (a[0].equals("-since")) {
sinceTagger.addVersion(a[1], a[2]);
}
else if (a[0].equals("-offlinemode")) {
offlineMode = true;
}
}
// read some prefs from the template
if (!readTemplateSettings()) {
return false;
}
// Set up the data structures
Converter.makeInfo(r);
if (generateDocs) {
long startTime = System.nanoTime();
// Apply @since tags from the XML file
sinceTagger.tagAll(Converter.rootClasses());
// Files for proofreading
if (proofreadFile != null) {
Proofread.initProofread(proofreadFile);
}
if (todoFile != null) {
TodoFile.writeTodoFile(todoFile);
}
// HTML Pages
if (!ClearPage.htmlDirs.isEmpty()) {
writeHTMLPages();
}
// Navigation tree
NavTree.writeNavTree(javadocDir);
// Packages Pages
writePackages(javadocDir
+ (!ClearPage.htmlDirs.isEmpty()
? "packages" + htmlExtension
: "index" + htmlExtension));
// Classes
writeClassLists();
writeClasses();
writeHierarchy();
// writeKeywords();
// Lists for JavaScript
writeLists();
if (keepListFile != null) {
writeKeepList(keepListFile);
}
// Sample Code
for (SampleCode sc: sampleCodes) {
sc.write(offlineMode);
}
// Index page
writeIndex();
Proofread.finishProofread(proofreadFile);
if (sdkValuePath != null) {
writeSdkValues(sdkValuePath);
}
long time = System.nanoTime() - startTime;
System.out.println("DroidDoc took " + (time / 1000000000) + " sec. to write docs to "
+ ClearPage.outputDir);
}
// Stubs
if (stubsDir != null) {
Stubs.writeStubs(stubsDir, apiXML, apiFile, stubPackages);
}
Errors.printErrors();
return !Errors.hadError;
}
private static void writeIndex() {
HDF data = makeHDF();
ClearPage.write(data, "index.cs", javadocDir + "index" + htmlExtension);
}
private static boolean readTemplateSettings()
{
HDF data = makeHDF();
htmlExtension = data.getValue("template.extension", ".html");
int i=0;
while (true) {
String k = data.getValue("template.escape." + i + ".key", "");
String v = data.getValue("template.escape." + i + ".value", "");
if ("".equals(k)) {
break;
}
if (k.length() != 1) {
System.err.println("template.escape." + i + ".key must have a length of 1: " + k);
return false;
}
escapeChars.put(k.charAt(0), v);
i++;
}
return true;
}
public static String escape(String s) {
if (escapeChars.size() == 0) {
return s;
}
StringBuffer b = null;
int begin = 0;
final int N = s.length();
for (int i=0; i<N; i++) {
char c = s.charAt(i);
String mapped = escapeChars.get(c);
if (mapped != null) {
if (b == null) {
b = new StringBuffer(s.length() + mapped.length());
}
if (begin != i) {
b.append(s.substring(begin, i));
}
b.append(mapped);
begin = i+1;
}
}
if (b != null) {
if (begin != N) {
b.append(s.substring(begin, N));
}
return b.toString();
}
return s;
}
public static void setPageTitle(HDF data, String title)
{
String s = title;
if (DroidDoc.title.length() > 0) {
s += " - " + DroidDoc.title;
}
data.setValue("page.title", s);
}
public static LanguageVersion languageVersion()
{
return LanguageVersion.JAVA_1_5;
}
public static int optionLength(String option)
{
if (option.equals("-d")) {
return 2;
}
if (option.equals("-templatedir")) {
return 2;
}
if (option.equals("-hdf")) {
return 3;
}
if (option.equals("-toroot")) {
return 2;
}
if (option.equals("-samplecode")) {
return 4;
}
if (option.equals("-htmldir")) {
return 2;
}
if (option.equals("-title")) {
return 2;
}
if (option.equals("-werror")) {
return 1;
}
if (option.equals("-hide")) {
return 2;
}
if (option.equals("-warning")) {
return 2;
}
if (option.equals("-error")) {
return 2;
}
if (option.equals("-keeplist")) {
return 2;
}
if (option.equals("-proofread")) {
return 2;
}
if (option.equals("-todo")) {
return 2;
}
if (option.equals("-public")) {
return 1;
}
if (option.equals("-protected")) {
return 1;
}
if (option.equals("-package")) {
return 1;
}
if (option.equals("-private")) {
return 1;
}
if (option.equals("-hidden")) {
return 1;
}
if (option.equals("-stubs")) {
return 2;
}
if (option.equals("-stubpackages")) {
return 2;
}
if (option.equals("-sdkvalues")) {
return 2;
}
if (option.equals("-apixml")) {
return 2;
}
if (option.equals("-nodocs")) {
return 1;
}
if (option.equals("-since")) {
return 3;
}
if (option.equals("-offlinemode")) {
return 1;
}
return 0;
}
public static boolean validOptions(String[][] options, DocErrorReporter r)
{
for (String[] a: options) {
if (a[0].equals("-error") || a[0].equals("-warning")
|| a[0].equals("-hide")) {
try {
Integer.parseInt(a[1]);
}
catch (NumberFormatException e) {
r.printError("bad -" + a[0] + " value must be a number: "
+ a[1]);
return false;
}
}
}
return true;
}
public static HDF makeHDF()
{
HDF data = new HDF();
for (String[] p: mHDFData) {
data.setValue(p[0], p[1]);
}
try {
for (String p: ClearPage.hdfFiles) {
data.readFile(p);
}
}
catch (IOException e) {
throw new RuntimeException(e);
}
return data;
}
public static HDF makePackageHDF()
{
HDF data = makeHDF();
ClassInfo[] classes = Converter.rootClasses();
SortedMap<String, PackageInfo> sorted = new TreeMap<String, PackageInfo>();
for (ClassInfo cl: classes) {
PackageInfo pkg = cl.containingPackage();
String name;
if (pkg == null) {
name = "";
} else {
name = pkg.name();
}
sorted.put(name, pkg);
}
int i = 0;
for (String s: sorted.keySet()) {
PackageInfo pkg = sorted.get(s);
if (pkg.isHidden()) {
continue;
}
Boolean allHidden = true;
int pass = 0;
ClassInfo[] classesToCheck = null;
while (pass < 5 ) {
switch(pass) {
case 0:
classesToCheck = pkg.ordinaryClasses();
break;
case 1:
classesToCheck = pkg.enums();
break;
case 2:
classesToCheck = pkg.errors();
break;
case 3:
classesToCheck = pkg.exceptions();
break;
case 4:
classesToCheck = pkg.interfaces();
break;
default:
System.err.println("Error reading package: " + pkg.name());
break;
}
for (ClassInfo cl : classesToCheck) {
if (!cl.isHidden()) {
allHidden = false;
break;
}
}
if (!allHidden) {
break;
}
pass++;
}
if (allHidden) {
continue;
}
data.setValue("reference", "true");
data.setValue("docs.packages." + i + ".name", s);
data.setValue("docs.packages." + i + ".link", pkg.htmlPage());
data.setValue("docs.packages." + i + ".since", pkg.getSince());
TagInfo.makeHDF(data, "docs.packages." + i + ".shortDescr",
pkg.firstSentenceTags());
i++;
}
sinceTagger.writeVersionNames(data);
return data;
}
public static void writeDirectory(File dir, String relative)
{
File[] files = dir.listFiles();
int i, count = files.length;
for (i=0; i<count; i++) {
File f = files[i];
if (f.isFile()) {
String templ = relative + f.getName();
int len = templ.length();
if (len > 3 && ".cs".equals(templ.substring(len-3))) {
HDF data = makeHDF();
String filename = templ.substring(0,len-3) + htmlExtension;
ClearPage.write(data, templ, filename);
}
else if (len > 3 && ".jd".equals(templ.substring(len-3))) {
String filename = templ.substring(0,len-3) + htmlExtension;
DocFile.writePage(f.getAbsolutePath(), relative, filename);
}
else {
ClearPage.copyFile(f, templ);
}
}
else if (f.isDirectory()) {
writeDirectory(f, relative + f.getName() + "/");
}
}
}
public static void writeHTMLPages()
{
for (String htmlDir : ClearPage.htmlDirs) {
File f = new File(htmlDir);
if (!f.isDirectory()) {
System.err.println("htmlDir not a directory: " + htmlDir);
continue;
}
writeDirectory(f, "");
}
}
public static void writeLists()
{
HDF data = makeHDF();
ClassInfo[] classes = Converter.rootClasses();
SortedMap<String, Object> sorted = new TreeMap<String, Object>();
for (ClassInfo cl: classes) {
if (cl.isHidden()) {
continue;
}
sorted.put(cl.qualifiedName(), cl);
PackageInfo pkg = cl.containingPackage();
String name;
if (pkg == null) {
name = "";
} else {
name = pkg.name();
}
sorted.put(name, pkg);
}
int i = 0;
for (String s: sorted.keySet()) {
data.setValue("docs.pages." + i + ".id" , ""+i);
data.setValue("docs.pages." + i + ".label" , s);
Object o = sorted.get(s);
if (o instanceof PackageInfo) {
PackageInfo pkg = (PackageInfo)o;
data.setValue("docs.pages." + i + ".link" , pkg.htmlPage());
data.setValue("docs.pages." + i + ".type" , "package");
}
else if (o instanceof ClassInfo) {
ClassInfo cl = (ClassInfo)o;
data.setValue("docs.pages." + i + ".link" , cl.htmlPage());
data.setValue("docs.pages." + i + ".type" , "class");
}
i++;
}
ClearPage.write(data, "lists.cs", javadocDir + "lists.js");
}
public static void cantStripThis(ClassInfo cl, HashSet<ClassInfo> notStrippable) {
if (!notStrippable.add(cl)) {
// slight optimization: if it already contains cl, it already contains
// all of cl's parents
return;
}
ClassInfo supr = cl.superclass();
if (supr != null) {
cantStripThis(supr, notStrippable);
}
for (ClassInfo iface: cl.interfaces()) {
cantStripThis(iface, notStrippable);
}
}
private static String getPrintableName(ClassInfo cl) {
ClassInfo containingClass = cl.containingClass();
if (containingClass != null) {
// This is an inner class.
String baseName = cl.name();
baseName = baseName.substring(baseName.lastIndexOf('.') + 1);
return getPrintableName(containingClass) + '$' + baseName;
}
return cl.qualifiedName();
}
/**
* Writes the list of classes that must be present in order to
* provide the non-hidden APIs known to javadoc.
*
* @param filename the path to the file to write the list to
*/
public static void writeKeepList(String filename) {
HashSet<ClassInfo> notStrippable = new HashSet<ClassInfo>();
ClassInfo[] all = Converter.allClasses();
Arrays.sort(all); // just to make the file a little more readable
// If a class is public and not hidden, then it and everything it derives
// from cannot be stripped. Otherwise we can strip it.
for (ClassInfo cl: all) {
if (cl.isPublic() && !cl.isHidden()) {
cantStripThis(cl, notStrippable);
}
}
PrintStream stream = null;
try {
stream = new PrintStream(filename);
for (ClassInfo cl: notStrippable) {
stream.println(getPrintableName(cl));
}
}
catch (FileNotFoundException e) {
System.err.println("error writing file: " + filename);
}
finally {
if (stream != null) {
stream.close();
}
}
}
private static PackageInfo[] sVisiblePackages = null;
public static PackageInfo[] choosePackages() {
if (sVisiblePackages != null) {
return sVisiblePackages;
}
ClassInfo[] classes = Converter.rootClasses();
SortedMap<String, PackageInfo> sorted = new TreeMap<String, PackageInfo>();
for (ClassInfo cl: classes) {
PackageInfo pkg = cl.containingPackage();
String name;
if (pkg == null) {
name = "";
} else {
name = pkg.name();
}
sorted.put(name, pkg);
}
ArrayList<PackageInfo> result = new ArrayList();
for (String s: sorted.keySet()) {
PackageInfo pkg = sorted.get(s);
if (pkg.isHidden()) {
continue;
}
Boolean allHidden = true;
int pass = 0;
ClassInfo[] classesToCheck = null;
while (pass < 5 ) {
switch(pass) {
case 0:
classesToCheck = pkg.ordinaryClasses();
break;
case 1:
classesToCheck = pkg.enums();
break;
case 2:
classesToCheck = pkg.errors();
break;
case 3:
classesToCheck = pkg.exceptions();
break;
case 4:
classesToCheck = pkg.interfaces();
break;
default:
System.err.println("Error reading package: " + pkg.name());
break;
}
for (ClassInfo cl : classesToCheck) {
if (!cl.isHidden()) {
allHidden = false;
break;
}
}
if (!allHidden) {
break;
}
pass++;
}
if (allHidden) {
continue;
}
result.add(pkg);
}
sVisiblePackages = result.toArray(new PackageInfo[result.size()]);
return sVisiblePackages;
}
public static void writePackages(String filename)
{
HDF data = makePackageHDF();
int i = 0;
for (PackageInfo pkg: choosePackages()) {
writePackage(pkg);
data.setValue("docs.packages." + i + ".name", pkg.name());
data.setValue("docs.packages." + i + ".link", pkg.htmlPage());
TagInfo.makeHDF(data, "docs.packages." + i + ".shortDescr",
pkg.firstSentenceTags());
i++;
}
setPageTitle(data, "Package Index");
TagInfo.makeHDF(data, "root.descr",
Converter.convertTags(root.inlineTags(), null));
ClearPage.write(data, "packages.cs", filename);
ClearPage.write(data, "package-list.cs", javadocDir + "package-list");
Proofread.writePackages(filename,
Converter.convertTags(root.inlineTags(), null));
}
public static void writePackage(PackageInfo pkg)
{
// these this and the description are in the same directory,
// so it's okay
HDF data = makePackageHDF();
String name = pkg.name();
data.setValue("package.name", name);
data.setValue("package.since", pkg.getSince());
data.setValue("package.descr", "...description...");
makeClassListHDF(data, "package.interfaces",
ClassInfo.sortByName(pkg.interfaces()));
makeClassListHDF(data, "package.classes",
ClassInfo.sortByName(pkg.ordinaryClasses()));
makeClassListHDF(data, "package.enums",
ClassInfo.sortByName(pkg.enums()));
makeClassListHDF(data, "package.exceptions",
ClassInfo.sortByName(pkg.exceptions()));
makeClassListHDF(data, "package.errors",
ClassInfo.sortByName(pkg.errors()));
TagInfo.makeHDF(data, "package.shortDescr",
pkg.firstSentenceTags());
TagInfo.makeHDF(data, "package.descr", pkg.inlineTags());
String filename = pkg.htmlPage();
setPageTitle(data, name);
ClearPage.write(data, "package.cs", filename);
filename = pkg.fullDescriptionHtmlPage();
setPageTitle(data, name + " Details");
ClearPage.write(data, "package-descr.cs", filename);
Proofread.writePackage(filename, pkg.inlineTags());
}
public static void writeClassLists()
{
int i;
HDF data = makePackageHDF();
ClassInfo[] classes = PackageInfo.filterHidden(
Converter.convertClasses(root.classes()));
if (classes.length == 0) {
return ;
}
Sorter[] sorted = new Sorter[classes.length];
for (i=0; i<sorted.length; i++) {
ClassInfo cl = classes[i];
String name = cl.name();
sorted[i] = new Sorter(name, cl);
}
Arrays.sort(sorted);
// make a pass and resolve ones that have the same name
int firstMatch = 0;
String lastName = sorted[0].label;
for (i=1; i<sorted.length; i++) {
String s = sorted[i].label;
if (!lastName.equals(s)) {
if (firstMatch != i-1) {
// there were duplicates
for (int j=firstMatch; j<i; j++) {
PackageInfo pkg = ((ClassInfo)sorted[j].data).containingPackage();
if (pkg != null) {
sorted[j].label = sorted[j].label + " (" + pkg.name() + ")";
}
}
}
firstMatch = i;
lastName = s;
}
}
// and sort again
Arrays.sort(sorted);
for (i=0; i<sorted.length; i++) {
String s = sorted[i].label;
ClassInfo cl = (ClassInfo)sorted[i].data;
char first = Character.toUpperCase(s.charAt(0));
cl.makeShortDescrHDF(data, "docs.classes." + first + '.' + i);
}
setPageTitle(data, "Class Index");
ClearPage.write(data, "classes.cs", javadocDir + "classes" + htmlExtension);
}
// we use the word keywords because "index" means something else in html land
// the user only ever sees the word index
/* public static void writeKeywords()
{
ArrayList<KeywordEntry> keywords = new ArrayList<KeywordEntry>();
ClassInfo[] classes = PackageInfo.filterHidden(Converter.convertClasses(root.classes()));
for (ClassInfo cl: classes) {
cl.makeKeywordEntries(keywords);
}
HDF data = makeHDF();
Collections.sort(keywords);
int i=0;
for (KeywordEntry entry: keywords) {
String base = "keywords." + entry.firstChar() + "." + i;
entry.makeHDF(data, base);
i++;
}
setPageTitle(data, "Index");
ClearPage.write(data, "keywords.cs", javadocDir + "keywords" + htmlExtension);
} */
public static void writeHierarchy()
{
ClassInfo[] classes = Converter.rootClasses();
ArrayList<ClassInfo> info = new ArrayList<ClassInfo>();
for (ClassInfo cl: classes) {
if (!cl.isHidden()) {
info.add(cl);
}
}
HDF data = makePackageHDF();
Hierarchy.makeHierarchy(data, info.toArray(new ClassInfo[info.size()]));
setPageTitle(data, "Class Hierarchy");
ClearPage.write(data, "hierarchy.cs", javadocDir + "hierarchy" + htmlExtension);
}
public static void writeClasses()
{
ClassInfo[] classes = Converter.rootClasses();
for (ClassInfo cl: classes) {
HDF data = makePackageHDF();
if (!cl.isHidden()) {
writeClass(cl, data);
}
}
}
public static void writeClass(ClassInfo cl, HDF data)
{
cl.makeHDF(data);
setPageTitle(data, cl.name());
ClearPage.write(data, "class.cs", cl.htmlPage());
Proofread.writeClass(cl.htmlPage(), cl);
}
public static void makeClassListHDF(HDF data, String base,
ClassInfo[] classes)
{
for (int i=0; i<classes.length; i++) {
ClassInfo cl = classes[i];
if (!cl.isHidden()) {
cl.makeShortDescrHDF(data, base + "." + i);
}
}
}
public static String linkTarget(String source, String target)
{
String[] src = source.split("/");
String[] tgt = target.split("/");
int srclen = src.length;
int tgtlen = tgt.length;
int same = 0;
while (same < (srclen-1)
&& same < (tgtlen-1)
&& (src[same].equals(tgt[same]))) {
same++;
}
String s = "";
int up = srclen-same-1;
for (int i=0; i<up; i++) {
s += "../";
}
int N = tgtlen-1;
for (int i=same; i<N; i++) {
s += tgt[i] + '/';
}
s += tgt[tgtlen-1];
return s;
}
/**
* Returns true if the given element has an @hide or @pending annotation.
*/
private static boolean hasHideAnnotation(Doc doc) {
String comment = doc.getRawCommentText();
return comment.indexOf("@hide") != -1 || comment.indexOf("@pending") != -1;
}
/**
* Returns true if the given element is hidden.
*/
private static boolean isHidden(Doc doc) {
// Methods, fields, constructors.
if (doc instanceof MemberDoc) {
return hasHideAnnotation(doc);
}
// Classes, interfaces, enums, annotation types.
if (doc instanceof ClassDoc) {
ClassDoc classDoc = (ClassDoc) doc;
// Check the containing package.
if (hasHideAnnotation(classDoc.containingPackage())) {
return true;
}
// Check the class doc and containing class docs if this is a
// nested class.
ClassDoc current = classDoc;
do {
if (hasHideAnnotation(current)) {
return true;
}
current = current.containingClass();
} while (current != null);
}
return false;
}
/**
* Filters out hidden elements.
*/
private static Object filterHidden(Object o, Class<?> expected) {
if (o == null) {
return null;
}
Class type = o.getClass();
if (type.getName().startsWith("com.sun.")) {
// TODO: Implement interfaces from superclasses, too.
return Proxy.newProxyInstance(type.getClassLoader(),
type.getInterfaces(), new HideHandler(o));
} else if (o instanceof Object[]) {
Class<?> componentType = expected.getComponentType();
Object[] array = (Object[]) o;
List<Object> list = new ArrayList<Object>(array.length);
for (Object entry : array) {
if ((entry instanceof Doc) && isHidden((Doc) entry)) {
continue;
}
list.add(filterHidden(entry, componentType));
}
return list.toArray(
(Object[]) Array.newInstance(componentType, list.size()));
} else {
return o;
}
}
/**
* Filters hidden elements out of method return values.
*/
private static class HideHandler implements InvocationHandler {
private final Object target;
public HideHandler(Object target) {
this.target = target;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
String methodName = method.getName();
if (args != null) {
if (methodName.equals("compareTo") ||
methodName.equals("equals") ||
methodName.equals("overrides") ||
methodName.equals("subclassOf")) {
args[0] = unwrap(args[0]);
}
}
if (methodName.equals("getRawCommentText")) {
return filterComment((String) method.invoke(target, args));
}
// escape "&" in disjunctive types.
if (proxy instanceof Type && methodName.equals("toString")) {
return ((String) method.invoke(target, args))
.replace("&", "&");
}
try {
return filterHidden(method.invoke(target, args),
method.getReturnType());
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
private String filterComment(String s) {
if (s == null) {
return null;
}
s = s.trim();
// Work around off by one error
while (s.length() >= 5
&& s.charAt(s.length() - 5) == '{') {
s += " ";
}
return s;
}
private static Object unwrap(Object proxy) {
if (proxy instanceof Proxy)
return ((HideHandler)Proxy.getInvocationHandler(proxy)).target;
return proxy;
}
}
public static String scope(Scoped scoped) {
if (scoped.isPublic()) {
return "public";
}
else if (scoped.isProtected()) {
return "protected";
}
else if (scoped.isPackagePrivate()) {
return "";
}
else if (scoped.isPrivate()) {
return "private";
}
else {
throw new RuntimeException("invalid scope for object " + scoped);
}
}
/**
* Collect the values used by the Dev tools and write them in files packaged with the SDK
* @param output the ouput directory for the files.
*/
private static void writeSdkValues(String output) {
ArrayList<String> activityActions = new ArrayList<String>();
ArrayList<String> broadcastActions = new ArrayList<String>();
ArrayList<String> serviceActions = new ArrayList<String>();
ArrayList<String> categories = new ArrayList<String>();
ArrayList<String> features = new ArrayList<String>();
ArrayList<ClassInfo> layouts = new ArrayList<ClassInfo>();
ArrayList<ClassInfo> widgets = new ArrayList<ClassInfo>();
ArrayList<ClassInfo> layoutParams = new ArrayList<ClassInfo>();
ClassInfo[] classes = Converter.allClasses();
// Go through all the fields of all the classes, looking SDK stuff.
for (ClassInfo clazz : classes) {
// first check constant fields for the SdkConstant annotation.
FieldInfo[] fields = clazz.allSelfFields();
for (FieldInfo field : fields) {
Object cValue = field.constantValue();
if (cValue != null) {
AnnotationInstanceInfo[] annotations = field.annotations();
if (annotations.length > 0) {
for (AnnotationInstanceInfo annotation : annotations) {
if (SDK_CONSTANT_ANNOTATION.equals(annotation.type().qualifiedName())) {
AnnotationValueInfo[] values = annotation.elementValues();
if (values.length > 0) {
String type = values[0].valueString();
if (SDK_CONSTANT_TYPE_ACTIVITY_ACTION.equals(type)) {
activityActions.add(cValue.toString());
} else if (SDK_CONSTANT_TYPE_BROADCAST_ACTION.equals(type)) {
broadcastActions.add(cValue.toString());
} else if (SDK_CONSTANT_TYPE_SERVICE_ACTION.equals(type)) {
serviceActions.add(cValue.toString());
} else if (SDK_CONSTANT_TYPE_CATEGORY.equals(type)) {
categories.add(cValue.toString());
} else if (SDK_CONSTANT_TYPE_FEATURE.equals(type)) {
features.add(cValue.toString());
}
}
break;
}
}
}
}
}
// Now check the class for @Widget or if its in the android.widget package
// (unless the class is hidden or abstract, or non public)
if (clazz.isHidden() == false && clazz.isPublic() && clazz.isAbstract() == false) {
boolean annotated = false;
AnnotationInstanceInfo[] annotations = clazz.annotations();
if (annotations.length > 0) {
for (AnnotationInstanceInfo annotation : annotations) {
if (SDK_WIDGET_ANNOTATION.equals(annotation.type().qualifiedName())) {
widgets.add(clazz);
annotated = true;
break;
} else if (SDK_LAYOUT_ANNOTATION.equals(annotation.type().qualifiedName())) {
layouts.add(clazz);
annotated = true;
break;
}
}
}
if (annotated == false) {
// lets check if this is inside android.widget
PackageInfo pckg = clazz.containingPackage();
String packageName = pckg.name();
if ("android.widget".equals(packageName) ||
"android.view".equals(packageName)) {
// now we check what this class inherits either from android.view.ViewGroup
// or android.view.View, or android.view.ViewGroup.LayoutParams
int type = checkInheritance(clazz);
switch (type) {
case TYPE_WIDGET:
widgets.add(clazz);
break;
case TYPE_LAYOUT:
layouts.add(clazz);
break;
case TYPE_LAYOUT_PARAM:
layoutParams.add(clazz);
break;
}
}
}
}
}
// now write the files, whether or not the list are empty.
// the SDK built requires those files to be present.
Collections.sort(activityActions);
writeValues(output + "/activity_actions.txt", activityActions);
Collections.sort(broadcastActions);
writeValues(output + "/broadcast_actions.txt", broadcastActions);
Collections.sort(serviceActions);
writeValues(output + "/service_actions.txt", serviceActions);
Collections.sort(categories);
writeValues(output + "/categories.txt", categories);
Collections.sort(features);
writeValues(output + "/features.txt", features);
// before writing the list of classes, we do some checks, to make sure the layout params
// are enclosed by a layout class (and not one that has been declared as a widget)
for (int i = 0 ; i < layoutParams.size();) {
ClassInfo layoutParamClass = layoutParams.get(i);
ClassInfo containingClass = layoutParamClass.containingClass();
if (containingClass == null || layouts.indexOf(containingClass) == -1) {
layoutParams.remove(i);
} else {
i++;
}
}
writeClasses(output + "/widgets.txt", widgets, layouts, layoutParams);
}
/**
* Writes a list of values into a text files.
* @param pathname the absolute os path of the output file.
* @param values the list of values to write.
*/
private static void writeValues(String pathname, ArrayList<String> values) {
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(pathname, false);
bw = new BufferedWriter(fw);
for (String value : values) {
bw.append(value).append('\n');
}
} catch (IOException e) {
// pass for now
} finally {
try {
if (bw != null) bw.close();
} catch (IOException e) {
// pass for now
}
try {
if (fw != null) fw.close();
} catch (IOException e) {
// pass for now
}
}
}
/**
* Writes the widget/layout/layout param classes into a text files.
* @param pathname the absolute os path of the output file.
* @param widgets the list of widget classes to write.
* @param layouts the list of layout classes to write.
* @param layoutParams the list of layout param classes to write.
*/
private static void writeClasses(String pathname, ArrayList<ClassInfo> widgets,
ArrayList<ClassInfo> layouts, ArrayList<ClassInfo> layoutParams) {
FileWriter fw = null;
BufferedWriter bw = null;
try {
fw = new FileWriter(pathname, false);
bw = new BufferedWriter(fw);
// write the 3 types of classes.
for (ClassInfo clazz : widgets) {
writeClass(bw, clazz, 'W');
}
for (ClassInfo clazz : layoutParams) {
writeClass(bw, clazz, 'P');
}
for (ClassInfo clazz : layouts) {
writeClass(bw, clazz, 'L');
}
} catch (IOException e) {
// pass for now
} finally {
try {
if (bw != null) bw.close();
} catch (IOException e) {
// pass for now
}
try {
if (fw != null) fw.close();
} catch (IOException e) {
// pass for now
}
}
}
/**
* Writes a class name and its super class names into a {@link BufferedWriter}.
* @param writer the BufferedWriter to write into
* @param clazz the class to write
* @param prefix the prefix to put at the beginning of the line.
* @throws IOException
*/
private static void writeClass(BufferedWriter writer, ClassInfo clazz, char prefix)
throws IOException {
writer.append(prefix).append(clazz.qualifiedName());
ClassInfo superClass = clazz;
while ((superClass = superClass.superclass()) != null) {
writer.append(' ').append(superClass.qualifiedName());
}
writer.append('\n');
}
/**
* Checks the inheritance of {@link ClassInfo} objects. This method return
* <ul>
* <li>{@link #TYPE_LAYOUT}: if the class extends <code>android.view.ViewGroup</code></li>
* <li>{@link #TYPE_WIDGET}: if the class extends <code>android.view.View</code></li>
* <li>{@link #TYPE_LAYOUT_PARAM}: if the class extends <code>android.view.ViewGroup$LayoutParams</code></li>
* <li>{@link #TYPE_NONE}: in all other cases</li>
* </ul>
* @param clazz the {@link ClassInfo} to check.
*/
private static int checkInheritance(ClassInfo clazz) {
if ("android.view.ViewGroup".equals(clazz.qualifiedName())) {
return TYPE_LAYOUT;
} else if ("android.view.View".equals(clazz.qualifiedName())) {
return TYPE_WIDGET;
} else if ("android.view.ViewGroup.LayoutParams".equals(clazz.qualifiedName())) {
return TYPE_LAYOUT_PARAM;
}
ClassInfo parent = clazz.superclass();
if (parent != null) {
return checkInheritance(parent);
}
return TYPE_NONE;
}
}
| am cd7c775e: fix the build still
Merge commit 'cd7c775ece6854765ae3208818e76d9d11724713' into gingerbread-plus-aosp
* commit 'cd7c775ece6854765ae3208818e76d9d11724713':
fix the build still
| tools/droiddoc/src/DroidDoc.java | am cd7c775e: fix the build still |
|
Java | apache-2.0 | 1348f1927ae3cf8a116ce0279af70ade82cbe65d | 0 | juliusHuelsmann/paint,juliusHuelsmann/paint,juliusHuelsmann/paint | //package declaration
package control.tabs;
//import declarations
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.border.LineBorder;
import control.ContorlPicture;
import control.ControlPaint;
import model.objects.painting.po.PaintObject;
import model.objects.painting.po.PaintObjectImage;
import model.objects.painting.po.PaintObjectPen;
import model.objects.painting.po.PaintObjectWriting;
import model.settings.Constants;
import model.settings.Status;
import model.settings.ViewSettings;
import model.util.DPoint;
import model.util.Util;
import model.util.adt.list.List;
import model.util.paint.MyClipboard;
import view.View;
import view.forms.Message;
import view.forms.Page;
import view.tabs.Paint;
import view.util.Item1PenSelection;
import view.util.VButtonWrapper;
/**
* Controller class dealing with main paint stuff.
*
* @author Julius Huelsmann
* @version %I%, %U%
*/
public final class CTabPainting implements ActionListener, MouseListener {
/**
* The StiftAuswahl which currently is selected for both groups.
*/
private Item1PenSelection[] lastSelected = null;
/**
* Instance of ControlPaint.
*/
private ControlPaint controlPaint;
/**
* empty utility class Constructor.
* @param _cp the instance of ControlPaint
*/
public CTabPainting(final ControlPaint _cp) {
this.controlPaint = _cp;
// initialize and start action
//initialize the last selected array
this.lastSelected = new Item1PenSelection[2];
}
/**
* Error-checked getter method.
* @return the controlPicture.
*/
private ContorlPicture getControlPicture() {
return controlPaint.getControlPic();
}
/**
* Fetch the instance of tab paint.
* @return the tab paint.
*/
public Paint getTabPaint() {
if (controlPaint != null
&& controlPaint.getView() != null
&& controlPaint.getView().getTabs() != null
&& controlPaint.getView().getTabs().getTab_paint() != null) {
return controlPaint.getView().getTabs().getTab_paint();
} else {
Status.getLogger().severe("Tab does not exist!");
return null;
}
}
/**
* Action-listener which handles the action of the following .
* {@inheritDoc}
*/
public void actionPerformed(final ActionEvent _event) {
/**
* Instance of paint fetched out of instance of the main controller
* class.
* The getter method handles the printing of an error message if the
* instance of Paint is null.
*/
final Paint paint = getTabPaint();
//if the initialization process has terminated without errors
//the instance of Paint is not equal to null, thus it is possible to
//check the source of the ActionEvent.
if (paint != null) {
if (
//turn inverted
_event.getSource().equals(paint.getTb_turnMirror()
.getActionCause())) {
/**
* The command which is executed in terminal for rotating the
* screen.
*/
final String commandNormal = "xrandr -o normal";
/**
* The result of the command's execution in terminal.
* If the response tells that the command has been executed
* successfully, there is nothing to do. Otherwise
* perform rotation done by program and print a warning.
*/
final String result = Util.executeCommandLinux(commandNormal);
if (result.startsWith(Util.EXECUTION_SUCCESS)) {
//print success information
Status.getLogger().info("Rotation normal success");
} else if (result.startsWith(Util.EXECUTION_FAILED)) {
//if the window has not been inverted yet invert it by
//using the implemented methods turn. Otherwise there
//is nothing to do.
if (Status.isNormalRotation()) {
//print a warning and turn the instance of view
//afterwards
Status.getLogger().warning("beta rotation");
getView().turn();
//set the new rotation value.
Status.setNormalRotation(false);
}
}
} else if (
//turn normal
_event.getSource().equals(
paint.getTb_turnNormal().getActionCause())) {
/**
* The command which is executed in terminal for rotating the
* screen.
*/
final String commandInverted = "xrandr -o inverted";
/**
* The result of the command's execution in terminal.
* If the response tells that the command has been executed
* successfully, there is nothing to do. Otherwise
* perform rotation done by program and print a warning.
*/
final String result = Util.executeCommandLinux(commandInverted);
if (result.startsWith(Util.EXECUTION_SUCCESS)) {
//print success information
Status.getLogger().info("Rotation normal success");
} else if (result.startsWith(Util.EXECUTION_FAILED)) {
//if the window has been inverted yet invert it by
//using the implemented methods turn. Otherwise there
//is nothing to do.
if (!Status.isNormalRotation()) {
//print a warning and turn the instance of view
//afterwards
Status.getLogger().warning("beta rotation");
getView().turn();
//set the new rotation value.
Status.setNormalRotation(true);
}
}
} else if (_event.getSource().equals(
paint.getTb_new().getActionCause())) {
mr_new();
} else if (_event.getSource().equals(
paint.getTb_save().getActionCause())) {
mr_save();
} else if (_event.getSource().equals(
paint.getTb_load().getActionCause())) {
mr_load();
} else if (_event.getSource().equals(
paint.getTb_zoomOut().getActionCause())) {
mr_zoomOut();
} else if (_event.getSource().equals(
paint.getTb_copy().getActionCause())) {
mr_copy();
} else if (_event.getSource().equals(
paint.getTb_paste().getActionCause())) {
mr_paste();
} else if (_event.getSource().equals(
paint.getTb_cut().getActionCause())) {
mr_cut();
} else if (_event.getSource().equals(
paint.getTb_eraseAll().getActionCause())) {
Status.setEraseIndex(Status.ERASE_ALL);
getView().getTabs().getTab_paint().getTb_erase().setOpen(false);
} else if (_event.getSource().equals(
paint.getTb_eraseDestroy().getActionCause())) {
Status.setEraseIndex(Status.ERASE_DESTROY);
getView().getTabs().getTab_paint().getTb_erase().setOpen(false);
} else if (_event.getSource().equals(
paint.getTb_prev().getActionCause())) {
controlPaint.getPicture().getHistory().applyPrevious();
controlPaint.getControlPic().refreshPaint();
} else if (_event.getSource().equals(
paint.getTb_next().getActionCause())) {
controlPaint.getPicture().getHistory().applyNext();
controlPaint.getControlPic().refreshPaint();
}
}
}
private Page getPage() {
return controlPaint.getView().getPage();
}
private View getView() {
return controlPaint.getView();
}
/*
*
*
* clipboard
*
*
*/
/**
* MouseReleased method for button press at button cut.
*/
public void mr_cut() {
MyClipboard.getInstance().copyPaintObjects(
controlPaint.getPicture(),
controlPaint.getPicture().getLs_poSelected(),
controlPaint.getPicture().paintSelectedBI(controlPaint
.getControlPaintSelection().getR_selection()));
controlPaint.getPicture().deleteSelected(
controlPaint.getView().getTabs().getTab_debug(),
controlPaint.getcTabSelection());
getControlPicture().releaseSelected();
getControlPicture().refreshPaint();
}
/**
* MouseReleased method for button press at button paste.
*/
public void mr_paste() {
getControlPicture().releaseSelected();
controlPaint.getPicture().releaseSelected(
controlPaint.getControlPaintSelection(),
controlPaint.getcTabSelection(),
controlPaint.getView().getTabs().getTab_debug(),
controlPaint.getView().getPage().getJlbl_painting()
.getLocation().x,
controlPaint.getView().getPage().getJlbl_painting()
.getLocation().y);
controlPaint.getPicture().createSelected();
Object o = MyClipboard.getInstance().paste();
if (o instanceof BufferedImage) {
PaintObjectImage poi = controlPaint.getPicture().createPOI(
(BufferedImage) o);
controlPaint.getPicture().insertIntoSelected(
poi, controlPaint.getView().getTabs().getTab_debug());
//finish insertion into selected.
controlPaint.getPicture().finishSelection(
controlPaint.getcTabSelection());
controlPaint.getPicture().paintSelected(getPage(),
controlPaint.getControlPic(),
controlPaint.getControlPaintSelection());
getPage().getJlbl_background2().repaint();
} else if (o instanceof List) {
@SuppressWarnings("unchecked")
List<PaintObject> ls = (List<PaintObject>) o;
ls.toFirst();
/*
* Calculate the center of the entire selection
* because that center is to be placed at the image's center.
*/
Point pnt_centerInImage = new Point();
int amount = 0;
//calculate the shift
while (!ls.isEmpty() && !ls.isBehind()) {
int cX = ls.getItem().getSnapshotBounds().width / 2
+ ls.getItem().getSnapshotBounds().x;
int cY = ls.getItem().getSnapshotBounds().height / 2
+ ls.getItem().getSnapshotBounds().y;
pnt_centerInImage.x += cX;
pnt_centerInImage.y += cY;
amount++;
ls.next();
}
//divide the sum of the image bounds by the total amount of items
pnt_centerInImage.x /= amount;
pnt_centerInImage.y /= amount;
final double stretchWidth = 1.0 * Status.getImageSize().getWidth()
/ Status.getImageShowSize().getWidth(),
stretchHeight = 1.0 * Status.getImageSize().getHeight()
/ Status.getImageShowSize().getHeight();
// calculate the wanted result for the center, thus the coordinates
// of the currently displayed image-scope's center.
Point pnt_wanted = new Point(
(int) ((-getPage().getJlbl_painting().getLocation().getX()
+ getPage().getJlbl_painting().getWidth() / 2)
* stretchWidth),
(int) ((-getPage().getJlbl_painting().getLocation().getY()
+ getPage().getJlbl_painting().getHeight() / 2)
* stretchHeight)
);
Point pnt_move = new Point(
-pnt_centerInImage.x + pnt_wanted.x,
-pnt_centerInImage.y + pnt_wanted.y);
ls.toFirst();
while (!ls.isEmpty() && !ls.isBehind()) {
PaintObject po = ls.getItem();
if (po instanceof PaintObjectImage) {
PaintObjectImage poi = (PaintObjectImage) po;
PaintObjectImage poi_new = controlPaint.getPicture()
.createPOI(poi.getSnapshot());
controlPaint.getPicture().insertIntoSelected(
poi_new, controlPaint.getView().getTabs()
.getTab_debug());
//finish insertion into selected.
controlPaint.getPicture().finishSelection(
controlPaint.getcTabSelection());
} else if (po instanceof PaintObjectWriting) {
PaintObjectWriting pow = (PaintObjectWriting) po;
PaintObjectWriting pow_new
= controlPaint.getPicture().createPOW(pow.getPen());
pow.getPoints().toFirst();
while (!pow.getPoints().isEmpty()
&& !pow.getPoints().isBehind()) {
pow_new.addPoint(new DPoint(
pow.getPoints().getItem()));
pow.getPoints().next();
}
controlPaint.getPicture().insertIntoSelected(pow_new,
controlPaint.getView().getTabs().getTab_debug());
} else if (po != null) {
Status.getLogger().warning("unknown kind of "
+ "PaintObject; element = " + po);
}
ls.next();
}
//finish insertion into selected.
controlPaint.getPicture().finishSelection(
controlPaint.getcTabSelection());
controlPaint.getPicture().moveSelected(pnt_move.x, pnt_move.y);
} else if (o instanceof PaintObjectWriting) {
//theoretically unused because everything is stored
//inside lists.
controlPaint.getPicture().insertIntoSelected(
(PaintObjectWriting) o,
controlPaint.getView().getTabs().getTab_debug());
//finish insertion into selected.
controlPaint.getPicture().finishSelection(
controlPaint.getcTabSelection());
} else if (o instanceof PaintObjectImage) {
//theoretically unused because everything is stored
//inside lists.
controlPaint.getPicture().insertIntoSelected(
(PaintObjectImage) o,
controlPaint.getView().getTabs().getTab_debug());
//finish insertion into selected.
controlPaint.getPicture().finishSelection(
controlPaint.getcTabSelection());
new Exception("hier").printStackTrace();
} else {
Status.getLogger().warning("unknown return type of clipboard"
+ "\ncontent: " + o);
}
controlPaint.getPicture().paintSelected(getPage(),
controlPaint.getControlPic(),
controlPaint.getControlPaintSelection());
getPage().getJlbl_background2().repaint();
getControlPicture().refreshPaint();
}
/**
* MouseReleased method for button press at button copy.
*/
public void mr_copy() {
MyClipboard.getInstance().copyPaintObjects(
controlPaint.getPicture(),
controlPaint.getPicture().getLs_poSelected(),
controlPaint.getPicture().paintSelectedBI(controlPaint
.getControlPaintSelection().getR_selection()));
}
/*
*
*
* exit
*
*
*/
/*
*
*
* File operations
*
*
*/
/**
* the save action.
*/
public void mr_save() {
final String fileEnding;
// if not saved yet. Otherwise use the saved save path.
if (Status.getSavePath() == null) {
// choose a file
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(new java.io.File("."));
jfc.setDialogTitle("Select save location");
int retval = jfc.showOpenDialog(getView());
// if selected a file.
if (retval == JFileChooser.APPROVE_OPTION) {
// fetch the selected file.
File file = jfc.getSelectedFile();
// edit file ending
if (!file.getName().toLowerCase().contains(".")) {
fileEnding = Status.getSaveFormat();
file = new File(file.getAbsolutePath() + ".pic");
} else if (!Constants.endsWithSaveFormat(file.getName())) {
fileEnding = "";
String formatList = "(";
for (String format : Constants.SAVE_FORMATS) {
formatList += format + ", ";
}
formatList = formatList.subSequence(0,
formatList.length() - 2) + ")";
JOptionPane.showMessageDialog(getView(),
"Error saving file:\nFile extension \""
+ Constants.getFileExtension(file.getName())
+ "\" not supported! Supported formats:\n\t"
+ formatList + ".", "Error",
JOptionPane.ERROR_MESSAGE);
mr_save();
return;
} else {
fileEnding = "."
+ Constants.getFileExtension(file.getName());
}
// if file already exists
if (file.exists()) {
int result = JOptionPane.showConfirmDialog(
getView(), "File already exists. "
+ "Owerwrite?", "Owerwrite file?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == 1) {
// no
mr_save();
return;
} else if (result == 2) {
// interrupt
return;
}
// overwrite
}
Status.setSavePath(file.getAbsolutePath());
} else {
fileEnding = "";
}
} else {
fileEnding = "";
}
// generate path without the file ending.
if (Status.getSavePath() != null) {
int d = Status.getSavePath().toCharArray().length - 2 - 1;
String firstPath = Status.getSavePath().substring(0, d);
// save images in both formats.
// controlPaint.getPicture().saveIMAGE(
// firstPath, getPage().getJlbl_painting().getLocation().x,
// getPage().getJlbl_painting().getLocation().y);
controlPaint.getPicture().saveIMAGE(firstPath, 0, 0, fileEnding);
controlPaint.getPicture().savePicture(firstPath + "pic");
Status.setUncommittedChanges(false);
}
}
/**
* MouseReleased method for button press at button load.
*/
public void mr_load() {
int i = JOptionPane.showConfirmDialog(getView(),
"Do you want to save the committed changes? ",
"Save changes", JOptionPane.YES_NO_CANCEL_OPTION);
// no
if (i == 1) {
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(new java.io.File("."));
jfc.setDialogTitle("Select load location");
int retval = jfc.showOpenDialog(getView());
if (retval == JFileChooser.APPROVE_OPTION) {
File file = jfc.getSelectedFile();
if (file.getName().toLowerCase().endsWith(".pic")) {
controlPaint.getPicture().loadPicture(
file.getAbsolutePath());
Status.setUncommittedChanges(false);
getControlPicture().refreshPaint();
} else if (file.getName().toLowerCase().endsWith(".png")
|| file.getName().toLowerCase().endsWith(".jpg")) {
try {
BufferedImage bi_imageBG = ImageIO.read(file);
Status.setImageSize(new Dimension(
bi_imageBG.getWidth(),
bi_imageBG.getHeight()));
Status.setImageShowSize(Status.getImageSize());
controlPaint.getPicture().emptyImage();
controlPaint.getPicture().addPaintObjectImage(
bi_imageBG);
getControlPicture().refreshPaint();
} catch (IOException e) {
e.printStackTrace();
new Error("not supported yet to load pictures "
+ "because there are no paintObjects for "
+ "pictures"
+ "but only those for lines.")
.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(getView(),
"Select a .png file.", "Error",
JOptionPane.ERROR_MESSAGE);
mr_save();
Status.setUncommittedChanges(false);
}
}
} else if (i == 0) {
// yes
mr_save();
}
}
/**
* the action which is performed if new image is released.
*/
public void mr_new() {
if (Status.isUncommittedChanges()) {
int i = JOptionPane.showConfirmDialog(getView(),
"Do you want to save the committed changes? ",
"Save changes", JOptionPane.YES_NO_CANCEL_OPTION);
if (i == 0) {
mr_save();
mr_new();
}
//if the user does not want to interrupt recall actionNew
if (i == 1) {
controlPaint.getView().getPage().getJpnl_new().setVisible(true);
controlPaint.getPicture().reload();
Status.setUncommittedChanges(false);
}
} else {
controlPaint.getView().getPage().getJpnl_new().setVisible(true);
controlPaint.getPicture().reload();
Status.setUncommittedChanges(false);
}
}
/*
*
*
* Zoom
*
*
*/
/**
* MouseReleased method for button press at button zoom out.
*/
public void mr_zoomOut() {
//TODO: adjust this one.
//if able to zoom out
if (Status.getImageSize().width
/ Status.getImageShowSize().width
< Math.pow(ViewSettings.ZOOM_MULITPLICATOR,
ViewSettings.MAX_ZOOM_OUT)) {
int
newWidth = Status.getImageShowSize().width
/ ViewSettings.ZOOM_MULITPLICATOR,
newHeight = Status
.getImageShowSize().height
/ ViewSettings.ZOOM_MULITPLICATOR;
Point oldLocation = new Point(
getPage().getJlbl_painting().getLocation().x
- getPage().getJlbl_painting().getWidth() / 2
+ getPage().getJlbl_painting().getWidth()
* ViewSettings.ZOOM_MULITPLICATOR / 2,
getPage().getJlbl_painting().getLocation().y
- getPage().getJlbl_painting().getHeight() / 2
+ getPage().getJlbl_painting().getHeight()
* ViewSettings.ZOOM_MULITPLICATOR / 2);
// not smaller than the
oldLocation.x = Math.max(oldLocation.x,
-(Status.getImageShowSize().width - getPage().getWidth()));
oldLocation.y = Math.max(oldLocation.y,
-(Status.getImageShowSize().height
- getPage().getHeight()));
// not greater than 0
oldLocation.x = Math.min(oldLocation.x, 0);
oldLocation.y = Math.min(oldLocation.y, 0);
//set new image size and adapt the page by flipping
//TODO: previously used getpage.getjlbl-p.setLoc(),
//why?
//transformed into setLocation. works too by now.
Status.setImageShowSize(new Dimension(newWidth, newHeight));
getPage().flip();
getPage().getJlbl_painting()
.setBounds(
(oldLocation.x) / ViewSettings.ZOOM_MULITPLICATOR ,
(oldLocation.y) / ViewSettings.ZOOM_MULITPLICATOR,
getPage().getJlbl_painting().getWidth(),
getPage().getJlbl_painting().getHeight());
getPage().refrehsSps();
if (controlPaint.getPicture().isSelected()) {
getControlPicture().releaseSelected();
controlPaint.getPicture().releaseSelected(
controlPaint.getControlPaintSelection(),
controlPaint.getcTabSelection(),
controlPaint.getView().getTabs().getTab_debug(),
controlPaint.getView().getPage().getJlbl_painting()
.getLocation().x,
controlPaint.getView().getPage().getJlbl_painting()
.getLocation().y);
}
updateResizeLocation();
} else {
Message.showMessage(Message.MESSAGE_ID_INFO,
"max zoom out reached");
updateResizeLocation();
}
// TODO: hier die location aktualisieren.
}
/**
* Update the location of the JButtons for resizing. Thus the user is
* able to resize the whole image.
*/
public void updateResizeLocation() {
//the width and the height
int w = Status.getImageShowSize().width;
int h = Status.getImageShowSize().height;
//set location
getPage().getJbtn_resize()[2][1].setLocation(w, h / 2);
getPage().getJbtn_resize()[2][2].setLocation(w, h);
getPage().getJbtn_resize()[1][2].setLocation(w / 2, h);
//set visible
getPage().getJbtn_resize()[1][2].setVisible(true);
getPage().getJbtn_resize()[2][2].setVisible(true);
getPage().getJbtn_resize()[2][1].setVisible(true);
}
/**
* {@inheritDoc}
*/
public void mouseEntered(final MouseEvent _event) {
/**
* Instance of paint fetched out of instance of the main controller
* class.
* The getter method handles the printing of an error message if the
* instance of Paint is null.
*/
final Paint paint = getTabPaint();
//if the initialization process has terminated without errors
//the instance of Paint is not equal to null, thus it is possible to
//check the source of the ActionEvent.
if (paint != null) {
//if mouse is over a pen
if (isAStiftAuswahl(_event.getSource())) {
//if is not selected
Item1PenSelection selected = (Item1PenSelection)
((VButtonWrapper) _event.getSource()).wrapObject();
if (!selected.isSelected()) {
applyFocus(selected);
}
return;
} else {
//for loop for identifying the cause of the event
for (int j = 0; j < paint.getJbtn_colors().length;
j++) {
if (_event.getSource().equals(
paint.getJbtn_colors()[j])) {
//highlight the border of the icon with mouse-over
paint.getJbtn_colors()[j].setBorder(
BorderFactory.createCompoundBorder(
new LineBorder(Color.black),
new LineBorder(Color.black)));
//return because only one item is performing action
//at one time
return;
}
}
}
}
}
/**
* {@inheritDoc}
*/
public void mouseExited(final MouseEvent _event) {
/**
* Instance of paint fetched out of instance of the main controller
* class.
* The getter method handles the printing of an error message if the
* instance of Paint is null.
*/
final Paint paint = getTabPaint();
//if the initialization process has terminated without errors
//the instance of Paint is not equal to null, thus it is possible to
//check the source of the ActionEvent.
if (paint != null) {
//outfit of StiftAuswahl
if (isAStiftAuswahl(_event.getSource())) {
//reset the instance of Pen if this pen is not selected
Item1PenSelection selected = (Item1PenSelection)
((VButtonWrapper) _event.getSource()).wrapObject();
if (!selected.isSelected()) {
selected.setOpaque(false);
}
return;
}
//for loop for identifying the cause of the event
for (int j = 0; j < paint.getJbtn_colors().length; j++) {
if (_event.getSource().equals(
paint.getJbtn_colors()[j])) {
//reset the border of the icon which had mouse-over
paint.getJbtn_colors()[j].setBorder(BorderFactory
.createCompoundBorder(new LineBorder(Color.black),
new LineBorder(Color.white)));
//return because only one item is performing action at one
//time
return;
}
}
}
}
/**
* apply focus to selected item.
* @param _selected the selected item
*/
public static void applyFocus(final Item1PenSelection _selected) {
_selected.setOpaque(true);
_selected.setBackground(ViewSettings.GENERAL_CLR_BORDER);
}
/**
* {@inheritDoc}
*/
public void mousePressed(final MouseEvent _event) { }
/**
* {@inheritDoc}
*/
public void mouseReleased(final MouseEvent _event) { }
/**
* {@inheritDoc}
*/
public void mouseClicked(final MouseEvent _event) {
//if mouse is over a pen
if (isAStiftAuswahl(_event.getSource())) {
Item1PenSelection stift_event = (Item1PenSelection)
((VButtonWrapper) _event.getSource()).wrapObject();
//if pen is not selected yet
if (lastSelected[stift_event.getPenSelection() - 1] != null
&& lastSelected[stift_event.getPenSelection() - 1]
!= stift_event) {
lastSelected[stift_event.getPenSelection() - 1]
.setSelected(false);
lastSelected[stift_event.getPenSelection() - 1]
.setOpaque(false);
lastSelected[stift_event.getPenSelection() - 1]
.setBackground(Color.green);
}
//select the current pen
stift_event.setSelected(true);
stift_event.setOpaque(true);
stift_event.setBackground(ViewSettings.GENERAL_CLR_BORDER);
//set the last selected
lastSelected[stift_event.getPenSelection() - 1] = stift_event;
}
}
/**
* Checks whether an Object is a StiftAuswahl wrapper button or not.
*
* @param _obj the object
* @return the boolean
*/
public static boolean isAStiftAuswahl(final Object _obj) {
try {
((Item1PenSelection) ((VButtonWrapper) _obj).wrapObject())
.toString();
return true;
} catch (Exception e) {
return false;
}
}
/**
* @return the controlPaint
*/
public ControlPaint getControlPaint() {
return controlPaint;
}
/**
* @param _controlPaint to set.
*/
public void setControlPaint(final ControlPaint _controlPaint) {
this.controlPaint = _controlPaint;
}
}
| PaintNotes/src/main/java/control/tabs/CTabPainting.java | //package declaration
package control.tabs;
//import declarations
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.border.LineBorder;
import control.ContorlPicture;
import control.ControlPaint;
import model.objects.painting.po.PaintObject;
import model.objects.painting.po.PaintObjectImage;
import model.objects.painting.po.PaintObjectWriting;
import model.settings.Constants;
import model.settings.Status;
import model.settings.ViewSettings;
import model.util.DPoint;
import model.util.Util;
import model.util.adt.list.List;
import model.util.paint.MyClipboard;
import view.View;
import view.forms.Message;
import view.forms.Page;
import view.tabs.Paint;
import view.util.Item1PenSelection;
import view.util.VButtonWrapper;
/**
* Controller class dealing with main paint stuff.
*
* @author Julius Huelsmann
* @version %I%, %U%
*/
public final class CTabPainting implements ActionListener, MouseListener {
/**
* The StiftAuswahl which currently is selected for both groups.
*/
private Item1PenSelection[] lastSelected = null;
/**
* Instance of ControlPaint.
*/
private ControlPaint controlPaint;
/**
* empty utility class Constructor.
* @param _cp the instance of ControlPaint
*/
public CTabPainting(final ControlPaint _cp) {
this.controlPaint = _cp;
// initialize and start action
//initialize the last selected array
this.lastSelected = new Item1PenSelection[2];
}
/**
* Error-checked getter method.
* @return the controlPicture.
*/
private ContorlPicture getControlPicture() {
return controlPaint.getControlPic();
}
/**
* Fetch the instance of tab paint.
* @return the tab paint.
*/
public Paint getTabPaint() {
if (controlPaint != null
&& controlPaint.getView() != null
&& controlPaint.getView().getTabs() != null
&& controlPaint.getView().getTabs().getTab_paint() != null) {
return controlPaint.getView().getTabs().getTab_paint();
} else {
Status.getLogger().severe("Tab does not exist!");
return null;
}
}
/**
* Action-listener which handles the action of the following .
* {@inheritDoc}
*/
public void actionPerformed(final ActionEvent _event) {
/**
* Instance of paint fetched out of instance of the main controller
* class.
* The getter method handles the printing of an error message if the
* instance of Paint is null.
*/
final Paint paint = getTabPaint();
//if the initialization process has terminated without errors
//the instance of Paint is not equal to null, thus it is possible to
//check the source of the ActionEvent.
if (paint != null) {
if (
//turn inverted
_event.getSource().equals(paint.getTb_turnMirror()
.getActionCause())) {
/**
* The command which is executed in terminal for rotating the
* screen.
*/
final String commandNormal = "xrandr -o normal";
/**
* The result of the command's execution in terminal.
* If the response tells that the command has been executed
* successfully, there is nothing to do. Otherwise
* perform rotation done by program and print a warning.
*/
final String result = Util.executeCommandLinux(commandNormal);
if (result.startsWith(Util.EXECUTION_SUCCESS)) {
//print success information
Status.getLogger().info("Rotation normal success");
} else if (result.startsWith(Util.EXECUTION_FAILED)) {
//if the window has not been inverted yet invert it by
//using the implemented methods turn. Otherwise there
//is nothing to do.
if (Status.isNormalRotation()) {
//print a warning and turn the instance of view
//afterwards
Status.getLogger().warning("beta rotation");
getView().turn();
//set the new rotation value.
Status.setNormalRotation(false);
}
}
} else if (
//turn normal
_event.getSource().equals(
paint.getTb_turnNormal().getActionCause())) {
/**
* The command which is executed in terminal for rotating the
* screen.
*/
final String commandInverted = "xrandr -o inverted";
/**
* The result of the command's execution in terminal.
* If the response tells that the command has been executed
* successfully, there is nothing to do. Otherwise
* perform rotation done by program and print a warning.
*/
final String result = Util.executeCommandLinux(commandInverted);
if (result.startsWith(Util.EXECUTION_SUCCESS)) {
//print success information
Status.getLogger().info("Rotation normal success");
} else if (result.startsWith(Util.EXECUTION_FAILED)) {
//if the window has been inverted yet invert it by
//using the implemented methods turn. Otherwise there
//is nothing to do.
if (!Status.isNormalRotation()) {
//print a warning and turn the instance of view
//afterwards
Status.getLogger().warning("beta rotation");
getView().turn();
//set the new rotation value.
Status.setNormalRotation(true);
}
}
} else if (_event.getSource().equals(
paint.getTb_new().getActionCause())) {
mr_new();
} else if (_event.getSource().equals(
paint.getTb_save().getActionCause())) {
mr_save();
} else if (_event.getSource().equals(
paint.getTb_load().getActionCause())) {
mr_load();
} else if (_event.getSource().equals(
paint.getTb_zoomOut().getActionCause())) {
mr_zoomOut();
} else if (_event.getSource().equals(
paint.getTb_copy().getActionCause())) {
mr_copy();
} else if (_event.getSource().equals(
paint.getTb_paste().getActionCause())) {
mr_paste();
} else if (_event.getSource().equals(
paint.getTb_cut().getActionCause())) {
mr_cut();
} else if (_event.getSource().equals(
paint.getTb_eraseAll().getActionCause())) {
Status.setEraseIndex(Status.ERASE_ALL);
getView().getTabs().getTab_paint().getTb_erase().setOpen(false);
} else if (_event.getSource().equals(
paint.getTb_eraseDestroy().getActionCause())) {
Status.setEraseIndex(Status.ERASE_DESTROY);
getView().getTabs().getTab_paint().getTb_erase().setOpen(false);
} else if (_event.getSource().equals(
paint.getTb_prev().getActionCause())) {
controlPaint.getPicture().getHistory().applyPrevious();
controlPaint.getControlPic().refreshPaint();
} else if (_event.getSource().equals(
paint.getTb_next().getActionCause())) {
controlPaint.getPicture().getHistory().applyNext();
controlPaint.getControlPic().refreshPaint();
}
}
}
private Page getPage() {
return controlPaint.getView().getPage();
}
private View getView() {
return controlPaint.getView();
}
/*
*
*
* clipboard
*
*
*/
/**
* MouseReleased method for button press at button cut.
*/
public void mr_cut() {
MyClipboard.getInstance().copyPaintObjects(
controlPaint.getPicture(),
controlPaint.getPicture().getLs_poSelected(),
controlPaint.getPicture().paintSelectedBI(controlPaint
.getControlPaintSelection().getR_selection()));
controlPaint.getPicture().deleteSelected(
controlPaint.getView().getTabs().getTab_debug(),
controlPaint.getcTabSelection());
getControlPicture().releaseSelected();
getControlPicture().refreshPaint();
}
/**
* MouseReleased method for button press at button paste.
*/
public void mr_paste() {
getControlPicture().releaseSelected();
controlPaint.getPicture().releaseSelected(
controlPaint.getControlPaintSelection(),
controlPaint.getcTabSelection(),
controlPaint.getView().getTabs().getTab_debug(),
controlPaint.getView().getPage().getJlbl_painting()
.getLocation().x,
controlPaint.getView().getPage().getJlbl_painting()
.getLocation().y);
controlPaint.getPicture().createSelected();
Object o = MyClipboard.getInstance().paste();
if (o instanceof BufferedImage) {
PaintObjectImage poi = controlPaint.getPicture().createPOI(
(BufferedImage) o);
controlPaint.getPicture().insertIntoSelected(
poi, controlPaint.getView().getTabs().getTab_debug());
//finish insertion into selected.
controlPaint.getPicture().finishSelection(
controlPaint.getcTabSelection());
controlPaint.getPicture().paintSelected(getPage(),
controlPaint.getControlPic(),
controlPaint.getControlPaintSelection());
getPage().getJlbl_background2().repaint();
} else if (o instanceof List) {
@SuppressWarnings("unchecked")
List<PaintObject> ls = (List<PaintObject>) o;
ls.toFirst();
while (!ls.isEmpty() && !ls.isBehind()) {
PaintObject po = ls.getItem();
if (po instanceof PaintObjectImage) {
PaintObjectImage poi = (PaintObjectImage) po;
PaintObjectImage poi_new = controlPaint.getPicture()
.createPOI(poi.getSnapshot());
controlPaint.getPicture().insertIntoSelected(
poi_new, controlPaint.getView().getTabs()
.getTab_debug());
//finish insertion into selected.
controlPaint.getPicture().finishSelection(
controlPaint.getcTabSelection());
} else if (po instanceof PaintObjectWriting) {
PaintObjectWriting pow = (PaintObjectWriting) po;
PaintObjectWriting pow_new
= controlPaint.getPicture().createPOW(pow.getPen());
pow.getPoints().toFirst();
while (!pow.getPoints().isEmpty()
&& !pow.getPoints().isBehind()) {
pow_new.addPoint(new DPoint(
pow.getPoints().getItem()));
pow.getPoints().next();
}
controlPaint.getPicture().insertIntoSelected(pow_new,
controlPaint.getView().getTabs().getTab_debug());
//finish insertion into selected.
controlPaint.getPicture().finishSelection(
controlPaint.getcTabSelection());
} else if (po != null) {
Status.getLogger().warning("unknown kind of "
+ "PaintObject; element = " + po);
}
ls.next();
}
} else if (o instanceof PaintObjectWriting) {
controlPaint.getPicture().insertIntoSelected(
(PaintObjectWriting) o,
controlPaint.getView().getTabs().getTab_debug());
//finish insertion into selected.
controlPaint.getPicture().finishSelection(
controlPaint.getcTabSelection());
} else if (o instanceof PaintObjectImage) {
controlPaint.getPicture().insertIntoSelected(
(PaintObjectImage) o,
controlPaint.getView().getTabs().getTab_debug());
//finish insertion into selected.
controlPaint.getPicture().finishSelection(
controlPaint.getcTabSelection());
new Exception("hier").printStackTrace();
} else {
System.out.println(o);
Status.getLogger().warning("unknown return type of clipboard");
}
controlPaint.getPicture().paintSelected(getPage(),
controlPaint.getControlPic(),
controlPaint.getControlPaintSelection());
getPage().getJlbl_background2().repaint();
getControlPicture().refreshPaint();
}
/**
* MouseReleased method for button press at button copy.
*/
public void mr_copy() {
MyClipboard.getInstance().copyPaintObjects(
controlPaint.getPicture(),
controlPaint.getPicture().getLs_poSelected(),
controlPaint.getPicture().paintSelectedBI(controlPaint
.getControlPaintSelection().getR_selection()));
}
/*
*
*
* exit
*
*
*/
/*
*
*
* File operations
*
*
*/
/**
* the save action.
*/
public void mr_save() {
final String fileEnding;
// if not saved yet. Otherwise use the saved save path.
if (Status.getSavePath() == null) {
// choose a file
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(new java.io.File("."));
jfc.setDialogTitle("Select save location");
int retval = jfc.showOpenDialog(getView());
// if selected a file.
if (retval == JFileChooser.APPROVE_OPTION) {
// fetch the selected file.
File file = jfc.getSelectedFile();
// edit file ending
if (!file.getName().toLowerCase().contains(".")) {
fileEnding = Status.getSaveFormat();
file = new File(file.getAbsolutePath() + ".pic");
} else if (!Constants.endsWithSaveFormat(file.getName())) {
fileEnding = "";
String formatList = "(";
for (String format : Constants.SAVE_FORMATS) {
formatList += format + ", ";
}
formatList = formatList.subSequence(0,
formatList.length() - 2) + ")";
JOptionPane.showMessageDialog(getView(),
"Error saving file:\nFile extension \""
+ Constants.getFileExtension(file.getName())
+ "\" not supported! Supported formats:\n\t"
+ formatList + ".", "Error",
JOptionPane.ERROR_MESSAGE);
mr_save();
return;
} else {
fileEnding = "."
+ Constants.getFileExtension(file.getName());
}
// if file already exists
if (file.exists()) {
int result = JOptionPane.showConfirmDialog(
getView(), "File already exists. "
+ "Owerwrite?", "Owerwrite file?",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == 1) {
// no
mr_save();
return;
} else if (result == 2) {
// interrupt
return;
}
// overwrite
}
Status.setSavePath(file.getAbsolutePath());
} else {
fileEnding = "";
}
} else {
fileEnding = "";
}
// generate path without the file ending.
if (Status.getSavePath() != null) {
int d = Status.getSavePath().toCharArray().length - 2 - 1;
String firstPath = Status.getSavePath().substring(0, d);
// save images in both formats.
// controlPaint.getPicture().saveIMAGE(
// firstPath, getPage().getJlbl_painting().getLocation().x,
// getPage().getJlbl_painting().getLocation().y);
controlPaint.getPicture().saveIMAGE(firstPath, 0, 0, fileEnding);
controlPaint.getPicture().savePicture(firstPath + "pic");
Status.setUncommittedChanges(false);
}
}
/**
* MouseReleased method for button press at button load.
*/
public void mr_load() {
int i = JOptionPane.showConfirmDialog(getView(),
"Do you want to save the committed changes? ",
"Save changes", JOptionPane.YES_NO_CANCEL_OPTION);
// no
if (i == 1) {
JFileChooser jfc = new JFileChooser();
jfc.setCurrentDirectory(new java.io.File("."));
jfc.setDialogTitle("Select load location");
int retval = jfc.showOpenDialog(getView());
if (retval == JFileChooser.APPROVE_OPTION) {
File file = jfc.getSelectedFile();
if (file.getName().toLowerCase().endsWith(".pic")) {
controlPaint.getPicture().loadPicture(
file.getAbsolutePath());
Status.setUncommittedChanges(false);
getControlPicture().refreshPaint();
} else if (file.getName().toLowerCase().endsWith(".png")
|| file.getName().toLowerCase().endsWith(".jpg")) {
try {
BufferedImage bi_imageBG = ImageIO.read(file);
Status.setImageSize(new Dimension(
bi_imageBG.getWidth(),
bi_imageBG.getHeight()));
Status.setImageShowSize(Status.getImageSize());
controlPaint.getPicture().emptyImage();
controlPaint.getPicture().addPaintObjectImage(
bi_imageBG);
getControlPicture().refreshPaint();
} catch (IOException e) {
e.printStackTrace();
new Error("not supported yet to load pictures "
+ "because there are no paintObjects for "
+ "pictures"
+ "but only those for lines.")
.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(getView(),
"Select a .png file.", "Error",
JOptionPane.ERROR_MESSAGE);
mr_save();
Status.setUncommittedChanges(false);
}
}
} else if (i == 0) {
// yes
mr_save();
}
}
/**
* the action which is performed if new image is released.
*/
public void mr_new() {
if (Status.isUncommittedChanges()) {
int i = JOptionPane.showConfirmDialog(getView(),
"Do you want to save the committed changes? ",
"Save changes", JOptionPane.YES_NO_CANCEL_OPTION);
if (i == 0) {
mr_save();
mr_new();
}
//if the user does not want to interrupt recall actionNew
if (i == 1) {
controlPaint.getView().getPage().getJpnl_new().setVisible(true);
controlPaint.getPicture().reload();
Status.setUncommittedChanges(false);
}
} else {
controlPaint.getView().getPage().getJpnl_new().setVisible(true);
controlPaint.getPicture().reload();
Status.setUncommittedChanges(false);
}
}
/*
*
*
* Zoom
*
*
*/
/**
* MouseReleased method for button press at button zoom out.
*/
public void mr_zoomOut() {
//TODO: adjust this one.
//if able to zoom out
if (Status.getImageSize().width
/ Status.getImageShowSize().width
< Math.pow(ViewSettings.ZOOM_MULITPLICATOR,
ViewSettings.MAX_ZOOM_OUT)) {
int
newWidth = Status.getImageShowSize().width
/ ViewSettings.ZOOM_MULITPLICATOR,
newHeight = Status
.getImageShowSize().height
/ ViewSettings.ZOOM_MULITPLICATOR;
Point oldLocation = new Point(
getPage().getJlbl_painting().getLocation().x
- getPage().getJlbl_painting().getWidth() / 2
+ getPage().getJlbl_painting().getWidth()
* ViewSettings.ZOOM_MULITPLICATOR / 2,
getPage().getJlbl_painting().getLocation().y
- getPage().getJlbl_painting().getHeight() / 2
+ getPage().getJlbl_painting().getHeight()
* ViewSettings.ZOOM_MULITPLICATOR / 2);
// not smaller than the
oldLocation.x = Math.max(oldLocation.x,
-(Status.getImageShowSize().width - getPage().getWidth()));
oldLocation.y = Math.max(oldLocation.y,
-(Status.getImageShowSize().height
- getPage().getHeight()));
// not greater than 0
oldLocation.x = Math.min(oldLocation.x, 0);
oldLocation.y = Math.min(oldLocation.y, 0);
//set new image size and adapt the page by flipping
//TODO: previously used getpage.getjlbl-p.setLoc(),
//why?
//transformed into setLocation. works too by now.
Status.setImageShowSize(new Dimension(newWidth, newHeight));
getPage().flip();
getPage().getJlbl_painting()
.setBounds(
(oldLocation.x) / ViewSettings.ZOOM_MULITPLICATOR ,
(oldLocation.y) / ViewSettings.ZOOM_MULITPLICATOR,
getPage().getJlbl_painting().getWidth(),
getPage().getJlbl_painting().getHeight());
getPage().refrehsSps();
if (controlPaint.getPicture().isSelected()) {
getControlPicture().releaseSelected();
controlPaint.getPicture().releaseSelected(
controlPaint.getControlPaintSelection(),
controlPaint.getcTabSelection(),
controlPaint.getView().getTabs().getTab_debug(),
controlPaint.getView().getPage().getJlbl_painting()
.getLocation().x,
controlPaint.getView().getPage().getJlbl_painting()
.getLocation().y);
}
updateResizeLocation();
} else {
Message.showMessage(Message.MESSAGE_ID_INFO,
"max zoom out reached");
updateResizeLocation();
}
// TODO: hier die location aktualisieren.
}
/**
* Update the location of the JButtons for resizing. Thus the user is
* able to resize the whole image.
*/
public void updateResizeLocation() {
//the width and the height
int w = Status.getImageShowSize().width;
int h = Status.getImageShowSize().height;
//set location
getPage().getJbtn_resize()[2][1].setLocation(w, h / 2);
getPage().getJbtn_resize()[2][2].setLocation(w, h);
getPage().getJbtn_resize()[1][2].setLocation(w / 2, h);
//set visible
getPage().getJbtn_resize()[1][2].setVisible(true);
getPage().getJbtn_resize()[2][2].setVisible(true);
getPage().getJbtn_resize()[2][1].setVisible(true);
}
/**
* {@inheritDoc}
*/
public void mouseEntered(final MouseEvent _event) {
/**
* Instance of paint fetched out of instance of the main controller
* class.
* The getter method handles the printing of an error message if the
* instance of Paint is null.
*/
final Paint paint = getTabPaint();
//if the initialization process has terminated without errors
//the instance of Paint is not equal to null, thus it is possible to
//check the source of the ActionEvent.
if (paint != null) {
//if mouse is over a pen
if (isAStiftAuswahl(_event.getSource())) {
//if is not selected
Item1PenSelection selected = (Item1PenSelection)
((VButtonWrapper) _event.getSource()).wrapObject();
if (!selected.isSelected()) {
applyFocus(selected);
}
return;
} else {
//for loop for identifying the cause of the event
for (int j = 0; j < paint.getJbtn_colors().length;
j++) {
if (_event.getSource().equals(
paint.getJbtn_colors()[j])) {
//highlight the border of the icon with mouse-over
paint.getJbtn_colors()[j].setBorder(
BorderFactory.createCompoundBorder(
new LineBorder(Color.black),
new LineBorder(Color.black)));
//return because only one item is performing action
//at one time
return;
}
}
}
}
}
/**
* {@inheritDoc}
*/
public void mouseExited(final MouseEvent _event) {
/**
* Instance of paint fetched out of instance of the main controller
* class.
* The getter method handles the printing of an error message if the
* instance of Paint is null.
*/
final Paint paint = getTabPaint();
//if the initialization process has terminated without errors
//the instance of Paint is not equal to null, thus it is possible to
//check the source of the ActionEvent.
if (paint != null) {
//outfit of StiftAuswahl
if (isAStiftAuswahl(_event.getSource())) {
//reset the instance of Pen if this pen is not selected
Item1PenSelection selected = (Item1PenSelection)
((VButtonWrapper) _event.getSource()).wrapObject();
if (!selected.isSelected()) {
selected.setOpaque(false);
}
return;
}
//for loop for identifying the cause of the event
for (int j = 0; j < paint.getJbtn_colors().length; j++) {
if (_event.getSource().equals(
paint.getJbtn_colors()[j])) {
//reset the border of the icon which had mouse-over
paint.getJbtn_colors()[j].setBorder(BorderFactory
.createCompoundBorder(new LineBorder(Color.black),
new LineBorder(Color.white)));
//return because only one item is performing action at one
//time
return;
}
}
}
}
/**
* apply focus to selected item.
* @param _selected the selected item
*/
public static void applyFocus(final Item1PenSelection _selected) {
_selected.setOpaque(true);
_selected.setBackground(ViewSettings.GENERAL_CLR_BORDER);
}
/**
* {@inheritDoc}
*/
public void mousePressed(final MouseEvent _event) { }
/**
* {@inheritDoc}
*/
public void mouseReleased(final MouseEvent _event) { }
/**
* {@inheritDoc}
*/
public void mouseClicked(final MouseEvent _event) {
//if mouse is over a pen
if (isAStiftAuswahl(_event.getSource())) {
Item1PenSelection stift_event = (Item1PenSelection)
((VButtonWrapper) _event.getSource()).wrapObject();
//if pen is not selected yet
if (lastSelected[stift_event.getPenSelection() - 1] != null
&& lastSelected[stift_event.getPenSelection() - 1]
!= stift_event) {
lastSelected[stift_event.getPenSelection() - 1]
.setSelected(false);
lastSelected[stift_event.getPenSelection() - 1]
.setOpaque(false);
lastSelected[stift_event.getPenSelection() - 1]
.setBackground(Color.green);
}
//select the current pen
stift_event.setSelected(true);
stift_event.setOpaque(true);
stift_event.setBackground(ViewSettings.GENERAL_CLR_BORDER);
//set the last selected
lastSelected[stift_event.getPenSelection() - 1] = stift_event;
}
}
/**
* Checks whether an Object is a StiftAuswahl wrapper button or not.
*
* @param _obj the object
* @return the boolean
*/
public static boolean isAStiftAuswahl(final Object _obj) {
try {
((Item1PenSelection) ((VButtonWrapper) _obj).wrapObject())
.toString();
return true;
} catch (Exception e) {
return false;
}
}
/**
* @return the controlPaint
*/
public ControlPaint getControlPaint() {
return controlPaint;
}
/**
* @param _controlPaint to set.
*/
public void setControlPaint(final ControlPaint _controlPaint) {
this.controlPaint = _controlPaint;
}
}
| closes #63
| PaintNotes/src/main/java/control/tabs/CTabPainting.java | closes #63 |
|
Java | apache-2.0 | e668a460fb9b64e4392755e888a22a4d3be85688 | 0 | ZUGFeRD/mustangproject,ZUGFeRD/mustangproject,ZUGFeRD/mustangproject | /** **********************************************************************
*
* Copyright 2018 Jochen Staerk
*
* Use is subject to license terms.
*
* 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.mustangproject.ZUGFeRD;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import javax.xml.bind.JAXBElement;
import org.mustangproject.ZUGFeRD.model.*;
class ZUGFeRDTransactionModelConverter {
private static final SimpleDateFormat zugferdDateFormat = new SimpleDateFormat("yyyyMMdd");
private static final ObjectFactory xmlFactory = new ObjectFactory();
private final IZUGFeRDExportableTransaction trans;
private final Totals totals;
private boolean isTest;
private String currency = "EUR";
private String profile;
ZUGFeRDTransactionModelConverter(IZUGFeRDExportableTransaction trans) {
this.trans = trans;
totals = new Totals();
currency = trans.getCurrency() != null ? trans.getCurrency() : currency;
}
JAXBElement<CrossIndustryDocumentType> convertToModel() {
CrossIndustryDocumentType invoice = xmlFactory
.createCrossIndustryDocumentType();
invoice.setSpecifiedExchangedDocumentContext(getDocumentContext());
invoice.setHeaderExchangedDocument(getDocument());
invoice.setSpecifiedSupplyChainTradeTransaction(getTradeTransaction());
return xmlFactory
.createCrossIndustryDocument(invoice);
}
private ExchangedDocumentContextType getDocumentContext() {
ExchangedDocumentContextType context = xmlFactory
.createExchangedDocumentContextType();
DocumentContextParameterType contextParameter = xmlFactory
.createDocumentContextParameterType();
IDType idType = xmlFactory.createIDType();
idType.setValue(profile);
contextParameter.setID(idType);
context.getGuidelineSpecifiedDocumentContextParameter().add(
contextParameter);
IndicatorType testIndicator = xmlFactory.createIndicatorType();
testIndicator.setIndicator(isTest);
context.setTestIndicator(testIndicator);
return context;
}
private ExchangedDocumentType getDocument() {
ExchangedDocumentType document = xmlFactory
.createExchangedDocumentType();
IDType id = xmlFactory.createIDType();
id.setValue(trans.getNumber());
document.setID(id);
DateTimeType issueDateTime = xmlFactory.createDateTimeType();
DateTimeType.DateTimeString issueDateTimeString = xmlFactory
.createDateTimeTypeDateTimeString();
issueDateTimeString.setFormat(DateTimeTypeConstants.DATE);
issueDateTimeString.setValue(zugferdDateFormat.format(trans
.getIssueDate()));
issueDateTime.setDateTimeString(issueDateTimeString);
document.setIssueDateTime(issueDateTime);
DocumentCodeType documentCodeType = xmlFactory.createDocumentCodeType();
documentCodeType.setValue(trans.getDocumentCode());
document.setTypeCode(documentCodeType);
TextType name = xmlFactory.createTextType();
name.setValue(trans.getDocumentName());
document.getName().add(name);
if (trans.getOwnOrganisationFullPlaintextInfo() != null) {
NoteType regularInfo = xmlFactory.createNoteType();
CodeType regularInfoSubjectCode = xmlFactory.createCodeType();
regularInfoSubjectCode.setValue(NoteTypeConstants.REGULARINFO);
regularInfo.setSubjectCode(regularInfoSubjectCode);
TextType regularInfoContent = xmlFactory.createTextType();
regularInfoContent.setValue(trans
.getOwnOrganisationFullPlaintextInfo());
regularInfo.getContent().add(regularInfoContent);
document.getIncludedNote().add(regularInfo);
}
if (trans.getReferenceNumber() != null && !"".equals(trans.getReferenceNumber())) {
NoteType referenceInfo = xmlFactory.createNoteType();
TextType referenceInfoContent = xmlFactory.createTextType();
referenceInfoContent.setValue(trans.getReferenceNumber());
referenceInfo.getContent().add(referenceInfoContent);
document.getIncludedNote().add(referenceInfo);
}
return document;
}
private SupplyChainTradeTransactionType getTradeTransaction() {
SupplyChainTradeTransactionType transaction = xmlFactory
.createSupplyChainTradeTransactionType();
transaction.getApplicableSupplyChainTradeAgreement().add(
getTradeAgreement());
transaction.setApplicableSupplyChainTradeDelivery(getTradeDelivery());
transaction.setApplicableSupplyChainTradeSettlement(getTradeSettlement());
transaction.getIncludedSupplyChainTradeLineItem().addAll(
getLineItems());
return transaction;
}
private SupplyChainTradeAgreementType getTradeAgreement() {
SupplyChainTradeAgreementType tradeAgreement = xmlFactory
.createSupplyChainTradeAgreementType();
tradeAgreement.setBuyerTradeParty(getBuyer());
tradeAgreement.setSellerTradeParty(getSeller());
if (trans.getBuyerOrderReferencedDocumentID() != null) {
ReferencedDocumentType refdoc = xmlFactory.createReferencedDocumentType();
IDType id = xmlFactory.createIDType();
id.setValue(trans.getBuyerOrderReferencedDocumentID());
refdoc.getID().add(id);
refdoc.setIssueDateTime(trans.getBuyerOrderReferencedDocumentIssueDateTime());
tradeAgreement.getBuyerOrderReferencedDocument().add(refdoc);
}
return tradeAgreement;
}
private TradePartyType getBuyer() {
TradePartyType buyerTradeParty = xmlFactory.createTradePartyType();
if (trans.getRecipient().getID() != null) {
IDType buyerID = xmlFactory.createIDType();
buyerID.setValue(trans.getRecipient().getID());
buyerTradeParty.getID().add(buyerID);
}
if (trans.getRecipient().getGlobalID() != null) {
IDType globalID = xmlFactory.createIDType();
globalID.setValue(trans.getRecipient().getGlobalID());
globalID.setSchemeID(trans.getRecipient().getGlobalIDScheme());
buyerTradeParty.getGlobalID().add(globalID);
}
TextType buyerName = xmlFactory.createTextType();
buyerName.setValue(trans.getRecipient().getName());
buyerTradeParty.setName(buyerName);
TradeAddressType buyerAddressType = xmlFactory.createTradeAddressType();
TextType buyerCityName = xmlFactory.createTextType();
buyerCityName.setValue(trans.getRecipient().getLocation());
buyerAddressType.setCityName(buyerCityName);
CountryIDType buyerCountryId = xmlFactory.createCountryIDType();
buyerCountryId.setValue(trans.getRecipient().getCountry());
buyerAddressType.setCountryID(buyerCountryId);
TextType buyerAddress = xmlFactory.createTextType();
buyerAddress.setValue(trans.getRecipient().getStreet());
buyerAddressType.setLineOne(buyerAddress);
CodeType buyerPostcode = xmlFactory.createCodeType();
buyerPostcode.setValue(trans.getRecipient().getZIP());
buyerAddressType.getPostcodeCode().add(buyerPostcode);
buyerTradeParty.setPostalTradeAddress(buyerAddressType);
// Ust-ID
TaxRegistrationType buyerTaxRegistration = xmlFactory
.createTaxRegistrationType();
IDType buyerUstId = xmlFactory.createIDType();
buyerUstId.setValue(trans.getRecipient().getVATID());
buyerUstId.setSchemeID(TaxRegistrationTypeConstants.USTID);
buyerTaxRegistration.setID(buyerUstId);
buyerTradeParty.getSpecifiedTaxRegistration().add(buyerTaxRegistration);
return buyerTradeParty;
}
private TradePartyType getSeller() {
TradePartyType sellerTradeParty = xmlFactory.createTradePartyType();
if (trans.getOwnForeignOrganisationID() != null) {
IDType sellerID = xmlFactory.createIDType();
sellerID.setValue(trans.getOwnForeignOrganisationID());
sellerTradeParty.getID().add(sellerID);
}
TextType sellerName = xmlFactory.createTextType();
sellerName.setValue(trans.getOwnOrganisationName());
sellerTradeParty.setName(sellerName);
TradeAddressType sellerAddressType = xmlFactory
.createTradeAddressType();
TextType sellerCityName = xmlFactory.createTextType();
sellerCityName.setValue(trans.getOwnLocation());
sellerAddressType.setCityName(sellerCityName);
CountryIDType sellerCountryId = xmlFactory.createCountryIDType();
sellerCountryId.setValue(trans.getOwnCountry());
sellerAddressType.setCountryID(sellerCountryId);
TextType sellerAddress = xmlFactory.createTextType();
sellerAddress.setValue(trans.getOwnStreet());
sellerAddressType.setLineOne(sellerAddress);
CodeType sellerPostcode = xmlFactory.createCodeType();
sellerPostcode.setValue(trans.getOwnZIP());
sellerAddressType.getPostcodeCode().add(sellerPostcode);
sellerTradeParty.setPostalTradeAddress(sellerAddressType);
// Steuernummer
TaxRegistrationType sellerTaxRegistration = xmlFactory
.createTaxRegistrationType();
IDType sellerTaxId = xmlFactory.createIDType();
sellerTaxId.setValue(trans.getOwnTaxID());
sellerTaxId.setSchemeID(TaxRegistrationTypeConstants.TAXID);
sellerTaxRegistration.setID(sellerTaxId);
sellerTradeParty.getSpecifiedTaxRegistration().add(
sellerTaxRegistration);
// Ust-ID
sellerTaxRegistration = xmlFactory.createTaxRegistrationType();
IDType sellerUstId = xmlFactory.createIDType();
sellerUstId.setValue(trans.getOwnVATID());
sellerUstId.setSchemeID(TaxRegistrationTypeConstants.USTID);
sellerTaxRegistration.setID(sellerUstId);
sellerTradeParty.getSpecifiedTaxRegistration().add(
sellerTaxRegistration);
return sellerTradeParty;
}
private SupplyChainTradeDeliveryType getTradeDelivery() {
SupplyChainTradeDeliveryType tradeDelivery = xmlFactory
.createSupplyChainTradeDeliveryType();
SupplyChainEventType deliveryEvent = xmlFactory
.createSupplyChainEventType();
DateTimeType deliveryDate = xmlFactory.createDateTimeType();
DateTimeType.DateTimeString deliveryDateString = xmlFactory
.createDateTimeTypeDateTimeString();
deliveryDateString.setFormat(DateTimeTypeConstants.DATE);
deliveryDateString.setValue(zugferdDateFormat.format(trans
.getDeliveryDate()));
deliveryDate.setDateTimeString(deliveryDateString);
deliveryEvent.getOccurrenceDateTime().add(deliveryDate);
tradeDelivery.getActualDeliverySupplyChainEvent().add(deliveryEvent);
return tradeDelivery;
}
private SupplyChainTradeSettlementType getTradeSettlement() {
SupplyChainTradeSettlementType tradeSettlement = xmlFactory
.createSupplyChainTradeSettlementType();
TextType paymentReference = xmlFactory.createTextType();
paymentReference.setValue(trans.getNumber());
tradeSettlement.getPaymentReference().add(paymentReference);
CodeType currencyCode = xmlFactory.createCodeType();
currencyCode.setValue(currency);
tradeSettlement.setInvoiceCurrencyCode(currencyCode);
tradeSettlement.getSpecifiedTradeSettlementPaymentMeans().addAll(
getPaymentData());
tradeSettlement.getApplicableTradeTax().addAll(getTradeTax());
tradeSettlement.getSpecifiedTradePaymentTerms().addAll(
getPaymentTerms());
if (trans.getZFAllowances() != null) {
tradeSettlement.getSpecifiedTradeAllowanceCharge().addAll(
getHeaderAllowances());
}
if (trans.getZFLogisticsServiceCharges() != null) {
tradeSettlement.getSpecifiedLogisticsServiceCharge().addAll(
getHeaderLogisticsServiceCharges());
}
if (trans.getZFCharges() != null) {
tradeSettlement.getSpecifiedTradeAllowanceCharge().addAll(
getHeaderCharges());
}
tradeSettlement.setSpecifiedTradeSettlementMonetarySummation(getMonetarySummation());
return tradeSettlement;
}
private List<TradeSettlementPaymentMeansType> getPaymentData() {
List<TradeSettlementPaymentMeansType> result = new ArrayList<>();
for (IZUGFeRDTradeSettlementPayment settlementPayment : trans.getTradeSettlementPayment()) {
TradeSettlementPaymentMeansType paymentData = xmlFactory
.createTradeSettlementPaymentMeansType();
PaymentMeansCodeType paymentDataType = xmlFactory
.createPaymentMeansCodeType();
paymentDataType.setValue(PaymentMeansCodeTypeConstants.BANKACCOUNT);
paymentData.setTypeCode(paymentDataType);
TextType paymentInfo = xmlFactory.createTextType();
String paymentInfoText = settlementPayment.getOwnPaymentInfoText();
if (paymentInfoText == null) {
paymentInfoText = "";
}
paymentInfo.setValue(paymentInfoText);
paymentData.getInformation().add(paymentInfo);
CreditorFinancialAccountType bankAccount = xmlFactory
.createCreditorFinancialAccountType();
IDType iban = xmlFactory.createIDType();
iban.setValue(settlementPayment.getOwnIBAN());
bankAccount.setIBANID(iban);
IDType kto = xmlFactory.createIDType();
kto.setValue(settlementPayment.getOwnKto());
bankAccount.setProprietaryID(kto);
paymentData.setPayeePartyCreditorFinancialAccount(bankAccount);
CreditorFinancialInstitutionType bankData = xmlFactory
.createCreditorFinancialInstitutionType();
IDType bicId = xmlFactory.createIDType();
bicId.setValue(settlementPayment.getOwnBIC());
bankData.setBICID(bicId);
TextType bankName = xmlFactory.createTextType();
bankName.setValue(settlementPayment.getOwnBankName());
bankData.setName(bankName);
IDType blz = xmlFactory.createIDType();
blz.setValue(settlementPayment.getOwnBLZ());
bankData.setGermanBankleitzahlID(blz);
paymentData.setPayeeSpecifiedCreditorFinancialInstitution(bankData);
result.add(paymentData);
}
return result;
}
private Collection<TradeTaxType> getTradeTax() {
List<TradeTaxType> tradeTaxTypes = new ArrayList<>();
HashMap<BigDecimal, VATAmount> VATPercentAmountMap = this.getVATPercentAmountMap();
for (BigDecimal currentTaxPercent : VATPercentAmountMap.keySet()) {
TradeTaxType tradeTax = xmlFactory.createTradeTaxType();
TaxTypeCodeType taxTypeCode = xmlFactory.createTaxTypeCodeType();
taxTypeCode.setValue(TaxTypeCodeTypeConstants.SALESTAX);
tradeTax.setTypeCode(taxTypeCode);
TaxCategoryCodeType taxCategoryCode = xmlFactory.createTaxCategoryCodeType();
VATAmount vatAmount = VATPercentAmountMap.get(currentTaxPercent);
taxCategoryCode.setValue(vatAmount.getCategoryCode());
tradeTax.setCategoryCode(taxCategoryCode);
VATAmount amount = VATPercentAmountMap.get(currentTaxPercent);
PercentType taxPercent = xmlFactory.createPercentType();
taxPercent.setValue(vatFormat(currentTaxPercent));
tradeTax.setApplicablePercent(taxPercent);
AmountType calculatedTaxAmount = xmlFactory.createAmountType();
calculatedTaxAmount.setCurrencyID(currency);
calculatedTaxAmount.setValue(currencyFormat(amount.getCalculated()));
tradeTax.getCalculatedAmount().add(calculatedTaxAmount);
AmountType basisTaxAmount = xmlFactory.createAmountType();
basisTaxAmount.setCurrencyID(currency);
basisTaxAmount.setValue(currencyFormat(amount.getBasis()));
tradeTax.getBasisAmount().add(basisTaxAmount);
tradeTaxTypes.add(tradeTax);
}
return tradeTaxTypes;
}
private Collection<TradeAllowanceChargeType> getHeaderAllowances() {
List<TradeAllowanceChargeType> headerAllowances = new ArrayList<>();
for (IZUGFeRDAllowanceCharge iAllowance : trans.getZFAllowances()) {
TradeAllowanceChargeType allowance = xmlFactory.createTradeAllowanceChargeType();
IndicatorType chargeIndicator = xmlFactory.createIndicatorType();
chargeIndicator.setIndicator(false);
allowance.setChargeIndicator(chargeIndicator);
AmountType actualAmount = xmlFactory.createAmountType();
actualAmount.setCurrencyID(currency);
actualAmount.setValue(currencyFormat(iAllowance.getTotalAmount()));
allowance.getActualAmount().add(actualAmount);
TextType reason = xmlFactory.createTextType();
reason.setValue(iAllowance.getReason());
allowance.setReason(reason);
TradeTaxType tradeTax = xmlFactory.createTradeTaxType();
PercentType vatPercent = xmlFactory.createPercentType();
vatPercent.setValue(currencyFormat(iAllowance.getTaxPercent()));
tradeTax.setApplicablePercent(vatPercent);
/*
* Only in extended AmountType basisAmount =
* xmlFactory.createAmountType();
* basisAmount.setCurrencyID(trans.getInvoiceCurrency());
* basisAmount.setValue(amount.getBasis());
* allowance.setBasisAmount(basisAmount);
*/
TaxCategoryCodeType taxType = xmlFactory.createTaxCategoryCodeType();
taxType.setValue(iAllowance.getCategoryCode());
tradeTax.setCategoryCode(taxType);
TaxTypeCodeType taxCode = xmlFactory.createTaxTypeCodeType();
taxCode.setValue(TaxTypeCodeTypeConstants.SALESTAX);
tradeTax.setTypeCode(taxCode);
allowance.getCategoryTradeTax().add(tradeTax);
headerAllowances.add(allowance);
}
return headerAllowances;
}
private Collection<TradeAllowanceChargeType> getHeaderCharges() {
List<TradeAllowanceChargeType> headerCharges = new ArrayList<>();
for (IZUGFeRDAllowanceCharge iCharge : trans.getZFCharges()) {
TradeAllowanceChargeType charge = xmlFactory.createTradeAllowanceChargeType();
IndicatorType chargeIndicator = xmlFactory.createIndicatorType();
chargeIndicator.setIndicator(true);
charge.setChargeIndicator(chargeIndicator);
AmountType actualAmount = xmlFactory.createAmountType();
actualAmount.setCurrencyID(currency);
actualAmount.setValue(currencyFormat(iCharge.getTotalAmount()));
charge.getActualAmount().add(actualAmount);
TextType reason = xmlFactory.createTextType();
reason.setValue(iCharge.getReason());
charge.setReason(reason);
TradeTaxType tradeTax = xmlFactory.createTradeTaxType();
PercentType vatPercent = xmlFactory.createPercentType();
vatPercent.setValue(currencyFormat(iCharge.getTaxPercent()));
tradeTax.setApplicablePercent(vatPercent);
/*
* Only in extended AmountType basisAmount =
* xmlFactory.createAmountType();
* basisAmount.setCurrencyID(trans.getInvoiceCurrency());
* basisAmount.setValue(amount.getBasis());
* allowance.setBasisAmount(basisAmount);
*/
TaxCategoryCodeType taxType = xmlFactory.createTaxCategoryCodeType();
taxType.setValue(iCharge.getCategoryCode());
tradeTax.setCategoryCode(taxType);
TaxTypeCodeType taxCode = xmlFactory.createTaxTypeCodeType();
taxCode.setValue(TaxTypeCodeTypeConstants.SALESTAX);
tradeTax.setTypeCode(taxCode);
charge.getCategoryTradeTax().add(tradeTax);
headerCharges.add(charge);
}
return headerCharges;
}
private Collection<LogisticsServiceChargeType> getHeaderLogisticsServiceCharges() {
List<LogisticsServiceChargeType> headerServiceCharge = new ArrayList<>();
for (IZUGFeRDAllowanceCharge iServiceCharge : trans.getZFLogisticsServiceCharges()) {
LogisticsServiceChargeType serviceCharge = xmlFactory.createLogisticsServiceChargeType();
AmountType actualAmount = xmlFactory.createAmountType();
actualAmount.setCurrencyID(currency);
actualAmount.setValue(currencyFormat(iServiceCharge.getTotalAmount()));
serviceCharge.getAppliedAmount().add(actualAmount);
TextType reason = xmlFactory.createTextType();
reason.setValue(iServiceCharge.getReason());
serviceCharge.getDescription().add(reason);
TradeTaxType tradeTax = xmlFactory.createTradeTaxType();
PercentType vatPercent = xmlFactory.createPercentType();
vatPercent.setValue(currencyFormat(iServiceCharge.getTaxPercent()));
tradeTax.setApplicablePercent(vatPercent);
/*
* Only in extended AmountType basisAmount =
* xmlFactory.createAmountType();
* basisAmount.setCurrencyID(trans.getInvoiceCurrency());
* basisAmount.setValue(amount.getBasis());
* allowance.setBasisAmount(basisAmount);
*/
TaxCategoryCodeType taxType = xmlFactory.createTaxCategoryCodeType();
taxType.setValue(iServiceCharge.getCategoryCode());
tradeTax.setCategoryCode(taxType);
TaxTypeCodeType taxCode = xmlFactory.createTaxTypeCodeType();
taxCode.setValue(TaxTypeCodeTypeConstants.SALESTAX);
tradeTax.setTypeCode(taxCode);
serviceCharge.getAppliedTradeTax().add(tradeTax);
headerServiceCharge.add(serviceCharge);
}
return headerServiceCharge;
}
private Collection<TradePaymentTermsType> getPaymentTerms() {
List<TradePaymentTermsType> paymentTerms = new ArrayList<>();
TradePaymentTermsType paymentTerm = xmlFactory
.createTradePaymentTermsType();
DateTimeType dueDate = xmlFactory.createDateTimeType();
DateTimeType.DateTimeString dueDateString = xmlFactory
.createDateTimeTypeDateTimeString();
dueDateString.setFormat(DateTimeTypeConstants.DATE);
dueDateString.setValue(zugferdDateFormat.format(trans.getDueDate()));
dueDate.setDateTimeString(dueDateString);
paymentTerm.setDueDateDateTime(dueDate);
TextType paymentTermDescr = xmlFactory.createTextType();
String paymentTermDescription = trans.getPaymentTermDescription();
if (paymentTermDescription == null) {
paymentTermDescription = "";
}
paymentTermDescr.setValue(paymentTermDescription);
paymentTerm.getDescription().add(paymentTermDescr);
paymentTerms.add(paymentTerm);
return paymentTerms;
}
private TradeSettlementMonetarySummationType getMonetarySummation() {
TradeSettlementMonetarySummationType monetarySummation = xmlFactory
.createTradeSettlementMonetarySummationType();
// AllowanceTotalAmount = sum of all allowances
AmountType allowanceTotalAmount = xmlFactory.createAmountType();
allowanceTotalAmount.setCurrencyID(currency);
if (trans.getZFAllowances() != null) {
BigDecimal totalHeaderAllowance = BigDecimal.ZERO;
for (IZUGFeRDAllowanceCharge headerAllowance : trans
.getZFAllowances()) {
totalHeaderAllowance = headerAllowance.getTotalAmount().add(
totalHeaderAllowance);
}
allowanceTotalAmount.setValue(currencyFormat(totalHeaderAllowance));
} else {
allowanceTotalAmount.setValue(currencyFormat(BigDecimal.ZERO));
}
monetarySummation.getAllowanceTotalAmount().add(allowanceTotalAmount);
// ChargeTotalAmount = sum of all Logistic service charges + normal
// charges
BigDecimal totalCharge = BigDecimal.ZERO;
AmountType totalChargeAmount = xmlFactory.createAmountType();
totalChargeAmount.setCurrencyID(currency);
if (trans.getZFLogisticsServiceCharges() != null) {
for (IZUGFeRDAllowanceCharge logisticsServiceCharge : trans
.getZFLogisticsServiceCharges()) {
totalCharge = logisticsServiceCharge.getTotalAmount().add(
totalCharge);
}
}
if (trans.getZFCharges() != null) {
for (IZUGFeRDAllowanceCharge charge : trans.getZFCharges()) {
totalCharge = charge.getTotalAmount().add(totalCharge);
}
}
totalChargeAmount.setValue(currencyFormat(totalCharge));
monetarySummation.getChargeTotalAmount().add(totalChargeAmount);
/*
* AmountType chargeTotalAmount = xmlFactory.createAmountType();
* chargeTotalAmount.setCurrencyID(trans.getInvoiceCurrency());
* chargeTotalAmount.setValue(currencyFormat(BigDecimal.ZERO));
* monetarySummation.getChargeTotalAmount().add(chargeTotalAmount);
*/
AmountType lineTotalAmount = xmlFactory.createAmountType();
lineTotalAmount.setCurrencyID(currency);
lineTotalAmount.setValue(currencyFormat(totals.getLineTotal()));
monetarySummation.getLineTotalAmount().add(lineTotalAmount);
AmountType taxBasisTotalAmount = xmlFactory.createAmountType();
taxBasisTotalAmount.setCurrencyID(currency);
taxBasisTotalAmount.setValue(currencyFormat(totals.getTotalNet()));
monetarySummation.getTaxBasisTotalAmount().add(taxBasisTotalAmount);
AmountType taxTotalAmount = xmlFactory.createAmountType();
taxTotalAmount.setCurrencyID(currency);
taxTotalAmount.setValue(currencyFormat(totals.getTaxTotal()));
monetarySummation.getTaxTotalAmount().add(taxTotalAmount);
AmountType grandTotalAmount = xmlFactory.createAmountType();
grandTotalAmount.setCurrencyID(currency);
grandTotalAmount.setValue(currencyFormat(totals.getTotalGross()));
monetarySummation.getGrandTotalAmount().add(grandTotalAmount);
AmountType totalPrepaidAmount = xmlFactory.createAmountType();
totalPrepaidAmount.setCurrencyID(currency);
totalPrepaidAmount.setValue(currencyFormat(trans.getTotalPrepaidAmount()));
monetarySummation.getTotalPrepaidAmount().add(totalPrepaidAmount);
AmountType duePayableAmount = xmlFactory.createAmountType();
duePayableAmount.setCurrencyID(currency);
duePayableAmount.setValue(currencyFormat(totals.getTotalGross().subtract(trans.getTotalPrepaidAmount())));
monetarySummation.getDuePayableAmount().add(duePayableAmount);
return monetarySummation;
}
private Collection<SupplyChainTradeLineItemType> getLineItems() {
ArrayList<SupplyChainTradeLineItemType> lineItems = new ArrayList<>();
int lineID = 0;
for (IZUGFeRDExportableItem currentItem : trans.getZFItems()) {
lineID++;
LineCalc lc = new LineCalc(currentItem);
SupplyChainTradeLineItemType lineItem = xmlFactory
.createSupplyChainTradeLineItemType();
DocumentLineDocumentType lineDocument = xmlFactory
.createDocumentLineDocumentType();
IDType lineNumber = xmlFactory.createIDType();
lineNumber.setValue(Integer.toString(lineID));
lineDocument.setLineID(lineNumber);
lineItem.setAssociatedDocumentLineDocument(lineDocument);
SupplyChainTradeAgreementType tradeAgreement = xmlFactory
.createSupplyChainTradeAgreementType();
TradePriceType grossTradePrice = xmlFactory.createTradePriceType();
QuantityType grossQuantity = xmlFactory.createQuantityType();
grossQuantity.setUnitCode(currentItem.getProduct().getUnit());
grossQuantity.setValue(quantityFormat(BigDecimal.ONE));
grossTradePrice.setBasisQuantity(grossQuantity);
AmountType grossChargeAmount = xmlFactory.createAmountType();
grossChargeAmount.setCurrencyID(currency);
grossChargeAmount.setValue(priceFormat(currentItem.getPrice()));
grossTradePrice.getChargeAmount().add(grossChargeAmount);
tradeAgreement.getGrossPriceProductTradePrice()
.add(grossTradePrice);
if (currentItem.getItemAllowances() != null) {
for (IZUGFeRDAllowanceCharge itemAllowance : currentItem
.getItemAllowances()) {
TradeAllowanceChargeType eItemAllowance = xmlFactory
.createTradeAllowanceChargeType();
IndicatorType chargeIndicator = xmlFactory
.createIndicatorType();
chargeIndicator.setIndicator(false);
eItemAllowance.setChargeIndicator(chargeIndicator);
AmountType actualAmount = xmlFactory.createAmountType();
actualAmount.setCurrencyID(currency);
actualAmount.setValue(priceFormat(itemAllowance
.getTotalAmount().divide(currentItem.getQuantity(),
4, BigDecimal.ROUND_HALF_UP)));
eItemAllowance.getActualAmount().add(actualAmount);
TextType reason = xmlFactory.createTextType();
reason.setValue(itemAllowance.getReason());
eItemAllowance.setReason(reason);
grossTradePrice.getAppliedTradeAllowanceCharge().add(
eItemAllowance);
}
}
if (currentItem.getItemCharges() != null) {
for (IZUGFeRDAllowanceCharge itemCharge : currentItem
.getItemCharges()) {
TradeAllowanceChargeType eItemCharge = xmlFactory
.createTradeAllowanceChargeType();
AmountType actualAmount = xmlFactory.createAmountType();
actualAmount.setCurrencyID(currency);
actualAmount.setValue(priceFormat(itemCharge
.getTotalAmount().divide(currentItem.getQuantity(),
4, BigDecimal.ROUND_HALF_UP)));
eItemCharge.getActualAmount().add(actualAmount);
TextType reason = xmlFactory.createTextType();
reason.setValue(itemCharge.getReason());
eItemCharge.setReason(reason);
IndicatorType chargeIndicator = xmlFactory
.createIndicatorType();
chargeIndicator.setIndicator(true);
eItemCharge.setChargeIndicator(chargeIndicator);
grossTradePrice.getAppliedTradeAllowanceCharge().add(
eItemCharge);
}
}
TradePriceType netTradePrice = xmlFactory.createTradePriceType();
QuantityType netQuantity = xmlFactory.createQuantityType();
netQuantity.setUnitCode(currentItem.getProduct().getUnit());
netQuantity.setValue(quantityFormat(BigDecimal.ONE));
netTradePrice.setBasisQuantity(netQuantity);
AmountType netChargeAmount = xmlFactory.createAmountType();
netChargeAmount.setCurrencyID(currency);
netChargeAmount.setValue(priceFormat(lc.getItemNetAmount()));
netTradePrice.getChargeAmount().add(netChargeAmount);
tradeAgreement.getNetPriceProductTradePrice().add(netTradePrice);
lineItem.setSpecifiedSupplyChainTradeAgreement(tradeAgreement);
SupplyChainTradeDeliveryType tradeDelivery = xmlFactory
.createSupplyChainTradeDeliveryType();
QuantityType billedQuantity = xmlFactory.createQuantityType();
billedQuantity.setUnitCode(currentItem.getProduct().getUnit());
billedQuantity.setValue(quantityFormat(currentItem.getQuantity()));
tradeDelivery.setBilledQuantity(billedQuantity);
lineItem.setSpecifiedSupplyChainTradeDelivery(tradeDelivery);
SupplyChainTradeSettlementType tradeSettlement = xmlFactory
.createSupplyChainTradeSettlementType();
TradeTaxType tradeTax = xmlFactory.createTradeTaxType();
TaxCategoryCodeType taxCategoryCode = xmlFactory.createTaxCategoryCodeType();
taxCategoryCode.setValue(currentItem.getCategoryCode());
tradeTax.setCategoryCode(taxCategoryCode);
TaxTypeCodeType taxCode = xmlFactory.createTaxTypeCodeType();
taxCode.setValue(TaxTypeCodeTypeConstants.SALESTAX);
tradeTax.setTypeCode(taxCode);
PercentType taxPercent = xmlFactory.createPercentType();
taxPercent.setValue(vatFormat(currentItem.getProduct()
.getVATPercent()));
tradeTax.setApplicablePercent(taxPercent);
tradeSettlement.getApplicableTradeTax().add(tradeTax);
TradeSettlementMonetarySummationType monetarySummation = xmlFactory
.createTradeSettlementMonetarySummationType();
AmountType itemAmount = xmlFactory.createAmountType();
itemAmount.setCurrencyID(currency);
itemAmount.setValue(currencyFormat(lc.getItemTotalNetAmount()));
monetarySummation.getLineTotalAmount().add(itemAmount);
tradeSettlement
.setSpecifiedTradeSettlementMonetarySummation(monetarySummation);
lineItem.setSpecifiedSupplyChainTradeSettlement(tradeSettlement);
TradeProductType tradeProduct = xmlFactory.createTradeProductType();
TextType productName = xmlFactory.createTextType();
productName.setValue(currentItem.getProduct().getName());
tradeProduct.getName().add(productName);
TextType productDescription = xmlFactory.createTextType();
productDescription.setValue(currentItem.getProduct()
.getDescription());
tradeProduct.getDescription().add(productDescription);
lineItem.setSpecifiedTradeProduct(tradeProduct);
lineItems.add(lineItem);
}
return lineItems;
}
private BigDecimal vatFormat(BigDecimal value) {
return value.setScale(2, RoundingMode.HALF_UP);
}
private BigDecimal currencyFormat(BigDecimal value) {
return value.setScale(2, RoundingMode.HALF_UP);
}
private BigDecimal priceFormat(BigDecimal value) {
return value.setScale(4, RoundingMode.HALF_UP);
}
private BigDecimal quantityFormat(BigDecimal value) {
return value.setScale(4, RoundingMode.HALF_UP);
}
/**
* which taxes have been used with which amounts in this transaction, empty for no taxes, or e.g. 19=>190 and 7=>14 if 1000 Eur were applicable to 19% VAT
* (=>190 EUR VAT) and 200 EUR were applicable to 7% (=>14 EUR VAT) 190 Eur
*
* @return HashMap<BigDecimal, VATAmount> which taxes have been used with which amounts
*/
private HashMap<BigDecimal, VATAmount> getVATPercentAmountMap() {
return getVATPercentAmountMap(false);
}
private HashMap<BigDecimal, VATAmount> getVATPercentAmountMap(Boolean itemOnly) {
HashMap<BigDecimal, VATAmount> hm = new HashMap<>();
for (IZUGFeRDExportableItem currentItem : trans.getZFItems()) {
BigDecimal percent = currentItem.getProduct().getVATPercent();
LineCalc lc = new LineCalc(currentItem);
VATAmount itemVATAmount = new VATAmount(lc.getItemTotalNetAmount(), lc.getItemTotalVATAmount(), lc.getCategoryCode());
VATAmount current = hm.get(percent);
if (current == null) {
hm.put(percent, itemVATAmount);
} else {
hm.put(percent, current.add(itemVATAmount));
}
}
if (itemOnly) {
return hm;
}
if (trans.getZFAllowances() != null) {
for (IZUGFeRDAllowanceCharge headerAllowance : trans.getZFAllowances()) {
BigDecimal percent = headerAllowance.getTaxPercent();
VATAmount itemVATAmount = new VATAmount(
headerAllowance.getTotalAmount(), headerAllowance
.getTotalAmount().multiply(percent)
.divide(new BigDecimal(100)), trans.getDocumentCode());
VATAmount current = hm.get(percent);
if (current == null) {
hm.put(percent, itemVATAmount);
} else {
hm.put(percent, current.subtract(itemVATAmount));
}
}
}
if (trans.getZFLogisticsServiceCharges() != null) {
for (IZUGFeRDAllowanceCharge logisticsServiceCharge : trans
.getZFLogisticsServiceCharges()) {
BigDecimal percent = logisticsServiceCharge.getTaxPercent();
VATAmount itemVATAmount = new VATAmount(
logisticsServiceCharge.getTotalAmount(),
logisticsServiceCharge.getTotalAmount()
.multiply(percent).divide(new BigDecimal(100)), logisticsServiceCharge.getCategoryCode());
VATAmount current = hm.get(percent);
if (current == null) {
hm.put(percent, itemVATAmount);
} else {
hm.put(percent, current.add(itemVATAmount));
}
}
}
if (trans.getZFCharges() != null) {
for (IZUGFeRDAllowanceCharge charge : trans.getZFCharges()) {
BigDecimal percent = charge.getTaxPercent();
VATAmount itemVATAmount = new VATAmount(
charge.getTotalAmount(), charge.getTotalAmount()
.multiply(percent).divide(new BigDecimal(100)), charge.getCategoryCode());
VATAmount current = hm.get(percent);
if (current == null) {
hm.put(percent, itemVATAmount);
} else {
hm.put(percent, current.add(itemVATAmount));
}
}
}
return hm;
}
ZUGFeRDTransactionModelConverter withTest(boolean isTest) {
this.isTest = isTest;
return this;
}
public ZUGFeRDTransactionModelConverter withProfile(String profile) {
this.profile = profile;
return this;
}
private class LineCalc {
private BigDecimal totalGross;
private BigDecimal itemTotalNetAmount;
private BigDecimal itemTotalVATAmount;
private BigDecimal itemNetAmount;
private String categoryCode;
public LineCalc(IZUGFeRDExportableItem currentItem) {
BigDecimal totalAllowance = BigDecimal.ZERO;
BigDecimal totalCharge = BigDecimal.ZERO;
if (currentItem.getItemAllowances() != null) {
for (IZUGFeRDAllowanceCharge itemAllowance : currentItem
.getItemAllowances()) {
totalAllowance = itemAllowance.getTotalAmount().add(
totalAllowance);
}
}
if (currentItem.getItemCharges() != null) {
for (IZUGFeRDAllowanceCharge itemCharge : currentItem
.getItemCharges()) {
totalCharge = itemCharge.getTotalAmount().add(totalCharge);
}
}
BigDecimal multiplicator = currentItem.getProduct().getVATPercent()
.divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_UP)
.add(BigDecimal.ONE);
// priceGross=currentItem.getPrice().multiply(multiplicator);
totalGross = currentItem.getPrice()
.multiply(currentItem.getQuantity())
.subtract(totalAllowance).add(totalCharge)
.multiply(multiplicator);
itemTotalNetAmount = currentItem.getPrice()
.multiply(currentItem.getQuantity())
.subtract(totalAllowance).add(totalCharge)
.setScale(2, BigDecimal.ROUND_HALF_UP);
itemTotalVATAmount = totalGross.subtract(itemTotalNetAmount);
itemNetAmount = currentItem
.getPrice()
.multiply(currentItem.getQuantity())
.subtract(totalAllowance)
.add(totalCharge)
.divide(currentItem.getQuantity(), 4,
BigDecimal.ROUND_HALF_UP);
categoryCode = currentItem.getCategoryCode();
}
public BigDecimal getItemTotalNetAmount() {
return itemTotalNetAmount;
}
public BigDecimal getItemTotalVATAmount() {
return itemTotalVATAmount;
}
public BigDecimal getItemNetAmount() {
return itemNetAmount;
}
public String getCategoryCode() { return categoryCode; }
}
private class Totals {
private BigDecimal totalNetAmount;
private BigDecimal totalGrossAmount;
private BigDecimal lineTotalAmount;
private BigDecimal totalTaxAmount;
public Totals() {
BigDecimal res = BigDecimal.ZERO;
for (IZUGFeRDExportableItem currentItem : trans.getZFItems()) {
LineCalc lc = new LineCalc(currentItem);
res = res.add(lc.getItemTotalNetAmount());
}
// Set line total
lineTotalAmount = res;
if (trans.getZFAllowances() != null) {
for (IZUGFeRDAllowanceCharge headerAllowance : trans
.getZFAllowances()) {
res = res.subtract(headerAllowance.getTotalAmount());
}
}
if (trans.getZFLogisticsServiceCharges() != null) {
for (IZUGFeRDAllowanceCharge logisticsServiceCharge : trans
.getZFLogisticsServiceCharges()) {
res = res.add(logisticsServiceCharge.getTotalAmount());
}
}
if (trans.getZFCharges() != null) {
for (IZUGFeRDAllowanceCharge charge : trans.getZFCharges()) {
res = res.add(charge.getTotalAmount());
}
}
// Set total net amount
totalNetAmount = res;
HashMap<BigDecimal, VATAmount> vatAmountHashMap = getVATPercentAmountMap();
for (VATAmount amount : vatAmountHashMap.values()) {
res = res.add(amount.getCalculated());
}
// Set total gross amount
totalGrossAmount = res;
totalTaxAmount = totalGrossAmount
.subtract(totalNetAmount);
}
public BigDecimal getTotalNet() {
return totalNetAmount;
}
public BigDecimal getTotalGross() {
return totalGrossAmount;
}
public BigDecimal getLineTotal() {
return lineTotalAmount;
}
public BigDecimal getTaxTotal() {
return totalTaxAmount;
}
}
}
| src/main/java/org/mustangproject/ZUGFeRD/ZUGFeRDTransactionModelConverter.java | /** **********************************************************************
*
* Copyright 2018 Jochen Staerk
*
* Use is subject to license terms.
*
* 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.mustangproject.ZUGFeRD;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import javax.xml.bind.JAXBElement;
import org.mustangproject.ZUGFeRD.model.*;
class ZUGFeRDTransactionModelConverter {
private static final SimpleDateFormat zugferdDateFormat = new SimpleDateFormat("yyyyMMdd");
private static final ObjectFactory xmlFactory = new ObjectFactory();
private final IZUGFeRDExportableTransaction trans;
private final Totals totals;
private boolean isTest;
private String currency = "EUR";
private String profile;
ZUGFeRDTransactionModelConverter(IZUGFeRDExportableTransaction trans) {
this.trans = trans;
totals = new Totals();
currency = trans.getCurrency() != null ? trans.getCurrency() : currency;
}
JAXBElement<CrossIndustryDocumentType> convertToModel() {
CrossIndustryDocumentType invoice = xmlFactory
.createCrossIndustryDocumentType();
invoice.setSpecifiedExchangedDocumentContext(getDocumentContext());
invoice.setHeaderExchangedDocument(getDocument());
invoice.setSpecifiedSupplyChainTradeTransaction(getTradeTransaction());
return xmlFactory
.createCrossIndustryDocument(invoice);
}
private ExchangedDocumentContextType getDocumentContext() {
ExchangedDocumentContextType context = xmlFactory
.createExchangedDocumentContextType();
DocumentContextParameterType contextParameter = xmlFactory
.createDocumentContextParameterType();
IDType idType = xmlFactory.createIDType();
idType.setValue(profile);
contextParameter.setID(idType);
context.getGuidelineSpecifiedDocumentContextParameter().add(
contextParameter);
IndicatorType testIndicator = xmlFactory.createIndicatorType();
testIndicator.setIndicator(isTest);
context.setTestIndicator(testIndicator);
return context;
}
private ExchangedDocumentType getDocument() {
ExchangedDocumentType document = xmlFactory
.createExchangedDocumentType();
IDType id = xmlFactory.createIDType();
id.setValue(trans.getNumber());
document.setID(id);
DateTimeType issueDateTime = xmlFactory.createDateTimeType();
DateTimeType.DateTimeString issueDateTimeString = xmlFactory
.createDateTimeTypeDateTimeString();
issueDateTimeString.setFormat(DateTimeTypeConstants.DATE);
issueDateTimeString.setValue(zugferdDateFormat.format(trans
.getIssueDate()));
issueDateTime.setDateTimeString(issueDateTimeString);
document.setIssueDateTime(issueDateTime);
DocumentCodeType documentCodeType = xmlFactory.createDocumentCodeType();
documentCodeType.setValue(trans.getDocumentCode());
document.setTypeCode(documentCodeType);
TextType name = xmlFactory.createTextType();
name.setValue(trans.getDocumentName());
document.getName().add(name);
if (trans.getOwnOrganisationFullPlaintextInfo() != null) {
NoteType regularInfo = xmlFactory.createNoteType();
CodeType regularInfoSubjectCode = xmlFactory.createCodeType();
regularInfoSubjectCode.setValue(NoteTypeConstants.REGULARINFO);
regularInfo.setSubjectCode(regularInfoSubjectCode);
TextType regularInfoContent = xmlFactory.createTextType();
regularInfoContent.setValue(trans
.getOwnOrganisationFullPlaintextInfo());
regularInfo.getContent().add(regularInfoContent);
document.getIncludedNote().add(regularInfo);
}
if (trans.getReferenceNumber() != null && !"".equals(trans.getReferenceNumber())) {
NoteType referenceInfo = xmlFactory.createNoteType();
TextType referenceInfoContent = xmlFactory.createTextType();
referenceInfoContent.setValue(trans.getReferenceNumber());
referenceInfo.getContent().add(referenceInfoContent);
document.getIncludedNote().add(referenceInfo);
}
return document;
}
private SupplyChainTradeTransactionType getTradeTransaction() {
SupplyChainTradeTransactionType transaction = xmlFactory
.createSupplyChainTradeTransactionType();
transaction.getApplicableSupplyChainTradeAgreement().add(
getTradeAgreement());
transaction.setApplicableSupplyChainTradeDelivery(getTradeDelivery());
transaction.setApplicableSupplyChainTradeSettlement(getTradeSettlement());
transaction.getIncludedSupplyChainTradeLineItem().addAll(
getLineItems());
return transaction;
}
private SupplyChainTradeAgreementType getTradeAgreement() {
SupplyChainTradeAgreementType tradeAgreement = xmlFactory
.createSupplyChainTradeAgreementType();
tradeAgreement.setBuyerTradeParty(getBuyer());
tradeAgreement.setSellerTradeParty(getSeller());
if (trans.getBuyerOrderReferencedDocumentID() != null) {
ReferencedDocumentType refdoc = xmlFactory.createReferencedDocumentType();
IDType id = xmlFactory.createIDType();
id.setValue(trans.getBuyerOrderReferencedDocumentID());
refdoc.getID().add(id);
refdoc.setIssueDateTime(trans.getBuyerOrderReferencedDocumentIssueDateTime());
tradeAgreement.getBuyerOrderReferencedDocument().add(refdoc);
}
return tradeAgreement;
}
private TradePartyType getBuyer() {
TradePartyType buyerTradeParty = xmlFactory.createTradePartyType();
if (trans.getRecipient().getID() != null) {
IDType buyerID = xmlFactory.createIDType();
buyerID.setValue(trans.getRecipient().getID());
buyerTradeParty.getID().add(buyerID);
}
if (trans.getRecipient().getGlobalID() != null) {
IDType globalID = xmlFactory.createIDType();
globalID.setValue(trans.getRecipient().getGlobalID());
globalID.setSchemeID(trans.getRecipient().getGlobalIDScheme());
buyerTradeParty.getGlobalID().add(globalID);
}
TextType buyerName = xmlFactory.createTextType();
buyerName.setValue(trans.getRecipient().getName());
buyerTradeParty.setName(buyerName);
TradeAddressType buyerAddressType = xmlFactory.createTradeAddressType();
TextType buyerCityName = xmlFactory.createTextType();
buyerCityName.setValue(trans.getRecipient().getLocation());
buyerAddressType.setCityName(buyerCityName);
CountryIDType buyerCountryId = xmlFactory.createCountryIDType();
buyerCountryId.setValue(trans.getRecipient().getCountry());
buyerAddressType.setCountryID(buyerCountryId);
TextType buyerAddress = xmlFactory.createTextType();
buyerAddress.setValue(trans.getRecipient().getStreet());
buyerAddressType.setLineOne(buyerAddress);
CodeType buyerPostcode = xmlFactory.createCodeType();
buyerPostcode.setValue(trans.getRecipient().getZIP());
buyerAddressType.getPostcodeCode().add(buyerPostcode);
buyerTradeParty.setPostalTradeAddress(buyerAddressType);
// Ust-ID
TaxRegistrationType buyerTaxRegistration = xmlFactory
.createTaxRegistrationType();
IDType buyerUstId = xmlFactory.createIDType();
buyerUstId.setValue(trans.getRecipient().getVATID());
buyerUstId.setSchemeID(TaxRegistrationTypeConstants.USTID);
buyerTaxRegistration.setID(buyerUstId);
buyerTradeParty.getSpecifiedTaxRegistration().add(buyerTaxRegistration);
return buyerTradeParty;
}
private TradePartyType getSeller() {
TradePartyType sellerTradeParty = xmlFactory.createTradePartyType();
if (trans.getOwnForeignOrganisationID() != null) {
IDType sellerID = xmlFactory.createIDType();
sellerID.setValue(trans.getOwnForeignOrganisationID());
sellerTradeParty.getID().add(sellerID);
}
TextType sellerName = xmlFactory.createTextType();
sellerName.setValue(trans.getOwnOrganisationName());
sellerTradeParty.setName(sellerName);
TradeAddressType sellerAddressType = xmlFactory
.createTradeAddressType();
TextType sellerCityName = xmlFactory.createTextType();
sellerCityName.setValue(trans.getOwnLocation());
sellerAddressType.setCityName(sellerCityName);
CountryIDType sellerCountryId = xmlFactory.createCountryIDType();
sellerCountryId.setValue(trans.getOwnCountry());
sellerAddressType.setCountryID(sellerCountryId);
TextType sellerAddress = xmlFactory.createTextType();
sellerAddress.setValue(trans.getOwnStreet());
sellerAddressType.setLineOne(sellerAddress);
CodeType sellerPostcode = xmlFactory.createCodeType();
sellerPostcode.setValue(trans.getOwnZIP());
sellerAddressType.getPostcodeCode().add(sellerPostcode);
sellerTradeParty.setPostalTradeAddress(sellerAddressType);
// Steuernummer
TaxRegistrationType sellerTaxRegistration = xmlFactory
.createTaxRegistrationType();
IDType sellerTaxId = xmlFactory.createIDType();
sellerTaxId.setValue(trans.getOwnTaxID());
sellerTaxId.setSchemeID(TaxRegistrationTypeConstants.TAXID);
sellerTaxRegistration.setID(sellerTaxId);
sellerTradeParty.getSpecifiedTaxRegistration().add(
sellerTaxRegistration);
// Ust-ID
sellerTaxRegistration = xmlFactory.createTaxRegistrationType();
IDType sellerUstId = xmlFactory.createIDType();
sellerUstId.setValue(trans.getOwnVATID());
sellerUstId.setSchemeID(TaxRegistrationTypeConstants.USTID);
sellerTaxRegistration.setID(sellerUstId);
sellerTradeParty.getSpecifiedTaxRegistration().add(
sellerTaxRegistration);
return sellerTradeParty;
}
private SupplyChainTradeDeliveryType getTradeDelivery() {
SupplyChainTradeDeliveryType tradeDelivery = xmlFactory
.createSupplyChainTradeDeliveryType();
SupplyChainEventType deliveryEvent = xmlFactory
.createSupplyChainEventType();
DateTimeType deliveryDate = xmlFactory.createDateTimeType();
DateTimeType.DateTimeString deliveryDateString = xmlFactory
.createDateTimeTypeDateTimeString();
deliveryDateString.setFormat(DateTimeTypeConstants.DATE);
deliveryDateString.setValue(zugferdDateFormat.format(trans
.getDeliveryDate()));
deliveryDate.setDateTimeString(deliveryDateString);
deliveryEvent.getOccurrenceDateTime().add(deliveryDate);
tradeDelivery.getActualDeliverySupplyChainEvent().add(deliveryEvent);
return tradeDelivery;
}
private SupplyChainTradeSettlementType getTradeSettlement() {
SupplyChainTradeSettlementType tradeSettlement = xmlFactory
.createSupplyChainTradeSettlementType();
TextType paymentReference = xmlFactory.createTextType();
paymentReference.setValue(trans.getNumber());
tradeSettlement.getPaymentReference().add(paymentReference);
CodeType currencyCode = xmlFactory.createCodeType();
currencyCode.setValue(currency);
tradeSettlement.setInvoiceCurrencyCode(currencyCode);
tradeSettlement.getSpecifiedTradeSettlementPaymentMeans().addAll(
getPaymentData());
tradeSettlement.getApplicableTradeTax().addAll(getTradeTax());
tradeSettlement.getSpecifiedTradePaymentTerms().addAll(
getPaymentTerms());
if (trans.getZFAllowances() != null) {
tradeSettlement.getSpecifiedTradeAllowanceCharge().addAll(
getHeaderAllowances());
}
if (trans.getZFLogisticsServiceCharges() != null) {
tradeSettlement.getSpecifiedLogisticsServiceCharge().addAll(
getHeaderLogisticsServiceCharges());
}
if (trans.getZFCharges() != null) {
tradeSettlement.getSpecifiedTradeAllowanceCharge().addAll(
getHeaderCharges());
}
tradeSettlement.setSpecifiedTradeSettlementMonetarySummation(getMonetarySummation());
return tradeSettlement;
}
private List<TradeSettlementPaymentMeansType> getPaymentData() {
List<TradeSettlementPaymentMeansType> result = new ArrayList<>();
for (IZUGFeRDTradeSettlementPayment settlementPayment : trans.getTradeSettlementPayment()) {
TradeSettlementPaymentMeansType paymentData = xmlFactory
.createTradeSettlementPaymentMeansType();
PaymentMeansCodeType paymentDataType = xmlFactory
.createPaymentMeansCodeType();
paymentDataType.setValue(PaymentMeansCodeTypeConstants.BANKACCOUNT);
paymentData.setTypeCode(paymentDataType);
TextType paymentInfo = xmlFactory.createTextType();
String paymentInfoText = settlementPayment.getOwnPaymentInfoText();
if (paymentInfoText == null) {
paymentInfoText = "";
}
paymentInfo.setValue(paymentInfoText);
paymentData.getInformation().add(paymentInfo);
CreditorFinancialAccountType bankAccount = xmlFactory
.createCreditorFinancialAccountType();
IDType iban = xmlFactory.createIDType();
iban.setValue(settlementPayment.getOwnIBAN());
bankAccount.setIBANID(iban);
IDType kto = xmlFactory.createIDType();
kto.setValue(settlementPayment.getOwnKto());
bankAccount.setProprietaryID(kto);
paymentData.setPayeePartyCreditorFinancialAccount(bankAccount);
CreditorFinancialInstitutionType bankData = xmlFactory
.createCreditorFinancialInstitutionType();
IDType bicId = xmlFactory.createIDType();
bicId.setValue(settlementPayment.getOwnBIC());
bankData.setBICID(bicId);
TextType bankName = xmlFactory.createTextType();
bankName.setValue(settlementPayment.getOwnBankName());
bankData.setName(bankName);
IDType blz = xmlFactory.createIDType();
blz.setValue(settlementPayment.getOwnBLZ());
bankData.setGermanBankleitzahlID(blz);
paymentData.setPayeeSpecifiedCreditorFinancialInstitution(bankData);
result.add(paymentData);
}
return result;
}
private Collection<TradeTaxType> getTradeTax() {
List<TradeTaxType> tradeTaxTypes = new ArrayList<>();
HashMap<BigDecimal, VATAmount> VATPercentAmountMap = this.getVATPercentAmountMap();
for (BigDecimal currentTaxPercent : VATPercentAmountMap.keySet()) {
TradeTaxType tradeTax = xmlFactory.createTradeTaxType();
TaxTypeCodeType taxTypeCode = xmlFactory.createTaxTypeCodeType();
taxTypeCode.setValue(TaxTypeCodeTypeConstants.SALESTAX);
tradeTax.setTypeCode(taxTypeCode);
TaxCategoryCodeType taxCategoryCode = xmlFactory.createTaxCategoryCodeType();
VATAmount vatAmount = VATPercentAmountMap.get(currentTaxPercent);
taxCategoryCode.setValue(vatAmount.getCategoryCode());
tradeTax.setCategoryCode(taxCategoryCode);
VATAmount amount = VATPercentAmountMap.get(currentTaxPercent);
PercentType taxPercent = xmlFactory.createPercentType();
taxPercent.setValue(vatFormat(currentTaxPercent));
tradeTax.setApplicablePercent(taxPercent);
AmountType calculatedTaxAmount = xmlFactory.createAmountType();
calculatedTaxAmount.setCurrencyID(currency);
calculatedTaxAmount.setValue(currencyFormat(amount.getCalculated()));
tradeTax.getCalculatedAmount().add(calculatedTaxAmount);
AmountType basisTaxAmount = xmlFactory.createAmountType();
basisTaxAmount.setCurrencyID(currency);
basisTaxAmount.setValue(currencyFormat(amount.getBasis()));
tradeTax.getBasisAmount().add(basisTaxAmount);
tradeTaxTypes.add(tradeTax);
}
return tradeTaxTypes;
}
private Collection<TradeAllowanceChargeType> getHeaderAllowances() {
List<TradeAllowanceChargeType> headerAllowances = new ArrayList<>();
for (IZUGFeRDAllowanceCharge iAllowance : trans.getZFAllowances()) {
TradeAllowanceChargeType allowance = xmlFactory.createTradeAllowanceChargeType();
IndicatorType chargeIndicator = xmlFactory.createIndicatorType();
chargeIndicator.setIndicator(false);
allowance.setChargeIndicator(chargeIndicator);
AmountType actualAmount = xmlFactory.createAmountType();
actualAmount.setCurrencyID(currency);
actualAmount.setValue(currencyFormat(iAllowance.getTotalAmount()));
allowance.getActualAmount().add(actualAmount);
TextType reason = xmlFactory.createTextType();
reason.setValue(iAllowance.getReason());
allowance.setReason(reason);
TradeTaxType tradeTax = xmlFactory.createTradeTaxType();
PercentType vatPercent = xmlFactory.createPercentType();
vatPercent.setValue(currencyFormat(iAllowance.getTaxPercent()));
tradeTax.setApplicablePercent(vatPercent);
/*
* Only in extended AmountType basisAmount =
* xmlFactory.createAmountType();
* basisAmount.setCurrencyID(trans.getInvoiceCurrency());
* basisAmount.setValue(amount.getBasis());
* allowance.setBasisAmount(basisAmount);
*/
TaxCategoryCodeType taxType = xmlFactory.createTaxCategoryCodeType();
taxType.setValue(iAllowance.getCategoryCode());
tradeTax.setCategoryCode(taxType);
TaxTypeCodeType taxCode = xmlFactory.createTaxTypeCodeType();
taxCode.setValue(TaxTypeCodeTypeConstants.SALESTAX);
tradeTax.setTypeCode(taxCode);
allowance.getCategoryTradeTax().add(tradeTax);
headerAllowances.add(allowance);
}
return headerAllowances;
}
private Collection<TradeAllowanceChargeType> getHeaderCharges() {
List<TradeAllowanceChargeType> headerCharges = new ArrayList<>();
for (IZUGFeRDAllowanceCharge iCharge : trans.getZFCharges()) {
TradeAllowanceChargeType charge = xmlFactory.createTradeAllowanceChargeType();
IndicatorType chargeIndicator = xmlFactory.createIndicatorType();
chargeIndicator.setIndicator(true);
charge.setChargeIndicator(chargeIndicator);
AmountType actualAmount = xmlFactory.createAmountType();
actualAmount.setCurrencyID(currency);
actualAmount.setValue(currencyFormat(iCharge.getTotalAmount()));
charge.getActualAmount().add(actualAmount);
TextType reason = xmlFactory.createTextType();
reason.setValue(iCharge.getReason());
charge.setReason(reason);
TradeTaxType tradeTax = xmlFactory.createTradeTaxType();
PercentType vatPercent = xmlFactory.createPercentType();
vatPercent.setValue(currencyFormat(iCharge.getTaxPercent()));
tradeTax.setApplicablePercent(vatPercent);
/*
* Only in extended AmountType basisAmount =
* xmlFactory.createAmountType();
* basisAmount.setCurrencyID(trans.getInvoiceCurrency());
* basisAmount.setValue(amount.getBasis());
* allowance.setBasisAmount(basisAmount);
*/
TaxCategoryCodeType taxType = xmlFactory.createTaxCategoryCodeType();
taxType.setValue(iCharge.getCategoryCode());
tradeTax.setCategoryCode(taxType);
TaxTypeCodeType taxCode = xmlFactory.createTaxTypeCodeType();
taxCode.setValue(TaxTypeCodeTypeConstants.SALESTAX);
tradeTax.setTypeCode(taxCode);
charge.getCategoryTradeTax().add(tradeTax);
headerCharges.add(charge);
}
return headerCharges;
}
private Collection<LogisticsServiceChargeType> getHeaderLogisticsServiceCharges() {
List<LogisticsServiceChargeType> headerServiceCharge = new ArrayList<>();
for (IZUGFeRDAllowanceCharge iServiceCharge : trans.getZFLogisticsServiceCharges()) {
LogisticsServiceChargeType serviceCharge = xmlFactory.createLogisticsServiceChargeType();
AmountType actualAmount = xmlFactory.createAmountType();
actualAmount.setCurrencyID(currency);
actualAmount.setValue(currencyFormat(iServiceCharge.getTotalAmount()));
serviceCharge.getAppliedAmount().add(actualAmount);
TextType reason = xmlFactory.createTextType();
reason.setValue(iServiceCharge.getReason());
serviceCharge.getDescription().add(reason);
TradeTaxType tradeTax = xmlFactory.createTradeTaxType();
PercentType vatPercent = xmlFactory.createPercentType();
vatPercent.setValue(currencyFormat(iServiceCharge.getTaxPercent()));
tradeTax.setApplicablePercent(vatPercent);
/*
* Only in extended AmountType basisAmount =
* xmlFactory.createAmountType();
* basisAmount.setCurrencyID(trans.getInvoiceCurrency());
* basisAmount.setValue(amount.getBasis());
* allowance.setBasisAmount(basisAmount);
*/
TaxCategoryCodeType taxType = xmlFactory.createTaxCategoryCodeType();
taxType.setValue(iServiceCharge.getCategoryCode());
tradeTax.setCategoryCode(taxType);
TaxTypeCodeType taxCode = xmlFactory.createTaxTypeCodeType();
taxCode.setValue(TaxTypeCodeTypeConstants.SALESTAX);
tradeTax.setTypeCode(taxCode);
serviceCharge.getAppliedTradeTax().add(tradeTax);
headerServiceCharge.add(serviceCharge);
}
return headerServiceCharge;
}
private Collection<TradePaymentTermsType> getPaymentTerms() {
List<TradePaymentTermsType> paymentTerms = new ArrayList<>();
TradePaymentTermsType paymentTerm = xmlFactory
.createTradePaymentTermsType();
DateTimeType dueDate = xmlFactory.createDateTimeType();
DateTimeType.DateTimeString dueDateString = xmlFactory
.createDateTimeTypeDateTimeString();
dueDateString.setFormat(DateTimeTypeConstants.DATE);
dueDateString.setValue(zugferdDateFormat.format(trans.getDueDate()));
dueDate.setDateTimeString(dueDateString);
paymentTerm.setDueDateDateTime(dueDate);
TextType paymentTermDescr = xmlFactory.createTextType();
String paymentTermDescription = trans.getPaymentTermDescription();
if (paymentTermDescription == null) {
paymentTermDescription = "";
}
paymentTermDescr.setValue(paymentTermDescription);
paymentTerm.getDescription().add(paymentTermDescr);
paymentTerms.add(paymentTerm);
return paymentTerms;
}
private TradeSettlementMonetarySummationType getMonetarySummation() {
TradeSettlementMonetarySummationType monetarySummation = xmlFactory
.createTradeSettlementMonetarySummationType();
// AllowanceTotalAmount = sum of all allowances
AmountType allowanceTotalAmount = xmlFactory.createAmountType();
allowanceTotalAmount.setCurrencyID(currency);
if (trans.getZFAllowances() != null) {
BigDecimal totalHeaderAllowance = BigDecimal.ZERO;
for (IZUGFeRDAllowanceCharge headerAllowance : trans
.getZFAllowances()) {
totalHeaderAllowance = headerAllowance.getTotalAmount().add(
totalHeaderAllowance);
}
allowanceTotalAmount.setValue(currencyFormat(totalHeaderAllowance));
} else {
allowanceTotalAmount.setValue(currencyFormat(BigDecimal.ZERO));
}
monetarySummation.getAllowanceTotalAmount().add(allowanceTotalAmount);
// ChargeTotalAmount = sum of all Logistic service charges + normal
// charges
BigDecimal totalCharge = BigDecimal.ZERO;
AmountType totalChargeAmount = xmlFactory.createAmountType();
totalChargeAmount.setCurrencyID(currency);
if (trans.getZFLogisticsServiceCharges() != null) {
for (IZUGFeRDAllowanceCharge logisticsServiceCharge : trans
.getZFLogisticsServiceCharges()) {
totalCharge = logisticsServiceCharge.getTotalAmount().add(
totalCharge);
}
}
if (trans.getZFCharges() != null) {
for (IZUGFeRDAllowanceCharge charge : trans.getZFCharges()) {
totalCharge = charge.getTotalAmount().add(totalCharge);
}
}
totalChargeAmount.setValue(currencyFormat(totalCharge));
monetarySummation.getChargeTotalAmount().add(totalChargeAmount);
/*
* AmountType chargeTotalAmount = xmlFactory.createAmountType();
* chargeTotalAmount.setCurrencyID(trans.getInvoiceCurrency());
* chargeTotalAmount.setValue(currencyFormat(BigDecimal.ZERO));
* monetarySummation.getChargeTotalAmount().add(chargeTotalAmount);
*/
AmountType lineTotalAmount = xmlFactory.createAmountType();
lineTotalAmount.setCurrencyID(currency);
lineTotalAmount.setValue(currencyFormat(totals.getLineTotal()));
monetarySummation.getLineTotalAmount().add(lineTotalAmount);
AmountType taxBasisTotalAmount = xmlFactory.createAmountType();
taxBasisTotalAmount.setCurrencyID(currency);
taxBasisTotalAmount.setValue(currencyFormat(totals.getTotalNet()));
monetarySummation.getTaxBasisTotalAmount().add(taxBasisTotalAmount);
AmountType taxTotalAmount = xmlFactory.createAmountType();
taxTotalAmount.setCurrencyID(currency);
taxTotalAmount.setValue(currencyFormat(totals.getTaxTotal()));
monetarySummation.getTaxTotalAmount().add(taxTotalAmount);
AmountType grandTotalAmount = xmlFactory.createAmountType();
grandTotalAmount.setCurrencyID(currency);
grandTotalAmount.setValue(currencyFormat(totals.getTotalGross()));
monetarySummation.getGrandTotalAmount().add(grandTotalAmount);
AmountType duePayableAmount = xmlFactory.createAmountType();
duePayableAmount.setCurrencyID(currency);
duePayableAmount.setValue(currencyFormat(totals.getTotalGross()));
monetarySummation.getDuePayableAmount().add(duePayableAmount);
return monetarySummation;
}
private Collection<SupplyChainTradeLineItemType> getLineItems() {
ArrayList<SupplyChainTradeLineItemType> lineItems = new ArrayList<>();
int lineID = 0;
for (IZUGFeRDExportableItem currentItem : trans.getZFItems()) {
lineID++;
LineCalc lc = new LineCalc(currentItem);
SupplyChainTradeLineItemType lineItem = xmlFactory
.createSupplyChainTradeLineItemType();
DocumentLineDocumentType lineDocument = xmlFactory
.createDocumentLineDocumentType();
IDType lineNumber = xmlFactory.createIDType();
lineNumber.setValue(Integer.toString(lineID));
lineDocument.setLineID(lineNumber);
lineItem.setAssociatedDocumentLineDocument(lineDocument);
SupplyChainTradeAgreementType tradeAgreement = xmlFactory
.createSupplyChainTradeAgreementType();
TradePriceType grossTradePrice = xmlFactory.createTradePriceType();
QuantityType grossQuantity = xmlFactory.createQuantityType();
grossQuantity.setUnitCode(currentItem.getProduct().getUnit());
grossQuantity.setValue(quantityFormat(BigDecimal.ONE));
grossTradePrice.setBasisQuantity(grossQuantity);
AmountType grossChargeAmount = xmlFactory.createAmountType();
grossChargeAmount.setCurrencyID(currency);
grossChargeAmount.setValue(priceFormat(currentItem.getPrice()));
grossTradePrice.getChargeAmount().add(grossChargeAmount);
tradeAgreement.getGrossPriceProductTradePrice()
.add(grossTradePrice);
if (currentItem.getItemAllowances() != null) {
for (IZUGFeRDAllowanceCharge itemAllowance : currentItem
.getItemAllowances()) {
TradeAllowanceChargeType eItemAllowance = xmlFactory
.createTradeAllowanceChargeType();
IndicatorType chargeIndicator = xmlFactory
.createIndicatorType();
chargeIndicator.setIndicator(false);
eItemAllowance.setChargeIndicator(chargeIndicator);
AmountType actualAmount = xmlFactory.createAmountType();
actualAmount.setCurrencyID(currency);
actualAmount.setValue(priceFormat(itemAllowance
.getTotalAmount().divide(currentItem.getQuantity(),
4, BigDecimal.ROUND_HALF_UP)));
eItemAllowance.getActualAmount().add(actualAmount);
TextType reason = xmlFactory.createTextType();
reason.setValue(itemAllowance.getReason());
eItemAllowance.setReason(reason);
grossTradePrice.getAppliedTradeAllowanceCharge().add(
eItemAllowance);
}
}
if (currentItem.getItemCharges() != null) {
for (IZUGFeRDAllowanceCharge itemCharge : currentItem
.getItemCharges()) {
TradeAllowanceChargeType eItemCharge = xmlFactory
.createTradeAllowanceChargeType();
AmountType actualAmount = xmlFactory.createAmountType();
actualAmount.setCurrencyID(currency);
actualAmount.setValue(priceFormat(itemCharge
.getTotalAmount().divide(currentItem.getQuantity(),
4, BigDecimal.ROUND_HALF_UP)));
eItemCharge.getActualAmount().add(actualAmount);
TextType reason = xmlFactory.createTextType();
reason.setValue(itemCharge.getReason());
eItemCharge.setReason(reason);
IndicatorType chargeIndicator = xmlFactory
.createIndicatorType();
chargeIndicator.setIndicator(true);
eItemCharge.setChargeIndicator(chargeIndicator);
grossTradePrice.getAppliedTradeAllowanceCharge().add(
eItemCharge);
}
}
TradePriceType netTradePrice = xmlFactory.createTradePriceType();
QuantityType netQuantity = xmlFactory.createQuantityType();
netQuantity.setUnitCode(currentItem.getProduct().getUnit());
netQuantity.setValue(quantityFormat(BigDecimal.ONE));
netTradePrice.setBasisQuantity(netQuantity);
AmountType netChargeAmount = xmlFactory.createAmountType();
netChargeAmount.setCurrencyID(currency);
netChargeAmount.setValue(priceFormat(lc.getItemNetAmount()));
netTradePrice.getChargeAmount().add(netChargeAmount);
tradeAgreement.getNetPriceProductTradePrice().add(netTradePrice);
lineItem.setSpecifiedSupplyChainTradeAgreement(tradeAgreement);
SupplyChainTradeDeliveryType tradeDelivery = xmlFactory
.createSupplyChainTradeDeliveryType();
QuantityType billedQuantity = xmlFactory.createQuantityType();
billedQuantity.setUnitCode(currentItem.getProduct().getUnit());
billedQuantity.setValue(quantityFormat(currentItem.getQuantity()));
tradeDelivery.setBilledQuantity(billedQuantity);
lineItem.setSpecifiedSupplyChainTradeDelivery(tradeDelivery);
SupplyChainTradeSettlementType tradeSettlement = xmlFactory
.createSupplyChainTradeSettlementType();
TradeTaxType tradeTax = xmlFactory.createTradeTaxType();
TaxCategoryCodeType taxCategoryCode = xmlFactory.createTaxCategoryCodeType();
taxCategoryCode.setValue(currentItem.getCategoryCode());
tradeTax.setCategoryCode(taxCategoryCode);
TaxTypeCodeType taxCode = xmlFactory.createTaxTypeCodeType();
taxCode.setValue(TaxTypeCodeTypeConstants.SALESTAX);
tradeTax.setTypeCode(taxCode);
PercentType taxPercent = xmlFactory.createPercentType();
taxPercent.setValue(vatFormat(currentItem.getProduct()
.getVATPercent()));
tradeTax.setApplicablePercent(taxPercent);
tradeSettlement.getApplicableTradeTax().add(tradeTax);
TradeSettlementMonetarySummationType monetarySummation = xmlFactory
.createTradeSettlementMonetarySummationType();
AmountType itemAmount = xmlFactory.createAmountType();
itemAmount.setCurrencyID(currency);
itemAmount.setValue(currencyFormat(lc.getItemTotalNetAmount()));
monetarySummation.getLineTotalAmount().add(itemAmount);
tradeSettlement
.setSpecifiedTradeSettlementMonetarySummation(monetarySummation);
lineItem.setSpecifiedSupplyChainTradeSettlement(tradeSettlement);
TradeProductType tradeProduct = xmlFactory.createTradeProductType();
TextType productName = xmlFactory.createTextType();
productName.setValue(currentItem.getProduct().getName());
tradeProduct.getName().add(productName);
TextType productDescription = xmlFactory.createTextType();
productDescription.setValue(currentItem.getProduct()
.getDescription());
tradeProduct.getDescription().add(productDescription);
lineItem.setSpecifiedTradeProduct(tradeProduct);
lineItems.add(lineItem);
}
return lineItems;
}
private BigDecimal vatFormat(BigDecimal value) {
return value.setScale(2, RoundingMode.HALF_UP);
}
private BigDecimal currencyFormat(BigDecimal value) {
return value.setScale(2, RoundingMode.HALF_UP);
}
private BigDecimal priceFormat(BigDecimal value) {
return value.setScale(4, RoundingMode.HALF_UP);
}
private BigDecimal quantityFormat(BigDecimal value) {
return value.setScale(4, RoundingMode.HALF_UP);
}
/**
* which taxes have been used with which amounts in this transaction, empty for no taxes, or e.g. 19=>190 and 7=>14 if 1000 Eur were applicable to 19% VAT
* (=>190 EUR VAT) and 200 EUR were applicable to 7% (=>14 EUR VAT) 190 Eur
*
* @return HashMap<BigDecimal, VATAmount> which taxes have been used with which amounts
*/
private HashMap<BigDecimal, VATAmount> getVATPercentAmountMap() {
return getVATPercentAmountMap(false);
}
private HashMap<BigDecimal, VATAmount> getVATPercentAmountMap(Boolean itemOnly) {
HashMap<BigDecimal, VATAmount> hm = new HashMap<>();
for (IZUGFeRDExportableItem currentItem : trans.getZFItems()) {
BigDecimal percent = currentItem.getProduct().getVATPercent();
LineCalc lc = new LineCalc(currentItem);
VATAmount itemVATAmount = new VATAmount(lc.getItemTotalNetAmount(), lc.getItemTotalVATAmount(), lc.getCategoryCode());
VATAmount current = hm.get(percent);
if (current == null) {
hm.put(percent, itemVATAmount);
} else {
hm.put(percent, current.add(itemVATAmount));
}
}
if (itemOnly) {
return hm;
}
if (trans.getZFAllowances() != null) {
for (IZUGFeRDAllowanceCharge headerAllowance : trans.getZFAllowances()) {
BigDecimal percent = headerAllowance.getTaxPercent();
VATAmount itemVATAmount = new VATAmount(
headerAllowance.getTotalAmount(), headerAllowance
.getTotalAmount().multiply(percent)
.divide(new BigDecimal(100)), trans.getDocumentCode());
VATAmount current = hm.get(percent);
if (current == null) {
hm.put(percent, itemVATAmount);
} else {
hm.put(percent, current.subtract(itemVATAmount));
}
}
}
if (trans.getZFLogisticsServiceCharges() != null) {
for (IZUGFeRDAllowanceCharge logisticsServiceCharge : trans
.getZFLogisticsServiceCharges()) {
BigDecimal percent = logisticsServiceCharge.getTaxPercent();
VATAmount itemVATAmount = new VATAmount(
logisticsServiceCharge.getTotalAmount(),
logisticsServiceCharge.getTotalAmount()
.multiply(percent).divide(new BigDecimal(100)), logisticsServiceCharge.getCategoryCode());
VATAmount current = hm.get(percent);
if (current == null) {
hm.put(percent, itemVATAmount);
} else {
hm.put(percent, current.add(itemVATAmount));
}
}
}
if (trans.getZFCharges() != null) {
for (IZUGFeRDAllowanceCharge charge : trans.getZFCharges()) {
BigDecimal percent = charge.getTaxPercent();
VATAmount itemVATAmount = new VATAmount(
charge.getTotalAmount(), charge.getTotalAmount()
.multiply(percent).divide(new BigDecimal(100)), charge.getCategoryCode());
VATAmount current = hm.get(percent);
if (current == null) {
hm.put(percent, itemVATAmount);
} else {
hm.put(percent, current.add(itemVATAmount));
}
}
}
return hm;
}
ZUGFeRDTransactionModelConverter withTest(boolean isTest) {
this.isTest = isTest;
return this;
}
public ZUGFeRDTransactionModelConverter withProfile(String profile) {
this.profile = profile;
return this;
}
private class LineCalc {
private BigDecimal totalGross;
private BigDecimal itemTotalNetAmount;
private BigDecimal itemTotalVATAmount;
private BigDecimal itemNetAmount;
private String categoryCode;
public LineCalc(IZUGFeRDExportableItem currentItem) {
BigDecimal totalAllowance = BigDecimal.ZERO;
BigDecimal totalCharge = BigDecimal.ZERO;
if (currentItem.getItemAllowances() != null) {
for (IZUGFeRDAllowanceCharge itemAllowance : currentItem
.getItemAllowances()) {
totalAllowance = itemAllowance.getTotalAmount().add(
totalAllowance);
}
}
if (currentItem.getItemCharges() != null) {
for (IZUGFeRDAllowanceCharge itemCharge : currentItem
.getItemCharges()) {
totalCharge = itemCharge.getTotalAmount().add(totalCharge);
}
}
BigDecimal multiplicator = currentItem.getProduct().getVATPercent()
.divide(new BigDecimal(100), 4, BigDecimal.ROUND_HALF_UP)
.add(BigDecimal.ONE);
// priceGross=currentItem.getPrice().multiply(multiplicator);
totalGross = currentItem.getPrice()
.multiply(currentItem.getQuantity())
.subtract(totalAllowance).add(totalCharge)
.multiply(multiplicator);
itemTotalNetAmount = currentItem.getPrice()
.multiply(currentItem.getQuantity())
.subtract(totalAllowance).add(totalCharge)
.setScale(2, BigDecimal.ROUND_HALF_UP);
itemTotalVATAmount = totalGross.subtract(itemTotalNetAmount);
itemNetAmount = currentItem
.getPrice()
.multiply(currentItem.getQuantity())
.subtract(totalAllowance)
.add(totalCharge)
.divide(currentItem.getQuantity(), 4,
BigDecimal.ROUND_HALF_UP);
categoryCode = currentItem.getCategoryCode();
}
public BigDecimal getItemTotalNetAmount() {
return itemTotalNetAmount;
}
public BigDecimal getItemTotalVATAmount() {
return itemTotalVATAmount;
}
public BigDecimal getItemNetAmount() {
return itemNetAmount;
}
public String getCategoryCode() { return categoryCode; }
}
private class Totals {
private BigDecimal totalNetAmount;
private BigDecimal totalGrossAmount;
private BigDecimal lineTotalAmount;
private BigDecimal totalTaxAmount;
public Totals() {
BigDecimal res = BigDecimal.ZERO;
for (IZUGFeRDExportableItem currentItem : trans.getZFItems()) {
LineCalc lc = new LineCalc(currentItem);
res = res.add(lc.getItemTotalNetAmount());
}
// Set line total
lineTotalAmount = res;
if (trans.getZFAllowances() != null) {
for (IZUGFeRDAllowanceCharge headerAllowance : trans
.getZFAllowances()) {
res = res.subtract(headerAllowance.getTotalAmount());
}
}
if (trans.getZFLogisticsServiceCharges() != null) {
for (IZUGFeRDAllowanceCharge logisticsServiceCharge : trans
.getZFLogisticsServiceCharges()) {
res = res.add(logisticsServiceCharge.getTotalAmount());
}
}
if (trans.getZFCharges() != null) {
for (IZUGFeRDAllowanceCharge charge : trans.getZFCharges()) {
res = res.add(charge.getTotalAmount());
}
}
// Set total net amount
totalNetAmount = res;
HashMap<BigDecimal, VATAmount> vatAmountHashMap = getVATPercentAmountMap();
for (VATAmount amount : vatAmountHashMap.values()) {
res = res.add(amount.getCalculated());
}
// Set total gross amount
totalGrossAmount = res;
totalTaxAmount = totalGrossAmount
.subtract(totalNetAmount);
}
public BigDecimal getTotalNet() {
return totalNetAmount;
}
public BigDecimal getTotalGross() {
return totalGrossAmount;
}
public BigDecimal getLineTotal() {
return lineTotalAmount;
}
public BigDecimal getTaxTotal() {
return totalTaxAmount;
}
}
}
| add totalPrepaidAmount to monetarySummation and use value to calculate duePayableAmount
| src/main/java/org/mustangproject/ZUGFeRD/ZUGFeRDTransactionModelConverter.java | add totalPrepaidAmount to monetarySummation and use value to calculate duePayableAmount |
|
Java | apache-2.0 | fd1c93fd6d033da88a1c30d3edb9617e384ac098 | 0 | syphr42/liblametrictime-java | /*
* Copyright 2017 Gregory P. Moyer
*
* 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.syphr.lametrictime.api.local.impl;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.glassfish.jersey.filter.LoggingFilter;
import org.syphr.lametrictime.api.cloud.impl.LaMetricTimeCloudImpl;
import org.syphr.lametrictime.api.common.impl.AbstractClient;
import org.syphr.lametrictime.api.local.LaMetricTimeLocal;
import org.syphr.lametrictime.api.local.LocalConfiguration;
import org.syphr.lametrictime.api.local.NotificationCreationException;
import org.syphr.lametrictime.api.local.NotificationNotFoundException;
import org.syphr.lametrictime.api.local.UpdateException;
import org.syphr.lametrictime.api.local.model.Api;
import org.syphr.lametrictime.api.local.model.Audio;
import org.syphr.lametrictime.api.local.model.Bluetooth;
import org.syphr.lametrictime.api.local.model.Device;
import org.syphr.lametrictime.api.local.model.Display;
import org.syphr.lametrictime.api.local.model.Failure;
import org.syphr.lametrictime.api.local.model.Notification;
import org.syphr.lametrictime.api.local.model.NotificationResult;
import org.syphr.lametrictime.api.local.model.WidgetUpdates;
import org.syphr.lametrictime.api.local.model.Wifi;
import com.eclipsesource.jaxrs.provider.gson.GsonProvider;
import com.google.gson.reflect.TypeToken;
public class LaMetricTimeLocalImpl extends AbstractClient implements LaMetricTimeLocal
{
private static final String HEADER_ACCESS_TOKEN = "X-Access-Token";
private final LocalConfiguration config;
private volatile Api api;
public LaMetricTimeLocalImpl(LocalConfiguration config)
{
this.config = config;
}
@Override
public Api getApi()
{
if (api == null)
{
synchronized (this)
{
if (api == null)
{
api = getClient().target(config.getBaseUri())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Api.class);
}
}
}
return api;
}
@Override
public Device getDevice()
{
return getClient().target(getApi().getEndpoints().getDeviceUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Device.class);
}
@Override
public String createNotification(Notification notification) throws NotificationCreationException
{
Response response = getClient().target(getApi().getEndpoints().getNotificationsUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(notification));
if (!Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily()))
{
throw new NotificationCreationException(response.readEntity(Failure.class));
}
try
{
return response.readEntity(NotificationResult.class).getSuccess().getId();
}
catch (Exception e)
{
throw new NotificationCreationException("Invalid JSON returned from service", e);
}
}
@Override
public List<Notification> getNotifications()
{
Response response = getClient().target(getApi().getEndpoints().getNotificationsUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.get();
// @formatter:off
return getGson().fromJson(response.readEntity(String.class),
new TypeToken<List<Notification>>(){}.getType());
// @formatter:on
}
@Override
public Notification getCurrentNotification()
{
Notification notification = getClient().target(getApi().getEndpoints()
.getCurrentNotificationUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Notification.class);
// when there is no current notification, return null
if (notification.getId() == null)
{
return null;
}
return notification;
}
@Override
public Notification getNotification(String id) throws NotificationNotFoundException
{
Response response = getClient().target(getApi().getEndpoints()
.getConcreteNotificationUrl()
.replace("{/:id}", "/" + id))
.request(MediaType.APPLICATION_JSON_TYPE)
.get();
if (!Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily()))
{
throw new NotificationNotFoundException(response.readEntity(Failure.class));
}
return response.readEntity(Notification.class);
}
@Override
public void deleteNotification(String id) throws NotificationNotFoundException
{
Response response = getClient().target(getApi().getEndpoints()
.getConcreteNotificationUrl()
.replace("{/:id}", "/" + id))
.request(MediaType.APPLICATION_JSON_TYPE)
.delete();
if (!Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily()))
{
throw new NotificationNotFoundException(response.readEntity(Failure.class));
}
response.close();
}
@Override
public Display getDisplay()
{
return getClient().target(getApi().getEndpoints().getDisplayUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Display.class);
}
@Override
public void updateDisplay(Display display) throws UpdateException
{
Response response = getClient().target(getApi().getEndpoints().getDisplayUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.put(Entity.json(display));
if (!Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily()))
{
throw new UpdateException(response.readEntity(Failure.class));
}
response.close();
}
@Override
public Audio getAudio()
{
return getClient().target(getApi().getEndpoints().getAudioUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Audio.class);
}
@Override
public void updateAudio(Audio audio) throws UpdateException
{
Response response = getClient().target(getApi().getEndpoints().getAudioUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.put(Entity.json(audio));
if (!Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily()))
{
throw new UpdateException(response.readEntity(Failure.class));
}
response.close();
}
@Override
public Bluetooth getBluetooth()
{
return getClient().target(getApi().getEndpoints().getBluetoothUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Bluetooth.class);
}
@Override
public void updateBluetooth(Bluetooth bluetooth) throws UpdateException
{
Response response = getClient().target(getApi().getEndpoints().getBluetoothUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.put(Entity.json(bluetooth));
if (!Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily()))
{
throw new UpdateException(response.readEntity(Failure.class));
}
response.close();
}
@Override
public Wifi getWifi()
{
return getClient().target(getApi().getEndpoints().getWifiUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Wifi.class);
}
@Override
public void updateApplication(String id,
String accessToken,
WidgetUpdates widgetUpdates) throws UpdateException
{
Response response = getClient().target(getApi().getEndpoints()
.getWidgetUpdateUrl()
.replace("{/:id}", "/" + id))
.request(MediaType.APPLICATION_JSON_TYPE)
.header(HEADER_ACCESS_TOKEN, accessToken)
.post(Entity.json(widgetUpdates));
if (!Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily()))
{
throw new UpdateException(response.readEntity(Failure.class));
}
response.close();
}
@Override
protected Client createClient()
{
ClientBuilder builder = ClientBuilder.newBuilder();
// setup Gson (de)serialization
GsonProvider<Object> gsonProvider = new GsonProvider<>();
gsonProvider.setGson(getGson());
builder.register(gsonProvider);
// deal with unverifiable cert
if (config.isSecure())
{
try
{
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { new X509TrustManager()
{
@Override
public void checkClientTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException
{
// noop
}
@Override
public void checkServerTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException
{
// noop
}
@Override
public X509Certificate[] getAcceptedIssuers()
{
return new X509Certificate[0];
}
} }, new java.security.SecureRandom());
builder.sslContext(sslcontext)
.hostnameVerifier((host, session) -> host.equals(config.getHost()));
}
catch (KeyManagementException | NoSuchAlgorithmException e)
{
throw new RuntimeException("Failed to setup secure communication", e);
}
}
// turn on logging if requested
if (config.isLogging())
{
builder.register(new LoggingFilter(Logger.getLogger(LaMetricTimeCloudImpl.class.getName()),
config.getLogMax()));
}
// setup basic auth
builder.register(HttpAuthenticationFeature.basic(config.getAuthUser(), config.getApiKey()));
return builder.build();
}
}
| src/main/java/org/syphr/lametrictime/api/local/impl/LaMetricTimeLocalImpl.java | /*
* Copyright 2017 Gregory P. Moyer
*
* 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.syphr.lametrictime.api.local.impl;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.glassfish.jersey.filter.LoggingFilter;
import org.syphr.lametrictime.api.cloud.impl.LaMetricTimeCloudImpl;
import org.syphr.lametrictime.api.common.impl.AbstractClient;
import org.syphr.lametrictime.api.local.LaMetricTimeLocal;
import org.syphr.lametrictime.api.local.LocalConfiguration;
import org.syphr.lametrictime.api.local.NotificationCreationException;
import org.syphr.lametrictime.api.local.NotificationNotFoundException;
import org.syphr.lametrictime.api.local.UpdateException;
import org.syphr.lametrictime.api.local.model.Api;
import org.syphr.lametrictime.api.local.model.Audio;
import org.syphr.lametrictime.api.local.model.Bluetooth;
import org.syphr.lametrictime.api.local.model.Device;
import org.syphr.lametrictime.api.local.model.Display;
import org.syphr.lametrictime.api.local.model.Failure;
import org.syphr.lametrictime.api.local.model.Notification;
import org.syphr.lametrictime.api.local.model.NotificationResult;
import org.syphr.lametrictime.api.local.model.WidgetUpdates;
import org.syphr.lametrictime.api.local.model.Wifi;
import com.eclipsesource.jaxrs.provider.gson.GsonProvider;
import com.google.gson.reflect.TypeToken;
public class LaMetricTimeLocalImpl extends AbstractClient implements LaMetricTimeLocal
{
private static final String HEADER_ACCESS_TOKEN = "X-Access-Token";
private final LocalConfiguration config;
private volatile Api api;
public LaMetricTimeLocalImpl(LocalConfiguration config)
{
this.config = config;
}
@Override
public Api getApi()
{
if (api == null)
{
synchronized (this)
{
if (api == null)
{
api = getClient().target(config.getBaseUri())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Api.class);
}
}
}
return api;
}
@Override
public Device getDevice()
{
return getClient().target(getApi().getEndpoints().getDeviceUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Device.class);
}
@Override
public String createNotification(Notification notification) throws NotificationCreationException
{
Response response = getClient().target(getApi().getEndpoints().getNotificationsUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.post(Entity.json(notification));
if (!Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily()))
{
throw new NotificationCreationException(response.readEntity(Failure.class));
}
try
{
return response.readEntity(NotificationResult.class).getSuccess().getId();
}
catch (Exception e)
{
throw new NotificationCreationException("Invalid JSON returned from service", e);
}
}
@Override
public List<Notification> getNotifications()
{
Response response = getClient().target(getApi().getEndpoints().getNotificationsUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.get();
// @formatter:off
return getGson().fromJson(response.readEntity(String.class),
new TypeToken<List<Notification>>(){}.getType());
// @formatter:on
}
@Override
public Notification getCurrentNotification()
{
Notification notification = getClient().target(getApi().getEndpoints()
.getCurrentNotificationUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Notification.class);
// when there is no current notification, return null
if (notification.getId() == null)
{
return null;
}
return notification;
}
@Override
public Notification getNotification(String id) throws NotificationNotFoundException
{
Response response = getClient().target(getApi().getEndpoints()
.getConcreteNotificationUrl()
.replace("{/:id}", "/" + id))
.request(MediaType.APPLICATION_JSON_TYPE)
.get();
if (!Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily()))
{
throw new NotificationNotFoundException(response.readEntity(Failure.class));
}
return response.readEntity(Notification.class);
}
@Override
public void deleteNotification(String id) throws NotificationNotFoundException
{
Response response = getClient().target(getApi().getEndpoints()
.getConcreteNotificationUrl()
.replace("{/:id}", "/" + id))
.request(MediaType.APPLICATION_JSON_TYPE)
.delete();
if (!Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily()))
{
throw new NotificationNotFoundException(response.readEntity(Failure.class));
}
response.close();
}
@Override
public Display getDisplay()
{
return getClient().target(getApi().getEndpoints().getDisplayUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Display.class);
}
@Override
public void updateDisplay(Display display) throws UpdateException
{
Response response = getClient().target(getApi().getEndpoints().getDisplayUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.put(Entity.json(display));
if (!Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily()))
{
throw new UpdateException(response.readEntity(Failure.class));
}
}
@Override
public Audio getAudio()
{
return getClient().target(getApi().getEndpoints().getAudioUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Audio.class);
}
@Override
public void updateAudio(Audio audio) throws UpdateException
{
Response response = getClient().target(getApi().getEndpoints().getAudioUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.put(Entity.json(audio));
if (!Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily()))
{
throw new UpdateException(response.readEntity(Failure.class));
}
}
@Override
public Bluetooth getBluetooth()
{
return getClient().target(getApi().getEndpoints().getBluetoothUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Bluetooth.class);
}
@Override
public void updateBluetooth(Bluetooth bluetooth) throws UpdateException
{
Response response = getClient().target(getApi().getEndpoints().getBluetoothUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.put(Entity.json(bluetooth));
if (!Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily()))
{
throw new UpdateException(response.readEntity(Failure.class));
}
}
@Override
public Wifi getWifi()
{
return getClient().target(getApi().getEndpoints().getWifiUrl())
.request(MediaType.APPLICATION_JSON_TYPE)
.get(Wifi.class);
}
@Override
public void updateApplication(String id,
String accessToken,
WidgetUpdates widgetUpdates) throws UpdateException
{
Response response = getClient().target(getApi().getEndpoints()
.getWidgetUpdateUrl()
.replace("{/:id}", "/" + id))
.request(MediaType.APPLICATION_JSON_TYPE)
.header(HEADER_ACCESS_TOKEN, accessToken)
.post(Entity.json(widgetUpdates));
if (!Status.Family.SUCCESSFUL.equals(response.getStatusInfo().getFamily()))
{
throw new UpdateException(response.readEntity(Failure.class));
}
}
@Override
protected Client createClient()
{
ClientBuilder builder = ClientBuilder.newBuilder();
// setup Gson (de)serialization
GsonProvider<Object> gsonProvider = new GsonProvider<>();
gsonProvider.setGson(getGson());
builder.register(gsonProvider);
// deal with unverifiable cert
if (config.isSecure())
{
try
{
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new TrustManager[] { new X509TrustManager()
{
@Override
public void checkClientTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException
{
// noop
}
@Override
public void checkServerTrusted(X509Certificate[] arg0,
String arg1) throws CertificateException
{
// noop
}
@Override
public X509Certificate[] getAcceptedIssuers()
{
return new X509Certificate[0];
}
} }, new java.security.SecureRandom());
builder.sslContext(sslcontext)
.hostnameVerifier((host, session) -> host.equals(config.getHost()));
}
catch (KeyManagementException | NoSuchAlgorithmException e)
{
throw new RuntimeException("Failed to setup secure communication", e);
}
}
// turn on logging if requested
if (config.isLogging())
{
builder.register(new LoggingFilter(Logger.getLogger(LaMetricTimeCloudImpl.class.getName()),
config.getLogMax()));
}
// setup basic auth
builder.register(HttpAuthenticationFeature.basic(config.getAuthUser(), config.getApiKey()));
return builder.build();
}
}
| Close response entities that are not read | src/main/java/org/syphr/lametrictime/api/local/impl/LaMetricTimeLocalImpl.java | Close response entities that are not read |
|
Java | apache-2.0 | 5c30c0cde28ffcad8b539e5099443735c75f8562 | 0 | dhatim/safesql,dhatim/safesql | package org.dhatim.safesql;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Stream;
public class SafeSqlBuilder implements SafeSqlizable {
static class Position {
private final int sqlPosition;
private final int paramPosition;
private Position(int sqlPosition, int paramPosition) {
this.sqlPosition = sqlPosition;
this.paramPosition = paramPosition;
}
}
private static final String DEFAULT_SEPARATOR = ", ";
protected final StringBuilder sql;
protected final List<Object> parameters;
public SafeSqlBuilder() {
this(new StringBuilder(), new ArrayList<>());
}
public SafeSqlBuilder(String query) {
this(new StringBuilder(query), new ArrayList<>());
}
public SafeSqlBuilder(SafeSqlBuilder other) {
this(new StringBuilder(other.sql), new ArrayList<>(other.parameters));
}
protected SafeSqlBuilder(StringBuilder stringBuilder, List<Object> parameters) {
// Without copy buffers
this.sql = stringBuilder;
this.parameters = parameters;
}
/**
* include integer parameter in SQL with a placeholder <b>?</b>
*
* @param num integer parameter
* @return a reference of this object
*/
public SafeSqlBuilder param(int num) {
appendObject(num);
return this;
}
/**
* include long parameter in SQL with a placeholder <b>?</b>
*
* @param num long parameter
* @return a reference of this object
*/
public SafeSqlBuilder param(long num) {
appendObject(num);
return this;
}
/**
* include double parameter in SQL with a placeholder <b>?</b>
*
* @param num double parameter
* @return a reference of this object
*/
public SafeSqlBuilder param(double num) {
appendObject(num);
return this;
}
/**
* include boolean parameter in SQL with a placeholder <b>?</b>
*
* @param bool boolean parameter
* @return a reference of this object
*/
public SafeSqlBuilder param(boolean bool) {
appendObject(bool);
return this;
}
/**
* include generic parameter in SQL with a placeholder <b>?</b>
*
* @param obj object parameter
* @return a reference of this object
*/
public SafeSqlBuilder param(Object obj) {
appendObject(obj);
return this;
}
/**
* include multiple parameters in SQL with placeholders <b>?</b>
*
* @param parameters list of parameter to include
* @return a reference of this object
*/
public SafeSqlBuilder params(Object... parameters) {
if (parameters.length == 1) {
param(parameters[0]);
} else if (parameters.length != 0) {
for (int i=0; i<parameters.length; i++) {
if (i > 0) {
append(DEFAULT_SEPARATOR);
}
param(parameters[i]);
}
}
return this;
}
/**
* include multiple parameters in SQL with placeholders <b>?</b>
*
* @param iterable {@link Iterable} of parameter to include
* @return a reference of this object
*/
public SafeSqlBuilder params(Iterable<?> iterable) {
paramsIterator(DEFAULT_SEPARATOR, iterable.iterator());
return this;
}
/**
* include multiple parameters in SQL with placeholders <b>?</b>
*
* @param stream stream of parameter to include
* @return a reference of this object
*/
public SafeSqlBuilder params(Stream<?> stream) {
paramsIterator(DEFAULT_SEPARATOR, stream.iterator());
return this;
}
private void paramsIterator(String delimiter, Iterator<?> iterator) {
boolean first = true;
while (iterator.hasNext()) {
if (first) {
first = false;
} else {
append(delimiter);
}
param(iterator.next());
}
}
private void paramsIterator(SafeSql delimiter, Iterator<?> iterator) {
boolean first = true;
while (iterator.hasNext()) {
if (first) {
first = false;
} else {
append(delimiter);
}
param(iterator.next());
}
}
@SafeVarargs
public final <T> SafeSqlBuilder array(String type, T... elements) {
appendObject(new PGArrayParameter(type, elements));
return this;
}
public <T> SafeSqlBuilder array(String type, Iterable<T> elements) {
appendObject(new PGArrayParameter(type, elements));
return this;
}
/**
* append a {@link SafeSql} to SQL
*
* @param s {@link SafeSql} to append to the final SQL
* @return a reference of this object
*/
public SafeSqlBuilder append(SafeSql s) {
sql.append(s.asSql());
Collections.addAll(parameters, s.getParameters());
return this;
}
public SafeSqlBuilder append(SafeSqlizable sqlizable) {
sqlizable.appendTo(this);
return this;
}
public SafeSqlBuilder append(String s) {
sql.append(s);
return this;
}
public SafeSqlBuilder append(char ch) {
sql.append(ch);
return this;
}
public SafeSqlBuilder append(int i) {
sql.append(i);
return this;
}
public SafeSqlBuilder append(long l) {
sql.append(l);
return this;
}
/**
* write a string literal by escaping
*
* @param s this string as literal string in SQL code
* @return a reference to this object.
*/
public SafeSqlBuilder literal(String s) {
sql.append(SafeSqlUtils.escapeString(s));
return this;
}
/**
* Appends a formatted sql string using the specified arguments.
*
* @param query string query with some <code>{}</code> argument place. The
* argument can have a number inside to force a argument index (start at 1).
* The escape sequence is <code>{{.*}}</code>.
* @param args arguments list
* @return a reference to this object.
*/
public SafeSqlBuilder format(String query, Object... args) {
SafeSqlUtils.formatTo(this, query, args);
return this;
}
public <E> SafeSqlBuilder joined(Iterable<E> iterable, Consumer<SafeSqlBuilder> delimiter, BiConsumer<SafeSqlBuilder, E> element) {
boolean first = true;
for (E e : iterable) {
if (first) {
first = false;
} else {
delimiter.accept(this);
}
element.accept(this, e);
}
return this;
}
public SafeSqlBuilder joined(String delimiter, Iterable<String> iterable) {
SafeSqlJoiner joiner = new SafeSqlJoiner(SafeSqlUtils.fromConstant(delimiter));
iterable.forEach(joiner::add);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joined(String delimiter, String prefix, String suffix, Iterable<String> iterable) {
SafeSqlJoiner joiner = new SafeSqlJoiner(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.fromConstant(prefix), SafeSqlUtils.fromConstant(suffix));
iterable.forEach(joiner::add);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joined(String delimiter, Stream<String> stream) {
SafeSqlJoiner joiner = stream.collect(() -> new SafeSqlJoiner(SafeSqlUtils.fromConstant(delimiter)),
SafeSqlJoiner::add, SafeSqlJoiner::merge);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joined(String delimiter, String prefix, String suffix, Stream<String> stream) {
SafeSqlJoiner joiner = stream.collect(() -> new SafeSqlJoiner(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.fromConstant(prefix), SafeSqlUtils.fromConstant(suffix)),
SafeSqlJoiner::add, SafeSqlJoiner::merge);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joinedSafeSqls(SafeSql delimiter, Iterable<SafeSql> iterable) {
return joinedSafeSqls(delimiter, SafeSqlUtils.EMPTY, SafeSqlUtils.EMPTY, iterable);
}
public SafeSqlBuilder joinedSafeSqls(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Iterable<SafeSql> iterable) {
SafeSqlJoiner joiner = new SafeSqlJoiner(delimiter, prefix, suffix);
iterable.forEach(joiner::add);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joinedSafeSqls(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Stream<SafeSql> stream) {
SafeSqlJoiner joiner = stream.collect(() -> new SafeSqlJoiner(delimiter, prefix, suffix), SafeSqlJoiner::add, SafeSqlJoiner::merge);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joinedSafeSqls(SafeSql delimiter, Stream<SafeSql> stream) {
return joinedSafeSqls(delimiter, SafeSqlUtils.EMPTY, SafeSqlUtils.EMPTY, stream);
}
public SafeSqlBuilder joinedSafeSqls(String delimiter, Iterable<SafeSql> iterable) {
return joinedSafeSqls(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.EMPTY, SafeSqlUtils.EMPTY, iterable);
}
public SafeSqlBuilder joinedSafeSqls(String delimiter, Stream<SafeSql> stream) {
return joinedSafeSqls(delimiter, "", "", stream);
}
public SafeSqlBuilder joinedSafeSqls(String delimiter, String prefix, String suffix, Iterable<SafeSql> iterable) {
return joinedSafeSqls(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.fromConstant(prefix), SafeSqlUtils.fromConstant(suffix), iterable);
}
public SafeSqlBuilder joinedSafeSqls(String delimiter, String prefix, String suffix, Stream<SafeSql> stream) {
return joinedSafeSqls(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.fromConstant(prefix), SafeSqlUtils.fromConstant(suffix), stream);
}
public SafeSqlBuilder joinedSqlizables(SafeSql delimiter, Iterable<? extends SafeSqlizable> iterable) {
return joinedSqlizables(delimiter, SafeSqlUtils.EMPTY, SafeSqlUtils.EMPTY, iterable);
}
public SafeSqlBuilder joinedSqlizables(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Iterable<? extends SafeSqlizable> iterable) {
SafeSqlJoiner joiner = new SafeSqlJoiner(delimiter, prefix, suffix);
iterable.forEach(joiner::add);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joinedSqlizables(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Stream<? extends SafeSqlizable> stream) {
SafeSqlJoiner joiner = stream.collect(() -> new SafeSqlJoiner(delimiter, prefix, suffix), SafeSqlJoiner::add, SafeSqlJoiner::merge);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joinedSqlizables(SafeSql delimiter, Stream<? extends SafeSqlizable> stream) {
return joinedSqlizables(delimiter, SafeSqlUtils.EMPTY, SafeSqlUtils.EMPTY, stream);
}
public SafeSqlBuilder joinedSqlizables(String delimiter, Iterable<? extends SafeSqlizable> iterable) {
return joinedSqlizables(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.EMPTY, SafeSqlUtils.EMPTY, iterable);
}
public SafeSqlBuilder joinedSqlizables(String delimiter, Stream<? extends SafeSqlizable> stream) {
return joinedSqlizables(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.EMPTY, SafeSqlUtils.EMPTY, stream);
}
public SafeSqlBuilder joinedSqlizables(String delimiter, String prefix, String suffix, Iterable<? extends SafeSqlizable> iterable) {
return joinedSqlizables(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.fromConstant(prefix), SafeSqlUtils.fromConstant(suffix), iterable);
}
public SafeSqlBuilder joinedSqlizables(String delimiter, String prefix, String suffix, Stream<? extends SafeSqlizable> stream) {
return joinedSqlizables(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.fromConstant(prefix), SafeSqlUtils.fromConstant(suffix), stream);
}
/**
* Write a byte array as literal in PostgreSQL
*
* @param bytes bytes to write as literal
* @return a reference to this object.
*/
public SafeSqlBuilder literal(byte[] bytes) {
sql.append("'\\x");
ArraySupport.appendHexBytes(sql, bytes);
sql.append('\'');
return this;
}
public SafeSqlBuilder identifier(String identifier) {
sql.append(SafeSqlUtils.mayEscapeIdentifier(identifier));
return this;
}
public SafeSqlBuilder identifier(String container, String identifier) {
if (null == container) {
return identifier(identifier);
} else {
sql.append(SafeSqlUtils.mayEscapeIdentifier(container)).append('.').append(SafeSqlUtils.mayEscapeIdentifier(identifier));
return this;
}
}
protected final String mayEscapeIdentifier(String identifier) {
return SafeSqlUtils.mayEscapeIdentifier(identifier);
}
/**
* @deprecated Use {@link #literal(String)} instead.
*/
@Deprecated
public SafeSqlBuilder appendStringLiteral(String s) {
return literal(s);
}
/**
* @deprecated Use {@link #format(String, Object...)} instead.
*/
@Deprecated
public SafeSqlBuilder appendFormat(String sql, Object... args) {
return format(sql, args);
}
/**
* @deprecated Use {@link #joinedSafeSqls(String, Iterable)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(String delimiter, Collection<? extends SafeSqlizable> collection) {
return joinedSqlizables(delimiter, collection);
}
/**
* @deprecated Use {@link #joinedSafeSqls(String, String, String, Iterable)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(String delimiter, String prefix, String suffix, Collection<? extends SafeSqlizable> collection) {
return joinedSqlizables(delimiter, prefix, suffix, collection);
}
/**
* @deprecated Use {@link #joinedSafeSqls(String, Stream)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(String delimiter, Stream<? extends SafeSqlizable> stream) {
return joinedSqlizables(delimiter, stream);
}
/**
* @deprecated Use {@link #joinedSafeSqls(String, String, String, Stream)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(String delimiter, String prefix, String suffix, Stream<? extends SafeSqlizable> stream) {
return joinedSqlizables(delimiter, prefix, suffix, stream);
}
/**
* @deprecated Use {@link #joinedSafeSqls(SafeSql, Iterable)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(SafeSql delimiter, Collection<? extends SafeSqlizable> collection) {
return joinedSqlizables(delimiter, collection);
}
/**
* @deprecated Use {@link #joinedSafeSqls(SafeSql, SafeSql, SafeSql, Iterable)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Collection<? extends SafeSqlizable> collection) {
return joinedSqlizables(delimiter, prefix, suffix, collection);
}
/**
* @deprecated Use {@link #joinedSafeSqls(SafeSql, Stream)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(SafeSql delimiter, Stream<? extends SafeSqlizable> stream) {
return joinedSqlizables(delimiter, stream);
}
/**
* @deprecated Use {@link #joinedSafeSqls(SafeSql, SafeSql, SafeSql, Stream)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Stream<? extends SafeSqlizable> stream) {
return joinedSqlizables(delimiter, prefix, suffix, stream);
}
/**
* @deprecated Use {@link #literal(byte[])} instead.
*/
@Deprecated
public SafeSqlBuilder appendByteLiteral(byte[] bytes) {
return literal(bytes);
}
/**
* @deprecated Use {@link #identifier(String)} instead.
*/
@Deprecated
public SafeSqlBuilder appendIdentifier(String identifier) {
return identifier(identifier);
}
/**
* @deprecated Use {@link #identifier(String, String)} instead.
*/
@Deprecated
public SafeSqlBuilder appendIdentifier(String container, String identifier) {
return identifier(container, identifier);
}
@Deprecated
public SafeSqlBuilder params(String delimiter, Collection<?> collection) {
paramsIterator(delimiter, collection.iterator());
return this;
}
@Deprecated
public SafeSqlBuilder params(String delimiter, String prefix, String suffix, Collection<?> collection) {
append(prefix);
paramsIterator(delimiter, collection.iterator());
append(suffix);
return this;
}
@Deprecated
public SafeSqlBuilder params(String delimiter, Stream<?> stream) {
paramsIterator(delimiter, stream.iterator());
return this;
}
@Deprecated
public SafeSqlBuilder params(String delimiter, String prefix, String suffix, Stream<?> stream) {
append(prefix);
paramsIterator(delimiter, stream.iterator());
append(suffix);
return this;
}
@Deprecated
public SafeSqlBuilder params(SafeSql delimiter, Collection<?> collection) {
paramsIterator(delimiter, collection.iterator());
return this;
}
@Deprecated
public SafeSqlBuilder params(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Collection<?> collection) {
append(prefix);
paramsIterator(delimiter, collection.iterator());
append(suffix);
return this;
}
@Deprecated
public SafeSqlBuilder params(SafeSql delimiter, Stream<?> stream) {
paramsIterator(delimiter, stream.iterator());
return this;
}
@Deprecated
public SafeSqlBuilder params(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Stream<?> stream) {
append(prefix);
paramsIterator(delimiter, stream.iterator());
append(suffix);
return this;
}
@Override
public SafeSql toSafeSql() {
return new SafeSqlImpl(asSql(), getParameters());
}
@Override
public void appendTo(SafeSqlBuilder builder) {
builder.sql.append(sql);
builder.parameters.addAll(parameters);
}
/**
* Returns {@code true} if this builder contains no sql and no parameters.
*
* @return {@code true} if this builder contains no sql and no parameters
*/
public boolean isEmpty() {
return sql.length() == 0 && parameters.isEmpty();
}
protected String asSql() {
return sql.toString();
}
protected Object[] getParameters() {
return parameters.toArray();
}
private void appendObject(Object o) {
sql.append('?');
parameters.add(o);
}
Position getLength() {
return new Position(sql.length(), parameters.size());
}
void setLength(Position position) {
sql.setLength(position.sqlPosition);
int currentSize = parameters.size();
if (position.paramPosition < currentSize) {
parameters.subList(position.paramPosition, currentSize).clear();
}
}
void append(SafeSqlBuilder other, Position after) {
sql.append(other.sql, after.sqlPosition, other.sql.length());
int afterLength = after.paramPosition;
parameters.addAll(other.parameters.subList(afterLength, other.parameters.size() - afterLength));
}
static Position getLength(SafeSql sql) {
return new Position(sql.asSql().length(), sql.getParameters().length);
}
}
| safesql/src/main/java/org/dhatim/safesql/SafeSqlBuilder.java | package org.dhatim.safesql;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Stream;
public class SafeSqlBuilder implements SafeSqlizable {
static class Position {
private final int sqlPosition;
private final int paramPosition;
private Position(int sqlPosition, int paramPosition) {
this.sqlPosition = sqlPosition;
this.paramPosition = paramPosition;
}
}
private static final String DEFAULT_SEPARATOR = ", ";
protected final StringBuilder sql;
protected final List<Object> parameters;
public SafeSqlBuilder() {
this(new StringBuilder(), new ArrayList<>());
}
public SafeSqlBuilder(String query) {
this(new StringBuilder(query), new ArrayList<>());
}
public SafeSqlBuilder(SafeSqlBuilder other) {
this(new StringBuilder(other.sql), new ArrayList<>(other.parameters));
}
protected SafeSqlBuilder(StringBuilder stringBuilder, List<Object> parameters) {
// Without copy buffers
this.sql = stringBuilder;
this.parameters = parameters;
}
/**
* include integer parameter in SQL with a placeholder <b>?</b>
*
* @param num integer parameter
* @return a reference of this object
*/
public SafeSqlBuilder param(int num) {
appendObject(num);
return this;
}
/**
* include long parameter in SQL with a placeholder <b>?</b>
*
* @param num long parameter
* @return a reference of this object
*/
public SafeSqlBuilder param(long num) {
appendObject(num);
return this;
}
/**
* include double parameter in SQL with a placeholder <b>?</b>
*
* @param num double parameter
* @return a reference of this object
*/
public SafeSqlBuilder param(double num) {
appendObject(num);
return this;
}
/**
* include boolean parameter in SQL with a placeholder <b>?</b>
*
* @param bool boolean parameter
* @return a reference of this object
*/
public SafeSqlBuilder param(boolean bool) {
appendObject(bool);
return this;
}
/**
* include generic parameter in SQL with a placeholder <b>?</b>
*
* @param obj object parameter
* @return a reference of this object
*/
public SafeSqlBuilder param(Object obj) {
appendObject(obj);
return this;
}
/**
* include multiple parameters in SQL with placeholders <b>?</b>
*
* @param parameters list of parameter to include
* @return a reference of this object
*/
public SafeSqlBuilder params(Object... parameters) {
if (parameters.length == 1) {
param(parameters[0]);
} else if (parameters.length != 0) {
for (int i=0; i<parameters.length; i++) {
if (i > 0) {
append(DEFAULT_SEPARATOR);
}
param(parameters[i]);
}
}
return this;
}
/**
* include multiple parameters in SQL with placeholders <b>?</b>
*
* @param iterable {@link Iterable} of parameter to include
* @return a reference of this object
*/
public SafeSqlBuilder params(Iterable<?> iterable) {
paramsIterator(DEFAULT_SEPARATOR, iterable.iterator());
return this;
}
/**
* include multiple parameters in SQL with placeholders <b>?</b>
*
* @param stream stream of parameter to include
* @return a reference of this object
*/
public SafeSqlBuilder params(Stream<?> stream) {
paramsIterator(DEFAULT_SEPARATOR, stream.iterator());
return this;
}
private void paramsIterator(String delimiter, Iterator<?> iterator) {
boolean first = true;
while (iterator.hasNext()) {
if (first) {
first = false;
} else {
append(delimiter);
}
param(iterator.next());
}
}
private void paramsIterator(SafeSql delimiter, Iterator<?> iterator) {
boolean first = true;
while (iterator.hasNext()) {
if (first) {
first = false;
} else {
append(delimiter);
}
param(iterator.next());
}
}
@SafeVarargs
public final <T> SafeSqlBuilder array(String type, T... elements) {
appendObject(new PGArrayParameter(type, elements));
return this;
}
public <T> SafeSqlBuilder array(String type, Iterable<T> elements) {
appendObject(new PGArrayParameter(type, elements));
return this;
}
/**
* append a {@link SafeSql} to SQL
*
* @param s {@link SafeSql} to append to the final SQL
* @return a reference of this object
*/
public SafeSqlBuilder append(SafeSql s) {
sql.append(s.asSql());
Collections.addAll(parameters, s.getParameters());
return this;
}
public SafeSqlBuilder append(SafeSqlizable sqlizable) {
sqlizable.appendTo(this);
return this;
}
public SafeSqlBuilder append(String s) {
sql.append(s);
return this;
}
public SafeSqlBuilder append(char ch) {
sql.append(ch);
return this;
}
public SafeSqlBuilder append(int i) {
sql.append(i);
return this;
}
public SafeSqlBuilder append(long l) {
sql.append(l);
return this;
}
/**
* write a string literal by escaping
*
* @param s this string as literal string in SQL code
* @return a reference to this object.
*/
public SafeSqlBuilder literal(String s) {
sql.append(SafeSqlUtils.escapeString(s));
return this;
}
/**
* Appends a formatted sql string using the specified arguments.
*
* @param query string query with some <code>{}</code> argument place. The
* argument can have a number inside to force a argument index (start at 1).
* The escape sequence is <code>{{.*}}</code>.
* @param args arguments list
* @return a reference to this object.
*/
public SafeSqlBuilder format(String query, Object... args) {
SafeSqlUtils.formatTo(this, query, args);
return this;
}
public <E> SafeSqlBuilder joined(Iterable<E> iterable, Consumer<SafeSqlBuilder> delimiter, BiConsumer<SafeSqlBuilder, E> element) {
boolean first = true;
for (E e : iterable) {
if (first) {
first = false;
} else {
delimiter.accept(this);
}
element.accept(this, e);
}
return this;
}
public SafeSqlBuilder joined(String delimiter, Iterable<String> iterable) {
SafeSqlJoiner joiner = new SafeSqlJoiner(SafeSqlUtils.fromConstant(delimiter));
iterable.forEach(joiner::add);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joined(String delimiter, String prefix, String suffix, Iterable<String> iterable) {
SafeSqlJoiner joiner = new SafeSqlJoiner(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.fromConstant(prefix), SafeSqlUtils.fromConstant(suffix));
iterable.forEach(joiner::add);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joined(String delimiter, Stream<String> stream) {
SafeSqlJoiner joiner = stream.collect(() -> new SafeSqlJoiner(SafeSqlUtils.fromConstant(delimiter)),
SafeSqlJoiner::add, SafeSqlJoiner::merge);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joined(String delimiter, String prefix, String suffix, Stream<String> stream) {
SafeSqlJoiner joiner = stream.collect(() -> new SafeSqlJoiner(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.fromConstant(prefix), SafeSqlUtils.fromConstant(suffix)),
SafeSqlJoiner::add, SafeSqlJoiner::merge);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joinedSafeSqls(SafeSql delimiter, Iterable<SafeSql> iterable) {
return joinedSafeSqls(delimiter, SafeSqlUtils.EMPTY, SafeSqlUtils.EMPTY, iterable);
}
public SafeSqlBuilder joinedSafeSqls(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Iterable<SafeSql> iterable) {
SafeSqlJoiner joiner = new SafeSqlJoiner(delimiter, prefix, suffix);
iterable.forEach(joiner::add);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joinedSafeSqls(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Stream<SafeSql> stream) {
SafeSqlJoiner joiner = stream.collect(() -> new SafeSqlJoiner(delimiter, prefix, suffix), SafeSqlJoiner::add, SafeSqlJoiner::merge);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joinedSafeSqls(SafeSql delimiter, Stream<SafeSql> stream) {
return joinedSafeSqls(delimiter, SafeSqlUtils.EMPTY, SafeSqlUtils.EMPTY, stream);
}
public SafeSqlBuilder joinedSafeSqls(String delimiter, Iterable<SafeSql> iterable) {
return joinedSafeSqls(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.EMPTY, SafeSqlUtils.EMPTY, iterable);
}
public SafeSqlBuilder joinedSafeSqls(String delimiter, Stream<SafeSql> stream) {
return joinedSafeSqls(delimiter, "", "", stream);
}
public SafeSqlBuilder joinedSafeSqls(String delimiter, String prefix, String suffix, Iterable<SafeSql> iterable) {
return joinedSafeSqls(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.fromConstant(prefix), SafeSqlUtils.fromConstant(suffix), iterable);
}
public SafeSqlBuilder joinedSafeSqls(String delimiter, String prefix, String suffix, Stream<SafeSql> stream) {
return joinedSafeSqls(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.fromConstant(prefix), SafeSqlUtils.fromConstant(suffix), stream);
}
public SafeSqlBuilder joinedSqlizables(SafeSql delimiter, Iterable<? extends SafeSqlizable> iterable) {
return joinedSqlizables(delimiter, SafeSqlUtils.EMPTY, SafeSqlUtils.EMPTY, iterable);
}
public SafeSqlBuilder joinedSqlizables(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Iterable<? extends SafeSqlizable> iterable) {
SafeSqlJoiner joiner = new SafeSqlJoiner(delimiter, prefix, suffix);
iterable.forEach(joiner::add);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joinedSqlizables(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Stream<? extends SafeSqlizable> stream) {
SafeSqlJoiner joiner = stream.collect(() -> new SafeSqlJoiner(delimiter, prefix, suffix), SafeSqlJoiner::add, SafeSqlJoiner::merge);
joiner.appendTo(this);
return this;
}
public SafeSqlBuilder joinedSqlizables(SafeSql delimiter, Stream<? extends SafeSqlizable> stream) {
return joinedSqlizables(delimiter, SafeSqlUtils.EMPTY, SafeSqlUtils.EMPTY, stream);
}
public SafeSqlBuilder joinedSqlizables(String delimiter, Iterable<? extends SafeSqlizable> iterable) {
return joinedSqlizables(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.EMPTY, SafeSqlUtils.EMPTY, iterable);
}
public SafeSqlBuilder joinedSqlizables(String delimiter, Stream<? extends SafeSqlizable> stream) {
return joinedSqlizables(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.EMPTY, SafeSqlUtils.EMPTY, stream);
}
public SafeSqlBuilder joinedSqlizables(String delimiter, String prefix, String suffix, Iterable<? extends SafeSqlizable> iterable) {
return joinedSqlizables(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.fromConstant(prefix), SafeSqlUtils.fromConstant(suffix), iterable);
}
public SafeSqlBuilder joinedSqlizables(String delimiter, String prefix, String suffix, Stream<? extends SafeSqlizable> stream) {
return joinedSqlizables(SafeSqlUtils.fromConstant(delimiter), SafeSqlUtils.fromConstant(prefix), SafeSqlUtils.fromConstant(suffix), stream);
}
/**
* Write a byte array as literal in PostgreSQL
*
* @param bytes bytes to write as literal
* @return a reference to this object.
*/
public SafeSqlBuilder literal(byte[] bytes) {
sql.append("'\\x");
ArraySupport.appendHexBytes(sql, bytes);
sql.append('\'');
return this;
}
public SafeSqlBuilder identifier(String identifier) {
sql.append(SafeSqlUtils.mayEscapeIdentifier(identifier));
return this;
}
public SafeSqlBuilder identifier(String container, String identifier) {
if (null == container) {
return identifier(identifier);
} else {
sql.append(SafeSqlUtils.mayEscapeIdentifier(container)).append('.').append(SafeSqlUtils.mayEscapeIdentifier(identifier));
return this;
}
}
protected final String mayEscapeIdentifier(String identifier) {
return SafeSqlUtils.mayEscapeIdentifier(identifier);
}
/**
* @deprecated Use {@link #literal(String)} instead.
*/
@Deprecated
public SafeSqlBuilder appendStringLiteral(String s) {
return literal(s);
}
/**
* @deprecated Use {@link #format(String, Object...)} instead.
*/
@Deprecated
public SafeSqlBuilder appendFormat(String sql, Object... args) {
return format(sql, args);
}
/**
* @deprecated Use {@link #joinedSafeSqls(String, Iterable)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(String delimiter, Collection<? extends SafeSqlizable> collection) {
return joinedSqlizables(delimiter, collection);
}
/**
* @deprecated Use {@link #joinedSafeSqls(String, String, String, Iterable)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(String delimiter, String prefix, String suffix, Collection<? extends SafeSqlizable> collection) {
return joinedSqlizables(delimiter, prefix, suffix, collection);
}
/**
* @deprecated Use {@link #joinedSafeSqls(String, Stream)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(String delimiter, Stream<? extends SafeSqlizable> stream) {
return joinedSqlizables(delimiter, stream);
}
/**
* @deprecated Use {@link #joinedSafeSqls(String, String, String, Stream)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(String delimiter, String prefix, String suffix, Stream<? extends SafeSqlizable> stream) {
return joinedSqlizables(delimiter, prefix, suffix, stream);
}
/**
* @deprecated Use {@link #joinedSafeSqls(SafeSql, Iterable)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(SafeSql delimiter, Collection<? extends SafeSqlizable> collection) {
return joinedSqlizables(delimiter, collection);
}
/**
* @deprecated Use {@link #joinedSafeSqls(SafeSql, SafeSql, SafeSql, Iterable)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Collection<? extends SafeSqlizable> collection) {
return joinedSqlizables(delimiter, prefix, suffix, collection);
}
/**
* @deprecated Use {@link #joinedSafeSqls(SafeSql, Stream)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(SafeSql delimiter, Stream<? extends SafeSqlizable> stream) {
return joinedSqlizables(delimiter, stream);
}
/**
* @deprecated Use {@link #joinedSafeSqls(SafeSql, SafeSql, SafeSql, Stream)} instead
*/
@Deprecated
public SafeSqlBuilder appendJoined(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Stream<? extends SafeSqlizable> stream) {
return joinedSqlizables(delimiter, prefix, suffix, stream);
}
/**
* @deprecated Use {@link #literal(byte[])} instead.
*/
@Deprecated
public SafeSqlBuilder appendByteLiteral(byte[] bytes) {
return literal(bytes);
}
/**
* @deprecated Use {@link #identifier(String)} instead.
*/
@Deprecated
public SafeSqlBuilder appendIdentifier(String identifier) {
return identifier(identifier);
}
/**
* @deprecated Use {@link #identifier(String, String)} instead.
*/
@Deprecated
public SafeSqlBuilder appendIdentifier(String container, String identifier) {
return identifier(container, identifier);
}
@Deprecated
public SafeSqlBuilder params(String delimiter, Collection<?> collection) {
paramsIterator(delimiter, collection.iterator());
return this;
}
@Deprecated
public SafeSqlBuilder params(String delimiter, String prefix, String suffix, Collection<?> collection) {
append(prefix);
paramsIterator(delimiter, collection.iterator());
append(suffix);
return this;
}
@Deprecated
public SafeSqlBuilder params(String delimiter, Stream<?> stream) {
paramsIterator(delimiter, stream.iterator());
return this;
}
@Deprecated
public SafeSqlBuilder params(String delimiter, String prefix, String suffix, Stream<?> stream) {
append(prefix);
paramsIterator(delimiter, stream.iterator());
append(suffix);
return this;
}
@Deprecated
public SafeSqlBuilder params(SafeSql delimiter, Collection<?> collection) {
paramsIterator(delimiter, collection.iterator());
return this;
}
@Deprecated
public SafeSqlBuilder params(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Collection<?> collection) {
append(prefix);
paramsIterator(delimiter, collection.iterator());
append(suffix);
return this;
}
@Deprecated
public SafeSqlBuilder params(SafeSql delimiter, Stream<?> stream) {
paramsIterator(delimiter, stream.iterator());
return this;
}
@Deprecated
public SafeSqlBuilder params(SafeSql delimiter, SafeSql prefix, SafeSql suffix, Stream<?> stream) {
append(prefix);
paramsIterator(delimiter, stream.iterator());
append(suffix);
return this;
}
@Override
public SafeSql toSafeSql() {
return new SafeSqlImpl(asSql(), getParameters());
}
@Override
public void appendTo(SafeSqlBuilder builder) {
builder.sql.append(sql);
builder.parameters.addAll(parameters);
}
/**
* Returns <tt>true</tt> if this builder contains no sql and no parameters.
*
* @return <tt>true</tt> if this builder contains no sql and no parameters
*/
public boolean isEmpty() {
return sql.length() == 0 && parameters.isEmpty();
}
protected String asSql() {
return sql.toString();
}
protected Object[] getParameters() {
return parameters.toArray();
}
private void appendObject(Object o) {
sql.append('?');
parameters.add(o);
}
Position getLength() {
return new Position(sql.length(), parameters.size());
}
void setLength(Position position) {
sql.setLength(position.sqlPosition);
int currentSize = parameters.size();
if (position.paramPosition < currentSize) {
parameters.subList(position.paramPosition, currentSize).clear();
}
}
void append(SafeSqlBuilder other, Position after) {
sql.append(other.sql, after.sqlPosition, other.sql.length());
int afterLength = after.paramPosition;
parameters.addAll(other.parameters.subList(afterLength, other.parameters.size() - afterLength));
}
static Position getLength(SafeSql sql) {
return new Position(sql.asSql().length(), sql.getParameters().length);
}
}
| Fix javadoc
| safesql/src/main/java/org/dhatim/safesql/SafeSqlBuilder.java | Fix javadoc |
|
Java | apache-2.0 | df7da60a9a2e130bf1a204b71d2fe3d9cf374228 | 0 | holmes/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,MichaelNedzelsky/intellij-community,semonte/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,supersven/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,vvv1559/intellij-community,samthor/intellij-community,da1z/intellij-community,diorcety/intellij-community,suncycheng/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,holmes/intellij-community,kool79/intellij-community,da1z/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,wreckJ/intellij-community,samthor/intellij-community,robovm/robovm-studio,orekyuu/intellij-community,allotria/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,jexp/idea2,ol-loginov/intellij-community,apixandru/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,da1z/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,fitermay/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,ernestp/consulo,caot/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,izonder/intellij-community,xfournet/intellij-community,signed/intellij-community,lucafavatella/intellij-community,consulo/consulo,idea4bsd/idea4bsd,idea4bsd/idea4bsd,allotria/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,retomerz/intellij-community,slisson/intellij-community,supersven/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,Lekanich/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,wreckJ/intellij-community,blademainer/intellij-community,jagguli/intellij-community,amith01994/intellij-community,ahb0327/intellij-community,blademainer/intellij-community,clumsy/intellij-community,ryano144/intellij-community,semonte/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,asedunov/intellij-community,fitermay/intellij-community,jexp/idea2,wreckJ/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,signed/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,muntasirsyed/intellij-community,retomerz/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,FHannes/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,apixandru/intellij-community,signed/intellij-community,petteyg/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,petteyg/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,allotria/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,vvv1559/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,signed/intellij-community,suncycheng/intellij-community,samthor/intellij-community,signed/intellij-community,joewalnes/idea-community,ibinti/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,pwoodworth/intellij-community,petteyg/intellij-community,izonder/intellij-community,vvv1559/intellij-community,fnouama/intellij-community,fitermay/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,petteyg/intellij-community,amith01994/intellij-community,diorcety/intellij-community,blademainer/intellij-community,izonder/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,signed/intellij-community,semonte/intellij-community,jagguli/intellij-community,signed/intellij-community,caot/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,samthor/intellij-community,diorcety/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,jagguli/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,joewalnes/idea-community,diorcety/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,samthor/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,kdwink/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,semonte/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,kool79/intellij-community,vladmm/intellij-community,clumsy/intellij-community,ibinti/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,xfournet/intellij-community,holmes/intellij-community,ernestp/consulo,joewalnes/idea-community,fitermay/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,vvv1559/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,slisson/intellij-community,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,FHannes/intellij-community,signed/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,vladmm/intellij-community,jexp/idea2,fitermay/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,kool79/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,apixandru/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,allotria/intellij-community,caot/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,vladmm/intellij-community,consulo/consulo,mglukhikh/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,caot/intellij-community,fitermay/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,slisson/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,da1z/intellij-community,hurricup/intellij-community,asedunov/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,clumsy/intellij-community,salguarnieri/intellij-community,Distrotech/intellij-community,joewalnes/idea-community,ahb0327/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,supersven/intellij-community,holmes/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,signed/intellij-community,Distrotech/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,FHannes/intellij-community,holmes/intellij-community,nicolargo/intellij-community,slisson/intellij-community,Distrotech/intellij-community,asedunov/intellij-community,da1z/intellij-community,asedunov/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,ibinti/intellij-community,ernestp/consulo,jagguli/intellij-community,holmes/intellij-community,caot/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,holmes/intellij-community,joewalnes/idea-community,pwoodworth/intellij-community,adedayo/intellij-community,FHannes/intellij-community,supersven/intellij-community,caot/intellij-community,vladmm/intellij-community,kool79/intellij-community,jexp/idea2,vladmm/intellij-community,gnuhub/intellij-community,TangHao1987/intellij-community,apixandru/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,allotria/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,jagguli/intellij-community,petteyg/intellij-community,youdonghai/intellij-community,amith01994/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,hurricup/intellij-community,semonte/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,retomerz/intellij-community,blademainer/intellij-community,dslomov/intellij-community,vladmm/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,signed/intellij-community,wreckJ/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,robovm/robovm-studio,youdonghai/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,allotria/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,ibinti/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,retomerz/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,izonder/intellij-community,blademainer/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,izonder/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,vvv1559/intellij-community,samthor/intellij-community,signed/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,ibinti/intellij-community,ernestp/consulo,robovm/robovm-studio,orekyuu/intellij-community,consulo/consulo,xfournet/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,allotria/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,clumsy/intellij-community,signed/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,semonte/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,kool79/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,supersven/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,fnouama/intellij-community,apixandru/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,jagguli/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,TangHao1987/intellij-community,clumsy/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,SerCeMan/intellij-community,SerCeMan/intellij-community,tmpgit/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,supersven/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,joewalnes/idea-community,hurricup/intellij-community,dslomov/intellij-community,allotria/intellij-community,hurricup/intellij-community,adedayo/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,slisson/intellij-community,caot/intellij-community,petteyg/intellij-community,lucafavatella/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,nicolargo/intellij-community,dslomov/intellij-community,fitermay/intellij-community,apixandru/intellij-community,retomerz/intellij-community,consulo/consulo,SerCeMan/intellij-community,holmes/intellij-community,xfournet/intellij-community,retomerz/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,Lekanich/intellij-community,amith01994/intellij-community,ernestp/consulo,semonte/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,clumsy/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,clumsy/intellij-community,ibinti/intellij-community,adedayo/intellij-community,ibinti/intellij-community,dslomov/intellij-community,dslomov/intellij-community,gnuhub/intellij-community,semonte/intellij-community,samthor/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,jexp/idea2,xfournet/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,SerCeMan/intellij-community,caot/intellij-community,izonder/intellij-community,slisson/intellij-community,blademainer/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,semonte/intellij-community,caot/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,consulo/consulo,nicolargo/intellij-community,jexp/idea2,ibinti/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,kool79/intellij-community,blademainer/intellij-community,robovm/robovm-studio,FHannes/intellij-community,hurricup/intellij-community,izonder/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,blademainer/intellij-community,diorcety/intellij-community,holmes/intellij-community,apixandru/intellij-community,vladmm/intellij-community,consulo/consulo,samthor/intellij-community,jexp/idea2,gnuhub/intellij-community,hurricup/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,izonder/intellij-community,holmes/intellij-community,ernestp/consulo,SerCeMan/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,jexp/idea2,fitermay/intellij-community,slisson/intellij-community,slisson/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,supersven/intellij-community,robovm/robovm-studio,dslomov/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,joewalnes/idea-community,alphafoobar/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,asedunov/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,da1z/intellij-community,samthor/intellij-community,ryano144/intellij-community,joewalnes/idea-community,vvv1559/intellij-community | package com.intellij.psi.impl.search;
import com.intellij.concurrency.JobUtil;
import com.intellij.ide.todo.TodoConfiguration;
import com.intellij.lang.LanguageParserDefinitions;
import com.intellij.lang.ParserDefinition;
import com.intellij.lang.properties.psi.Property;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.impl.ProgressManagerImpl;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.search.*;
import com.intellij.psi.search.searches.AllClassesSearch;
import com.intellij.psi.search.searches.IndexPatternSearch;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Processor;
import com.intellij.util.text.StringSearcher;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class PsiSearchHelperImpl implements PsiSearchHelper {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.search.PsiSearchHelperImpl");
private final PsiManagerEx myManager;
private static final TodoItem[] EMPTY_TODO_ITEMS = new TodoItem[0];
static {
ReferencesSearch.INSTANCE.registerExecutor(new CachesBasedRefSearcher());
ReferencesSearch.INSTANCE.registerExecutor(new PsiAnnotationMethodReferencesSearcher());
ReferencesSearch.INSTANCE.registerExecutor(new ConstructorReferencesSearcher());
ReferencesSearch.INSTANCE.registerExecutor(new SimpleAccessorReferenceSearcher());
ReferencesSearch.INSTANCE.registerExecutor(new PropertyReferenceViaLastWordSearcher());
AllClassesSearch.INSTANCE.registerExecutor(new AllClassesSearchExecutor());
IndexPatternSearch.INDEX_PATTERN_SEARCH_INSTANCE = new IndexPatternSearchImpl();
}
@NotNull
public SearchScope getUseScope(@NotNull PsiElement element) {
final GlobalSearchScope maximalUseScope = myManager.getFileManager().getUseScope(element);
if (element instanceof PsiPackage) {
return maximalUseScope;
}
else if (element instanceof PsiClass) {
if (element instanceof PsiAnonymousClass) {
return new LocalSearchScope(element);
}
PsiFile file = element.getContainingFile();
if (PsiUtil.isInJspFile(file)) return maximalUseScope;
PsiClass aClass = (PsiClass)element;
final PsiClass containingClass = aClass.getContainingClass();
if (aClass.hasModifierProperty(PsiModifier.PUBLIC)) {
return containingClass != null ? containingClass.getUseScope() : maximalUseScope;
}
else if (aClass.hasModifierProperty(PsiModifier.PROTECTED)) {
return containingClass != null ? containingClass.getUseScope() : maximalUseScope;
}
else if (aClass.hasModifierProperty(PsiModifier.PRIVATE) || aClass instanceof PsiTypeParameter) {
PsiClass topClass = PsiUtil.getTopLevelClass(aClass);
return new LocalSearchScope(topClass == null ? aClass.getContainingFile() : topClass);
}
else {
PsiPackage aPackage = null;
if (file instanceof PsiJavaFile) {
aPackage = JavaPsiFacade.getInstance(element.getManager().getProject()).findPackage(((PsiJavaFile)file).getPackageName());
}
if (aPackage == null) {
PsiDirectory dir = file.getContainingDirectory();
if (dir != null) {
aPackage = JavaDirectoryService.getInstance().getPackage(dir);
}
}
if (aPackage != null) {
SearchScope scope = GlobalSearchScope.packageScope(aPackage, false);
scope = scope.intersectWith(maximalUseScope);
return scope;
}
return new LocalSearchScope(file);
}
}
else if (element instanceof PsiMethod || element instanceof PsiField) {
PsiMember member = (PsiMember) element;
PsiFile file = element.getContainingFile();
if (PsiUtil.isInJspFile(file)) return maximalUseScope;
PsiClass aClass = member.getContainingClass();
if (aClass instanceof PsiAnonymousClass) {
//member from anonymous class can be called from outside the class
PsiElement methodCallExpr = PsiTreeUtil.getParentOfType(aClass, PsiMethodCallExpression.class);
return new LocalSearchScope(methodCallExpr != null ? methodCallExpr : aClass);
}
if (member.hasModifierProperty(PsiModifier.PUBLIC)) {
return aClass != null ? aClass.getUseScope() : maximalUseScope;
}
else if (member.hasModifierProperty(PsiModifier.PROTECTED)) {
return aClass != null ? aClass.getUseScope() : maximalUseScope;
}
else if (member.hasModifierProperty(PsiModifier.PRIVATE)) {
PsiClass topClass = PsiUtil.getTopLevelClass(member);
return topClass != null ? new LocalSearchScope(topClass) : new LocalSearchScope(file);
}
else {
PsiPackage aPackage = file instanceof PsiJavaFile ? JavaPsiFacade.getInstance(myManager.getProject())
.findPackage(((PsiJavaFile)file).getPackageName()) : null;
if (aPackage != null) {
SearchScope scope = GlobalSearchScope.packageScope(aPackage, false);
scope = scope.intersectWith(maximalUseScope);
return scope;
}
return maximalUseScope;
}
}
else if (element instanceof ImplicitVariable) {
return new LocalSearchScope(((ImplicitVariable)element).getDeclarationScope());
}
else if (element instanceof PsiLocalVariable) {
PsiElement parent = element.getParent();
if (parent instanceof PsiDeclarationStatement) {
return new LocalSearchScope(parent.getParent());
}
else {
return maximalUseScope;
}
}
else if (element instanceof PsiParameter) {
return new LocalSearchScope(((PsiParameter)element).getDeclarationScope());
}
else if (element instanceof PsiLabeledStatement) {
return new LocalSearchScope(element);
}
else if (element instanceof Property) {
// property ref can occur in any file
return GlobalSearchScope.allScope(myManager.getProject());
}
else {
return maximalUseScope;
}
}
public PsiSearchHelperImpl(PsiManagerEx manager) {
myManager = manager;
}
@NotNull
public PsiFile[] findFilesWithTodoItems() {
return myManager.getCacheManager().getFilesWithTodoItems();
}
@NotNull
public TodoItem[] findTodoItems(@NotNull PsiFile file) {
return doFindTodoItems(file, new TextRange(0, file.getTextLength()));
}
@NotNull
public TodoItem[] findTodoItems(@NotNull PsiFile file, int startOffset, int endOffset) {
return doFindTodoItems(file, new TextRange(startOffset, endOffset));
}
private static TodoItem[] doFindTodoItems(final PsiFile file, final TextRange textRange) {
final Collection<IndexPatternOccurrence> occurrences = IndexPatternSearch.search(file, TodoConfiguration.getInstance()).findAll();
if (occurrences.isEmpty()) {
return EMPTY_TODO_ITEMS;
}
List<TodoItem> items = new ArrayList<TodoItem>(occurrences.size());
for(IndexPatternOccurrence occurrence: occurrences) {
if (!textRange.contains(occurrence.getTextRange())) continue;
items.add(new TodoItemImpl(occurrence.getFile(), occurrence.getTextRange().getStartOffset(), occurrence.getTextRange().getEndOffset(),
mapPattern(occurrence.getPattern())));
}
return items.toArray(new TodoItem[items.size()]);
}
private static TodoPattern mapPattern(final IndexPattern pattern) {
for(TodoPattern todoPattern: TodoConfiguration.getInstance().getTodoPatterns()) {
if (todoPattern.getIndexPattern() == pattern) {
return todoPattern;
}
}
LOG.assertTrue(false, "Could not find matching TODO pattern for index pattern " + pattern.getPatternString());
return null;
}
public int getTodoItemsCount(@NotNull PsiFile file) {
int count = myManager.getCacheManager().getTodoCount(file.getVirtualFile(), TodoConfiguration.getInstance());
if (count != -1) return count;
return findTodoItems(file).length;
}
public int getTodoItemsCount(@NotNull PsiFile file, @NotNull TodoPattern pattern) {
int count = myManager.getCacheManager().getTodoCount(file.getVirtualFile(), pattern.getIndexPattern());
if (count != -1) return count;
TodoItem[] items = findTodoItems(file);
count = 0;
for (TodoItem item : items) {
if (item.getPattern().equals(pattern)) count++;
}
return count;
}
@NotNull
public PsiElement[] findCommentsContainingIdentifier(@NotNull String identifier, @NotNull SearchScope searchScope) {
final ArrayList<PsiElement> results = new ArrayList<PsiElement>();
TextOccurenceProcessor processor = new TextOccurenceProcessor() {
public boolean execute(PsiElement element, int offsetInElement) {
final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(element.getLanguage());
if (parserDefinition == null) return true;
if (element.getNode() != null && !parserDefinition.getCommentTokens().contains(element.getNode().getElementType())) return true;
if (element.findReferenceAt(offsetInElement) == null) {
synchronized (results) {
results.add(element);
}
}
return true;
}
};
processElementsWithWord(processor, searchScope, identifier, UsageSearchContext.IN_COMMENTS, true);
return results.toArray(new PsiElement[results.size()]);
}
public boolean processElementsWithWord(@NotNull TextOccurenceProcessor processor,
@NotNull SearchScope searchScope,
@NotNull String text,
short searchContext,
boolean caseSensitively) {
if (searchScope instanceof GlobalSearchScope) {
StringSearcher searcher = new StringSearcher(text);
searcher.setCaseSensitive(caseSensitively);
return processElementsWithTextInGlobalScope(processor,
(GlobalSearchScope)searchScope,
searcher,
searchContext, caseSensitively);
}
else {
LocalSearchScope scope = (LocalSearchScope)searchScope;
PsiElement[] scopeElements = scope.getScope();
final boolean ignoreInjectedPsi = scope.isIgnoreInjectedPsi();
for (final PsiElement scopeElement : scopeElements) {
if (!processElementsWithWordInScopeElement(scopeElement, processor, text, caseSensitively, ignoreInjectedPsi)) return false;
}
return true;
}
}
private static boolean processElementsWithWordInScopeElement(final PsiElement scopeElement,
final TextOccurenceProcessor processor,
final String word,
final boolean caseSensitive,
final boolean ignoreInjectedPsi) {
return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
public Boolean compute() {
StringSearcher searcher = new StringSearcher(word);
searcher.setCaseSensitive(caseSensitive);
return LowLevelSearchUtil.processElementsContainingWordInElement(processor, scopeElement, searcher, ignoreInjectedPsi);
}
}).booleanValue();
}
private boolean processElementsWithTextInGlobalScope(final TextOccurenceProcessor processor,
final GlobalSearchScope scope,
final StringSearcher searcher,
final short searchContext,
final boolean caseSensitively) {
LOG.assertTrue(!Thread.holdsLock(PsiLock.LOCK), "You must not run search from within updating PSI activity. Please consider invokeLatering it instead.");
final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
if (progress != null) {
progress.pushState();
progress.setText(PsiBundle.message("psi.scanning.files.progress"));
}
myManager.startBatchFilesProcessingMode();
try {
List<String> words = StringUtil.getWordsIn(searcher.getPattern());
if (words.isEmpty()) return true;
Set<PsiFile> fileSet = new THashSet<PsiFile>();
final Application application = ApplicationManager.getApplication();
for (final String word : words) {
List<PsiFile> psiFiles = application.runReadAction(new Computable<List<PsiFile>>() {
public List<PsiFile> compute() {
return Arrays.asList(myManager.getCacheManager().getFilesWithWord(word, searchContext, scope, caseSensitively));
}
});
if (fileSet.isEmpty()) {
fileSet.addAll(psiFiles);
}
else {
fileSet.retainAll(psiFiles);
}
if (fileSet.isEmpty()) break;
}
final PsiFile[] files = fileSet.toArray(new PsiFile[fileSet.size()]);
if (progress != null) {
progress.setText(PsiBundle.message("psi.search.for.word.progress", searcher.getPattern()));
}
final AtomicInteger counter = new AtomicInteger(0);
final AtomicBoolean canceled = new AtomicBoolean(false);
final AtomicBoolean pceThrown = new AtomicBoolean(false);
boolean completed = JobUtil.invokeConcurrentlyForAll(files, new Processor<PsiFile>() {
public boolean process(final PsiFile file) {
if (file instanceof PsiBinaryFile) return true;
((ProgressManagerImpl)ProgressManager.getInstance()).executeProcessUnderProgress(new Runnable() {
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
try {
PsiElement[] psiRoots = file.getPsiRoots();
Set<PsiElement> processed = new HashSet<PsiElement>(psiRoots.length * 2, (float)0.5);
for (PsiElement psiRoot : psiRoots) {
ProgressManager.getInstance().checkCanceled();
if (!processed.add(psiRoot)) continue;
if (!LowLevelSearchUtil.processElementsContainingWordInElement(processor, psiRoot, searcher, false)) {
canceled.set(true);
return;
}
}
if (progress != null) {
double fraction = (double)counter.incrementAndGet() / files.length;
progress.setFraction(fraction);
}
myManager.dropResolveCaches();
}
catch (ProcessCanceledException e) {
canceled.set(true);
pceThrown.set(true);
}
}
});
}
}, progress);
return !canceled.get();
}
}, "Process usages in files");
if (pceThrown.get()) {
throw new ProcessCanceledException();
}
return completed;
}
finally {
if (progress != null) {
progress.popState();
}
myManager.finishBatchFilesProcessingMode();
}
}
@NotNull
public PsiFile[] findFilesWithPlainTextWords(@NotNull String word) {
return myManager.getCacheManager().getFilesWithWord(word,
UsageSearchContext.IN_PLAIN_TEXT,
GlobalSearchScope.projectScope(myManager.getProject()), true);
}
public void processUsagesInNonJavaFiles(@NotNull String qName,
@NotNull PsiNonJavaFileReferenceProcessor processor,
@NotNull GlobalSearchScope searchScope) {
processUsagesInNonJavaFiles(null, qName, processor, searchScope);
}
public void processUsagesInNonJavaFiles(@Nullable final PsiElement originalElement,
@NotNull String qName,
@NotNull final PsiNonJavaFileReferenceProcessor processor,
@NotNull GlobalSearchScope searchScope) {
ProgressManager progressManager = ProgressManager.getInstance();
ProgressIndicator progress = progressManager.getProgressIndicator();
int dotIndex = qName.lastIndexOf('.');
int dollarIndex = qName.lastIndexOf('$');
int maxIndex = Math.max(dotIndex, dollarIndex);
String wordToSearch = maxIndex >= 0 ? qName.substring(maxIndex + 1) : qName;
if (originalElement != null && myManager.isInProject(originalElement) && searchScope.isSearchInLibraries()) {
searchScope = searchScope.intersectWith(GlobalSearchScope.projectScope(myManager.getProject()));
}
PsiFile[] files = myManager.getCacheManager().getFilesWithWord(wordToSearch, UsageSearchContext.IN_PLAIN_TEXT, searchScope, true);
final StringSearcher searcher = new StringSearcher(qName);
searcher.setCaseSensitive(true);
searcher.setForwardDirection(true);
if (progress != null) {
progress.pushState();
progress.setText(PsiBundle.message("psi.search.in.non.java.files.progress"));
}
final Ref<Boolean> cancelled = new Ref<Boolean>(Boolean.FALSE);
final GlobalSearchScope finalScope = searchScope;
for (int i = 0; i < files.length; i++) {
progressManager.checkCanceled();
final PsiFile psiFile = files[i];
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
CharSequence text = psiFile.getViewProvider().getContents();
for (int index = LowLevelSearchUtil.searchWord(text, 0, text.length(), searcher); index >= 0;) {
PsiReference referenceAt = psiFile.findReferenceAt(index);
if (referenceAt == null || originalElement == null ||
!PsiSearchScopeUtil.isInScope(getUseScope(originalElement).intersectWith(finalScope), psiFile)) {
if (!processor.process(psiFile, index, index + searcher.getPattern().length())) {
cancelled.set(Boolean.TRUE);
return;
}
}
index = LowLevelSearchUtil.searchWord(text, index + searcher.getPattern().length(), text.length(), searcher);
}
}
});
if (cancelled.get()) break;
if (progress != null) {
progress.setFraction((double)(i + 1) / files.length);
}
}
if (progress != null) {
progress.popState();
}
}
public void processAllFilesWithWord(@NotNull String word, @NotNull GlobalSearchScope scope, @NotNull Processor<PsiFile> processor, final boolean caseSensitively) {
myManager.getCacheManager().processFilesWithWord(processor,word, UsageSearchContext.IN_CODE, scope, caseSensitively);
}
public void processAllFilesWithWordInText(@NotNull final String word, @NotNull final GlobalSearchScope scope, @NotNull final Processor<PsiFile> processor,
final boolean caseSensitively) {
myManager.getCacheManager().processFilesWithWord(processor,word, UsageSearchContext.IN_PLAIN_TEXT, scope, caseSensitively);
}
public void processAllFilesWithWordInComments(@NotNull String word, @NotNull GlobalSearchScope scope, @NotNull Processor<PsiFile> processor) {
myManager.getCacheManager().processFilesWithWord(processor, word, UsageSearchContext.IN_COMMENTS, scope, true);
}
public void processAllFilesWithWordInLiterals(@NotNull String word, @NotNull GlobalSearchScope scope, @NotNull Processor<PsiFile> processor) {
myManager.getCacheManager().processFilesWithWord(processor, word, UsageSearchContext.IN_STRINGS, scope, true);
}
}
| source/com/intellij/psi/impl/search/PsiSearchHelperImpl.java | package com.intellij.psi.impl.search;
import com.intellij.concurrency.JobUtil;
import com.intellij.ide.todo.TodoConfiguration;
import com.intellij.lang.properties.psi.Property;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.impl.ProgressManagerImpl;
import com.intellij.openapi.util.Computable;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.*;
import com.intellij.psi.impl.PsiManagerEx;
import com.intellij.psi.search.*;
import com.intellij.psi.search.searches.AllClassesSearch;
import com.intellij.psi.search.searches.IndexPatternSearch;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.tree.TokenSet;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.Processor;
import com.intellij.util.text.StringSearcher;
import gnu.trove.THashSet;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
public class PsiSearchHelperImpl implements PsiSearchHelper {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.search.PsiSearchHelperImpl");
private final PsiManagerEx myManager;
private static final TodoItem[] EMPTY_TODO_ITEMS = new TodoItem[0];
static {
ReferencesSearch.INSTANCE.registerExecutor(new CachesBasedRefSearcher());
ReferencesSearch.INSTANCE.registerExecutor(new PsiAnnotationMethodReferencesSearcher());
ReferencesSearch.INSTANCE.registerExecutor(new ConstructorReferencesSearcher());
ReferencesSearch.INSTANCE.registerExecutor(new SimpleAccessorReferenceSearcher());
ReferencesSearch.INSTANCE.registerExecutor(new PropertyReferenceViaLastWordSearcher());
AllClassesSearch.INSTANCE.registerExecutor(new AllClassesSearchExecutor());
IndexPatternSearch.INDEX_PATTERN_SEARCH_INSTANCE = new IndexPatternSearchImpl();
}
@NotNull
public SearchScope getUseScope(@NotNull PsiElement element) {
final GlobalSearchScope maximalUseScope = myManager.getFileManager().getUseScope(element);
if (element instanceof PsiPackage) {
return maximalUseScope;
}
else if (element instanceof PsiClass) {
if (element instanceof PsiAnonymousClass) {
return new LocalSearchScope(element);
}
PsiFile file = element.getContainingFile();
if (PsiUtil.isInJspFile(file)) return maximalUseScope;
PsiClass aClass = (PsiClass)element;
final PsiClass containingClass = aClass.getContainingClass();
if (aClass.hasModifierProperty(PsiModifier.PUBLIC)) {
return containingClass != null ? containingClass.getUseScope() : maximalUseScope;
}
else if (aClass.hasModifierProperty(PsiModifier.PROTECTED)) {
return containingClass != null ? containingClass.getUseScope() : maximalUseScope;
}
else if (aClass.hasModifierProperty(PsiModifier.PRIVATE) || aClass instanceof PsiTypeParameter) {
PsiClass topClass = PsiUtil.getTopLevelClass(aClass);
return new LocalSearchScope(topClass == null ? aClass.getContainingFile() : topClass);
}
else {
PsiPackage aPackage = null;
if (file instanceof PsiJavaFile) {
aPackage = JavaPsiFacade.getInstance(element.getManager().getProject()).findPackage(((PsiJavaFile)file).getPackageName());
}
if (aPackage == null) {
PsiDirectory dir = file.getContainingDirectory();
if (dir != null) {
aPackage = JavaDirectoryService.getInstance().getPackage(dir);
}
}
if (aPackage != null) {
SearchScope scope = GlobalSearchScope.packageScope(aPackage, false);
scope = scope.intersectWith(maximalUseScope);
return scope;
}
return new LocalSearchScope(file);
}
}
else if (element instanceof PsiMethod || element instanceof PsiField) {
PsiMember member = (PsiMember) element;
PsiFile file = element.getContainingFile();
if (PsiUtil.isInJspFile(file)) return maximalUseScope;
PsiClass aClass = member.getContainingClass();
if (aClass instanceof PsiAnonymousClass) {
//member from anonymous class can be called from outside the class
PsiElement methodCallExpr = PsiTreeUtil.getParentOfType(aClass, PsiMethodCallExpression.class);
return new LocalSearchScope(methodCallExpr != null ? methodCallExpr : aClass);
}
if (member.hasModifierProperty(PsiModifier.PUBLIC)) {
return aClass != null ? aClass.getUseScope() : maximalUseScope;
}
else if (member.hasModifierProperty(PsiModifier.PROTECTED)) {
return aClass != null ? aClass.getUseScope() : maximalUseScope;
}
else if (member.hasModifierProperty(PsiModifier.PRIVATE)) {
PsiClass topClass = PsiUtil.getTopLevelClass(member);
return topClass != null ? new LocalSearchScope(topClass) : new LocalSearchScope(file);
}
else {
PsiPackage aPackage = file instanceof PsiJavaFile ? JavaPsiFacade.getInstance(myManager.getProject())
.findPackage(((PsiJavaFile)file).getPackageName()) : null;
if (aPackage != null) {
SearchScope scope = GlobalSearchScope.packageScope(aPackage, false);
scope = scope.intersectWith(maximalUseScope);
return scope;
}
return maximalUseScope;
}
}
else if (element instanceof ImplicitVariable) {
return new LocalSearchScope(((ImplicitVariable)element).getDeclarationScope());
}
else if (element instanceof PsiLocalVariable) {
PsiElement parent = element.getParent();
if (parent instanceof PsiDeclarationStatement) {
return new LocalSearchScope(parent.getParent());
}
else {
return maximalUseScope;
}
}
else if (element instanceof PsiParameter) {
return new LocalSearchScope(((PsiParameter)element).getDeclarationScope());
}
else if (element instanceof PsiLabeledStatement) {
return new LocalSearchScope(element);
}
else if (element instanceof Property) {
// property ref can occur in any file
return GlobalSearchScope.allScope(myManager.getProject());
}
else {
return maximalUseScope;
}
}
public PsiSearchHelperImpl(PsiManagerEx manager) {
myManager = manager;
}
@NotNull
public PsiFile[] findFilesWithTodoItems() {
return myManager.getCacheManager().getFilesWithTodoItems();
}
@NotNull
public TodoItem[] findTodoItems(@NotNull PsiFile file) {
return doFindTodoItems(file, new TextRange(0, file.getTextLength()));
}
@NotNull
public TodoItem[] findTodoItems(@NotNull PsiFile file, int startOffset, int endOffset) {
return doFindTodoItems(file, new TextRange(startOffset, endOffset));
}
private static TodoItem[] doFindTodoItems(final PsiFile file, final TextRange textRange) {
final Collection<IndexPatternOccurrence> occurrences = IndexPatternSearch.search(file, TodoConfiguration.getInstance()).findAll();
if (occurrences.isEmpty()) {
return EMPTY_TODO_ITEMS;
}
List<TodoItem> items = new ArrayList<TodoItem>(occurrences.size());
for(IndexPatternOccurrence occurrence: occurrences) {
if (!textRange.contains(occurrence.getTextRange())) continue;
items.add(new TodoItemImpl(occurrence.getFile(), occurrence.getTextRange().getStartOffset(), occurrence.getTextRange().getEndOffset(),
mapPattern(occurrence.getPattern())));
}
return items.toArray(new TodoItem[items.size()]);
}
private static TodoPattern mapPattern(final IndexPattern pattern) {
for(TodoPattern todoPattern: TodoConfiguration.getInstance().getTodoPatterns()) {
if (todoPattern.getIndexPattern() == pattern) {
return todoPattern;
}
}
LOG.assertTrue(false, "Could not find matching TODO pattern for index pattern " + pattern.getPatternString());
return null;
}
public int getTodoItemsCount(@NotNull PsiFile file) {
int count = myManager.getCacheManager().getTodoCount(file.getVirtualFile(), TodoConfiguration.getInstance());
if (count != -1) return count;
return findTodoItems(file).length;
}
public int getTodoItemsCount(@NotNull PsiFile file, @NotNull TodoPattern pattern) {
int count = myManager.getCacheManager().getTodoCount(file.getVirtualFile(), pattern.getIndexPattern());
if (count != -1) return count;
TodoItem[] items = findTodoItems(file);
count = 0;
for (TodoItem item : items) {
if (item.getPattern().equals(pattern)) count++;
}
return count;
}
private static final TokenSet COMMENT_BIT_SET = TokenSet.create(JavaDocTokenType.DOC_COMMENT_DATA, JavaDocTokenType.DOC_TAG_VALUE_TOKEN,
JavaTokenType.C_STYLE_COMMENT, JavaTokenType.END_OF_LINE_COMMENT);
@NotNull
public PsiElement[] findCommentsContainingIdentifier(@NotNull String identifier, @NotNull SearchScope searchScope) {
final ArrayList<PsiElement> results = new ArrayList<PsiElement>();
TextOccurenceProcessor processor = new TextOccurenceProcessor() {
public boolean execute(PsiElement element, int offsetInElement) {
if (element.getNode() != null && !COMMENT_BIT_SET.contains(element.getNode().getElementType())) return true;
if (element.findReferenceAt(offsetInElement) == null) {
synchronized (results) {
results.add(element);
}
}
return true;
}
};
processElementsWithWord(processor, searchScope, identifier, UsageSearchContext.IN_COMMENTS, true);
return results.toArray(new PsiElement[results.size()]);
}
public boolean processElementsWithWord(@NotNull TextOccurenceProcessor processor,
@NotNull SearchScope searchScope,
@NotNull String text,
short searchContext,
boolean caseSensitively) {
if (searchScope instanceof GlobalSearchScope) {
StringSearcher searcher = new StringSearcher(text);
searcher.setCaseSensitive(caseSensitively);
return processElementsWithTextInGlobalScope(processor,
(GlobalSearchScope)searchScope,
searcher,
searchContext, caseSensitively);
}
else {
LocalSearchScope scope = (LocalSearchScope)searchScope;
PsiElement[] scopeElements = scope.getScope();
final boolean ignoreInjectedPsi = scope.isIgnoreInjectedPsi();
for (final PsiElement scopeElement : scopeElements) {
if (!processElementsWithWordInScopeElement(scopeElement, processor, text, caseSensitively, ignoreInjectedPsi)) return false;
}
return true;
}
}
private static boolean processElementsWithWordInScopeElement(final PsiElement scopeElement,
final TextOccurenceProcessor processor,
final String word,
final boolean caseSensitive,
final boolean ignoreInjectedPsi) {
return ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
public Boolean compute() {
StringSearcher searcher = new StringSearcher(word);
searcher.setCaseSensitive(caseSensitive);
return LowLevelSearchUtil.processElementsContainingWordInElement(processor, scopeElement, searcher, ignoreInjectedPsi);
}
}).booleanValue();
}
private boolean processElementsWithTextInGlobalScope(final TextOccurenceProcessor processor,
final GlobalSearchScope scope,
final StringSearcher searcher,
final short searchContext,
final boolean caseSensitively) {
LOG.assertTrue(!Thread.holdsLock(PsiLock.LOCK), "You must not run search from within updating PSI activity. Please consider invokeLatering it instead.");
final ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
if (progress != null) {
progress.pushState();
progress.setText(PsiBundle.message("psi.scanning.files.progress"));
}
myManager.startBatchFilesProcessingMode();
try {
List<String> words = StringUtil.getWordsIn(searcher.getPattern());
if (words.isEmpty()) return true;
Set<PsiFile> fileSet = new THashSet<PsiFile>();
final Application application = ApplicationManager.getApplication();
for (final String word : words) {
List<PsiFile> psiFiles = application.runReadAction(new Computable<List<PsiFile>>() {
public List<PsiFile> compute() {
return Arrays.asList(myManager.getCacheManager().getFilesWithWord(word, searchContext, scope, caseSensitively));
}
});
if (fileSet.isEmpty()) {
fileSet.addAll(psiFiles);
}
else {
fileSet.retainAll(psiFiles);
}
if (fileSet.isEmpty()) break;
}
final PsiFile[] files = fileSet.toArray(new PsiFile[fileSet.size()]);
if (progress != null) {
progress.setText(PsiBundle.message("psi.search.for.word.progress", searcher.getPattern()));
}
final AtomicInteger counter = new AtomicInteger(0);
final AtomicBoolean canceled = new AtomicBoolean(false);
final AtomicBoolean pceThrown = new AtomicBoolean(false);
boolean completed = JobUtil.invokeConcurrentlyForAll(files, new Processor<PsiFile>() {
public boolean process(final PsiFile file) {
if (file instanceof PsiBinaryFile) return true;
((ProgressManagerImpl)ProgressManager.getInstance()).executeProcessUnderProgress(new Runnable() {
public void run() {
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
try {
PsiElement[] psiRoots = file.getPsiRoots();
Set<PsiElement> processed = new HashSet<PsiElement>(psiRoots.length * 2, (float)0.5);
for (PsiElement psiRoot : psiRoots) {
ProgressManager.getInstance().checkCanceled();
if (!processed.add(psiRoot)) continue;
if (!LowLevelSearchUtil.processElementsContainingWordInElement(processor, psiRoot, searcher, false)) {
canceled.set(true);
return;
}
}
if (progress != null) {
double fraction = (double)counter.incrementAndGet() / files.length;
progress.setFraction(fraction);
}
myManager.dropResolveCaches();
}
catch (ProcessCanceledException e) {
canceled.set(true);
pceThrown.set(true);
}
}
});
}
}, progress);
return !canceled.get();
}
}, "Process usages in files");
if (pceThrown.get()) {
throw new ProcessCanceledException();
}
return completed;
}
finally {
if (progress != null) {
progress.popState();
}
myManager.finishBatchFilesProcessingMode();
}
}
@NotNull
public PsiFile[] findFilesWithPlainTextWords(@NotNull String word) {
return myManager.getCacheManager().getFilesWithWord(word,
UsageSearchContext.IN_PLAIN_TEXT,
GlobalSearchScope.projectScope(myManager.getProject()), true);
}
public void processUsagesInNonJavaFiles(@NotNull String qName,
@NotNull PsiNonJavaFileReferenceProcessor processor,
@NotNull GlobalSearchScope searchScope) {
processUsagesInNonJavaFiles(null, qName, processor, searchScope);
}
public void processUsagesInNonJavaFiles(@Nullable final PsiElement originalElement,
@NotNull String qName,
@NotNull final PsiNonJavaFileReferenceProcessor processor,
@NotNull GlobalSearchScope searchScope) {
ProgressManager progressManager = ProgressManager.getInstance();
ProgressIndicator progress = progressManager.getProgressIndicator();
int dotIndex = qName.lastIndexOf('.');
int dollarIndex = qName.lastIndexOf('$');
int maxIndex = Math.max(dotIndex, dollarIndex);
String wordToSearch = maxIndex >= 0 ? qName.substring(maxIndex + 1) : qName;
if (originalElement != null && myManager.isInProject(originalElement) && searchScope.isSearchInLibraries()) {
searchScope = searchScope.intersectWith(GlobalSearchScope.projectScope(myManager.getProject()));
}
PsiFile[] files = myManager.getCacheManager().getFilesWithWord(wordToSearch, UsageSearchContext.IN_PLAIN_TEXT, searchScope, true);
final StringSearcher searcher = new StringSearcher(qName);
searcher.setCaseSensitive(true);
searcher.setForwardDirection(true);
if (progress != null) {
progress.pushState();
progress.setText(PsiBundle.message("psi.search.in.non.java.files.progress"));
}
final Ref<Boolean> cancelled = new Ref<Boolean>(Boolean.FALSE);
final GlobalSearchScope finalScope = searchScope;
for (int i = 0; i < files.length; i++) {
progressManager.checkCanceled();
final PsiFile psiFile = files[i];
ApplicationManager.getApplication().runReadAction(new Runnable() {
public void run() {
CharSequence text = psiFile.getViewProvider().getContents();
for (int index = LowLevelSearchUtil.searchWord(text, 0, text.length(), searcher); index >= 0;) {
PsiReference referenceAt = psiFile.findReferenceAt(index);
if (referenceAt == null || originalElement == null ||
!PsiSearchScopeUtil.isInScope(getUseScope(originalElement).intersectWith(finalScope), psiFile)) {
if (!processor.process(psiFile, index, index + searcher.getPattern().length())) {
cancelled.set(Boolean.TRUE);
return;
}
}
index = LowLevelSearchUtil.searchWord(text, index + searcher.getPattern().length(), text.length(), searcher);
}
}
});
if (cancelled.get()) break;
if (progress != null) {
progress.setFraction((double)(i + 1) / files.length);
}
}
if (progress != null) {
progress.popState();
}
}
public void processAllFilesWithWord(@NotNull String word, @NotNull GlobalSearchScope scope, @NotNull Processor<PsiFile> processor, final boolean caseSensitively) {
myManager.getCacheManager().processFilesWithWord(processor,word, UsageSearchContext.IN_CODE, scope, caseSensitively);
}
public void processAllFilesWithWordInText(@NotNull final String word, @NotNull final GlobalSearchScope scope, @NotNull final Processor<PsiFile> processor,
final boolean caseSensitively) {
myManager.getCacheManager().processFilesWithWord(processor,word, UsageSearchContext.IN_PLAIN_TEXT, scope, caseSensitively);
}
public void processAllFilesWithWordInComments(@NotNull String word, @NotNull GlobalSearchScope scope, @NotNull Processor<PsiFile> processor) {
myManager.getCacheManager().processFilesWithWord(processor, word, UsageSearchContext.IN_COMMENTS, scope, true);
}
public void processAllFilesWithWordInLiterals(@NotNull String word, @NotNull GlobalSearchScope scope, @NotNull Processor<PsiFile> processor) {
myManager.getCacheManager().processFilesWithWord(processor, word, UsageSearchContext.IN_STRINGS, scope, true);
}
}
| IDEADEV-23792: Comments filtering uses language provided comments, not hardcoded java ones.
| source/com/intellij/psi/impl/search/PsiSearchHelperImpl.java | IDEADEV-23792: Comments filtering uses language provided comments, not hardcoded java ones. |
|
Java | apache-2.0 | b53de204104bbd0262ed8fd7e0341f147698f1f1 | 0 | apurtell/phoenix,dumindux/phoenix,apache/phoenix,jfernandosf/phoenix,apache/phoenix,twdsilva/phoenix,shehzaadn/phoenix,growingio/phoenix,ohadshacham/phoenix,ohadshacham/phoenix,ohadshacham/phoenix,apurtell/phoenix,jfernandosf/phoenix,growingio/phoenix,apurtell/phoenix,apache/phoenix,jfernandosf/phoenix,twdsilva/phoenix,twdsilva/phoenix,apache/phoenix,twdsilva/phoenix,ohadshacham/phoenix,growingio/phoenix,ankitsinghal/phoenix,jfernandosf/phoenix,shehzaadn/phoenix,shehzaadn/phoenix,apache/phoenix,jfernandosf/phoenix,growingio/phoenix,growingio/phoenix,twdsilva/phoenix,ankitsinghal/phoenix,shehzaadn/phoenix,shehzaadn/phoenix,apurtell/phoenix,dumindux/phoenix,ankitsinghal/phoenix,apurtell/phoenix,ohadshacham/phoenix,ankitsinghal/phoenix,ankitsinghal/phoenix | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.phoenix.end2end;
import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA;
import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_TABLE;
import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_FUNCTION_TABLE;
import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TYPE_SEQUENCE;
import static org.apache.phoenix.util.TestUtil.ATABLE_NAME;
import static org.apache.phoenix.util.TestUtil.CUSTOM_ENTITY_DATA_FULL_NAME;
import static org.apache.phoenix.util.TestUtil.PTSDB_NAME;
import static org.apache.phoenix.util.TestUtil.STABLE_NAME;
import static org.apache.phoenix.util.TestUtil.TABLE_WITH_SALTING;
import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.apache.phoenix.util.TestUtil.createGroupByTestTable;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.phoenix.coprocessor.GroupedAggregateRegionObserver;
import org.apache.phoenix.coprocessor.ServerCachingEndpointImpl;
import org.apache.phoenix.coprocessor.UngroupedAggregateRegionObserver;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData;
import org.apache.phoenix.schema.ColumnNotFoundException;
import org.apache.phoenix.schema.PTable.ViewType;
import org.apache.phoenix.schema.PTableType;
import org.apache.phoenix.schema.ReadOnlyTableException;
import org.apache.phoenix.schema.TableNotFoundException;
import org.apache.phoenix.schema.types.PChar;
import org.apache.phoenix.schema.types.PDecimal;
import org.apache.phoenix.schema.types.PInteger;
import org.apache.phoenix.schema.types.PLong;
import org.apache.phoenix.util.PropertiesUtil;
import org.apache.phoenix.util.SchemaUtil;
import org.apache.phoenix.util.StringUtil;
import org.junit.Before;
import org.junit.Test;
public class QueryDatabaseMetaDataIT extends ParallelStatsDisabledIT {
private static void createMDTestTable(Connection conn, String tableName, String extraProps)
throws SQLException {
String ddl =
"create table if not exists " + tableName + " (id char(1) primary key,\n"
+ " a.col1 integer,\n" + " b.col2 bigint,\n" + " b.col3 decimal,\n"
+ " b.col4 decimal(5),\n" + " b.col5 decimal(6,3))\n" + " a."
+ HConstants.VERSIONS + "=" + 1 + "," + "a."
+ HColumnDescriptor.DATA_BLOCK_ENCODING + "='" + DataBlockEncoding.NONE
+ "'";
if (extraProps != null && extraProps.length() > 0) {
ddl += "," + extraProps;
}
conn.createStatement().execute(ddl);
}
@Before
// We need to clean up phoenix metadata to ensure tests don't step on each other
public void deleteMetadata() throws Exception {
try (Connection conn = DriverManager.getConnection(getUrl())) {
String delete =
"DELETE FROM SYSTEM.CATALOG WHERE TABLE_SCHEM IS NULL OR TABLE_SCHEM = '' OR TABLE_SCHEM != 'SYSTEM'";
conn.createStatement().executeUpdate(delete);
conn.commit();
delete = "DELETE FROM \"SYSTEM\".\"SEQUENCE\"";
conn.createStatement().executeUpdate(delete);
conn.commit();
conn.unwrap(PhoenixConnection.class).getQueryServices().clearCache();
}
}
@Test
public void testTableMetadataScan() throws SQLException {
String tableAName = generateUniqueName() + "TABLE";
String tableASchema = "";
ensureTableCreated(getUrl(), tableAName, ATABLE_NAME, null);
String tableS = generateUniqueName() + "TABLE";
ensureTableCreated(getUrl(), tableS, STABLE_NAME, null);
String tableC = generateUniqueName();
String tableCSchema = generateUniqueName();
ensureTableCreated(getUrl(), tableCSchema + "." + tableC, CUSTOM_ENTITY_DATA_FULL_NAME,
null);
try (Connection conn = DriverManager.getConnection(getUrl())) {
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getTables(null, tableASchema, tableAName, null);
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), tableAName);
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertEquals(rs.getString(3), tableAName);
assertEquals(PTableType.TABLE.toString(), rs.getString(4));
assertFalse(rs.next());
rs = dbmd.getTables(null, null, null, null);
assertTrue(rs.next());
assertEquals(SYSTEM_CATALOG_SCHEMA, rs.getString("TABLE_SCHEM"));
assertEquals(SYSTEM_CATALOG_TABLE, rs.getString("TABLE_NAME"));
assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals(SYSTEM_CATALOG_SCHEMA, rs.getString("TABLE_SCHEM"));
assertEquals(SYSTEM_FUNCTION_TABLE, rs.getString("TABLE_NAME"));
assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals(SYSTEM_CATALOG_SCHEMA, rs.getString("TABLE_SCHEM"));
assertEquals(TYPE_SEQUENCE, rs.getString("TABLE_NAME"));
assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals(SYSTEM_CATALOG_SCHEMA, rs.getString("TABLE_SCHEM"));
assertEquals(PhoenixDatabaseMetaData.SYSTEM_STATS_TABLE, rs.getString("TABLE_NAME"));
assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals(null, rs.getString("TABLE_SCHEM"));
assertEquals(tableAName, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals(null, rs.getString("TABLE_SCHEM"));
assertEquals(tableS, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals(tableCSchema, rs.getString("TABLE_SCHEM"));
assertEquals(tableC, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertEquals("false", rs.getString(PhoenixDatabaseMetaData.TRANSACTIONAL));
assertEquals(Boolean.FALSE, rs.getBoolean(PhoenixDatabaseMetaData.IS_NAMESPACE_MAPPED));
rs = dbmd.getTables(null, tableCSchema, tableC, null);
assertTrue(rs.next());
try {
rs.getString("RANDOM_COLUMN_NAME");
fail();
} catch (ColumnNotFoundException e) {
// expected
}
assertEquals(tableCSchema, rs.getString("TABLE_SCHEM"));
assertEquals(tableC, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertFalse(rs.next());
rs = dbmd.getTables(null, "", "%TABLE", new String[] { PTableType.TABLE.toString() });
assertTrue(rs.next());
assertEquals(null, rs.getString("TABLE_SCHEM"));
assertEquals(tableAName, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals(null, rs.getString("TABLE_SCHEM"));
assertEquals(tableS, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertFalse(rs.next());
}
}
@Test
public void testTableTypes() throws SQLException {
try (Connection conn = DriverManager.getConnection(getUrl())) {
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getTableTypes();
assertTrue(rs.next());
assertEquals("INDEX", rs.getString(1));
assertTrue(rs.next());
assertEquals("SEQUENCE", rs.getString(1));
assertTrue(rs.next());
assertEquals("SYSTEM TABLE", rs.getString(1));
assertTrue(rs.next());
assertEquals("TABLE", rs.getString(1));
assertTrue(rs.next());
assertEquals("VIEW", rs.getString(1));
assertFalse(rs.next());
}
}
@Test
public void testSequenceMetadataScan() throws SQLException {
try (Connection conn = DriverManager.getConnection(getUrl())) {
String schema1 = "B" + generateUniqueName();
String seq1 = generateUniqueName();
String seq1FullName = schema1 + "." + seq1;
String schema2 = generateUniqueName();
String seq2 = generateUniqueName();
String seq2FullName = schema2 + "." + seq2;
String schema3 = schema1;
String seq3 = generateUniqueName();
String seq3FullName = schema3 + "." + seq3;
String schema4 = generateUniqueName();
String seq4 = seq1;
String seq4FullName = schema4 + "." + seq4;
conn.createStatement().execute("CREATE SEQUENCE " + seq1FullName);
conn.createStatement().execute("CREATE SEQUENCE " + seq2FullName);
conn.createStatement().execute("CREATE SEQUENCE " + seq3FullName);
conn.createStatement().execute("CREATE SEQUENCE " + seq4FullName);
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getTables(null, null, null, new String[] { "FOO" });
assertFalse(rs.next());
rs =
dbmd.getTables(null, null, null,
new String[] { "FOO", PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE });
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema1, rs.getString("TABLE_SCHEM"));
assertEquals(seq1, rs.getString("TABLE_NAME"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema3, rs.getString("TABLE_SCHEM"));
assertEquals(seq3, rs.getString("TABLE_NAME"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(seq2, rs.getString("TABLE_NAME"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema4, rs.getString("TABLE_SCHEM"));
assertEquals(seq4, rs.getString("TABLE_NAME"));
assertFalse(rs.next());
String foo = generateUniqueName();
String basSchema = generateUniqueName();
String bas = generateUniqueName();
conn.createStatement().execute("CREATE TABLE " + foo + " (k bigint primary key)");
conn.createStatement()
.execute("CREATE TABLE " + basSchema + "." + bas + " (k bigint primary key)");
dbmd = conn.getMetaData();
rs =
dbmd.getTables(null, null, null, new String[] { PTableType.TABLE.toString(),
PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE });
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema1, rs.getString("TABLE_SCHEM"));
assertEquals(seq1, rs.getString("TABLE_NAME"));
assertEquals(PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE, rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema3, rs.getString("TABLE_SCHEM"));
assertEquals(seq3, rs.getString("TABLE_NAME"));
assertEquals(PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE, rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(seq2, rs.getString("TABLE_NAME"));
assertEquals(PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE, rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema4, rs.getString("TABLE_SCHEM"));
assertEquals(seq4, rs.getString("TABLE_NAME"));
assertEquals(PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE, rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertNull(rs.getString("TABLE_SCHEM"));
assertEquals(foo, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(basSchema, rs.getString("TABLE_SCHEM"));
assertEquals(bas, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertFalse(rs.next());
rs =
dbmd.getTables(null, "B%", null,
new String[] { PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE });
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema1, rs.getString("TABLE_SCHEM"));
assertEquals(seq1, rs.getString("TABLE_NAME"));
assertEquals(PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE, rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema3, rs.getString("TABLE_SCHEM"));
assertEquals(seq3, rs.getString("TABLE_NAME"));
assertEquals(PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE, rs.getString("TABLE_TYPE"));
assertFalse(rs.next());
}
}
@Test
public void testSchemaMetadataScan() throws SQLException {
String table1 = generateUniqueName();
String schema1 = generateUniqueName();
String fullTable1 = schema1 + "." + table1;
ensureTableCreated(getUrl(), fullTable1, CUSTOM_ENTITY_DATA_FULL_NAME, null);
String fullTable2 = generateUniqueName();
ensureTableCreated(getUrl(), fullTable2, PTSDB_NAME, null);
try (Connection conn = DriverManager.getConnection(getUrl())) {
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs;
rs = dbmd.getSchemas(null, schema1);
assertTrue(rs.next());
assertEquals(rs.getString(1), schema1);
assertEquals(rs.getString(2), null);
assertFalse(rs.next());
rs = dbmd.getSchemas(null, null);
assertTrue(rs.next());
assertEquals(null, rs.getString("TABLE_SCHEM"));
assertEquals(null, rs.getString("TABLE_CATALOG"));
assertTrue(rs.next());
assertEquals(PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA,
rs.getString("TABLE_SCHEM"));
assertEquals(null, rs.getString("TABLE_CATALOG"));
assertTrue(rs.next());
assertEquals(schema1, rs.getString("TABLE_SCHEM"));
assertEquals(null, rs.getString("TABLE_CATALOG"));
assertFalse(rs.next());
}
}
@Test
public void testColumnMetadataScan() throws SQLException {
Connection conn = DriverManager.getConnection(getUrl());
String table = generateUniqueName();
createMDTestTable(conn, table, "");
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs;
rs = dbmd.getColumns(null, "", table, null);
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNoNulls, rs.getShort("NULLABLE"));
assertEquals(PChar.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(1, rs.getInt("ORDINAL_POSITION"));
assertEquals(1, rs.getInt("COLUMN_SIZE"));
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PInteger.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(2, rs.getInt("ORDINAL_POSITION"));
assertEquals(0, rs.getInt("COLUMN_SIZE"));
assertTrue(rs.wasNull());
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.wasNull());
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PLong.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(3, rs.getInt("ORDINAL_POSITION"));
assertEquals(0, rs.getInt("COLUMN_SIZE"));
assertTrue(rs.wasNull());
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.wasNull());
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PDecimal.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(4, rs.getInt("ORDINAL_POSITION"));
assertEquals(0, rs.getInt("COLUMN_SIZE"));
assertTrue(rs.wasNull());
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.wasNull());
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PDecimal.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(5, rs.getInt("ORDINAL_POSITION"));
assertEquals(5, rs.getInt("COLUMN_SIZE"));
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PDecimal.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(6, rs.getInt("ORDINAL_POSITION"));
assertEquals(6, rs.getInt("COLUMN_SIZE"));
assertEquals(3, rs.getInt("DECIMAL_DIGITS"));
assertFalse(rs.next());
// Look up only columns in a column family
rs = dbmd.getColumns(null, "", table, "A.");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PInteger.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(2, rs.getInt("ORDINAL_POSITION"));
assertEquals(0, rs.getInt("COLUMN_SIZE"));
assertTrue(rs.wasNull());
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.wasNull());
assertFalse(rs.next());
// Look up KV columns in a column family
rs = dbmd.getColumns("", "", table, "%.COL%");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PInteger.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(2, rs.getInt("ORDINAL_POSITION"));
assertEquals(0, rs.getInt("COLUMN_SIZE"));
assertTrue(rs.wasNull());
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.wasNull());
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PLong.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(3, rs.getInt("ORDINAL_POSITION"));
assertEquals(0, rs.getInt("COLUMN_SIZE"));
assertTrue(rs.wasNull());
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.wasNull());
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PDecimal.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(4, rs.getInt("ORDINAL_POSITION"));
assertEquals(0, rs.getInt("COLUMN_SIZE"));
assertTrue(rs.wasNull());
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.wasNull());
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PDecimal.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(5, rs.getInt("ORDINAL_POSITION"));
assertEquals(5, rs.getInt("COLUMN_SIZE"));
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertFalse(rs.wasNull());
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PDecimal.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(6, rs.getInt("ORDINAL_POSITION"));
assertEquals(6, rs.getInt("COLUMN_SIZE"));
assertEquals(3, rs.getInt("DECIMAL_DIGITS"));
assertFalse(rs.next());
// Look up KV columns in a column family
rs = dbmd.getColumns("", "", table, "B.COL2");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME"));
assertFalse(rs.next());
String table2 = generateUniqueName();
ensureTableCreated(getUrl(), table2, TABLE_WITH_SALTING, null);
rs = dbmd.getColumns("", "", table2, StringUtil.escapeLike("A_INTEGER"));
assertTrue(rs.next());
assertEquals(1, rs.getInt("ORDINAL_POSITION"));
assertFalse(rs.next());
}
@Test
public void testPrimaryKeyMetadataScan() throws SQLException {
try (Connection conn = DriverManager.getConnection(getUrl())) {
String table1 = generateUniqueName();
createMDTestTable(conn, table1, "");
String schema2 = generateUniqueName();
String table2 = generateUniqueName();
String fullTable2 = schema2 + "." + table2;
ensureTableCreated(getUrl(), fullTable2, CUSTOM_ENTITY_DATA_FULL_NAME, null);
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs;
rs = dbmd.getPrimaryKeys(null, "", table1);
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table1, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME"));
assertEquals(1, rs.getInt("KEY_SEQ"));
assertEquals(null, rs.getString("PK_NAME"));
assertFalse(rs.next());
rs = dbmd.getPrimaryKeys(null, schema2, table2);
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("custom_entity_data_id"),
rs.getString("COLUMN_NAME"));
assertEquals(3, rs.getInt("KEY_SEQ"));
assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME"));
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME"));
assertEquals(2, rs.getInt("KEY_SEQ"));
assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME"));
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("organization_id"),
rs.getString("COLUMN_NAME"));
assertEquals(1, rs.getInt("KEY_SEQ"));
assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME")); // TODO:
// this is
// on the
// table
// row
assertFalse(rs.next());
rs = dbmd.getColumns("", schema2, table2, null);
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("organization_id"),
rs.getString("COLUMN_NAME"));
assertEquals(rs.getInt("COLUMN_SIZE"), 15);
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME"));
assertEquals(rs.getInt("COLUMN_SIZE"), 3);
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("custom_entity_data_id"),
rs.getString("COLUMN_NAME"));
// The above returns all columns, starting with the PK columns
assertTrue(rs.next());
rs = dbmd.getColumns("", schema2, table2, "KEY_PREFIX");
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME"));
rs = dbmd.getColumns("", schema2, table2, "KEY_PREFIX");
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME"));
assertFalse(rs.next());
String table3 = generateUniqueName();
conn.createStatement().execute(
"CREATE TABLE " + table3 + " (k INTEGER PRIMARY KEY, v VARCHAR) SALT_BUCKETS=3");
dbmd = conn.getMetaData();
rs = dbmd.getPrimaryKeys(null, "", table3);
assertTrue(rs.next());
assertEquals(null, rs.getString("TABLE_SCHEM"));
assertEquals(table3, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals("K", rs.getString("COLUMN_NAME"));
assertEquals(1, rs.getInt("KEY_SEQ"));
assertEquals(null, rs.getString("PK_NAME"));
assertFalse(rs.next());
}
}
@Test
public void testMultiTableColumnsMetadataScan() throws SQLException {
try (Connection conn = DriverManager.getConnection(getUrl())) {
String table1 = "TEST" + generateUniqueName();
String table2 = "TEST" + generateUniqueName();
createGroupByTestTable(conn, table1);
createMDTestTable(conn, table2, "");
String table3 = generateUniqueName();
ensureTableCreated(getUrl(), table3, PTSDB_NAME, null);
String table4 = generateUniqueName();
ensureTableCreated(getUrl(), table4, CUSTOM_ENTITY_DATA_FULL_NAME, null);
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getColumns(null, "", "%TEST%", null);
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table1);
assertEquals(null, rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table1);
assertEquals(PhoenixDatabaseMetaData.TABLE_FAMILY, rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("uri"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table1);
assertEquals(PhoenixDatabaseMetaData.TABLE_FAMILY, rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("appcpu"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table2);
assertEquals(null, rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table2);
assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table2);
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table2);
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table2);
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table2);
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME"));
assertFalse(rs.next());
}
}
@Test
public void testCreateOnExistingTable() throws Exception {
try (PhoenixConnection pconn =
DriverManager.getConnection(getUrl()).unwrap(PhoenixConnection.class)) {
String tableName = generateUniqueName();// MDTEST_NAME;
String schemaName = "";// MDTEST_SCHEMA_NAME;
byte[] cfA = Bytes.toBytes(SchemaUtil.normalizeIdentifier("a"));
byte[] cfB = Bytes.toBytes(SchemaUtil.normalizeIdentifier("b"));
byte[] cfC = Bytes.toBytes("c");
byte[][] familyNames = new byte[][] { cfB, cfC };
byte[] htableName = SchemaUtil.getTableNameAsBytes(schemaName, tableName);
HBaseAdmin admin = pconn.getQueryServices().getAdmin();
try {
admin.disableTable(htableName);
admin.deleteTable(htableName);
admin.enableTable(htableName);
} catch (org.apache.hadoop.hbase.TableNotFoundException e) {
}
@SuppressWarnings("deprecation")
HTableDescriptor descriptor = new HTableDescriptor(htableName);
for (byte[] familyName : familyNames) {
HColumnDescriptor columnDescriptor = new HColumnDescriptor(familyName);
descriptor.addFamily(columnDescriptor);
}
admin.createTable(descriptor);
createMDTestTable(pconn, tableName,
"a." + HColumnDescriptor.KEEP_DELETED_CELLS + "=" + Boolean.TRUE);
descriptor = admin.getTableDescriptor(htableName);
assertEquals(3, descriptor.getColumnFamilies().length);
HColumnDescriptor cdA = descriptor.getFamily(cfA);
assertNotEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdA.getKeepDeletedCells());
assertEquals(DataBlockEncoding.NONE, cdA.getDataBlockEncoding()); // Overriden using
// WITH
assertEquals(1, cdA.getMaxVersions());// Overriden using WITH
HColumnDescriptor cdB = descriptor.getFamily(cfB);
// Allow KEEP_DELETED_CELLS to be false for VIEW
assertEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdB.getKeepDeletedCells());
assertEquals(DataBlockEncoding.NONE, cdB.getDataBlockEncoding()); // Should keep the
// original value.
// CF c should stay the same since it's not a Phoenix cf.
HColumnDescriptor cdC = descriptor.getFamily(cfC);
assertNotNull("Column family not found", cdC);
assertEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdC.getKeepDeletedCells());
assertFalse(SchemaUtil.DEFAULT_DATA_BLOCK_ENCODING == cdC.getDataBlockEncoding());
assertTrue(descriptor.hasCoprocessor(UngroupedAggregateRegionObserver.class.getName()));
assertTrue(descriptor.hasCoprocessor(GroupedAggregateRegionObserver.class.getName()));
assertTrue(descriptor.hasCoprocessor(ServerCachingEndpointImpl.class.getName()));
admin.close();
int rowCount = 5;
String upsert = "UPSERT INTO " + tableName + "(id,col1,col2) VALUES(?,?,?)";
PreparedStatement ps = pconn.prepareStatement(upsert);
for (int i = 0; i < rowCount; i++) {
ps.setString(1, Integer.toString(i));
ps.setInt(2, i + 1);
ps.setInt(3, i + 2);
ps.execute();
}
pconn.commit();
String query = "SELECT count(1) FROM " + tableName;
ResultSet rs = pconn.createStatement().executeQuery(query);
assertTrue(rs.next());
assertEquals(rowCount, rs.getLong(1));
query = "SELECT id, col1,col2 FROM " + tableName;
rs = pconn.createStatement().executeQuery(query);
for (int i = 0; i < rowCount; i++) {
assertTrue(rs.next());
assertEquals(Integer.toString(i), rs.getString(1));
assertEquals(i + 1, rs.getInt(2));
assertEquals(i + 2, rs.getInt(3));
}
assertFalse(rs.next());
}
}
@SuppressWarnings("deprecation")
@Test
public void testCreateViewOnExistingTable() throws Exception {
try (PhoenixConnection pconn =
DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES))
.unwrap(PhoenixConnection.class)) {
String tableName = generateUniqueName();// MDTEST_NAME;
String schemaName = "";// MDTEST_SCHEMA_NAME;
byte[] cfB = Bytes.toBytes(SchemaUtil.normalizeIdentifier("b"));
byte[] cfC = Bytes.toBytes("c");
byte[][] familyNames = new byte[][] { cfB, cfC };
byte[] htableName = SchemaUtil.getTableNameAsBytes(schemaName, tableName);
try (HBaseAdmin admin = pconn.getQueryServices().getAdmin()) {
try {
admin.disableTable(htableName);
admin.deleteTable(htableName);
} catch (org.apache.hadoop.hbase.TableNotFoundException e) {
}
HTableDescriptor descriptor = new HTableDescriptor(htableName);
for (byte[] familyName : familyNames) {
HColumnDescriptor columnDescriptor = new HColumnDescriptor(familyName);
descriptor.addFamily(columnDescriptor);
}
admin.createTable(descriptor);
}
String createStmt =
"create view " + generateUniqueName() + " (id char(1) not null primary key,\n"
+ " a.col1 integer,\n" + " d.col2 bigint)\n";
try {
pconn.createStatement().execute(createStmt);
fail();
} catch (TableNotFoundException e) {
// expected to fail b/c table doesn't exist
} catch (ReadOnlyTableException e) {
// expected to fail b/c table doesn't exist
}
createStmt =
"create view " + tableName + " (id char(1) not null primary key,\n"
+ " a.col1 integer,\n" + " b.col2 bigint)\n";
try {
pconn.createStatement().execute(createStmt);
fail();
} catch (ReadOnlyTableException e) {
// expected to fail b/c cf a doesn't exist
}
createStmt =
"create view " + tableName + " (id char(1) not null primary key,\n"
+ " b.col1 integer,\n" + " c.col2 bigint)\n";
try {
pconn.createStatement().execute(createStmt);
fail();
} catch (ReadOnlyTableException e) {
// expected to fail b/c cf C doesn't exist (case issue)
}
createStmt =
"create view " + tableName + " (id char(1) not null primary key,\n"
+ " b.col1 integer,\n"
+ " \"c\".col2 bigint) IMMUTABLE_ROWS=true \n";
// should be ok now
pconn.createStatement().execute(createStmt);
ResultSet rs = pconn.getMetaData().getTables(null, null, tableName, null);
assertTrue(rs.next());
assertEquals(ViewType.MAPPED.name(), rs.getString(PhoenixDatabaseMetaData.VIEW_TYPE));
assertFalse(rs.next());
String deleteStmt = "DELETE FROM " + tableName;
PreparedStatement ps = pconn.prepareStatement(deleteStmt);
try {
ps.execute();
fail();
} catch (ReadOnlyTableException e) {
// expected to fail b/c table is read-only
}
String upsert = "UPSERT INTO " + tableName + "(id,col1,col2) VALUES(?,?,?)";
ps = pconn.prepareStatement(upsert);
try {
ps.setString(1, Integer.toString(0));
ps.setInt(2, 1);
ps.setInt(3, 2);
ps.execute();
fail();
} catch (ReadOnlyTableException e) {
// expected to fail b/c table is read-only
}
HTableInterface htable =
pconn.getQueryServices()
.getTable(SchemaUtil.getTableNameAsBytes(schemaName, tableName));
Put put = new Put(Bytes.toBytes("0"));
put.add(cfB, Bytes.toBytes("COL1"), PInteger.INSTANCE.toBytes(1));
put.add(cfC, Bytes.toBytes("COL2"), PLong.INSTANCE.toBytes(2));
htable.put(put);
// Should be ok b/c we've marked the view with IMMUTABLE_ROWS=true
pconn.createStatement().execute("CREATE INDEX idx ON " + tableName + "(B.COL1)");
String select = "SELECT col1 FROM " + tableName + " WHERE col2=?";
ps = pconn.prepareStatement(select);
ps.setInt(1, 2);
rs = ps.executeQuery();
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertFalse(rs.next());
String dropTable = "DROP TABLE " + tableName;
ps = pconn.prepareStatement(dropTable);
try {
ps.execute();
fail();
} catch (TableNotFoundException e) {
// expected to fail b/c it is a view
}
String alterView = "alter view " + tableName + " drop column \"c\".col2";
pconn.createStatement().execute(alterView);
}
}
@Test
public void testAddKVColumnToExistingFamily() throws Throwable {
String tenantId = getOrganizationId();
String tableName = generateUniqueName();
initATableValues(tableName, tenantId, getDefaultSplits(tenantId), null, null, getUrl(),
null);
try (Connection conn1 = DriverManager.getConnection(getUrl())) {
conn1.createStatement()
.executeUpdate("ALTER TABLE " + tableName + " ADD z_integer integer");
String query = "SELECT z_integer FROM " + tableName;
assertTrue(conn1.prepareStatement(query).executeQuery().next());
}
}
@Test
public void testAddKVColumnToNewFamily() throws Exception {
String tenantId = getOrganizationId();
String tableName =
initATableValues(null, tenantId, getDefaultSplits(tenantId), null, null, getUrl(),
null);
try (Connection conn1 = DriverManager.getConnection(getUrl())) {
conn1.createStatement()
.executeUpdate("ALTER TABLE " + tableName + " ADD newcf.z_integer integer");
String query = "SELECT z_integer FROM " + tableName;
assertTrue(conn1.prepareStatement(query).executeQuery().next());
}
}
@Test
public void testAddPKColumn() throws Exception {
String tenantId = getOrganizationId();
String tableName =
initATableValues(null, tenantId, getDefaultSplits(tenantId), null, null, getUrl(),
null);
try (Connection conn1 = DriverManager.getConnection(getUrl())) {
try {
conn1.createStatement().executeUpdate(
"ALTER TABLE " + tableName + " ADD z_string varchar not null primary key");
fail();
} catch (SQLException e) {
assertTrue(e.getMessage(), e.getMessage().contains(
"ERROR 1006 (42J04): Only nullable columns may be added to a multi-part row key."));
}
conn1.createStatement().executeUpdate(
"ALTER TABLE " + tableName + " ADD z_string varchar primary key");
String query = "SELECT z_string FROM " + tableName;
assertTrue(conn1.prepareStatement(query).executeQuery().next());
}
}
@Test
public void testDropKVColumn() throws Exception {
String tenantId = getOrganizationId();
String tableName =
initATableValues(null, tenantId, getDefaultSplits(tenantId), null, null, getUrl(),
null);
try (Connection conn5 = DriverManager.getConnection(getUrl())) {
assertTrue(conn5.createStatement()
.executeQuery("SELECT 1 FROM " + tableName + " WHERE b_string IS NOT NULL")
.next());
conn5.createStatement()
.executeUpdate("ALTER TABLE " + tableName + " DROP COLUMN b_string");
String query = "SELECT b_string FROM " + tableName;
try {
conn5.prepareStatement(query).executeQuery().next();
fail();
} catch (ColumnNotFoundException e) {
}
conn5.createStatement()
.executeUpdate("ALTER TABLE " + tableName + " ADD b_string VARCHAR");
assertFalse(conn5.createStatement()
.executeQuery("SELECT 1 FROM " + tableName + " WHERE b_string IS NOT NULL")
.next());
}
}
@Test
public void testDropPKColumn() throws Exception {
String tenantId = getOrganizationId();
String tableName =
initATableValues(generateUniqueName(), tenantId, getDefaultSplits(tenantId), null,
null, getUrl(), null);
try (Connection conn1 = DriverManager.getConnection(getUrl())) {
conn1.createStatement()
.executeUpdate("ALTER TABLE " + tableName + " DROP COLUMN entity_id");
fail();
} catch (SQLException e) {
assertTrue(e.getMessage(), e.getMessage()
.contains("ERROR 506 (42817): Primary key column may not be dropped."));
}
}
@Test
public void testDropAllKVCols() throws Exception {
ResultSet rs;
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
String tableName = generateUniqueName();
createMDTestTable(conn, tableName, "");
conn.createStatement().executeUpdate("UPSERT INTO " + tableName + " VALUES('a',1,1)");
conn.createStatement().executeUpdate("UPSERT INTO " + tableName + " VALUES('b',2,2)");
conn.commit();
rs = conn.createStatement().executeQuery("SELECT count(1) FROM " + tableName);
assertTrue(rs.next());
assertEquals(2, rs.getLong(1));
conn.createStatement().executeUpdate("ALTER TABLE " + tableName + " DROP COLUMN col1");
rs = conn.createStatement().executeQuery("SELECT count(1) FROM " + tableName);
assertTrue(rs.next());
assertEquals(2, rs.getLong(1));
conn.createStatement().executeUpdate("ALTER TABLE " + tableName + " DROP COLUMN col2");
rs = conn.createStatement().executeQuery("SELECT count(1) FROM " + tableName);
assertTrue(rs.next());
assertEquals(2, rs.getLong(1));
}
}
@Test
public void testTableWithScemaMetadataScan() throws SQLException {
try (Connection conn = DriverManager.getConnection(getUrl())) {
String table1 = generateUniqueName();
String schema1 = generateUniqueName();
String fullTable1 = schema1 + "." + table1;
String table2 = table1;
conn.createStatement()
.execute("create table " + fullTable1 + " (k varchar primary key)");
conn.createStatement().execute("create table " + table2 + " (k varchar primary key)");
DatabaseMetaData metaData = conn.getMetaData();
ResultSet rs;
// Tricky case that requires returning false for null AND true expression
rs = metaData.getTables(null, schema1, table1, null);
assertTrue(rs.next());
assertEquals(schema1, rs.getString("TABLE_SCHEM"));
assertEquals(table1, rs.getString("TABLE_NAME"));
assertFalse(rs.next());
// Tricky case that requires end key to maintain trailing nulls
rs = metaData.getTables("", schema1, table1, null);
assertTrue(rs.next());
assertEquals(schema1, rs.getString("TABLE_SCHEM"));
assertEquals(table1, rs.getString("TABLE_NAME"));
assertFalse(rs.next());
rs = metaData.getTables("", null, table2, null);
assertTrue(rs.next());
assertEquals(null, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertTrue(rs.next());
assertEquals(schema1, rs.getString("TABLE_SCHEM"));
assertEquals(table1, rs.getString("TABLE_NAME"));
assertFalse(rs.next());
}
}
@Test
public void testRemarkColumn() throws SQLException {
Connection conn = DriverManager.getConnection(getUrl());
// Retrieve the database metadata
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getColumns(null, null, null, null);
rs.next();
// Lookup column by name, this should return null but not throw an exception
String remarks = rs.getString("REMARKS");
assertNull(remarks);
// Same as above, but lookup by position
remarks = rs.getString(12);
assertNull(remarks);
// Iterate through metadata columns to find 'COLUMN_NAME' == 'REMARKS'
boolean foundRemarksColumn = false;
while (rs.next()) {
String colName = rs.getString("COLUMN_NAME");
if (PhoenixDatabaseMetaData.REMARKS.equals(colName)) {
foundRemarksColumn = true;
break;
}
}
assertTrue("Could not find REMARKS column", foundRemarksColumn);
}
}
| phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryDatabaseMetaDataIT.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.phoenix.end2end;
import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA;
import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_CATALOG_TABLE;
import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.SYSTEM_FUNCTION_TABLE;
import static org.apache.phoenix.jdbc.PhoenixDatabaseMetaData.TYPE_SEQUENCE;
import static org.apache.phoenix.util.TestUtil.ATABLE_NAME;
import static org.apache.phoenix.util.TestUtil.CUSTOM_ENTITY_DATA_FULL_NAME;
import static org.apache.phoenix.util.TestUtil.PTSDB_NAME;
import static org.apache.phoenix.util.TestUtil.STABLE_NAME;
import static org.apache.phoenix.util.TestUtil.TABLE_WITH_SALTING;
import static org.apache.phoenix.util.TestUtil.TEST_PROPERTIES;
import static org.apache.phoenix.util.TestUtil.createGroupByTestTable;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.phoenix.coprocessor.GroupedAggregateRegionObserver;
import org.apache.phoenix.coprocessor.ServerCachingEndpointImpl;
import org.apache.phoenix.coprocessor.UngroupedAggregateRegionObserver;
import org.apache.phoenix.jdbc.PhoenixConnection;
import org.apache.phoenix.jdbc.PhoenixDatabaseMetaData;
import org.apache.phoenix.schema.ColumnNotFoundException;
import org.apache.phoenix.schema.PTable.ViewType;
import org.apache.phoenix.schema.PTableType;
import org.apache.phoenix.schema.ReadOnlyTableException;
import org.apache.phoenix.schema.TableNotFoundException;
import org.apache.phoenix.schema.types.PChar;
import org.apache.phoenix.schema.types.PDecimal;
import org.apache.phoenix.schema.types.PInteger;
import org.apache.phoenix.schema.types.PLong;
import org.apache.phoenix.util.PropertiesUtil;
import org.apache.phoenix.util.SchemaUtil;
import org.apache.phoenix.util.StringUtil;
import org.junit.Before;
import org.junit.Test;
public class QueryDatabaseMetaDataIT extends ParallelStatsDisabledIT {
private static void createMDTestTable(Connection conn, String tableName, String extraProps)
throws SQLException {
String ddl =
"create table if not exists " + tableName + " (id char(1) primary key,\n"
+ " a.col1 integer,\n" + " b.col2 bigint,\n" + " b.col3 decimal,\n"
+ " b.col4 decimal(5),\n" + " b.col5 decimal(6,3))\n" + " a."
+ HConstants.VERSIONS + "=" + 1 + "," + "a."
+ HColumnDescriptor.DATA_BLOCK_ENCODING + "='" + DataBlockEncoding.NONE
+ "'";
if (extraProps != null && extraProps.length() > 0) {
ddl += "," + extraProps;
}
conn.createStatement().execute(ddl);
}
@Before
// We need to clean up phoenix metadata to ensure tests don't step on each other
public void deleteMetadata() throws Exception {
try (Connection conn = DriverManager.getConnection(getUrl())) {
String delete =
"DELETE FROM SYSTEM.CATALOG WHERE TABLE_SCHEM IS NULL OR TABLE_SCHEM = '' OR TABLE_SCHEM != 'SYSTEM'";
conn.createStatement().executeUpdate(delete);
conn.commit();
delete = "DELETE FROM \"SYSTEM\".\"SEQUENCE\"";
conn.createStatement().executeUpdate(delete);
conn.commit();
}
}
@Test
public void testTableMetadataScan() throws SQLException {
String tableAName = generateUniqueName() + "TABLE";
String tableASchema = "";
ensureTableCreated(getUrl(), tableAName, ATABLE_NAME, null);
String tableS = generateUniqueName() + "TABLE";
ensureTableCreated(getUrl(), tableS, STABLE_NAME, null);
String tableC = generateUniqueName();
String tableCSchema = generateUniqueName();
ensureTableCreated(getUrl(), tableCSchema + "." + tableC, CUSTOM_ENTITY_DATA_FULL_NAME,
null);
try (Connection conn = DriverManager.getConnection(getUrl())) {
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getTables(null, tableASchema, tableAName, null);
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_NAME"), tableAName);
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertEquals(rs.getString(3), tableAName);
assertEquals(PTableType.TABLE.toString(), rs.getString(4));
assertFalse(rs.next());
rs = dbmd.getTables(null, null, null, null);
assertTrue(rs.next());
assertEquals(SYSTEM_CATALOG_SCHEMA, rs.getString("TABLE_SCHEM"));
assertEquals(SYSTEM_CATALOG_TABLE, rs.getString("TABLE_NAME"));
assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals(SYSTEM_CATALOG_SCHEMA, rs.getString("TABLE_SCHEM"));
assertEquals(SYSTEM_FUNCTION_TABLE, rs.getString("TABLE_NAME"));
assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals(SYSTEM_CATALOG_SCHEMA, rs.getString("TABLE_SCHEM"));
assertEquals(TYPE_SEQUENCE, rs.getString("TABLE_NAME"));
assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals(SYSTEM_CATALOG_SCHEMA, rs.getString("TABLE_SCHEM"));
assertEquals(PhoenixDatabaseMetaData.SYSTEM_STATS_TABLE, rs.getString("TABLE_NAME"));
assertEquals(PTableType.SYSTEM.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals(null, rs.getString("TABLE_SCHEM"));
assertEquals(tableAName, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals(null, rs.getString("TABLE_SCHEM"));
assertEquals(tableS, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals(tableCSchema, rs.getString("TABLE_SCHEM"));
assertEquals(tableC, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertEquals("false", rs.getString(PhoenixDatabaseMetaData.TRANSACTIONAL));
assertEquals(Boolean.FALSE, rs.getBoolean(PhoenixDatabaseMetaData.IS_NAMESPACE_MAPPED));
rs = dbmd.getTables(null, tableCSchema, tableC, null);
assertTrue(rs.next());
try {
rs.getString("RANDOM_COLUMN_NAME");
fail();
} catch (ColumnNotFoundException e) {
// expected
}
assertEquals(tableCSchema, rs.getString("TABLE_SCHEM"));
assertEquals(tableC, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertFalse(rs.next());
rs = dbmd.getTables(null, "", "%TABLE", new String[] { PTableType.TABLE.toString() });
assertTrue(rs.next());
assertEquals(null, rs.getString("TABLE_SCHEM"));
assertEquals(tableAName, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertEquals(null, rs.getString("TABLE_SCHEM"));
assertEquals(tableS, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertFalse(rs.next());
}
}
@Test
public void testTableTypes() throws SQLException {
try (Connection conn = DriverManager.getConnection(getUrl())) {
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getTableTypes();
assertTrue(rs.next());
assertEquals("INDEX", rs.getString(1));
assertTrue(rs.next());
assertEquals("SEQUENCE", rs.getString(1));
assertTrue(rs.next());
assertEquals("SYSTEM TABLE", rs.getString(1));
assertTrue(rs.next());
assertEquals("TABLE", rs.getString(1));
assertTrue(rs.next());
assertEquals("VIEW", rs.getString(1));
assertFalse(rs.next());
}
}
@Test
public void testSequenceMetadataScan() throws SQLException {
try (Connection conn = DriverManager.getConnection(getUrl())) {
String schema1 = "B" + generateUniqueName();
String seq1 = generateUniqueName();
String seq1FullName = schema1 + "." + seq1;
String schema2 = generateUniqueName();
String seq2 = generateUniqueName();
String seq2FullName = schema2 + "." + seq2;
String schema3 = schema1;
String seq3 = generateUniqueName();
String seq3FullName = schema3 + "." + seq3;
String schema4 = generateUniqueName();
String seq4 = seq1;
String seq4FullName = schema4 + "." + seq4;
conn.createStatement().execute("CREATE SEQUENCE " + seq1FullName);
conn.createStatement().execute("CREATE SEQUENCE " + seq2FullName);
conn.createStatement().execute("CREATE SEQUENCE " + seq3FullName);
conn.createStatement().execute("CREATE SEQUENCE " + seq4FullName);
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getTables(null, null, null, new String[] { "FOO" });
assertFalse(rs.next());
rs =
dbmd.getTables(null, null, null,
new String[] { "FOO", PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE });
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema1, rs.getString("TABLE_SCHEM"));
assertEquals(seq1, rs.getString("TABLE_NAME"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema3, rs.getString("TABLE_SCHEM"));
assertEquals(seq3, rs.getString("TABLE_NAME"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(seq2, rs.getString("TABLE_NAME"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema4, rs.getString("TABLE_SCHEM"));
assertEquals(seq4, rs.getString("TABLE_NAME"));
assertFalse(rs.next());
String foo = generateUniqueName();
String basSchema = generateUniqueName();
String bas = generateUniqueName();
conn.createStatement().execute("CREATE TABLE " + foo + " (k bigint primary key)");
conn.createStatement()
.execute("CREATE TABLE " + basSchema + "." + bas + " (k bigint primary key)");
dbmd = conn.getMetaData();
rs =
dbmd.getTables(null, null, null, new String[] { PTableType.TABLE.toString(),
PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE });
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema1, rs.getString("TABLE_SCHEM"));
assertEquals(seq1, rs.getString("TABLE_NAME"));
assertEquals(PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE, rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema3, rs.getString("TABLE_SCHEM"));
assertEquals(seq3, rs.getString("TABLE_NAME"));
assertEquals(PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE, rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(seq2, rs.getString("TABLE_NAME"));
assertEquals(PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE, rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema4, rs.getString("TABLE_SCHEM"));
assertEquals(seq4, rs.getString("TABLE_NAME"));
assertEquals(PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE, rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertNull(rs.getString("TABLE_SCHEM"));
assertEquals(foo, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(basSchema, rs.getString("TABLE_SCHEM"));
assertEquals(bas, rs.getString("TABLE_NAME"));
assertEquals(PTableType.TABLE.toString(), rs.getString("TABLE_TYPE"));
assertFalse(rs.next());
rs =
dbmd.getTables(null, "B%", null,
new String[] { PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE });
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema1, rs.getString("TABLE_SCHEM"));
assertEquals(seq1, rs.getString("TABLE_NAME"));
assertEquals(PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE, rs.getString("TABLE_TYPE"));
assertTrue(rs.next());
assertNull(rs.getString("TABLE_CAT"));
assertEquals(schema3, rs.getString("TABLE_SCHEM"));
assertEquals(seq3, rs.getString("TABLE_NAME"));
assertEquals(PhoenixDatabaseMetaData.SEQUENCE_TABLE_TYPE, rs.getString("TABLE_TYPE"));
assertFalse(rs.next());
}
}
@Test
public void testSchemaMetadataScan() throws SQLException {
String table1 = generateUniqueName();
String schema1 = generateUniqueName();
String fullTable1 = schema1 + "." + table1;
ensureTableCreated(getUrl(), fullTable1, CUSTOM_ENTITY_DATA_FULL_NAME, null);
String fullTable2 = generateUniqueName();
ensureTableCreated(getUrl(), fullTable2, PTSDB_NAME, null);
try (Connection conn = DriverManager.getConnection(getUrl())) {
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs;
rs = dbmd.getSchemas(null, schema1);
assertTrue(rs.next());
assertEquals(rs.getString(1), schema1);
assertEquals(rs.getString(2), null);
assertFalse(rs.next());
rs = dbmd.getSchemas(null, null);
assertTrue(rs.next());
assertEquals(null, rs.getString("TABLE_SCHEM"));
assertEquals(null, rs.getString("TABLE_CATALOG"));
assertTrue(rs.next());
assertEquals(PhoenixDatabaseMetaData.SYSTEM_CATALOG_SCHEMA,
rs.getString("TABLE_SCHEM"));
assertEquals(null, rs.getString("TABLE_CATALOG"));
assertTrue(rs.next());
assertEquals(schema1, rs.getString("TABLE_SCHEM"));
assertEquals(null, rs.getString("TABLE_CATALOG"));
assertFalse(rs.next());
}
}
@Test
public void testColumnMetadataScan() throws SQLException {
Connection conn = DriverManager.getConnection(getUrl());
String table = generateUniqueName();
createMDTestTable(conn, table, "");
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs;
rs = dbmd.getColumns(null, "", table, null);
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNoNulls, rs.getShort("NULLABLE"));
assertEquals(PChar.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(1, rs.getInt("ORDINAL_POSITION"));
assertEquals(1, rs.getInt("COLUMN_SIZE"));
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PInteger.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(2, rs.getInt("ORDINAL_POSITION"));
assertEquals(0, rs.getInt("COLUMN_SIZE"));
assertTrue(rs.wasNull());
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.wasNull());
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PLong.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(3, rs.getInt("ORDINAL_POSITION"));
assertEquals(0, rs.getInt("COLUMN_SIZE"));
assertTrue(rs.wasNull());
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.wasNull());
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PDecimal.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(4, rs.getInt("ORDINAL_POSITION"));
assertEquals(0, rs.getInt("COLUMN_SIZE"));
assertTrue(rs.wasNull());
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.wasNull());
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PDecimal.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(5, rs.getInt("ORDINAL_POSITION"));
assertEquals(5, rs.getInt("COLUMN_SIZE"));
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PDecimal.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(6, rs.getInt("ORDINAL_POSITION"));
assertEquals(6, rs.getInt("COLUMN_SIZE"));
assertEquals(3, rs.getInt("DECIMAL_DIGITS"));
assertFalse(rs.next());
// Look up only columns in a column family
rs = dbmd.getColumns(null, "", table, "A.");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PInteger.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(2, rs.getInt("ORDINAL_POSITION"));
assertEquals(0, rs.getInt("COLUMN_SIZE"));
assertTrue(rs.wasNull());
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.wasNull());
assertFalse(rs.next());
// Look up KV columns in a column family
rs = dbmd.getColumns("", "", table, "%.COL%");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PInteger.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(2, rs.getInt("ORDINAL_POSITION"));
assertEquals(0, rs.getInt("COLUMN_SIZE"));
assertTrue(rs.wasNull());
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.wasNull());
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PLong.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(3, rs.getInt("ORDINAL_POSITION"));
assertEquals(0, rs.getInt("COLUMN_SIZE"));
assertTrue(rs.wasNull());
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.wasNull());
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PDecimal.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(4, rs.getInt("ORDINAL_POSITION"));
assertEquals(0, rs.getInt("COLUMN_SIZE"));
assertTrue(rs.wasNull());
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertTrue(rs.wasNull());
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PDecimal.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(5, rs.getInt("ORDINAL_POSITION"));
assertEquals(5, rs.getInt("COLUMN_SIZE"));
assertEquals(0, rs.getInt("DECIMAL_DIGITS"));
assertFalse(rs.wasNull());
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME"));
assertEquals(DatabaseMetaData.attributeNullable, rs.getShort("NULLABLE"));
assertEquals(PDecimal.INSTANCE.getSqlType(), rs.getInt("DATA_TYPE"));
assertEquals(6, rs.getInt("ORDINAL_POSITION"));
assertEquals(6, rs.getInt("COLUMN_SIZE"));
assertEquals(3, rs.getInt("DECIMAL_DIGITS"));
assertFalse(rs.next());
// Look up KV columns in a column family
rs = dbmd.getColumns("", "", table, "B.COL2");
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table, rs.getString("TABLE_NAME"));
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME"));
assertFalse(rs.next());
String table2 = generateUniqueName();
ensureTableCreated(getUrl(), table2, TABLE_WITH_SALTING, null);
rs = dbmd.getColumns("", "", table2, StringUtil.escapeLike("A_INTEGER"));
assertTrue(rs.next());
assertEquals(1, rs.getInt("ORDINAL_POSITION"));
assertFalse(rs.next());
}
@Test
public void testPrimaryKeyMetadataScan() throws SQLException {
try (Connection conn = DriverManager.getConnection(getUrl())) {
String table1 = generateUniqueName();
createMDTestTable(conn, table1, "");
String schema2 = generateUniqueName();
String table2 = generateUniqueName();
String fullTable2 = schema2 + "." + table2;
ensureTableCreated(getUrl(), fullTable2, CUSTOM_ENTITY_DATA_FULL_NAME, null);
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs;
rs = dbmd.getPrimaryKeys(null, "", table1);
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(table1, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME"));
assertEquals(1, rs.getInt("KEY_SEQ"));
assertEquals(null, rs.getString("PK_NAME"));
assertFalse(rs.next());
rs = dbmd.getPrimaryKeys(null, schema2, table2);
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("custom_entity_data_id"),
rs.getString("COLUMN_NAME"));
assertEquals(3, rs.getInt("KEY_SEQ"));
assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME"));
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME"));
assertEquals(2, rs.getInt("KEY_SEQ"));
assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME"));
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("organization_id"),
rs.getString("COLUMN_NAME"));
assertEquals(1, rs.getInt("KEY_SEQ"));
assertEquals(SchemaUtil.normalizeIdentifier("pk"), rs.getString("PK_NAME")); // TODO:
// this is
// on the
// table
// row
assertFalse(rs.next());
rs = dbmd.getColumns("", schema2, table2, null);
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("organization_id"),
rs.getString("COLUMN_NAME"));
assertEquals(rs.getInt("COLUMN_SIZE"), 15);
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME"));
assertEquals(rs.getInt("COLUMN_SIZE"), 3);
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("custom_entity_data_id"),
rs.getString("COLUMN_NAME"));
// The above returns all columns, starting with the PK columns
assertTrue(rs.next());
rs = dbmd.getColumns("", schema2, table2, "KEY_PREFIX");
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME"));
rs = dbmd.getColumns("", schema2, table2, "KEY_PREFIX");
assertTrue(rs.next());
assertEquals(schema2, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals(SchemaUtil.normalizeIdentifier("key_prefix"), rs.getString("COLUMN_NAME"));
assertFalse(rs.next());
String table3 = generateUniqueName();
conn.createStatement().execute(
"CREATE TABLE " + table3 + " (k INTEGER PRIMARY KEY, v VARCHAR) SALT_BUCKETS=3");
dbmd = conn.getMetaData();
rs = dbmd.getPrimaryKeys(null, "", table3);
assertTrue(rs.next());
assertEquals(null, rs.getString("TABLE_SCHEM"));
assertEquals(table3, rs.getString("TABLE_NAME"));
assertEquals(null, rs.getString("TABLE_CAT"));
assertEquals("K", rs.getString("COLUMN_NAME"));
assertEquals(1, rs.getInt("KEY_SEQ"));
assertEquals(null, rs.getString("PK_NAME"));
assertFalse(rs.next());
}
}
@Test
public void testMultiTableColumnsMetadataScan() throws SQLException {
try (Connection conn = DriverManager.getConnection(getUrl())) {
String table1 = "TEST" + generateUniqueName();
String table2 = "TEST" + generateUniqueName();
createGroupByTestTable(conn, table1);
createMDTestTable(conn, table2, "");
String table3 = generateUniqueName();
ensureTableCreated(getUrl(), table3, PTSDB_NAME, null);
String table4 = generateUniqueName();
ensureTableCreated(getUrl(), table4, CUSTOM_ENTITY_DATA_FULL_NAME, null);
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getColumns(null, "", "%TEST%", null);
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table1);
assertEquals(null, rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table1);
assertEquals(PhoenixDatabaseMetaData.TABLE_FAMILY, rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("uri"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table1);
assertEquals(PhoenixDatabaseMetaData.TABLE_FAMILY, rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("appcpu"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table2);
assertEquals(null, rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("id"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table2);
assertEquals(SchemaUtil.normalizeIdentifier("a"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col1"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table2);
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col2"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table2);
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col3"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table2);
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col4"), rs.getString("COLUMN_NAME"));
assertTrue(rs.next());
assertEquals(rs.getString("TABLE_SCHEM"), null);
assertEquals(rs.getString("TABLE_NAME"), table2);
assertEquals(SchemaUtil.normalizeIdentifier("b"), rs.getString("COLUMN_FAMILY"));
assertEquals(SchemaUtil.normalizeIdentifier("col5"), rs.getString("COLUMN_NAME"));
assertFalse(rs.next());
}
}
@Test
public void testCreateOnExistingTable() throws Exception {
try (PhoenixConnection pconn =
DriverManager.getConnection(getUrl()).unwrap(PhoenixConnection.class)) {
String tableName = generateUniqueName();// MDTEST_NAME;
String schemaName = "";// MDTEST_SCHEMA_NAME;
byte[] cfA = Bytes.toBytes(SchemaUtil.normalizeIdentifier("a"));
byte[] cfB = Bytes.toBytes(SchemaUtil.normalizeIdentifier("b"));
byte[] cfC = Bytes.toBytes("c");
byte[][] familyNames = new byte[][] { cfB, cfC };
byte[] htableName = SchemaUtil.getTableNameAsBytes(schemaName, tableName);
HBaseAdmin admin = pconn.getQueryServices().getAdmin();
try {
admin.disableTable(htableName);
admin.deleteTable(htableName);
admin.enableTable(htableName);
} catch (org.apache.hadoop.hbase.TableNotFoundException e) {
}
@SuppressWarnings("deprecation")
HTableDescriptor descriptor = new HTableDescriptor(htableName);
for (byte[] familyName : familyNames) {
HColumnDescriptor columnDescriptor = new HColumnDescriptor(familyName);
descriptor.addFamily(columnDescriptor);
}
admin.createTable(descriptor);
createMDTestTable(pconn, tableName,
"a." + HColumnDescriptor.KEEP_DELETED_CELLS + "=" + Boolean.TRUE);
descriptor = admin.getTableDescriptor(htableName);
assertEquals(3, descriptor.getColumnFamilies().length);
HColumnDescriptor cdA = descriptor.getFamily(cfA);
assertNotEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdA.getKeepDeletedCells());
assertEquals(DataBlockEncoding.NONE, cdA.getDataBlockEncoding()); // Overriden using
// WITH
assertEquals(1, cdA.getMaxVersions());// Overriden using WITH
HColumnDescriptor cdB = descriptor.getFamily(cfB);
// Allow KEEP_DELETED_CELLS to be false for VIEW
assertEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdB.getKeepDeletedCells());
assertEquals(DataBlockEncoding.NONE, cdB.getDataBlockEncoding()); // Should keep the
// original value.
// CF c should stay the same since it's not a Phoenix cf.
HColumnDescriptor cdC = descriptor.getFamily(cfC);
assertNotNull("Column family not found", cdC);
assertEquals(HColumnDescriptor.DEFAULT_KEEP_DELETED, cdC.getKeepDeletedCells());
assertFalse(SchemaUtil.DEFAULT_DATA_BLOCK_ENCODING == cdC.getDataBlockEncoding());
assertTrue(descriptor.hasCoprocessor(UngroupedAggregateRegionObserver.class.getName()));
assertTrue(descriptor.hasCoprocessor(GroupedAggregateRegionObserver.class.getName()));
assertTrue(descriptor.hasCoprocessor(ServerCachingEndpointImpl.class.getName()));
admin.close();
int rowCount = 5;
String upsert = "UPSERT INTO " + tableName + "(id,col1,col2) VALUES(?,?,?)";
PreparedStatement ps = pconn.prepareStatement(upsert);
for (int i = 0; i < rowCount; i++) {
ps.setString(1, Integer.toString(i));
ps.setInt(2, i + 1);
ps.setInt(3, i + 2);
ps.execute();
}
pconn.commit();
String query = "SELECT count(1) FROM " + tableName;
ResultSet rs = pconn.createStatement().executeQuery(query);
assertTrue(rs.next());
assertEquals(rowCount, rs.getLong(1));
query = "SELECT id, col1,col2 FROM " + tableName;
rs = pconn.createStatement().executeQuery(query);
for (int i = 0; i < rowCount; i++) {
assertTrue(rs.next());
assertEquals(Integer.toString(i), rs.getString(1));
assertEquals(i + 1, rs.getInt(2));
assertEquals(i + 2, rs.getInt(3));
}
assertFalse(rs.next());
}
}
@SuppressWarnings("deprecation")
@Test
public void testCreateViewOnExistingTable() throws Exception {
try (PhoenixConnection pconn =
DriverManager.getConnection(getUrl(), PropertiesUtil.deepCopy(TEST_PROPERTIES))
.unwrap(PhoenixConnection.class)) {
String tableName = generateUniqueName();// MDTEST_NAME;
String schemaName = "";// MDTEST_SCHEMA_NAME;
byte[] cfB = Bytes.toBytes(SchemaUtil.normalizeIdentifier("b"));
byte[] cfC = Bytes.toBytes("c");
byte[][] familyNames = new byte[][] { cfB, cfC };
byte[] htableName = SchemaUtil.getTableNameAsBytes(schemaName, tableName);
try (HBaseAdmin admin = pconn.getQueryServices().getAdmin()) {
try {
admin.disableTable(htableName);
admin.deleteTable(htableName);
} catch (org.apache.hadoop.hbase.TableNotFoundException e) {
}
HTableDescriptor descriptor = new HTableDescriptor(htableName);
for (byte[] familyName : familyNames) {
HColumnDescriptor columnDescriptor = new HColumnDescriptor(familyName);
descriptor.addFamily(columnDescriptor);
}
admin.createTable(descriptor);
}
String createStmt =
"create view " + generateUniqueName() + " (id char(1) not null primary key,\n"
+ " a.col1 integer,\n" + " d.col2 bigint)\n";
try {
pconn.createStatement().execute(createStmt);
fail();
} catch (TableNotFoundException e) {
// expected to fail b/c table doesn't exist
} catch (ReadOnlyTableException e) {
// expected to fail b/c table doesn't exist
}
createStmt =
"create view " + tableName + " (id char(1) not null primary key,\n"
+ " a.col1 integer,\n" + " b.col2 bigint)\n";
try {
pconn.createStatement().execute(createStmt);
fail();
} catch (ReadOnlyTableException e) {
// expected to fail b/c cf a doesn't exist
}
createStmt =
"create view " + tableName + " (id char(1) not null primary key,\n"
+ " b.col1 integer,\n" + " c.col2 bigint)\n";
try {
pconn.createStatement().execute(createStmt);
fail();
} catch (ReadOnlyTableException e) {
// expected to fail b/c cf C doesn't exist (case issue)
}
createStmt =
"create view " + tableName + " (id char(1) not null primary key,\n"
+ " b.col1 integer,\n"
+ " \"c\".col2 bigint) IMMUTABLE_ROWS=true \n";
// should be ok now
pconn.createStatement().execute(createStmt);
ResultSet rs = pconn.getMetaData().getTables(null, null, tableName, null);
assertTrue(rs.next());
assertEquals(ViewType.MAPPED.name(), rs.getString(PhoenixDatabaseMetaData.VIEW_TYPE));
assertFalse(rs.next());
String deleteStmt = "DELETE FROM " + tableName;
PreparedStatement ps = pconn.prepareStatement(deleteStmt);
try {
ps.execute();
fail();
} catch (ReadOnlyTableException e) {
// expected to fail b/c table is read-only
}
String upsert = "UPSERT INTO " + tableName + "(id,col1,col2) VALUES(?,?,?)";
ps = pconn.prepareStatement(upsert);
try {
ps.setString(1, Integer.toString(0));
ps.setInt(2, 1);
ps.setInt(3, 2);
ps.execute();
fail();
} catch (ReadOnlyTableException e) {
// expected to fail b/c table is read-only
}
HTableInterface htable =
pconn.getQueryServices()
.getTable(SchemaUtil.getTableNameAsBytes(schemaName, tableName));
Put put = new Put(Bytes.toBytes("0"));
put.add(cfB, Bytes.toBytes("COL1"), PInteger.INSTANCE.toBytes(1));
put.add(cfC, Bytes.toBytes("COL2"), PLong.INSTANCE.toBytes(2));
htable.put(put);
// Should be ok b/c we've marked the view with IMMUTABLE_ROWS=true
pconn.createStatement().execute("CREATE INDEX idx ON " + tableName + "(B.COL1)");
String select = "SELECT col1 FROM " + tableName + " WHERE col2=?";
ps = pconn.prepareStatement(select);
ps.setInt(1, 2);
rs = ps.executeQuery();
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
assertFalse(rs.next());
String dropTable = "DROP TABLE " + tableName;
ps = pconn.prepareStatement(dropTable);
try {
ps.execute();
fail();
} catch (TableNotFoundException e) {
// expected to fail b/c it is a view
}
String alterView = "alter view " + tableName + " drop column \"c\".col2";
pconn.createStatement().execute(alterView);
}
}
@Test
public void testAddKVColumnToExistingFamily() throws Throwable {
String tenantId = getOrganizationId();
String tableName = generateUniqueName();
initATableValues(tableName, tenantId, getDefaultSplits(tenantId), null, null, getUrl(),
null);
try (Connection conn1 = DriverManager.getConnection(getUrl())) {
conn1.createStatement()
.executeUpdate("ALTER TABLE " + tableName + " ADD z_integer integer");
String query = "SELECT z_integer FROM " + tableName;
assertTrue(conn1.prepareStatement(query).executeQuery().next());
}
}
@Test
public void testAddKVColumnToNewFamily() throws Exception {
String tenantId = getOrganizationId();
String tableName =
initATableValues(null, tenantId, getDefaultSplits(tenantId), null, null, getUrl(),
null);
try (Connection conn1 = DriverManager.getConnection(getUrl())) {
conn1.createStatement()
.executeUpdate("ALTER TABLE " + tableName + " ADD newcf.z_integer integer");
String query = "SELECT z_integer FROM " + tableName;
assertTrue(conn1.prepareStatement(query).executeQuery().next());
}
}
@Test
public void testAddPKColumn() throws Exception {
String tenantId = getOrganizationId();
String tableName =
initATableValues(null, tenantId, getDefaultSplits(tenantId), null, null, getUrl(),
null);
try (Connection conn1 = DriverManager.getConnection(getUrl())) {
try {
conn1.createStatement().executeUpdate(
"ALTER TABLE " + tableName + " ADD z_string varchar not null primary key");
fail();
} catch (SQLException e) {
assertTrue(e.getMessage(), e.getMessage().contains(
"ERROR 1006 (42J04): Only nullable columns may be added to a multi-part row key."));
}
conn1.createStatement().executeUpdate(
"ALTER TABLE " + tableName + " ADD z_string varchar primary key");
String query = "SELECT z_string FROM " + tableName;
assertTrue(conn1.prepareStatement(query).executeQuery().next());
}
}
@Test
public void testDropKVColumn() throws Exception {
String tenantId = getOrganizationId();
String tableName =
initATableValues(null, tenantId, getDefaultSplits(tenantId), null, null, getUrl(),
null);
try (Connection conn5 = DriverManager.getConnection(getUrl())) {
assertTrue(conn5.createStatement()
.executeQuery("SELECT 1 FROM " + tableName + " WHERE b_string IS NOT NULL")
.next());
conn5.createStatement()
.executeUpdate("ALTER TABLE " + tableName + " DROP COLUMN b_string");
String query = "SELECT b_string FROM " + tableName;
try {
conn5.prepareStatement(query).executeQuery().next();
fail();
} catch (ColumnNotFoundException e) {
}
conn5.createStatement()
.executeUpdate("ALTER TABLE " + tableName + " ADD b_string VARCHAR");
assertFalse(conn5.createStatement()
.executeQuery("SELECT 1 FROM " + tableName + " WHERE b_string IS NOT NULL")
.next());
}
}
@Test
public void testDropPKColumn() throws Exception {
String tenantId = getOrganizationId();
String tableName =
initATableValues(generateUniqueName(), tenantId, getDefaultSplits(tenantId), null,
null, getUrl(), null);
try (Connection conn1 = DriverManager.getConnection(getUrl())) {
conn1.createStatement()
.executeUpdate("ALTER TABLE " + tableName + " DROP COLUMN entity_id");
fail();
} catch (SQLException e) {
assertTrue(e.getMessage(), e.getMessage()
.contains("ERROR 506 (42817): Primary key column may not be dropped."));
}
}
@Test
public void testDropAllKVCols() throws Exception {
ResultSet rs;
Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
try (Connection conn = DriverManager.getConnection(getUrl(), props)) {
String tableName = generateUniqueName();
createMDTestTable(conn, tableName, "");
conn.createStatement().executeUpdate("UPSERT INTO " + tableName + " VALUES('a',1,1)");
conn.createStatement().executeUpdate("UPSERT INTO " + tableName + " VALUES('b',2,2)");
conn.commit();
rs = conn.createStatement().executeQuery("SELECT count(1) FROM " + tableName);
assertTrue(rs.next());
assertEquals(2, rs.getLong(1));
conn.createStatement().executeUpdate("ALTER TABLE " + tableName + " DROP COLUMN col1");
rs = conn.createStatement().executeQuery("SELECT count(1) FROM " + tableName);
assertTrue(rs.next());
assertEquals(2, rs.getLong(1));
conn.createStatement().executeUpdate("ALTER TABLE " + tableName + " DROP COLUMN col2");
rs = conn.createStatement().executeQuery("SELECT count(1) FROM " + tableName);
assertTrue(rs.next());
assertEquals(2, rs.getLong(1));
}
}
@Test
public void testTableWithScemaMetadataScan() throws SQLException {
try (Connection conn = DriverManager.getConnection(getUrl())) {
String table1 = generateUniqueName();
String schema1 = generateUniqueName();
String fullTable1 = schema1 + "." + table1;
String table2 = table1;
conn.createStatement()
.execute("create table " + fullTable1 + " (k varchar primary key)");
conn.createStatement().execute("create table " + table2 + " (k varchar primary key)");
DatabaseMetaData metaData = conn.getMetaData();
ResultSet rs;
// Tricky case that requires returning false for null AND true expression
rs = metaData.getTables(null, schema1, table1, null);
assertTrue(rs.next());
assertEquals(schema1, rs.getString("TABLE_SCHEM"));
assertEquals(table1, rs.getString("TABLE_NAME"));
assertFalse(rs.next());
// Tricky case that requires end key to maintain trailing nulls
rs = metaData.getTables("", schema1, table1, null);
assertTrue(rs.next());
assertEquals(schema1, rs.getString("TABLE_SCHEM"));
assertEquals(table1, rs.getString("TABLE_NAME"));
assertFalse(rs.next());
rs = metaData.getTables("", null, table2, null);
assertTrue(rs.next());
assertEquals(null, rs.getString("TABLE_SCHEM"));
assertEquals(table2, rs.getString("TABLE_NAME"));
assertTrue(rs.next());
assertEquals(schema1, rs.getString("TABLE_SCHEM"));
assertEquals(table1, rs.getString("TABLE_NAME"));
assertFalse(rs.next());
}
}
@Test
public void testRemarkColumn() throws SQLException {
Connection conn = DriverManager.getConnection(getUrl());
// Retrieve the database metadata
DatabaseMetaData dbmd = conn.getMetaData();
ResultSet rs = dbmd.getColumns(null, null, null, null);
rs.next();
// Lookup column by name, this should return null but not throw an exception
String remarks = rs.getString("REMARKS");
assertNull(remarks);
// Same as above, but lookup by position
remarks = rs.getString(12);
assertNull(remarks);
// Iterate through metadata columns to find 'COLUMN_NAME' == 'REMARKS'
boolean foundRemarksColumn = false;
while (rs.next()) {
String colName = rs.getString("COLUMN_NAME");
if (PhoenixDatabaseMetaData.REMARKS.equals(colName)) {
foundRemarksColumn = true;
break;
}
}
assertTrue("Could not find REMARKS column", foundRemarksColumn);
}
}
| PHOENIX-4201 Addendum to clear cache in deleteMetadata
| phoenix-core/src/it/java/org/apache/phoenix/end2end/QueryDatabaseMetaDataIT.java | PHOENIX-4201 Addendum to clear cache in deleteMetadata |
|
Java | apache-2.0 | 4e0ac22f58e1ea75183b57d792b51c7cd262f8ae | 0 | Tycheo/coffeemud,bozimmerman/CoffeeMud,MaxRau/CoffeeMud,sfunk1x/CoffeeMud,oriontribunal/CoffeeMud,bozimmerman/CoffeeMud,Tycheo/coffeemud,Tycheo/coffeemud,MaxRau/CoffeeMud,sfunk1x/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud,oriontribunal/CoffeeMud,oriontribunal/CoffeeMud,MaxRau/CoffeeMud,bozimmerman/CoffeeMud,oriontribunal/CoffeeMud,sfunk1x/CoffeeMud | package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
/*
Copyright 2000-2007 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class BaseGenerics extends StdCommand
{
private final long maxLength=Long.MAX_VALUE;
// showNumber should always be a valid number no less than 1
// showFlag should be a valid number for editing, or -1 for skipping
protected void genName(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{
String newName=CMLib.english().prompt(mob,E.Name(),showNumber,showFlag,"Name",false,false);
if(newName.equals(E.Name())) return;
if((!CMath.bset(E.baseEnvStats().disposition(),EnvStats.IS_CATALOGED))
||((!(E instanceof MOB))&&(!(E instanceof Item)))
||(mob.session()==null))
{ E.setName(newName); return;}
int oldIndex=(E instanceof MOB)?
CMLib.map().getCatalogMobIndex(E.Name()):
CMLib.map().getCatalogItemIndex(E.Name());
if(oldIndex<0) return;
int[] usage=(E instanceof MOB)?
CMLib.map().getCatalogMobUsage(oldIndex):
CMLib.map().getCatalogItemUsage(oldIndex);
if(mob.session().confirm("This object is cataloged. Changing its name will detach it from the cataloged version, are you sure (y/N)?","N"))
{
E.setName(newName);
E.baseEnvStats().setDisposition(CMath.unsetb(E.baseEnvStats().disposition(), EnvStats.IS_CATALOGED));
E.envStats().setDisposition(CMath.unsetb(E.envStats().disposition(), EnvStats.IS_CATALOGED));
usage[0]--;
}
}
protected void catalogCheckUpdate(MOB mob, Environmental E)
throws IOException
{
if((!CMath.bset(E.baseEnvStats().disposition(),EnvStats.IS_CATALOGED))
||((!(E instanceof MOB))&&(!(E instanceof Item)))
||(mob.session()==null))
return;
int oldIndex=(E instanceof MOB)?
CMLib.map().getCatalogMobIndex(E.Name()):
CMLib.map().getCatalogItemIndex(E.Name());
if(oldIndex<0) return;
Environmental cataE=(E instanceof MOB)?
(Environmental)CMLib.map().getCatalogMob(oldIndex):
(Environmental)CMLib.map().getCatalogItem(oldIndex);
if(cataE.sameAs(E)) return;
int[] usage=(E instanceof MOB)?
CMLib.map().getCatalogMobUsage(oldIndex):
CMLib.map().getCatalogItemUsage(oldIndex);
E.baseEnvStats().setDisposition(CMath.unsetb(E.baseEnvStats().disposition(), EnvStats.IS_CATALOGED));
E.envStats().setDisposition(CMath.unsetb(E.envStats().disposition(), EnvStats.IS_CATALOGED));
if(mob.session().confirm("This object is cataloged. Enter Y to update the cataloged version, or N to detach this object from the catalog (Y/n)?","Y"))
{
cataE.setMiscText(E.text());
if(E instanceof MOB)
CMLib.database().DBUpdateMOB("CATALOG_MOBS",(MOB)cataE);
else
CMLib.database().DBUpdateItem("CATALOG_ITEMS",(Item)cataE);
E.baseEnvStats().setDisposition(E.baseEnvStats().disposition()|EnvStats.IS_CATALOGED);
E.envStats().setDisposition(E.envStats().disposition()|EnvStats.IS_CATALOGED);
CMLib.map().propogateCatalogChange(cataE);
mob.tell("Catalog update complete.");
}
else
{
E.baseEnvStats().setDisposition(CMath.unsetb(E.baseEnvStats().disposition(), EnvStats.IS_CATALOGED));
E.envStats().setDisposition(CMath.unsetb(E.envStats().disposition(), EnvStats.IS_CATALOGED));
usage[0]--;
}
}
protected void genImage(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.setImage(CMLib.english().prompt(mob,E.rawImage(),showNumber,showFlag,"MXP Image filename",true,false,"This is the path/filename of your MXP image file for this object."));}
protected void genCorpseData(MOB mob, DeadBody E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Corpse Data: '"+E.mobName()+"/"+E.killerName()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
mob.tell("Dead MOB name: '"+E.mobName()+"'.");
String newName=mob.session().prompt("Enter a new name\n\r:","");
if(newName.length()>0) E.setMobName(newName);
else mob.tell("(no change)");
mob.tell("Dead MOB Description: '"+E.mobDescription()+"'.");
newName=mob.session().prompt("Enter a new description\n\r:","");
if(newName.length()>0) E.setMobDescription(newName);
else mob.tell("(no change)");
mob.tell("Is a Players corpse: "+E.playerCorpse());
newName=mob.session().prompt("Enter a new true/false\n\r:","");
if((newName.length()>0)&&(newName.equalsIgnoreCase("true")||newName.equalsIgnoreCase("false")))
E.setPlayerCorpse(Boolean.valueOf(newName.toLowerCase()).booleanValue());
else mob.tell("(no change)");
mob.tell("Dead mobs PK flag: "+E.mobPKFlag());
newName=mob.session().prompt("Enter a new true/false\n\r:","");
if((newName.length()>0)&&(newName.equalsIgnoreCase("true")||newName.equalsIgnoreCase("false")))
E.setMobPKFlag(Boolean.valueOf(newName.toLowerCase()).booleanValue());
else mob.tell("(no change)");
genCharStats(mob,E.charStats());
mob.tell("Killers Name: '"+E.killerName()+"'.");
newName=mob.session().prompt("Enter a new killer\n\r:","");
if(newName.length()>0) E.setKillerName(newName);
else mob.tell("(no change)");
mob.tell("Killer is a player: "+E.killerPlayer());
newName=mob.session().prompt("Enter a new true/false\n\r:","");
if((newName.length()>0)&&(newName.equalsIgnoreCase("true")||newName.equalsIgnoreCase("false")))
E.setKillerPlayer(Boolean.valueOf(newName.toLowerCase()).booleanValue());
else mob.tell("(no change)");
mob.tell("Time of death: "+CMLib.time().date2String(E.timeOfDeath()));
newName=mob.session().prompt("Enter a new value\n\r:","");
if(newName.length()>0) E.setTimeOfDeath(CMLib.time().string2Millis(newName));
else mob.tell("(no change)");
mob.tell("Last message string: "+E.lastMessage());
newName=mob.session().prompt("Enter a new value\n\r:","");
if(newName.length()>0) E.setLastMessage(newName);
else mob.tell("(no change)");
}
protected void genAuthor(MOB mob, Area A, int showNumber, int showFlag) throws IOException
{ A.setAuthorID(CMLib.english().prompt(mob,A.getAuthorID(),showNumber,showFlag,"Author",true,false,"Area Author's Name"));}
protected void genPanelType(MOB mob, ShipComponent.ShipPanel S, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String componentType=CMStrings.capitalizeAndLower(ShipComponent.ShipPanel.COMPONENT_PANEL_DESC[S.panelType()].toLowerCase());
mob.tell(showNumber+". Panel Type: '"+componentType+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean continueThis=true;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(continueThis))
{
continueThis=false;
String newName=mob.session().prompt("Enter a new one (?)\n\r:","");
if(newName.length()>0)
{
if(newName.equalsIgnoreCase("?"))
{
mob.tell("Component Types: "+CMParms.toStringList(ShipComponent.ShipPanel.COMPONENT_PANEL_DESC));
continueThis=true;
}
else
{
int newType=-1;
for(int i=0;i<ShipComponent.ShipPanel.COMPONENT_PANEL_DESC.length;i++)
if(ShipComponent.ShipPanel.COMPONENT_PANEL_DESC[i].equalsIgnoreCase(newName))
newType=i;
if(newType<0)
{
mob.tell("'"+newName+"' is not recognized. Try '?' for a list.");
continueThis=true;
}
else
S.setPanelType(newType);
}
}
else
mob.tell("(no change)");
}
}
protected void genCurrency(MOB mob, Area A, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String currencyName=A.getCurrency().length()==0?"Default":A.getCurrency();
mob.tell(showNumber+". Currency: '"+currencyName+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a new one or 'DEFAULT'\n\r:","");
if(newName.length()>0)
{
if(newName.equalsIgnoreCase("default"))
A.setCurrency("");
else
if((newName.indexOf("=")<0)&&(!CMLib.beanCounter().getAllCurrencies().contains(newName.trim().toUpperCase())))
{
Vector V=CMLib.beanCounter().getAllCurrencies();
mob.tell("'"+newName.trim().toUpperCase()+"' is not a known currency. Existing currencies include: DEFAULT"+CMParms.toStringList(V));
}
else
if(newName.indexOf("=")>=0)
A.setCurrency(newName.trim());
else
A.setCurrency(newName.toUpperCase().trim());
}
else
mob.tell("(no change)");
}
protected void genTimeClock(MOB mob, Area A, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
TimeClock TC=A.getTimeObj();
StringBuffer report=new StringBuffer("");
if(TC==CMClass.globalClock())
report.append("Default -- Can't be changed.");
else
{
report.append(TC.getHoursInDay()+" hrs-day/");
report.append(TC.getDaysInMonth()+" days-mn/");
report.append(TC.getMonthsInYear()+" mnths-yr");
}
mob.tell(showNumber+". Calendar: '"+report.toString()+"'.");
if(TC==CMClass.globalClock()) return;
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName="";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.length()==0))
{
report=new StringBuffer("\n\rCalendar/Clock settings:\n\r");
report.append("1. "+TC.getHoursInDay()+" hours per day\n\r");
report.append("2. Dawn Hour: "+TC.getDawnToDusk()[TimeClock.TIME_DAWN]+"\n\r");
report.append("3. Day Hour: "+TC.getDawnToDusk()[TimeClock.TIME_DAY]+"\n\r");
report.append("4. Dusk Hour: "+TC.getDawnToDusk()[TimeClock.TIME_DUSK]+"\n\r");
report.append("5. Night Hour: "+TC.getDawnToDusk()[TimeClock.TIME_NIGHT]+"\n\r");
report.append("6. Weekdays: "+CMParms.toStringList(TC.getWeekNames())+"\n\r");
report.append("7. Months: "+CMParms.toStringList(TC.getMonthNames())+"\n\r");
report.append("8. Year Title(s): "+CMParms.toStringList(TC.getYearNames()));
mob.tell(report.toString());
newName=mob.session().prompt("Enter one to change:","");
if(newName.length()==0) break;
int which=CMath.s_int(newName);
if((which<0)||(which>8))
mob.tell("Invalid: "+which+"");
else
if(which<=5)
{
newName="";
String newNum=mob.session().prompt("Enter a new number:","");
int val=CMath.s_int(newNum);
if(newNum.length()==0)
mob.tell("(no change)");
else
switch(which)
{
case 1:
TC.setHoursInDay(val);
break;
case 2:
TC.getDawnToDusk()[TimeClock.TIME_DAWN]=val;
break;
case 3:
if((val>=0)&&(TC.getDawnToDusk()[TimeClock.TIME_DAWN]>=val))
mob.tell("That value is before the dawn!");
else
TC.getDawnToDusk()[TimeClock.TIME_DAY]=val;
break;
case 4:
if((val>=0)&&(TC.getDawnToDusk()[TimeClock.TIME_DAWN]>=val))
mob.tell("That value is before the dawn!");
else
if((val>=0)&&(TC.getDawnToDusk()[TimeClock.TIME_DAY]>=val))
mob.tell("That value is before the day!");
else
TC.getDawnToDusk()[TimeClock.TIME_DUSK]=val;
break;
case 5:
if((val>=0)&&(TC.getDawnToDusk()[TimeClock.TIME_DAWN]>=val))
mob.tell("That value is before the dawn!");
else
if((val>=0)&&(TC.getDawnToDusk()[TimeClock.TIME_DAY]>=val))
mob.tell("That value is before the day!");
else
if((val>=0)&&(TC.getDawnToDusk()[TimeClock.TIME_DUSK]>=val))
mob.tell("That value is before the dusk!");
else
TC.getDawnToDusk()[TimeClock.TIME_NIGHT]=val;
break;
}
}
else
{
newName="";
String newNum=mob.session().prompt("Enter a new list (comma delimited)\n\r:","");
if(newNum.length()==0)
mob.tell("(no change)");
else
switch(which)
{
case 6:
TC.setDaysInWeek(CMParms.toStringArray(CMParms.parseCommas(newNum,true)));
break;
case 7:
TC.setMonthsInYear(CMParms.toStringArray(CMParms.parseCommas(newNum,true)));
break;
case 8:
TC.setYearNames(CMParms.toStringArray(CMParms.parseCommas(newNum,true)));
break;
}
}
}
TC.save();
}
protected void genClan(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag<=0)||(showFlag==showNumber))
{
mob.tell(showNumber+". Clan (ID): '"+E.getClanID()+"'.");
if((showFlag==showNumber)||(showFlag<=-999))
{
String newName=mob.session().prompt("Enter a new one (null)\n\r:","");
if(newName.equalsIgnoreCase("null"))
E.setClanID("");
else
if(newName.length()>0)
{
E.setClanID(newName);
E.setClanRole(Clan.POS_MEMBER);
}
else
mob.tell("(no change)");
}
}
if(((showFlag<=0)||(showFlag==showNumber))
&&(!E.isMonster())
&&(E.getClanID().length()>0)
&&(CMLib.clans().getClan(E.getClanID())!=null))
{
Clan C=CMLib.clans().getClan(E.getClanID());
mob.tell(showNumber+". Clan (Role): '"+CMLib.clans().getRoleName(C.getGovernment(),E.getClanRole(),true,false)+"'.");
if((showFlag==showNumber)||(showFlag<=-999))
{
String newName=mob.session().prompt("Enter a new one\n\r:","");
if(newName.length()>0)
{
int newRole=-1;
for(int i=0;i<Clan.ROL_DESCS[C.getGovernment()].length;i++)
if(newName.equalsIgnoreCase(Clan.ROL_DESCS[C.getGovernment()][i]))
{
newRole=(int)CMath.pow(2,i-1);
break;
}
if(newRole<0)
mob.tell("That role is invalid. Try: "+CMParms.toStringList(Clan.ROL_DESCS[C.getGovernment()]));
else
E.setClanRole(newRole);
}
else
mob.tell("(no change)");
}
}
}
protected void genArchivePath(MOB mob, Area E, int showNumber, int showFlag) throws IOException
{ E.setArchivePath(CMLib.english().prompt(mob,E.getArchivePath(),showNumber,showFlag,"Archive Path",true,false,"Path/filename for EXPORT AREA command. Enter NULL for default."));}
protected Room changeRoomType(Room R, Room newRoom)
{
if((R==null)||(newRoom==null)) return R;
synchronized(("SYNC"+R.roomID()).intern())
{
R=CMLib.map().getRoom(R);
Room oldR=R;
R=newRoom;
Vector oldBehavsNEffects=new Vector();
for(int a=oldR.numEffects()-1;a>=0;a--)
{
Ability A=oldR.fetchEffect(a);
if(A!=null)
{
if(!A.canBeUninvoked())
{
oldBehavsNEffects.addElement(A);
oldR.delEffect(A);
}
else
A.unInvoke();
}
}
for(int b=0;b<oldR.numBehaviors();b++)
{
Behavior B=oldR.fetchBehavior(b);
if(B!=null)
oldBehavsNEffects.addElement(B);
}
CMLib.threads().deleteTick(oldR,-1);
R.setRoomID(oldR.roomID());
Area A=oldR.getArea();
if(A!=null) A.delProperRoom(oldR);
R.setArea(A);
for(int d=0;d<R.rawDoors().length;d++)
R.rawDoors()[d]=oldR.rawDoors()[d];
for(int d=0;d<R.rawExits().length;d++)
R.rawExits()[d]=oldR.rawExits()[d];
R.setDisplayText(oldR.displayText());
R.setDescription(oldR.description());
if(R.image().equalsIgnoreCase(CMProps.getDefaultMXPImage(oldR))) R.setImage(null);
if((R instanceof GridLocale)&&(oldR instanceof GridLocale))
{
((GridLocale)R).setXGridSize(((GridLocale)oldR).xGridSize());
((GridLocale)R).setYGridSize(((GridLocale)oldR).yGridSize());
((GridLocale)R).clearGrid(null);
}
Vector allmobs=new Vector();
int skip=0;
while(oldR.numInhabitants()>(skip))
{
MOB M=oldR.fetchInhabitant(skip);
if(M.savable())
{
if(!allmobs.contains(M))
allmobs.addElement(M);
oldR.delInhabitant(M);
}
else
if(oldR!=R)
{
oldR.delInhabitant(M);
R.bringMobHere(M,true);
}
else
skip++;
}
Vector allitems=new Vector();
while(oldR.numItems()>0)
{
Item I=oldR.fetchItem(0);
if(!allitems.contains(I))
allitems.addElement(I);
oldR.delItem(I);
}
for(int i=0;i<allitems.size();i++)
{
Item I=(Item)allitems.elementAt(i);
if(!R.isContent(I))
{
if(I.subjectToWearAndTear())
I.setUsesRemaining(100);
I.recoverEnvStats();
R.addItem(I);
R.recoverRoomStats();
}
}
for(int m=0;m<allmobs.size();m++)
{
MOB M=(MOB)allmobs.elementAt(m);
if(!R.isInhabitant(M))
{
MOB M2=(MOB)M.copyOf();
M2.setStartRoom(R);
M2.setLocation(R);
long rejuv=Tickable.TICKS_PER_RLMIN+Tickable.TICKS_PER_RLMIN+(Tickable.TICKS_PER_RLMIN/2);
if(rejuv>(Tickable.TICKS_PER_RLMIN*20)) rejuv=(Tickable.TICKS_PER_RLMIN*20);
M2.envStats().setRejuv((int)rejuv);
M2.recoverCharStats();
M2.recoverEnvStats();
M2.recoverMaxState();
M2.resetToMaxState();
M2.bringToLife(R,true);
R.recoverRoomStats();
M.destroy();
}
}
try
{
for(Enumeration r=CMLib.map().rooms();r.hasMoreElements();)
{
Room R2=(Room)r.nextElement();
for(int d=0;d<R2.rawDoors().length;d++)
if(R2.rawDoors()[d]==oldR)
{
R2.rawDoors()[d]=R;
if(R2 instanceof GridLocale)
((GridLocale)R2).buildGrid();
}
}
}catch(NoSuchElementException e){}
try
{
for(Enumeration e=CMLib.map().players();e.hasMoreElements();)
{
MOB M=(MOB)e.nextElement();
if(M.getStartRoom()==oldR)
M.setStartRoom(R);
else
if(M.location()==oldR)
M.setLocation(R);
}
}catch(NoSuchElementException e){}
R.getArea().fillInAreaRoom(R);
for(int i=0;i<oldBehavsNEffects.size();i++)
{
if(oldBehavsNEffects.elementAt(i) instanceof Behavior)
R.addBehavior((Behavior)oldBehavsNEffects.elementAt(i));
else
R.addNonUninvokableEffect((Ability)oldBehavsNEffects.elementAt(i));
}
CMLib.database().DBUpdateRoom(R);
CMLib.database().DBUpdateMOBs(R);
CMLib.database().DBUpdateItems(R);
oldR.destroy();
R.getArea().addProperRoom(R); // necessary because of the destroy
R.setImage(R.rawImage());
R.startItemRejuv();
}
return R;
}
protected Room genRoomType(MOB mob, Room R, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return R;
mob.tell(showNumber+". Type: '"+CMClass.classID(R)+"'");
if((showFlag!=showNumber)&&(showFlag>-999)) return R;
String newName="";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.length()==0))
{
newName=mob.session().prompt("Enter a new one (?)\n\r:","");
if(newName.trim().equals("?"))
{
mob.tell(CMLib.lister().reallyList2Cols(CMClass.locales(),-1,null).toString()+"\n\r");
newName="";
}
else
if(newName.length()>0)
{
Room newRoom=CMClass.getLocale(newName);
if(newRoom==null)
mob.tell("'"+newName+"' does not exist. No Change.");
else
if(mob.session().confirm("This will change the room type of room "+R.roomID()+". It will automatically save any mobs and items in this room permanently. Are you absolutely sure (y/N)?","N"))
R=changeRoomType(R,newRoom);
R.recoverRoomStats();
}
else
{
mob.tell("(no change)");
break;
}
}
return R;
}
protected void genDescription(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.setDescription(CMLib.english().prompt(mob,E.description(),showNumber,showFlag,"Description",true,false,null));}
protected void genNotes(MOB mob, MOB E, int showNumber, int showFlag) throws IOException
{
if(E.playerStats()!=null)
E.playerStats().setNotes(CMLib.english().prompt(mob,E.playerStats().notes(),showNumber,showFlag,"Private notes",true,false,null));
}
protected void genPassword(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Password: ********.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a new one to reset\n\r:","");
if((newName.length()>0)&&(E.playerStats()!=null))
{
E.playerStats().setPassword(newName);
CMLib.database().DBUpdatePassword(E);
}
else
mob.tell("(no change)");
}
protected void genEmail(MOB mob, MOB E, int showNumber, int showFlag) throws IOException
{
if(E.playerStats()!=null)
E.playerStats().setEmail(CMLib.english().prompt(mob,E.playerStats().getEmail(),showNumber,showFlag,"Email",true,false,null));
}
protected void genDisplayText(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Display: '"+E.displayText()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=null;
if(E instanceof Item)
newName=mob.session().prompt("Enter something new (null == blended)\n\r:","");
else
if(E instanceof Exit)
newName=mob.session().prompt("Enter something new (null == see-through)\n\r:","");
else
newName=mob.session().prompt("Enter something new (null = empty)\n\r:","");
if(newName.length()>0)
{
if(newName.trim().equalsIgnoreCase("null"))
newName="";
E.setDisplayText(newName);
}
else
mob.tell("(no change)");
if((E instanceof Item)&&(E.displayText().length()==0))
mob.tell("(blended)");
}
protected void genClosedText(MOB mob, Exit E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if(E instanceof Item)
mob.tell(showNumber+". Exit Closed Text: '"+E.closedText()+"'.");
else
mob.tell(showNumber+". Closed Text: '"+E.closedText()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter something new (null=blank)\n\r:","");
if(newName.equals("null"))
E.setExitParams(E.doorName(),E.closeWord(),E.openWord(),"");
else
if(newName.length()>0)
E.setExitParams(E.doorName(),E.closeWord(),E.openWord(),newName);
else
mob.tell("(no change)");
}
protected void genDoorName(MOB mob, Exit E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if(E instanceof Item)
mob.tell(showNumber+". Exit Direction: '"+E.doorName()+"'.");
else
mob.tell(showNumber+". Door Name: '"+E.doorName()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter something new\n\r:","");
if(newName.length()>0)
E.setExitParams(newName,E.closeWord(),E.openWord(),E.closedText());
else
mob.tell("(no change)");
}
protected void genBurnout(MOB mob, Light E, int showNumber, int showFlag)
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Is destroyed after burnout: '"+E.destroyedWhenBurnedOut()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
E.setDestroyedWhenBurntOut(!E.destroyedWhenBurnedOut());
}
protected void genOpenWord(MOB mob, Exit E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Open Word: '"+E.openWord()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter something new\n\r:","");
if(newName.length()>0)
E.setExitParams(E.doorName(),E.closeWord(),newName,E.closedText());
else
mob.tell("(no change)");
}
protected void genSubOps(MOB mob, Area A, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String newName="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.length()>0))
{
mob.tell(showNumber+". Area staff names: "+A.getSubOpList());
if((showFlag!=showNumber)&&(showFlag>-999)) return;
newName=mob.session().prompt("Enter a name to add or remove\n\r:","");
if(newName.length()>0)
{
if(A.amISubOp(newName))
{
A.delSubOp(newName);
mob.tell("Staff removed.");
}
else
if(CMLib.database().DBUserSearch(null,newName))
{
A.addSubOp(newName);
mob.tell("Staff added.");
}
else
mob.tell("'"+newName+"' is not recognized as a valid user name.");
}
}
}
protected void genParentAreas(MOB mob, Area A, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String newArea="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newArea.length()>0))
{
mob.tell(showNumber+". Parent Areas: "+A.getParentsList());
if((showFlag!=showNumber)&&(showFlag>-999)) return;
newArea=mob.session().prompt("Enter an area name to add or remove\n\r:","");
if(newArea.length()>0)
{
Area lookedUp=CMLib.map().getArea(newArea);
if(lookedUp!=null)
{
if (lookedUp.isChild(A))
{
// this new area is already a parent to A,
// they must want it removed
A.removeParent(lookedUp);
lookedUp.removeChild(A);
mob.tell("Enter an area name to add or remove\n\r:");
}
else
{
if(A.canParent(lookedUp))
{
A.addParent(lookedUp);
lookedUp.addChild(A);
mob.tell("Area '"+lookedUp.Name()+"' added.");
}
else
{
mob.tell("Area '"+lookedUp.Name()+"" +"' cannot be added because this would create a circular reference.");
}
}
}
else
mob.tell("'"+newArea+"' is not recognized as a valid area name.");
}
}
}
protected void genChildAreas(MOB mob, Area A, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String newArea="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newArea.length()>0))
{
mob.tell(showNumber+". Area Children: "+A.getChildrenList());
if((showFlag!=showNumber)&&(showFlag>-999)) return;
newArea=mob.session().prompt("Enter an area name to add or remove\n\r:","");
if(newArea.length()>0)
{
Area lookedUp=CMLib.map().getArea(newArea);
if(lookedUp!=null)
{
if (lookedUp.isParent(A))
{
// this area is already a child to A, they must want it removed
A.removeChild(lookedUp);
lookedUp.removeParent(A);
mob.tell("Enter an area name to add or remove\n\r:");
}
else
{
if(A.canChild(lookedUp))
{
A.addChild(lookedUp);
lookedUp.addParent(A);
mob.tell("Area '"+ lookedUp.Name()+"' added.");
}
else
{
mob.tell("Area '"+ lookedUp.Name()+"" +"' cannot be added because this would create a circular reference.");
}
}
}
else
mob.tell("'"+newArea+"' is not recognized as a valid area name.");
}
}
}
protected void genCloseWord(MOB mob, Exit E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Close Word: '"+E.closeWord()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter something new\n\r:","");
if(newName.length()>0)
E.setExitParams(E.doorName(),newName,E.openWord(),E.closedText());
else
mob.tell("(no change)");
}
protected void genExitMisc(MOB mob, Exit E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if(E.hasALock())
{
E.setReadable(false);
mob.tell(showNumber+". Assigned Key Item: '"+E.keyName()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter something new (null=blank)\n\r:","");
if(newName.equalsIgnoreCase("null"))
E.setKeyName("");
else
if(newName.length()>0)
E.setKeyName(newName);
else
mob.tell("(no change)");
}
else
{
if((showFlag!=showNumber)&&(showFlag>-999))
{
if(!E.isReadable())
mob.tell(showNumber+". Door not is readable.");
else
mob.tell(showNumber+". Door is readable: "+E.readableText());
return;
}
else
if(genGenericPrompt(mob,"Is this door ",E.isReadable()))
{
E.setReadable(true);
mob.tell("\n\rText: '"+E.readableText()+"'.");
String newName=mob.session().prompt("Enter something new (null=blank)\n\r:","");
if(newName.equalsIgnoreCase("null"))
E.setReadableText("");
else
if(newName.length()>0)
E.setReadableText(newName);
else
mob.tell("(no change)");
}
else
E.setReadable(false);
}
}
protected void genReadable1(MOB mob, Item E, int showNumber, int showFlag)
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if((E instanceof Wand)
||(E instanceof SpellHolder)
||(E instanceof Light)
||(E instanceof Container)
||(E instanceof Ammunition)
||((E instanceof ClanItem)
&&((((ClanItem)E).ciType()==ClanItem.CI_GATHERITEM)
||(((ClanItem)E).ciType()==ClanItem.CI_CRAFTITEM)
||(((ClanItem)E).ciType()==ClanItem.CI_SPECIALAPRON)))
||(E instanceof Key))
CMLib.flags().setReadable(E,false);
else
if((CMClass.classID(E).endsWith("Readable"))
||(E instanceof Recipe)
||(E instanceof com.planet_ink.coffee_mud.Items.interfaces.Map))
CMLib.flags().setReadable(E,true);
else
if((showFlag!=showNumber)&&(showFlag>-999))
mob.tell(showNumber+". Item is readable: "+CMLib.flags().isReadable(E)+"");
else
CMLib.flags().setReadable(E,genGenericPrompt(mob,showNumber+". Is this item readable",CMLib.flags().isReadable(E)));
}
protected void genReadable2(MOB mob, Item E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if((CMLib.flags().isReadable(E))
||(E instanceof SpellHolder)
||(E instanceof Ammunition)
||(E instanceof Recipe)
||(E instanceof Exit)
||(E instanceof Wand)
||(E instanceof ClanItem)
||(E instanceof Light)
||(E instanceof Key))
{
boolean ok=false;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
if(CMClass.classID(E).endsWith("SuperPill"))
{
mob.tell(showNumber+". Assigned Spell or Parameters: '"+E.readableText()+"'.");
ok=true;
}
else
if(E instanceof SpellHolder)
mob.tell(showNumber+". Assigned Spell(s) ( ';' delimited)\n: '"+E.readableText()+"'.");
else
if(E instanceof Ammunition)
{
mob.tell(showNumber+". Ammunition type: '"+E.readableText()+"'.");
ok=true;
}
else
if(E instanceof Exit)
{
mob.tell(showNumber+". Assigned Room IDs: '"+E.readableText()+"'.");
ok=true;
}
else
if(E instanceof Wand)
mob.tell(showNumber+". Assigned Spell Name: '"+E.readableText()+"'.");
else
if(E instanceof Key)
{
mob.tell(showNumber+". Assigned Key Code: '"+E.readableText()+"'.");
ok=true;
}
else
if(E instanceof com.planet_ink.coffee_mud.Items.interfaces.Map)
{
mob.tell(showNumber+". Assigned Map Area(s): '"+E.readableText()+"'.");
ok=true;
}
else
if(E instanceof Light)
{
mob.tell(showNumber+". Light duration (before burn out): '"+CMath.s_int(E.readableText())+"'.");
ok=true;
}
else
{
mob.tell(showNumber+". Assigned Read Text: '"+E.readableText()+"'.");
ok=true;
}
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=null;
if((E instanceof Wand)
||((E instanceof SpellHolder)&&(!(CMClass.classID(E).endsWith("SuperPill")))))
{
newName=mob.session().prompt("Enter something new (?)\n\r:","");
if(newName.length()==0)
ok=true;
else
{
if(newName.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
if(E instanceof Wand)
{
if(CMClass.getAbility(newName)!=null)
ok=true;
else
mob.tell("'"+newName+"' is not recognized. Try '?'.");
}
else
if(E instanceof SpellHolder)
{
String oldName=newName;
if(!newName.endsWith(";")) newName+=";";
int x=newName.indexOf(";");
while(x>=0)
{
String spellName=newName.substring(0,x).trim();
if(CMClass.getAbility(spellName)!=null)
ok=true;
else
{
mob.tell("'"+spellName+"' is not recognized. Try '?'.");
break;
}
newName=newName.substring(x+1).trim();
x=newName.indexOf(";");
}
newName=oldName;
}
}
}
else
newName=mob.session().prompt("Enter something new (null=blank)\n\r:","");
if(ok)
{
if(newName.equalsIgnoreCase("null"))
E.setReadableText("");
else
if(newName.length()>0)
E.setReadableText(newName);
else
mob.tell("(no change)");
}
}
}
else
if(E instanceof Drink)
{
mob.session().println(showNumber+". Current liquid type: "+RawMaterial.RESOURCE_DESCS[((Drink)E).liquidType()&RawMaterial.RESOURCE_MASK]);
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean q=false;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!q))
{
String newType=mob.session().prompt("Enter a new type (?)\n\r:",RawMaterial.RESOURCE_DESCS[((Drink)E).liquidType()&RawMaterial.RESOURCE_MASK]);
if(newType.equals("?"))
{
StringBuffer say=new StringBuffer("");
for(int i=0;i<RawMaterial.RESOURCE_DESCS.length-1;i++)
if((RawMaterial.RESOURCE_DATA[i][0]&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_LIQUID)
say.append(RawMaterial.RESOURCE_DESCS[i]+", ");
mob.tell(say.toString().substring(0,say.length()-2));
q=false;
}
else
{
q=true;
int newValue=-1;
for(int i=0;i<RawMaterial.RESOURCE_DESCS.length-1;i++)
if((RawMaterial.RESOURCE_DATA[i][0]&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_LIQUID)
if(newType.equalsIgnoreCase(RawMaterial.RESOURCE_DESCS[i]))
newValue=RawMaterial.RESOURCE_DATA[i][0];
if(newValue>=0)
((Drink)E).setLiquidType(newValue);
else
mob.tell("(no change)");
}
}
}
}
protected void genRecipe(MOB mob, Recipe E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String prompt="Recipe Data ";
mob.tell(showNumber+". "+prompt+": "+E.getCommonSkillID()+".");
mob.tell(CMStrings.padRight(" ",(""+showNumber).length()+2+prompt.length())+": "+CMStrings.replaceAll(E.getRecipeCodeLine(),"\t",",")+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
while(!mob.session().killFlag())
{
String newName=mob.session().prompt("Enter new skill id (?)\n\r:","");
if(newName.equalsIgnoreCase("?"))
{
StringBuffer str=new StringBuffer("");
Ability A=null;
for(Enumeration e=CMClass.abilities();e.hasMoreElements();)
{
A=(Ability)e.nextElement();
if(((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_COMMON_SKILL)
&&((A.classificationCode()&Ability.ALL_DOMAINS)==Ability.DOMAIN_CRAFTINGSKILL))
str.append(A.ID()+"\n\r");
}
mob.tell("\n\rCommon Skills:\n\r"+str.toString()+"\n\r");
}
else
if((newName.length()>0)
&&(CMClass.getAbility(newName)!=null)
&&((CMClass.getAbility(newName).classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_COMMON_SKILL))
{
E.setCommonSkillID(CMClass.getAbility(newName).ID());
break;
}
else
if(newName.length()>0)
mob.tell("'"+newName+"' is not a valid common skill. Try ?.");
else
{
mob.tell("(no change)");
break;
}
}
String newName=mob.session().prompt("Enter new data line\n\r:","");
if(newName.length()>0)
E.setRecipeCodeLine(CMStrings.replaceAll(newName,",","\t"));
else
mob.tell("(no change)");
}
protected void genGettable(MOB mob, Item E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if(E instanceof Potion)
((Potion)E).setDrunk(false);
String c="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!c.equals("\n")))
{
mob.session().println(showNumber+". A) Is Gettable : "+(!CMath.bset(E.baseEnvStats().sensesMask(),EnvStats.SENSE_ITEMNOTGET)));
mob.session().println(" B) Is Droppable : "+(!CMath.bset(E.baseEnvStats().sensesMask(),EnvStats.SENSE_ITEMNODROP)));
mob.session().println(" C) Is Removable : "+(!CMath.bset(E.baseEnvStats().sensesMask(),EnvStats.SENSE_ITEMNOREMOVE)));
mob.session().println(" D) Non-Locatable : "+(((E.baseEnvStats().sensesMask()&EnvStats.SENSE_UNLOCATABLE)>0)?"true":"false"));
if(E instanceof Weapon)
mob.session().println(" E) Is Two-Handed : "+E.rawLogicalAnd());
if((showFlag!=showNumber)&&(showFlag>-999)) return;
c=mob.session().choose("Enter one to change, or ENTER when done:","ABCDE\n","\n").toUpperCase();
switch(Character.toUpperCase(c.charAt(0)))
{
case 'A': CMLib.flags().setGettable(E,(CMath.bset(E.baseEnvStats().sensesMask(),EnvStats.SENSE_ITEMNOTGET))); break;
case 'B': CMLib.flags().setDroppable(E,(CMath.bset(E.baseEnvStats().sensesMask(),EnvStats.SENSE_ITEMNODROP))); break;
case 'C': CMLib.flags().setRemovable(E,(CMath.bset(E.baseEnvStats().sensesMask(),EnvStats.SENSE_ITEMNOREMOVE))); break;
case 'D': if((E.baseEnvStats().sensesMask()&EnvStats.SENSE_UNLOCATABLE)>0)
E.baseEnvStats().setSensesMask(E.baseEnvStats().sensesMask()-EnvStats.SENSE_UNLOCATABLE);
else
E.baseEnvStats().setSensesMask(E.baseEnvStats().sensesMask()|EnvStats.SENSE_UNLOCATABLE);
break;
case 'E': if(E instanceof Weapon)
E.setRawLogicalAnd(!E.rawLogicalAnd());
break;
}
}
}
protected void toggleDispositionMask(EnvStats E, int mask)
{
int current=E.disposition();
if((current&mask)==0)
E.setDisposition(current|mask);
else
E.setDisposition(current&((int)(EnvStats.ALLMASK-mask)));
}
protected void genDisposition(MOB mob, EnvStats E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
int[] disps={EnvStats.IS_INVISIBLE,
EnvStats.IS_HIDDEN,
EnvStats.IS_NOT_SEEN,
EnvStats.IS_BONUS,
EnvStats.IS_GLOWING,
EnvStats.IS_LIGHTSOURCE,
EnvStats.IS_FLYING,
EnvStats.IS_CLIMBING,
EnvStats.IS_SNEAKING,
EnvStats.IS_SWIMMING,
EnvStats.IS_EVIL,
EnvStats.IS_GOOD};
String[] briefs={"invisible",
"hide",
"unseen",
"magical",
"glowing",
"lightsrc",
"fly",
"climb",
"sneak",
"swimmer",
"evil",
"good"};
if((showFlag!=showNumber)&&(showFlag>-999))
{
StringBuffer buf=new StringBuffer(showNumber+". Dispositions: ");
for(int i=0;i<disps.length;i++)
{
int mask=disps[i];
if((E.disposition()&mask)!=0)
buf.append(briefs[i]+" ");
}
mob.tell(buf.toString());
return;
}
String c="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!c.equals("\n")))
{
char letter='A';
String letters="";
for(int i=0;i<disps.length;i++)
{
int mask=disps[i];
for(int num=0;num<EnvStats.dispositionsDesc.length;num++)
if(mask==CMath.pow(2,num))
{
mob.session().println(" "+letter+") "+CMStrings.padRight(EnvStats.dispositionsDesc[num],20)+":"+((E.disposition()&mask)!=0));
letters+=letter;
break;
}
letter++;
}
c=mob.session().choose("Enter one to change, or ENTER when done: ",letters+"\n","\n").toUpperCase();
letter='A';
for(int i=0;i<disps.length;i++)
{
int mask=disps[i];
if(letter==Character.toUpperCase(c.charAt(0)))
{
toggleDispositionMask(E,mask);
break;
}
letter++;
}
}
}
public boolean genGenericPrompt(MOB mob, String prompt, boolean val)
{
try
{
prompt=CMStrings.padRight(prompt,35);
if(val)
prompt+="(Y/n): ";
else
prompt+="(y/N): ";
return mob.session().confirm(prompt,val?"Y":"N");
}
catch(IOException e)
{
return val;
}
}
protected void toggleSensesMask(EnvStats E, int mask)
{
int current=E.sensesMask();
if((current&mask)==0)
E.setSensesMask(current|mask);
else
E.setSensesMask(current&((int)(EnvStats.ALLMASK-mask)));
}
protected void toggleClimateMask(Area A, int mask)
{
int current=A.climateType();
if((current&mask)==0)
A.setClimateType(current|mask);
else
A.setClimateType(current&((int)(EnvStats.ALLMASK-mask)));
}
protected void genClimateType(MOB mob, Area A, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String c="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!c.equals("\n")))
{
mob.session().println(""+showNumber+". Climate:");
mob.session().println(" R) Wet and Rainy : "+((A.climateType()&Area.CLIMASK_WET)>0));
mob.session().println(" H) Excessively hot : "+((A.climateType()&Area.CLIMASK_HOT)>0));
mob.session().println(" C) Excessively cold : "+((A.climateType()&Area.CLIMASK_COLD)>0));
mob.session().println(" W) Very windy : "+((A.climateType()&Area.CLIMATE_WINDY)>0));
mob.session().println(" D) Very dry : "+((A.climateType()&Area.CLIMASK_DRY)>0));
if((showFlag!=showNumber)&&(showFlag>-999)) return;
c=mob.session().choose("Enter one to change, or ENTER when done: ","RHCWD\n","\n").toUpperCase();
switch(c.charAt(0))
{
case 'C': toggleClimateMask(A,Area.CLIMASK_COLD); break;
case 'H': toggleClimateMask(A,Area.CLIMASK_HOT); break;
case 'R': toggleClimateMask(A,Area.CLIMASK_WET); break;
case 'W': toggleClimateMask(A,Area.CLIMATE_WINDY); break;
case 'D': toggleClimateMask(A,Area.CLIMASK_DRY); break;
}
}
}
protected void genCharStats(MOB mob, CharStats E)
throws IOException
{
String c="Q";
String commandStr="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()=+-";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!c.equals("\n")))
{
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
if(i!=CharStats.STAT_GENDER)
mob.session().println(" "+commandStr.charAt(i)+") "+CMStrings.padRight(CharStats.STAT_DESCS[i],20)+":"+((E.getStat(i))));
c=mob.session().choose("Enter one to change, or ENTER when done: ",commandStr.substring(0,CharStats.STAT_DESCS.length)+"\n","\n").toUpperCase();
int num=commandStr.indexOf(c);
if(num>=0)
{
String newVal=mob.session().prompt("Enter a new value: "+CharStats.STAT_DESCS[num]+" ("+E.getStat(num)+"): ","");
if(((CMath.s_int(newVal)>0)||(newVal.trim().equals("0")))
&&(num!=CharStats.STAT_GENDER))
E.setStat(num,CMath.s_int(newVal));
else
mob.tell("(no change)");
}
}
}
protected void genCharStats(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if((showFlag!=showNumber)&&(showFlag>-999))
{
StringBuffer buf=new StringBuffer(showNumber+". Stats: ");
for(int i=0;i<CharStats.NUM_BASE_STATS;i++)
buf.append(CharStats.STAT_ABBR[i]+":"+E.baseCharStats().getStat(i)+" ");
mob.tell(buf.toString());
return;
}
String c="Q";
String commandStr="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()=+-";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!c.equals("\n")))
{
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
if(i!=CharStats.STAT_GENDER)
mob.session().println(" "+commandStr.charAt(i)+") "+CMStrings.padRight(CharStats.STAT_DESCS[i],20)+":"+((E.baseCharStats().getStat(i))));
c=mob.session().choose("Enter one to change, or ENTER when done: ",commandStr.substring(0,CharStats.STAT_DESCS.length)+"\n","\n").toUpperCase();
int num=commandStr.indexOf(c);
if(num>=0)
{
String newVal=mob.session().prompt("Enter a new value: "+CharStats.STAT_DESCS[num]+" ("+E.baseCharStats().getStat(num)+"): ","");
if(((CMath.s_int(newVal)>0)||(newVal.trim().equals("0")))
&&(num!=CharStats.STAT_GENDER))
{
E.baseCharStats().setStat(num,CMath.s_int(newVal));
if((num==CharStats.STAT_AGE)&&(E.playerStats()!=null)&&(E.playerStats().getBirthday()!=null))
E.playerStats().getBirthday()[2]=CMClass.globalClock().getYear()-CMath.s_int(newVal);
}
else
mob.tell("(no change)");
}
}
}
protected void genSensesMask(MOB mob, EnvStats E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
int[] senses={EnvStats.CAN_SEE_DARK,
EnvStats.CAN_SEE_HIDDEN,
EnvStats.CAN_SEE_INVISIBLE,
EnvStats.CAN_SEE_SNEAKERS,
EnvStats.CAN_SEE_INFRARED,
EnvStats.CAN_SEE_GOOD,
EnvStats.CAN_SEE_EVIL,
EnvStats.CAN_SEE_BONUS,
EnvStats.CAN_NOT_SPEAK,
EnvStats.CAN_NOT_HEAR,
EnvStats.CAN_NOT_SEE};
String[] briefs={"darkvision",
"hidden",
"invisible",
"sneakers",
"infrared",
"good",
"evil",
"magic",
"MUTE",
"DEAF",
"BLIND"};
if((showFlag!=showNumber)&&(showFlag>-999))
{
StringBuffer buf=new StringBuffer(showNumber+". Senses: ");
for(int i=0;i<senses.length;i++)
{
int mask=senses[i];
if((E.sensesMask()&mask)!=0)
buf.append(briefs[i]+" ");
}
mob.tell(buf.toString());
return;
}
String c="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!c.equals("\n")))
{
char letter='A';
String letters="";
for(int i=0;i<senses.length;i++)
{
int mask=senses[i];
for(int num=0;num<EnvStats.sensesDesc.length;num++)
if(mask==CMath.pow(2,num))
{
letters+=letter;
mob.session().println(" "+letter+") "+CMStrings.padRight(EnvStats.sensesDesc[num],20)+":"+((E.sensesMask()&mask)!=0));
break;
}
letter++;
}
c=mob.session().choose("Enter one to change, or ENTER when done: ",letters+"\n","\n").toUpperCase();
letter='A';
for(int i=0;i<senses.length;i++)
{
int mask=senses[i];
if(letter==Character.toUpperCase(c.charAt(0)))
{
toggleSensesMask(E,mask);
break;
}
letter++;
}
}
}
protected void genDoorsNLocks(MOB mob, Exit E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
boolean HasDoor=E.hasADoor();
boolean Open=E.isOpen();
boolean DefaultsClosed=E.defaultsClosed();
boolean HasLock=E.hasALock();
boolean Locked=E.isLocked();
boolean DefaultsLocked=E.defaultsLocked();
if((showFlag!=showNumber)&&(showFlag>-999)){
mob.tell(showNumber+". Has a door: "+E.hasADoor()
+"\n\r Has a lock : "+E.hasALock()
+"\n\r Open ticks: "+E.openDelayTicks());
return;
}
if(genGenericPrompt(mob,"Has a door",E.hasADoor()))
{
HasDoor=true;
DefaultsClosed=genGenericPrompt(mob,"Defaults closed",E.defaultsClosed());
Open=!DefaultsClosed;
if(genGenericPrompt(mob,"Has a lock",E.hasALock()))
{
HasLock=true;
DefaultsLocked=genGenericPrompt(mob,"Defaults locked",E.defaultsLocked());
Locked=DefaultsLocked;
}
else
{
HasLock=false;
Locked=false;
DefaultsLocked=false;
}
mob.tell("\n\rReset Delay (# ticks): '"+E.openDelayTicks()+"'.");
int newLevel=CMath.s_int(mob.session().prompt("Enter a new delay\n\r:",""));
if(newLevel>0)
E.setOpenDelayTicks(newLevel);
else
mob.tell("(no change)");
}
else
{
HasDoor=false;
Open=true;
DefaultsClosed=false;
HasLock=false;
Locked=false;
DefaultsLocked=false;
}
E.setDoorsNLocks(HasDoor,Open,DefaultsClosed,HasLock,Locked,DefaultsLocked);
}
public String makeContainerTypes(Container E)
{
String canContain=", "+Container.CONTAIN_DESCS[0];
if(E.containTypes()>0)
{
canContain="";
for(int i=0;i<20;i++)
if(CMath.isSet((int)E.containTypes(),i))
canContain+=", "+Container.CONTAIN_DESCS[i+1];
}
return canContain.substring(2);
}
protected void genLidsNLocks(MOB mob, Container E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if((showFlag!=showNumber)&&(showFlag>-999)){
mob.tell(showNumber+". Can contain : "+makeContainerTypes(E)
+"\n\r Has a lid : "+E.hasALid()
+"\n\r Has a lock : "+E.hasALock()
+"\n\r Key name : "+E.keyName());
return;
}
String change="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(change.length()>0))
{
mob.tell("\n\rCan only contain: "+makeContainerTypes(E));
change=mob.session().prompt("Enter a type to add/remove (?)\n\r:","");
if(change.length()==0) break;
int found=-1;
if(change.equalsIgnoreCase("?"))
for(int i=0;i<Container.CONTAIN_DESCS.length;i++)
mob.tell(Container.CONTAIN_DESCS[i]);
else
{
for(int i=0;i<Container.CONTAIN_DESCS.length;i++)
if(Container.CONTAIN_DESCS[i].startsWith(change.toUpperCase()))
found=i;
if(found<0)
mob.tell("Unknown type. Try '?'.");
else
if(found==0)
E.setContainTypes(0);
else
if(CMath.isSet((int)E.containTypes(),found-1))
E.setContainTypes(E.containTypes()-CMath.pow(2,found-1));
else
E.setContainTypes(E.containTypes()|CMath.pow(2,found-1));
}
}
if(genGenericPrompt(mob,"Has a lid " ,E.hasALid()))
{
E.setLidsNLocks(true,false,E.hasALock(),E.isLocked());
if(genGenericPrompt(mob,"Has a lock",E.hasALock()))
{
E.setLidsNLocks(E.hasALid(),E.isOpen(),true,true);
mob.tell("\n\rKey code: '"+E.keyName()+"'.");
String newName=mob.session().prompt("Enter something new\n\r:","");
if(newName.length()>0)
E.setKeyName(newName);
else
mob.tell("(no change)");
}
else
{
E.setKeyName("");
E.setLidsNLocks(E.hasALid(),E.isOpen(),false,false);
}
}
else
{
E.setKeyName("");
E.setLidsNLocks(false,true,false,false);
}
}
protected void genLevel(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{
if(E.baseEnvStats().level()<0) E.baseEnvStats().setLevel(1);
E.baseEnvStats().setLevel(CMLib.english().prompt(mob,E.baseEnvStats().level(),showNumber,showFlag,"Level"));
}
protected void genRejuv(MOB mob, Environmental E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if(E instanceof Item)
mob.tell(showNumber+". Rejuv/Pct: '"+E.baseEnvStats().rejuv()+"' (0=special).");
else
mob.tell(showNumber+". Rejuv Ticks: '"+E.baseEnvStats().rejuv()+"' (0=never).");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String rlevel=mob.session().prompt("Enter new amount\n\r:","");
int newLevel=CMath.s_int(rlevel);
if((newLevel>0)||(rlevel.trim().equals("0")))
{
E.baseEnvStats().setRejuv(newLevel);
if((E.baseEnvStats().rejuv()==0)&&(E instanceof MOB))
{
E.baseEnvStats().setRejuv(Integer.MAX_VALUE);
mob.tell(E.Name()+" will now never rejuvinate.");
}
}
else
mob.tell("(no change)");
}
protected void genUses(MOB mob, Item E, int showNumber, int showFlag) throws IOException
{ E.setUsesRemaining(CMLib.english().prompt(mob,E.usesRemaining(),showNumber,showFlag,"Uses Remaining")); }
protected void genMaxUses(MOB mob, Wand E, int showNumber, int showFlag) throws IOException
{ E.setMaxUses(CMLib.english().prompt(mob,E.maxUses(),showNumber,showFlag,"Maximum Uses")); }
protected void genCondition(MOB mob, Item E, int showNumber, int showFlag) throws IOException
{ E.setUsesRemaining(CMLib.english().prompt(mob,E.usesRemaining(),showNumber,showFlag,"Condition")); }
protected void genMiscSet(MOB mob, Environmental E)
throws IOException
{
if(E instanceof ShopKeeper)
modifyGenShopkeeper(mob,(ShopKeeper)E);
else
if(E instanceof MOB)
{
if(((MOB)E).isMonster())
modifyGenMOB(mob,(MOB)E);
else
modifyPlayer(mob,(MOB)E);
}
else
if((E instanceof Exit)&&(!(E instanceof Item)))
modifyGenExit(mob,(Exit)E);
else
if(E instanceof com.planet_ink.coffee_mud.Items.interfaces.Map)
modifyGenMap(mob,(com.planet_ink.coffee_mud.Items.interfaces.Map)E);
else
if(E instanceof Armor)
modifyGenArmor(mob,(Armor)E);
else
if(E instanceof MusicalInstrument)
modifyGenInstrument(mob,(MusicalInstrument)E);
else
if(E instanceof Food)
modifyGenFood(mob,(Food)E);
else
if((E instanceof Drink)&&(E instanceof Item))
modifyGenDrink(mob,(Drink)E);
else
if(E instanceof Weapon)
modifyGenWeapon(mob,(Weapon)E);
else
if(E instanceof Container)
modifyGenContainer(mob,(Container)E);
else
if(E instanceof Item)
{
if(E.ID().equals("GenWallpaper"))
modifyGenWallpaper(mob,(Item)E);
else
modifyGenItem(mob,(Item)E);
}
}
protected void genMiscText(MOB mob, Environmental E, int showNumber, int showFlag)
throws IOException
{
if(E.isGeneric())
genMiscSet(mob,E);
else
{ E.setMiscText(CMLib.english().prompt(mob,E.text(),showNumber,showFlag,"Misc Text",true,false));}
}
protected void genTitleRoom(MOB mob, LandTitle E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Land plot ID: '"+E.landPropertyID()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newText="?!?!";
while((mob.session()!=null)&&(!mob.session().killFlag())
&&((newText.length()>0)&&(CMLib.map().getRoom(newText)==null)))
{
newText=mob.session().prompt("New Property ID:","");
if((newText.length()==0)
&&(CMLib.map().getRoom(newText)==null)
&&(CMLib.map().getArea(newText)==null))
mob.tell("That property (room ID) doesn't exist!");
}
if(newText.length()>0)
E.setLandPropertyID(newText);
else
mob.tell("(no change)");
}
protected void genAbility(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.baseEnvStats().setAbility(CMLib.english().prompt(mob,E.baseEnvStats().ability(),showNumber,showFlag,"Magical Ability")); }
protected void genCoinStuff(MOB mob, Coins E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Money data: '"+E.getNumberOfCoins()+" x "+CMLib.beanCounter().getDenominationName(E.getCurrency(),E.getDenomination())+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean gocontinue=true;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(gocontinue))
{
gocontinue=false;
String oldCurrency=E.getCurrency();
if(oldCurrency.length()==0) oldCurrency="Default";
oldCurrency=mob.session().prompt("Enter currency code (?):",oldCurrency).trim().toUpperCase();
if(oldCurrency.equalsIgnoreCase("Default"))
{
if(E.getCurrency().length()>0)
E.setCurrency("");
else
mob.tell("(no change)");
}
else
if((oldCurrency.length()==0)||(oldCurrency.equalsIgnoreCase(E.getCurrency())))
mob.tell("(no change)");
else
if(!CMLib.beanCounter().getAllCurrencies().contains(oldCurrency))
{
Vector V=CMLib.beanCounter().getAllCurrencies();
for(int v=0;v<V.size();v++)
if(((String)V.elementAt(v)).length()==0)
V.setElementAt("Default",v);
mob.tell("'"+oldCurrency+"' is not a known currency. Existing currencies include: DEFAULT"+CMParms.toStringList(V));
gocontinue=true;
}
else
E.setCurrency(oldCurrency.toUpperCase().trim());
}
gocontinue=true;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(gocontinue))
{
gocontinue=false;
String newDenom=mob.session().prompt("Enter denomination (?):",""+E.getDenomination()).trim().toUpperCase();
DVector DV=CMLib.beanCounter().getCurrencySet(E.getCurrency());
if((newDenom.length()>0)
&&(!CMath.isDouble(newDenom))
&&(!newDenom.equalsIgnoreCase("?")))
{
double denom=CMLib.english().matchAnyDenomination(E.getCurrency(),newDenom);
if(denom>0.0) newDenom=""+denom;
}
if((newDenom.length()==0)
||(CMath.isDouble(newDenom)
&&(!newDenom.equalsIgnoreCase("?"))
&&(CMath.s_double(newDenom)==E.getDenomination())))
mob.tell("(no change)");
else
if((!CMath.isDouble(newDenom))
||(newDenom.equalsIgnoreCase("?"))
||((DV!=null)&&(!DV.contains(new Double(CMath.s_double(newDenom))))))
{
StringBuffer allDenoms=new StringBuffer("");
for(int i=0;i<DV.size();i++)
allDenoms.append(((Double)DV.elementAt(i,1)).doubleValue()+"("+((String)DV.elementAt(i,2))+"), ");
if(allDenoms.toString().endsWith(", "))
allDenoms=new StringBuffer(allDenoms.substring(0,allDenoms.length()-2));
mob.tell("'"+newDenom+"' is not a defined denomination. Try one of these: "+allDenoms.toString()+".");
gocontinue=true;
}
else
E.setDenomination(CMath.s_double(newDenom));
}
if((mob.session()!=null)&&(!mob.session().killFlag()))
E.setNumberOfCoins(CMath.s_int(mob.session().prompt("Enter stack size\n\r:",""+E.getNumberOfCoins())));
}
protected void genHitPoints(MOB mob, MOB E, int showNumber, int showFlag) throws IOException
{
if(E.isMonster())
E.baseEnvStats().setAbility(CMLib.english().prompt(mob,E.baseEnvStats().ability(),showNumber,showFlag,"Hit Points Bonus Modifier","Hit points = (level*level) + (random*level*THIS)"));
else
E.baseEnvStats().setAbility(CMLib.english().prompt(mob,E.baseEnvStats().ability(),showNumber,showFlag,"Ability -- unused"));
}
protected void genValue(MOB mob, Item E, int showNumber, int showFlag) throws IOException
{ E.setBaseValue(CMLib.english().prompt(mob,E.baseGoldValue(),showNumber,showFlag,"Base Value")); }
protected void genWeight(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.baseEnvStats().setWeight(CMLib.english().prompt(mob,E.baseEnvStats().weight(),showNumber,showFlag,"Weight")); }
protected void genClanItem(MOB mob, ClanItem E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Clan: '"+E.clanID()+"', Type: "+ClanItem.CI_DESC[E.ciType()]+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String clanID=E.clanID();
E.setClanID(mob.session().prompt("Enter a new clan\n\r:",clanID));
if(E.clanID().equals(clanID))
mob.tell("(no change)");
String clanType=ClanItem.CI_DESC[E.ciType()];
String s="?";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(s.equals("?")))
{
s=mob.session().prompt("Enter a new type (?)\n\r:",clanType);
if(s.equalsIgnoreCase("?"))
mob.tell("Types: "+CMParms.toStringList(ClanItem.CI_DESC));
else
if(s.equalsIgnoreCase(clanType))
{
mob.tell("(no change)");
break;
}
else
{
boolean found=false;
for(int i=0;i<ClanItem.CI_DESC.length;i++)
if(ClanItem.CI_DESC[i].equalsIgnoreCase(s))
{ found=true; E.setCIType(i); break;}
if(!found)
{
mob.tell("'"+s+"' is unknown. Try '?'");
s="?";
}
}
}
}
protected void genHeight(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.baseEnvStats().setHeight(CMLib.english().prompt(mob,E.baseEnvStats().height(),showNumber,showFlag,"Height")); }
protected void genSize(MOB mob, Armor E, int showNumber, int showFlag) throws IOException
{ E.baseEnvStats().setHeight(CMLib.english().prompt(mob,E.baseEnvStats().height(),showNumber,showFlag,"Size")); }
protected void genLayer(MOB mob, Armor E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
boolean seeThroughBool=CMath.bset(E.getLayerAttributes(),Armor.LAYERMASK_SEETHROUGH);
boolean multiWearBool=CMath.bset(E.getLayerAttributes(),Armor.LAYERMASK_MULTIWEAR);
String seeThroughStr=(!seeThroughBool)?" (opaque)":" (see-through)";
String multiWearStr=multiWearBool?" (multi)":"";
mob.tell(showNumber+". Layer: '"+E.getClothingLayer()+"'"+seeThroughStr+""+multiWearStr+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
if((mob.session()!=null)&&(!mob.session().killFlag()))
E.setClothingLayer(CMath.s_short(mob.session().prompt("Enter a new layer\n\r:",""+E.getClothingLayer())));
boolean newSeeThrough=seeThroughBool;
if((mob.session()!=null)&&(!mob.session().killFlag()))
newSeeThrough=mob.session().confirm("Is see-through (Y/N)? ",""+seeThroughBool);
boolean multiWear=multiWearBool;
if((mob.session()!=null)&&(!mob.session().killFlag()))
multiWear=mob.session().confirm("Is multi-wear (Y/N)? ",""+multiWearBool);
E.setLayerAttributes((short)0);
E.setLayerAttributes((short)(E.getLayerAttributes()|(newSeeThrough?Armor.LAYERMASK_SEETHROUGH:0)));
E.setLayerAttributes((short)(E.getLayerAttributes()|(multiWear?Armor.LAYERMASK_MULTIWEAR:0)));
}
protected void genCapacity(MOB mob, Container E, int showNumber, int showFlag) throws IOException
{ E.setCapacity(CMLib.english().prompt(mob,E.capacity(),showNumber,showFlag,"Capacity")); }
protected void genAttack(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.baseEnvStats().setAttackAdjustment(CMLib.english().prompt(mob,E.baseEnvStats().attackAdjustment(),showNumber,showFlag,"Attack Adjustment")); }
protected void genDamage(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.baseEnvStats().setDamage(CMLib.english().prompt(mob,E.baseEnvStats().damage(),showNumber,showFlag,"Damage")); }
protected void genBanker1(MOB mob, Banker E, int showNumber, int showFlag) throws IOException
{ E.setCoinInterest(CMLib.english().prompt(mob,E.getCoinInterest(),showNumber,showFlag,"Coin Interest [% per real day]")); }
protected void genBanker2(MOB mob, Banker E, int showNumber, int showFlag) throws IOException
{ E.setItemInterest(CMLib.english().prompt(mob,E.getItemInterest(),showNumber,showFlag,"Item Interest [% per real day]")); }
protected void genBanker3(MOB mob, Banker E, int showNumber, int showFlag) throws IOException
{ E.setBankChain(CMLib.english().prompt(mob,E.bankChain(),showNumber,showFlag,"Bank Chain",false,false)); }
protected void genBanker4(MOB mob, Banker E, int showNumber, int showFlag) throws IOException
{ E.setLoanInterest(CMLib.english().prompt(mob,E.getLoanInterest(),showNumber,showFlag,"Loan Interest [% per mud month]")); }
protected void genSpeed(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.baseEnvStats().setSpeed(CMLib.english().prompt(mob,E.baseEnvStats().speed(),showNumber,showFlag,"Actions/Attacks per tick")); }
protected void genArmor(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{
if(E instanceof MOB)
E.baseEnvStats().setArmor(CMLib.english().prompt(mob,E.baseEnvStats().armor(),showNumber,showFlag,"Armor (lower-better)"));
else
E.baseEnvStats().setArmor(CMLib.english().prompt(mob,E.baseEnvStats().armor(),showNumber,showFlag,"Armor (higher-better)"));
}
protected void genMoney(MOB mob, MOB E, int showNumber, int showFlag) throws IOException
{ CMLib.beanCounter().setMoney(E,CMLib.english().prompt(mob,CMLib.beanCounter().getMoney(E),showNumber,showFlag,"Money")); }
protected void genWeaponAmmo(MOB mob, Weapon E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String defaultAmmo=(E.requiresAmmunition())?"Y":"N";
if((showFlag!=showNumber)&&(showFlag>-999))
{
mob.tell(showNumber+". Ammo required: "+E.requiresAmmunition()+" ("+E.ammunitionType()+")");
return;
}
if(mob.session().confirm("Does this weapon require ammunition (default="+defaultAmmo+") (Y/N)?",defaultAmmo))
{
mob.tell("\n\rAmmo type: '"+E.ammunitionType()+"'.");
String newName=mob.session().prompt("Enter a new one\n\r:","");
if(newName.length()>0)
{
E.setAmmunitionType(newName);
mob.tell("(Remember to create a GenAmmunition item with '"+E.ammunitionType()+"' in the secret identity, and the uses remaining above 0!");
}
else
mob.tell("(no change)");
mob.tell("\n\rAmmo capacity: '"+E.ammunitionCapacity()+"'.)");
int newValue=CMath.s_int(mob.session().prompt("Enter a new value\n\r:",""));
if(newValue>0)
E.setAmmoCapacity(newValue);
else
mob.tell("(no change)");
E.setAmmoRemaining(E.ammunitionCapacity());
}
else
{
E.setAmmunitionType("");
E.setAmmoCapacity(0);
}
}
protected void genWeaponRanges(MOB mob, Weapon E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Minimum/Maximum Ranges: "+Math.round(E.minRange())+"/"+Math.round(E.maxRange())+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newMinStr=mob.session().prompt("Enter a new minimum range\n\r:","");
String newMaxStr=mob.session().prompt("Enter a new maximum range\n\r:","");
if((newMinStr.length()==0)&&(newMaxStr.length()==0))
mob.tell("(no change)");
else
{
E.setRanges(CMath.s_int(newMinStr),CMath.s_int(newMaxStr));
if((E.minRange()>E.maxRange())||(E.minRange()<0)||(E.maxRange()<0))
{
mob.tell("(defective entries. resetting.)");
E.setRanges(0,0);
}
}
}
protected void genWeaponType(MOB mob, Weapon E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Weapon Attack Type: '"+Weapon.typeDescription[E.weaponType()]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean q=false;
String sel="NSPBFMR";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!q))
{
String newType=mob.session().choose("Enter a new value\n\r:",sel+"?","");
if(newType.equals("?"))
{
for(int i=0;i<sel.length();i++)
mob.tell(sel.charAt(i)+") "+Weapon.typeDescription[i]);
q=false;
}
else
{
q=true;
int newValue=-1;
if(newType.length()>0)
newValue=sel.indexOf(newType.toUpperCase());
if(newValue>=0)
E.setWeaponType(newValue);
else
mob.tell("(no change)");
}
}
}
protected void genTechLevel(MOB mob, Area A, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Theme setting: '"+Area.THEME_DESCS[A.getTechLevel()]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean q=false;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!q))
{
String newType=mob.session().prompt("Enter a new level (?)\n\r",Area.THEME_DESCS[A.getTechLevel()]);
if(newType.equals("?"))
{
StringBuffer say=new StringBuffer("");
for(int i=1;i<Area.THEME_DESCS.length;i++)
say.append(i+") "+Area.THEME_DESCS[i]+"\n\r");
mob.tell(say.toString());
q=false;
}
else
{
q=true;
int newValue=-1;
if(CMath.s_int(newType)>0)
newValue=CMath.s_int(newType);
else
for(int i=0;i<Area.THEME_DESCS.length;i++)
if(Area.THEME_DESCS[i].toUpperCase().startsWith(newType.toUpperCase()))
newValue=i;
if(newValue>=0)
A.setTechLevel(newValue);
else
mob.tell("(no change)");
}
}
}
protected void genMaterialCode(MOB mob, Item E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Material Type: '"+RawMaterial.RESOURCE_DESCS[E.material()&RawMaterial.RESOURCE_MASK]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean q=false;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!q))
{
String newType=mob.session().prompt("Enter a new material (?)\n\r:",RawMaterial.RESOURCE_DESCS[E.material()&RawMaterial.RESOURCE_MASK]);
if(newType.equals("?"))
{
StringBuffer say=new StringBuffer("");
for(int i=0;i<RawMaterial.RESOURCE_DESCS.length-1;i++)
say.append(RawMaterial.RESOURCE_DESCS[i]+", ");
mob.tell(say.toString().substring(0,say.length()-2));
q=false;
}
else
{
q=true;
int newValue=-1;
for(int i=0;i<RawMaterial.RESOURCE_DESCS.length-1;i++)
if(newType.equalsIgnoreCase(RawMaterial.RESOURCE_DESCS[i]))
newValue=RawMaterial.RESOURCE_DATA[i][0];
if(newValue>=0)
E.setMaterial(newValue);
else
mob.tell("(no change)");
}
}
}
protected void genInstrumentType(MOB mob, MusicalInstrument E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Instrument Type: '"+MusicalInstrument.TYPE_DESC[E.instrumentType()]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean q=false;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!q))
{
String newType=mob.session().prompt("Enter a new type (?)\n\r:",MusicalInstrument.TYPE_DESC[E.instrumentType()]);
if(newType.equals("?"))
{
StringBuffer say=new StringBuffer("");
for(int i=0;i<MusicalInstrument.TYPE_DESC.length-1;i++)
say.append(MusicalInstrument.TYPE_DESC[i]+", ");
mob.tell(say.toString().substring(0,say.length()-2));
q=false;
}
else
{
q=true;
int newValue=-1;
for(int i=0;i<MusicalInstrument.TYPE_DESC.length-1;i++)
if(newType.equalsIgnoreCase(MusicalInstrument.TYPE_DESC[i]))
newValue=i;
if(newValue>=0)
E.setInstrumentType(newValue);
else
mob.tell("(no change)");
}
}
}
protected void genSpecialFaction(MOB mob, MOB E, int showNumber, int showFlag, Faction F)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if(F==null) return;
Faction.FactionRange myFR=CMLib.factions().getRange(F.factionID(),E.fetchFaction(F.factionID()));
mob.tell(showNumber+". "+F.name()+": "+((myFR!=null)?myFR.name():"UNDEFINED")+" ("+E.fetchFaction(F.factionID())+")");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
if(F.ranges()!=null)
for(int v=0;v<F.ranges().size();v++)
{
Faction.FactionRange FR=(Faction.FactionRange)F.ranges().elementAt(v);
mob.tell(CMStrings.padRight(FR.name(),20)+": "+FR.low()+" - "+FR.high()+")");
}
String newOne=mob.session().prompt("Enter a new value\n\r:");
if(CMath.isInteger(newOne))
{
E.addFaction(F.factionID(),CMath.s_int(newOne));
return;
}
for(int v=0;v<F.ranges().size();v++)
{
Faction.FactionRange FR=(Faction.FactionRange)F.ranges().elementAt(v);
if(FR.name().toUpperCase().startsWith(newOne.toUpperCase()))
{
if(FR.low()==F.lowest())
E.addFaction(F.factionID(),FR.low());
else
if(FR.high()==F.highest())
E.addFaction(F.factionID(),FR.high());
else
E.addFaction(F.factionID(),FR.low()+((FR.high()-FR.low())/2));
return;
}
}
mob.tell("(no change)");
}
protected void genFaction(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String newFact="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newFact.length()>0))
{
mob.tell(showNumber+". Factions: "+E.getFactionListing());
if((showFlag!=showNumber)&&(showFlag>-999)) return;
newFact=mob.session().prompt("Enter a faction name to add or remove\n\r:","");
if(newFact.length()>0)
{
Faction lookedUp=CMLib.factions().getFactionByName(newFact);
if(lookedUp==null) lookedUp=CMLib.factions().getFaction(newFact);
if(lookedUp!=null)
{
if (E.fetchFaction(lookedUp.factionID())!=Integer.MAX_VALUE)
{
// this mob already has this faction, they must want it removed
E.removeFaction(lookedUp.factionID());
mob.tell("Faction '"+lookedUp.name() +"' removed.");
}
else
{
int value =new Integer(mob.session().prompt("How much faction ("+lookedUp.findDefault(E)+")?",
new Integer(lookedUp.findDefault(E)).toString())).intValue();
if(value<lookedUp.minimum()) value=lookedUp.minimum();
if(value>lookedUp.maximum()) value=lookedUp.maximum();
E.addFaction(lookedUp.factionID(),value);
mob.tell("Faction '"+lookedUp.name() +"' added.");
}
}
else
mob.tell("'"+newFact+"' is not recognized as a valid faction name or file.");
}
}
}
protected void genGender(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Gender: '"+Character.toUpperCase((char)E.baseCharStats().getStat(CharStats.STAT_GENDER))+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newType=mob.session().choose("Enter a new gender (M/F/N)\n\r:","MFN","");
int newValue=-1;
if(newType.length()>0)
newValue=("MFN").indexOf(newType.trim().toUpperCase());
if(newValue>=0)
{
switch(newValue)
{
case 0:
E.baseCharStats().setStat(CharStats.STAT_GENDER,'M');
break;
case 1:
E.baseCharStats().setStat(CharStats.STAT_GENDER,'F');
break;
case 2:
E.baseCharStats().setStat(CharStats.STAT_GENDER,'N');
break;
}
}
else
mob.tell("(no change)");
}
protected void genWeaponClassification(MOB mob, Weapon E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Weapon Classification: '"+Weapon.classifictionDescription[E.weaponClassification()]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean q=false;
String sel=("ABEFHKPRSDTN");
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!q))
{
String newType=mob.session().choose("Enter a new value (?)\n\r:",sel+"?","");
if(newType.equals("?"))
{
for(int i=0;i<sel.length();i++)
mob.tell(sel.charAt(i)+") "+Weapon.classifictionDescription[i]);
q=false;
}
else
{
q=true;
int newValue=-1;
if(newType.length()>0)
newValue=sel.indexOf(newType.toUpperCase());
if(newValue>=0)
E.setWeaponClassification(newValue);
else
mob.tell("(no change)");
}
}
}
protected void genSecretIdentity(MOB mob, Item E, int showNumber, int showFlag) throws IOException
{ E.setSecretIdentity(CMLib.english().prompt(mob,E.rawSecretIdentity(),showNumber,showFlag,"Secret Identity",true,false)); }
protected void genNourishment(MOB mob, Food E, int showNumber, int showFlag) throws IOException
{ E.setNourishment(CMLib.english().prompt(mob,E.nourishment(),showNumber,showFlag,"Nourishment/Eat")); }
protected void genRace(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String raceID="begin!";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(raceID.length()>0))
{
mob.tell(showNumber+". Race: '"+E.baseCharStats().getMyRace().ID()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
raceID=mob.session().prompt("Enter a new race (?)\n\r:","").trim();
if(raceID.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.races(),-1).toString());
else
if(raceID.length()==0)
mob.tell("(no change)");
else
{
Race R=CMClass.getRace(raceID);
if(R!=null)
{
E.baseCharStats().setMyRace(R);
E.baseCharStats().getMyRace().startRacing(E,false);
E.baseCharStats().getMyRace().setHeightWeight(E.baseEnvStats(),(char)E.baseCharStats().getStat(CharStats.STAT_GENDER));
}
else
mob.tell("Unknown race! Try '?'.");
}
}
}
protected void genCharClass(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String classID="begin!";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(classID.length()>0))
{
StringBuffer str=new StringBuffer("");
for(int c=0;c<E.baseCharStats().numClasses();c++)
{
CharClass C=E.baseCharStats().getMyClass(c);
str.append(C.ID()+"("+E.baseCharStats().getClassLevel(C)+") ");
}
mob.tell(showNumber+". Class: '"+str.toString()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
classID=mob.session().prompt("Enter a class to add/remove(?)\n\r:","").trim();
if(classID.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.charClasses(),-1).toString());
else
if(classID.length()==0)
mob.tell("(no change)");
else
{
CharClass C=CMClass.getCharClass(classID);
if(C!=null)
{
if(E.baseCharStats().getClassLevel(C)>=0)
{
if(E.baseCharStats().numClasses()<2)
mob.tell("Final class may not be removed. To change a class, add the new one first.");
else
{
StringBuffer charClasses=new StringBuffer("");
StringBuffer classLevels=new StringBuffer("");
for(int c=0;c<E.baseCharStats().numClasses();c++)
{
CharClass C2=E.baseCharStats().getMyClass(c);
int L2=E.baseCharStats().getClassLevel(C2);
if(C2!=C)
{
charClasses.append(";"+C2.ID());
classLevels.append(";"+L2);
}
}
E.baseCharStats().setMyClasses(charClasses.toString());
E.baseCharStats().setMyLevels(classLevels.toString());
}
}
else
{
int highLvl=Integer.MIN_VALUE;
CharClass highestC=null;
for(int c=0;c<E.baseCharStats().numClasses();c++)
{
CharClass C2=E.baseCharStats().getMyClass(c);
if(E.baseCharStats().getClassLevel(C2)>highLvl)
{
highestC=C2;
highLvl=E.baseCharStats().getClassLevel(C2);
}
}
E.baseCharStats().setCurrentClass(C);
int levels=E.baseCharStats().combinedSubLevels();
levels=E.baseEnvStats().level()-levels;
String lvl=null;
if(levels>0)
{
lvl=mob.session().prompt("Levels to give this class ("+levels+")\n\r:",""+levels).trim();
int lvl2=CMath.s_int(lvl);
if(lvl2>levels) lvl2=levels;
E.baseCharStats().setClassLevel(C,lvl2);
}
else
{
lvl=mob.session().prompt("Levels to siphon from "+highestC.ID()+" for this class (0)\n\r:",""+0).trim();
int lvl2=CMath.s_int(lvl);
if(lvl2>highLvl) lvl2=highLvl;
E.baseCharStats().setClassLevel(highestC,highLvl-lvl2);
E.baseCharStats().setClassLevel(C,lvl2);
}
}
int levels=E.baseCharStats().combinedSubLevels();
levels=E.baseEnvStats().level()-levels;
C=E.baseCharStats().getCurrentClass();
E.baseCharStats().setClassLevel(C,levels);
}
else
mob.tell("Unknown character class! Try '?'.");
}
}
}
protected void genTattoos(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String tattoostr="";
for(int b=0;b<E.numTattoos();b++)
{
String B=E.fetchTattoo(b);
if(B!=null) tattoostr+=B+", ";
}
if(tattoostr.length()>0)
tattoostr=tattoostr.substring(0,tattoostr.length()-2);
if((tattoostr.length()>60)&&((showFlag!=showNumber)&&(showFlag>-999)))
tattoostr=tattoostr.substring(0,60)+"...";
mob.tell(showNumber+". Tattoos: '"+tattoostr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter a tattoo to add/remove\n\r:","");
if(behave.length()>0)
{
String tattoo=behave;
if((tattoo.length()>0)
&&(Character.isDigit(tattoo.charAt(0)))
&&(tattoo.indexOf(" ")>0)
&&(CMath.isNumber(tattoo.substring(0,tattoo.indexOf(" ")))))
tattoo=tattoo.substring(tattoo.indexOf(" ")+1).trim();
if(E.fetchTattoo(tattoo)!=null)
{
mob.tell(tattoo.trim().toUpperCase()+" removed.");
E.delTattoo(behave);
}
else
{
mob.tell(behave.trim().toUpperCase()+" added.");
E.addTattoo(behave);
}
}
else
mob.tell("(no change)");
}
}
protected void genTitles(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if(E.playerStats()==null) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String behaviorstr="";
for(int b=0;b<E.playerStats().getTitles().size();b++)
{
String B=(String)E.playerStats().getTitles().elementAt(b);
if(B!=null) behaviorstr+=B+", ";
}
if(behaviorstr.length()>0)
behaviorstr=behaviorstr.substring(0,behaviorstr.length()-2);
mob.tell(showNumber+". Titles: '"+behaviorstr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter a title to add or a number to remove\n\r:","");
if(behave.length()>0)
{
String tattoo=behave;
if((tattoo.length()>0)
&&(CMath.isInteger(tattoo))
&&(CMath.s_int(tattoo)>0)
&&(CMath.s_int(tattoo)<=E.playerStats().getTitles().size()))
tattoo=(String)E.playerStats().getTitles().elementAt(CMath.s_int(tattoo)-1);
else
if((tattoo.length()>0)
&&(Character.isDigit(tattoo.charAt(0)))
&&(tattoo.indexOf(" ")>0)
&&(CMath.isNumber(tattoo.substring(0,tattoo.indexOf(" ")))))
tattoo=tattoo.substring(tattoo.indexOf(" ")+1).trim();
if(E.playerStats().getTitles().contains(tattoo))
{
mob.tell(tattoo.trim().toUpperCase()+" removed.");
E.playerStats().getTitles().remove(tattoo);
}
else
{
mob.tell(behave.trim().toUpperCase()+" added.");
E.playerStats().getTitles().addElement(tattoo);
}
}
else
mob.tell("(no change)");
}
}
protected void genExpertises(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String behaviorstr="";
for(int b=0;b<E.numExpertises();b++)
{
String B=E.fetchExpertise(b);
if(B!=null) behaviorstr+=B+", ";
}
if(behaviorstr.length()>0)
behaviorstr=behaviorstr.substring(0,behaviorstr.length()-2);
if((behaviorstr.length()>60)&&((showFlag!=showNumber)&&(showFlag>-999)))
behaviorstr=behaviorstr.substring(0,60)+"...";
mob.tell(showNumber+". Expertises: '"+behaviorstr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter a lesson to add/remove\n\r:","");
if(behave.length()>0)
{
if(E.fetchExpertise(behave)!=null)
{
mob.tell(behave+" removed.");
E.delExpertise(behave);
}
else
{
mob.tell(behave+" added.");
E.addExpertise(behave);
}
}
else
mob.tell("(no change)");
}
}
protected void genSecurity(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
PlayerStats P=E.playerStats();
if(P==null) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String behaviorstr="";
for(int b=0;b<P.getSecurityGroups().size();b++)
{
String B=(String)P.getSecurityGroups().elementAt(b);
if(B!=null) behaviorstr+=B+", ";
}
if(behaviorstr.length()>0)
behaviorstr=behaviorstr.substring(0,behaviorstr.length()-2);
mob.tell(showNumber+". Security Groups: '"+behaviorstr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter a group to add/remove\n\r:","");
if(behave.length()>0)
{
if(P.getSecurityGroups().contains(behave.trim().toUpperCase()))
{
P.getSecurityGroups().remove(behave.trim().toUpperCase());
mob.tell(behave+" removed.");
}
else
if((behave.trim().toUpperCase().startsWith("AREA "))
&&(!CMSecurity.isAllowedAnywhere(mob,behave.trim().toUpperCase().substring(5).trim())))
mob.tell("You do not have clearance to add security code '"+behave+"' to this class.");
else
if((!behave.trim().toUpperCase().startsWith("AREA "))
&&(!CMSecurity.isAllowedEverywhere(mob,behave.trim().toUpperCase())))
mob.tell("You do not have clearance to add security code '"+behave+"' to this class.");
else
{
P.getSecurityGroups().addElement(behave.trim().toUpperCase());
mob.tell(behave+" added.");
}
}
else
mob.tell("(no change)");
}
}
protected void genBehaviors(MOB mob, Environmental E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String behaviorstr="";
for(int b=0;b<E.numBehaviors();b++)
{
Behavior B=E.fetchBehavior(b);
if((B!=null)&&(B.isSavable()))
{
behaviorstr+=B.ID();
if(B.getParms().trim().length()>0)
behaviorstr+="("+B.getParms().trim()+"), ";
else
behaviorstr+=", ";
}
}
if(behaviorstr.length()>0)
behaviorstr=behaviorstr.substring(0,behaviorstr.length()-2);
mob.tell(showNumber+". Behaviors: '"+behaviorstr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter a behavior to add/remove (?)\n\r:","");
if(behave.length()>0)
{
if(behave.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.behaviors(),-1).toString());
else
{
Behavior chosenOne=null;
for(int b=0;b<E.numBehaviors();b++)
{
Behavior B=E.fetchBehavior(b);
if((B!=null)&&(B.ID().equalsIgnoreCase(behave)))
chosenOne=B;
}
if(chosenOne!=null)
{
mob.tell(chosenOne.ID()+" removed.");
E.delBehavior(chosenOne);
}
else
{
chosenOne=CMClass.getBehavior(behave);
if(chosenOne!=null)
{
boolean alreadyHasIt=false;
for(int b=0;b<E.numBehaviors();b++)
{
Behavior B=E.fetchBehavior(b);
if((B!=null)&&(B.ID().equals(chosenOne.ID())))
{
alreadyHasIt=true;
chosenOne=B;
}
}
String parms="?";
while(parms.equals("?"))
{
parms=chosenOne.getParms();
parms=mob.session().prompt("Enter any behavior parameters (?)\n\r:"+parms);
if(parms.equals("?")){ StringBuffer s2=CMLib.help().getHelpText(chosenOne.ID(),mob,true); if(s2!=null) mob.tell(s2.toString()); else mob.tell("no help!");}
}
chosenOne.setParms(parms.trim());
if(!alreadyHasIt)
{
mob.tell(chosenOne.ID()+" added.");
E.addBehavior(chosenOne);
}
else
mob.tell(chosenOne.ID()+" re-added.");
}
else
{
mob.tell("'"+behave+"' is not recognized. Try '?'.");
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genAffects(MOB mob, Environmental E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String affectstr="";
for(int b=0;b<E.numEffects();b++)
{
Ability A=E.fetchEffect(b);
if((A!=null)&&(A.savable()))
{
affectstr+=A.ID();
if(A.text().trim().length()>0)
affectstr+="("+A.text().trim()+"), ";
else
affectstr+=", ";
}
}
if(affectstr.length()>0)
affectstr=affectstr.substring(0,affectstr.length()-2);
mob.tell(showNumber+". Effects: '"+affectstr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter an effect to add/remove (?)\n\r:","");
if(behave.length()>0)
{
if(behave.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
{
Ability chosenOne=null;
for(int a=0;a<E.numEffects();a++)
{
Ability A=E.fetchEffect(a);
if((A!=null)&&(A.ID().equalsIgnoreCase(behave)))
chosenOne=A;
}
if(chosenOne!=null)
{
mob.tell(chosenOne.ID()+" removed.");
E.delEffect(chosenOne);
}
else
{
chosenOne=CMClass.getAbility(behave);
if(chosenOne!=null)
{
String parms="?";
while(parms.equals("?"))
{
parms=chosenOne.text();
parms=mob.session().prompt("Enter any effect parameters (?)\n\r:"+parms);
if(parms.equals("?")){ StringBuffer s2=CMLib.help().getHelpText(chosenOne.ID(),mob,true); if(s2!=null) mob.tell(s2.toString()); else mob.tell("no help!");}
}
chosenOne.setMiscText(parms.trim());
mob.tell(chosenOne.ID()+" added.");
E.addNonUninvokableEffect(chosenOne);
}
else
{
mob.tell("'"+behave+"' is not recognized. Try '?'.");
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genRideable1(MOB mob, Rideable R, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Rideable Type: '"+Rideable.RIDEABLE_DESCS[R.rideBasis()]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean q=false;
String sel="LWACBTEDG";
while(!q)
{
String newType=mob.session().choose("Enter a new value (?)\n\r:",sel+"?","");
if(newType.equals("?"))
{
for(int i=0;i<sel.length();i++)
mob.tell(sel.charAt(i)+") "+Rideable.RIDEABLE_DESCS[i].toLowerCase());
q=false;
}
else
{
q=true;
int newValue=-1;
if(newType.length()>0)
newValue=sel.indexOf(newType.toUpperCase());
if(newValue>=0)
R.setRideBasis(newValue);
else
mob.tell("(no change)");
}
}
}
protected void genRideable2(MOB mob, Rideable E, int showNumber, int showFlag) throws IOException
{ E.setRiderCapacity(CMLib.english().prompt(mob,E.riderCapacity(),showNumber,showFlag,"Number of MOBs held")); }
protected void genShopkeeper1(MOB mob, ShopKeeper E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Shopkeeper type: '"+E.storeKeeperString()+"'.");
StringBuffer buf=new StringBuffer("");
StringBuffer codes=new StringBuffer("");
String codeStr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if(E instanceof Banker)
{
int r=ShopKeeper.DEAL_BANKER;
char c=codeStr.charAt(r);
codes.append(c);
buf.append(c+") "+ShopKeeper.DEAL_DESCS[r]+"\n\r");
r=ShopKeeper.DEAL_CLANBANKER;
c=codeStr.charAt(r);
codes.append(c);
buf.append(c+") "+ShopKeeper.DEAL_DESCS[r]+"\n\r");
}
else
if(E instanceof PostOffice)
{
int r=ShopKeeper.DEAL_POSTMAN;
char c=codeStr.charAt(r);
codes.append(c);
buf.append(c+") "+ShopKeeper.DEAL_DESCS[r]+"\n\r");
r=ShopKeeper.DEAL_CLANPOSTMAN;
c=codeStr.charAt(r);
codes.append(c);
buf.append(c+") "+ShopKeeper.DEAL_DESCS[r]+"\n\r");
}
else
if(E instanceof Auctioneer)
{
int r=ShopKeeper.DEAL_AUCTIONEER;
char c=codeStr.charAt(r);
codes.append(c);
buf.append(c+") "+ShopKeeper.DEAL_DESCS[r]+"\n\r");
r=ShopKeeper.DEAL_AUCTIONEER;
c=codeStr.charAt(r);
codes.append(c);
buf.append(c+") "+ShopKeeper.DEAL_DESCS[r]+"\n\r");
}
else
for(int r=0;r<ShopKeeper.DEAL_DESCS.length;r++)
{
if((r!=ShopKeeper.DEAL_CLANBANKER)
&&(r!=ShopKeeper.DEAL_BANKER)
&&(r!=ShopKeeper.DEAL_CLANPOSTMAN)
&&(r!=ShopKeeper.DEAL_POSTMAN))
{
char c=codeStr.charAt(r);
codes.append(c);
buf.append(c+") "+ShopKeeper.DEAL_DESCS[r]+"\n\r");
}
}
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newType=mob.session().choose(buf.toString()+"Enter a new value\n\r: ",codes.toString(),"");
int newValue=-1;
if(newType.length()>0)
newValue=codeStr.indexOf(newType.toUpperCase());
if(newValue>=0)
{
boolean reexamine=(E.whatIsSold()!=newValue);
E.setWhatIsSold(newValue);
if(reexamine)
{
Vector V=E.getShop().getStoreInventory();
for(int b=0;b<V.size();b++)
if(!E.doISellThis((Environmental)V.elementAt(b)))
E.getShop().delAllStoreInventory((Environmental)V.elementAt(b),E.whatIsSold());
}
}
}
protected void genShopkeeper2(MOB mob, ShopKeeper E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String itemstr="NO";
while(itemstr.length()>0)
{
String inventorystr="";
Vector V=E.getShop().getStoreInventory();
for(int b=0;b<V.size();b++)
{
Environmental E2=(Environmental)V.elementAt(b);
if(E2.isGeneric())
inventorystr+=E2.name()+" ("+E.getShop().numberInStock(E2)+"), ";
else
inventorystr+=CMClass.classID(E2)+" ("+E.getShop().numberInStock(E2)+"), ";
}
if(inventorystr.length()>0)
inventorystr=inventorystr.substring(0,inventorystr.length()-2);
mob.tell(showNumber+". Inventory: '"+inventorystr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
itemstr=mob.session().prompt("Enter something to add/remove (?)\n\r:","");
if(itemstr.length()>0)
{
if(itemstr.equalsIgnoreCase("?"))
{
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
mob.tell(CMLib.lister().reallyList(CMClass.armor(),-1).toString());
mob.tell(CMLib.lister().reallyList(CMClass.weapons(),-1).toString());
mob.tell(CMLib.lister().reallyList(CMClass.miscMagic(),-1).toString());
mob.tell(CMLib.lister().reallyList(CMClass.miscTech(),-1).toString());
mob.tell(CMLib.lister().reallyList(CMClass.clanItems(),-1).toString());
mob.tell(CMLib.lister().reallyList(CMClass.basicItems(),-1).toString());
mob.tell(CMLib.lister().reallyList(CMClass.mobTypes(),-1).toString());
mob.tell("* Plus! Any items on the ground.");
mob.tell("* Plus! Any mobs hanging around in the room.");
}
else
{
Environmental item=E.getShop().getStock(itemstr,null,E.whatIsSold(),null);
if(item!=null)
{
mob.tell(item.ID()+" removed.");
E.getShop().delAllStoreInventory((Environmental)item.copyOf(),E.whatIsSold());
}
else
{
item=CMClass.getUnknown(itemstr);
if((item==null)&&(mob.location()!=null))
{
Room R=mob.location();
item=R.fetchItem(null,itemstr);
if(item==null)
{
item=R.fetchInhabitant(itemstr);
if((item instanceof MOB)&&(!((MOB)item).isMonster()))
item=null;
}
}
if(item!=null)
{
item=(Environmental)item.copyOf();
item.recoverEnvStats();
boolean ok=E.doISellThis(item);
if((item instanceof Ability)
&&((E.whatIsSold()==ShopKeeper.DEAL_TRAINER)||(E.whatIsSold()==ShopKeeper.DEAL_CASTER)))
ok=true;
else
if(E.whatIsSold()==ShopKeeper.DEAL_INVENTORYONLY)
ok=true;
if(!ok)
{
mob.tell("The shopkeeper does not sell that.");
}
else
{
boolean alreadyHasIt=false;
if(E.getShop().doIHaveThisInStock(item.Name(),null,E.whatIsSold(),null))
alreadyHasIt=true;
if(!alreadyHasIt)
{
mob.tell(item.ID()+" added.");
int num=1;
if(!(item instanceof Ability))
num=CMath.s_int(mob.session().prompt("How many? :",""));
int price=CMath.s_int(mob.session().prompt("At what price? :",""));
E.getShop().addStoreInventory(item,num,price,E);
}
}
}
else
{
mob.tell("'"+itemstr+"' is not recognized. Try '?'.");
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genEconomics1(MOB mob, Economics E, int showNumber, int showFlag) throws IOException
{ E.setPrejudiceFactors(CMLib.english().prompt(mob,E.prejudiceFactors(),showNumber,showFlag,"Prejudice",true,false)); }
protected void genEconomics2(MOB mob, Economics E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String header=showNumber+". Item Pricing Factors: ";
String[] prics=E.itemPricingAdjustments();
if((showFlag!=showNumber)&&(showFlag>-999))
{
if(prics.length<1)
mob.tell(header+"''.");
else
if(prics.length==1)
mob.tell(header+"'"+prics[0]+"'.");
else
mob.tell(header+prics.length+" defined..");
return;
}
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
mob.tell(header+"\n\r");
for(int p=0;p<prics.length;p++)
mob.tell(CMStrings.SPACES.substring(0,header.length()-3)
+(p+1)+") "+prics[p]+"\n\r");
String newValue=mob.session().prompt("Enter # to remove, or A to add:\n\r:","");
if(CMath.isInteger(newValue))
{
int x=CMath.s_int(newValue);
if((x>0)&&(x<=prics.length))
{
String[] newPrics=new String[prics.length-1];
int y=0;
for(int i=0;i<prics.length;i++)
if(i!=(x-1))
newPrics[y++]=prics[i];
prics=newPrics;
}
}
else
if(newValue.toUpperCase().startsWith("A"))
{
double dbl=CMath.s_double(mob.session().prompt("Enter a price multiplier between 0.0 and X.Y\n\r: "));
String mask="?";
while(mask.equals("?"))
{
mask=mob.session().prompt("Now enter a mask that describes the item (? for syntax)\n\r: ");
if(mask.equals("?"))
mob.tell(CMLib.masking().maskHelp("\n\r","disallow"));
}
String[] newPrics=new String[prics.length+1];
for(int i=0;i<prics.length;i++)
newPrics[i]=prics[i];
newPrics[prics.length]=dbl+" "+mask;
prics=newPrics;
}
else
{
mob.tell("(no change)");
break;
}
}
E.setItemPricingAdjustments(prics);
}
protected void genAreaBlurbs(MOB mob, Area E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String header=showNumber+". Area Blurb Flags: ";
if((showFlag!=showNumber)&&(showFlag>-999))
{
int numFlags=E.numBlurbFlags();
if(numFlags<1)
mob.tell(header+"''.");
else
if(numFlags==1)
mob.tell(header+"'"+E.getBlurbFlag(0)+": "+E.getBlurbFlag(E.getBlurbFlag(0))+"'.");
else
mob.tell(header+numFlags+" defined..");
return;
}
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
mob.tell(header+"\n\r");
for(int p=0;p<E.numBlurbFlags();p++)
mob.tell((E.getBlurbFlag(p))+": "+E.getBlurbFlag(E.getBlurbFlag(p)));
String newValue=mob.session().prompt("Enter flag to remove, or A to add:\n\r:","");
if(E.getBlurbFlag(newValue.toUpperCase().trim())!=null)
{
E.delBlurbFlag(newValue.toUpperCase().trim());
mob.tell(newValue.toUpperCase().trim()+" removed");
}
else
if(newValue.toUpperCase().equals("A"))
{
String flag=mob.session().prompt("Enter a new flag: ");
if(flag.trim().length()==0) continue;
String desc=mob.session().prompt("Enter a flag blurb (or nothing): ");
E.addBlurbFlag((flag.toUpperCase().trim()+" "+desc).trim());
mob.tell(flag.toUpperCase().trim()+" added");
}
else
if(newValue.length()==0)
{
mob.tell("(no change)");
break;
}
}
}
protected void genEconomics3(MOB mob, Economics E, int showNumber, int showFlag) throws IOException
{ E.setBudget(CMLib.english().prompt(mob,E.budget(),showNumber,showFlag,"Budget",true,false)); }
protected void genEconomics4(MOB mob, Economics E, int showNumber, int showFlag) throws IOException
{ E.setDevalueRate(CMLib.english().prompt(mob,E.devalueRate(),showNumber,showFlag,"Devaluation rate(s)",true,false)); }
protected void genEconomics5(MOB mob, Economics E, int showNumber, int showFlag) throws IOException
{ E.setInvResetRate(CMLib.english().prompt(mob,E.invResetRate(),showNumber,showFlag,"Inventory reset rate [ticks]")); }
protected void genEconomics6(MOB mob, Economics E, int showNumber, int showFlag) throws IOException
{ E.setIgnoreMask(CMLib.english().prompt(mob,E.ignoreMask(),showNumber,showFlag,"Ignore Mask",true,false)); }
protected void genAbilities(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String abilitiestr="";
for(int a=0;a<E.numLearnedAbilities();a++)
{
Ability A=E.fetchAbility(a);
if((A!=null)&&(A.savable()))
abilitiestr+=A.ID()+", ";
}
if(abilitiestr.length()>0)
abilitiestr=abilitiestr.substring(0,abilitiestr.length()-2);
if((abilitiestr.length()>60)&&((showFlag!=showNumber)&&(showFlag>-999)))
abilitiestr=abilitiestr.substring(0,60)+"...";
mob.tell(showNumber+". Abilities: '"+abilitiestr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter an ability to add/remove (?)\n\r:","");
if(behave.length()>0)
{
if(behave.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
{
Ability chosenOne=null;
for(int a=0;a<E.numLearnedAbilities();a++)
{
Ability A=E.fetchAbility(a);
if((A!=null)&&(A.ID().equalsIgnoreCase(behave)))
chosenOne=A;
}
if(chosenOne!=null)
{
mob.tell(chosenOne.ID()+" removed.");
E.delAbility(chosenOne);
if(E.fetchEffect(chosenOne.ID())!=null)
E.delEffect(E.fetchEffect(chosenOne.ID()));
}
else
{
chosenOne=CMClass.getAbility(behave);
if(chosenOne!=null)
{
boolean alreadyHasIt=(E.fetchAbility(chosenOne.ID())!=null);
if(!alreadyHasIt)
mob.tell(chosenOne.ID()+" added.");
else
mob.tell(chosenOne.ID()+" re-added.");
if(!alreadyHasIt)
{
chosenOne=(Ability)chosenOne.copyOf();
E.addAbility(chosenOne);
chosenOne.setProficiency(50);
chosenOne.autoInvocation(mob);
}
}
else
{
mob.tell("'"+behave+"' is not recognized. Try '?'.");
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genClanMembers(MOB mob, Clan E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
DVector members=E.getMemberList();
DVector membersCopy=members.copyOf();
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String memberStr="";
for(int m=0;m<members.size();m++)
memberStr+=((String)members.elementAt(m,1))+" ("+CMLib.clans().getRoleName(E.getGovernment(),((Integer)members.elementAt(m,2)).intValue(),true,false)+"), ";
if(memberStr.length()>0)
memberStr=memberStr.substring(0,memberStr.length()-2);
mob.tell(showNumber+". Clan Members : '"+memberStr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter a name to add/remove\n\r:","");
if(behave.length()>0)
{
int chosenOne=-1;
for(int m=0;m<members.size();m++)
if(behave.equalsIgnoreCase((String)members.elementAt(m,1)))
chosenOne=m;
if(chosenOne>=0)
{
mob.tell((String)members.elementAt(chosenOne,1)+" removed.");
members.removeElementAt(chosenOne);
}
else
{
MOB M=CMLib.map().getLoadPlayer(behave);
if(M!=null)
{
int oldNum=-1;
for(int m=0;m<membersCopy.size();m++)
if(behave.equalsIgnoreCase((String)membersCopy.elementAt(m,1)))
{
oldNum=m;
members.addElement(membersCopy.elementAt(m,1),membersCopy.elementAt(m,2),membersCopy.elementAt(m,3));
break;
}
int index=oldNum;
if(index<0)
{
index=members.size();
members.addElement(M.Name(),new Integer(Clan.POS_MEMBER),new Long(M.playerStats().lastDateTime()));
}
int newRole=-1;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newRole<0))
{
String newRoleStr=mob.session().prompt("Enter this members role (?) '"+CMLib.clans().getRoleName(E.getGovernment(),((Integer)members.elementAt(index,2)).intValue(),true,false)+"': ","");
StringBuffer roles=new StringBuffer();
for(int i=0;i<Clan.ROL_DESCS[E.getGovernment()].length;i++)
{
roles.append(Clan.ROL_DESCS[E.getGovernment()][i]+", ");
if(newRoleStr.equalsIgnoreCase(Clan.ROL_DESCS[E.getGovernment()][i]))
newRole=Clan.POSORDER[i];
}
roles=new StringBuffer(roles.substring(0,roles.length()-2));
if(newRole<0)
mob.tell("That role is invalid. Valid roles include: "+roles.toString());
else
break;
}
if(oldNum<0)
mob.tell(M.Name()+" added.");
else
mob.tell(M.Name()+" re-added.");
members.setElementAt(index,2,new Integer(newRole));
}
else
{
mob.tell("'"+behave+"' is an unrecognized player name.");
}
}
// first add missing ones
for(int m=0;m<members.size();m++)
{
String newName=(String)members.elementAt(m,1);
if(!membersCopy.contains(newName))
{
MOB M=CMLib.map().getLoadPlayer(newName);
if(M!=null)
{
Clan oldC=CMLib.clans().getClan(M.getClanID());
if((oldC!=null)
&&(!M.getClanID().equalsIgnoreCase(E.clanID())))
{
M.setClanID("");
M.setClanRole(Clan.POS_APPLICANT);
oldC.updateClanPrivileges(M);
}
Integer role=(Integer)members.elementAt(m,2);
CMLib.database().DBUpdateClanMembership(M.Name(), E.clanID(), role.intValue());
M.setClanID(E.clanID());
M.setClanRole(role.intValue());
E.updateClanPrivileges(M);
}
}
}
// now adjust changed roles
for(int m=0;m<members.size();m++)
{
String newName=(String)members.elementAt(m,1);
if(membersCopy.contains(newName))
{
MOB M=CMLib.map().getLoadPlayer(newName);
int newRole=((Integer)members.elementAt(m,2)).intValue();
if((M!=null)&&(newRole!=M.getClanRole()))
{
CMLib.database().DBUpdateClanMembership(M.Name(), E.clanID(), newRole);
M.setClanRole(newRole);
E.updateClanPrivileges(M);
}
}
}
// now remove old members
for(int m=0;m<membersCopy.size();m++)
{
String newName=(String)membersCopy.elementAt(m,1);
if(!members.contains(newName))
{
MOB M=CMLib.map().getLoadPlayer(newName);
if(M!=null)
{
M.setClanID("");
M.setClanRole(Clan.POS_APPLICANT);
E.updateClanPrivileges(M);
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genDeity1(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setClericRequirements(CMLib.english().prompt(mob,E.getClericRequirements(),showNumber,showFlag,"Cleric Requirements",false,false)); }
protected void genDeity2(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setClericRitual(CMLib.english().prompt(mob,E.getClericRitual(),showNumber,showFlag,"Cleric Ritual",false,false)); }
protected void genDeity3(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setWorshipRequirements(CMLib.english().prompt(mob,E.getWorshipRequirements(),showNumber,showFlag,"Worshiper Requirements",false,false)); }
protected void genDeity4(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setWorshipRitual(CMLib.english().prompt(mob,E.getWorshipRitual(),showNumber,showFlag,"Worshiper Ritual",false,false)); }
protected void genDeity5(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String abilitiestr="";
for(int a=0;a<E.numBlessings();a++)
{
Ability A=E.fetchBlessing(a);
if((A!=null)&&(A.savable()))
abilitiestr+=A.ID()+", ";
}
if(abilitiestr.length()>0)
abilitiestr=abilitiestr.substring(0,abilitiestr.length()-2);
mob.tell(showNumber+". Blessings: '"+abilitiestr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter an ability to add/remove (?)\n\r:","");
if(behave.length()>0)
{
if(behave.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
{
Ability chosenOne=null;
for(int a=0;a<E.numBlessings();a++)
{
Ability A=E.fetchBlessing(a);
if((A!=null)&&(A.ID().equalsIgnoreCase(behave)))
chosenOne=A;
}
if(chosenOne!=null)
{
mob.tell(chosenOne.ID()+" removed.");
E.delBlessing(chosenOne);
}
else
{
chosenOne=CMClass.getAbility(behave);
if(chosenOne!=null)
{
boolean alreadyHasIt=false;
for(int a=0;a<E.numBlessings();a++)
{
Ability A=E.fetchBlessing(a);
if((A!=null)&&(A.ID().equals(chosenOne.ID())))
alreadyHasIt=true;
}
boolean clericOnly=mob.session().confirm("Is this for clerics only (y/N)?","N");
if(!alreadyHasIt)
mob.tell(chosenOne.ID()+" added.");
else
mob.tell(chosenOne.ID()+" re-added.");
if(!alreadyHasIt)
E.addBlessing((Ability)chosenOne.copyOf(),clericOnly);
}
else
{
mob.tell("'"+behave+"' is not recognized. Try '?'.");
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genDeity6(MOB mob, Deity E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String abilitiestr="";
for(int a=0;a<E.numCurses();a++)
{
Ability A=E.fetchCurse(a);
if((A!=null)&&(A.savable()))
abilitiestr+=A.ID()+", ";
}
if(abilitiestr.length()>0)
abilitiestr=abilitiestr.substring(0,abilitiestr.length()-2);
mob.tell(showNumber+". Curses: '"+abilitiestr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter an ability to add/remove (?)\n\r:","");
if(behave.length()>0)
{
if(behave.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
{
Ability chosenOne=null;
for(int a=0;a<E.numCurses();a++)
{
Ability A=E.fetchCurse(a);
if((A!=null)&&(A.ID().equalsIgnoreCase(behave)))
chosenOne=A;
}
if(chosenOne!=null)
{
mob.tell(chosenOne.ID()+" removed.");
E.delCurse(chosenOne);
}
else
{
chosenOne=CMClass.getAbility(behave);
if(chosenOne!=null)
{
boolean alreadyHasIt=false;
for(int a=0;a<E.numCurses();a++)
{
Ability A=E.fetchCurse(a);
if((A!=null)&&(A.ID().equals(chosenOne.ID())))
alreadyHasIt=true;
}
boolean clericOnly=mob.session().confirm("Is this for clerics only (y/N)?","N");
if(!alreadyHasIt)
mob.tell(chosenOne.ID()+" added.");
else
mob.tell(chosenOne.ID()+" re-added.");
if(!alreadyHasIt)
E.addCurse((Ability)chosenOne.copyOf(),clericOnly);
}
else
{
mob.tell("'"+behave+"' is not recognized. Try '?'.");
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genDeity7(MOB mob, Deity E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String abilitiestr="";
for(int a=0;a<E.numPowers();a++)
{
Ability A=E.fetchPower(a);
if((A!=null)&&(A.savable()))
abilitiestr+=A.ID()+", ";
}
if(abilitiestr.length()>0)
abilitiestr=abilitiestr.substring(0,abilitiestr.length()-2);
mob.tell(showNumber+". Granted Powers: '"+abilitiestr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter an ability to add/remove (?)\n\r:","");
if(behave.length()>0)
{
if(behave.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
{
Ability chosenOne=null;
for(int a=0;a<E.numPowers();a++)
{
Ability A=E.fetchPower(a);
if((A!=null)&&(A.ID().equalsIgnoreCase(behave)))
chosenOne=A;
}
if(chosenOne!=null)
{
mob.tell(chosenOne.ID()+" removed.");
E.delPower(chosenOne);
}
else
{
chosenOne=CMClass.getAbility(behave);
if(chosenOne!=null)
{
boolean alreadyHasIt=false;
for(int a=0;a<E.numPowers();a++)
{
Ability A=E.fetchPower(a);
if((A!=null)&&(A.ID().equals(chosenOne.ID())))
alreadyHasIt=true;
}
if(!alreadyHasIt)
mob.tell(chosenOne.ID()+" added.");
else
mob.tell(chosenOne.ID()+" re-added.");
if(!alreadyHasIt)
E.addPower((Ability)chosenOne.copyOf());
}
else
{
mob.tell("'"+behave+"' is not recognized. Try '?'.");
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genDeity8(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setClericSin(CMLib.english().prompt(mob,E.getClericSin(),showNumber,showFlag,"Cleric Sin",false,false)); }
protected void genDeity9(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setWorshipSin(CMLib.english().prompt(mob,E.getWorshipSin(),showNumber,showFlag,"Worshiper Sin",false,false)); }
protected void genDeity0(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setClericPowerup(CMLib.english().prompt(mob,E.getClericPowerup(),showNumber,showFlag,"Cleric Power Ritual",false,false)); }
protected void genDeity11(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setServiceRitual(CMLib.english().prompt(mob,E.getServiceRitual(),showNumber,showFlag,"Service Ritual",false,false)); }
protected void genGridLocaleX(MOB mob, GridZones E, int showNumber, int showFlag) throws IOException
{ E.setXGridSize(CMLib.english().prompt(mob,E.xGridSize(),showNumber,showFlag,"Size (X)")); }
protected void genGridLocaleY(MOB mob, GridZones E, int showNumber, int showFlag) throws IOException
{ E.setYGridSize(CMLib.english().prompt(mob,E.yGridSize(),showNumber,showFlag,"Size (Y)")); }
protected void genWornLocation(MOB mob, Item E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if((showFlag!=showNumber)&&(showFlag>-999))
{
StringBuffer buf=new StringBuffer(showNumber+". ");
if(!E.rawLogicalAnd())
buf.append("Wear on any one of: ");
else
buf.append("Worn on all of: ");
for(int l=0;l<Item.WORN_CODES.length;l++)
{
long wornCode=1<<l;
if((CMLib.flags().wornLocation(wornCode).length()>0)
&&(((E.rawProperLocationBitmap()&wornCode)==wornCode)))
buf.append(CMLib.flags().wornLocation(wornCode)+", ");
}
if(buf.toString().endsWith(", "))
mob.tell(buf.substring(0,buf.length()-2));
else
mob.tell(buf.toString());
return;
}
int codeVal=-1;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(codeVal!=0))
{
mob.tell("Wearing parameters\n\r0: Done");
if(!E.rawLogicalAnd())
mob.tell("1: Able to worn on any ONE of these locations:");
else
mob.tell("1: Must be worn on ALL of these locations:");
for(int l=0;l<Item.WORN_CODES.length;l++)
{
long wornCode=1<<l;
if(CMLib.flags().wornLocation(wornCode).length()>0)
{
String header=(l+2)+": ("+CMLib.flags().wornLocation(wornCode)+") : "+(((E.rawProperLocationBitmap()&wornCode)==wornCode)?"YES":"NO");
mob.tell(header);
}
}
codeVal=CMath.s_int(mob.session().prompt("Select an option number above to TOGGLE\n\r: "));
if(codeVal>0)
{
if(codeVal==1)
E.setRawLogicalAnd(!E.rawLogicalAnd());
else
{
int wornCode=1<<(codeVal-2);
if((E.rawProperLocationBitmap()&wornCode)==wornCode)
E.setRawProperLocationBitmap(E.rawProperLocationBitmap()-wornCode);
else
E.setRawProperLocationBitmap(E.rawProperLocationBitmap()|wornCode);
}
}
}
}
protected void genThirstQuenched(MOB mob, Drink E, int showNumber, int showFlag) throws IOException
{ E.setThirstQuenched(CMLib.english().prompt(mob,E.thirstQuenched(),showNumber,showFlag,"Quenched/Drink")); }
protected void genDrinkHeld(MOB mob, Drink E, int showNumber, int showFlag) throws IOException
{
E.setLiquidHeld(CMLib.english().prompt(mob,E.liquidHeld(),showNumber,showFlag,"Amount of Drink Held"));
E.setLiquidRemaining(E.liquidHeld());
}
protected void genAttackAttribute(MOB mob, CharClass E, int showNumber, int showFlag, String FieldDisp, String Field)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". "+FieldDisp+": '"+CharStats.STAT_DESCS[CMath.s_int(E.getStat(Field))]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a new one\n\r:","");
String newStat="";
for(int i=0;i<CharStats.NUM_BASE_STATS;i++)
if(newName.equalsIgnoreCase(CharStats.STAT_DESCS[i]))
newStat=""+i;
if(newStat.length()>0)
E.setStat(Field,newStat);
else
mob.tell("(no change)");
}
protected void genArmorCode(MOB mob, CharClass E, int showNumber, int showFlag, String FieldDisp, String Field)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". "+FieldDisp+": '"+CharClass.ARMOR_LONGDESC[CMath.s_int(E.getStat(Field))]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter ("+CMParms.toStringList(CharClass.ARMOR_DESCS)+")\n\r:","");
String newStat="";
for(int i=0;i<CharClass.ARMOR_DESCS.length;i++)
if(newName.equalsIgnoreCase(CharClass.ARMOR_DESCS[i]))
newStat=""+i;
if(newStat.length()>0)
E.setStat(Field,newStat);
else
mob.tell("(no change)");
}
protected void genQualifications(MOB mob, CharClass E, int showNumber, int showFlag, String FieldDisp, String Field)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". "+FieldDisp+": '"+CMLib.masking().maskDesc(E.getStat(Field))+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName="?";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.equals("?")))
{
newName=mob.session().prompt("Enter a new mask (?)\n\r:","");
if(newName.equals("?"))
mob.tell(CMLib.masking().maskHelp("\n","disallow"));
}
if((newName.length()>0)&&(!newName.equals("?")))
E.setStat(Field,newName);
else
mob.tell("(no change)");
}
protected void genClanAccept(MOB mob, Clan E, int showNumber, int showFlag) throws IOException
{ E.setAcceptanceSettings(CMLib.english().prompt(mob,E.getAcceptanceSettings(),showNumber,showFlag,"Clan Qualifications",false,false,CMLib.masking().maskHelp("\n","disallow"))); }
protected void genWeaponRestr(MOB mob, CharClass E, int showNumber, int showFlag, String FieldDisp, String FieldNum, String Field)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
Vector set=CMParms.parseCommas(E.getStat(Field),true);
StringBuffer str=new StringBuffer("");
for(int v=0;v<set.size();v++)
str.append(" "+Weapon.classifictionDescription[CMath.s_int((String)set.elementAt(v))].toLowerCase());
mob.tell(showNumber+". "+FieldDisp+": '"+str.toString()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName="?";
boolean setChanged=false;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.equals("?")))
{
newName=mob.session().prompt("Enter a weapon class to add/remove (?)\n\r:","");
if(newName.equals("?"))
mob.tell(CMParms.toStringList(Weapon.classifictionDescription));
else
if(newName.length()>0)
{
int foundCode=-1;
for(int i=0;i<Weapon.classifictionDescription.length;i++)
if(Weapon.classifictionDescription[i].equalsIgnoreCase(newName))
foundCode=i;
if(foundCode<0)
{
mob.tell("'"+newName+"' is not recognized. Try '?'.");
newName="?";
}
else
{
int x=set.indexOf(""+foundCode);
if(x>=0)
{
setChanged=true;
set.removeElementAt(x);
mob.tell("'"+newName+"' removed.");
newName="?";
}
else
{
set.addElement(""+foundCode);
setChanged=true;
mob.tell("'"+newName+"' added.");
newName="?";
}
}
}
}
if(setChanged)
E.setStat(Field,CMParms.toStringList(set));
else
mob.tell("(no change)");
}
protected void genWeaponMaterials(MOB mob, CharClass E, int showNumber, int showFlag, String FieldDisp, String FieldNum, String Field)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
Vector set=CMParms.parseCommas(E.getStat(Field),true);
StringBuffer str=new StringBuffer("");
for(int v=0;v<set.size();v++)
str.append(" "+CMLib.materials().getMaterialDesc(CMath.s_int((String)set.elementAt(v))));
mob.tell(showNumber+". "+FieldDisp+": '"+str.toString()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName="?";
boolean setChanged=false;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.equals("?")))
{
newName=mob.session().prompt("Enter a material type to add/remove to requirements (?)\n\r:","");
if(newName.equals("?"))
mob.tell(CMParms.toStringList(RawMaterial.MATERIAL_DESCS));
else
if(newName.length()>0)
{
int foundCode=CMLib.materials().getMaterialCode(newName,true);
if(foundCode<0) foundCode=CMLib.materials().getMaterialCode(newName,false);
if(foundCode<0)
{
mob.tell("'"+newName+"' is not recognized. Try '?'.");
newName="?";
}
else
{
int x=set.indexOf(""+foundCode);
if(x>=0)
{
setChanged=true;
set.removeElementAt(x);
mob.tell("'"+newName+"' removed.");
newName="?";
}
else
{
set.addElement(""+foundCode);
setChanged=true;
mob.tell("'"+newName+"' added.");
newName="?";
}
}
}
}
if(setChanged)
E.setStat(Field,CMParms.toStringList(set));
else
mob.tell("(no change)");
}
protected void genDisableFlags(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
int flags=CMath.s_int(E.getStat("DISFLAGS"));
String newName="?";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.equals("?")))
{
StringBuffer disabled=new StringBuffer("");
for(int i=0;i<Race.GENFLAG_DESCS.length;i++)
if(CMath.isSet(flags,i))
disabled.append(Race.GENFLAG_DESCS[i]);
mob.tell(showNumber+". Disabled: '"+disabled+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
newName=mob.session().prompt("Enter flag to toggle (?)\n\r:","").toUpperCase();
if(newName.length()==0)
mob.tell("(no change)");
else
if(CMParms.contains(Race.GENFLAG_DESCS,newName))
{
int bit=CMParms.indexOf(Race.GENFLAG_DESCS,newName);
if(CMath.isSet(flags,bit))
flags=flags-(int)CMath.pow(2,bit);
else
flags=flags+(int)CMath.pow(2,bit);
}
else
if(newName.equalsIgnoreCase("?"))
{
StringBuffer str=new StringBuffer("Valid values: \n\r");
for(int i=0;i<Race.GENFLAG_DESCS.length;i++)
str.append(Race.GENFLAG_DESCS[i]+"\n\r");
mob.tell(str.toString());
}
else
mob.tell("(no change)");
}
E.setStat("DISFLAGS",""+flags);
}
protected void genRaceWearFlags(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
int flags=CMath.s_int(E.getStat("WEAR"));
String newName="?";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.equals("?")))
{
StringBuffer wearable=new StringBuffer("");
for(int i=1;i<Item.WORN_DESCS.length;i++)
if(CMath.isSet(flags,i-1))
wearable.append(Item.WORN_DESCS[i]+" ");
mob.tell(showNumber+". UNWearable locations: '"+wearable+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
newName=mob.session().prompt("Enter a location to toggle (?)\n\r:","").toUpperCase();
if(newName.length()==0)
mob.tell("(no change)");
else
if(CMParms.contains(Item.WORN_DESCS,newName))
{
int bit=CMParms.indexOf(Item.WORN_DESCS,newName)-1;
if(bit>=0)
{
if(CMath.isSet(flags,bit))
flags=flags-(int)CMath.pow(2,bit);
else
flags=flags+(int)CMath.pow(2,bit);
}
}
else
if(newName.equalsIgnoreCase("?"))
{
StringBuffer str=new StringBuffer("Valid values: \n\r");
for(int i=0;i<Item.WORN_DESCS.length;i++)
str.append(Item.WORN_DESCS[i]+" ");
mob.tell(str.toString());
}
else
mob.tell("(no change)");
}
E.setStat("WEAR",""+flags);
}
protected void genRaceAvailability(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Availability: '"+Area.THEME_DESCS_EXT[CMath.s_int(E.getStat("AVAIL"))]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName="?";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.equals("?")))
{
newName=mob.session().prompt("Enter a new value (?)\n\r:","");
if(newName.length()==0)
mob.tell("(no change)");
else
if((CMath.isNumber(newName))&&(CMath.s_int(newName)<Area.THEME_DESCS_EXT.length))
E.setStat("AVAIL",""+CMath.s_int(newName));
else
if(newName.equalsIgnoreCase("?"))
{
StringBuffer str=new StringBuffer("Valid values: \n\r");
for(int i=0;i<Area.THEME_DESCS_EXT.length;i++)
str.append(i+") "+Area.THEME_DESCS_EXT[i]+"\n\r");
mob.tell(str.toString());
}
else
mob.tell("(no change)");
}
}
void genClassAvailability(MOB mob, CharClass E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Availability: '"+Area.THEME_DESCS_EXT[CMath.s_int(E.getStat("PLAYER"))]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName="?";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.equals("?")))
{
newName=mob.session().prompt("Enter a new value (?)\n\r:","");
if(newName.length()==0)
mob.tell("(no change)");
else
if((CMath.isNumber(newName))&&(CMath.s_int(newName)<Area.THEME_DESCS_EXT.length))
E.setStat("PLAYER",""+CMath.s_int(newName));
else
if(newName.equalsIgnoreCase("?"))
{
StringBuffer str=new StringBuffer("Valid values: \n\r");
for(int i=0;i<Area.THEME_DESCS_EXT.length;i++)
str.append(i+") "+Area.THEME_DESCS_EXT[i]+"\n\r");
mob.tell(str.toString());
}
else
mob.tell("(no change)");
}
}
protected void genCat(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Racial Category: '"+E.racialCategory()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a new one\n\r:","");
if(newName.length()>0)
{
boolean found=false;
if(newName.startsWith("new "))
{
newName=CMStrings.capitalizeAndLower(newName.substring(4));
if(newName.length()>0)
found=true;
}
else
for(Enumeration r=CMClass.races();r.hasMoreElements();)
{
Race R=(Race)r.nextElement();
if(newName.equalsIgnoreCase(R.racialCategory()))
{
newName=R.racialCategory();
found=true;
break;
}
}
if(!found)
{
StringBuffer str=new StringBuffer("That category does not exist. Valid categories include: ");
HashSet H=new HashSet();
for(Enumeration r=CMClass.races();r.hasMoreElements();)
{
Race R=(Race)r.nextElement();
if(!H.contains(R.racialCategory()))
{
H.add(R.racialCategory());
str.append(R.racialCategory()+", ");
}
}
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
E.setStat("CAT",newName);
}
else
mob.tell("(no change)");
}
protected void genRaceBuddy(MOB mob, Race E, int showNumber, int showFlag, String prompt, String flag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". "+prompt+": '"+E.getStat(flag)+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a new one\n\r:","");
if(newName.length()>0)
{
Race R2=CMClass.getRace(newName);
if(R2==null) R2=(Race)CMClass.unsortedLoadClass("RACE",newName);
if((R2!=null)&&(R2.isGeneric()))
R2=null;
if(R2==null)
{
StringBuffer str=new StringBuffer("That race name is invalid or is generic. Valid races include: ");
for(Enumeration r=CMClass.races();r.hasMoreElements();)
{
Race R=(Race)r.nextElement();
if(!R.isGeneric())
str.append(R.ID()+", ");
}
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
if(CMClass.getRace(newName)==R2)
E.setStat(flag,R2.ID());
else
E.setStat(flag,R2.getClass().getName());
}
else
mob.tell("(no change)");
}
protected void genClassBuddy(MOB mob, CharClass E, int showNumber, int showFlag, String prompt, String flag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". "+prompt+": '"+E.getStat(flag)+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a new one\n\r:","");
if(newName.length()>0)
{
CharClass C2=CMClass.getCharClass(newName);
if(C2==null) C2=(CharClass)CMClass.unsortedLoadClass("CHARCLASS",newName);
if((C2!=null)&&(C2.isGeneric()))
C2=null;
if(C2==null)
{
StringBuffer str=new StringBuffer("That char class name is invalid or is generic. Valid char classes include: ");
for(Enumeration r=CMClass.charClasses();r.hasMoreElements();)
{
CharClass C=(CharClass)r.nextElement();
if(!C.isGeneric())
str.append(C.ID()+", ");
}
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
if(CMClass.getCharClass(newName)==C2)
E.setStat(flag,C2.ID());
else
E.setStat(flag,C2.getClass().getName());
}
else
mob.tell("(no change)");
}
protected void genBodyParts(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
StringBuffer parts=new StringBuffer("");
for(int i=0;i<Race.BODYPARTSTR.length;i++)
if(E.bodyMask()[i]!=0) parts.append(Race.BODYPARTSTR[i].toLowerCase()+"("+E.bodyMask()[i]+") ");
mob.tell(showNumber+". Body Parts: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a body part\n\r:","");
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<Race.BODYPARTSTR.length;i++)
if(newName.equalsIgnoreCase(Race.BODYPARTSTR[i]))
{ partNum=i; break;}
if(partNum<0)
{
StringBuffer str=new StringBuffer("That body part is invalid. Valid parts include: ");
for(int i=0;i<Race.BODYPARTSTR.length;i++)
str.append(Race.BODYPARTSTR[i]+", ");
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
{
newName=mob.session().prompt("Enter new number ("+E.bodyMask()[partNum]+"), 0=none\n\r:",""+E.bodyMask()[partNum]);
if(newName.length()>0)
E.bodyMask()[partNum]=CMath.s_int(newName);
else
mob.tell("(no change)");
}
}
else
mob.tell("(no change)");
}
protected void genEStats(MOB mob, Race R, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
EnvStats S=(EnvStats)CMClass.getCommon("DefaultEnvStats");
S.setAllValues(0);
CMLib.coffeeMaker().setEnvStats(S,R.getStat("ESTATS"));
StringBuffer parts=new StringBuffer("");
for(int i=0;i<S.getStatCodes().length;i++)
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
parts.append(CMStrings.capitalizeAndLower(S.getStatCodes()[i])+"("+S.getStat(S.getStatCodes()[i])+") ");
mob.tell(showNumber+". EStat Adjustments: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean done=false;
while((!done)&&(mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a stat name\n\r:","");
if(newName.length()>0)
{
String partName=null;
for(int i=0;i<S.getStatCodes().length;i++)
if(newName.equalsIgnoreCase(S.getStatCodes()[i]))
{ partName=S.getStatCodes()[i]; break;}
if(partName==null)
{
StringBuffer str=new StringBuffer("That stat is invalid. Valid stats include: ");
for(int i=0;i<S.getStatCodes().length;i++)
str.append(S.getStatCodes()[i]+", ");
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
{
boolean checkChange=false;
if(partName.equals("DISPOSITION"))
{
genDisposition(mob,S,0,0);
checkChange=true;
}
else
if(partName.equals("SENSES"))
{
genSensesMask(mob,S,0,0);
checkChange=true;
}
else
{
newName=mob.session().prompt("Enter a value\n\r:","");
if(newName.length()>0)
{
S.setStat(partName,newName);
checkChange=true;
}
else
mob.tell("(no change)");
}
if(checkChange)
{
boolean zereoed=true;
for(int i=0;i<S.getStatCodes().length;i++)
{
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
{ zereoed=false; break;}
}
if(zereoed)
R.setStat("ESTATS","");
else
R.setStat("ESTATS",CMLib.coffeeMaker().getEnvStatsStr(S));
}
}
}
else
{
mob.tell("(no change)");
done=true;
}
}
}
protected void genAState(MOB mob,
Race R,
String field,
String prompt,
int showNumber,
int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
CharState S=(CharState)CMClass.getCommon("DefaultCharState"); S.setAllValues(0);
CMLib.coffeeMaker().setCharState(S,R.getStat(field));
StringBuffer parts=new StringBuffer("");
for(int i=0;i<S.getStatCodes().length;i++)
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
parts.append(CMStrings.capitalizeAndLower(S.getStatCodes()[i])+"("+S.getStat(S.getStatCodes()[i])+") ");
mob.tell(showNumber+". "+prompt+": "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean done=false;
while((!done)&&(mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a stat name\n\r:","");
if(newName.length()>0)
{
String partName=null;
for(int i=0;i<S.getStatCodes().length;i++)
if(newName.equalsIgnoreCase(S.getStatCodes()[i]))
{ partName=S.getStatCodes()[i]; break;}
if(partName==null)
{
StringBuffer str=new StringBuffer("That stat is invalid. Valid stats include: ");
for(int i=0;i<S.getStatCodes().length;i++)
str.append(S.getStatCodes()[i]+", ");
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
{
newName=mob.session().prompt("Enter a value\n\r:","");
if(newName.length()>0)
{
S.setStat(partName,newName);
boolean zereoed=true;
for(int i=0;i<S.getStatCodes().length;i++)
{
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
{ zereoed=false; break;}
}
if(zereoed)
R.setStat(field,"");
else
R.setStat(field,CMLib.coffeeMaker().getCharStateStr(S));
}
else
mob.tell("(no change)");
}
}
else
{
mob.tell("(no change)");
done=true;
}
}
}
protected void genAStats(MOB mob, Race R, String Field, String FieldName, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
CharStats S=(CharStats)CMClass.getCommon("DefaultCharStats"); S.setAllValues(0);
CMLib.coffeeMaker().setCharStats(S,R.getStat(Field));
StringBuffer parts=new StringBuffer("");
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
if(S.getStat(i)!=0)
parts.append(CMStrings.capitalizeAndLower(CharStats.STAT_DESCS[i])+"("+S.getStat(i)+") ");
mob.tell(showNumber+". "+FieldName+": "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean done=false;
while((!done)&&(mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a stat name\n\r:","");
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
if(newName.equalsIgnoreCase(CharStats.STAT_DESCS[i]))
{ partNum=i; break;}
if(partNum<0)
{
StringBuffer str=new StringBuffer("That stat is invalid. Valid stats include: ");
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
str.append(CharStats.STAT_DESCS[i]+", ");
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
{
newName=mob.session().prompt("Enter a value\n\r:","");
if(newName.length()>0)
{
if(newName.trim().equalsIgnoreCase("0"))
S.setStat(partNum,CMath.s_int(newName));
else
if(partNum==CharStats.STAT_GENDER)
S.setStat(partNum,(int)newName.charAt(0));
else
S.setStat(partNum,CMath.s_int(newName));
boolean zereoed=true;
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
{
if(S.getStat(i)!=0)
{ zereoed=false; break;}
}
if(zereoed)
R.setStat(Field,"");
else
R.setStat(Field,CMLib.coffeeMaker().getCharStatsStr(S));
}
else
mob.tell("(no change)");
}
}
else
{
mob.tell("(no change)");
done=true;
}
}
}
protected void genEStats(MOB mob, CharClass R, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
EnvStats S=(EnvStats)CMClass.getCommon("DefaultEnvStats");
S.setAllValues(0);
CMLib.coffeeMaker().setEnvStats(S,R.getStat("ESTATS"));
StringBuffer parts=new StringBuffer("");
for(int i=0;i<S.getStatCodes().length;i++)
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
parts.append(CMStrings.capitalizeAndLower(S.getStatCodes()[i])+"("+S.getStat(S.getStatCodes()[i])+") ");
mob.tell(showNumber+". EStat Adjustments: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean done=false;
while((!done)&&(mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a stat name\n\r:","");
if(newName.length()>0)
{
String partName=null;
for(int i=0;i<S.getStatCodes().length;i++)
if(newName.equalsIgnoreCase(S.getStatCodes()[i]))
{ partName=S.getStatCodes()[i]; break;}
if(partName==null)
{
StringBuffer str=new StringBuffer("That stat is invalid. Valid stats include: ");
for(int i=0;i<S.getStatCodes().length;i++)
str.append(S.getStatCodes()[i]+", ");
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
{
boolean checkChange=false;
if(partName.equals("DISPOSITION"))
{
genDisposition(mob,S,0,0);
checkChange=true;
}
else
if(partName.equals("SENSES"))
{
genSensesMask(mob,S,0,0);
checkChange=true;
}
else
{
newName=mob.session().prompt("Enter a value\n\r:","");
if(newName.length()>0)
{
S.setStat(partName,newName);
checkChange=true;
}
else
mob.tell("(no change)");
}
if(checkChange)
{
boolean zereoed=true;
for(int i=0;i<S.getStatCodes().length;i++)
{
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
{ zereoed=false; break;}
}
if(zereoed)
R.setStat("ESTATS","");
else
R.setStat("ESTATS",CMLib.coffeeMaker().getEnvStatsStr(S));
}
}
}
else
{
mob.tell("(no change)");
done=true;
}
}
}
protected void genAState(MOB mob,
CharClass R,
String field,
String prompt,
int showNumber,
int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
CharState S=(CharState)CMClass.getCommon("DefaultCharState"); S.setAllValues(0);
CMLib.coffeeMaker().setCharState(S,R.getStat(field));
StringBuffer parts=new StringBuffer("");
for(int i=0;i<S.getStatCodes().length;i++)
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
parts.append(CMStrings.capitalizeAndLower(S.getStatCodes()[i])+"("+S.getStat(S.getStatCodes()[i])+") ");
mob.tell(showNumber+". "+prompt+": "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean done=false;
while((!done)&&(mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a stat name\n\r:","");
if(newName.length()>0)
{
String partName=null;
for(int i=0;i<S.getStatCodes().length;i++)
if(newName.equalsIgnoreCase(S.getStatCodes()[i]))
{ partName=S.getStatCodes()[i]; break;}
if(partName==null)
{
StringBuffer str=new StringBuffer("That stat is invalid. Valid stats include: ");
for(int i=0;i<S.getStatCodes().length;i++)
str.append(S.getStatCodes()[i]+", ");
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
{
newName=mob.session().prompt("Enter a value\n\r:","");
if(newName.length()>0)
{
S.setStat(partName,newName);
boolean zereoed=true;
for(int i=0;i<S.getStatCodes().length;i++)
{
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
{ zereoed=false; break;}
}
if(zereoed)
R.setStat(field,"");
else
R.setStat(field,CMLib.coffeeMaker().getCharStateStr(S));
}
else
mob.tell("(no change)");
}
}
else
{
mob.tell("(no change)");
done=true;
}
}
}
protected void genAStats(MOB mob, CharClass R, String Field, String FieldName, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
CharStats S=(CharStats)CMClass.getCommon("DefaultCharStats"); S.setAllValues(0);
CMLib.coffeeMaker().setCharStats(S,R.getStat(Field));
StringBuffer parts=new StringBuffer("");
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
if(S.getStat(i)!=0)
parts.append(CMStrings.capitalizeAndLower(CharStats.STAT_DESCS[i])+"("+S.getStat(i)+") ");
mob.tell(showNumber+". "+FieldName+": "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean done=false;
while((!done)&&(mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a stat name\n\r:","");
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
if(newName.equalsIgnoreCase(CharStats.STAT_DESCS[i]))
{ partNum=i; break;}
if(partNum<0)
{
StringBuffer str=new StringBuffer("That stat is invalid. Valid stats include: ");
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
str.append(CharStats.STAT_DESCS[i]+", ");
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
{
newName=mob.session().prompt("Enter a value\n\r:","");
if(newName.length()>0)
{
S.setStat(partNum,CMath.s_int(newName));
boolean zereoed=true;
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
{
if(S.getStat(i)!=0)
{ zereoed=false; break;}
}
if(zereoed)
R.setStat(Field,"");
else
R.setStat(Field,CMLib.coffeeMaker().getCharStatsStr(S));
}
else
mob.tell("(no change)");
}
}
else
{
mob.tell("(no change)");
done=true;
}
}
}
protected void genResources(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
StringBuffer parts=new StringBuffer("");
int numResources=CMath.s_int(E.getStat("NUMRSC"));
DVector DV=new DVector(2);
for(int r=0;r<numResources;r++)
{
Item I=CMClass.getItem(E.getStat("GETRSCID"+r));
if(I!=null)
{
I.setMiscText(E.getStat("GETRSCPARM"+r));
I.recoverEnvStats();
boolean done=false;
for(int v=0;v<DV.size();v++)
if(I.sameAs((Environmental)DV.elementAt(v,1)))
{ DV.setElementAt(v,2,new Integer(((Integer)DV.elementAt(v,2)).intValue()+1)); done=true; break;}
if(!done)
DV.addElement(I,new Integer(1));
}
else
parts.append("Unknown: "+E.getStat("GETRSCID"+r)+", ");
}
for(int v=0;v<DV.size();v++)
{
Item I=(Item)DV.elementAt(v,1);
int i=((Integer)DV.elementAt(v,2)).intValue();
if(i<2)
parts.append(I.name()+", ");
else
parts.append(I.name()+" ("+i+"), ");
}
if(parts.toString().endsWith(", "))
{parts.deleteCharAt(parts.length()-1);parts.deleteCharAt(parts.length()-1);}
mob.tell(showNumber+". Resources: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a resource name to remove or\n\rthe word new and an item name to add from your inventory\n\r:","");
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<DV.size();i++)
if(CMLib.english().containsString(((Item)DV.elementAt(i,1)).name(),newName))
{ partNum=i; break;}
boolean updateList=false;
if(partNum<0)
{
if(!newName.toLowerCase().startsWith("new "))
mob.tell("That is neither an existing resource name, or the word new followed by a valid item name.");
else
{
Item I=mob.fetchCarried(null,newName.substring(4).trim());
if(I!=null)
{
I=(Item)I.copyOf();
boolean done=false;
for(int v=0;v<DV.size();v++)
if(I.sameAs((Environmental)DV.elementAt(v,1)))
{ DV.setElementAt(v,2,new Integer(((Integer)DV.elementAt(v,2)).intValue()+1)); done=true; break;}
if(!done)
DV.addElement(I,new Integer(1));
mob.tell(I.name()+" added.");
updateList=true;
}
}
}
else
{
Item I=(Item)DV.elementAt(partNum,1);
int i=((Integer)DV.elementAt(partNum,2)).intValue();
if(i<2)
DV.removeElementAt(partNum);
else
DV.setElementAt(partNum,2,new Integer(i-1));
mob.tell(I.name()+" removed.");
updateList=true;
}
if(updateList)
{
int dex=0;
for(int i=0;i<DV.size();i++)
dex+=((Integer)DV.elementAt(i,2)).intValue();
E.setStat("NUMRSC",""+dex);
dex=0;
Item I=null;
Integer N=null;
for(int i=0;i<DV.size();i++)
{
I=(Item)DV.elementAt(i,1);
N=(Integer)DV.elementAt(i,2);
for(int n=0;n<N.intValue();n++)
E.setStat("GETRSCID"+(dex++),I.ID());
}
dex=0;
for(int i=0;i<DV.size();i++)
{
I=(Item)DV.elementAt(i,1);
N=(Integer)DV.elementAt(i,2);
for(int n=0;n<N.intValue();n++)
E.setStat("GETRSCPARM"+(dex++),I.text());
}
}
}
else
{
mob.tell("(no change)");
return;
}
}
}
protected void genOutfit(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
StringBuffer parts=new StringBuffer("");
int numResources=CMath.s_int(E.getStat("NUMOFT"));
Vector V=new Vector();
for(int v=0;v<numResources;v++)
{
Item I=CMClass.getItem(E.getStat("GETOFTID"+v));
if(I!=null)
{
I.setMiscText(E.getStat("GETOFTPARM"+v));
I.recoverEnvStats();
parts.append(I.name()+", ");
V.addElement(I);
}
}
if(parts.toString().endsWith(", "))
{parts.deleteCharAt(parts.length()-1);parts.deleteCharAt(parts.length()-1);}
mob.tell(showNumber+". Outfit: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter an item name to remove or\n\rthe word new and an item name to add from your inventory\n\r:","");
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<V.size();i++)
if(CMLib.english().containsString(((Item)V.elementAt(i)).name(),newName))
{ partNum=i; break;}
boolean updateList=false;
if(partNum<0)
{
if(!newName.toLowerCase().startsWith("new "))
mob.tell("That is neither an existing item name, or the word new followed by a valid item name.");
else
{
Item I=mob.fetchCarried(null,newName.substring(4).trim());
if(I!=null)
{
I=(Item)I.copyOf();
V.addElement(I);
mob.tell(I.name()+" added.");
updateList=true;
}
}
}
else
{
Item I=(Item)V.elementAt(partNum);
V.removeElementAt(partNum);
mob.tell(I.name()+" removed.");
updateList=true;
}
if(updateList)
{
E.setStat("NUMOFT","");
for(int i=0;i<V.size();i++)
E.setStat("GETOFTID"+i,((Item)V.elementAt(i)).ID());
for(int i=0;i<V.size();i++)
E.setStat("GETOFTPARM"+i,((Item)V.elementAt(i)).text());
}
}
else
{
mob.tell("(no change)");
return;
}
}
}
protected void genOutfit(MOB mob, CharClass E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
StringBuffer parts=new StringBuffer("");
int numResources=CMath.s_int(E.getStat("NUMOFT"));
Vector V=new Vector();
for(int v=0;v<numResources;v++)
{
Item I=CMClass.getItem(E.getStat("GETOFTID"+v));
if(I!=null)
{
I.setMiscText(E.getStat("GETOFTPARM"+v));
I.recoverEnvStats();
parts.append(I.name()+", ");
V.addElement(I);
}
}
if(parts.toString().endsWith(", "))
{parts.deleteCharAt(parts.length()-1);parts.deleteCharAt(parts.length()-1);}
mob.tell(showNumber+". Outfit: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter an item name to remove or\n\rthe word new and an item name to add from your inventory\n\r:","");
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<V.size();i++)
if(CMLib.english().containsString(((Item)V.elementAt(i)).name(),newName))
{ partNum=i; break;}
boolean updateList=false;
if(partNum<0)
{
if(!newName.toLowerCase().startsWith("new "))
mob.tell("That is neither an existing item name, or the word new followed by a valid item name.");
else
{
Item I=mob.fetchCarried(null,newName.substring(4).trim());
if(I!=null)
{
I=(Item)I.copyOf();
V.addElement(I);
mob.tell(I.name()+" added.");
updateList=true;
}
}
}
else
{
Item I=(Item)V.elementAt(partNum);
V.removeElementAt(partNum);
mob.tell(I.name()+" removed.");
updateList=true;
}
if(updateList)
{
E.setStat("NUMOFT","");
for(int i=0;i<V.size();i++)
E.setStat("GETOFTID"+i,((Item)V.elementAt(i)).ID());
for(int i=0;i<V.size();i++)
E.setStat("GETOFTPARM"+i,((Item)V.elementAt(i)).text());
}
}
else
{
mob.tell("(no change)");
return;
}
}
}
protected void genWeapon(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
StringBuffer parts=new StringBuffer("");
Item I=CMClass.getItem(E.getStat("WEAPONCLASS"));
if(I!=null)
{
I.setMiscText(E.getStat("WEAPONXML"));
I.recoverEnvStats();
parts.append(I.name());
}
mob.tell(showNumber+". Natural Weapon: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a weapon name from your inventory to change, or 'null' for human\n\r:","");
if(newName.equalsIgnoreCase("null"))
{
E.setStat("WEAPONCLASS","");
mob.tell("Human weapons set.");
}
else
if(newName.length()>0)
{
I=mob.fetchCarried(null,newName);
if(I==null)
{
mob.tell("'"+newName+"' is not in your inventory.");
mob.tell("(no change)");
return;
}
I=(Item)I.copyOf();
E.setStat("WEAPONCLASS",I.ID());
E.setStat("WEAPONXML",I.text());
}
else
{
mob.tell("(no change)");
return;
}
}
protected void modifyDField(DVector fields, String fieldName, String value)
{
int x=fields.indexOf(fieldName.toUpperCase());
if(x<0) return;
fields.setElementAt(x,2,value);
}
protected void genAgingChart(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Aging Chart: "+CMParms.toStringList(E.getAgingChart())+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
String newName=mob.session().prompt("Enter a comma-delimited list of 9 numbers, running from infant -> ancient\n\r:","");
if(newName.length()==0)
{
mob.tell("(no change)");
return;
}
Vector V=CMParms.parseCommas(newName,true);
if(V.size()==9)
{
int highest=-1;
boolean cont=false;
for(int i=0;i<V.size();i++)
{
if(CMath.s_int((String)V.elementAt(i))<highest)
{
mob.tell("Entry "+((String)V.elementAt(i))+" is out of place.");
cont=true;
break;
}
highest=CMath.s_int((String)V.elementAt(i));
}
if(cont) continue;
E.setStat("AGING",newName);
break;
}
}
}
protected void genClassFlags(MOB mob, CharClass E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber))
return;
int flags=CMath.s_int(E.getStat("DISFLAGS"));
StringBuffer sets=new StringBuffer("");
if(CMath.bset(flags,CharClass.GENFLAG_NORACE))
sets.append("Raceless ");
if(CMath.bset(flags,CharClass.GENFLAG_NOLEVELS))
sets.append("Leveless ");
if(CMath.bset(flags,CharClass.GENFLAG_NOEXP))
sets.append("Expless ");
mob.tell(showNumber+". Extra CharClass Flags: "+sets.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999))
return;
String newName=mob.session().prompt("Enter: 1) Classless, 2) Leveless, 3) Expless\n\r:","");
switch(CMath.s_int(newName))
{
case 1:
if(CMath.bset(flags,CharClass.GENFLAG_NORACE))
flags=CMath.unsetb(flags,CharClass.GENFLAG_NORACE);
else
flags=flags|CharClass.GENFLAG_NORACE;
break;
case 2:
if(CMath.bset(flags,CharClass.GENFLAG_NOLEVELS))
flags=CMath.unsetb(flags,CharClass.GENFLAG_NOLEVELS);
else
flags=flags|CharClass.GENFLAG_NOLEVELS;
break;
case 3:
if(CMath.bset(flags,CharClass.GENFLAG_NOEXP))
flags=CMath.unsetb(flags,CharClass.GENFLAG_NOEXP);
else
flags=flags|CharClass.GENFLAG_NOEXP;
break;
default:
mob.tell("(no change)");
break;
}
E.setStat("DISFLAGS",""+flags);
}
protected void genRacialAbilities(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
StringBuffer parts=new StringBuffer("");
int numResources=CMath.s_int(E.getStat("NUMRABLE"));
Vector ables=new Vector();
Vector data=new Vector();
for(int v=0;v<numResources;v++)
{
Ability A=CMClass.getAbility(E.getStat("GETRABLE"+v));
if(A!=null)
{
parts.append("("+A.ID()+"/"+E.getStat("GETRABLELVL"+v)+"/"+E.getStat("GETRABLEQUAL"+v)+"/"+E.getStat("GETRABLEPROF"+v)+"), ");
ables.addElement(A);
data.addElement(A.ID()+";"+E.getStat("GETRABLELVL"+v)+";"+E.getStat("GETRABLEQUAL"+v)+";"+E.getStat("GETRABLEPROF"+v));
}
}
if(parts.toString().endsWith(", "))
{parts.deleteCharAt(parts.length()-1);parts.deleteCharAt(parts.length()-1);}
mob.tell(showNumber+". Racial Abilities: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter an ability name to add or remove (?)\n\r:","");
if(newName.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<ables.size();i++)
if(CMLib.english().containsString(((Ability)ables.elementAt(i)).ID(),newName))
{ partNum=i; break;}
boolean updateList=false;
if(partNum<0)
{
Ability A=CMClass.getAbility(newName);
if(A==null)
mob.tell("That is neither an existing ability name, nor a valid one to add. Use ? for a list.");
else
if(A.isAutoInvoked())
mob.tell("'"+A.name()+"' cannot be named, as it is autoinvoked.");
else
if((A.triggerStrings()==null)||(A.triggerStrings().length==0))
mob.tell("'"+A.name()+"' cannot be named, as it has no trigger/command words.");
else
{
StringBuffer str=new StringBuffer(A.ID()+";");
String level=mob.session().prompt("Enter the level of this skill (1): ","1");
str.append((""+CMath.s_int(level))+";");
if(mob.session().confirm("Is this skill automatically gained (Y/n)?","Y"))
str.append("false;");
else
str.append("true;");
String prof=mob.session().prompt("Enter the (perm) proficiency level (100): ","100");
str.append((""+CMath.s_int(prof)));
data.addElement(str.toString());
ables.addElement(A);
mob.tell(A.name()+" added.");
updateList=true;
}
}
else
{
Ability A=(Ability)ables.elementAt(partNum);
ables.removeElementAt(partNum);
data.removeElementAt(partNum);
updateList=true;
mob.tell(A.name()+" removed.");
}
if(updateList)
{
if(data.size()>0)
E.setStat("NUMRABLE",""+data.size());
else
E.setStat("NUMRABLE","");
for(int i=0;i<data.size();i++)
{
Vector V=CMParms.parseSemicolons((String)data.elementAt(i),false);
E.setStat("GETRABLE"+i,((String)V.elementAt(0)));
E.setStat("GETRABLELVL"+i,((String)V.elementAt(1)));
E.setStat("GETRABLEQUAL"+i,((String)V.elementAt(2)));
E.setStat("GETRABLEPROF"+i,((String)V.elementAt(3)));
}
}
}
else
{
mob.tell("(no change)");
return;
}
}
}
protected void genRacialEffects(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
StringBuffer parts=new StringBuffer("");
int numResources=CMath.s_int(E.getStat("NUMREFF"));
Vector ables=new Vector();
Vector data=new Vector();
for(int v=0;v<numResources;v++)
{
Ability A=CMClass.getAbility(E.getStat("GETREFF"+v));
if(A!=null)
{
parts.append("("+A.ID()+"/"+E.getStat("GETREFFLVL"+v)+"/"+E.getStat("GETREFFPARM"+v)+"), ");
ables.addElement(A);
data.addElement(A.ID()+"~"+E.getStat("GETREFFLVL"+v)+"~"+E.getStat("GETREFFPARM"+v));
}
}
if(parts.toString().endsWith(", "))
{parts.deleteCharAt(parts.length()-1);parts.deleteCharAt(parts.length()-1);}
mob.tell(showNumber+". Racial Effects: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter an effect name to add or remove\n\r:","");
if(newName.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<ables.size();i++)
if(CMLib.english().containsString(((Ability)ables.elementAt(i)).ID(),newName))
{ partNum=i; break;}
boolean updateList=false;
if(partNum<0)
{
Ability A=CMClass.getAbility(newName);
if(A==null)
mob.tell("That is neither an existing effect name, nor a valid one to add. Use ? for a list.");
else
{
StringBuffer str=new StringBuffer(A.ID()+"~");
String level=mob.session().prompt("Enter the level to gain this effect (1): ","1");
str.append((""+CMath.s_int(level))+"~");
String prof=mob.session().prompt("Enter any parameters: ","");
str.append(""+prof);
data.addElement(str.toString());
ables.addElement(A);
mob.tell(A.name()+" added.");
updateList=true;
}
}
else
{
Ability A=(Ability)ables.elementAt(partNum);
ables.removeElementAt(partNum);
data.removeElementAt(partNum);
updateList=true;
mob.tell(A.name()+" removed.");
}
if(updateList)
{
if(data.size()>0)
E.setStat("NUMREFF",""+data.size());
else
E.setStat("NUMREFF","");
for(int i=0;i<data.size();i++)
{
Vector V=CMParms.parseSquiggleDelimited((String)data.elementAt(i),false);
E.setStat("GETREFF"+i,((String)V.elementAt(0)));
E.setStat("GETREFFLVL"+i,((String)V.elementAt(1)));
E.setStat("GETREFFPARM"+i,((String)V.elementAt(2)));
}
}
}
else
{
mob.tell("(no change)");
return;
}
}
}
protected DVector genClassAbleMod(MOB mob, DVector sets, String ableID, int origLevelIndex, int origAbleIndex)
throws IOException
{
Integer level=null;
if(origLevelIndex>=0)
{
if(mob.session().confirm("Enter Y to DELETE, or N to modify (y/N)?","N"))
{
DVector set=(DVector)sets.elementAt(origLevelIndex,2);
set.removeElementAt(origAbleIndex);
return null;
}
level=(Integer)sets.elementAt(origLevelIndex,1);
}
else
level=new Integer(1);
level=new Integer(CMath.s_int(mob.session().prompt("Enter the level of this skill ("+level+"): ",""+level)));
if(level.intValue()<=0)
{
mob.tell("Aborted.");
return null;
}
Integer prof=null;
Boolean secret=null;
Boolean gained=null;
String parms="";
if(origLevelIndex<0)
{
prof=new Integer(0);
secret=new Boolean(false);
gained=new Boolean(false);
parms="";
}
else
{
DVector set=(DVector)sets.elementAt(origLevelIndex,2);
gained=(Boolean)set.elementAt(origAbleIndex,2);
prof=(Integer)set.elementAt(origAbleIndex,3);
secret=(Boolean)set.elementAt(origAbleIndex,4);
parms=(String)set.elementAt(origAbleIndex,5);
set.removeElementAt(origAbleIndex);
origAbleIndex=-1;
}
int newlevelIndex=sets.indexOf(level);
DVector levelSet=null;
if(newlevelIndex<0)
{
newlevelIndex=sets.size();
levelSet=new DVector(5);
sets.addElement(level,levelSet);
}
else
levelSet=(DVector)sets.elementAt(newlevelIndex,2);
prof=new Integer(CMath.s_int(mob.session().prompt("Enter the (default) proficiency level ("+prof.toString()+"): ",prof.toString())));
gained=new Boolean(mob.session().confirm("Is this skill automatically gained (Y/N)?",""+gained.toString()));
secret=new Boolean(mob.session().confirm("Is this skill secret (N/y)?",secret.toString()));
parms=mob.session().prompt("Enter any properties ("+parms+"): ",parms);
levelSet.addElement(ableID,gained,prof,secret,parms);
return sets;
}
protected void genClassAbilities(MOB mob, CharClass E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if((showFlag!=showNumber)&&(showFlag>-999))
{
mob.tell(showNumber+". Class Abilities: [...].");
return;
}
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
StringBuffer parts=new StringBuffer("");
int numAbles=CMath.s_int(E.getStat("NUMCABLE"));
DVector levelSets=new DVector(2);
int maxAbledLevel=Integer.MIN_VALUE;
for(int v=0;v<numAbles;v++)
{
Ability A=CMClass.getAbility(E.getStat("GETCABLE"+v));
if(A!=null)
{
Boolean gain=new Boolean(CMath.s_bool(E.getStat("GETCABLEGAIN"+v)));
Integer defProf=new Integer(CMath.s_int(E.getStat("GETCABLEPROF"+v)));
Integer lvl=new Integer(CMath.s_int(E.getStat("GETCABLELVL"+v)));
Boolean secret=new Boolean(CMath.s_bool(E.getStat("GETCABLESECR"+v)));
String parm=E.getStat("GETCABLEPARM"+v);
int lvlIndex=levelSets.indexOf(lvl);
DVector set=null;
if(lvlIndex<0)
{
set=new DVector(5);
levelSets.addElement(lvl,set);
if(lvl.intValue()>maxAbledLevel)
maxAbledLevel=lvl.intValue();
}
else
set=(DVector)levelSets.elementAt(lvlIndex,2);
set.addElement(A.ID(),gain,defProf,secret,parm);
}
}
String header=showNumber+". Class Abilities: ";
String spaces=CMStrings.repeat(" ",2+(""+showNumber).length());
parts.append("\n\r");
parts.append(spaces+CMStrings.padRight("Lvl",3)+" "
+CMStrings.padRight("Skill",25)+" "
+CMStrings.padRight("Proff",5)+" "
+CMStrings.padRight("Gain",5)+" "
+CMStrings.padRight("Secret",6)+" "
+CMStrings.padRight("Parm",20)+"\n\r"
);
for(int i=0;i<=maxAbledLevel;i++)
{
int index=levelSets.indexOf(new Integer(i));
if(index<0) continue;
DVector set=(DVector)levelSets.elementAt(index,2);
for(int s=0;s<set.size();s++)
{
String ID=(String)set.elementAt(s,1);
Boolean gain=(Boolean)set.elementAt(s,2);
Integer defProf=(Integer)set.elementAt(s,3);
Boolean secret=(Boolean)set.elementAt(s,4);
String parm=(String)set.elementAt(s,5);
parts.append(spaces+CMStrings.padRight(""+i,3)+" "
+CMStrings.padRight(""+ID,25)+" "
+CMStrings.padRight(defProf.toString(),5)+" "
+CMStrings.padRight(gain.toString(),5)+" "
+CMStrings.padRight(secret.toString(),6)+" "
+CMStrings.padRight(parm,20)+"\n\r"
);
}
}
mob.session().wraplessPrintln(header+parts.toString());
String newName=mob.session().prompt("Enter an ability name to add or remove (?)\n\r:","");
if(newName.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
if(newName.length()>0)
{
int lvlIndex=-1;
int ableIndex=-1;
DVector myLevelSet=null;
for(int s=0;s<levelSets.size();s++)
{
DVector lvls=(DVector)levelSets.elementAt(s,2);
for(int l=0;l<lvls.size();l++)
if(CMLib.english().containsString(((String)lvls.elementAt(l,1)),newName))
{
lvlIndex=s;
ableIndex=l;
myLevelSet=lvls;
break;
}
if(lvlIndex>=0) break;
}
boolean updateList=false;
if(ableIndex<0)
{
Ability A=CMClass.getAbility(newName);
if(A==null)
mob.tell("That is neither an existing ability name, nor a valid one to add. Use ? for a list.");
else
{
// add new one here
if(genClassAbleMod(mob,levelSets,A.ID(),-1,-1)!=null)
{
mob.tell(A.ID()+" added.");
updateList=true;
numAbles++;
}
}
}
else
{
String aID=(String)myLevelSet.elementAt(ableIndex,1);
if(genClassAbleMod(mob,levelSets,aID,lvlIndex,ableIndex)!=null)
mob.tell(aID+" modified.");
else
{
mob.tell(aID+" removed.");
numAbles--;
}
updateList=true;
}
if(updateList)
{
if(numAbles>0)
E.setStat("NUMCABLE",""+numAbles);
else
E.setStat("NUMCABLE","");
int dex=0;
for(int s=0;s<levelSets.size();s++)
{
Integer lvl=(Integer)levelSets.elementAt(s,1);
DVector lvls=(DVector)levelSets.elementAt(s,2);
for(int l=0;l<lvls.size();l++)
{
E.setStat("GETCABLE"+dex,lvls.elementAt(l,1).toString());
E.setStat("GETCABLELVL"+dex,lvl.toString());
E.setStat("GETCABLEGAIN"+dex,lvls.elementAt(l,2).toString());
E.setStat("GETCABLEPROF"+dex,lvls.elementAt(l,3).toString());
E.setStat("GETCABLESECR"+dex,lvls.elementAt(l,4).toString());
E.setStat("GETCABLEPARM"+dex,lvls.elementAt(l,5).toString());
dex++;
}
}
}
}
else
{
mob.tell("(no change)");
return;
}
}
}
protected void genCulturalAbilities(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
StringBuffer parts=new StringBuffer("");
int numResources=CMath.s_int(E.getStat("NUMCABLE"));
Vector ables=new Vector();
Vector data=new Vector();
for(int v=0;v<numResources;v++)
{
Ability A=CMClass.getAbility(E.getStat("GETCABLE"+v));
if(A!=null)
{
parts.append("("+A.ID()+"/"+E.getStat("GETCABLEPROF"+v)+"), ");
ables.addElement(A);
data.addElement(A.ID()+";"+E.getStat("GETCABLEPROF"+v));
}
}
if(parts.toString().endsWith(", "))
{parts.deleteCharAt(parts.length()-1);parts.deleteCharAt(parts.length()-1);}
mob.tell(showNumber+". Cultural Abilities: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter an ability name to add or remove (?)\n\r:","");
if(newName.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<ables.size();i++)
if(CMLib.english().containsString(((Ability)ables.elementAt(i)).ID(),newName))
{ partNum=i; break;}
boolean updateList=false;
if(partNum<0)
{
Ability A=CMClass.getAbility(newName);
if(A==null)
mob.tell("That is neither an existing ability name, nor a valid one to add. Use ? for a list.");
else
{
StringBuffer str=new StringBuffer(A.ID()+";");
String prof=mob.session().prompt("Enter the default proficiency level (100): ","100");
str.append((""+CMath.s_int(prof)));
data.addElement(str.toString());
ables.addElement(A);
mob.tell(A.name()+" added.");
updateList=true;
}
}
else
{
Ability A=(Ability)ables.elementAt(partNum);
ables.removeElementAt(partNum);
data.removeElementAt(partNum);
updateList=true;
mob.tell(A.name()+" removed.");
}
if(updateList)
{
if(data.size()>0)
E.setStat("NUMCABLE",""+data.size());
else
E.setStat("NUMCABLE","");
for(int i=0;i<data.size();i++)
{
Vector V=CMParms.parseSemicolons((String)data.elementAt(i),false);
E.setStat("GETCABLE"+i,((String)V.elementAt(0)));
E.setStat("GETCABLEPROF"+i,((String)V.elementAt(1)));
}
}
}
else
{
mob.tell("(no change)");
return;
}
}
}
protected void modifyGenClass(MOB mob, CharClass me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Number of Class Names: ","NUMNAME");
int numNames=CMath.s_int(me.getStat("NUMNAME"));
if(numNames<=1)
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Class Name","NAME0");
else
for(int i=0;i<numNames;i++)
{
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Class Name #"+i+": ","NAME"+i);
if(i>0)
while(!mob.session().killFlag())
{
int oldNameLevel=CMath.s_int(me.getStat("NAMELEVEL"+i));
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Class Name #"+i+" class level: ","NAMELEVEL"+i);
int previousNameLevel=CMath.s_int(me.getStat("NAMELEVEL"+(i-1)));
int newNameLevel=CMath.s_int(me.getStat("NAMELEVEL"+i));
if((oldNameLevel!=newNameLevel)&&(newNameLevel<(previousNameLevel+1)))
{
mob.tell("This level may not be less than "+(previousNameLevel+1)+".");
me.setStat("NAMELEVEL"+i,""+(previousNameLevel+1));
showNumber--;
}
else
break;
}
}
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Base Class","BASE");
genClassAvailability(mob,me,++showNumber,showFlag);
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"HP Con Divisor","HPDIV");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"HP Die","HPDICE");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"HP #Dice","HPDIE");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Mana Divisor","MANADIV");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Mana #Dice","MANADICE");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Mana Die","MANADIE");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Prac/Level","LVLPRAC");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Attack/Level","LVLATT");
genAttackAttribute(mob,me,++showNumber,showFlag,"Attack Attribute","ATTATT");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Practices/1stLvl","FSTPRAC");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Trains/1stLvl","FSTTRAN");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Levels/Dmg Pt","LVLDAM");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Moves/Level","LVLMOVE");
genArmorCode(mob,me,++showNumber,showFlag,"Armor Restr.","ARMOR");
int armorMinorCode=CMath.s_int(me.getStat("ARMORMINOR"));
boolean newSpells=CMLib.english().prompt(mob,armorMinorCode>0,++showNumber,showFlag,"Armor restricts only spells");
me.setStat("ARMORMINOR",""+(newSpells?CMMsg.TYP_CAST_SPELL:-1));
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Limitations","STRLMT");
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Bonuses","STRBON");
genQualifications(mob,me,++showNumber,showFlag,"Qualifications","QUAL");
genEStats(mob,me,++showNumber,showFlag);
genAStats(mob,me,"ASTATS","CharStat Adjustments",++showNumber,showFlag);
genAStats(mob,me,"CSTATS","CharStat Settings",++showNumber,showFlag);
genAState(mob,me,"ASTATE","CharState Adjustments",++showNumber,showFlag);
genAState(mob,me,"STARTASTATE","New Player CharState Adj.",++showNumber,showFlag);
genClassFlags(mob,me,++showNumber,showFlag);
genWeaponRestr(mob,me,++showNumber,showFlag,"Weapon Restr.","NUMWEP","GETWEP");
genWeaponMaterials(mob,me,++showNumber,showFlag,"Weapon Materials","NUMWMAT","GETWMAT");
genOutfit(mob,me,++showNumber,showFlag);
genClassBuddy(mob,me,++showNumber,showFlag,"Stat-Modifying Class","STATCLASS");
genClassBuddy(mob,me,++showNumber,showFlag,"Special Events Class","EVENTCLASS");
genClassAbilities(mob,me,++showNumber,showFlag);
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Number of Security Code Sets: ","NUMSSET");
int numGroups=CMath.s_int(me.getStat("NUMSSET"));
for(int i=0;i<numGroups;i++)
{
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Security Codes in Set #"+i,"SSET"+i);
while(!mob.session().killFlag())
{
int oldGroupLevel=CMath.s_int(me.getStat("SSETLEVEL"+i));
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Class Level for Security Set #"+i+": ","SSETLEVEL"+i);
int previousGroupLevel=CMath.s_int(me.getStat("SSETLEVEL"+(i-1)));
int newGroupLevel=CMath.s_int(me.getStat("SSETLEVEL"+i));
if((oldGroupLevel!=newGroupLevel)
&&(i>0)
&&(newGroupLevel<(previousGroupLevel+1)))
{
mob.tell("This level may not be less than "+(previousGroupLevel+1)+".");
me.setStat("SSETLEVEL"+i,""+(previousGroupLevel+1));
showNumber--;
}
else
break;
}
}
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
}
}
}
protected void modifyGenAbility(MOB mob, Ability me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
// id is bad to change.. make them delete it.
//genText(mob,me,null,++showNumber,showFlag,"Enter the class","CLASS");
CMLib.english().promptStatStr(mob,me,null,++showNumber,showFlag,"Enter an ability name to add or remove","NAME",false);
CMLib.english().promptStatStr(mob,me,CMParms.toStringList(Ability.ACODE_DESCS)+","+CMParms.toStringList(Ability.DOMAIN_DESCS),++showNumber,showFlag,"Type, Domain","CLASSIFICATION",false);
CMLib.english().promptStatStr(mob,me,null,++showNumber,showFlag,"Command Words (comma sep)","TRIGSTR",false);
CMLib.english().promptStatStr(mob,me,CMParms.toStringList(Ability.RANGE_CHOICES),++showNumber,showFlag,"Minimum Range","MINRANGE",false);
CMLib.english().promptStatStr(mob,me,CMParms.toStringList(Ability.RANGE_CHOICES),++showNumber,showFlag,"Maximum Range","MAXRANGE",false);
CMLib.english().promptStatStr(mob,me,null,++showNumber,showFlag,"Affect String","DISPLAY",true);
CMLib.english().promptStatBool(mob,me,++showNumber,showFlag,"Is Auto-invoking","AUTOINVOKE");
CMLib.english().promptStatStr(mob,me,"0,"+CMParms.toStringList(Ability.FLAG_DESCS),++showNumber,showFlag,"Skill Flags (comma sep)","FLAGS",true);
CMLib.english().promptStatInt(mob,me,"-1,x,"+Integer.MAX_VALUE+","+Integer.MAX_VALUE+"-(1 to 100)",++showNumber,showFlag,"Override Cost","OVERRIDEMANA");
CMLib.english().promptStatStr(mob,me,CMParms.toStringList(Ability.USAGE_DESCS),++showNumber,showFlag,"Cost Type","USAGEMASK",false);
CMLib.english().promptStatStr(mob,me,"0,"+CMParms.toStringList(Ability.CAN_DESCS),++showNumber,showFlag,"Can Affect","CANAFFECTMASK",true);
CMLib.english().promptStatStr(mob,me,"0,"+CMParms.toStringList(Ability.CAN_DESCS),++showNumber,showFlag,"Can Target","CANTARGETMASK",true);
CMLib.english().promptStatStr(mob,me,CMParms.toStringList(Ability.QUALITY_DESCS),++showNumber,showFlag,"Quality Code","QUALITY",true);
CMLib.english().promptStatStr(mob,me,"The parameters for this field are LIKE the parameters for this property:\n\r\n\r"+
CMLib.help().getHelpText("Prop_HereAdjuster",mob,true).toString(),++showNumber,showFlag,"Affect Adjustments","HERESTATS",true);
CMLib.english().promptStatStr(mob,me,CMLib.masking().maskHelp("\n","disallow"),++showNumber,showFlag,"Caster Mask","CASTMASK",true);
CMLib.english().promptStatStr(mob,me,CMLib.help().getHelpText("Scriptable",mob,true).toString(),++showNumber,showFlag,"Scriptable Parm","SCRIPT",true);
CMLib.english().promptStatStr(mob,me,CMLib.masking().maskHelp("\n","disallow"),++showNumber,showFlag,"Target Mask","TARGETMASK",true);
CMLib.english().promptStatStr(mob,me,null,++showNumber,showFlag,"Fizzle Message","FIZZLEMSG",true);
CMLib.english().promptStatStr(mob,me,null,++showNumber,showFlag,"Auto-Cast Message","AUTOCASTMSG",true);
CMLib.english().promptStatStr(mob,me,null,++showNumber,showFlag,"Normal-Cast Message","CASTMSG",true);
CMLib.english().promptStatStr(mob,me,null,++showNumber,showFlag,"Post-Cast Message","POSTCASTMSG",true);
CMLib.english().promptStatStr(mob,me,CMParms.toStringList(CMMsg.TYPE_DESCS),++showNumber,showFlag,"Attack-Type","ATTACKCODE",true);
CMLib.english().promptStatStr(mob,me,"The parameters for this field are LIKE the parameters for this property:\n\r\n\r"+
CMLib.help().getHelpText("Prop_HereSpellCast",mob,true).toString(),++showNumber,showFlag,"Silent affects","POSTCASTAFFECT",true);
CMLib.english().promptStatStr(mob,me,"The parameters for this field are LIKE the parameters for this property:\n\r\n\r"+
CMLib.help().getHelpText("Prop_HereSpellCast",mob,true).toString(),++showNumber,showFlag,"Extra castings","POSTCASTABILITY",true);
CMLib.english().promptStatStr(mob,me,"Enter a damage or healing formula. Use +-*/()?. @x1=caster level, @x2=target level. Formula evaluates >0 for damage, <0 for healing. Requires Can Target!",++showNumber,showFlag,"Damage/Healing Formula","POSTCASTDAMAGE",true);
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
}
}
}
boolean genText(MOB mob, DVector set, String[] choices, String help, int showNumber, int showFlag, String FieldDisp, String Field)
throws IOException
{
int setDex=set.indexOf(Field);
if(((showFlag>0)&&(showFlag!=showNumber))||(setDex<0)) return true;
mob.tell(showNumber+". "+FieldDisp+": '"+((String)set.elementAt(setDex,2)+"'."));
if((showFlag!=showNumber)&&(showFlag>-999)) return true;
String newName=mob.session().prompt("Enter a new one\n\r:","");
if(newName.trim().length()==0)
{
mob.tell("(no change)");
return false;
}
if((newName.equalsIgnoreCase("?"))&&(help!=null))
{
if((mob.session()==null)||(mob.session().killFlag()))
return false;
mob.tell(help);
return genText(mob,set,choices,help,showNumber,showFlag,FieldDisp,Field);
}
if(newName.equalsIgnoreCase("null")) newName="";
if((choices==null)||(choices.length==0))
{
set.setElementAt(setDex,2,newName);
return true;
}
boolean found=false;
for(int s=0;s<choices.length;s++)
{
if(newName.equalsIgnoreCase(choices[s]))
{ newName=choices[s]; found=true; break;}
}
if(!found)
{
if((mob.session()==null)||(mob.session().killFlag()))
return false;
mob.tell(help);
return genText(mob,set,choices,help,showNumber,showFlag,FieldDisp,Field);
}
set.setElementAt(setDex,2,newName);
return true;
}
protected boolean modifyComponent(MOB mob, DVector components, int componentIndex)
throws IOException
{
DVector decoded=CMLib.ableMapper().getAbilityComponentDecodedDVector(components,componentIndex);
if(mob.isMonster()) return true;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
String choices="Your choices are: ";
String allComponents=CMParms.toStringList(RawMaterial.MATERIAL_DESCS)+","+CMParms.toStringList(RawMaterial.RESOURCE_DESCS);
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genText(mob,decoded,(new String[]{"&&","||","X"}),choices+" &&, ||, X",++showNumber,showFlag,"Conjunction (X Deletes) (?)","ANDOR");
if(((String)decoded.elementAt(0,2)).equalsIgnoreCase("X")) return false;
genText(mob,decoded,(new String[]{"INVENTORY","HELD","WORN"}),choices+" INVENTORY, HELD, WORN",++showNumber,showFlag,"Component position (?)","DISPOSITION");
genText(mob,decoded,(new String[]{"KEPT","CONSUMED"}),choices+" KEPT, CONSUMED",++showNumber,showFlag,"Component fate (?)","FATE");
genText(mob,decoded,null,null,++showNumber,showFlag,"Amount of component","AMOUNT");
genText(mob,decoded,null,allComponents,++showNumber,showFlag,"Type of component (?)","COMPONENTID");
genText(mob,decoded,null,CMLib.masking().maskHelp("\n","disallow"),++showNumber,showFlag,"Component applies-to mask (?)","MASK");
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
}
}
CMLib.ableMapper().setAbilityComponentCodedFromDecodedDVector(decoded,components,componentIndex);
return true;
}
protected void modifyComponents(MOB mob, String componentID)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
DVector codedDV=CMLib.ableMapper().getAbilityComponentDVector(componentID);
if(codedDV!=null)
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
for(int v=0;v<codedDV.size();v++)
if((mob.session()!=null)&&(!mob.session().killFlag()))
{
showNumber++;
if((showFlag>0)&&(showFlag!=showNumber)) continue;
mob.tell(showNumber+": '"+CMLib.ableMapper().getAbilityComponentDesc(null,codedDV,v)+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) continue;
if(!modifyComponent(mob,codedDV,v))
{
codedDV.removeElementAt(v);
v--;
}
}
while((mob.session()!=null)&&(!mob.session().killFlag()))
{
showNumber++;
mob.tell(showNumber+". Add new component requirement.");
if((showFlag==showNumber)||(showFlag<=-999))
{
CMLib.ableMapper().addBlankAbilityComponent(codedDV);
boolean success=modifyComponent(mob,codedDV,codedDV.size()-1);
if(!success)
codedDV.removeElementAt(codedDV.size()-1);
else
if(showFlag<=-999)
continue;
}
break;
}
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
}
}
}
protected void modifyGenRace(MOB mob, Race me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Name","NAME");
genCat(mob,me,++showNumber,showFlag);
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Base Weight","BWEIGHT");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Weight Variance","VWEIGHT");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Base Male Height","MHEIGHT");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Base Female Height","FHEIGHT");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Height Variance","VHEIGHT");
genRaceAvailability(mob,me,++showNumber,showFlag);
genDisableFlags(mob,me,++showNumber,showFlag);
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Leaving text","LEAVE");
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Arriving text","ARRIVE");
genRaceBuddy(mob,me,++showNumber,showFlag,"Health Race","HEALTHRACE");
genRaceBuddy(mob,me,++showNumber,showFlag,"Event Race","EVENTRACE");
genBodyParts(mob,me,++showNumber,showFlag);
genRaceWearFlags(mob,me,++showNumber,showFlag);
genAgingChart(mob,me,++showNumber,showFlag);
CMLib.english().promptStatBool(mob,me,++showNumber,showFlag,"Never create corpse","BODYKILL");
genEStats(mob,me,++showNumber,showFlag);
genAStats(mob,me,"ASTATS","CharStat Adjustments",++showNumber,showFlag);
genAStats(mob,me,"CSTATS","CharStat Settings",++showNumber,showFlag);
genAState(mob,me,"ASTATE","CharState Adjustments",++showNumber,showFlag);
genAState(mob,me,"STARTASTATE","New Player CharState Adj.",++showNumber,showFlag);
genResources(mob,me,++showNumber,showFlag);
genOutfit(mob,me,++showNumber,showFlag);
genWeapon(mob,me,++showNumber,showFlag);
genRaceBuddy(mob,me,++showNumber,showFlag,"Weapons Race","WEAPONRACE");
genRacialAbilities(mob,me,++showNumber,showFlag);
genCulturalAbilities(mob,me,++showNumber,showFlag);
//genRacialEffects(mob,me,++showNumber,showFlag);
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
}
}
}
protected void modifyGenItem(MOB mob, Item me)
throws IOException
{
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
if(mob.isMonster()) return;
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,me,++showNumber,showFlag);
genMaterialCode(mob,me,++showNumber,showFlag);
if(me instanceof ClanItem)
genClanItem(mob,(ClanItem)me,++showNumber,showFlag);
if(me instanceof ShipComponent)
{
if(me instanceof ShipComponent.ShipPanel)
genPanelType(mob,(ShipComponent.ShipPanel)me,++showNumber,showFlag);
}
if(me instanceof PackagedItems)
((PackagedItems)me).setNumberOfItemsInPackage(CMLib.english().prompt(mob,((PackagedItems)me).numberOfItemsInPackage(),++showNumber,showFlag,"Number of items in the package"));
genGettable(mob,me,++showNumber,showFlag);
genReadable1(mob,me,++showNumber,showFlag);
genReadable2(mob,me,++showNumber,showFlag);
if(me instanceof Recipe) genRecipe(mob,(Recipe)me,++showNumber,showFlag);
if(me instanceof Light) genBurnout(mob,(Light)me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
if(me instanceof Coins)
genCoinStuff(mob,(Coins)me,++showNumber,showFlag);
else
genAbility(mob,me,++showNumber,showFlag);
genUses(mob,me,++showNumber,showFlag);
if(me instanceof Wand)
genMaxUses(mob,(Wand)me,++showNumber,showFlag);
genValue(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
if(me instanceof LandTitle)
genTitleRoom(mob,(LandTitle)me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
catalogCheckUpdate(mob, me);
}
protected void modifyGenFood(MOB mob, Food me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genValue(mob,me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genMaterialCode(mob,me,++showNumber,showFlag);
genNourishment(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genGettable(mob,me,++showNumber,showFlag);
genReadable1(mob,me,++showNumber,showFlag);
genReadable2(mob,me,++showNumber,showFlag);
if(me instanceof Light) genBurnout(mob,(Light)me,++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
catalogCheckUpdate(mob, me);
}
protected void modifyGenDrink(MOB mob, Drink me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,(Item)me,++showNumber,showFlag);
genValue(mob,(Item)me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
genThirstQuenched(mob,me,++showNumber,showFlag);
genMaterialCode(mob,(Item)me,++showNumber,showFlag);
genDrinkHeld(mob,me,++showNumber,showFlag);
genGettable(mob,(Item)me,++showNumber,showFlag);
genReadable1(mob,(Item)me,++showNumber,showFlag);
genReadable2(mob,(Item)me,++showNumber,showFlag);
if(me instanceof Light) genBurnout(mob,(Light)me,++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
if(me instanceof Container)
genCapacity(mob,(Container)me,++showNumber,showFlag);
if(me instanceof Perfume)
((Perfume)me).setSmellList(CMLib.english().prompt(mob,((Perfume)me).getSmellList(),++showNumber,showFlag,"Smells list (; delimited)"));
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
catalogCheckUpdate(mob, me);
}
protected void modifyGenWallpaper(MOB mob, Item me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genReadable1(mob,me,++showNumber,showFlag);
genReadable2(mob,me,++showNumber,showFlag);
if(me instanceof Light) genBurnout(mob,(Light)me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
}
protected void modifyGenMap(MOB mob, com.planet_ink.coffee_mud.Items.interfaces.Map me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,me,++showNumber,showFlag);
genGettable(mob,me,++showNumber,showFlag);
genReadable1(mob,me,++showNumber,showFlag);
genReadable2(mob,me,++showNumber,showFlag);
genValue(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
genMaterialCode(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
catalogCheckUpdate(mob, me);
}
protected void modifyGenContainer(MOB mob, Container me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
genCapacity(mob,me,++showNumber,showFlag);
if(me instanceof ShipComponent)
{
if(me instanceof ShipComponent.ShipPanel)
genPanelType(mob,(ShipComponent.ShipPanel)me,++showNumber,showFlag);
}
genLidsNLocks(mob,me,++showNumber,showFlag);
genMaterialCode(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,me,++showNumber,showFlag);
genValue(mob,me,++showNumber,showFlag);
genUses(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
if(me instanceof DeadBody)
genCorpseData(mob,(DeadBody)me,++showNumber,showFlag);
if(me instanceof ClanItem)
genClanItem(mob,(ClanItem)me,++showNumber,showFlag);
genGettable(mob,me,++showNumber,showFlag);
genReadable1(mob,me,++showNumber,showFlag);
genReadable2(mob,me,++showNumber,showFlag);
if(me instanceof Light) genBurnout(mob,(Light)me,++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
if(me instanceof Rideable)
{
genRideable1(mob,(Rideable)me,++showNumber,showFlag);
genRideable2(mob,(Rideable)me,++showNumber,showFlag);
}
if(me instanceof Exit)
{
genDoorName(mob,(Exit)me,++showNumber,showFlag);
genClosedText(mob,(Exit)me,++showNumber,showFlag);
}
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
catalogCheckUpdate(mob, me);
}
protected void modifyGenWeapon(MOB mob, Weapon me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genAttack(mob,me,++showNumber,showFlag);
genDamage(mob,me,++showNumber,showFlag);
genMaterialCode(mob,me,++showNumber,showFlag);
genWeaponType(mob,me,++showNumber,showFlag);
genWeaponClassification(mob,me,++showNumber,showFlag);
genWeaponRanges(mob,me,++showNumber,showFlag);
if(me instanceof Wand)
{
genReadable1(mob,me,++showNumber,showFlag);
genReadable2(mob,me,++showNumber,showFlag);
genUses(mob,me,++showNumber,showFlag);
genMaxUses(mob,(Wand)me,++showNumber,showFlag);
if(me instanceof Light) genBurnout(mob,(Light)me,++showNumber,showFlag);
}
else
genWeaponAmmo(mob,me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
if((!me.requiresAmmunition())&&(!(me instanceof Wand)))
genCondition(mob,me,++showNumber,showFlag);
genAbility(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,me,++showNumber,showFlag);
if(me instanceof ClanItem)
genClanItem(mob,(ClanItem)me,++showNumber,showFlag);
genGettable(mob,me,++showNumber,showFlag);
genValue(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
catalogCheckUpdate(mob, me);
}
protected void modifyGenArmor(MOB mob, Armor me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genMaterialCode(mob,me,++showNumber,showFlag);
genWornLocation(mob,me,++showNumber,showFlag);
genLayer(mob,me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
genArmor(mob,me,++showNumber,showFlag);
genCondition(mob,me,++showNumber,showFlag);
genAbility(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,me,++showNumber,showFlag);
if(me instanceof ClanItem)
genClanItem(mob,(ClanItem)me,++showNumber,showFlag);
genGettable(mob,me,++showNumber,showFlag);
genCapacity(mob,me,++showNumber,showFlag);
genLidsNLocks(mob,me,++showNumber,showFlag);
genReadable1(mob,me,++showNumber,showFlag);
genReadable2(mob,me,++showNumber,showFlag);
if(me instanceof Light) genBurnout(mob,(Light)me,++showNumber,showFlag);
genValue(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genSize(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
catalogCheckUpdate(mob, me);
}
protected void modifyGenInstrument(MOB mob, MusicalInstrument me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genMaterialCode(mob,me,++showNumber,showFlag);
genWornLocation(mob,me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
genAbility(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,me,++showNumber,showFlag);
genGettable(mob,me,++showNumber,showFlag);
genInstrumentType(mob,me,++showNumber,showFlag);
genValue(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
catalogCheckUpdate(mob, me);
}
protected void modifyGenExit(MOB mob, Exit me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genDoorsNLocks(mob,me,++showNumber,showFlag);
if(me.hasADoor())
{
genClosedText(mob,me,++showNumber,showFlag);
genDoorName(mob,me,++showNumber,showFlag);
genOpenWord(mob,me,++showNumber,showFlag);
genCloseWord(mob,me,++showNumber,showFlag);
}
genExitMisc(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
}
protected void modifyGenMOB(MOB mob, MOB me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
int oldLevel=me.baseEnvStats().level();
genLevel(mob,me,++showNumber,showFlag);
if((oldLevel<2)&&(me.baseEnvStats().level()>1))
me.baseCharStats().getCurrentClass().fillOutMOB(me,me.baseEnvStats().level());
genRejuv(mob,me,++showNumber,showFlag);
genRace(mob,me,++showNumber,showFlag);
Faction F=null;
for(Enumeration e=CMLib.factions().factionSet().elements();e.hasMoreElements();)
{
F=(Faction)e.nextElement();
if((!F.hasFaction(me))&&(F.findAutoDefault(me)!=Integer.MAX_VALUE))
mob.addFaction(F.factionID(),F.findAutoDefault(me));
if(F.showineditor())
genSpecialFaction(mob,me,++showNumber,showFlag,F);
}
genGender(mob,me,++showNumber,showFlag);
genHeight(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genClan(mob,me,++showNumber,showFlag);
genSpeed(mob,me,++showNumber,showFlag);
if((oldLevel<2)&&(me.baseEnvStats().level()>1))
me.baseEnvStats().setDamage((int)Math.round(CMath.div(me.baseEnvStats().damage(),me.baseEnvStats().speed())));
genAttack(mob,me,++showNumber,showFlag);
genDamage(mob,me,++showNumber,showFlag);
genArmor(mob,me,++showNumber,showFlag);
genHitPoints(mob,me,++showNumber,showFlag);
genMoney(mob,me,++showNumber,showFlag);
genAbilities(mob,me,++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genSensesMask(mob,me.baseEnvStats(),++showNumber,showFlag);
if(me instanceof Rideable)
{
genRideable1(mob,(Rideable)me,++showNumber,showFlag);
genRideable2(mob,(Rideable)me,++showNumber,showFlag);
}
if(me instanceof Deity)
{
genDeity1(mob,(Deity)me,++showNumber,showFlag);
genDeity2(mob,(Deity)me,++showNumber,showFlag);
genDeity3(mob,(Deity)me,++showNumber,showFlag);
genDeity4(mob,(Deity)me,++showNumber,showFlag);
genDeity5(mob,(Deity)me,++showNumber,showFlag);
genDeity8(mob,(Deity)me,++showNumber,showFlag);
genDeity9(mob,(Deity)me,++showNumber,showFlag);
genDeity6(mob,(Deity)me,++showNumber,showFlag);
genDeity0(mob,(Deity)me,++showNumber,showFlag);
genDeity7(mob,(Deity)me,++showNumber,showFlag);
genDeity11(mob,(Deity)me,++showNumber,showFlag);
}
genFaction(mob,me,++showNumber,showFlag);
genTattoos(mob,me,++showNumber,showFlag);
genExpertises(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverCharStats();
me.recoverMaxState();
me.recoverEnvStats();
me.resetToMaxState();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
me.setMiscText(me.text());
}
}
catalogCheckUpdate(mob, me);
mob.tell("\n\rNow don't forget to equip "+me.charStats().himher()+" with stuff before saving!\n\r");
}
protected void modifyPlayer(MOB mob, MOB me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
String oldName=me.Name();
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
while((!me.Name().equals(oldName))&&(CMLib.database().DBUserSearch(null,me.Name())))
{
mob.tell("The name given cannot be chosen, as it is already being used.");
genName(mob,me,showNumber,showFlag);
}
genPassword(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genRace(mob,me,++showNumber,showFlag);
genCharClass(mob,me,++showNumber,showFlag);
genCharStats(mob,me,++showNumber,showFlag);
Faction F=null;
for(Enumeration e=CMLib.factions().factionSet().elements();e.hasMoreElements();)
{
F=(Faction)e.nextElement();
if((!F.hasFaction(me))&&(F.findAutoDefault(me)!=Integer.MAX_VALUE))
mob.addFaction(F.factionID(),F.findAutoDefault(me));
if(F.showineditor())
genSpecialFaction(mob,me,++showNumber,showFlag,F);
}
genGender(mob,me,++showNumber,showFlag);
genHeight(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genSpeed(mob,me,++showNumber,showFlag);
genAttack(mob,me,++showNumber,showFlag);
genDamage(mob,me,++showNumber,showFlag);
genArmor(mob,me,++showNumber,showFlag);
genHitPoints(mob,me,++showNumber,showFlag);
genMoney(mob,me,++showNumber,showFlag);
me.setTrains(CMLib.english().prompt(mob,me.getTrains(),++showNumber,showFlag,"Training Points"));
me.setPractices(CMLib.english().prompt(mob,me.getPractices(),++showNumber,showFlag,"Practice Points"));
me.setQuestPoint(CMLib.english().prompt(mob,me.getQuestPoint(),++showNumber,showFlag,"Quest Points"));
genAbilities(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genSensesMask(mob,me.baseEnvStats(),++showNumber,showFlag);
if(me instanceof Rideable)
{
genRideable1(mob,(Rideable)me,++showNumber,showFlag);
genRideable2(mob,(Rideable)me,++showNumber,showFlag);
}
genFaction(mob,me,++showNumber,showFlag);
genTattoos(mob,me,++showNumber,showFlag);
genExpertises(mob,me,++showNumber,showFlag);
genTitles(mob,me,++showNumber,showFlag);
genEmail(mob,me,++showNumber,showFlag);
genSecurity(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
genNotes(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(me.playerStats()!=null)
for(int x=me.playerStats().getSaveStatIndex();x<me.playerStats().getStatCodes().length;x++)
me.playerStats().setStat(me.playerStats().getStatCodes()[x],CMLib.english().prompt(mob,me.playerStats().getStat(me.playerStats().getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.playerStats().getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverCharStats();
me.recoverMaxState();
me.recoverEnvStats();
me.resetToMaxState();
if(!oldName.equals(me.Name()))
{
MOB fakeMe=(MOB)me.copyOf();
fakeMe.setName(oldName);
CMLib.database().DBDeleteMOB(fakeMe);
CMLib.database().DBCreateCharacter(me);
}
CMLib.database().DBUpdatePlayer(me);
CMLib.database().DBUpdateFollowers(me);
}
}
}
protected void genClanStatus(MOB mob, Clan C, int showNumber, int showFlag)
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Clan Status: "+Clan.CLANSTATUS_DESC[C.getStatus()]);
if((showFlag!=showNumber)&&(showFlag>-999)) return;
switch(C.getStatus())
{
case Clan.CLANSTATUS_ACTIVE:
C.setStatus(Clan.CLANSTATUS_PENDING);
mob.tell("Clan '"+C.name()+"' has been changed from active to pending!");
break;
case Clan.CLANSTATUS_PENDING:
C.setStatus(Clan.CLANSTATUS_ACTIVE);
mob.tell("Clan '"+C.name()+"' has been changed from pending to active!");
break;
case Clan.CLANSTATUS_FADING:
C.setStatus(Clan.CLANSTATUS_ACTIVE);
mob.tell("Clan '"+C.name()+"' has been changed from fading to active!");
break;
default:
mob.tell("Clan '"+C.name()+"' has not been changed!");
break;
}
}
protected void genClanGovt(MOB mob, Clan C, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Government type: '"+C.typeName()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
while((mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a new one (?)\n\r:","");
if(newName.trim().length()==0)
{
mob.tell("(no change)");
return;
}
int newGovt=-1;
StringBuffer gvts=new StringBuffer();
for(int i=0;i<Clan.GVT_DESCS.length;i++)
{
gvts.append(Clan.GVT_DESCS[i]+", ");
if(newName.equalsIgnoreCase(Clan.GVT_DESCS[i]))
newGovt=i;
}
gvts=new StringBuffer(gvts.substring(0,gvts.length()-2));
if(newGovt<0)
mob.tell("That government type is invalid. Valid types include: "+gvts.toString());
else
{
C.setGovernment(newGovt);
break;
}
}
}
protected double genAuctionPrompt(MOB mob, double oldVal, int showNumber, int showFlag, String msg, boolean pct)
throws IOException
{
String oldStr=(oldVal<0)?"":(pct?""+(oldVal*100.0)+"%":""+oldVal);
String newStr=CMLib.english().prompt(mob,oldStr,showNumber,showFlag,msg);
if(newStr.trim().length()==0)
return -1.0;
if((pct)&&(!CMath.isPct(newStr))&&(!CMath.isNumber(newStr)))
return -1.0;
else
if((!pct)&&(!CMath.isNumber(newStr)))
return -1.0;
if(pct) return CMath.s_pct(newStr);
return CMath.s_double(newStr);
}
protected int genAuctionPrompt(MOB mob, int oldVal, int showNumber, int showFlag, String msg)
throws IOException
{
String oldStr=(oldVal<0)?"":""+oldVal;
String newStr=CMLib.english().prompt(mob,oldStr,showNumber,showFlag,msg);
if(newStr.trim().length()==0)
return -1;
if(!CMath.isNumber(newStr))
return -1;
return CMath.s_int(newStr);
}
protected void genClanRole(MOB mob, Clan C, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Clan (Role): '"+CMLib.clans().getRoleName(C.getGovernment(),C.getAutoPosition(),true,false)+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
while((mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a new one (?)\n\r:","");
if(newName.trim().length()==0)
{
mob.tell("(no change)");
return;
}
int newRole=-1;
StringBuffer roles=new StringBuffer();
for(int i=0;i<Clan.ROL_DESCS[C.getGovernment()].length;i++)
{
roles.append(Clan.ROL_DESCS[C.getGovernment()][i]+", ");
if(newName.equalsIgnoreCase(Clan.ROL_DESCS[C.getGovernment()][i]))
newRole=Clan.POSORDER[i];
}
roles=new StringBuffer(roles.substring(0,roles.length()-2));
if(newRole<0)
mob.tell("That role is invalid. Valid roles include: "+roles.toString());
else
{
C.setAutoPosition(newRole);
break;
}
}
}
protected void genClanClass(MOB mob, Clan C, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
CharClass CC=CMClass.getCharClass(C.getClanClass());
if(CC==null)CC=CMClass.findCharClass(C.getClanClass());
String clasName=(CC==null)?"NONE":CC.name();
mob.tell(showNumber+". Clan Auto-Class: '"+clasName+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
while((mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a new one (?)\n\r:","");
if(newName.trim().equalsIgnoreCase("none"))
{
C.setClanClass("");
return;
}
else
if(newName.trim().length()==0)
{
mob.tell("(no change)");
return;
}
CharClass newC=null;
StringBuffer clss=new StringBuffer();
for(Enumeration e=CMClass.charClasses();e.hasMoreElements();)
{
CC=(CharClass)e.nextElement();
clss.append(CC.name()+", ");
if(newName.equalsIgnoreCase(CC.name())||(newName.equalsIgnoreCase(CC.ID())))
newC=CC;
}
clss=new StringBuffer(clss.substring(0,clss.length()-2));
if(newC==null)
mob.tell("That class name is invalid. Valid names include: "+clss.toString());
else
{
C.setClanClass(newC.ID());
break;
}
}
}
String genClanRoom(MOB mob, Clan C, String oldRoomID, String promptCode, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return oldRoomID;
mob.tell(showNumber+CMStrings.replaceAll(promptCode,"@x1",oldRoomID));
if((showFlag!=showNumber)&&(showFlag>-999)) return oldRoomID;
while((mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a new one (null)\n\r:","");
if(newName.trim().equalsIgnoreCase("null"))
return "";
else
if(newName.trim().length()==0)
{
mob.tell("(no change)");
return oldRoomID;
}
Room newRoom=CMLib.map().getRoom(newName);
if((newRoom==null)
||(CMLib.map().getExtendedRoomID(newRoom).length()==0)
||(!CMLib.law().doesOwnThisProperty(C.clanID(),newRoom)))
mob.tell("That is either not a valid room id, or that room is not owned by the clan.");
else
return CMLib.map().getExtendedRoomID(newRoom);
}
return oldRoomID;
}
protected void modifyClan(MOB mob, Clan C)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
String oldName=C.ID();
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
mob.tell("*. Name: '"+C.name()+"'.");
int showNumber=0;
genClanGovt(mob,C,++showNumber,showFlag);
C.setPremise(CMLib.english().prompt(mob,C.getPremise(),++showNumber,showFlag,"Clan Premise: ",true));
C.setExp(CMLib.english().prompt(mob,C.getExp(),++showNumber,showFlag,"Clan Experience: "));
C.setTaxes(CMLib.english().prompt(mob,C.getTaxes(),++showNumber,showFlag,"Clan Tax Rate (X 100%): "));
C.setMorgue(genClanRoom(mob,C,C.getMorgue(),". Morgue RoomID: '@x1'.",++showNumber,showFlag));
C.setRecall(genClanRoom(mob,C,C.getRecall(),". Clan Home RoomID: '@x1'.",++showNumber,showFlag));
C.setDonation(genClanRoom(mob,C,C.getDonation(),". Clan Donate RoomID: '@x1'.",++showNumber,showFlag));
genClanAccept(mob,C,++showNumber,showFlag);
genClanClass(mob,C,++showNumber,showFlag);
genClanRole(mob,C,++showNumber,showFlag);
genClanStatus(mob,C,++showNumber,showFlag);
genClanMembers(mob,C,++showNumber,showFlag);
/*setClanRelations, votes?*/
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
if(!oldName.equals(C.ID()))
{
//cycle through everything changing the name
CMLib.database().DBDeleteClan(C);
CMLib.database().DBCreateClan(C);
}
C.update();
}
}
}
protected void modifyGenShopkeeper(MOB mob, ShopKeeper me)
throws IOException
{
if(mob.isMonster())
return;
if(!(me instanceof MOB))
return;
MOB mme=(MOB)me;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
int oldLevel=me.baseEnvStats().level();
genLevel(mob,me,++showNumber,showFlag);
if((oldLevel<2)&&(me.baseEnvStats().level()>1))
mme.baseCharStats().getCurrentClass().fillOutMOB(mme,me.baseEnvStats().level());
genRejuv(mob,me,++showNumber,showFlag);
genRace(mob,mme,++showNumber,showFlag);
genHeight(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
Faction F=null;
for(Enumeration e=CMLib.factions().factionSet().elements();e.hasMoreElements();)
{
F=(Faction)e.nextElement();
if((!F.hasFaction((MOB)me))&&(F.findAutoDefault((MOB)me)!=Integer.MAX_VALUE))
mob.addFaction(F.factionID(),F.findAutoDefault((MOB)me));
if(F.showineditor())
genSpecialFaction(mob,(MOB)me,++showNumber,showFlag,F);
}
genGender(mob,mme,++showNumber,showFlag);
genClan(mob,mme,++showNumber,showFlag);
genSpeed(mob,me,++showNumber,showFlag);
if((oldLevel<2)&&(me.baseEnvStats().level()>1))
me.baseEnvStats().setDamage((int)Math.round(CMath.div(me.baseEnvStats().damage(),me.baseEnvStats().speed())));
genAttack(mob,me,++showNumber,showFlag);
genDamage(mob,me,++showNumber,showFlag);
genArmor(mob,me,++showNumber,showFlag);
if(me instanceof MOB)
genHitPoints(mob,(MOB)me,++showNumber,showFlag);
genMoney(mob,mme,++showNumber,showFlag);
genAbilities(mob,mme,++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
if(!(me instanceof Auctioneer))
{
genShopkeeper1(mob,me,++showNumber,showFlag);
genShopkeeper2(mob,me,++showNumber,showFlag);
genEconomics1(mob,me,++showNumber,showFlag);
genEconomics5(mob,me,++showNumber,showFlag);
}
genEconomics6(mob,me,++showNumber,showFlag);
if(me instanceof Banker)
{
genBanker1(mob,(Banker)me,++showNumber,showFlag);
genBanker2(mob,(Banker)me,++showNumber,showFlag);
genBanker3(mob,(Banker)me,++showNumber,showFlag);
genBanker4(mob,(Banker)me,++showNumber,showFlag);
}
else
if(me instanceof PostOffice)
{
((PostOffice)me).setPostalChain(CMLib.english().prompt(mob,((PostOffice)me).postalChain(),++showNumber,showFlag,"Postal chain"));
((PostOffice)me).setFeeForNewBox(CMLib.english().prompt(mob,((PostOffice)me).feeForNewBox(),++showNumber,showFlag,"Fee to open a new box"));
((PostOffice)me).setMinimumPostage(CMLib.english().prompt(mob,((PostOffice)me).minimumPostage(),++showNumber,showFlag,"Minimum postage cost"));
((PostOffice)me).setPostagePerPound(CMLib.english().prompt(mob,((PostOffice)me).postagePerPound(),++showNumber,showFlag,"Postage cost per pound after 1st pound"));
((PostOffice)me).setHoldFeePerPound(CMLib.english().prompt(mob,((PostOffice)me).holdFeePerPound(),++showNumber,showFlag,"Holding fee per pound per month"));
((PostOffice)me).setMaxMudMonthsHeld(CMLib.english().prompt(mob,((PostOffice)me).maxMudMonthsHeld(),++showNumber,showFlag,"Maximum number of months held"));
}
else
if(me instanceof Auctioneer)
{
((Auctioneer)me).setAuctionHouse(CMLib.english().prompt(mob,((Auctioneer)me).auctionHouse(),++showNumber,showFlag,"Auction house"));
((Auctioneer)me).setTimedListingPrice(genAuctionPrompt(mob,((Auctioneer)me).timedListingPrice(),++showNumber,showFlag,"Flat fee per auction",false));
((Auctioneer)me).setTimedListingPct(genAuctionPrompt(mob,((Auctioneer)me).timedListingPct(),++showNumber,showFlag,"Listing Cut/%Pct per day",true));
((Auctioneer)me).setTimedFinalCutPct(genAuctionPrompt(mob,((Auctioneer)me).timedFinalCutPct(),++showNumber,showFlag,"Cut/%Pct of final price",true));
((Auctioneer)me).setMaxTimedAuctionDays(genAuctionPrompt(mob,((Auctioneer)me).maxTimedAuctionDays(),++showNumber,showFlag,"Maximum number of auction mud-days"));
((Auctioneer)me).setMinTimedAuctionDays(genAuctionPrompt(mob,((Auctioneer)me).minTimedAuctionDays(),++showNumber,showFlag,"Minimum number of auction mud-days"));
}
else
{
genEconomics2(mob,me,++showNumber,showFlag);
genEconomics3(mob,me,++showNumber,showFlag);
genEconomics4(mob,me,++showNumber,showFlag);
}
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genSensesMask(mob,me.baseEnvStats(),++showNumber,showFlag);
genFaction(mob,mme,++showNumber,showFlag);
genTattoos(mob,(MOB)me,++showNumber,showFlag);
genExpertises(mob,(MOB)me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
mme.recoverCharStats();
mme.recoverMaxState();
me.recoverEnvStats();
mme.resetToMaxState();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
me.setMiscText(me.text());
}
}
catalogCheckUpdate(mob, me);
mob.tell("\n\rNow don't forget to equip him with non-generic items before saving! If you DO add items to his list, be sure to come back here in case you've exceeded the string limit again.\n\r");
}
}
| com/planet_ink/coffee_mud/Commands/BaseGenerics.java | package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
import java.util.*;
import java.io.ByteArrayInputStream;
import java.io.IOException;
/*
Copyright 2000-2007 Bo Zimmerman
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
public class BaseGenerics extends StdCommand
{
private final long maxLength=Long.MAX_VALUE;
// showNumber should always be a valid number no less than 1
// showFlag should be a valid number for editing, or -1 for skipping
protected void genName(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{
String newName=CMLib.english().prompt(mob,E.Name(),showNumber,showFlag,"Name",false,false);
if(newName.equals(E.Name())) return;
if((!CMath.bset(E.baseEnvStats().disposition(),EnvStats.IS_CATALOGED))
||((!(E instanceof MOB))&&(!(E instanceof Item)))
||(mob.session()==null))
{ E.setName(newName); return;}
int oldIndex=(E instanceof MOB)?
CMLib.map().getCatalogMobIndex(E.Name()):
CMLib.map().getCatalogItemIndex(E.Name());
if(oldIndex<0) return;
int[] usage=(E instanceof MOB)?
CMLib.map().getCatalogMobUsage(oldIndex):
CMLib.map().getCatalogItemUsage(oldIndex);
if(mob.session().confirm("This object is cataloged. Changing its name will detach it from the cataloged version, are you sure (y/N)?","N"))
{
E.setName(newName);
E.baseEnvStats().setDisposition(CMath.unsetb(E.baseEnvStats().disposition(), EnvStats.IS_CATALOGED));
E.envStats().setDisposition(CMath.unsetb(E.envStats().disposition(), EnvStats.IS_CATALOGED));
usage[0]--;
}
}
protected void catalogCheckUpdate(MOB mob, Environmental E)
throws IOException
{
if((!CMath.bset(E.baseEnvStats().disposition(),EnvStats.IS_CATALOGED))
||((!(E instanceof MOB))&&(!(E instanceof Item)))
||(mob.session()==null))
return;
int oldIndex=(E instanceof MOB)?
CMLib.map().getCatalogMobIndex(E.Name()):
CMLib.map().getCatalogItemIndex(E.Name());
if(oldIndex<0) return;
Environmental cataE=(E instanceof MOB)?
(Environmental)CMLib.map().getCatalogMob(oldIndex):
(Environmental)CMLib.map().getCatalogItem(oldIndex);
int[] usage=(E instanceof MOB)?
CMLib.map().getCatalogMobUsage(oldIndex):
CMLib.map().getCatalogItemUsage(oldIndex);
E.baseEnvStats().setDisposition(CMath.unsetb(E.baseEnvStats().disposition(), EnvStats.IS_CATALOGED));
E.envStats().setDisposition(CMath.unsetb(E.envStats().disposition(), EnvStats.IS_CATALOGED));
if(mob.session().confirm("This object is cataloged. Enter Y to update the cataloged version, or N to detach this object from the catalog (Y/n)?","Y"))
{
cataE.setMiscText(E.text());
if(E instanceof MOB)
CMLib.database().DBUpdateMOB("CATALOG_MOBS",(MOB)cataE);
else
CMLib.database().DBUpdateItem("CATALOG_ITEMS",(Item)cataE);
E.baseEnvStats().setDisposition(E.baseEnvStats().disposition()|EnvStats.IS_CATALOGED);
E.envStats().setDisposition(E.envStats().disposition()|EnvStats.IS_CATALOGED);
CMLib.map().propogateCatalogChange(cataE);
mob.tell("Catalog update complete.");
}
else
{
E.baseEnvStats().setDisposition(CMath.unsetb(E.baseEnvStats().disposition(), EnvStats.IS_CATALOGED));
E.envStats().setDisposition(CMath.unsetb(E.envStats().disposition(), EnvStats.IS_CATALOGED));
usage[0]--;
}
}
protected void genImage(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.setImage(CMLib.english().prompt(mob,E.rawImage(),showNumber,showFlag,"MXP Image filename",true,false,"This is the path/filename of your MXP image file for this object."));}
protected void genCorpseData(MOB mob, DeadBody E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Corpse Data: '"+E.mobName()+"/"+E.killerName()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
mob.tell("Dead MOB name: '"+E.mobName()+"'.");
String newName=mob.session().prompt("Enter a new name\n\r:","");
if(newName.length()>0) E.setMobName(newName);
else mob.tell("(no change)");
mob.tell("Dead MOB Description: '"+E.mobDescription()+"'.");
newName=mob.session().prompt("Enter a new description\n\r:","");
if(newName.length()>0) E.setMobDescription(newName);
else mob.tell("(no change)");
mob.tell("Is a Players corpse: "+E.playerCorpse());
newName=mob.session().prompt("Enter a new true/false\n\r:","");
if((newName.length()>0)&&(newName.equalsIgnoreCase("true")||newName.equalsIgnoreCase("false")))
E.setPlayerCorpse(Boolean.valueOf(newName.toLowerCase()).booleanValue());
else mob.tell("(no change)");
mob.tell("Dead mobs PK flag: "+E.mobPKFlag());
newName=mob.session().prompt("Enter a new true/false\n\r:","");
if((newName.length()>0)&&(newName.equalsIgnoreCase("true")||newName.equalsIgnoreCase("false")))
E.setMobPKFlag(Boolean.valueOf(newName.toLowerCase()).booleanValue());
else mob.tell("(no change)");
genCharStats(mob,E.charStats());
mob.tell("Killers Name: '"+E.killerName()+"'.");
newName=mob.session().prompt("Enter a new killer\n\r:","");
if(newName.length()>0) E.setKillerName(newName);
else mob.tell("(no change)");
mob.tell("Killer is a player: "+E.killerPlayer());
newName=mob.session().prompt("Enter a new true/false\n\r:","");
if((newName.length()>0)&&(newName.equalsIgnoreCase("true")||newName.equalsIgnoreCase("false")))
E.setKillerPlayer(Boolean.valueOf(newName.toLowerCase()).booleanValue());
else mob.tell("(no change)");
mob.tell("Time of death: "+CMLib.time().date2String(E.timeOfDeath()));
newName=mob.session().prompt("Enter a new value\n\r:","");
if(newName.length()>0) E.setTimeOfDeath(CMLib.time().string2Millis(newName));
else mob.tell("(no change)");
mob.tell("Last message string: "+E.lastMessage());
newName=mob.session().prompt("Enter a new value\n\r:","");
if(newName.length()>0) E.setLastMessage(newName);
else mob.tell("(no change)");
}
protected void genAuthor(MOB mob, Area A, int showNumber, int showFlag) throws IOException
{ A.setAuthorID(CMLib.english().prompt(mob,A.getAuthorID(),showNumber,showFlag,"Author",true,false,"Area Author's Name"));}
protected void genPanelType(MOB mob, ShipComponent.ShipPanel S, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String componentType=CMStrings.capitalizeAndLower(ShipComponent.ShipPanel.COMPONENT_PANEL_DESC[S.panelType()].toLowerCase());
mob.tell(showNumber+". Panel Type: '"+componentType+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean continueThis=true;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(continueThis))
{
continueThis=false;
String newName=mob.session().prompt("Enter a new one (?)\n\r:","");
if(newName.length()>0)
{
if(newName.equalsIgnoreCase("?"))
{
mob.tell("Component Types: "+CMParms.toStringList(ShipComponent.ShipPanel.COMPONENT_PANEL_DESC));
continueThis=true;
}
else
{
int newType=-1;
for(int i=0;i<ShipComponent.ShipPanel.COMPONENT_PANEL_DESC.length;i++)
if(ShipComponent.ShipPanel.COMPONENT_PANEL_DESC[i].equalsIgnoreCase(newName))
newType=i;
if(newType<0)
{
mob.tell("'"+newName+"' is not recognized. Try '?' for a list.");
continueThis=true;
}
else
S.setPanelType(newType);
}
}
else
mob.tell("(no change)");
}
}
protected void genCurrency(MOB mob, Area A, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String currencyName=A.getCurrency().length()==0?"Default":A.getCurrency();
mob.tell(showNumber+". Currency: '"+currencyName+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a new one or 'DEFAULT'\n\r:","");
if(newName.length()>0)
{
if(newName.equalsIgnoreCase("default"))
A.setCurrency("");
else
if((newName.indexOf("=")<0)&&(!CMLib.beanCounter().getAllCurrencies().contains(newName.trim().toUpperCase())))
{
Vector V=CMLib.beanCounter().getAllCurrencies();
mob.tell("'"+newName.trim().toUpperCase()+"' is not a known currency. Existing currencies include: DEFAULT"+CMParms.toStringList(V));
}
else
if(newName.indexOf("=")>=0)
A.setCurrency(newName.trim());
else
A.setCurrency(newName.toUpperCase().trim());
}
else
mob.tell("(no change)");
}
protected void genTimeClock(MOB mob, Area A, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
TimeClock TC=A.getTimeObj();
StringBuffer report=new StringBuffer("");
if(TC==CMClass.globalClock())
report.append("Default -- Can't be changed.");
else
{
report.append(TC.getHoursInDay()+" hrs-day/");
report.append(TC.getDaysInMonth()+" days-mn/");
report.append(TC.getMonthsInYear()+" mnths-yr");
}
mob.tell(showNumber+". Calendar: '"+report.toString()+"'.");
if(TC==CMClass.globalClock()) return;
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName="";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.length()==0))
{
report=new StringBuffer("\n\rCalendar/Clock settings:\n\r");
report.append("1. "+TC.getHoursInDay()+" hours per day\n\r");
report.append("2. Dawn Hour: "+TC.getDawnToDusk()[TimeClock.TIME_DAWN]+"\n\r");
report.append("3. Day Hour: "+TC.getDawnToDusk()[TimeClock.TIME_DAY]+"\n\r");
report.append("4. Dusk Hour: "+TC.getDawnToDusk()[TimeClock.TIME_DUSK]+"\n\r");
report.append("5. Night Hour: "+TC.getDawnToDusk()[TimeClock.TIME_NIGHT]+"\n\r");
report.append("6. Weekdays: "+CMParms.toStringList(TC.getWeekNames())+"\n\r");
report.append("7. Months: "+CMParms.toStringList(TC.getMonthNames())+"\n\r");
report.append("8. Year Title(s): "+CMParms.toStringList(TC.getYearNames()));
mob.tell(report.toString());
newName=mob.session().prompt("Enter one to change:","");
if(newName.length()==0) break;
int which=CMath.s_int(newName);
if((which<0)||(which>8))
mob.tell("Invalid: "+which+"");
else
if(which<=5)
{
newName="";
String newNum=mob.session().prompt("Enter a new number:","");
int val=CMath.s_int(newNum);
if(newNum.length()==0)
mob.tell("(no change)");
else
switch(which)
{
case 1:
TC.setHoursInDay(val);
break;
case 2:
TC.getDawnToDusk()[TimeClock.TIME_DAWN]=val;
break;
case 3:
if((val>=0)&&(TC.getDawnToDusk()[TimeClock.TIME_DAWN]>=val))
mob.tell("That value is before the dawn!");
else
TC.getDawnToDusk()[TimeClock.TIME_DAY]=val;
break;
case 4:
if((val>=0)&&(TC.getDawnToDusk()[TimeClock.TIME_DAWN]>=val))
mob.tell("That value is before the dawn!");
else
if((val>=0)&&(TC.getDawnToDusk()[TimeClock.TIME_DAY]>=val))
mob.tell("That value is before the day!");
else
TC.getDawnToDusk()[TimeClock.TIME_DUSK]=val;
break;
case 5:
if((val>=0)&&(TC.getDawnToDusk()[TimeClock.TIME_DAWN]>=val))
mob.tell("That value is before the dawn!");
else
if((val>=0)&&(TC.getDawnToDusk()[TimeClock.TIME_DAY]>=val))
mob.tell("That value is before the day!");
else
if((val>=0)&&(TC.getDawnToDusk()[TimeClock.TIME_DUSK]>=val))
mob.tell("That value is before the dusk!");
else
TC.getDawnToDusk()[TimeClock.TIME_NIGHT]=val;
break;
}
}
else
{
newName="";
String newNum=mob.session().prompt("Enter a new list (comma delimited)\n\r:","");
if(newNum.length()==0)
mob.tell("(no change)");
else
switch(which)
{
case 6:
TC.setDaysInWeek(CMParms.toStringArray(CMParms.parseCommas(newNum,true)));
break;
case 7:
TC.setMonthsInYear(CMParms.toStringArray(CMParms.parseCommas(newNum,true)));
break;
case 8:
TC.setYearNames(CMParms.toStringArray(CMParms.parseCommas(newNum,true)));
break;
}
}
}
TC.save();
}
protected void genClan(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag<=0)||(showFlag==showNumber))
{
mob.tell(showNumber+". Clan (ID): '"+E.getClanID()+"'.");
if((showFlag==showNumber)||(showFlag<=-999))
{
String newName=mob.session().prompt("Enter a new one (null)\n\r:","");
if(newName.equalsIgnoreCase("null"))
E.setClanID("");
else
if(newName.length()>0)
{
E.setClanID(newName);
E.setClanRole(Clan.POS_MEMBER);
}
else
mob.tell("(no change)");
}
}
if(((showFlag<=0)||(showFlag==showNumber))
&&(!E.isMonster())
&&(E.getClanID().length()>0)
&&(CMLib.clans().getClan(E.getClanID())!=null))
{
Clan C=CMLib.clans().getClan(E.getClanID());
mob.tell(showNumber+". Clan (Role): '"+CMLib.clans().getRoleName(C.getGovernment(),E.getClanRole(),true,false)+"'.");
if((showFlag==showNumber)||(showFlag<=-999))
{
String newName=mob.session().prompt("Enter a new one\n\r:","");
if(newName.length()>0)
{
int newRole=-1;
for(int i=0;i<Clan.ROL_DESCS[C.getGovernment()].length;i++)
if(newName.equalsIgnoreCase(Clan.ROL_DESCS[C.getGovernment()][i]))
{
newRole=(int)CMath.pow(2,i-1);
break;
}
if(newRole<0)
mob.tell("That role is invalid. Try: "+CMParms.toStringList(Clan.ROL_DESCS[C.getGovernment()]));
else
E.setClanRole(newRole);
}
else
mob.tell("(no change)");
}
}
}
protected void genArchivePath(MOB mob, Area E, int showNumber, int showFlag) throws IOException
{ E.setArchivePath(CMLib.english().prompt(mob,E.getArchivePath(),showNumber,showFlag,"Archive Path",true,false,"Path/filename for EXPORT AREA command. Enter NULL for default."));}
protected Room changeRoomType(Room R, Room newRoom)
{
if((R==null)||(newRoom==null)) return R;
synchronized(("SYNC"+R.roomID()).intern())
{
R=CMLib.map().getRoom(R);
Room oldR=R;
R=newRoom;
Vector oldBehavsNEffects=new Vector();
for(int a=oldR.numEffects()-1;a>=0;a--)
{
Ability A=oldR.fetchEffect(a);
if(A!=null)
{
if(!A.canBeUninvoked())
{
oldBehavsNEffects.addElement(A);
oldR.delEffect(A);
}
else
A.unInvoke();
}
}
for(int b=0;b<oldR.numBehaviors();b++)
{
Behavior B=oldR.fetchBehavior(b);
if(B!=null)
oldBehavsNEffects.addElement(B);
}
CMLib.threads().deleteTick(oldR,-1);
R.setRoomID(oldR.roomID());
Area A=oldR.getArea();
if(A!=null) A.delProperRoom(oldR);
R.setArea(A);
for(int d=0;d<R.rawDoors().length;d++)
R.rawDoors()[d]=oldR.rawDoors()[d];
for(int d=0;d<R.rawExits().length;d++)
R.rawExits()[d]=oldR.rawExits()[d];
R.setDisplayText(oldR.displayText());
R.setDescription(oldR.description());
if(R.image().equalsIgnoreCase(CMProps.getDefaultMXPImage(oldR))) R.setImage(null);
if((R instanceof GridLocale)&&(oldR instanceof GridLocale))
{
((GridLocale)R).setXGridSize(((GridLocale)oldR).xGridSize());
((GridLocale)R).setYGridSize(((GridLocale)oldR).yGridSize());
((GridLocale)R).clearGrid(null);
}
Vector allmobs=new Vector();
int skip=0;
while(oldR.numInhabitants()>(skip))
{
MOB M=oldR.fetchInhabitant(skip);
if(M.savable())
{
if(!allmobs.contains(M))
allmobs.addElement(M);
oldR.delInhabitant(M);
}
else
if(oldR!=R)
{
oldR.delInhabitant(M);
R.bringMobHere(M,true);
}
else
skip++;
}
Vector allitems=new Vector();
while(oldR.numItems()>0)
{
Item I=oldR.fetchItem(0);
if(!allitems.contains(I))
allitems.addElement(I);
oldR.delItem(I);
}
for(int i=0;i<allitems.size();i++)
{
Item I=(Item)allitems.elementAt(i);
if(!R.isContent(I))
{
if(I.subjectToWearAndTear())
I.setUsesRemaining(100);
I.recoverEnvStats();
R.addItem(I);
R.recoverRoomStats();
}
}
for(int m=0;m<allmobs.size();m++)
{
MOB M=(MOB)allmobs.elementAt(m);
if(!R.isInhabitant(M))
{
MOB M2=(MOB)M.copyOf();
M2.setStartRoom(R);
M2.setLocation(R);
long rejuv=Tickable.TICKS_PER_RLMIN+Tickable.TICKS_PER_RLMIN+(Tickable.TICKS_PER_RLMIN/2);
if(rejuv>(Tickable.TICKS_PER_RLMIN*20)) rejuv=(Tickable.TICKS_PER_RLMIN*20);
M2.envStats().setRejuv((int)rejuv);
M2.recoverCharStats();
M2.recoverEnvStats();
M2.recoverMaxState();
M2.resetToMaxState();
M2.bringToLife(R,true);
R.recoverRoomStats();
M.destroy();
}
}
try
{
for(Enumeration r=CMLib.map().rooms();r.hasMoreElements();)
{
Room R2=(Room)r.nextElement();
for(int d=0;d<R2.rawDoors().length;d++)
if(R2.rawDoors()[d]==oldR)
{
R2.rawDoors()[d]=R;
if(R2 instanceof GridLocale)
((GridLocale)R2).buildGrid();
}
}
}catch(NoSuchElementException e){}
try
{
for(Enumeration e=CMLib.map().players();e.hasMoreElements();)
{
MOB M=(MOB)e.nextElement();
if(M.getStartRoom()==oldR)
M.setStartRoom(R);
else
if(M.location()==oldR)
M.setLocation(R);
}
}catch(NoSuchElementException e){}
R.getArea().fillInAreaRoom(R);
for(int i=0;i<oldBehavsNEffects.size();i++)
{
if(oldBehavsNEffects.elementAt(i) instanceof Behavior)
R.addBehavior((Behavior)oldBehavsNEffects.elementAt(i));
else
R.addNonUninvokableEffect((Ability)oldBehavsNEffects.elementAt(i));
}
CMLib.database().DBUpdateRoom(R);
CMLib.database().DBUpdateMOBs(R);
CMLib.database().DBUpdateItems(R);
oldR.destroy();
R.getArea().addProperRoom(R); // necessary because of the destroy
R.setImage(R.rawImage());
R.startItemRejuv();
}
return R;
}
protected Room genRoomType(MOB mob, Room R, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return R;
mob.tell(showNumber+". Type: '"+CMClass.classID(R)+"'");
if((showFlag!=showNumber)&&(showFlag>-999)) return R;
String newName="";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.length()==0))
{
newName=mob.session().prompt("Enter a new one (?)\n\r:","");
if(newName.trim().equals("?"))
{
mob.tell(CMLib.lister().reallyList2Cols(CMClass.locales(),-1,null).toString()+"\n\r");
newName="";
}
else
if(newName.length()>0)
{
Room newRoom=CMClass.getLocale(newName);
if(newRoom==null)
mob.tell("'"+newName+"' does not exist. No Change.");
else
if(mob.session().confirm("This will change the room type of room "+R.roomID()+". It will automatically save any mobs and items in this room permanently. Are you absolutely sure (y/N)?","N"))
R=changeRoomType(R,newRoom);
R.recoverRoomStats();
}
else
{
mob.tell("(no change)");
break;
}
}
return R;
}
protected void genDescription(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.setDescription(CMLib.english().prompt(mob,E.description(),showNumber,showFlag,"Description",true,false,null));}
protected void genNotes(MOB mob, MOB E, int showNumber, int showFlag) throws IOException
{
if(E.playerStats()!=null)
E.playerStats().setNotes(CMLib.english().prompt(mob,E.playerStats().notes(),showNumber,showFlag,"Private notes",true,false,null));
}
protected void genPassword(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Password: ********.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a new one to reset\n\r:","");
if((newName.length()>0)&&(E.playerStats()!=null))
{
E.playerStats().setPassword(newName);
CMLib.database().DBUpdatePassword(E);
}
else
mob.tell("(no change)");
}
protected void genEmail(MOB mob, MOB E, int showNumber, int showFlag) throws IOException
{
if(E.playerStats()!=null)
E.playerStats().setEmail(CMLib.english().prompt(mob,E.playerStats().getEmail(),showNumber,showFlag,"Email",true,false,null));
}
protected void genDisplayText(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Display: '"+E.displayText()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=null;
if(E instanceof Item)
newName=mob.session().prompt("Enter something new (null == blended)\n\r:","");
else
if(E instanceof Exit)
newName=mob.session().prompt("Enter something new (null == see-through)\n\r:","");
else
newName=mob.session().prompt("Enter something new (null = empty)\n\r:","");
if(newName.length()>0)
{
if(newName.trim().equalsIgnoreCase("null"))
newName="";
E.setDisplayText(newName);
}
else
mob.tell("(no change)");
if((E instanceof Item)&&(E.displayText().length()==0))
mob.tell("(blended)");
}
protected void genClosedText(MOB mob, Exit E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if(E instanceof Item)
mob.tell(showNumber+". Exit Closed Text: '"+E.closedText()+"'.");
else
mob.tell(showNumber+". Closed Text: '"+E.closedText()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter something new (null=blank)\n\r:","");
if(newName.equals("null"))
E.setExitParams(E.doorName(),E.closeWord(),E.openWord(),"");
else
if(newName.length()>0)
E.setExitParams(E.doorName(),E.closeWord(),E.openWord(),newName);
else
mob.tell("(no change)");
}
protected void genDoorName(MOB mob, Exit E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if(E instanceof Item)
mob.tell(showNumber+". Exit Direction: '"+E.doorName()+"'.");
else
mob.tell(showNumber+". Door Name: '"+E.doorName()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter something new\n\r:","");
if(newName.length()>0)
E.setExitParams(newName,E.closeWord(),E.openWord(),E.closedText());
else
mob.tell("(no change)");
}
protected void genBurnout(MOB mob, Light E, int showNumber, int showFlag)
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Is destroyed after burnout: '"+E.destroyedWhenBurnedOut()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
E.setDestroyedWhenBurntOut(!E.destroyedWhenBurnedOut());
}
protected void genOpenWord(MOB mob, Exit E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Open Word: '"+E.openWord()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter something new\n\r:","");
if(newName.length()>0)
E.setExitParams(E.doorName(),E.closeWord(),newName,E.closedText());
else
mob.tell("(no change)");
}
protected void genSubOps(MOB mob, Area A, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String newName="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.length()>0))
{
mob.tell(showNumber+". Area staff names: "+A.getSubOpList());
if((showFlag!=showNumber)&&(showFlag>-999)) return;
newName=mob.session().prompt("Enter a name to add or remove\n\r:","");
if(newName.length()>0)
{
if(A.amISubOp(newName))
{
A.delSubOp(newName);
mob.tell("Staff removed.");
}
else
if(CMLib.database().DBUserSearch(null,newName))
{
A.addSubOp(newName);
mob.tell("Staff added.");
}
else
mob.tell("'"+newName+"' is not recognized as a valid user name.");
}
}
}
protected void genParentAreas(MOB mob, Area A, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String newArea="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newArea.length()>0))
{
mob.tell(showNumber+". Parent Areas: "+A.getParentsList());
if((showFlag!=showNumber)&&(showFlag>-999)) return;
newArea=mob.session().prompt("Enter an area name to add or remove\n\r:","");
if(newArea.length()>0)
{
Area lookedUp=CMLib.map().getArea(newArea);
if(lookedUp!=null)
{
if (lookedUp.isChild(A))
{
// this new area is already a parent to A,
// they must want it removed
A.removeParent(lookedUp);
lookedUp.removeChild(A);
mob.tell("Enter an area name to add or remove\n\r:");
}
else
{
if(A.canParent(lookedUp))
{
A.addParent(lookedUp);
lookedUp.addChild(A);
mob.tell("Area '"+lookedUp.Name()+"' added.");
}
else
{
mob.tell("Area '"+lookedUp.Name()+"" +"' cannot be added because this would create a circular reference.");
}
}
}
else
mob.tell("'"+newArea+"' is not recognized as a valid area name.");
}
}
}
protected void genChildAreas(MOB mob, Area A, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String newArea="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newArea.length()>0))
{
mob.tell(showNumber+". Area Children: "+A.getChildrenList());
if((showFlag!=showNumber)&&(showFlag>-999)) return;
newArea=mob.session().prompt("Enter an area name to add or remove\n\r:","");
if(newArea.length()>0)
{
Area lookedUp=CMLib.map().getArea(newArea);
if(lookedUp!=null)
{
if (lookedUp.isParent(A))
{
// this area is already a child to A, they must want it removed
A.removeChild(lookedUp);
lookedUp.removeParent(A);
mob.tell("Enter an area name to add or remove\n\r:");
}
else
{
if(A.canChild(lookedUp))
{
A.addChild(lookedUp);
lookedUp.addParent(A);
mob.tell("Area '"+ lookedUp.Name()+"' added.");
}
else
{
mob.tell("Area '"+ lookedUp.Name()+"" +"' cannot be added because this would create a circular reference.");
}
}
}
else
mob.tell("'"+newArea+"' is not recognized as a valid area name.");
}
}
}
protected void genCloseWord(MOB mob, Exit E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Close Word: '"+E.closeWord()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter something new\n\r:","");
if(newName.length()>0)
E.setExitParams(E.doorName(),newName,E.openWord(),E.closedText());
else
mob.tell("(no change)");
}
protected void genExitMisc(MOB mob, Exit E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if(E.hasALock())
{
E.setReadable(false);
mob.tell(showNumber+". Assigned Key Item: '"+E.keyName()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter something new (null=blank)\n\r:","");
if(newName.equalsIgnoreCase("null"))
E.setKeyName("");
else
if(newName.length()>0)
E.setKeyName(newName);
else
mob.tell("(no change)");
}
else
{
if((showFlag!=showNumber)&&(showFlag>-999))
{
if(!E.isReadable())
mob.tell(showNumber+". Door not is readable.");
else
mob.tell(showNumber+". Door is readable: "+E.readableText());
return;
}
else
if(genGenericPrompt(mob,"Is this door ",E.isReadable()))
{
E.setReadable(true);
mob.tell("\n\rText: '"+E.readableText()+"'.");
String newName=mob.session().prompt("Enter something new (null=blank)\n\r:","");
if(newName.equalsIgnoreCase("null"))
E.setReadableText("");
else
if(newName.length()>0)
E.setReadableText(newName);
else
mob.tell("(no change)");
}
else
E.setReadable(false);
}
}
protected void genReadable1(MOB mob, Item E, int showNumber, int showFlag)
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if((E instanceof Wand)
||(E instanceof SpellHolder)
||(E instanceof Light)
||(E instanceof Container)
||(E instanceof Ammunition)
||((E instanceof ClanItem)
&&((((ClanItem)E).ciType()==ClanItem.CI_GATHERITEM)
||(((ClanItem)E).ciType()==ClanItem.CI_CRAFTITEM)
||(((ClanItem)E).ciType()==ClanItem.CI_SPECIALAPRON)))
||(E instanceof Key))
CMLib.flags().setReadable(E,false);
else
if((CMClass.classID(E).endsWith("Readable"))
||(E instanceof Recipe)
||(E instanceof com.planet_ink.coffee_mud.Items.interfaces.Map))
CMLib.flags().setReadable(E,true);
else
if((showFlag!=showNumber)&&(showFlag>-999))
mob.tell(showNumber+". Item is readable: "+CMLib.flags().isReadable(E)+"");
else
CMLib.flags().setReadable(E,genGenericPrompt(mob,showNumber+". Is this item readable",CMLib.flags().isReadable(E)));
}
protected void genReadable2(MOB mob, Item E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if((CMLib.flags().isReadable(E))
||(E instanceof SpellHolder)
||(E instanceof Ammunition)
||(E instanceof Recipe)
||(E instanceof Exit)
||(E instanceof Wand)
||(E instanceof ClanItem)
||(E instanceof Light)
||(E instanceof Key))
{
boolean ok=false;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
if(CMClass.classID(E).endsWith("SuperPill"))
{
mob.tell(showNumber+". Assigned Spell or Parameters: '"+E.readableText()+"'.");
ok=true;
}
else
if(E instanceof SpellHolder)
mob.tell(showNumber+". Assigned Spell(s) ( ';' delimited)\n: '"+E.readableText()+"'.");
else
if(E instanceof Ammunition)
{
mob.tell(showNumber+". Ammunition type: '"+E.readableText()+"'.");
ok=true;
}
else
if(E instanceof Exit)
{
mob.tell(showNumber+". Assigned Room IDs: '"+E.readableText()+"'.");
ok=true;
}
else
if(E instanceof Wand)
mob.tell(showNumber+". Assigned Spell Name: '"+E.readableText()+"'.");
else
if(E instanceof Key)
{
mob.tell(showNumber+". Assigned Key Code: '"+E.readableText()+"'.");
ok=true;
}
else
if(E instanceof com.planet_ink.coffee_mud.Items.interfaces.Map)
{
mob.tell(showNumber+". Assigned Map Area(s): '"+E.readableText()+"'.");
ok=true;
}
else
if(E instanceof Light)
{
mob.tell(showNumber+". Light duration (before burn out): '"+CMath.s_int(E.readableText())+"'.");
ok=true;
}
else
{
mob.tell(showNumber+". Assigned Read Text: '"+E.readableText()+"'.");
ok=true;
}
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=null;
if((E instanceof Wand)
||((E instanceof SpellHolder)&&(!(CMClass.classID(E).endsWith("SuperPill")))))
{
newName=mob.session().prompt("Enter something new (?)\n\r:","");
if(newName.length()==0)
ok=true;
else
{
if(newName.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
if(E instanceof Wand)
{
if(CMClass.getAbility(newName)!=null)
ok=true;
else
mob.tell("'"+newName+"' is not recognized. Try '?'.");
}
else
if(E instanceof SpellHolder)
{
String oldName=newName;
if(!newName.endsWith(";")) newName+=";";
int x=newName.indexOf(";");
while(x>=0)
{
String spellName=newName.substring(0,x).trim();
if(CMClass.getAbility(spellName)!=null)
ok=true;
else
{
mob.tell("'"+spellName+"' is not recognized. Try '?'.");
break;
}
newName=newName.substring(x+1).trim();
x=newName.indexOf(";");
}
newName=oldName;
}
}
}
else
newName=mob.session().prompt("Enter something new (null=blank)\n\r:","");
if(ok)
{
if(newName.equalsIgnoreCase("null"))
E.setReadableText("");
else
if(newName.length()>0)
E.setReadableText(newName);
else
mob.tell("(no change)");
}
}
}
else
if(E instanceof Drink)
{
mob.session().println(showNumber+". Current liquid type: "+RawMaterial.RESOURCE_DESCS[((Drink)E).liquidType()&RawMaterial.RESOURCE_MASK]);
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean q=false;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!q))
{
String newType=mob.session().prompt("Enter a new type (?)\n\r:",RawMaterial.RESOURCE_DESCS[((Drink)E).liquidType()&RawMaterial.RESOURCE_MASK]);
if(newType.equals("?"))
{
StringBuffer say=new StringBuffer("");
for(int i=0;i<RawMaterial.RESOURCE_DESCS.length-1;i++)
if((RawMaterial.RESOURCE_DATA[i][0]&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_LIQUID)
say.append(RawMaterial.RESOURCE_DESCS[i]+", ");
mob.tell(say.toString().substring(0,say.length()-2));
q=false;
}
else
{
q=true;
int newValue=-1;
for(int i=0;i<RawMaterial.RESOURCE_DESCS.length-1;i++)
if((RawMaterial.RESOURCE_DATA[i][0]&RawMaterial.MATERIAL_MASK)==RawMaterial.MATERIAL_LIQUID)
if(newType.equalsIgnoreCase(RawMaterial.RESOURCE_DESCS[i]))
newValue=RawMaterial.RESOURCE_DATA[i][0];
if(newValue>=0)
((Drink)E).setLiquidType(newValue);
else
mob.tell("(no change)");
}
}
}
}
protected void genRecipe(MOB mob, Recipe E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String prompt="Recipe Data ";
mob.tell(showNumber+". "+prompt+": "+E.getCommonSkillID()+".");
mob.tell(CMStrings.padRight(" ",(""+showNumber).length()+2+prompt.length())+": "+CMStrings.replaceAll(E.getRecipeCodeLine(),"\t",",")+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
while(!mob.session().killFlag())
{
String newName=mob.session().prompt("Enter new skill id (?)\n\r:","");
if(newName.equalsIgnoreCase("?"))
{
StringBuffer str=new StringBuffer("");
Ability A=null;
for(Enumeration e=CMClass.abilities();e.hasMoreElements();)
{
A=(Ability)e.nextElement();
if(((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_COMMON_SKILL)
&&((A.classificationCode()&Ability.ALL_DOMAINS)==Ability.DOMAIN_CRAFTINGSKILL))
str.append(A.ID()+"\n\r");
}
mob.tell("\n\rCommon Skills:\n\r"+str.toString()+"\n\r");
}
else
if((newName.length()>0)
&&(CMClass.getAbility(newName)!=null)
&&((CMClass.getAbility(newName).classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_COMMON_SKILL))
{
E.setCommonSkillID(CMClass.getAbility(newName).ID());
break;
}
else
if(newName.length()>0)
mob.tell("'"+newName+"' is not a valid common skill. Try ?.");
else
{
mob.tell("(no change)");
break;
}
}
String newName=mob.session().prompt("Enter new data line\n\r:","");
if(newName.length()>0)
E.setRecipeCodeLine(CMStrings.replaceAll(newName,",","\t"));
else
mob.tell("(no change)");
}
protected void genGettable(MOB mob, Item E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if(E instanceof Potion)
((Potion)E).setDrunk(false);
String c="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!c.equals("\n")))
{
mob.session().println(showNumber+". A) Is Gettable : "+(!CMath.bset(E.baseEnvStats().sensesMask(),EnvStats.SENSE_ITEMNOTGET)));
mob.session().println(" B) Is Droppable : "+(!CMath.bset(E.baseEnvStats().sensesMask(),EnvStats.SENSE_ITEMNODROP)));
mob.session().println(" C) Is Removable : "+(!CMath.bset(E.baseEnvStats().sensesMask(),EnvStats.SENSE_ITEMNOREMOVE)));
mob.session().println(" D) Non-Locatable : "+(((E.baseEnvStats().sensesMask()&EnvStats.SENSE_UNLOCATABLE)>0)?"true":"false"));
if(E instanceof Weapon)
mob.session().println(" E) Is Two-Handed : "+E.rawLogicalAnd());
if((showFlag!=showNumber)&&(showFlag>-999)) return;
c=mob.session().choose("Enter one to change, or ENTER when done:","ABCDE\n","\n").toUpperCase();
switch(Character.toUpperCase(c.charAt(0)))
{
case 'A': CMLib.flags().setGettable(E,(CMath.bset(E.baseEnvStats().sensesMask(),EnvStats.SENSE_ITEMNOTGET))); break;
case 'B': CMLib.flags().setDroppable(E,(CMath.bset(E.baseEnvStats().sensesMask(),EnvStats.SENSE_ITEMNODROP))); break;
case 'C': CMLib.flags().setRemovable(E,(CMath.bset(E.baseEnvStats().sensesMask(),EnvStats.SENSE_ITEMNOREMOVE))); break;
case 'D': if((E.baseEnvStats().sensesMask()&EnvStats.SENSE_UNLOCATABLE)>0)
E.baseEnvStats().setSensesMask(E.baseEnvStats().sensesMask()-EnvStats.SENSE_UNLOCATABLE);
else
E.baseEnvStats().setSensesMask(E.baseEnvStats().sensesMask()|EnvStats.SENSE_UNLOCATABLE);
break;
case 'E': if(E instanceof Weapon)
E.setRawLogicalAnd(!E.rawLogicalAnd());
break;
}
}
}
protected void toggleDispositionMask(EnvStats E, int mask)
{
int current=E.disposition();
if((current&mask)==0)
E.setDisposition(current|mask);
else
E.setDisposition(current&((int)(EnvStats.ALLMASK-mask)));
}
protected void genDisposition(MOB mob, EnvStats E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
int[] disps={EnvStats.IS_INVISIBLE,
EnvStats.IS_HIDDEN,
EnvStats.IS_NOT_SEEN,
EnvStats.IS_BONUS,
EnvStats.IS_GLOWING,
EnvStats.IS_LIGHTSOURCE,
EnvStats.IS_FLYING,
EnvStats.IS_CLIMBING,
EnvStats.IS_SNEAKING,
EnvStats.IS_SWIMMING,
EnvStats.IS_EVIL,
EnvStats.IS_GOOD};
String[] briefs={"invisible",
"hide",
"unseen",
"magical",
"glowing",
"lightsrc",
"fly",
"climb",
"sneak",
"swimmer",
"evil",
"good"};
if((showFlag!=showNumber)&&(showFlag>-999))
{
StringBuffer buf=new StringBuffer(showNumber+". Dispositions: ");
for(int i=0;i<disps.length;i++)
{
int mask=disps[i];
if((E.disposition()&mask)!=0)
buf.append(briefs[i]+" ");
}
mob.tell(buf.toString());
return;
}
String c="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!c.equals("\n")))
{
char letter='A';
String letters="";
for(int i=0;i<disps.length;i++)
{
int mask=disps[i];
for(int num=0;num<EnvStats.dispositionsDesc.length;num++)
if(mask==CMath.pow(2,num))
{
mob.session().println(" "+letter+") "+CMStrings.padRight(EnvStats.dispositionsDesc[num],20)+":"+((E.disposition()&mask)!=0));
letters+=letter;
break;
}
letter++;
}
c=mob.session().choose("Enter one to change, or ENTER when done: ",letters+"\n","\n").toUpperCase();
letter='A';
for(int i=0;i<disps.length;i++)
{
int mask=disps[i];
if(letter==Character.toUpperCase(c.charAt(0)))
{
toggleDispositionMask(E,mask);
break;
}
letter++;
}
}
}
public boolean genGenericPrompt(MOB mob, String prompt, boolean val)
{
try
{
prompt=CMStrings.padRight(prompt,35);
if(val)
prompt+="(Y/n): ";
else
prompt+="(y/N): ";
return mob.session().confirm(prompt,val?"Y":"N");
}
catch(IOException e)
{
return val;
}
}
protected void toggleSensesMask(EnvStats E, int mask)
{
int current=E.sensesMask();
if((current&mask)==0)
E.setSensesMask(current|mask);
else
E.setSensesMask(current&((int)(EnvStats.ALLMASK-mask)));
}
protected void toggleClimateMask(Area A, int mask)
{
int current=A.climateType();
if((current&mask)==0)
A.setClimateType(current|mask);
else
A.setClimateType(current&((int)(EnvStats.ALLMASK-mask)));
}
protected void genClimateType(MOB mob, Area A, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String c="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!c.equals("\n")))
{
mob.session().println(""+showNumber+". Climate:");
mob.session().println(" R) Wet and Rainy : "+((A.climateType()&Area.CLIMASK_WET)>0));
mob.session().println(" H) Excessively hot : "+((A.climateType()&Area.CLIMASK_HOT)>0));
mob.session().println(" C) Excessively cold : "+((A.climateType()&Area.CLIMASK_COLD)>0));
mob.session().println(" W) Very windy : "+((A.climateType()&Area.CLIMATE_WINDY)>0));
mob.session().println(" D) Very dry : "+((A.climateType()&Area.CLIMASK_DRY)>0));
if((showFlag!=showNumber)&&(showFlag>-999)) return;
c=mob.session().choose("Enter one to change, or ENTER when done: ","RHCWD\n","\n").toUpperCase();
switch(c.charAt(0))
{
case 'C': toggleClimateMask(A,Area.CLIMASK_COLD); break;
case 'H': toggleClimateMask(A,Area.CLIMASK_HOT); break;
case 'R': toggleClimateMask(A,Area.CLIMASK_WET); break;
case 'W': toggleClimateMask(A,Area.CLIMATE_WINDY); break;
case 'D': toggleClimateMask(A,Area.CLIMASK_DRY); break;
}
}
}
protected void genCharStats(MOB mob, CharStats E)
throws IOException
{
String c="Q";
String commandStr="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()=+-";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!c.equals("\n")))
{
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
if(i!=CharStats.STAT_GENDER)
mob.session().println(" "+commandStr.charAt(i)+") "+CMStrings.padRight(CharStats.STAT_DESCS[i],20)+":"+((E.getStat(i))));
c=mob.session().choose("Enter one to change, or ENTER when done: ",commandStr.substring(0,CharStats.STAT_DESCS.length)+"\n","\n").toUpperCase();
int num=commandStr.indexOf(c);
if(num>=0)
{
String newVal=mob.session().prompt("Enter a new value: "+CharStats.STAT_DESCS[num]+" ("+E.getStat(num)+"): ","");
if(((CMath.s_int(newVal)>0)||(newVal.trim().equals("0")))
&&(num!=CharStats.STAT_GENDER))
E.setStat(num,CMath.s_int(newVal));
else
mob.tell("(no change)");
}
}
}
protected void genCharStats(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if((showFlag!=showNumber)&&(showFlag>-999))
{
StringBuffer buf=new StringBuffer(showNumber+". Stats: ");
for(int i=0;i<CharStats.NUM_BASE_STATS;i++)
buf.append(CharStats.STAT_ABBR[i]+":"+E.baseCharStats().getStat(i)+" ");
mob.tell(buf.toString());
return;
}
String c="Q";
String commandStr="ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()=+-";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!c.equals("\n")))
{
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
if(i!=CharStats.STAT_GENDER)
mob.session().println(" "+commandStr.charAt(i)+") "+CMStrings.padRight(CharStats.STAT_DESCS[i],20)+":"+((E.baseCharStats().getStat(i))));
c=mob.session().choose("Enter one to change, or ENTER when done: ",commandStr.substring(0,CharStats.STAT_DESCS.length)+"\n","\n").toUpperCase();
int num=commandStr.indexOf(c);
if(num>=0)
{
String newVal=mob.session().prompt("Enter a new value: "+CharStats.STAT_DESCS[num]+" ("+E.baseCharStats().getStat(num)+"): ","");
if(((CMath.s_int(newVal)>0)||(newVal.trim().equals("0")))
&&(num!=CharStats.STAT_GENDER))
{
E.baseCharStats().setStat(num,CMath.s_int(newVal));
if((num==CharStats.STAT_AGE)&&(E.playerStats()!=null)&&(E.playerStats().getBirthday()!=null))
E.playerStats().getBirthday()[2]=CMClass.globalClock().getYear()-CMath.s_int(newVal);
}
else
mob.tell("(no change)");
}
}
}
protected void genSensesMask(MOB mob, EnvStats E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
int[] senses={EnvStats.CAN_SEE_DARK,
EnvStats.CAN_SEE_HIDDEN,
EnvStats.CAN_SEE_INVISIBLE,
EnvStats.CAN_SEE_SNEAKERS,
EnvStats.CAN_SEE_INFRARED,
EnvStats.CAN_SEE_GOOD,
EnvStats.CAN_SEE_EVIL,
EnvStats.CAN_SEE_BONUS,
EnvStats.CAN_NOT_SPEAK,
EnvStats.CAN_NOT_HEAR,
EnvStats.CAN_NOT_SEE};
String[] briefs={"darkvision",
"hidden",
"invisible",
"sneakers",
"infrared",
"good",
"evil",
"magic",
"MUTE",
"DEAF",
"BLIND"};
if((showFlag!=showNumber)&&(showFlag>-999))
{
StringBuffer buf=new StringBuffer(showNumber+". Senses: ");
for(int i=0;i<senses.length;i++)
{
int mask=senses[i];
if((E.sensesMask()&mask)!=0)
buf.append(briefs[i]+" ");
}
mob.tell(buf.toString());
return;
}
String c="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!c.equals("\n")))
{
char letter='A';
String letters="";
for(int i=0;i<senses.length;i++)
{
int mask=senses[i];
for(int num=0;num<EnvStats.sensesDesc.length;num++)
if(mask==CMath.pow(2,num))
{
letters+=letter;
mob.session().println(" "+letter+") "+CMStrings.padRight(EnvStats.sensesDesc[num],20)+":"+((E.sensesMask()&mask)!=0));
break;
}
letter++;
}
c=mob.session().choose("Enter one to change, or ENTER when done: ",letters+"\n","\n").toUpperCase();
letter='A';
for(int i=0;i<senses.length;i++)
{
int mask=senses[i];
if(letter==Character.toUpperCase(c.charAt(0)))
{
toggleSensesMask(E,mask);
break;
}
letter++;
}
}
}
protected void genDoorsNLocks(MOB mob, Exit E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
boolean HasDoor=E.hasADoor();
boolean Open=E.isOpen();
boolean DefaultsClosed=E.defaultsClosed();
boolean HasLock=E.hasALock();
boolean Locked=E.isLocked();
boolean DefaultsLocked=E.defaultsLocked();
if((showFlag!=showNumber)&&(showFlag>-999)){
mob.tell(showNumber+". Has a door: "+E.hasADoor()
+"\n\r Has a lock : "+E.hasALock()
+"\n\r Open ticks: "+E.openDelayTicks());
return;
}
if(genGenericPrompt(mob,"Has a door",E.hasADoor()))
{
HasDoor=true;
DefaultsClosed=genGenericPrompt(mob,"Defaults closed",E.defaultsClosed());
Open=!DefaultsClosed;
if(genGenericPrompt(mob,"Has a lock",E.hasALock()))
{
HasLock=true;
DefaultsLocked=genGenericPrompt(mob,"Defaults locked",E.defaultsLocked());
Locked=DefaultsLocked;
}
else
{
HasLock=false;
Locked=false;
DefaultsLocked=false;
}
mob.tell("\n\rReset Delay (# ticks): '"+E.openDelayTicks()+"'.");
int newLevel=CMath.s_int(mob.session().prompt("Enter a new delay\n\r:",""));
if(newLevel>0)
E.setOpenDelayTicks(newLevel);
else
mob.tell("(no change)");
}
else
{
HasDoor=false;
Open=true;
DefaultsClosed=false;
HasLock=false;
Locked=false;
DefaultsLocked=false;
}
E.setDoorsNLocks(HasDoor,Open,DefaultsClosed,HasLock,Locked,DefaultsLocked);
}
public String makeContainerTypes(Container E)
{
String canContain=", "+Container.CONTAIN_DESCS[0];
if(E.containTypes()>0)
{
canContain="";
for(int i=0;i<20;i++)
if(CMath.isSet((int)E.containTypes(),i))
canContain+=", "+Container.CONTAIN_DESCS[i+1];
}
return canContain.substring(2);
}
protected void genLidsNLocks(MOB mob, Container E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if((showFlag!=showNumber)&&(showFlag>-999)){
mob.tell(showNumber+". Can contain : "+makeContainerTypes(E)
+"\n\r Has a lid : "+E.hasALid()
+"\n\r Has a lock : "+E.hasALock()
+"\n\r Key name : "+E.keyName());
return;
}
String change="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(change.length()>0))
{
mob.tell("\n\rCan only contain: "+makeContainerTypes(E));
change=mob.session().prompt("Enter a type to add/remove (?)\n\r:","");
if(change.length()==0) break;
int found=-1;
if(change.equalsIgnoreCase("?"))
for(int i=0;i<Container.CONTAIN_DESCS.length;i++)
mob.tell(Container.CONTAIN_DESCS[i]);
else
{
for(int i=0;i<Container.CONTAIN_DESCS.length;i++)
if(Container.CONTAIN_DESCS[i].startsWith(change.toUpperCase()))
found=i;
if(found<0)
mob.tell("Unknown type. Try '?'.");
else
if(found==0)
E.setContainTypes(0);
else
if(CMath.isSet((int)E.containTypes(),found-1))
E.setContainTypes(E.containTypes()-CMath.pow(2,found-1));
else
E.setContainTypes(E.containTypes()|CMath.pow(2,found-1));
}
}
if(genGenericPrompt(mob,"Has a lid " ,E.hasALid()))
{
E.setLidsNLocks(true,false,E.hasALock(),E.isLocked());
if(genGenericPrompt(mob,"Has a lock",E.hasALock()))
{
E.setLidsNLocks(E.hasALid(),E.isOpen(),true,true);
mob.tell("\n\rKey code: '"+E.keyName()+"'.");
String newName=mob.session().prompt("Enter something new\n\r:","");
if(newName.length()>0)
E.setKeyName(newName);
else
mob.tell("(no change)");
}
else
{
E.setKeyName("");
E.setLidsNLocks(E.hasALid(),E.isOpen(),false,false);
}
}
else
{
E.setKeyName("");
E.setLidsNLocks(false,true,false,false);
}
}
protected void genLevel(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{
if(E.baseEnvStats().level()<0) E.baseEnvStats().setLevel(1);
E.baseEnvStats().setLevel(CMLib.english().prompt(mob,E.baseEnvStats().level(),showNumber,showFlag,"Level"));
}
protected void genRejuv(MOB mob, Environmental E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if(E instanceof Item)
mob.tell(showNumber+". Rejuv/Pct: '"+E.baseEnvStats().rejuv()+"' (0=special).");
else
mob.tell(showNumber+". Rejuv Ticks: '"+E.baseEnvStats().rejuv()+"' (0=never).");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String rlevel=mob.session().prompt("Enter new amount\n\r:","");
int newLevel=CMath.s_int(rlevel);
if((newLevel>0)||(rlevel.trim().equals("0")))
{
E.baseEnvStats().setRejuv(newLevel);
if((E.baseEnvStats().rejuv()==0)&&(E instanceof MOB))
{
E.baseEnvStats().setRejuv(Integer.MAX_VALUE);
mob.tell(E.Name()+" will now never rejuvinate.");
}
}
else
mob.tell("(no change)");
}
protected void genUses(MOB mob, Item E, int showNumber, int showFlag) throws IOException
{ E.setUsesRemaining(CMLib.english().prompt(mob,E.usesRemaining(),showNumber,showFlag,"Uses Remaining")); }
protected void genMaxUses(MOB mob, Wand E, int showNumber, int showFlag) throws IOException
{ E.setMaxUses(CMLib.english().prompt(mob,E.maxUses(),showNumber,showFlag,"Maximum Uses")); }
protected void genCondition(MOB mob, Item E, int showNumber, int showFlag) throws IOException
{ E.setUsesRemaining(CMLib.english().prompt(mob,E.usesRemaining(),showNumber,showFlag,"Condition")); }
protected void genMiscSet(MOB mob, Environmental E)
throws IOException
{
if(E instanceof ShopKeeper)
modifyGenShopkeeper(mob,(ShopKeeper)E);
else
if(E instanceof MOB)
{
if(((MOB)E).isMonster())
modifyGenMOB(mob,(MOB)E);
else
modifyPlayer(mob,(MOB)E);
}
else
if((E instanceof Exit)&&(!(E instanceof Item)))
modifyGenExit(mob,(Exit)E);
else
if(E instanceof com.planet_ink.coffee_mud.Items.interfaces.Map)
modifyGenMap(mob,(com.planet_ink.coffee_mud.Items.interfaces.Map)E);
else
if(E instanceof Armor)
modifyGenArmor(mob,(Armor)E);
else
if(E instanceof MusicalInstrument)
modifyGenInstrument(mob,(MusicalInstrument)E);
else
if(E instanceof Food)
modifyGenFood(mob,(Food)E);
else
if((E instanceof Drink)&&(E instanceof Item))
modifyGenDrink(mob,(Drink)E);
else
if(E instanceof Weapon)
modifyGenWeapon(mob,(Weapon)E);
else
if(E instanceof Container)
modifyGenContainer(mob,(Container)E);
else
if(E instanceof Item)
{
if(E.ID().equals("GenWallpaper"))
modifyGenWallpaper(mob,(Item)E);
else
modifyGenItem(mob,(Item)E);
}
}
protected void genMiscText(MOB mob, Environmental E, int showNumber, int showFlag)
throws IOException
{
if(E.isGeneric())
genMiscSet(mob,E);
else
{ E.setMiscText(CMLib.english().prompt(mob,E.text(),showNumber,showFlag,"Misc Text",true,false));}
}
protected void genTitleRoom(MOB mob, LandTitle E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Land plot ID: '"+E.landPropertyID()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newText="?!?!";
while((mob.session()!=null)&&(!mob.session().killFlag())
&&((newText.length()>0)&&(CMLib.map().getRoom(newText)==null)))
{
newText=mob.session().prompt("New Property ID:","");
if((newText.length()==0)
&&(CMLib.map().getRoom(newText)==null)
&&(CMLib.map().getArea(newText)==null))
mob.tell("That property (room ID) doesn't exist!");
}
if(newText.length()>0)
E.setLandPropertyID(newText);
else
mob.tell("(no change)");
}
protected void genAbility(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.baseEnvStats().setAbility(CMLib.english().prompt(mob,E.baseEnvStats().ability(),showNumber,showFlag,"Magical Ability")); }
protected void genCoinStuff(MOB mob, Coins E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Money data: '"+E.getNumberOfCoins()+" x "+CMLib.beanCounter().getDenominationName(E.getCurrency(),E.getDenomination())+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean gocontinue=true;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(gocontinue))
{
gocontinue=false;
String oldCurrency=E.getCurrency();
if(oldCurrency.length()==0) oldCurrency="Default";
oldCurrency=mob.session().prompt("Enter currency code (?):",oldCurrency).trim().toUpperCase();
if(oldCurrency.equalsIgnoreCase("Default"))
{
if(E.getCurrency().length()>0)
E.setCurrency("");
else
mob.tell("(no change)");
}
else
if((oldCurrency.length()==0)||(oldCurrency.equalsIgnoreCase(E.getCurrency())))
mob.tell("(no change)");
else
if(!CMLib.beanCounter().getAllCurrencies().contains(oldCurrency))
{
Vector V=CMLib.beanCounter().getAllCurrencies();
for(int v=0;v<V.size();v++)
if(((String)V.elementAt(v)).length()==0)
V.setElementAt("Default",v);
mob.tell("'"+oldCurrency+"' is not a known currency. Existing currencies include: DEFAULT"+CMParms.toStringList(V));
gocontinue=true;
}
else
E.setCurrency(oldCurrency.toUpperCase().trim());
}
gocontinue=true;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(gocontinue))
{
gocontinue=false;
String newDenom=mob.session().prompt("Enter denomination (?):",""+E.getDenomination()).trim().toUpperCase();
DVector DV=CMLib.beanCounter().getCurrencySet(E.getCurrency());
if((newDenom.length()>0)
&&(!CMath.isDouble(newDenom))
&&(!newDenom.equalsIgnoreCase("?")))
{
double denom=CMLib.english().matchAnyDenomination(E.getCurrency(),newDenom);
if(denom>0.0) newDenom=""+denom;
}
if((newDenom.length()==0)
||(CMath.isDouble(newDenom)
&&(!newDenom.equalsIgnoreCase("?"))
&&(CMath.s_double(newDenom)==E.getDenomination())))
mob.tell("(no change)");
else
if((!CMath.isDouble(newDenom))
||(newDenom.equalsIgnoreCase("?"))
||((DV!=null)&&(!DV.contains(new Double(CMath.s_double(newDenom))))))
{
StringBuffer allDenoms=new StringBuffer("");
for(int i=0;i<DV.size();i++)
allDenoms.append(((Double)DV.elementAt(i,1)).doubleValue()+"("+((String)DV.elementAt(i,2))+"), ");
if(allDenoms.toString().endsWith(", "))
allDenoms=new StringBuffer(allDenoms.substring(0,allDenoms.length()-2));
mob.tell("'"+newDenom+"' is not a defined denomination. Try one of these: "+allDenoms.toString()+".");
gocontinue=true;
}
else
E.setDenomination(CMath.s_double(newDenom));
}
if((mob.session()!=null)&&(!mob.session().killFlag()))
E.setNumberOfCoins(CMath.s_int(mob.session().prompt("Enter stack size\n\r:",""+E.getNumberOfCoins())));
}
protected void genHitPoints(MOB mob, MOB E, int showNumber, int showFlag) throws IOException
{
if(E.isMonster())
E.baseEnvStats().setAbility(CMLib.english().prompt(mob,E.baseEnvStats().ability(),showNumber,showFlag,"Hit Points Bonus Modifier","Hit points = (level*level) + (random*level*THIS)"));
else
E.baseEnvStats().setAbility(CMLib.english().prompt(mob,E.baseEnvStats().ability(),showNumber,showFlag,"Ability -- unused"));
}
protected void genValue(MOB mob, Item E, int showNumber, int showFlag) throws IOException
{ E.setBaseValue(CMLib.english().prompt(mob,E.baseGoldValue(),showNumber,showFlag,"Base Value")); }
protected void genWeight(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.baseEnvStats().setWeight(CMLib.english().prompt(mob,E.baseEnvStats().weight(),showNumber,showFlag,"Weight")); }
protected void genClanItem(MOB mob, ClanItem E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Clan: '"+E.clanID()+"', Type: "+ClanItem.CI_DESC[E.ciType()]+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String clanID=E.clanID();
E.setClanID(mob.session().prompt("Enter a new clan\n\r:",clanID));
if(E.clanID().equals(clanID))
mob.tell("(no change)");
String clanType=ClanItem.CI_DESC[E.ciType()];
String s="?";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(s.equals("?")))
{
s=mob.session().prompt("Enter a new type (?)\n\r:",clanType);
if(s.equalsIgnoreCase("?"))
mob.tell("Types: "+CMParms.toStringList(ClanItem.CI_DESC));
else
if(s.equalsIgnoreCase(clanType))
{
mob.tell("(no change)");
break;
}
else
{
boolean found=false;
for(int i=0;i<ClanItem.CI_DESC.length;i++)
if(ClanItem.CI_DESC[i].equalsIgnoreCase(s))
{ found=true; E.setCIType(i); break;}
if(!found)
{
mob.tell("'"+s+"' is unknown. Try '?'");
s="?";
}
}
}
}
protected void genHeight(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.baseEnvStats().setHeight(CMLib.english().prompt(mob,E.baseEnvStats().height(),showNumber,showFlag,"Height")); }
protected void genSize(MOB mob, Armor E, int showNumber, int showFlag) throws IOException
{ E.baseEnvStats().setHeight(CMLib.english().prompt(mob,E.baseEnvStats().height(),showNumber,showFlag,"Size")); }
protected void genLayer(MOB mob, Armor E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
boolean seeThroughBool=CMath.bset(E.getLayerAttributes(),Armor.LAYERMASK_SEETHROUGH);
boolean multiWearBool=CMath.bset(E.getLayerAttributes(),Armor.LAYERMASK_MULTIWEAR);
String seeThroughStr=(!seeThroughBool)?" (opaque)":" (see-through)";
String multiWearStr=multiWearBool?" (multi)":"";
mob.tell(showNumber+". Layer: '"+E.getClothingLayer()+"'"+seeThroughStr+""+multiWearStr+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
if((mob.session()!=null)&&(!mob.session().killFlag()))
E.setClothingLayer(CMath.s_short(mob.session().prompt("Enter a new layer\n\r:",""+E.getClothingLayer())));
boolean newSeeThrough=seeThroughBool;
if((mob.session()!=null)&&(!mob.session().killFlag()))
newSeeThrough=mob.session().confirm("Is see-through (Y/N)? ",""+seeThroughBool);
boolean multiWear=multiWearBool;
if((mob.session()!=null)&&(!mob.session().killFlag()))
multiWear=mob.session().confirm("Is multi-wear (Y/N)? ",""+multiWearBool);
E.setLayerAttributes((short)0);
E.setLayerAttributes((short)(E.getLayerAttributes()|(newSeeThrough?Armor.LAYERMASK_SEETHROUGH:0)));
E.setLayerAttributes((short)(E.getLayerAttributes()|(multiWear?Armor.LAYERMASK_MULTIWEAR:0)));
}
protected void genCapacity(MOB mob, Container E, int showNumber, int showFlag) throws IOException
{ E.setCapacity(CMLib.english().prompt(mob,E.capacity(),showNumber,showFlag,"Capacity")); }
protected void genAttack(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.baseEnvStats().setAttackAdjustment(CMLib.english().prompt(mob,E.baseEnvStats().attackAdjustment(),showNumber,showFlag,"Attack Adjustment")); }
protected void genDamage(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.baseEnvStats().setDamage(CMLib.english().prompt(mob,E.baseEnvStats().damage(),showNumber,showFlag,"Damage")); }
protected void genBanker1(MOB mob, Banker E, int showNumber, int showFlag) throws IOException
{ E.setCoinInterest(CMLib.english().prompt(mob,E.getCoinInterest(),showNumber,showFlag,"Coin Interest [% per real day]")); }
protected void genBanker2(MOB mob, Banker E, int showNumber, int showFlag) throws IOException
{ E.setItemInterest(CMLib.english().prompt(mob,E.getItemInterest(),showNumber,showFlag,"Item Interest [% per real day]")); }
protected void genBanker3(MOB mob, Banker E, int showNumber, int showFlag) throws IOException
{ E.setBankChain(CMLib.english().prompt(mob,E.bankChain(),showNumber,showFlag,"Bank Chain",false,false)); }
protected void genBanker4(MOB mob, Banker E, int showNumber, int showFlag) throws IOException
{ E.setLoanInterest(CMLib.english().prompt(mob,E.getLoanInterest(),showNumber,showFlag,"Loan Interest [% per mud month]")); }
protected void genSpeed(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{ E.baseEnvStats().setSpeed(CMLib.english().prompt(mob,E.baseEnvStats().speed(),showNumber,showFlag,"Actions/Attacks per tick")); }
protected void genArmor(MOB mob, Environmental E, int showNumber, int showFlag) throws IOException
{
if(E instanceof MOB)
E.baseEnvStats().setArmor(CMLib.english().prompt(mob,E.baseEnvStats().armor(),showNumber,showFlag,"Armor (lower-better)"));
else
E.baseEnvStats().setArmor(CMLib.english().prompt(mob,E.baseEnvStats().armor(),showNumber,showFlag,"Armor (higher-better)"));
}
protected void genMoney(MOB mob, MOB E, int showNumber, int showFlag) throws IOException
{ CMLib.beanCounter().setMoney(E,CMLib.english().prompt(mob,CMLib.beanCounter().getMoney(E),showNumber,showFlag,"Money")); }
protected void genWeaponAmmo(MOB mob, Weapon E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String defaultAmmo=(E.requiresAmmunition())?"Y":"N";
if((showFlag!=showNumber)&&(showFlag>-999))
{
mob.tell(showNumber+". Ammo required: "+E.requiresAmmunition()+" ("+E.ammunitionType()+")");
return;
}
if(mob.session().confirm("Does this weapon require ammunition (default="+defaultAmmo+") (Y/N)?",defaultAmmo))
{
mob.tell("\n\rAmmo type: '"+E.ammunitionType()+"'.");
String newName=mob.session().prompt("Enter a new one\n\r:","");
if(newName.length()>0)
{
E.setAmmunitionType(newName);
mob.tell("(Remember to create a GenAmmunition item with '"+E.ammunitionType()+"' in the secret identity, and the uses remaining above 0!");
}
else
mob.tell("(no change)");
mob.tell("\n\rAmmo capacity: '"+E.ammunitionCapacity()+"'.)");
int newValue=CMath.s_int(mob.session().prompt("Enter a new value\n\r:",""));
if(newValue>0)
E.setAmmoCapacity(newValue);
else
mob.tell("(no change)");
E.setAmmoRemaining(E.ammunitionCapacity());
}
else
{
E.setAmmunitionType("");
E.setAmmoCapacity(0);
}
}
protected void genWeaponRanges(MOB mob, Weapon E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Minimum/Maximum Ranges: "+Math.round(E.minRange())+"/"+Math.round(E.maxRange())+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newMinStr=mob.session().prompt("Enter a new minimum range\n\r:","");
String newMaxStr=mob.session().prompt("Enter a new maximum range\n\r:","");
if((newMinStr.length()==0)&&(newMaxStr.length()==0))
mob.tell("(no change)");
else
{
E.setRanges(CMath.s_int(newMinStr),CMath.s_int(newMaxStr));
if((E.minRange()>E.maxRange())||(E.minRange()<0)||(E.maxRange()<0))
{
mob.tell("(defective entries. resetting.)");
E.setRanges(0,0);
}
}
}
protected void genWeaponType(MOB mob, Weapon E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Weapon Attack Type: '"+Weapon.typeDescription[E.weaponType()]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean q=false;
String sel="NSPBFMR";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!q))
{
String newType=mob.session().choose("Enter a new value\n\r:",sel+"?","");
if(newType.equals("?"))
{
for(int i=0;i<sel.length();i++)
mob.tell(sel.charAt(i)+") "+Weapon.typeDescription[i]);
q=false;
}
else
{
q=true;
int newValue=-1;
if(newType.length()>0)
newValue=sel.indexOf(newType.toUpperCase());
if(newValue>=0)
E.setWeaponType(newValue);
else
mob.tell("(no change)");
}
}
}
protected void genTechLevel(MOB mob, Area A, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Theme setting: '"+Area.THEME_DESCS[A.getTechLevel()]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean q=false;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!q))
{
String newType=mob.session().prompt("Enter a new level (?)\n\r",Area.THEME_DESCS[A.getTechLevel()]);
if(newType.equals("?"))
{
StringBuffer say=new StringBuffer("");
for(int i=1;i<Area.THEME_DESCS.length;i++)
say.append(i+") "+Area.THEME_DESCS[i]+"\n\r");
mob.tell(say.toString());
q=false;
}
else
{
q=true;
int newValue=-1;
if(CMath.s_int(newType)>0)
newValue=CMath.s_int(newType);
else
for(int i=0;i<Area.THEME_DESCS.length;i++)
if(Area.THEME_DESCS[i].toUpperCase().startsWith(newType.toUpperCase()))
newValue=i;
if(newValue>=0)
A.setTechLevel(newValue);
else
mob.tell("(no change)");
}
}
}
protected void genMaterialCode(MOB mob, Item E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Material Type: '"+RawMaterial.RESOURCE_DESCS[E.material()&RawMaterial.RESOURCE_MASK]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean q=false;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!q))
{
String newType=mob.session().prompt("Enter a new material (?)\n\r:",RawMaterial.RESOURCE_DESCS[E.material()&RawMaterial.RESOURCE_MASK]);
if(newType.equals("?"))
{
StringBuffer say=new StringBuffer("");
for(int i=0;i<RawMaterial.RESOURCE_DESCS.length-1;i++)
say.append(RawMaterial.RESOURCE_DESCS[i]+", ");
mob.tell(say.toString().substring(0,say.length()-2));
q=false;
}
else
{
q=true;
int newValue=-1;
for(int i=0;i<RawMaterial.RESOURCE_DESCS.length-1;i++)
if(newType.equalsIgnoreCase(RawMaterial.RESOURCE_DESCS[i]))
newValue=RawMaterial.RESOURCE_DATA[i][0];
if(newValue>=0)
E.setMaterial(newValue);
else
mob.tell("(no change)");
}
}
}
protected void genInstrumentType(MOB mob, MusicalInstrument E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Instrument Type: '"+MusicalInstrument.TYPE_DESC[E.instrumentType()]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean q=false;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!q))
{
String newType=mob.session().prompt("Enter a new type (?)\n\r:",MusicalInstrument.TYPE_DESC[E.instrumentType()]);
if(newType.equals("?"))
{
StringBuffer say=new StringBuffer("");
for(int i=0;i<MusicalInstrument.TYPE_DESC.length-1;i++)
say.append(MusicalInstrument.TYPE_DESC[i]+", ");
mob.tell(say.toString().substring(0,say.length()-2));
q=false;
}
else
{
q=true;
int newValue=-1;
for(int i=0;i<MusicalInstrument.TYPE_DESC.length-1;i++)
if(newType.equalsIgnoreCase(MusicalInstrument.TYPE_DESC[i]))
newValue=i;
if(newValue>=0)
E.setInstrumentType(newValue);
else
mob.tell("(no change)");
}
}
}
protected void genSpecialFaction(MOB mob, MOB E, int showNumber, int showFlag, Faction F)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if(F==null) return;
Faction.FactionRange myFR=CMLib.factions().getRange(F.factionID(),E.fetchFaction(F.factionID()));
mob.tell(showNumber+". "+F.name()+": "+((myFR!=null)?myFR.name():"UNDEFINED")+" ("+E.fetchFaction(F.factionID())+")");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
if(F.ranges()!=null)
for(int v=0;v<F.ranges().size();v++)
{
Faction.FactionRange FR=(Faction.FactionRange)F.ranges().elementAt(v);
mob.tell(CMStrings.padRight(FR.name(),20)+": "+FR.low()+" - "+FR.high()+")");
}
String newOne=mob.session().prompt("Enter a new value\n\r:");
if(CMath.isInteger(newOne))
{
E.addFaction(F.factionID(),CMath.s_int(newOne));
return;
}
for(int v=0;v<F.ranges().size();v++)
{
Faction.FactionRange FR=(Faction.FactionRange)F.ranges().elementAt(v);
if(FR.name().toUpperCase().startsWith(newOne.toUpperCase()))
{
if(FR.low()==F.lowest())
E.addFaction(F.factionID(),FR.low());
else
if(FR.high()==F.highest())
E.addFaction(F.factionID(),FR.high());
else
E.addFaction(F.factionID(),FR.low()+((FR.high()-FR.low())/2));
return;
}
}
mob.tell("(no change)");
}
protected void genFaction(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String newFact="Q";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newFact.length()>0))
{
mob.tell(showNumber+". Factions: "+E.getFactionListing());
if((showFlag!=showNumber)&&(showFlag>-999)) return;
newFact=mob.session().prompt("Enter a faction name to add or remove\n\r:","");
if(newFact.length()>0)
{
Faction lookedUp=CMLib.factions().getFactionByName(newFact);
if(lookedUp==null) lookedUp=CMLib.factions().getFaction(newFact);
if(lookedUp!=null)
{
if (E.fetchFaction(lookedUp.factionID())!=Integer.MAX_VALUE)
{
// this mob already has this faction, they must want it removed
E.removeFaction(lookedUp.factionID());
mob.tell("Faction '"+lookedUp.name() +"' removed.");
}
else
{
int value =new Integer(mob.session().prompt("How much faction ("+lookedUp.findDefault(E)+")?",
new Integer(lookedUp.findDefault(E)).toString())).intValue();
if(value<lookedUp.minimum()) value=lookedUp.minimum();
if(value>lookedUp.maximum()) value=lookedUp.maximum();
E.addFaction(lookedUp.factionID(),value);
mob.tell("Faction '"+lookedUp.name() +"' added.");
}
}
else
mob.tell("'"+newFact+"' is not recognized as a valid faction name or file.");
}
}
}
protected void genGender(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Gender: '"+Character.toUpperCase((char)E.baseCharStats().getStat(CharStats.STAT_GENDER))+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newType=mob.session().choose("Enter a new gender (M/F/N)\n\r:","MFN","");
int newValue=-1;
if(newType.length()>0)
newValue=("MFN").indexOf(newType.trim().toUpperCase());
if(newValue>=0)
{
switch(newValue)
{
case 0:
E.baseCharStats().setStat(CharStats.STAT_GENDER,'M');
break;
case 1:
E.baseCharStats().setStat(CharStats.STAT_GENDER,'F');
break;
case 2:
E.baseCharStats().setStat(CharStats.STAT_GENDER,'N');
break;
}
}
else
mob.tell("(no change)");
}
protected void genWeaponClassification(MOB mob, Weapon E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Weapon Classification: '"+Weapon.classifictionDescription[E.weaponClassification()]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean q=false;
String sel=("ABEFHKPRSDTN");
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!q))
{
String newType=mob.session().choose("Enter a new value (?)\n\r:",sel+"?","");
if(newType.equals("?"))
{
for(int i=0;i<sel.length();i++)
mob.tell(sel.charAt(i)+") "+Weapon.classifictionDescription[i]);
q=false;
}
else
{
q=true;
int newValue=-1;
if(newType.length()>0)
newValue=sel.indexOf(newType.toUpperCase());
if(newValue>=0)
E.setWeaponClassification(newValue);
else
mob.tell("(no change)");
}
}
}
protected void genSecretIdentity(MOB mob, Item E, int showNumber, int showFlag) throws IOException
{ E.setSecretIdentity(CMLib.english().prompt(mob,E.rawSecretIdentity(),showNumber,showFlag,"Secret Identity",true,false)); }
protected void genNourishment(MOB mob, Food E, int showNumber, int showFlag) throws IOException
{ E.setNourishment(CMLib.english().prompt(mob,E.nourishment(),showNumber,showFlag,"Nourishment/Eat")); }
protected void genRace(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String raceID="begin!";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(raceID.length()>0))
{
mob.tell(showNumber+". Race: '"+E.baseCharStats().getMyRace().ID()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
raceID=mob.session().prompt("Enter a new race (?)\n\r:","").trim();
if(raceID.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.races(),-1).toString());
else
if(raceID.length()==0)
mob.tell("(no change)");
else
{
Race R=CMClass.getRace(raceID);
if(R!=null)
{
E.baseCharStats().setMyRace(R);
E.baseCharStats().getMyRace().startRacing(E,false);
E.baseCharStats().getMyRace().setHeightWeight(E.baseEnvStats(),(char)E.baseCharStats().getStat(CharStats.STAT_GENDER));
}
else
mob.tell("Unknown race! Try '?'.");
}
}
}
protected void genCharClass(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String classID="begin!";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(classID.length()>0))
{
StringBuffer str=new StringBuffer("");
for(int c=0;c<E.baseCharStats().numClasses();c++)
{
CharClass C=E.baseCharStats().getMyClass(c);
str.append(C.ID()+"("+E.baseCharStats().getClassLevel(C)+") ");
}
mob.tell(showNumber+". Class: '"+str.toString()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
classID=mob.session().prompt("Enter a class to add/remove(?)\n\r:","").trim();
if(classID.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.charClasses(),-1).toString());
else
if(classID.length()==0)
mob.tell("(no change)");
else
{
CharClass C=CMClass.getCharClass(classID);
if(C!=null)
{
if(E.baseCharStats().getClassLevel(C)>=0)
{
if(E.baseCharStats().numClasses()<2)
mob.tell("Final class may not be removed. To change a class, add the new one first.");
else
{
StringBuffer charClasses=new StringBuffer("");
StringBuffer classLevels=new StringBuffer("");
for(int c=0;c<E.baseCharStats().numClasses();c++)
{
CharClass C2=E.baseCharStats().getMyClass(c);
int L2=E.baseCharStats().getClassLevel(C2);
if(C2!=C)
{
charClasses.append(";"+C2.ID());
classLevels.append(";"+L2);
}
}
E.baseCharStats().setMyClasses(charClasses.toString());
E.baseCharStats().setMyLevels(classLevels.toString());
}
}
else
{
int highLvl=Integer.MIN_VALUE;
CharClass highestC=null;
for(int c=0;c<E.baseCharStats().numClasses();c++)
{
CharClass C2=E.baseCharStats().getMyClass(c);
if(E.baseCharStats().getClassLevel(C2)>highLvl)
{
highestC=C2;
highLvl=E.baseCharStats().getClassLevel(C2);
}
}
E.baseCharStats().setCurrentClass(C);
int levels=E.baseCharStats().combinedSubLevels();
levels=E.baseEnvStats().level()-levels;
String lvl=null;
if(levels>0)
{
lvl=mob.session().prompt("Levels to give this class ("+levels+")\n\r:",""+levels).trim();
int lvl2=CMath.s_int(lvl);
if(lvl2>levels) lvl2=levels;
E.baseCharStats().setClassLevel(C,lvl2);
}
else
{
lvl=mob.session().prompt("Levels to siphon from "+highestC.ID()+" for this class (0)\n\r:",""+0).trim();
int lvl2=CMath.s_int(lvl);
if(lvl2>highLvl) lvl2=highLvl;
E.baseCharStats().setClassLevel(highestC,highLvl-lvl2);
E.baseCharStats().setClassLevel(C,lvl2);
}
}
int levels=E.baseCharStats().combinedSubLevels();
levels=E.baseEnvStats().level()-levels;
C=E.baseCharStats().getCurrentClass();
E.baseCharStats().setClassLevel(C,levels);
}
else
mob.tell("Unknown character class! Try '?'.");
}
}
}
protected void genTattoos(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String tattoostr="";
for(int b=0;b<E.numTattoos();b++)
{
String B=E.fetchTattoo(b);
if(B!=null) tattoostr+=B+", ";
}
if(tattoostr.length()>0)
tattoostr=tattoostr.substring(0,tattoostr.length()-2);
if((tattoostr.length()>60)&&((showFlag!=showNumber)&&(showFlag>-999)))
tattoostr=tattoostr.substring(0,60)+"...";
mob.tell(showNumber+". Tattoos: '"+tattoostr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter a tattoo to add/remove\n\r:","");
if(behave.length()>0)
{
String tattoo=behave;
if((tattoo.length()>0)
&&(Character.isDigit(tattoo.charAt(0)))
&&(tattoo.indexOf(" ")>0)
&&(CMath.isNumber(tattoo.substring(0,tattoo.indexOf(" ")))))
tattoo=tattoo.substring(tattoo.indexOf(" ")+1).trim();
if(E.fetchTattoo(tattoo)!=null)
{
mob.tell(tattoo.trim().toUpperCase()+" removed.");
E.delTattoo(behave);
}
else
{
mob.tell(behave.trim().toUpperCase()+" added.");
E.addTattoo(behave);
}
}
else
mob.tell("(no change)");
}
}
protected void genTitles(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if(E.playerStats()==null) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String behaviorstr="";
for(int b=0;b<E.playerStats().getTitles().size();b++)
{
String B=(String)E.playerStats().getTitles().elementAt(b);
if(B!=null) behaviorstr+=B+", ";
}
if(behaviorstr.length()>0)
behaviorstr=behaviorstr.substring(0,behaviorstr.length()-2);
mob.tell(showNumber+". Titles: '"+behaviorstr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter a title to add or a number to remove\n\r:","");
if(behave.length()>0)
{
String tattoo=behave;
if((tattoo.length()>0)
&&(CMath.isInteger(tattoo))
&&(CMath.s_int(tattoo)>0)
&&(CMath.s_int(tattoo)<=E.playerStats().getTitles().size()))
tattoo=(String)E.playerStats().getTitles().elementAt(CMath.s_int(tattoo)-1);
else
if((tattoo.length()>0)
&&(Character.isDigit(tattoo.charAt(0)))
&&(tattoo.indexOf(" ")>0)
&&(CMath.isNumber(tattoo.substring(0,tattoo.indexOf(" ")))))
tattoo=tattoo.substring(tattoo.indexOf(" ")+1).trim();
if(E.playerStats().getTitles().contains(tattoo))
{
mob.tell(tattoo.trim().toUpperCase()+" removed.");
E.playerStats().getTitles().remove(tattoo);
}
else
{
mob.tell(behave.trim().toUpperCase()+" added.");
E.playerStats().getTitles().addElement(tattoo);
}
}
else
mob.tell("(no change)");
}
}
protected void genExpertises(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String behaviorstr="";
for(int b=0;b<E.numExpertises();b++)
{
String B=E.fetchExpertise(b);
if(B!=null) behaviorstr+=B+", ";
}
if(behaviorstr.length()>0)
behaviorstr=behaviorstr.substring(0,behaviorstr.length()-2);
if((behaviorstr.length()>60)&&((showFlag!=showNumber)&&(showFlag>-999)))
behaviorstr=behaviorstr.substring(0,60)+"...";
mob.tell(showNumber+". Expertises: '"+behaviorstr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter a lesson to add/remove\n\r:","");
if(behave.length()>0)
{
if(E.fetchExpertise(behave)!=null)
{
mob.tell(behave+" removed.");
E.delExpertise(behave);
}
else
{
mob.tell(behave+" added.");
E.addExpertise(behave);
}
}
else
mob.tell("(no change)");
}
}
protected void genSecurity(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
PlayerStats P=E.playerStats();
if(P==null) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String behaviorstr="";
for(int b=0;b<P.getSecurityGroups().size();b++)
{
String B=(String)P.getSecurityGroups().elementAt(b);
if(B!=null) behaviorstr+=B+", ";
}
if(behaviorstr.length()>0)
behaviorstr=behaviorstr.substring(0,behaviorstr.length()-2);
mob.tell(showNumber+". Security Groups: '"+behaviorstr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter a group to add/remove\n\r:","");
if(behave.length()>0)
{
if(P.getSecurityGroups().contains(behave.trim().toUpperCase()))
{
P.getSecurityGroups().remove(behave.trim().toUpperCase());
mob.tell(behave+" removed.");
}
else
if((behave.trim().toUpperCase().startsWith("AREA "))
&&(!CMSecurity.isAllowedAnywhere(mob,behave.trim().toUpperCase().substring(5).trim())))
mob.tell("You do not have clearance to add security code '"+behave+"' to this class.");
else
if((!behave.trim().toUpperCase().startsWith("AREA "))
&&(!CMSecurity.isAllowedEverywhere(mob,behave.trim().toUpperCase())))
mob.tell("You do not have clearance to add security code '"+behave+"' to this class.");
else
{
P.getSecurityGroups().addElement(behave.trim().toUpperCase());
mob.tell(behave+" added.");
}
}
else
mob.tell("(no change)");
}
}
protected void genBehaviors(MOB mob, Environmental E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String behaviorstr="";
for(int b=0;b<E.numBehaviors();b++)
{
Behavior B=E.fetchBehavior(b);
if((B!=null)&&(B.isSavable()))
{
behaviorstr+=B.ID();
if(B.getParms().trim().length()>0)
behaviorstr+="("+B.getParms().trim()+"), ";
else
behaviorstr+=", ";
}
}
if(behaviorstr.length()>0)
behaviorstr=behaviorstr.substring(0,behaviorstr.length()-2);
mob.tell(showNumber+". Behaviors: '"+behaviorstr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter a behavior to add/remove (?)\n\r:","");
if(behave.length()>0)
{
if(behave.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.behaviors(),-1).toString());
else
{
Behavior chosenOne=null;
for(int b=0;b<E.numBehaviors();b++)
{
Behavior B=E.fetchBehavior(b);
if((B!=null)&&(B.ID().equalsIgnoreCase(behave)))
chosenOne=B;
}
if(chosenOne!=null)
{
mob.tell(chosenOne.ID()+" removed.");
E.delBehavior(chosenOne);
}
else
{
chosenOne=CMClass.getBehavior(behave);
if(chosenOne!=null)
{
boolean alreadyHasIt=false;
for(int b=0;b<E.numBehaviors();b++)
{
Behavior B=E.fetchBehavior(b);
if((B!=null)&&(B.ID().equals(chosenOne.ID())))
{
alreadyHasIt=true;
chosenOne=B;
}
}
String parms="?";
while(parms.equals("?"))
{
parms=chosenOne.getParms();
parms=mob.session().prompt("Enter any behavior parameters (?)\n\r:"+parms);
if(parms.equals("?")){ StringBuffer s2=CMLib.help().getHelpText(chosenOne.ID(),mob,true); if(s2!=null) mob.tell(s2.toString()); else mob.tell("no help!");}
}
chosenOne.setParms(parms.trim());
if(!alreadyHasIt)
{
mob.tell(chosenOne.ID()+" added.");
E.addBehavior(chosenOne);
}
else
mob.tell(chosenOne.ID()+" re-added.");
}
else
{
mob.tell("'"+behave+"' is not recognized. Try '?'.");
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genAffects(MOB mob, Environmental E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String affectstr="";
for(int b=0;b<E.numEffects();b++)
{
Ability A=E.fetchEffect(b);
if((A!=null)&&(A.savable()))
{
affectstr+=A.ID();
if(A.text().trim().length()>0)
affectstr+="("+A.text().trim()+"), ";
else
affectstr+=", ";
}
}
if(affectstr.length()>0)
affectstr=affectstr.substring(0,affectstr.length()-2);
mob.tell(showNumber+". Effects: '"+affectstr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter an effect to add/remove (?)\n\r:","");
if(behave.length()>0)
{
if(behave.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
{
Ability chosenOne=null;
for(int a=0;a<E.numEffects();a++)
{
Ability A=E.fetchEffect(a);
if((A!=null)&&(A.ID().equalsIgnoreCase(behave)))
chosenOne=A;
}
if(chosenOne!=null)
{
mob.tell(chosenOne.ID()+" removed.");
E.delEffect(chosenOne);
}
else
{
chosenOne=CMClass.getAbility(behave);
if(chosenOne!=null)
{
String parms="?";
while(parms.equals("?"))
{
parms=chosenOne.text();
parms=mob.session().prompt("Enter any effect parameters (?)\n\r:"+parms);
if(parms.equals("?")){ StringBuffer s2=CMLib.help().getHelpText(chosenOne.ID(),mob,true); if(s2!=null) mob.tell(s2.toString()); else mob.tell("no help!");}
}
chosenOne.setMiscText(parms.trim());
mob.tell(chosenOne.ID()+" added.");
E.addNonUninvokableEffect(chosenOne);
}
else
{
mob.tell("'"+behave+"' is not recognized. Try '?'.");
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genRideable1(MOB mob, Rideable R, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Rideable Type: '"+Rideable.RIDEABLE_DESCS[R.rideBasis()]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean q=false;
String sel="LWACBTEDG";
while(!q)
{
String newType=mob.session().choose("Enter a new value (?)\n\r:",sel+"?","");
if(newType.equals("?"))
{
for(int i=0;i<sel.length();i++)
mob.tell(sel.charAt(i)+") "+Rideable.RIDEABLE_DESCS[i].toLowerCase());
q=false;
}
else
{
q=true;
int newValue=-1;
if(newType.length()>0)
newValue=sel.indexOf(newType.toUpperCase());
if(newValue>=0)
R.setRideBasis(newValue);
else
mob.tell("(no change)");
}
}
}
protected void genRideable2(MOB mob, Rideable E, int showNumber, int showFlag) throws IOException
{ E.setRiderCapacity(CMLib.english().prompt(mob,E.riderCapacity(),showNumber,showFlag,"Number of MOBs held")); }
protected void genShopkeeper1(MOB mob, ShopKeeper E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Shopkeeper type: '"+E.storeKeeperString()+"'.");
StringBuffer buf=new StringBuffer("");
StringBuffer codes=new StringBuffer("");
String codeStr="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if(E instanceof Banker)
{
int r=ShopKeeper.DEAL_BANKER;
char c=codeStr.charAt(r);
codes.append(c);
buf.append(c+") "+ShopKeeper.DEAL_DESCS[r]+"\n\r");
r=ShopKeeper.DEAL_CLANBANKER;
c=codeStr.charAt(r);
codes.append(c);
buf.append(c+") "+ShopKeeper.DEAL_DESCS[r]+"\n\r");
}
else
if(E instanceof PostOffice)
{
int r=ShopKeeper.DEAL_POSTMAN;
char c=codeStr.charAt(r);
codes.append(c);
buf.append(c+") "+ShopKeeper.DEAL_DESCS[r]+"\n\r");
r=ShopKeeper.DEAL_CLANPOSTMAN;
c=codeStr.charAt(r);
codes.append(c);
buf.append(c+") "+ShopKeeper.DEAL_DESCS[r]+"\n\r");
}
else
if(E instanceof Auctioneer)
{
int r=ShopKeeper.DEAL_AUCTIONEER;
char c=codeStr.charAt(r);
codes.append(c);
buf.append(c+") "+ShopKeeper.DEAL_DESCS[r]+"\n\r");
r=ShopKeeper.DEAL_AUCTIONEER;
c=codeStr.charAt(r);
codes.append(c);
buf.append(c+") "+ShopKeeper.DEAL_DESCS[r]+"\n\r");
}
else
for(int r=0;r<ShopKeeper.DEAL_DESCS.length;r++)
{
if((r!=ShopKeeper.DEAL_CLANBANKER)
&&(r!=ShopKeeper.DEAL_BANKER)
&&(r!=ShopKeeper.DEAL_CLANPOSTMAN)
&&(r!=ShopKeeper.DEAL_POSTMAN))
{
char c=codeStr.charAt(r);
codes.append(c);
buf.append(c+") "+ShopKeeper.DEAL_DESCS[r]+"\n\r");
}
}
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newType=mob.session().choose(buf.toString()+"Enter a new value\n\r: ",codes.toString(),"");
int newValue=-1;
if(newType.length()>0)
newValue=codeStr.indexOf(newType.toUpperCase());
if(newValue>=0)
{
boolean reexamine=(E.whatIsSold()!=newValue);
E.setWhatIsSold(newValue);
if(reexamine)
{
Vector V=E.getShop().getStoreInventory();
for(int b=0;b<V.size();b++)
if(!E.doISellThis((Environmental)V.elementAt(b)))
E.getShop().delAllStoreInventory((Environmental)V.elementAt(b),E.whatIsSold());
}
}
}
protected void genShopkeeper2(MOB mob, ShopKeeper E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String itemstr="NO";
while(itemstr.length()>0)
{
String inventorystr="";
Vector V=E.getShop().getStoreInventory();
for(int b=0;b<V.size();b++)
{
Environmental E2=(Environmental)V.elementAt(b);
if(E2.isGeneric())
inventorystr+=E2.name()+" ("+E.getShop().numberInStock(E2)+"), ";
else
inventorystr+=CMClass.classID(E2)+" ("+E.getShop().numberInStock(E2)+"), ";
}
if(inventorystr.length()>0)
inventorystr=inventorystr.substring(0,inventorystr.length()-2);
mob.tell(showNumber+". Inventory: '"+inventorystr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
itemstr=mob.session().prompt("Enter something to add/remove (?)\n\r:","");
if(itemstr.length()>0)
{
if(itemstr.equalsIgnoreCase("?"))
{
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
mob.tell(CMLib.lister().reallyList(CMClass.armor(),-1).toString());
mob.tell(CMLib.lister().reallyList(CMClass.weapons(),-1).toString());
mob.tell(CMLib.lister().reallyList(CMClass.miscMagic(),-1).toString());
mob.tell(CMLib.lister().reallyList(CMClass.miscTech(),-1).toString());
mob.tell(CMLib.lister().reallyList(CMClass.clanItems(),-1).toString());
mob.tell(CMLib.lister().reallyList(CMClass.basicItems(),-1).toString());
mob.tell(CMLib.lister().reallyList(CMClass.mobTypes(),-1).toString());
mob.tell("* Plus! Any items on the ground.");
mob.tell("* Plus! Any mobs hanging around in the room.");
}
else
{
Environmental item=E.getShop().getStock(itemstr,null,E.whatIsSold(),null);
if(item!=null)
{
mob.tell(item.ID()+" removed.");
E.getShop().delAllStoreInventory((Environmental)item.copyOf(),E.whatIsSold());
}
else
{
item=CMClass.getUnknown(itemstr);
if((item==null)&&(mob.location()!=null))
{
Room R=mob.location();
item=R.fetchItem(null,itemstr);
if(item==null)
{
item=R.fetchInhabitant(itemstr);
if((item instanceof MOB)&&(!((MOB)item).isMonster()))
item=null;
}
}
if(item!=null)
{
item=(Environmental)item.copyOf();
item.recoverEnvStats();
boolean ok=E.doISellThis(item);
if((item instanceof Ability)
&&((E.whatIsSold()==ShopKeeper.DEAL_TRAINER)||(E.whatIsSold()==ShopKeeper.DEAL_CASTER)))
ok=true;
else
if(E.whatIsSold()==ShopKeeper.DEAL_INVENTORYONLY)
ok=true;
if(!ok)
{
mob.tell("The shopkeeper does not sell that.");
}
else
{
boolean alreadyHasIt=false;
if(E.getShop().doIHaveThisInStock(item.Name(),null,E.whatIsSold(),null))
alreadyHasIt=true;
if(!alreadyHasIt)
{
mob.tell(item.ID()+" added.");
int num=1;
if(!(item instanceof Ability))
num=CMath.s_int(mob.session().prompt("How many? :",""));
int price=CMath.s_int(mob.session().prompt("At what price? :",""));
E.getShop().addStoreInventory(item,num,price,E);
}
}
}
else
{
mob.tell("'"+itemstr+"' is not recognized. Try '?'.");
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genEconomics1(MOB mob, Economics E, int showNumber, int showFlag) throws IOException
{ E.setPrejudiceFactors(CMLib.english().prompt(mob,E.prejudiceFactors(),showNumber,showFlag,"Prejudice",true,false)); }
protected void genEconomics2(MOB mob, Economics E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String header=showNumber+". Item Pricing Factors: ";
String[] prics=E.itemPricingAdjustments();
if((showFlag!=showNumber)&&(showFlag>-999))
{
if(prics.length<1)
mob.tell(header+"''.");
else
if(prics.length==1)
mob.tell(header+"'"+prics[0]+"'.");
else
mob.tell(header+prics.length+" defined..");
return;
}
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
mob.tell(header+"\n\r");
for(int p=0;p<prics.length;p++)
mob.tell(CMStrings.SPACES.substring(0,header.length()-3)
+(p+1)+") "+prics[p]+"\n\r");
String newValue=mob.session().prompt("Enter # to remove, or A to add:\n\r:","");
if(CMath.isInteger(newValue))
{
int x=CMath.s_int(newValue);
if((x>0)&&(x<=prics.length))
{
String[] newPrics=new String[prics.length-1];
int y=0;
for(int i=0;i<prics.length;i++)
if(i!=(x-1))
newPrics[y++]=prics[i];
prics=newPrics;
}
}
else
if(newValue.toUpperCase().startsWith("A"))
{
double dbl=CMath.s_double(mob.session().prompt("Enter a price multiplier between 0.0 and X.Y\n\r: "));
String mask="?";
while(mask.equals("?"))
{
mask=mob.session().prompt("Now enter a mask that describes the item (? for syntax)\n\r: ");
if(mask.equals("?"))
mob.tell(CMLib.masking().maskHelp("\n\r","disallow"));
}
String[] newPrics=new String[prics.length+1];
for(int i=0;i<prics.length;i++)
newPrics[i]=prics[i];
newPrics[prics.length]=dbl+" "+mask;
prics=newPrics;
}
else
{
mob.tell("(no change)");
break;
}
}
E.setItemPricingAdjustments(prics);
}
protected void genAreaBlurbs(MOB mob, Area E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String header=showNumber+". Area Blurb Flags: ";
if((showFlag!=showNumber)&&(showFlag>-999))
{
int numFlags=E.numBlurbFlags();
if(numFlags<1)
mob.tell(header+"''.");
else
if(numFlags==1)
mob.tell(header+"'"+E.getBlurbFlag(0)+": "+E.getBlurbFlag(E.getBlurbFlag(0))+"'.");
else
mob.tell(header+numFlags+" defined..");
return;
}
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
mob.tell(header+"\n\r");
for(int p=0;p<E.numBlurbFlags();p++)
mob.tell((E.getBlurbFlag(p))+": "+E.getBlurbFlag(E.getBlurbFlag(p)));
String newValue=mob.session().prompt("Enter flag to remove, or A to add:\n\r:","");
if(E.getBlurbFlag(newValue.toUpperCase().trim())!=null)
{
E.delBlurbFlag(newValue.toUpperCase().trim());
mob.tell(newValue.toUpperCase().trim()+" removed");
}
else
if(newValue.toUpperCase().equals("A"))
{
String flag=mob.session().prompt("Enter a new flag: ");
if(flag.trim().length()==0) continue;
String desc=mob.session().prompt("Enter a flag blurb (or nothing): ");
E.addBlurbFlag((flag.toUpperCase().trim()+" "+desc).trim());
mob.tell(flag.toUpperCase().trim()+" added");
}
else
if(newValue.length()==0)
{
mob.tell("(no change)");
break;
}
}
}
protected void genEconomics3(MOB mob, Economics E, int showNumber, int showFlag) throws IOException
{ E.setBudget(CMLib.english().prompt(mob,E.budget(),showNumber,showFlag,"Budget",true,false)); }
protected void genEconomics4(MOB mob, Economics E, int showNumber, int showFlag) throws IOException
{ E.setDevalueRate(CMLib.english().prompt(mob,E.devalueRate(),showNumber,showFlag,"Devaluation rate(s)",true,false)); }
protected void genEconomics5(MOB mob, Economics E, int showNumber, int showFlag) throws IOException
{ E.setInvResetRate(CMLib.english().prompt(mob,E.invResetRate(),showNumber,showFlag,"Inventory reset rate [ticks]")); }
protected void genEconomics6(MOB mob, Economics E, int showNumber, int showFlag) throws IOException
{ E.setIgnoreMask(CMLib.english().prompt(mob,E.ignoreMask(),showNumber,showFlag,"Ignore Mask",true,false)); }
protected void genAbilities(MOB mob, MOB E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String abilitiestr="";
for(int a=0;a<E.numLearnedAbilities();a++)
{
Ability A=E.fetchAbility(a);
if((A!=null)&&(A.savable()))
abilitiestr+=A.ID()+", ";
}
if(abilitiestr.length()>0)
abilitiestr=abilitiestr.substring(0,abilitiestr.length()-2);
if((abilitiestr.length()>60)&&((showFlag!=showNumber)&&(showFlag>-999)))
abilitiestr=abilitiestr.substring(0,60)+"...";
mob.tell(showNumber+". Abilities: '"+abilitiestr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter an ability to add/remove (?)\n\r:","");
if(behave.length()>0)
{
if(behave.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
{
Ability chosenOne=null;
for(int a=0;a<E.numLearnedAbilities();a++)
{
Ability A=E.fetchAbility(a);
if((A!=null)&&(A.ID().equalsIgnoreCase(behave)))
chosenOne=A;
}
if(chosenOne!=null)
{
mob.tell(chosenOne.ID()+" removed.");
E.delAbility(chosenOne);
if(E.fetchEffect(chosenOne.ID())!=null)
E.delEffect(E.fetchEffect(chosenOne.ID()));
}
else
{
chosenOne=CMClass.getAbility(behave);
if(chosenOne!=null)
{
boolean alreadyHasIt=(E.fetchAbility(chosenOne.ID())!=null);
if(!alreadyHasIt)
mob.tell(chosenOne.ID()+" added.");
else
mob.tell(chosenOne.ID()+" re-added.");
if(!alreadyHasIt)
{
chosenOne=(Ability)chosenOne.copyOf();
E.addAbility(chosenOne);
chosenOne.setProficiency(50);
chosenOne.autoInvocation(mob);
}
}
else
{
mob.tell("'"+behave+"' is not recognized. Try '?'.");
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genClanMembers(MOB mob, Clan E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
DVector members=E.getMemberList();
DVector membersCopy=members.copyOf();
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String memberStr="";
for(int m=0;m<members.size();m++)
memberStr+=((String)members.elementAt(m,1))+" ("+CMLib.clans().getRoleName(E.getGovernment(),((Integer)members.elementAt(m,2)).intValue(),true,false)+"), ";
if(memberStr.length()>0)
memberStr=memberStr.substring(0,memberStr.length()-2);
mob.tell(showNumber+". Clan Members : '"+memberStr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter a name to add/remove\n\r:","");
if(behave.length()>0)
{
int chosenOne=-1;
for(int m=0;m<members.size();m++)
if(behave.equalsIgnoreCase((String)members.elementAt(m,1)))
chosenOne=m;
if(chosenOne>=0)
{
mob.tell((String)members.elementAt(chosenOne,1)+" removed.");
members.removeElementAt(chosenOne);
}
else
{
MOB M=CMLib.map().getLoadPlayer(behave);
if(M!=null)
{
int oldNum=-1;
for(int m=0;m<membersCopy.size();m++)
if(behave.equalsIgnoreCase((String)membersCopy.elementAt(m,1)))
{
oldNum=m;
members.addElement(membersCopy.elementAt(m,1),membersCopy.elementAt(m,2),membersCopy.elementAt(m,3));
break;
}
int index=oldNum;
if(index<0)
{
index=members.size();
members.addElement(M.Name(),new Integer(Clan.POS_MEMBER),new Long(M.playerStats().lastDateTime()));
}
int newRole=-1;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newRole<0))
{
String newRoleStr=mob.session().prompt("Enter this members role (?) '"+CMLib.clans().getRoleName(E.getGovernment(),((Integer)members.elementAt(index,2)).intValue(),true,false)+"': ","");
StringBuffer roles=new StringBuffer();
for(int i=0;i<Clan.ROL_DESCS[E.getGovernment()].length;i++)
{
roles.append(Clan.ROL_DESCS[E.getGovernment()][i]+", ");
if(newRoleStr.equalsIgnoreCase(Clan.ROL_DESCS[E.getGovernment()][i]))
newRole=Clan.POSORDER[i];
}
roles=new StringBuffer(roles.substring(0,roles.length()-2));
if(newRole<0)
mob.tell("That role is invalid. Valid roles include: "+roles.toString());
else
break;
}
if(oldNum<0)
mob.tell(M.Name()+" added.");
else
mob.tell(M.Name()+" re-added.");
members.setElementAt(index,2,new Integer(newRole));
}
else
{
mob.tell("'"+behave+"' is an unrecognized player name.");
}
}
// first add missing ones
for(int m=0;m<members.size();m++)
{
String newName=(String)members.elementAt(m,1);
if(!membersCopy.contains(newName))
{
MOB M=CMLib.map().getLoadPlayer(newName);
if(M!=null)
{
Clan oldC=CMLib.clans().getClan(M.getClanID());
if((oldC!=null)
&&(!M.getClanID().equalsIgnoreCase(E.clanID())))
{
M.setClanID("");
M.setClanRole(Clan.POS_APPLICANT);
oldC.updateClanPrivileges(M);
}
Integer role=(Integer)members.elementAt(m,2);
CMLib.database().DBUpdateClanMembership(M.Name(), E.clanID(), role.intValue());
M.setClanID(E.clanID());
M.setClanRole(role.intValue());
E.updateClanPrivileges(M);
}
}
}
// now adjust changed roles
for(int m=0;m<members.size();m++)
{
String newName=(String)members.elementAt(m,1);
if(membersCopy.contains(newName))
{
MOB M=CMLib.map().getLoadPlayer(newName);
int newRole=((Integer)members.elementAt(m,2)).intValue();
if((M!=null)&&(newRole!=M.getClanRole()))
{
CMLib.database().DBUpdateClanMembership(M.Name(), E.clanID(), newRole);
M.setClanRole(newRole);
E.updateClanPrivileges(M);
}
}
}
// now remove old members
for(int m=0;m<membersCopy.size();m++)
{
String newName=(String)membersCopy.elementAt(m,1);
if(!members.contains(newName))
{
MOB M=CMLib.map().getLoadPlayer(newName);
if(M!=null)
{
M.setClanID("");
M.setClanRole(Clan.POS_APPLICANT);
E.updateClanPrivileges(M);
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genDeity1(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setClericRequirements(CMLib.english().prompt(mob,E.getClericRequirements(),showNumber,showFlag,"Cleric Requirements",false,false)); }
protected void genDeity2(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setClericRitual(CMLib.english().prompt(mob,E.getClericRitual(),showNumber,showFlag,"Cleric Ritual",false,false)); }
protected void genDeity3(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setWorshipRequirements(CMLib.english().prompt(mob,E.getWorshipRequirements(),showNumber,showFlag,"Worshiper Requirements",false,false)); }
protected void genDeity4(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setWorshipRitual(CMLib.english().prompt(mob,E.getWorshipRitual(),showNumber,showFlag,"Worshiper Ritual",false,false)); }
protected void genDeity5(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String abilitiestr="";
for(int a=0;a<E.numBlessings();a++)
{
Ability A=E.fetchBlessing(a);
if((A!=null)&&(A.savable()))
abilitiestr+=A.ID()+", ";
}
if(abilitiestr.length()>0)
abilitiestr=abilitiestr.substring(0,abilitiestr.length()-2);
mob.tell(showNumber+". Blessings: '"+abilitiestr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter an ability to add/remove (?)\n\r:","");
if(behave.length()>0)
{
if(behave.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
{
Ability chosenOne=null;
for(int a=0;a<E.numBlessings();a++)
{
Ability A=E.fetchBlessing(a);
if((A!=null)&&(A.ID().equalsIgnoreCase(behave)))
chosenOne=A;
}
if(chosenOne!=null)
{
mob.tell(chosenOne.ID()+" removed.");
E.delBlessing(chosenOne);
}
else
{
chosenOne=CMClass.getAbility(behave);
if(chosenOne!=null)
{
boolean alreadyHasIt=false;
for(int a=0;a<E.numBlessings();a++)
{
Ability A=E.fetchBlessing(a);
if((A!=null)&&(A.ID().equals(chosenOne.ID())))
alreadyHasIt=true;
}
boolean clericOnly=mob.session().confirm("Is this for clerics only (y/N)?","N");
if(!alreadyHasIt)
mob.tell(chosenOne.ID()+" added.");
else
mob.tell(chosenOne.ID()+" re-added.");
if(!alreadyHasIt)
E.addBlessing((Ability)chosenOne.copyOf(),clericOnly);
}
else
{
mob.tell("'"+behave+"' is not recognized. Try '?'.");
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genDeity6(MOB mob, Deity E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String abilitiestr="";
for(int a=0;a<E.numCurses();a++)
{
Ability A=E.fetchCurse(a);
if((A!=null)&&(A.savable()))
abilitiestr+=A.ID()+", ";
}
if(abilitiestr.length()>0)
abilitiestr=abilitiestr.substring(0,abilitiestr.length()-2);
mob.tell(showNumber+". Curses: '"+abilitiestr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter an ability to add/remove (?)\n\r:","");
if(behave.length()>0)
{
if(behave.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
{
Ability chosenOne=null;
for(int a=0;a<E.numCurses();a++)
{
Ability A=E.fetchCurse(a);
if((A!=null)&&(A.ID().equalsIgnoreCase(behave)))
chosenOne=A;
}
if(chosenOne!=null)
{
mob.tell(chosenOne.ID()+" removed.");
E.delCurse(chosenOne);
}
else
{
chosenOne=CMClass.getAbility(behave);
if(chosenOne!=null)
{
boolean alreadyHasIt=false;
for(int a=0;a<E.numCurses();a++)
{
Ability A=E.fetchCurse(a);
if((A!=null)&&(A.ID().equals(chosenOne.ID())))
alreadyHasIt=true;
}
boolean clericOnly=mob.session().confirm("Is this for clerics only (y/N)?","N");
if(!alreadyHasIt)
mob.tell(chosenOne.ID()+" added.");
else
mob.tell(chosenOne.ID()+" re-added.");
if(!alreadyHasIt)
E.addCurse((Ability)chosenOne.copyOf(),clericOnly);
}
else
{
mob.tell("'"+behave+"' is not recognized. Try '?'.");
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genDeity7(MOB mob, Deity E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
String behave="NO";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(behave.length()>0))
{
String abilitiestr="";
for(int a=0;a<E.numPowers();a++)
{
Ability A=E.fetchPower(a);
if((A!=null)&&(A.savable()))
abilitiestr+=A.ID()+", ";
}
if(abilitiestr.length()>0)
abilitiestr=abilitiestr.substring(0,abilitiestr.length()-2);
mob.tell(showNumber+". Granted Powers: '"+abilitiestr+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
behave=mob.session().prompt("Enter an ability to add/remove (?)\n\r:","");
if(behave.length()>0)
{
if(behave.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
{
Ability chosenOne=null;
for(int a=0;a<E.numPowers();a++)
{
Ability A=E.fetchPower(a);
if((A!=null)&&(A.ID().equalsIgnoreCase(behave)))
chosenOne=A;
}
if(chosenOne!=null)
{
mob.tell(chosenOne.ID()+" removed.");
E.delPower(chosenOne);
}
else
{
chosenOne=CMClass.getAbility(behave);
if(chosenOne!=null)
{
boolean alreadyHasIt=false;
for(int a=0;a<E.numPowers();a++)
{
Ability A=E.fetchPower(a);
if((A!=null)&&(A.ID().equals(chosenOne.ID())))
alreadyHasIt=true;
}
if(!alreadyHasIt)
mob.tell(chosenOne.ID()+" added.");
else
mob.tell(chosenOne.ID()+" re-added.");
if(!alreadyHasIt)
E.addPower((Ability)chosenOne.copyOf());
}
else
{
mob.tell("'"+behave+"' is not recognized. Try '?'.");
}
}
}
}
else
mob.tell("(no change)");
}
}
protected void genDeity8(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setClericSin(CMLib.english().prompt(mob,E.getClericSin(),showNumber,showFlag,"Cleric Sin",false,false)); }
protected void genDeity9(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setWorshipSin(CMLib.english().prompt(mob,E.getWorshipSin(),showNumber,showFlag,"Worshiper Sin",false,false)); }
protected void genDeity0(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setClericPowerup(CMLib.english().prompt(mob,E.getClericPowerup(),showNumber,showFlag,"Cleric Power Ritual",false,false)); }
protected void genDeity11(MOB mob, Deity E, int showNumber, int showFlag) throws IOException
{ E.setServiceRitual(CMLib.english().prompt(mob,E.getServiceRitual(),showNumber,showFlag,"Service Ritual",false,false)); }
protected void genGridLocaleX(MOB mob, GridZones E, int showNumber, int showFlag) throws IOException
{ E.setXGridSize(CMLib.english().prompt(mob,E.xGridSize(),showNumber,showFlag,"Size (X)")); }
protected void genGridLocaleY(MOB mob, GridZones E, int showNumber, int showFlag) throws IOException
{ E.setYGridSize(CMLib.english().prompt(mob,E.yGridSize(),showNumber,showFlag,"Size (Y)")); }
protected void genWornLocation(MOB mob, Item E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if((showFlag!=showNumber)&&(showFlag>-999))
{
StringBuffer buf=new StringBuffer(showNumber+". ");
if(!E.rawLogicalAnd())
buf.append("Wear on any one of: ");
else
buf.append("Worn on all of: ");
for(int l=0;l<Item.WORN_CODES.length;l++)
{
long wornCode=1<<l;
if((CMLib.flags().wornLocation(wornCode).length()>0)
&&(((E.rawProperLocationBitmap()&wornCode)==wornCode)))
buf.append(CMLib.flags().wornLocation(wornCode)+", ");
}
if(buf.toString().endsWith(", "))
mob.tell(buf.substring(0,buf.length()-2));
else
mob.tell(buf.toString());
return;
}
int codeVal=-1;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(codeVal!=0))
{
mob.tell("Wearing parameters\n\r0: Done");
if(!E.rawLogicalAnd())
mob.tell("1: Able to worn on any ONE of these locations:");
else
mob.tell("1: Must be worn on ALL of these locations:");
for(int l=0;l<Item.WORN_CODES.length;l++)
{
long wornCode=1<<l;
if(CMLib.flags().wornLocation(wornCode).length()>0)
{
String header=(l+2)+": ("+CMLib.flags().wornLocation(wornCode)+") : "+(((E.rawProperLocationBitmap()&wornCode)==wornCode)?"YES":"NO");
mob.tell(header);
}
}
codeVal=CMath.s_int(mob.session().prompt("Select an option number above to TOGGLE\n\r: "));
if(codeVal>0)
{
if(codeVal==1)
E.setRawLogicalAnd(!E.rawLogicalAnd());
else
{
int wornCode=1<<(codeVal-2);
if((E.rawProperLocationBitmap()&wornCode)==wornCode)
E.setRawProperLocationBitmap(E.rawProperLocationBitmap()-wornCode);
else
E.setRawProperLocationBitmap(E.rawProperLocationBitmap()|wornCode);
}
}
}
}
protected void genThirstQuenched(MOB mob, Drink E, int showNumber, int showFlag) throws IOException
{ E.setThirstQuenched(CMLib.english().prompt(mob,E.thirstQuenched(),showNumber,showFlag,"Quenched/Drink")); }
protected void genDrinkHeld(MOB mob, Drink E, int showNumber, int showFlag) throws IOException
{
E.setLiquidHeld(CMLib.english().prompt(mob,E.liquidHeld(),showNumber,showFlag,"Amount of Drink Held"));
E.setLiquidRemaining(E.liquidHeld());
}
protected void genAttackAttribute(MOB mob, CharClass E, int showNumber, int showFlag, String FieldDisp, String Field)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". "+FieldDisp+": '"+CharStats.STAT_DESCS[CMath.s_int(E.getStat(Field))]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a new one\n\r:","");
String newStat="";
for(int i=0;i<CharStats.NUM_BASE_STATS;i++)
if(newName.equalsIgnoreCase(CharStats.STAT_DESCS[i]))
newStat=""+i;
if(newStat.length()>0)
E.setStat(Field,newStat);
else
mob.tell("(no change)");
}
protected void genArmorCode(MOB mob, CharClass E, int showNumber, int showFlag, String FieldDisp, String Field)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". "+FieldDisp+": '"+CharClass.ARMOR_LONGDESC[CMath.s_int(E.getStat(Field))]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter ("+CMParms.toStringList(CharClass.ARMOR_DESCS)+")\n\r:","");
String newStat="";
for(int i=0;i<CharClass.ARMOR_DESCS.length;i++)
if(newName.equalsIgnoreCase(CharClass.ARMOR_DESCS[i]))
newStat=""+i;
if(newStat.length()>0)
E.setStat(Field,newStat);
else
mob.tell("(no change)");
}
protected void genQualifications(MOB mob, CharClass E, int showNumber, int showFlag, String FieldDisp, String Field)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". "+FieldDisp+": '"+CMLib.masking().maskDesc(E.getStat(Field))+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName="?";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.equals("?")))
{
newName=mob.session().prompt("Enter a new mask (?)\n\r:","");
if(newName.equals("?"))
mob.tell(CMLib.masking().maskHelp("\n","disallow"));
}
if((newName.length()>0)&&(!newName.equals("?")))
E.setStat(Field,newName);
else
mob.tell("(no change)");
}
protected void genClanAccept(MOB mob, Clan E, int showNumber, int showFlag) throws IOException
{ E.setAcceptanceSettings(CMLib.english().prompt(mob,E.getAcceptanceSettings(),showNumber,showFlag,"Clan Qualifications",false,false,CMLib.masking().maskHelp("\n","disallow"))); }
protected void genWeaponRestr(MOB mob, CharClass E, int showNumber, int showFlag, String FieldDisp, String FieldNum, String Field)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
Vector set=CMParms.parseCommas(E.getStat(Field),true);
StringBuffer str=new StringBuffer("");
for(int v=0;v<set.size();v++)
str.append(" "+Weapon.classifictionDescription[CMath.s_int((String)set.elementAt(v))].toLowerCase());
mob.tell(showNumber+". "+FieldDisp+": '"+str.toString()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName="?";
boolean setChanged=false;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.equals("?")))
{
newName=mob.session().prompt("Enter a weapon class to add/remove (?)\n\r:","");
if(newName.equals("?"))
mob.tell(CMParms.toStringList(Weapon.classifictionDescription));
else
if(newName.length()>0)
{
int foundCode=-1;
for(int i=0;i<Weapon.classifictionDescription.length;i++)
if(Weapon.classifictionDescription[i].equalsIgnoreCase(newName))
foundCode=i;
if(foundCode<0)
{
mob.tell("'"+newName+"' is not recognized. Try '?'.");
newName="?";
}
else
{
int x=set.indexOf(""+foundCode);
if(x>=0)
{
setChanged=true;
set.removeElementAt(x);
mob.tell("'"+newName+"' removed.");
newName="?";
}
else
{
set.addElement(""+foundCode);
setChanged=true;
mob.tell("'"+newName+"' added.");
newName="?";
}
}
}
}
if(setChanged)
E.setStat(Field,CMParms.toStringList(set));
else
mob.tell("(no change)");
}
protected void genWeaponMaterials(MOB mob, CharClass E, int showNumber, int showFlag, String FieldDisp, String FieldNum, String Field)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
Vector set=CMParms.parseCommas(E.getStat(Field),true);
StringBuffer str=new StringBuffer("");
for(int v=0;v<set.size();v++)
str.append(" "+CMLib.materials().getMaterialDesc(CMath.s_int((String)set.elementAt(v))));
mob.tell(showNumber+". "+FieldDisp+": '"+str.toString()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName="?";
boolean setChanged=false;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.equals("?")))
{
newName=mob.session().prompt("Enter a material type to add/remove to requirements (?)\n\r:","");
if(newName.equals("?"))
mob.tell(CMParms.toStringList(RawMaterial.MATERIAL_DESCS));
else
if(newName.length()>0)
{
int foundCode=CMLib.materials().getMaterialCode(newName,true);
if(foundCode<0) foundCode=CMLib.materials().getMaterialCode(newName,false);
if(foundCode<0)
{
mob.tell("'"+newName+"' is not recognized. Try '?'.");
newName="?";
}
else
{
int x=set.indexOf(""+foundCode);
if(x>=0)
{
setChanged=true;
set.removeElementAt(x);
mob.tell("'"+newName+"' removed.");
newName="?";
}
else
{
set.addElement(""+foundCode);
setChanged=true;
mob.tell("'"+newName+"' added.");
newName="?";
}
}
}
}
if(setChanged)
E.setStat(Field,CMParms.toStringList(set));
else
mob.tell("(no change)");
}
protected void genDisableFlags(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
int flags=CMath.s_int(E.getStat("DISFLAGS"));
String newName="?";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.equals("?")))
{
StringBuffer disabled=new StringBuffer("");
for(int i=0;i<Race.GENFLAG_DESCS.length;i++)
if(CMath.isSet(flags,i))
disabled.append(Race.GENFLAG_DESCS[i]);
mob.tell(showNumber+". Disabled: '"+disabled+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
newName=mob.session().prompt("Enter flag to toggle (?)\n\r:","").toUpperCase();
if(newName.length()==0)
mob.tell("(no change)");
else
if(CMParms.contains(Race.GENFLAG_DESCS,newName))
{
int bit=CMParms.indexOf(Race.GENFLAG_DESCS,newName);
if(CMath.isSet(flags,bit))
flags=flags-(int)CMath.pow(2,bit);
else
flags=flags+(int)CMath.pow(2,bit);
}
else
if(newName.equalsIgnoreCase("?"))
{
StringBuffer str=new StringBuffer("Valid values: \n\r");
for(int i=0;i<Race.GENFLAG_DESCS.length;i++)
str.append(Race.GENFLAG_DESCS[i]+"\n\r");
mob.tell(str.toString());
}
else
mob.tell("(no change)");
}
E.setStat("DISFLAGS",""+flags);
}
protected void genRaceWearFlags(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
int flags=CMath.s_int(E.getStat("WEAR"));
String newName="?";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.equals("?")))
{
StringBuffer wearable=new StringBuffer("");
for(int i=1;i<Item.WORN_DESCS.length;i++)
if(CMath.isSet(flags,i-1))
wearable.append(Item.WORN_DESCS[i]+" ");
mob.tell(showNumber+". UNWearable locations: '"+wearable+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
newName=mob.session().prompt("Enter a location to toggle (?)\n\r:","").toUpperCase();
if(newName.length()==0)
mob.tell("(no change)");
else
if(CMParms.contains(Item.WORN_DESCS,newName))
{
int bit=CMParms.indexOf(Item.WORN_DESCS,newName)-1;
if(bit>=0)
{
if(CMath.isSet(flags,bit))
flags=flags-(int)CMath.pow(2,bit);
else
flags=flags+(int)CMath.pow(2,bit);
}
}
else
if(newName.equalsIgnoreCase("?"))
{
StringBuffer str=new StringBuffer("Valid values: \n\r");
for(int i=0;i<Item.WORN_DESCS.length;i++)
str.append(Item.WORN_DESCS[i]+" ");
mob.tell(str.toString());
}
else
mob.tell("(no change)");
}
E.setStat("WEAR",""+flags);
}
protected void genRaceAvailability(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Availability: '"+Area.THEME_DESCS_EXT[CMath.s_int(E.getStat("AVAIL"))]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName="?";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.equals("?")))
{
newName=mob.session().prompt("Enter a new value (?)\n\r:","");
if(newName.length()==0)
mob.tell("(no change)");
else
if((CMath.isNumber(newName))&&(CMath.s_int(newName)<Area.THEME_DESCS_EXT.length))
E.setStat("AVAIL",""+CMath.s_int(newName));
else
if(newName.equalsIgnoreCase("?"))
{
StringBuffer str=new StringBuffer("Valid values: \n\r");
for(int i=0;i<Area.THEME_DESCS_EXT.length;i++)
str.append(i+") "+Area.THEME_DESCS_EXT[i]+"\n\r");
mob.tell(str.toString());
}
else
mob.tell("(no change)");
}
}
void genClassAvailability(MOB mob, CharClass E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Availability: '"+Area.THEME_DESCS_EXT[CMath.s_int(E.getStat("PLAYER"))]+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName="?";
while((mob.session()!=null)&&(!mob.session().killFlag())&&(newName.equals("?")))
{
newName=mob.session().prompt("Enter a new value (?)\n\r:","");
if(newName.length()==0)
mob.tell("(no change)");
else
if((CMath.isNumber(newName))&&(CMath.s_int(newName)<Area.THEME_DESCS_EXT.length))
E.setStat("PLAYER",""+CMath.s_int(newName));
else
if(newName.equalsIgnoreCase("?"))
{
StringBuffer str=new StringBuffer("Valid values: \n\r");
for(int i=0;i<Area.THEME_DESCS_EXT.length;i++)
str.append(i+") "+Area.THEME_DESCS_EXT[i]+"\n\r");
mob.tell(str.toString());
}
else
mob.tell("(no change)");
}
}
protected void genCat(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Racial Category: '"+E.racialCategory()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a new one\n\r:","");
if(newName.length()>0)
{
boolean found=false;
if(newName.startsWith("new "))
{
newName=CMStrings.capitalizeAndLower(newName.substring(4));
if(newName.length()>0)
found=true;
}
else
for(Enumeration r=CMClass.races();r.hasMoreElements();)
{
Race R=(Race)r.nextElement();
if(newName.equalsIgnoreCase(R.racialCategory()))
{
newName=R.racialCategory();
found=true;
break;
}
}
if(!found)
{
StringBuffer str=new StringBuffer("That category does not exist. Valid categories include: ");
HashSet H=new HashSet();
for(Enumeration r=CMClass.races();r.hasMoreElements();)
{
Race R=(Race)r.nextElement();
if(!H.contains(R.racialCategory()))
{
H.add(R.racialCategory());
str.append(R.racialCategory()+", ");
}
}
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
E.setStat("CAT",newName);
}
else
mob.tell("(no change)");
}
protected void genRaceBuddy(MOB mob, Race E, int showNumber, int showFlag, String prompt, String flag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". "+prompt+": '"+E.getStat(flag)+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a new one\n\r:","");
if(newName.length()>0)
{
Race R2=CMClass.getRace(newName);
if(R2==null) R2=(Race)CMClass.unsortedLoadClass("RACE",newName);
if((R2!=null)&&(R2.isGeneric()))
R2=null;
if(R2==null)
{
StringBuffer str=new StringBuffer("That race name is invalid or is generic. Valid races include: ");
for(Enumeration r=CMClass.races();r.hasMoreElements();)
{
Race R=(Race)r.nextElement();
if(!R.isGeneric())
str.append(R.ID()+", ");
}
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
if(CMClass.getRace(newName)==R2)
E.setStat(flag,R2.ID());
else
E.setStat(flag,R2.getClass().getName());
}
else
mob.tell("(no change)");
}
protected void genClassBuddy(MOB mob, CharClass E, int showNumber, int showFlag, String prompt, String flag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". "+prompt+": '"+E.getStat(flag)+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a new one\n\r:","");
if(newName.length()>0)
{
CharClass C2=CMClass.getCharClass(newName);
if(C2==null) C2=(CharClass)CMClass.unsortedLoadClass("CHARCLASS",newName);
if((C2!=null)&&(C2.isGeneric()))
C2=null;
if(C2==null)
{
StringBuffer str=new StringBuffer("That char class name is invalid or is generic. Valid char classes include: ");
for(Enumeration r=CMClass.charClasses();r.hasMoreElements();)
{
CharClass C=(CharClass)r.nextElement();
if(!C.isGeneric())
str.append(C.ID()+", ");
}
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
if(CMClass.getCharClass(newName)==C2)
E.setStat(flag,C2.ID());
else
E.setStat(flag,C2.getClass().getName());
}
else
mob.tell("(no change)");
}
protected void genBodyParts(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
StringBuffer parts=new StringBuffer("");
for(int i=0;i<Race.BODYPARTSTR.length;i++)
if(E.bodyMask()[i]!=0) parts.append(Race.BODYPARTSTR[i].toLowerCase()+"("+E.bodyMask()[i]+") ");
mob.tell(showNumber+". Body Parts: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a body part\n\r:","");
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<Race.BODYPARTSTR.length;i++)
if(newName.equalsIgnoreCase(Race.BODYPARTSTR[i]))
{ partNum=i; break;}
if(partNum<0)
{
StringBuffer str=new StringBuffer("That body part is invalid. Valid parts include: ");
for(int i=0;i<Race.BODYPARTSTR.length;i++)
str.append(Race.BODYPARTSTR[i]+", ");
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
{
newName=mob.session().prompt("Enter new number ("+E.bodyMask()[partNum]+"), 0=none\n\r:",""+E.bodyMask()[partNum]);
if(newName.length()>0)
E.bodyMask()[partNum]=CMath.s_int(newName);
else
mob.tell("(no change)");
}
}
else
mob.tell("(no change)");
}
protected void genEStats(MOB mob, Race R, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
EnvStats S=(EnvStats)CMClass.getCommon("DefaultEnvStats");
S.setAllValues(0);
CMLib.coffeeMaker().setEnvStats(S,R.getStat("ESTATS"));
StringBuffer parts=new StringBuffer("");
for(int i=0;i<S.getStatCodes().length;i++)
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
parts.append(CMStrings.capitalizeAndLower(S.getStatCodes()[i])+"("+S.getStat(S.getStatCodes()[i])+") ");
mob.tell(showNumber+". EStat Adjustments: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean done=false;
while((!done)&&(mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a stat name\n\r:","");
if(newName.length()>0)
{
String partName=null;
for(int i=0;i<S.getStatCodes().length;i++)
if(newName.equalsIgnoreCase(S.getStatCodes()[i]))
{ partName=S.getStatCodes()[i]; break;}
if(partName==null)
{
StringBuffer str=new StringBuffer("That stat is invalid. Valid stats include: ");
for(int i=0;i<S.getStatCodes().length;i++)
str.append(S.getStatCodes()[i]+", ");
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
{
boolean checkChange=false;
if(partName.equals("DISPOSITION"))
{
genDisposition(mob,S,0,0);
checkChange=true;
}
else
if(partName.equals("SENSES"))
{
genSensesMask(mob,S,0,0);
checkChange=true;
}
else
{
newName=mob.session().prompt("Enter a value\n\r:","");
if(newName.length()>0)
{
S.setStat(partName,newName);
checkChange=true;
}
else
mob.tell("(no change)");
}
if(checkChange)
{
boolean zereoed=true;
for(int i=0;i<S.getStatCodes().length;i++)
{
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
{ zereoed=false; break;}
}
if(zereoed)
R.setStat("ESTATS","");
else
R.setStat("ESTATS",CMLib.coffeeMaker().getEnvStatsStr(S));
}
}
}
else
{
mob.tell("(no change)");
done=true;
}
}
}
protected void genAState(MOB mob,
Race R,
String field,
String prompt,
int showNumber,
int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
CharState S=(CharState)CMClass.getCommon("DefaultCharState"); S.setAllValues(0);
CMLib.coffeeMaker().setCharState(S,R.getStat(field));
StringBuffer parts=new StringBuffer("");
for(int i=0;i<S.getStatCodes().length;i++)
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
parts.append(CMStrings.capitalizeAndLower(S.getStatCodes()[i])+"("+S.getStat(S.getStatCodes()[i])+") ");
mob.tell(showNumber+". "+prompt+": "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean done=false;
while((!done)&&(mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a stat name\n\r:","");
if(newName.length()>0)
{
String partName=null;
for(int i=0;i<S.getStatCodes().length;i++)
if(newName.equalsIgnoreCase(S.getStatCodes()[i]))
{ partName=S.getStatCodes()[i]; break;}
if(partName==null)
{
StringBuffer str=new StringBuffer("That stat is invalid. Valid stats include: ");
for(int i=0;i<S.getStatCodes().length;i++)
str.append(S.getStatCodes()[i]+", ");
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
{
newName=mob.session().prompt("Enter a value\n\r:","");
if(newName.length()>0)
{
S.setStat(partName,newName);
boolean zereoed=true;
for(int i=0;i<S.getStatCodes().length;i++)
{
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
{ zereoed=false; break;}
}
if(zereoed)
R.setStat(field,"");
else
R.setStat(field,CMLib.coffeeMaker().getCharStateStr(S));
}
else
mob.tell("(no change)");
}
}
else
{
mob.tell("(no change)");
done=true;
}
}
}
protected void genAStats(MOB mob, Race R, String Field, String FieldName, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
CharStats S=(CharStats)CMClass.getCommon("DefaultCharStats"); S.setAllValues(0);
CMLib.coffeeMaker().setCharStats(S,R.getStat(Field));
StringBuffer parts=new StringBuffer("");
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
if(S.getStat(i)!=0)
parts.append(CMStrings.capitalizeAndLower(CharStats.STAT_DESCS[i])+"("+S.getStat(i)+") ");
mob.tell(showNumber+". "+FieldName+": "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean done=false;
while((!done)&&(mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a stat name\n\r:","");
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
if(newName.equalsIgnoreCase(CharStats.STAT_DESCS[i]))
{ partNum=i; break;}
if(partNum<0)
{
StringBuffer str=new StringBuffer("That stat is invalid. Valid stats include: ");
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
str.append(CharStats.STAT_DESCS[i]+", ");
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
{
newName=mob.session().prompt("Enter a value\n\r:","");
if(newName.length()>0)
{
if(newName.trim().equalsIgnoreCase("0"))
S.setStat(partNum,CMath.s_int(newName));
else
if(partNum==CharStats.STAT_GENDER)
S.setStat(partNum,(int)newName.charAt(0));
else
S.setStat(partNum,CMath.s_int(newName));
boolean zereoed=true;
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
{
if(S.getStat(i)!=0)
{ zereoed=false; break;}
}
if(zereoed)
R.setStat(Field,"");
else
R.setStat(Field,CMLib.coffeeMaker().getCharStatsStr(S));
}
else
mob.tell("(no change)");
}
}
else
{
mob.tell("(no change)");
done=true;
}
}
}
protected void genEStats(MOB mob, CharClass R, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
EnvStats S=(EnvStats)CMClass.getCommon("DefaultEnvStats");
S.setAllValues(0);
CMLib.coffeeMaker().setEnvStats(S,R.getStat("ESTATS"));
StringBuffer parts=new StringBuffer("");
for(int i=0;i<S.getStatCodes().length;i++)
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
parts.append(CMStrings.capitalizeAndLower(S.getStatCodes()[i])+"("+S.getStat(S.getStatCodes()[i])+") ");
mob.tell(showNumber+". EStat Adjustments: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean done=false;
while((!done)&&(mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a stat name\n\r:","");
if(newName.length()>0)
{
String partName=null;
for(int i=0;i<S.getStatCodes().length;i++)
if(newName.equalsIgnoreCase(S.getStatCodes()[i]))
{ partName=S.getStatCodes()[i]; break;}
if(partName==null)
{
StringBuffer str=new StringBuffer("That stat is invalid. Valid stats include: ");
for(int i=0;i<S.getStatCodes().length;i++)
str.append(S.getStatCodes()[i]+", ");
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
{
boolean checkChange=false;
if(partName.equals("DISPOSITION"))
{
genDisposition(mob,S,0,0);
checkChange=true;
}
else
if(partName.equals("SENSES"))
{
genSensesMask(mob,S,0,0);
checkChange=true;
}
else
{
newName=mob.session().prompt("Enter a value\n\r:","");
if(newName.length()>0)
{
S.setStat(partName,newName);
checkChange=true;
}
else
mob.tell("(no change)");
}
if(checkChange)
{
boolean zereoed=true;
for(int i=0;i<S.getStatCodes().length;i++)
{
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
{ zereoed=false; break;}
}
if(zereoed)
R.setStat("ESTATS","");
else
R.setStat("ESTATS",CMLib.coffeeMaker().getEnvStatsStr(S));
}
}
}
else
{
mob.tell("(no change)");
done=true;
}
}
}
protected void genAState(MOB mob,
CharClass R,
String field,
String prompt,
int showNumber,
int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
CharState S=(CharState)CMClass.getCommon("DefaultCharState"); S.setAllValues(0);
CMLib.coffeeMaker().setCharState(S,R.getStat(field));
StringBuffer parts=new StringBuffer("");
for(int i=0;i<S.getStatCodes().length;i++)
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
parts.append(CMStrings.capitalizeAndLower(S.getStatCodes()[i])+"("+S.getStat(S.getStatCodes()[i])+") ");
mob.tell(showNumber+". "+prompt+": "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean done=false;
while((!done)&&(mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a stat name\n\r:","");
if(newName.length()>0)
{
String partName=null;
for(int i=0;i<S.getStatCodes().length;i++)
if(newName.equalsIgnoreCase(S.getStatCodes()[i]))
{ partName=S.getStatCodes()[i]; break;}
if(partName==null)
{
StringBuffer str=new StringBuffer("That stat is invalid. Valid stats include: ");
for(int i=0;i<S.getStatCodes().length;i++)
str.append(S.getStatCodes()[i]+", ");
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
{
newName=mob.session().prompt("Enter a value\n\r:","");
if(newName.length()>0)
{
S.setStat(partName,newName);
boolean zereoed=true;
for(int i=0;i<S.getStatCodes().length;i++)
{
if(CMath.s_int(S.getStat(S.getStatCodes()[i]))!=0)
{ zereoed=false; break;}
}
if(zereoed)
R.setStat(field,"");
else
R.setStat(field,CMLib.coffeeMaker().getCharStateStr(S));
}
else
mob.tell("(no change)");
}
}
else
{
mob.tell("(no change)");
done=true;
}
}
}
protected void genAStats(MOB mob, CharClass R, String Field, String FieldName, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
CharStats S=(CharStats)CMClass.getCommon("DefaultCharStats"); S.setAllValues(0);
CMLib.coffeeMaker().setCharStats(S,R.getStat(Field));
StringBuffer parts=new StringBuffer("");
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
if(S.getStat(i)!=0)
parts.append(CMStrings.capitalizeAndLower(CharStats.STAT_DESCS[i])+"("+S.getStat(i)+") ");
mob.tell(showNumber+". "+FieldName+": "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
boolean done=false;
while((!done)&&(mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a stat name\n\r:","");
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
if(newName.equalsIgnoreCase(CharStats.STAT_DESCS[i]))
{ partNum=i; break;}
if(partNum<0)
{
StringBuffer str=new StringBuffer("That stat is invalid. Valid stats include: ");
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
str.append(CharStats.STAT_DESCS[i]+", ");
mob.tell(str.toString().substring(0,str.length()-2)+".");
}
else
{
newName=mob.session().prompt("Enter a value\n\r:","");
if(newName.length()>0)
{
S.setStat(partNum,CMath.s_int(newName));
boolean zereoed=true;
for(int i=0;i<CharStats.STAT_DESCS.length;i++)
{
if(S.getStat(i)!=0)
{ zereoed=false; break;}
}
if(zereoed)
R.setStat(Field,"");
else
R.setStat(Field,CMLib.coffeeMaker().getCharStatsStr(S));
}
else
mob.tell("(no change)");
}
}
else
{
mob.tell("(no change)");
done=true;
}
}
}
protected void genResources(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
StringBuffer parts=new StringBuffer("");
int numResources=CMath.s_int(E.getStat("NUMRSC"));
DVector DV=new DVector(2);
for(int r=0;r<numResources;r++)
{
Item I=CMClass.getItem(E.getStat("GETRSCID"+r));
if(I!=null)
{
I.setMiscText(E.getStat("GETRSCPARM"+r));
I.recoverEnvStats();
boolean done=false;
for(int v=0;v<DV.size();v++)
if(I.sameAs((Environmental)DV.elementAt(v,1)))
{ DV.setElementAt(v,2,new Integer(((Integer)DV.elementAt(v,2)).intValue()+1)); done=true; break;}
if(!done)
DV.addElement(I,new Integer(1));
}
else
parts.append("Unknown: "+E.getStat("GETRSCID"+r)+", ");
}
for(int v=0;v<DV.size();v++)
{
Item I=(Item)DV.elementAt(v,1);
int i=((Integer)DV.elementAt(v,2)).intValue();
if(i<2)
parts.append(I.name()+", ");
else
parts.append(I.name()+" ("+i+"), ");
}
if(parts.toString().endsWith(", "))
{parts.deleteCharAt(parts.length()-1);parts.deleteCharAt(parts.length()-1);}
mob.tell(showNumber+". Resources: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a resource name to remove or\n\rthe word new and an item name to add from your inventory\n\r:","");
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<DV.size();i++)
if(CMLib.english().containsString(((Item)DV.elementAt(i,1)).name(),newName))
{ partNum=i; break;}
boolean updateList=false;
if(partNum<0)
{
if(!newName.toLowerCase().startsWith("new "))
mob.tell("That is neither an existing resource name, or the word new followed by a valid item name.");
else
{
Item I=mob.fetchCarried(null,newName.substring(4).trim());
if(I!=null)
{
I=(Item)I.copyOf();
boolean done=false;
for(int v=0;v<DV.size();v++)
if(I.sameAs((Environmental)DV.elementAt(v,1)))
{ DV.setElementAt(v,2,new Integer(((Integer)DV.elementAt(v,2)).intValue()+1)); done=true; break;}
if(!done)
DV.addElement(I,new Integer(1));
mob.tell(I.name()+" added.");
updateList=true;
}
}
}
else
{
Item I=(Item)DV.elementAt(partNum,1);
int i=((Integer)DV.elementAt(partNum,2)).intValue();
if(i<2)
DV.removeElementAt(partNum);
else
DV.setElementAt(partNum,2,new Integer(i-1));
mob.tell(I.name()+" removed.");
updateList=true;
}
if(updateList)
{
int dex=0;
for(int i=0;i<DV.size();i++)
dex+=((Integer)DV.elementAt(i,2)).intValue();
E.setStat("NUMRSC",""+dex);
dex=0;
Item I=null;
Integer N=null;
for(int i=0;i<DV.size();i++)
{
I=(Item)DV.elementAt(i,1);
N=(Integer)DV.elementAt(i,2);
for(int n=0;n<N.intValue();n++)
E.setStat("GETRSCID"+(dex++),I.ID());
}
dex=0;
for(int i=0;i<DV.size();i++)
{
I=(Item)DV.elementAt(i,1);
N=(Integer)DV.elementAt(i,2);
for(int n=0;n<N.intValue();n++)
E.setStat("GETRSCPARM"+(dex++),I.text());
}
}
}
else
{
mob.tell("(no change)");
return;
}
}
}
protected void genOutfit(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
StringBuffer parts=new StringBuffer("");
int numResources=CMath.s_int(E.getStat("NUMOFT"));
Vector V=new Vector();
for(int v=0;v<numResources;v++)
{
Item I=CMClass.getItem(E.getStat("GETOFTID"+v));
if(I!=null)
{
I.setMiscText(E.getStat("GETOFTPARM"+v));
I.recoverEnvStats();
parts.append(I.name()+", ");
V.addElement(I);
}
}
if(parts.toString().endsWith(", "))
{parts.deleteCharAt(parts.length()-1);parts.deleteCharAt(parts.length()-1);}
mob.tell(showNumber+". Outfit: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter an item name to remove or\n\rthe word new and an item name to add from your inventory\n\r:","");
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<V.size();i++)
if(CMLib.english().containsString(((Item)V.elementAt(i)).name(),newName))
{ partNum=i; break;}
boolean updateList=false;
if(partNum<0)
{
if(!newName.toLowerCase().startsWith("new "))
mob.tell("That is neither an existing item name, or the word new followed by a valid item name.");
else
{
Item I=mob.fetchCarried(null,newName.substring(4).trim());
if(I!=null)
{
I=(Item)I.copyOf();
V.addElement(I);
mob.tell(I.name()+" added.");
updateList=true;
}
}
}
else
{
Item I=(Item)V.elementAt(partNum);
V.removeElementAt(partNum);
mob.tell(I.name()+" removed.");
updateList=true;
}
if(updateList)
{
E.setStat("NUMOFT","");
for(int i=0;i<V.size();i++)
E.setStat("GETOFTID"+i,((Item)V.elementAt(i)).ID());
for(int i=0;i<V.size();i++)
E.setStat("GETOFTPARM"+i,((Item)V.elementAt(i)).text());
}
}
else
{
mob.tell("(no change)");
return;
}
}
}
protected void genOutfit(MOB mob, CharClass E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
StringBuffer parts=new StringBuffer("");
int numResources=CMath.s_int(E.getStat("NUMOFT"));
Vector V=new Vector();
for(int v=0;v<numResources;v++)
{
Item I=CMClass.getItem(E.getStat("GETOFTID"+v));
if(I!=null)
{
I.setMiscText(E.getStat("GETOFTPARM"+v));
I.recoverEnvStats();
parts.append(I.name()+", ");
V.addElement(I);
}
}
if(parts.toString().endsWith(", "))
{parts.deleteCharAt(parts.length()-1);parts.deleteCharAt(parts.length()-1);}
mob.tell(showNumber+". Outfit: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter an item name to remove or\n\rthe word new and an item name to add from your inventory\n\r:","");
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<V.size();i++)
if(CMLib.english().containsString(((Item)V.elementAt(i)).name(),newName))
{ partNum=i; break;}
boolean updateList=false;
if(partNum<0)
{
if(!newName.toLowerCase().startsWith("new "))
mob.tell("That is neither an existing item name, or the word new followed by a valid item name.");
else
{
Item I=mob.fetchCarried(null,newName.substring(4).trim());
if(I!=null)
{
I=(Item)I.copyOf();
V.addElement(I);
mob.tell(I.name()+" added.");
updateList=true;
}
}
}
else
{
Item I=(Item)V.elementAt(partNum);
V.removeElementAt(partNum);
mob.tell(I.name()+" removed.");
updateList=true;
}
if(updateList)
{
E.setStat("NUMOFT","");
for(int i=0;i<V.size();i++)
E.setStat("GETOFTID"+i,((Item)V.elementAt(i)).ID());
for(int i=0;i<V.size();i++)
E.setStat("GETOFTPARM"+i,((Item)V.elementAt(i)).text());
}
}
else
{
mob.tell("(no change)");
return;
}
}
}
protected void genWeapon(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
StringBuffer parts=new StringBuffer("");
Item I=CMClass.getItem(E.getStat("WEAPONCLASS"));
if(I!=null)
{
I.setMiscText(E.getStat("WEAPONXML"));
I.recoverEnvStats();
parts.append(I.name());
}
mob.tell(showNumber+". Natural Weapon: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter a weapon name from your inventory to change, or 'null' for human\n\r:","");
if(newName.equalsIgnoreCase("null"))
{
E.setStat("WEAPONCLASS","");
mob.tell("Human weapons set.");
}
else
if(newName.length()>0)
{
I=mob.fetchCarried(null,newName);
if(I==null)
{
mob.tell("'"+newName+"' is not in your inventory.");
mob.tell("(no change)");
return;
}
I=(Item)I.copyOf();
E.setStat("WEAPONCLASS",I.ID());
E.setStat("WEAPONXML",I.text());
}
else
{
mob.tell("(no change)");
return;
}
}
protected void modifyDField(DVector fields, String fieldName, String value)
{
int x=fields.indexOf(fieldName.toUpperCase());
if(x<0) return;
fields.setElementAt(x,2,value);
}
protected void genAgingChart(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Aging Chart: "+CMParms.toStringList(E.getAgingChart())+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
String newName=mob.session().prompt("Enter a comma-delimited list of 9 numbers, running from infant -> ancient\n\r:","");
if(newName.length()==0)
{
mob.tell("(no change)");
return;
}
Vector V=CMParms.parseCommas(newName,true);
if(V.size()==9)
{
int highest=-1;
boolean cont=false;
for(int i=0;i<V.size();i++)
{
if(CMath.s_int((String)V.elementAt(i))<highest)
{
mob.tell("Entry "+((String)V.elementAt(i))+" is out of place.");
cont=true;
break;
}
highest=CMath.s_int((String)V.elementAt(i));
}
if(cont) continue;
E.setStat("AGING",newName);
break;
}
}
}
protected void genClassFlags(MOB mob, CharClass E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber))
return;
int flags=CMath.s_int(E.getStat("DISFLAGS"));
StringBuffer sets=new StringBuffer("");
if(CMath.bset(flags,CharClass.GENFLAG_NORACE))
sets.append("Raceless ");
if(CMath.bset(flags,CharClass.GENFLAG_NOLEVELS))
sets.append("Leveless ");
if(CMath.bset(flags,CharClass.GENFLAG_NOEXP))
sets.append("Expless ");
mob.tell(showNumber+". Extra CharClass Flags: "+sets.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999))
return;
String newName=mob.session().prompt("Enter: 1) Classless, 2) Leveless, 3) Expless\n\r:","");
switch(CMath.s_int(newName))
{
case 1:
if(CMath.bset(flags,CharClass.GENFLAG_NORACE))
flags=CMath.unsetb(flags,CharClass.GENFLAG_NORACE);
else
flags=flags|CharClass.GENFLAG_NORACE;
break;
case 2:
if(CMath.bset(flags,CharClass.GENFLAG_NOLEVELS))
flags=CMath.unsetb(flags,CharClass.GENFLAG_NOLEVELS);
else
flags=flags|CharClass.GENFLAG_NOLEVELS;
break;
case 3:
if(CMath.bset(flags,CharClass.GENFLAG_NOEXP))
flags=CMath.unsetb(flags,CharClass.GENFLAG_NOEXP);
else
flags=flags|CharClass.GENFLAG_NOEXP;
break;
default:
mob.tell("(no change)");
break;
}
E.setStat("DISFLAGS",""+flags);
}
protected void genRacialAbilities(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
StringBuffer parts=new StringBuffer("");
int numResources=CMath.s_int(E.getStat("NUMRABLE"));
Vector ables=new Vector();
Vector data=new Vector();
for(int v=0;v<numResources;v++)
{
Ability A=CMClass.getAbility(E.getStat("GETRABLE"+v));
if(A!=null)
{
parts.append("("+A.ID()+"/"+E.getStat("GETRABLELVL"+v)+"/"+E.getStat("GETRABLEQUAL"+v)+"/"+E.getStat("GETRABLEPROF"+v)+"), ");
ables.addElement(A);
data.addElement(A.ID()+";"+E.getStat("GETRABLELVL"+v)+";"+E.getStat("GETRABLEQUAL"+v)+";"+E.getStat("GETRABLEPROF"+v));
}
}
if(parts.toString().endsWith(", "))
{parts.deleteCharAt(parts.length()-1);parts.deleteCharAt(parts.length()-1);}
mob.tell(showNumber+". Racial Abilities: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter an ability name to add or remove (?)\n\r:","");
if(newName.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<ables.size();i++)
if(CMLib.english().containsString(((Ability)ables.elementAt(i)).ID(),newName))
{ partNum=i; break;}
boolean updateList=false;
if(partNum<0)
{
Ability A=CMClass.getAbility(newName);
if(A==null)
mob.tell("That is neither an existing ability name, nor a valid one to add. Use ? for a list.");
else
if(A.isAutoInvoked())
mob.tell("'"+A.name()+"' cannot be named, as it is autoinvoked.");
else
if((A.triggerStrings()==null)||(A.triggerStrings().length==0))
mob.tell("'"+A.name()+"' cannot be named, as it has no trigger/command words.");
else
{
StringBuffer str=new StringBuffer(A.ID()+";");
String level=mob.session().prompt("Enter the level of this skill (1): ","1");
str.append((""+CMath.s_int(level))+";");
if(mob.session().confirm("Is this skill automatically gained (Y/n)?","Y"))
str.append("false;");
else
str.append("true;");
String prof=mob.session().prompt("Enter the (perm) proficiency level (100): ","100");
str.append((""+CMath.s_int(prof)));
data.addElement(str.toString());
ables.addElement(A);
mob.tell(A.name()+" added.");
updateList=true;
}
}
else
{
Ability A=(Ability)ables.elementAt(partNum);
ables.removeElementAt(partNum);
data.removeElementAt(partNum);
updateList=true;
mob.tell(A.name()+" removed.");
}
if(updateList)
{
if(data.size()>0)
E.setStat("NUMRABLE",""+data.size());
else
E.setStat("NUMRABLE","");
for(int i=0;i<data.size();i++)
{
Vector V=CMParms.parseSemicolons((String)data.elementAt(i),false);
E.setStat("GETRABLE"+i,((String)V.elementAt(0)));
E.setStat("GETRABLELVL"+i,((String)V.elementAt(1)));
E.setStat("GETRABLEQUAL"+i,((String)V.elementAt(2)));
E.setStat("GETRABLEPROF"+i,((String)V.elementAt(3)));
}
}
}
else
{
mob.tell("(no change)");
return;
}
}
}
protected void genRacialEffects(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
StringBuffer parts=new StringBuffer("");
int numResources=CMath.s_int(E.getStat("NUMREFF"));
Vector ables=new Vector();
Vector data=new Vector();
for(int v=0;v<numResources;v++)
{
Ability A=CMClass.getAbility(E.getStat("GETREFF"+v));
if(A!=null)
{
parts.append("("+A.ID()+"/"+E.getStat("GETREFFLVL"+v)+"/"+E.getStat("GETREFFPARM"+v)+"), ");
ables.addElement(A);
data.addElement(A.ID()+"~"+E.getStat("GETREFFLVL"+v)+"~"+E.getStat("GETREFFPARM"+v));
}
}
if(parts.toString().endsWith(", "))
{parts.deleteCharAt(parts.length()-1);parts.deleteCharAt(parts.length()-1);}
mob.tell(showNumber+". Racial Effects: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter an effect name to add or remove\n\r:","");
if(newName.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<ables.size();i++)
if(CMLib.english().containsString(((Ability)ables.elementAt(i)).ID(),newName))
{ partNum=i; break;}
boolean updateList=false;
if(partNum<0)
{
Ability A=CMClass.getAbility(newName);
if(A==null)
mob.tell("That is neither an existing effect name, nor a valid one to add. Use ? for a list.");
else
{
StringBuffer str=new StringBuffer(A.ID()+"~");
String level=mob.session().prompt("Enter the level to gain this effect (1): ","1");
str.append((""+CMath.s_int(level))+"~");
String prof=mob.session().prompt("Enter any parameters: ","");
str.append(""+prof);
data.addElement(str.toString());
ables.addElement(A);
mob.tell(A.name()+" added.");
updateList=true;
}
}
else
{
Ability A=(Ability)ables.elementAt(partNum);
ables.removeElementAt(partNum);
data.removeElementAt(partNum);
updateList=true;
mob.tell(A.name()+" removed.");
}
if(updateList)
{
if(data.size()>0)
E.setStat("NUMREFF",""+data.size());
else
E.setStat("NUMREFF","");
for(int i=0;i<data.size();i++)
{
Vector V=CMParms.parseSquiggleDelimited((String)data.elementAt(i),false);
E.setStat("GETREFF"+i,((String)V.elementAt(0)));
E.setStat("GETREFFLVL"+i,((String)V.elementAt(1)));
E.setStat("GETREFFPARM"+i,((String)V.elementAt(2)));
}
}
}
else
{
mob.tell("(no change)");
return;
}
}
}
protected DVector genClassAbleMod(MOB mob, DVector sets, String ableID, int origLevelIndex, int origAbleIndex)
throws IOException
{
Integer level=null;
if(origLevelIndex>=0)
{
if(mob.session().confirm("Enter Y to DELETE, or N to modify (y/N)?","N"))
{
DVector set=(DVector)sets.elementAt(origLevelIndex,2);
set.removeElementAt(origAbleIndex);
return null;
}
level=(Integer)sets.elementAt(origLevelIndex,1);
}
else
level=new Integer(1);
level=new Integer(CMath.s_int(mob.session().prompt("Enter the level of this skill ("+level+"): ",""+level)));
if(level.intValue()<=0)
{
mob.tell("Aborted.");
return null;
}
Integer prof=null;
Boolean secret=null;
Boolean gained=null;
String parms="";
if(origLevelIndex<0)
{
prof=new Integer(0);
secret=new Boolean(false);
gained=new Boolean(false);
parms="";
}
else
{
DVector set=(DVector)sets.elementAt(origLevelIndex,2);
gained=(Boolean)set.elementAt(origAbleIndex,2);
prof=(Integer)set.elementAt(origAbleIndex,3);
secret=(Boolean)set.elementAt(origAbleIndex,4);
parms=(String)set.elementAt(origAbleIndex,5);
set.removeElementAt(origAbleIndex);
origAbleIndex=-1;
}
int newlevelIndex=sets.indexOf(level);
DVector levelSet=null;
if(newlevelIndex<0)
{
newlevelIndex=sets.size();
levelSet=new DVector(5);
sets.addElement(level,levelSet);
}
else
levelSet=(DVector)sets.elementAt(newlevelIndex,2);
prof=new Integer(CMath.s_int(mob.session().prompt("Enter the (default) proficiency level ("+prof.toString()+"): ",prof.toString())));
gained=new Boolean(mob.session().confirm("Is this skill automatically gained (Y/N)?",""+gained.toString()));
secret=new Boolean(mob.session().confirm("Is this skill secret (N/y)?",secret.toString()));
parms=mob.session().prompt("Enter any properties ("+parms+"): ",parms);
levelSet.addElement(ableID,gained,prof,secret,parms);
return sets;
}
protected void genClassAbilities(MOB mob, CharClass E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
if((showFlag!=showNumber)&&(showFlag>-999))
{
mob.tell(showNumber+". Class Abilities: [...].");
return;
}
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
StringBuffer parts=new StringBuffer("");
int numAbles=CMath.s_int(E.getStat("NUMCABLE"));
DVector levelSets=new DVector(2);
int maxAbledLevel=Integer.MIN_VALUE;
for(int v=0;v<numAbles;v++)
{
Ability A=CMClass.getAbility(E.getStat("GETCABLE"+v));
if(A!=null)
{
Boolean gain=new Boolean(CMath.s_bool(E.getStat("GETCABLEGAIN"+v)));
Integer defProf=new Integer(CMath.s_int(E.getStat("GETCABLEPROF"+v)));
Integer lvl=new Integer(CMath.s_int(E.getStat("GETCABLELVL"+v)));
Boolean secret=new Boolean(CMath.s_bool(E.getStat("GETCABLESECR"+v)));
String parm=E.getStat("GETCABLEPARM"+v);
int lvlIndex=levelSets.indexOf(lvl);
DVector set=null;
if(lvlIndex<0)
{
set=new DVector(5);
levelSets.addElement(lvl,set);
if(lvl.intValue()>maxAbledLevel)
maxAbledLevel=lvl.intValue();
}
else
set=(DVector)levelSets.elementAt(lvlIndex,2);
set.addElement(A.ID(),gain,defProf,secret,parm);
}
}
String header=showNumber+". Class Abilities: ";
String spaces=CMStrings.repeat(" ",2+(""+showNumber).length());
parts.append("\n\r");
parts.append(spaces+CMStrings.padRight("Lvl",3)+" "
+CMStrings.padRight("Skill",25)+" "
+CMStrings.padRight("Proff",5)+" "
+CMStrings.padRight("Gain",5)+" "
+CMStrings.padRight("Secret",6)+" "
+CMStrings.padRight("Parm",20)+"\n\r"
);
for(int i=0;i<=maxAbledLevel;i++)
{
int index=levelSets.indexOf(new Integer(i));
if(index<0) continue;
DVector set=(DVector)levelSets.elementAt(index,2);
for(int s=0;s<set.size();s++)
{
String ID=(String)set.elementAt(s,1);
Boolean gain=(Boolean)set.elementAt(s,2);
Integer defProf=(Integer)set.elementAt(s,3);
Boolean secret=(Boolean)set.elementAt(s,4);
String parm=(String)set.elementAt(s,5);
parts.append(spaces+CMStrings.padRight(""+i,3)+" "
+CMStrings.padRight(""+ID,25)+" "
+CMStrings.padRight(defProf.toString(),5)+" "
+CMStrings.padRight(gain.toString(),5)+" "
+CMStrings.padRight(secret.toString(),6)+" "
+CMStrings.padRight(parm,20)+"\n\r"
);
}
}
mob.session().wraplessPrintln(header+parts.toString());
String newName=mob.session().prompt("Enter an ability name to add or remove (?)\n\r:","");
if(newName.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
if(newName.length()>0)
{
int lvlIndex=-1;
int ableIndex=-1;
DVector myLevelSet=null;
for(int s=0;s<levelSets.size();s++)
{
DVector lvls=(DVector)levelSets.elementAt(s,2);
for(int l=0;l<lvls.size();l++)
if(CMLib.english().containsString(((String)lvls.elementAt(l,1)),newName))
{
lvlIndex=s;
ableIndex=l;
myLevelSet=lvls;
break;
}
if(lvlIndex>=0) break;
}
boolean updateList=false;
if(ableIndex<0)
{
Ability A=CMClass.getAbility(newName);
if(A==null)
mob.tell("That is neither an existing ability name, nor a valid one to add. Use ? for a list.");
else
{
// add new one here
if(genClassAbleMod(mob,levelSets,A.ID(),-1,-1)!=null)
{
mob.tell(A.ID()+" added.");
updateList=true;
numAbles++;
}
}
}
else
{
String aID=(String)myLevelSet.elementAt(ableIndex,1);
if(genClassAbleMod(mob,levelSets,aID,lvlIndex,ableIndex)!=null)
mob.tell(aID+" modified.");
else
{
mob.tell(aID+" removed.");
numAbles--;
}
updateList=true;
}
if(updateList)
{
if(numAbles>0)
E.setStat("NUMCABLE",""+numAbles);
else
E.setStat("NUMCABLE","");
int dex=0;
for(int s=0;s<levelSets.size();s++)
{
Integer lvl=(Integer)levelSets.elementAt(s,1);
DVector lvls=(DVector)levelSets.elementAt(s,2);
for(int l=0;l<lvls.size();l++)
{
E.setStat("GETCABLE"+dex,lvls.elementAt(l,1).toString());
E.setStat("GETCABLELVL"+dex,lvl.toString());
E.setStat("GETCABLEGAIN"+dex,lvls.elementAt(l,2).toString());
E.setStat("GETCABLEPROF"+dex,lvls.elementAt(l,3).toString());
E.setStat("GETCABLESECR"+dex,lvls.elementAt(l,4).toString());
E.setStat("GETCABLEPARM"+dex,lvls.elementAt(l,5).toString());
dex++;
}
}
}
}
else
{
mob.tell("(no change)");
return;
}
}
}
protected void genCulturalAbilities(MOB mob, Race E, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(true))
{
StringBuffer parts=new StringBuffer("");
int numResources=CMath.s_int(E.getStat("NUMCABLE"));
Vector ables=new Vector();
Vector data=new Vector();
for(int v=0;v<numResources;v++)
{
Ability A=CMClass.getAbility(E.getStat("GETCABLE"+v));
if(A!=null)
{
parts.append("("+A.ID()+"/"+E.getStat("GETCABLEPROF"+v)+"), ");
ables.addElement(A);
data.addElement(A.ID()+";"+E.getStat("GETCABLEPROF"+v));
}
}
if(parts.toString().endsWith(", "))
{parts.deleteCharAt(parts.length()-1);parts.deleteCharAt(parts.length()-1);}
mob.tell(showNumber+". Cultural Abilities: "+parts.toString()+".");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
String newName=mob.session().prompt("Enter an ability name to add or remove (?)\n\r:","");
if(newName.equalsIgnoreCase("?"))
mob.tell(CMLib.lister().reallyList(CMClass.abilities(),-1).toString());
else
if(newName.length()>0)
{
int partNum=-1;
for(int i=0;i<ables.size();i++)
if(CMLib.english().containsString(((Ability)ables.elementAt(i)).ID(),newName))
{ partNum=i; break;}
boolean updateList=false;
if(partNum<0)
{
Ability A=CMClass.getAbility(newName);
if(A==null)
mob.tell("That is neither an existing ability name, nor a valid one to add. Use ? for a list.");
else
{
StringBuffer str=new StringBuffer(A.ID()+";");
String prof=mob.session().prompt("Enter the default proficiency level (100): ","100");
str.append((""+CMath.s_int(prof)));
data.addElement(str.toString());
ables.addElement(A);
mob.tell(A.name()+" added.");
updateList=true;
}
}
else
{
Ability A=(Ability)ables.elementAt(partNum);
ables.removeElementAt(partNum);
data.removeElementAt(partNum);
updateList=true;
mob.tell(A.name()+" removed.");
}
if(updateList)
{
if(data.size()>0)
E.setStat("NUMCABLE",""+data.size());
else
E.setStat("NUMCABLE","");
for(int i=0;i<data.size();i++)
{
Vector V=CMParms.parseSemicolons((String)data.elementAt(i),false);
E.setStat("GETCABLE"+i,((String)V.elementAt(0)));
E.setStat("GETCABLEPROF"+i,((String)V.elementAt(1)));
}
}
}
else
{
mob.tell("(no change)");
return;
}
}
}
protected void modifyGenClass(MOB mob, CharClass me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Number of Class Names: ","NUMNAME");
int numNames=CMath.s_int(me.getStat("NUMNAME"));
if(numNames<=1)
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Class Name","NAME0");
else
for(int i=0;i<numNames;i++)
{
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Class Name #"+i+": ","NAME"+i);
if(i>0)
while(!mob.session().killFlag())
{
int oldNameLevel=CMath.s_int(me.getStat("NAMELEVEL"+i));
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Class Name #"+i+" class level: ","NAMELEVEL"+i);
int previousNameLevel=CMath.s_int(me.getStat("NAMELEVEL"+(i-1)));
int newNameLevel=CMath.s_int(me.getStat("NAMELEVEL"+i));
if((oldNameLevel!=newNameLevel)&&(newNameLevel<(previousNameLevel+1)))
{
mob.tell("This level may not be less than "+(previousNameLevel+1)+".");
me.setStat("NAMELEVEL"+i,""+(previousNameLevel+1));
showNumber--;
}
else
break;
}
}
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Base Class","BASE");
genClassAvailability(mob,me,++showNumber,showFlag);
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"HP Con Divisor","HPDIV");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"HP Die","HPDICE");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"HP #Dice","HPDIE");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Mana Divisor","MANADIV");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Mana #Dice","MANADICE");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Mana Die","MANADIE");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Prac/Level","LVLPRAC");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Attack/Level","LVLATT");
genAttackAttribute(mob,me,++showNumber,showFlag,"Attack Attribute","ATTATT");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Practices/1stLvl","FSTPRAC");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Trains/1stLvl","FSTTRAN");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Levels/Dmg Pt","LVLDAM");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Moves/Level","LVLMOVE");
genArmorCode(mob,me,++showNumber,showFlag,"Armor Restr.","ARMOR");
int armorMinorCode=CMath.s_int(me.getStat("ARMORMINOR"));
boolean newSpells=CMLib.english().prompt(mob,armorMinorCode>0,++showNumber,showFlag,"Armor restricts only spells");
me.setStat("ARMORMINOR",""+(newSpells?CMMsg.TYP_CAST_SPELL:-1));
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Limitations","STRLMT");
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Bonuses","STRBON");
genQualifications(mob,me,++showNumber,showFlag,"Qualifications","QUAL");
genEStats(mob,me,++showNumber,showFlag);
genAStats(mob,me,"ASTATS","CharStat Adjustments",++showNumber,showFlag);
genAStats(mob,me,"CSTATS","CharStat Settings",++showNumber,showFlag);
genAState(mob,me,"ASTATE","CharState Adjustments",++showNumber,showFlag);
genAState(mob,me,"STARTASTATE","New Player CharState Adj.",++showNumber,showFlag);
genClassFlags(mob,me,++showNumber,showFlag);
genWeaponRestr(mob,me,++showNumber,showFlag,"Weapon Restr.","NUMWEP","GETWEP");
genWeaponMaterials(mob,me,++showNumber,showFlag,"Weapon Materials","NUMWMAT","GETWMAT");
genOutfit(mob,me,++showNumber,showFlag);
genClassBuddy(mob,me,++showNumber,showFlag,"Stat-Modifying Class","STATCLASS");
genClassBuddy(mob,me,++showNumber,showFlag,"Special Events Class","EVENTCLASS");
genClassAbilities(mob,me,++showNumber,showFlag);
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Number of Security Code Sets: ","NUMSSET");
int numGroups=CMath.s_int(me.getStat("NUMSSET"));
for(int i=0;i<numGroups;i++)
{
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Security Codes in Set #"+i,"SSET"+i);
while(!mob.session().killFlag())
{
int oldGroupLevel=CMath.s_int(me.getStat("SSETLEVEL"+i));
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Class Level for Security Set #"+i+": ","SSETLEVEL"+i);
int previousGroupLevel=CMath.s_int(me.getStat("SSETLEVEL"+(i-1)));
int newGroupLevel=CMath.s_int(me.getStat("SSETLEVEL"+i));
if((oldGroupLevel!=newGroupLevel)
&&(i>0)
&&(newGroupLevel<(previousGroupLevel+1)))
{
mob.tell("This level may not be less than "+(previousGroupLevel+1)+".");
me.setStat("SSETLEVEL"+i,""+(previousGroupLevel+1));
showNumber--;
}
else
break;
}
}
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
}
}
}
protected void modifyGenAbility(MOB mob, Ability me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
// id is bad to change.. make them delete it.
//genText(mob,me,null,++showNumber,showFlag,"Enter the class","CLASS");
CMLib.english().promptStatStr(mob,me,null,++showNumber,showFlag,"Enter an ability name to add or remove","NAME",false);
CMLib.english().promptStatStr(mob,me,CMParms.toStringList(Ability.ACODE_DESCS)+","+CMParms.toStringList(Ability.DOMAIN_DESCS),++showNumber,showFlag,"Type, Domain","CLASSIFICATION",false);
CMLib.english().promptStatStr(mob,me,null,++showNumber,showFlag,"Command Words (comma sep)","TRIGSTR",false);
CMLib.english().promptStatStr(mob,me,CMParms.toStringList(Ability.RANGE_CHOICES),++showNumber,showFlag,"Minimum Range","MINRANGE",false);
CMLib.english().promptStatStr(mob,me,CMParms.toStringList(Ability.RANGE_CHOICES),++showNumber,showFlag,"Maximum Range","MAXRANGE",false);
CMLib.english().promptStatStr(mob,me,null,++showNumber,showFlag,"Affect String","DISPLAY",true);
CMLib.english().promptStatBool(mob,me,++showNumber,showFlag,"Is Auto-invoking","AUTOINVOKE");
CMLib.english().promptStatStr(mob,me,"0,"+CMParms.toStringList(Ability.FLAG_DESCS),++showNumber,showFlag,"Skill Flags (comma sep)","FLAGS",true);
CMLib.english().promptStatInt(mob,me,"-1,x,"+Integer.MAX_VALUE+","+Integer.MAX_VALUE+"-(1 to 100)",++showNumber,showFlag,"Override Cost","OVERRIDEMANA");
CMLib.english().promptStatStr(mob,me,CMParms.toStringList(Ability.USAGE_DESCS),++showNumber,showFlag,"Cost Type","USAGEMASK",false);
CMLib.english().promptStatStr(mob,me,"0,"+CMParms.toStringList(Ability.CAN_DESCS),++showNumber,showFlag,"Can Affect","CANAFFECTMASK",true);
CMLib.english().promptStatStr(mob,me,"0,"+CMParms.toStringList(Ability.CAN_DESCS),++showNumber,showFlag,"Can Target","CANTARGETMASK",true);
CMLib.english().promptStatStr(mob,me,CMParms.toStringList(Ability.QUALITY_DESCS),++showNumber,showFlag,"Quality Code","QUALITY",true);
CMLib.english().promptStatStr(mob,me,"The parameters for this field are LIKE the parameters for this property:\n\r\n\r"+
CMLib.help().getHelpText("Prop_HereAdjuster",mob,true).toString(),++showNumber,showFlag,"Affect Adjustments","HERESTATS",true);
CMLib.english().promptStatStr(mob,me,CMLib.masking().maskHelp("\n","disallow"),++showNumber,showFlag,"Caster Mask","CASTMASK",true);
CMLib.english().promptStatStr(mob,me,CMLib.help().getHelpText("Scriptable",mob,true).toString(),++showNumber,showFlag,"Scriptable Parm","SCRIPT",true);
CMLib.english().promptStatStr(mob,me,CMLib.masking().maskHelp("\n","disallow"),++showNumber,showFlag,"Target Mask","TARGETMASK",true);
CMLib.english().promptStatStr(mob,me,null,++showNumber,showFlag,"Fizzle Message","FIZZLEMSG",true);
CMLib.english().promptStatStr(mob,me,null,++showNumber,showFlag,"Auto-Cast Message","AUTOCASTMSG",true);
CMLib.english().promptStatStr(mob,me,null,++showNumber,showFlag,"Normal-Cast Message","CASTMSG",true);
CMLib.english().promptStatStr(mob,me,null,++showNumber,showFlag,"Post-Cast Message","POSTCASTMSG",true);
CMLib.english().promptStatStr(mob,me,CMParms.toStringList(CMMsg.TYPE_DESCS),++showNumber,showFlag,"Attack-Type","ATTACKCODE",true);
CMLib.english().promptStatStr(mob,me,"The parameters for this field are LIKE the parameters for this property:\n\r\n\r"+
CMLib.help().getHelpText("Prop_HereSpellCast",mob,true).toString(),++showNumber,showFlag,"Silent affects","POSTCASTAFFECT",true);
CMLib.english().promptStatStr(mob,me,"The parameters for this field are LIKE the parameters for this property:\n\r\n\r"+
CMLib.help().getHelpText("Prop_HereSpellCast",mob,true).toString(),++showNumber,showFlag,"Extra castings","POSTCASTABILITY",true);
CMLib.english().promptStatStr(mob,me,"Enter a damage or healing formula. Use +-*/()?. @x1=caster level, @x2=target level. Formula evaluates >0 for damage, <0 for healing. Requires Can Target!",++showNumber,showFlag,"Damage/Healing Formula","POSTCASTDAMAGE",true);
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
}
}
}
boolean genText(MOB mob, DVector set, String[] choices, String help, int showNumber, int showFlag, String FieldDisp, String Field)
throws IOException
{
int setDex=set.indexOf(Field);
if(((showFlag>0)&&(showFlag!=showNumber))||(setDex<0)) return true;
mob.tell(showNumber+". "+FieldDisp+": '"+((String)set.elementAt(setDex,2)+"'."));
if((showFlag!=showNumber)&&(showFlag>-999)) return true;
String newName=mob.session().prompt("Enter a new one\n\r:","");
if(newName.trim().length()==0)
{
mob.tell("(no change)");
return false;
}
if((newName.equalsIgnoreCase("?"))&&(help!=null))
{
if((mob.session()==null)||(mob.session().killFlag()))
return false;
mob.tell(help);
return genText(mob,set,choices,help,showNumber,showFlag,FieldDisp,Field);
}
if(newName.equalsIgnoreCase("null")) newName="";
if((choices==null)||(choices.length==0))
{
set.setElementAt(setDex,2,newName);
return true;
}
boolean found=false;
for(int s=0;s<choices.length;s++)
{
if(newName.equalsIgnoreCase(choices[s]))
{ newName=choices[s]; found=true; break;}
}
if(!found)
{
if((mob.session()==null)||(mob.session().killFlag()))
return false;
mob.tell(help);
return genText(mob,set,choices,help,showNumber,showFlag,FieldDisp,Field);
}
set.setElementAt(setDex,2,newName);
return true;
}
protected boolean modifyComponent(MOB mob, DVector components, int componentIndex)
throws IOException
{
DVector decoded=CMLib.ableMapper().getAbilityComponentDecodedDVector(components,componentIndex);
if(mob.isMonster()) return true;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
String choices="Your choices are: ";
String allComponents=CMParms.toStringList(RawMaterial.MATERIAL_DESCS)+","+CMParms.toStringList(RawMaterial.RESOURCE_DESCS);
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genText(mob,decoded,(new String[]{"&&","||","X"}),choices+" &&, ||, X",++showNumber,showFlag,"Conjunction (X Deletes) (?)","ANDOR");
if(((String)decoded.elementAt(0,2)).equalsIgnoreCase("X")) return false;
genText(mob,decoded,(new String[]{"INVENTORY","HELD","WORN"}),choices+" INVENTORY, HELD, WORN",++showNumber,showFlag,"Component position (?)","DISPOSITION");
genText(mob,decoded,(new String[]{"KEPT","CONSUMED"}),choices+" KEPT, CONSUMED",++showNumber,showFlag,"Component fate (?)","FATE");
genText(mob,decoded,null,null,++showNumber,showFlag,"Amount of component","AMOUNT");
genText(mob,decoded,null,allComponents,++showNumber,showFlag,"Type of component (?)","COMPONENTID");
genText(mob,decoded,null,CMLib.masking().maskHelp("\n","disallow"),++showNumber,showFlag,"Component applies-to mask (?)","MASK");
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
}
}
CMLib.ableMapper().setAbilityComponentCodedFromDecodedDVector(decoded,components,componentIndex);
return true;
}
protected void modifyComponents(MOB mob, String componentID)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
DVector codedDV=CMLib.ableMapper().getAbilityComponentDVector(componentID);
if(codedDV!=null)
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
for(int v=0;v<codedDV.size();v++)
if((mob.session()!=null)&&(!mob.session().killFlag()))
{
showNumber++;
if((showFlag>0)&&(showFlag!=showNumber)) continue;
mob.tell(showNumber+": '"+CMLib.ableMapper().getAbilityComponentDesc(null,codedDV,v)+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) continue;
if(!modifyComponent(mob,codedDV,v))
{
codedDV.removeElementAt(v);
v--;
}
}
while((mob.session()!=null)&&(!mob.session().killFlag()))
{
showNumber++;
mob.tell(showNumber+". Add new component requirement.");
if((showFlag==showNumber)||(showFlag<=-999))
{
CMLib.ableMapper().addBlankAbilityComponent(codedDV);
boolean success=modifyComponent(mob,codedDV,codedDV.size()-1);
if(!success)
codedDV.removeElementAt(codedDV.size()-1);
else
if(showFlag<=-999)
continue;
}
break;
}
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
}
}
}
protected void modifyGenRace(MOB mob, Race me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Name","NAME");
genCat(mob,me,++showNumber,showFlag);
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Base Weight","BWEIGHT");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Weight Variance","VWEIGHT");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Base Male Height","MHEIGHT");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Base Female Height","FHEIGHT");
CMLib.english().promptStatInt(mob,me,++showNumber,showFlag,"Height Variance","VHEIGHT");
genRaceAvailability(mob,me,++showNumber,showFlag);
genDisableFlags(mob,me,++showNumber,showFlag);
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Leaving text","LEAVE");
CMLib.english().promptStatStr(mob,me,++showNumber,showFlag,"Arriving text","ARRIVE");
genRaceBuddy(mob,me,++showNumber,showFlag,"Health Race","HEALTHRACE");
genRaceBuddy(mob,me,++showNumber,showFlag,"Event Race","EVENTRACE");
genBodyParts(mob,me,++showNumber,showFlag);
genRaceWearFlags(mob,me,++showNumber,showFlag);
genAgingChart(mob,me,++showNumber,showFlag);
CMLib.english().promptStatBool(mob,me,++showNumber,showFlag,"Never create corpse","BODYKILL");
genEStats(mob,me,++showNumber,showFlag);
genAStats(mob,me,"ASTATS","CharStat Adjustments",++showNumber,showFlag);
genAStats(mob,me,"CSTATS","CharStat Settings",++showNumber,showFlag);
genAState(mob,me,"ASTATE","CharState Adjustments",++showNumber,showFlag);
genAState(mob,me,"STARTASTATE","New Player CharState Adj.",++showNumber,showFlag);
genResources(mob,me,++showNumber,showFlag);
genOutfit(mob,me,++showNumber,showFlag);
genWeapon(mob,me,++showNumber,showFlag);
genRaceBuddy(mob,me,++showNumber,showFlag,"Weapons Race","WEAPONRACE");
genRacialAbilities(mob,me,++showNumber,showFlag);
genCulturalAbilities(mob,me,++showNumber,showFlag);
//genRacialEffects(mob,me,++showNumber,showFlag);
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
}
}
}
protected void modifyGenItem(MOB mob, Item me)
throws IOException
{
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
if(mob.isMonster()) return;
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,me,++showNumber,showFlag);
genMaterialCode(mob,me,++showNumber,showFlag);
if(me instanceof ClanItem)
genClanItem(mob,(ClanItem)me,++showNumber,showFlag);
if(me instanceof ShipComponent)
{
if(me instanceof ShipComponent.ShipPanel)
genPanelType(mob,(ShipComponent.ShipPanel)me,++showNumber,showFlag);
}
if(me instanceof PackagedItems)
((PackagedItems)me).setNumberOfItemsInPackage(CMLib.english().prompt(mob,((PackagedItems)me).numberOfItemsInPackage(),++showNumber,showFlag,"Number of items in the package"));
genGettable(mob,me,++showNumber,showFlag);
genReadable1(mob,me,++showNumber,showFlag);
genReadable2(mob,me,++showNumber,showFlag);
if(me instanceof Recipe) genRecipe(mob,(Recipe)me,++showNumber,showFlag);
if(me instanceof Light) genBurnout(mob,(Light)me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
if(me instanceof Coins)
genCoinStuff(mob,(Coins)me,++showNumber,showFlag);
else
genAbility(mob,me,++showNumber,showFlag);
genUses(mob,me,++showNumber,showFlag);
if(me instanceof Wand)
genMaxUses(mob,(Wand)me,++showNumber,showFlag);
genValue(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
if(me instanceof LandTitle)
genTitleRoom(mob,(LandTitle)me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
}
protected void modifyGenFood(MOB mob, Food me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genValue(mob,me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genMaterialCode(mob,me,++showNumber,showFlag);
genNourishment(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genGettable(mob,me,++showNumber,showFlag);
genReadable1(mob,me,++showNumber,showFlag);
genReadable2(mob,me,++showNumber,showFlag);
if(me instanceof Light) genBurnout(mob,(Light)me,++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
}
protected void modifyGenDrink(MOB mob, Drink me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,(Item)me,++showNumber,showFlag);
genValue(mob,(Item)me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
genThirstQuenched(mob,me,++showNumber,showFlag);
genMaterialCode(mob,(Item)me,++showNumber,showFlag);
genDrinkHeld(mob,me,++showNumber,showFlag);
genGettable(mob,(Item)me,++showNumber,showFlag);
genReadable1(mob,(Item)me,++showNumber,showFlag);
genReadable2(mob,(Item)me,++showNumber,showFlag);
if(me instanceof Light) genBurnout(mob,(Light)me,++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
if(me instanceof Container)
genCapacity(mob,(Container)me,++showNumber,showFlag);
if(me instanceof Perfume)
((Perfume)me).setSmellList(CMLib.english().prompt(mob,((Perfume)me).getSmellList(),++showNumber,showFlag,"Smells list (; delimited)"));
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
}
protected void modifyGenWallpaper(MOB mob, Item me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genReadable1(mob,me,++showNumber,showFlag);
genReadable2(mob,me,++showNumber,showFlag);
if(me instanceof Light) genBurnout(mob,(Light)me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
}
protected void modifyGenMap(MOB mob, com.planet_ink.coffee_mud.Items.interfaces.Map me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,me,++showNumber,showFlag);
genGettable(mob,me,++showNumber,showFlag);
genReadable1(mob,me,++showNumber,showFlag);
genReadable2(mob,me,++showNumber,showFlag);
genValue(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
genMaterialCode(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
}
protected void modifyGenContainer(MOB mob, Container me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
genCapacity(mob,me,++showNumber,showFlag);
if(me instanceof ShipComponent)
{
if(me instanceof ShipComponent.ShipPanel)
genPanelType(mob,(ShipComponent.ShipPanel)me,++showNumber,showFlag);
}
genLidsNLocks(mob,me,++showNumber,showFlag);
genMaterialCode(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,me,++showNumber,showFlag);
genValue(mob,me,++showNumber,showFlag);
genUses(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
if(me instanceof DeadBody)
genCorpseData(mob,(DeadBody)me,++showNumber,showFlag);
if(me instanceof ClanItem)
genClanItem(mob,(ClanItem)me,++showNumber,showFlag);
genGettable(mob,me,++showNumber,showFlag);
genReadable1(mob,me,++showNumber,showFlag);
genReadable2(mob,me,++showNumber,showFlag);
if(me instanceof Light) genBurnout(mob,(Light)me,++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
if(me instanceof Rideable)
{
genRideable1(mob,(Rideable)me,++showNumber,showFlag);
genRideable2(mob,(Rideable)me,++showNumber,showFlag);
}
if(me instanceof Exit)
{
genDoorName(mob,(Exit)me,++showNumber,showFlag);
genClosedText(mob,(Exit)me,++showNumber,showFlag);
}
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
}
protected void modifyGenWeapon(MOB mob, Weapon me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genAttack(mob,me,++showNumber,showFlag);
genDamage(mob,me,++showNumber,showFlag);
genMaterialCode(mob,me,++showNumber,showFlag);
genWeaponType(mob,me,++showNumber,showFlag);
genWeaponClassification(mob,me,++showNumber,showFlag);
genWeaponRanges(mob,me,++showNumber,showFlag);
if(me instanceof Wand)
{
genReadable1(mob,me,++showNumber,showFlag);
genReadable2(mob,me,++showNumber,showFlag);
genUses(mob,me,++showNumber,showFlag);
genMaxUses(mob,(Wand)me,++showNumber,showFlag);
if(me instanceof Light) genBurnout(mob,(Light)me,++showNumber,showFlag);
}
else
genWeaponAmmo(mob,me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
if((!me.requiresAmmunition())&&(!(me instanceof Wand)))
genCondition(mob,me,++showNumber,showFlag);
genAbility(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,me,++showNumber,showFlag);
if(me instanceof ClanItem)
genClanItem(mob,(ClanItem)me,++showNumber,showFlag);
genGettable(mob,me,++showNumber,showFlag);
genValue(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
}
protected void modifyGenArmor(MOB mob, Armor me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genMaterialCode(mob,me,++showNumber,showFlag);
genWornLocation(mob,me,++showNumber,showFlag);
genLayer(mob,me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
genArmor(mob,me,++showNumber,showFlag);
genCondition(mob,me,++showNumber,showFlag);
genAbility(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,me,++showNumber,showFlag);
if(me instanceof ClanItem)
genClanItem(mob,(ClanItem)me,++showNumber,showFlag);
genGettable(mob,me,++showNumber,showFlag);
genCapacity(mob,me,++showNumber,showFlag);
genLidsNLocks(mob,me,++showNumber,showFlag);
genReadable1(mob,me,++showNumber,showFlag);
genReadable2(mob,me,++showNumber,showFlag);
if(me instanceof Light) genBurnout(mob,(Light)me,++showNumber,showFlag);
genValue(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genSize(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
}
protected void modifyGenInstrument(MOB mob, MusicalInstrument me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genMaterialCode(mob,me,++showNumber,showFlag);
genWornLocation(mob,me,++showNumber,showFlag);
genRejuv(mob,me,++showNumber,showFlag);
genAbility(mob,me,++showNumber,showFlag);
genSecretIdentity(mob,me,++showNumber,showFlag);
genGettable(mob,me,++showNumber,showFlag);
genInstrumentType(mob,me,++showNumber,showFlag);
genValue(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
}
protected void modifyGenExit(MOB mob, Exit me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genDoorsNLocks(mob,me,++showNumber,showFlag);
if(me.hasADoor())
{
genClosedText(mob,me,++showNumber,showFlag);
genDoorName(mob,me,++showNumber,showFlag);
genOpenWord(mob,me,++showNumber,showFlag);
genCloseWord(mob,me,++showNumber,showFlag);
}
genExitMisc(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverEnvStats();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
}
}
}
protected void modifyGenMOB(MOB mob, MOB me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
int oldLevel=me.baseEnvStats().level();
genLevel(mob,me,++showNumber,showFlag);
if((oldLevel<2)&&(me.baseEnvStats().level()>1))
me.baseCharStats().getCurrentClass().fillOutMOB(me,me.baseEnvStats().level());
genRejuv(mob,me,++showNumber,showFlag);
genRace(mob,me,++showNumber,showFlag);
Faction F=null;
for(Enumeration e=CMLib.factions().factionSet().elements();e.hasMoreElements();)
{
F=(Faction)e.nextElement();
if((!F.hasFaction(me))&&(F.findAutoDefault(me)!=Integer.MAX_VALUE))
mob.addFaction(F.factionID(),F.findAutoDefault(me));
if(F.showineditor())
genSpecialFaction(mob,me,++showNumber,showFlag,F);
}
genGender(mob,me,++showNumber,showFlag);
genHeight(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genClan(mob,me,++showNumber,showFlag);
genSpeed(mob,me,++showNumber,showFlag);
if((oldLevel<2)&&(me.baseEnvStats().level()>1))
me.baseEnvStats().setDamage((int)Math.round(CMath.div(me.baseEnvStats().damage(),me.baseEnvStats().speed())));
genAttack(mob,me,++showNumber,showFlag);
genDamage(mob,me,++showNumber,showFlag);
genArmor(mob,me,++showNumber,showFlag);
genHitPoints(mob,me,++showNumber,showFlag);
genMoney(mob,me,++showNumber,showFlag);
genAbilities(mob,me,++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genSensesMask(mob,me.baseEnvStats(),++showNumber,showFlag);
if(me instanceof Rideable)
{
genRideable1(mob,(Rideable)me,++showNumber,showFlag);
genRideable2(mob,(Rideable)me,++showNumber,showFlag);
}
if(me instanceof Deity)
{
genDeity1(mob,(Deity)me,++showNumber,showFlag);
genDeity2(mob,(Deity)me,++showNumber,showFlag);
genDeity3(mob,(Deity)me,++showNumber,showFlag);
genDeity4(mob,(Deity)me,++showNumber,showFlag);
genDeity5(mob,(Deity)me,++showNumber,showFlag);
genDeity8(mob,(Deity)me,++showNumber,showFlag);
genDeity9(mob,(Deity)me,++showNumber,showFlag);
genDeity6(mob,(Deity)me,++showNumber,showFlag);
genDeity0(mob,(Deity)me,++showNumber,showFlag);
genDeity7(mob,(Deity)me,++showNumber,showFlag);
genDeity11(mob,(Deity)me,++showNumber,showFlag);
}
genFaction(mob,me,++showNumber,showFlag);
genTattoos(mob,me,++showNumber,showFlag);
genExpertises(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverCharStats();
me.recoverMaxState();
me.recoverEnvStats();
me.resetToMaxState();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
me.setMiscText(me.text());
}
}
mob.tell("\n\rNow don't forget to equip "+me.charStats().himher()+" with stuff before saving!\n\r");
}
protected void modifyPlayer(MOB mob, MOB me)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
String oldName=me.Name();
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
while((!me.Name().equals(oldName))&&(CMLib.database().DBUserSearch(null,me.Name())))
{
mob.tell("The name given cannot be chosen, as it is already being used.");
genName(mob,me,showNumber,showFlag);
}
genPassword(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
genLevel(mob,me,++showNumber,showFlag);
genRace(mob,me,++showNumber,showFlag);
genCharClass(mob,me,++showNumber,showFlag);
genCharStats(mob,me,++showNumber,showFlag);
Faction F=null;
for(Enumeration e=CMLib.factions().factionSet().elements();e.hasMoreElements();)
{
F=(Faction)e.nextElement();
if((!F.hasFaction(me))&&(F.findAutoDefault(me)!=Integer.MAX_VALUE))
mob.addFaction(F.factionID(),F.findAutoDefault(me));
if(F.showineditor())
genSpecialFaction(mob,me,++showNumber,showFlag,F);
}
genGender(mob,me,++showNumber,showFlag);
genHeight(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
genSpeed(mob,me,++showNumber,showFlag);
genAttack(mob,me,++showNumber,showFlag);
genDamage(mob,me,++showNumber,showFlag);
genArmor(mob,me,++showNumber,showFlag);
genHitPoints(mob,me,++showNumber,showFlag);
genMoney(mob,me,++showNumber,showFlag);
me.setTrains(CMLib.english().prompt(mob,me.getTrains(),++showNumber,showFlag,"Training Points"));
me.setPractices(CMLib.english().prompt(mob,me.getPractices(),++showNumber,showFlag,"Practice Points"));
me.setQuestPoint(CMLib.english().prompt(mob,me.getQuestPoint(),++showNumber,showFlag,"Quest Points"));
genAbilities(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genSensesMask(mob,me.baseEnvStats(),++showNumber,showFlag);
if(me instanceof Rideable)
{
genRideable1(mob,(Rideable)me,++showNumber,showFlag);
genRideable2(mob,(Rideable)me,++showNumber,showFlag);
}
genFaction(mob,me,++showNumber,showFlag);
genTattoos(mob,me,++showNumber,showFlag);
genExpertises(mob,me,++showNumber,showFlag);
genTitles(mob,me,++showNumber,showFlag);
genEmail(mob,me,++showNumber,showFlag);
genSecurity(mob,me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
genNotes(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(me.playerStats()!=null)
for(int x=me.playerStats().getSaveStatIndex();x<me.playerStats().getStatCodes().length;x++)
me.playerStats().setStat(me.playerStats().getStatCodes()[x],CMLib.english().prompt(mob,me.playerStats().getStat(me.playerStats().getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.playerStats().getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
me.recoverCharStats();
me.recoverMaxState();
me.recoverEnvStats();
me.resetToMaxState();
if(!oldName.equals(me.Name()))
{
MOB fakeMe=(MOB)me.copyOf();
fakeMe.setName(oldName);
CMLib.database().DBDeleteMOB(fakeMe);
CMLib.database().DBCreateCharacter(me);
}
CMLib.database().DBUpdatePlayer(me);
CMLib.database().DBUpdateFollowers(me);
}
}
}
protected void genClanStatus(MOB mob, Clan C, int showNumber, int showFlag)
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Clan Status: "+Clan.CLANSTATUS_DESC[C.getStatus()]);
if((showFlag!=showNumber)&&(showFlag>-999)) return;
switch(C.getStatus())
{
case Clan.CLANSTATUS_ACTIVE:
C.setStatus(Clan.CLANSTATUS_PENDING);
mob.tell("Clan '"+C.name()+"' has been changed from active to pending!");
break;
case Clan.CLANSTATUS_PENDING:
C.setStatus(Clan.CLANSTATUS_ACTIVE);
mob.tell("Clan '"+C.name()+"' has been changed from pending to active!");
break;
case Clan.CLANSTATUS_FADING:
C.setStatus(Clan.CLANSTATUS_ACTIVE);
mob.tell("Clan '"+C.name()+"' has been changed from fading to active!");
break;
default:
mob.tell("Clan '"+C.name()+"' has not been changed!");
break;
}
}
protected void genClanGovt(MOB mob, Clan C, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Government type: '"+C.typeName()+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
while((mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a new one (?)\n\r:","");
if(newName.trim().length()==0)
{
mob.tell("(no change)");
return;
}
int newGovt=-1;
StringBuffer gvts=new StringBuffer();
for(int i=0;i<Clan.GVT_DESCS.length;i++)
{
gvts.append(Clan.GVT_DESCS[i]+", ");
if(newName.equalsIgnoreCase(Clan.GVT_DESCS[i]))
newGovt=i;
}
gvts=new StringBuffer(gvts.substring(0,gvts.length()-2));
if(newGovt<0)
mob.tell("That government type is invalid. Valid types include: "+gvts.toString());
else
{
C.setGovernment(newGovt);
break;
}
}
}
protected double genAuctionPrompt(MOB mob, double oldVal, int showNumber, int showFlag, String msg, boolean pct)
throws IOException
{
String oldStr=(oldVal<0)?"":(pct?""+(oldVal*100.0)+"%":""+oldVal);
String newStr=CMLib.english().prompt(mob,oldStr,showNumber,showFlag,msg);
if(newStr.trim().length()==0)
return -1.0;
if((pct)&&(!CMath.isPct(newStr))&&(!CMath.isNumber(newStr)))
return -1.0;
else
if((!pct)&&(!CMath.isNumber(newStr)))
return -1.0;
if(pct) return CMath.s_pct(newStr);
return CMath.s_double(newStr);
}
protected int genAuctionPrompt(MOB mob, int oldVal, int showNumber, int showFlag, String msg)
throws IOException
{
String oldStr=(oldVal<0)?"":""+oldVal;
String newStr=CMLib.english().prompt(mob,oldStr,showNumber,showFlag,msg);
if(newStr.trim().length()==0)
return -1;
if(!CMath.isNumber(newStr))
return -1;
return CMath.s_int(newStr);
}
protected void genClanRole(MOB mob, Clan C, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
mob.tell(showNumber+". Clan (Role): '"+CMLib.clans().getRoleName(C.getGovernment(),C.getAutoPosition(),true,false)+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
while((mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a new one (?)\n\r:","");
if(newName.trim().length()==0)
{
mob.tell("(no change)");
return;
}
int newRole=-1;
StringBuffer roles=new StringBuffer();
for(int i=0;i<Clan.ROL_DESCS[C.getGovernment()].length;i++)
{
roles.append(Clan.ROL_DESCS[C.getGovernment()][i]+", ");
if(newName.equalsIgnoreCase(Clan.ROL_DESCS[C.getGovernment()][i]))
newRole=Clan.POSORDER[i];
}
roles=new StringBuffer(roles.substring(0,roles.length()-2));
if(newRole<0)
mob.tell("That role is invalid. Valid roles include: "+roles.toString());
else
{
C.setAutoPosition(newRole);
break;
}
}
}
protected void genClanClass(MOB mob, Clan C, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return;
CharClass CC=CMClass.getCharClass(C.getClanClass());
if(CC==null)CC=CMClass.findCharClass(C.getClanClass());
String clasName=(CC==null)?"NONE":CC.name();
mob.tell(showNumber+". Clan Auto-Class: '"+clasName+"'.");
if((showFlag!=showNumber)&&(showFlag>-999)) return;
while((mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a new one (?)\n\r:","");
if(newName.trim().equalsIgnoreCase("none"))
{
C.setClanClass("");
return;
}
else
if(newName.trim().length()==0)
{
mob.tell("(no change)");
return;
}
CharClass newC=null;
StringBuffer clss=new StringBuffer();
for(Enumeration e=CMClass.charClasses();e.hasMoreElements();)
{
CC=(CharClass)e.nextElement();
clss.append(CC.name()+", ");
if(newName.equalsIgnoreCase(CC.name())||(newName.equalsIgnoreCase(CC.ID())))
newC=CC;
}
clss=new StringBuffer(clss.substring(0,clss.length()-2));
if(newC==null)
mob.tell("That class name is invalid. Valid names include: "+clss.toString());
else
{
C.setClanClass(newC.ID());
break;
}
}
}
String genClanRoom(MOB mob, Clan C, String oldRoomID, String promptCode, int showNumber, int showFlag)
throws IOException
{
if((showFlag>0)&&(showFlag!=showNumber)) return oldRoomID;
mob.tell(showNumber+CMStrings.replaceAll(promptCode,"@x1",oldRoomID));
if((showFlag!=showNumber)&&(showFlag>-999)) return oldRoomID;
while((mob.session()!=null)&&(!mob.session().killFlag()))
{
String newName=mob.session().prompt("Enter a new one (null)\n\r:","");
if(newName.trim().equalsIgnoreCase("null"))
return "";
else
if(newName.trim().length()==0)
{
mob.tell("(no change)");
return oldRoomID;
}
Room newRoom=CMLib.map().getRoom(newName);
if((newRoom==null)
||(CMLib.map().getExtendedRoomID(newRoom).length()==0)
||(!CMLib.law().doesOwnThisProperty(C.clanID(),newRoom)))
mob.tell("That is either not a valid room id, or that room is not owned by the clan.");
else
return CMLib.map().getExtendedRoomID(newRoom);
}
return oldRoomID;
}
protected void modifyClan(MOB mob, Clan C)
throws IOException
{
if(mob.isMonster())
return;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
String oldName=C.ID();
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
mob.tell("*. Name: '"+C.name()+"'.");
int showNumber=0;
genClanGovt(mob,C,++showNumber,showFlag);
C.setPremise(CMLib.english().prompt(mob,C.getPremise(),++showNumber,showFlag,"Clan Premise: ",true));
C.setExp(CMLib.english().prompt(mob,C.getExp(),++showNumber,showFlag,"Clan Experience: "));
C.setTaxes(CMLib.english().prompt(mob,C.getTaxes(),++showNumber,showFlag,"Clan Tax Rate (X 100%): "));
C.setMorgue(genClanRoom(mob,C,C.getMorgue(),". Morgue RoomID: '@x1'.",++showNumber,showFlag));
C.setRecall(genClanRoom(mob,C,C.getRecall(),". Clan Home RoomID: '@x1'.",++showNumber,showFlag));
C.setDonation(genClanRoom(mob,C,C.getDonation(),". Clan Donate RoomID: '@x1'.",++showNumber,showFlag));
genClanAccept(mob,C,++showNumber,showFlag);
genClanClass(mob,C,++showNumber,showFlag);
genClanRole(mob,C,++showNumber,showFlag);
genClanStatus(mob,C,++showNumber,showFlag);
genClanMembers(mob,C,++showNumber,showFlag);
/*setClanRelations, votes?*/
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
if(!oldName.equals(C.ID()))
{
//cycle through everything changing the name
CMLib.database().DBDeleteClan(C);
CMLib.database().DBCreateClan(C);
}
C.update();
}
}
}
protected void modifyGenShopkeeper(MOB mob, ShopKeeper me)
throws IOException
{
if(mob.isMonster())
return;
if(!(me instanceof MOB))
return;
MOB mme=(MOB)me;
boolean ok=false;
int showFlag=-1;
if(CMProps.getIntVar(CMProps.SYSTEMI_EDITORTYPE)>0)
showFlag=-999;
while((mob.session()!=null)&&(!mob.session().killFlag())&&(!ok))
{
int showNumber=0;
genName(mob,me,++showNumber,showFlag);
genDisplayText(mob,me,++showNumber,showFlag);
genDescription(mob,me,++showNumber,showFlag);
int oldLevel=me.baseEnvStats().level();
genLevel(mob,me,++showNumber,showFlag);
if((oldLevel<2)&&(me.baseEnvStats().level()>1))
mme.baseCharStats().getCurrentClass().fillOutMOB(mme,me.baseEnvStats().level());
genRejuv(mob,me,++showNumber,showFlag);
genRace(mob,mme,++showNumber,showFlag);
genHeight(mob,me,++showNumber,showFlag);
genWeight(mob,me,++showNumber,showFlag);
Faction F=null;
for(Enumeration e=CMLib.factions().factionSet().elements();e.hasMoreElements();)
{
F=(Faction)e.nextElement();
if((!F.hasFaction((MOB)me))&&(F.findAutoDefault((MOB)me)!=Integer.MAX_VALUE))
mob.addFaction(F.factionID(),F.findAutoDefault((MOB)me));
if(F.showineditor())
genSpecialFaction(mob,(MOB)me,++showNumber,showFlag,F);
}
genGender(mob,mme,++showNumber,showFlag);
genClan(mob,mme,++showNumber,showFlag);
genSpeed(mob,me,++showNumber,showFlag);
if((oldLevel<2)&&(me.baseEnvStats().level()>1))
me.baseEnvStats().setDamage((int)Math.round(CMath.div(me.baseEnvStats().damage(),me.baseEnvStats().speed())));
genAttack(mob,me,++showNumber,showFlag);
genDamage(mob,me,++showNumber,showFlag);
genArmor(mob,me,++showNumber,showFlag);
if(me instanceof MOB)
genHitPoints(mob,(MOB)me,++showNumber,showFlag);
genMoney(mob,mme,++showNumber,showFlag);
genAbilities(mob,mme,++showNumber,showFlag);
genBehaviors(mob,me,++showNumber,showFlag);
genAffects(mob,me,++showNumber,showFlag);
if(!(me instanceof Auctioneer))
{
genShopkeeper1(mob,me,++showNumber,showFlag);
genShopkeeper2(mob,me,++showNumber,showFlag);
genEconomics1(mob,me,++showNumber,showFlag);
genEconomics5(mob,me,++showNumber,showFlag);
}
genEconomics6(mob,me,++showNumber,showFlag);
if(me instanceof Banker)
{
genBanker1(mob,(Banker)me,++showNumber,showFlag);
genBanker2(mob,(Banker)me,++showNumber,showFlag);
genBanker3(mob,(Banker)me,++showNumber,showFlag);
genBanker4(mob,(Banker)me,++showNumber,showFlag);
}
else
if(me instanceof PostOffice)
{
((PostOffice)me).setPostalChain(CMLib.english().prompt(mob,((PostOffice)me).postalChain(),++showNumber,showFlag,"Postal chain"));
((PostOffice)me).setFeeForNewBox(CMLib.english().prompt(mob,((PostOffice)me).feeForNewBox(),++showNumber,showFlag,"Fee to open a new box"));
((PostOffice)me).setMinimumPostage(CMLib.english().prompt(mob,((PostOffice)me).minimumPostage(),++showNumber,showFlag,"Minimum postage cost"));
((PostOffice)me).setPostagePerPound(CMLib.english().prompt(mob,((PostOffice)me).postagePerPound(),++showNumber,showFlag,"Postage cost per pound after 1st pound"));
((PostOffice)me).setHoldFeePerPound(CMLib.english().prompt(mob,((PostOffice)me).holdFeePerPound(),++showNumber,showFlag,"Holding fee per pound per month"));
((PostOffice)me).setMaxMudMonthsHeld(CMLib.english().prompt(mob,((PostOffice)me).maxMudMonthsHeld(),++showNumber,showFlag,"Maximum number of months held"));
}
else
if(me instanceof Auctioneer)
{
((Auctioneer)me).setAuctionHouse(CMLib.english().prompt(mob,((Auctioneer)me).auctionHouse(),++showNumber,showFlag,"Auction house"));
((Auctioneer)me).setTimedListingPrice(genAuctionPrompt(mob,((Auctioneer)me).timedListingPrice(),++showNumber,showFlag,"Flat fee per auction",false));
((Auctioneer)me).setTimedListingPct(genAuctionPrompt(mob,((Auctioneer)me).timedListingPct(),++showNumber,showFlag,"Listing Cut/%Pct per day",true));
((Auctioneer)me).setTimedFinalCutPct(genAuctionPrompt(mob,((Auctioneer)me).timedFinalCutPct(),++showNumber,showFlag,"Cut/%Pct of final price",true));
((Auctioneer)me).setMaxTimedAuctionDays(genAuctionPrompt(mob,((Auctioneer)me).maxTimedAuctionDays(),++showNumber,showFlag,"Maximum number of auction mud-days"));
((Auctioneer)me).setMinTimedAuctionDays(genAuctionPrompt(mob,((Auctioneer)me).minTimedAuctionDays(),++showNumber,showFlag,"Minimum number of auction mud-days"));
}
else
{
genEconomics2(mob,me,++showNumber,showFlag);
genEconomics3(mob,me,++showNumber,showFlag);
genEconomics4(mob,me,++showNumber,showFlag);
}
genDisposition(mob,me.baseEnvStats(),++showNumber,showFlag);
genSensesMask(mob,me.baseEnvStats(),++showNumber,showFlag);
genFaction(mob,mme,++showNumber,showFlag);
genTattoos(mob,(MOB)me,++showNumber,showFlag);
genExpertises(mob,(MOB)me,++showNumber,showFlag);
genImage(mob,me,++showNumber,showFlag);
for(int x=me.getSaveStatIndex();x<me.getStatCodes().length;x++)
me.setStat(me.getStatCodes()[x],CMLib.english().prompt(mob,me.getStat(me.getStatCodes()[x]),++showNumber,showFlag,CMStrings.capitalizeAndLower(me.getStatCodes()[x])));
if(showFlag<-900){ ok=true; break;}
if(showFlag>0){ showFlag=-1; continue;}
showFlag=CMath.s_int(mob.session().prompt("Edit which? ",""));
if(showFlag<=0)
{
showFlag=-1;
ok=true;
mme.recoverCharStats();
mme.recoverMaxState();
me.recoverEnvStats();
mme.resetToMaxState();
if(me.text().length()>=maxLength)
{
mob.tell("\n\rThe data entered exceeds the string limit of "+maxLength+" characters. Please modify!");
ok=false;
}
me.setMiscText(me.text());
}
}
mob.tell("\n\rNow don't forget to equip him with non-generic items before saving! If you DO add items to his list, be sure to come back here in case you've exceeded the string limit again.\n\r");
}
}
|
git-svn-id: svn://192.168.1.10/public/CoffeeMud@6747 0d6f1817-ed0e-0410-87c9-987e46238f29
| com/planet_ink/coffee_mud/Commands/BaseGenerics.java | ||
Java | apache-2.0 | d0d3505d570336c8c39a48c92ee28e28505edec4 | 0 | dslomov/bazel,nkhuyu/bazel,xindaya/bazel,mrdomino/bazel,hhclam/bazel,wakashige/bazel,aehlig/bazel,Ansahmadiba/bazel,anupcshan/bazel,bazelbuild/bazel,katre/bazel,dslomov/bazel,sicipio/bazel,perezd/bazel,wakashige/bazel,mrdomino/bazel,twitter-forks/bazel,dslomov/bazel,Asana/bazel,hermione521/bazel,mikelalcon/bazel,dhootha/bazel,joshua0pang/bazel,Asana/bazel,damienmg/bazel,kchodorow/bazel,twitter-forks/bazel,Asana/bazel,akira-baruah/bazel,ButterflyNetwork/bazel,dslomov/bazel,manashmndl/bazel,bazelbuild/bazel,twitter-forks/bazel,sicipio/bazel,JackSullivan/bazel,UrbanCompass/bazel,d/bazel,LuminateWireless/bazel,asarazan/bazel,kchodorow/bazel,UrbanCompass/bazel,xindaya/bazel,dhootha/bazel,Ansahmadiba/bazel,iamthearm/bazel,kamalmarhubi/bazel,katre/bazel,joshua0pang/bazel,ruo91/bazel,dropbox/bazel,anupcshan/bazel,dhootha/bazel,iamthearm/bazel,iamthearm/bazel,katre/bazel,variac/bazel,anupcshan/bazel,xindaya/bazel,murugamsm/bazel,perezd/bazel,variac/bazel,dhootha/bazel,aehlig/bazel,mikelikespie/bazel,sicipio/bazel,dhootha/bazel,Ansahmadiba/bazel,Digas29/bazel,davidzchen/bazel,mikelalcon/bazel,cushon/bazel,ulfjack/bazel,ButterflyNetwork/bazel,dslomov/bazel,akira-baruah/bazel,rhuss/bazel,rohitsaboo/bazel,safarmer/bazel,whuwxl/bazel,variac/bazel,JackSullivan/bazel,Ansahmadiba/bazel,damienmg/bazel,spxtr/bazel,bazelbuild/bazel,rohitsaboo/bazel,UrbanCompass/bazel,joshua0pang/bazel,anupcshan/bazel,vt09/bazel,nkhuyu/bazel,UrbanCompass/bazel,aehlig/bazel,Asana/bazel,mbrukman/bazel,dslomov/bazel,nkhuyu/bazel,joshua0pang/bazel,mbrukman/bazel,JackSullivan/bazel,nkhuyu/bazel,mrdomino/bazel,iamthearm/bazel,davidzchen/bazel,aehlig/bazel,zhexuany/bazel,rohitsaboo/bazel,damienmg/bazel,rohitsaboo/bazel,hhclam/bazel,dinowernli/bazel,LuminateWireless/bazel,ulfjack/bazel,aehlig/bazel,kchodorow/bazel,juhalindfors/bazel-patches,dinowernli/bazel,kchodorow/bazel-1,twitter-forks/bazel,werkt/bazel,dropbox/bazel,LuminateWireless/bazel,whuwxl/bazel,ButterflyNetwork/bazel,cushon/bazel,vt09/bazel,xindaya/bazel,asarazan/bazel,davidzchen/bazel,LuminateWireless/bazel,mbrukman/bazel,dropbox/bazel,Digas29/bazel,LuminateWireless/bazel,ruo91/bazel,kchodorow/bazel-1,mrdomino/bazel,nkhuyu/bazel,spxtr/bazel,wakashige/bazel,perezd/bazel,snnn/bazel,ruo91/bazel,kchodorow/bazel-1,juhalindfors/bazel-patches,mikelalcon/bazel,JackSullivan/bazel,variac/bazel,manashmndl/bazel,twitter-forks/bazel,dinowernli/bazel,mbrukman/bazel,rohitsaboo/bazel,mrdomino/bazel,twitter-forks/bazel,safarmer/bazel,rhuss/bazel,hhclam/bazel,ButterflyNetwork/bazel,abergmeier-dsfishlabs/bazel,dinowernli/bazel,hhclam/bazel,abergmeier-dsfishlabs/bazel,kamalmarhubi/bazel,Ansahmadiba/bazel,d/bazel,kchodorow/bazel,dslomov/bazel-windows,meteorcloudy/bazel,murugamsm/bazel,wakashige/bazel,juhalindfors/bazel-patches,meteorcloudy/bazel,bazelbuild/bazel,Asana/bazel,murugamsm/bazel,dslomov/bazel,UrbanCompass/bazel,Ansahmadiba/bazel,Digas29/bazel,meteorcloudy/bazel,wakashige/bazel,damienmg/bazel,werkt/bazel,hermione521/bazel,abergmeier-dsfishlabs/bazel,Digas29/bazel,damienmg/bazel,snnn/bazel,zhexuany/bazel,kchodorow/bazel-1,variac/bazel,snnn/bazel,hermione521/bazel,werkt/bazel,dslomov/bazel-windows,hermione521/bazel,ulfjack/bazel,juhalindfors/bazel-patches,katre/bazel,d/bazel,mikelikespie/bazel,damienmg/bazel,davidzchen/bazel,werkt/bazel,murugamsm/bazel,kamalmarhubi/bazel,davidzchen/bazel,manashmndl/bazel,vt09/bazel,JackSullivan/bazel,dinowernli/bazel,juhalindfors/bazel-patches,JackSullivan/bazel,xindaya/bazel,kamalmarhubi/bazel,dslomov/bazel-windows,whuwxl/bazel,rhuss/bazel,hhclam/bazel,rhuss/bazel,cushon/bazel,dslomov/bazel-windows,snnn/bazel,mikelikespie/bazel,spxtr/bazel,davidzchen/bazel,zhexuany/bazel,werkt/bazel,UrbanCompass/bazel,whuwxl/bazel,ButterflyNetwork/bazel,spxtr/bazel,murugamsm/bazel,dslomov/bazel-windows,kchodorow/bazel,hhclam/bazel,safarmer/bazel,juhalindfors/bazel-patches,sicipio/bazel,asarazan/bazel,iamthearm/bazel,aehlig/bazel,dropbox/bazel,xindaya/bazel,murugamsm/bazel,dslomov/bazel-windows,meteorcloudy/bazel,nkhuyu/bazel,iamthearm/bazel,perezd/bazel,mikelikespie/bazel,twitter-forks/bazel,manashmndl/bazel,akira-baruah/bazel,ulfjack/bazel,ulfjack/bazel,aehlig/bazel,vt09/bazel,rohitsaboo/bazel,joshua0pang/bazel,asarazan/bazel,kchodorow/bazel-1,joshua0pang/bazel,vt09/bazel,abergmeier-dsfishlabs/bazel,kchodorow/bazel,asarazan/bazel,dinowernli/bazel,kamalmarhubi/bazel,d/bazel,akira-baruah/bazel,mbrukman/bazel,zhexuany/bazel,d/bazel,Digas29/bazel,ruo91/bazel,kchodorow/bazel-1,rhuss/bazel,spxtr/bazel,dhootha/bazel,katre/bazel,safarmer/bazel,kchodorow/bazel,dropbox/bazel,mbrukman/bazel,safarmer/bazel,sicipio/bazel,akira-baruah/bazel,mrdomino/bazel,joshua0pang/bazel,asarazan/bazel,d/bazel,dropbox/bazel,damienmg/bazel,wakashige/bazel,zhexuany/bazel,JackSullivan/bazel,perezd/bazel,ruo91/bazel,Digas29/bazel,cushon/bazel,manashmndl/bazel,bazelbuild/bazel,xindaya/bazel,whuwxl/bazel,mikelikespie/bazel,whuwxl/bazel,snnn/bazel,bazelbuild/bazel,werkt/bazel,perezd/bazel,davidzchen/bazel,dhootha/bazel,vt09/bazel,spxtr/bazel,hermione521/bazel,spxtr/bazel,kamalmarhubi/bazel,hermione521/bazel,Asana/bazel,cushon/bazel,katre/bazel,murugamsm/bazel,ruo91/bazel,asarazan/bazel,anupcshan/bazel,cushon/bazel,perezd/bazel,LuminateWireless/bazel,d/bazel,mikelikespie/bazel,safarmer/bazel,mikelalcon/bazel,meteorcloudy/bazel,juhalindfors/bazel-patches,snnn/bazel,Asana/bazel,rhuss/bazel,vt09/bazel,zhexuany/bazel,manashmndl/bazel,abergmeier-dsfishlabs/bazel,sicipio/bazel,Ansahmadiba/bazel,ulfjack/bazel,sicipio/bazel,meteorcloudy/bazel,meteorcloudy/bazel,nkhuyu/bazel,mikelalcon/bazel,mikelalcon/bazel,variac/bazel,ButterflyNetwork/bazel,abergmeier-dsfishlabs/bazel,wakashige/bazel,manashmndl/bazel,akira-baruah/bazel,anupcshan/bazel,variac/bazel,rhuss/bazel,ulfjack/bazel,snnn/bazel,ruo91/bazel | // Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.nativedeps;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.Constants;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Root;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.actions.SymlinkAction;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.rules.cpp.CcLinkParams;
import com.google.devtools.build.lib.rules.cpp.CcToolchainProvider;
import com.google.devtools.build.lib.rules.cpp.CppBuildInfo;
import com.google.devtools.build.lib.rules.cpp.CppConfiguration;
import com.google.devtools.build.lib.rules.cpp.CppHelper;
import com.google.devtools.build.lib.rules.cpp.CppLinkAction;
import com.google.devtools.build.lib.rules.cpp.Link.LinkStaticness;
import com.google.devtools.build.lib.rules.cpp.Link.LinkTargetType;
import com.google.devtools.build.lib.rules.cpp.LinkerInputs;
import com.google.devtools.build.lib.rules.cpp.LinkerInputs.LibraryToLink;
import com.google.devtools.build.lib.util.Fingerprint;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Helper class to create a dynamic library for rules which support integration with native code.
*
* <p>This library gets created by the build system by linking all C++ libraries in the transitive
* closure of the dependencies into a standalone dynamic library, with some exceptions. It usually
* does not include neverlink libraries or C++ binaries (or their transitive dependencies). Note
* that some rules are implicitly neverlink.
*/
public abstract class NativeDepsHelper {
/**
* An implementation of {@link
* com.google.devtools.build.lib.rules.cpp.CppLinkAction.LinkArtifactFactory} that can create
* artifacts anywhere.
*
* <p>Necessary because the actions of nativedeps libraries should be shareable, and thus cannot
* be under the package directory.
*/
private static final CppLinkAction.LinkArtifactFactory SHAREABLE_LINK_ARTIFACT_FACTORY =
new CppLinkAction.LinkArtifactFactory() {
@Override
public Artifact create(RuleContext ruleContext, PathFragment rootRelativePath) {
return ruleContext.getShareableArtifact(rootRelativePath,
ruleContext.getConfiguration().getBinDirectory());
}
};
private NativeDepsHelper() {}
/**
* Creates an Action to create a dynamic library by linking all native code
* (C/C++) libraries in the transitive dependency closure of a rule.
*
* <p>This is used for all native code in a rule's dependencies, regardless of type.
*
* <p>We link the native deps in the equivalent of linkstatic=1, linkshared=1
* mode.
*
* <p>linkstatic=1 means mostly-static mode, i.e. we select the ".a" (or
* ".pic.a") files, but we don't include "-static" in linkopts.
*
* <p>linkshared=1 means we prefer the ".pic.a" files to the ".a" files, and
* the LinkTargetType is set to DYNAMIC_LIBRARY which causes Link.java to
* include "-shared" in the linker options.
*
* @param ruleContext the rule context to determine the native library
* @param linkParams the {@link CcLinkParams} for the rule, collected with
* linkstatic = 1 and linkshared = 1
* @param extraLinkOpts additional parameters to the linker
* @param includeMalloc whether or not to link in the rule's malloc dependency
* @param configuration the {@link BuildConfiguration} to run the link action under
* @return the native library runfiles. If the transitive deps closure of
* the rule contains no native code libraries, its fields are null.
*/
public static NativeDepsRunfiles maybeCreateNativeDepsAction(final RuleContext ruleContext,
CcLinkParams linkParams, Collection<String> extraLinkOpts, boolean includeMalloc,
final BuildConfiguration configuration) {
if (includeMalloc) {
// Add in the custom malloc dependency if it was requested.
CcLinkParams.Builder linkParamsBuilder = CcLinkParams.builder(true, true);
linkParamsBuilder.addTransitiveArgs(linkParams);
linkParamsBuilder.addTransitiveTarget(CppHelper.mallocForTarget(ruleContext));
linkParams = linkParamsBuilder.build();
}
if (linkParams.getLibraries().isEmpty()) {
return NativeDepsRunfiles.EMPTY;
}
PathFragment relativePath = new PathFragment(ruleContext.getLabel().getName());
PathFragment nativeDepsPath = relativePath.replaceName(
relativePath.getBaseName() + Constants.NATIVE_DEPS_LIB_SUFFIX + ".so");
Artifact nativeDeps = ruleContext.getPackageRelativeArtifact(nativeDepsPath,
configuration.getBinDirectory());
return createNativeDepsAction(
ruleContext,
linkParams,
extraLinkOpts,
configuration,
CppHelper.getToolchain(ruleContext),
nativeDeps,
ruleContext.getConfiguration().getBinDirectory(), /*useDynamicRuntime*/
true);
}
private static final String ANDROID_UNIQUE_DIR = "nativedeps";
/**
* Creates an Action to create a dynamic library for Android by linking all native code (C/C++)
* libraries in the transitive dependency closure of a rule.
*
* <p>We link the native deps in the equivalent of linkstatic=1, linkshared=1 mode.
*
* <p>linkstatic=1 means mostly-static mode, i.e. we select the ".a" (or ".pic.a") files, but we
* don't include "-static" in linkopts.
*
* <p>linkshared=1 means we prefer the ".pic.a" files to the ".a" files, and the LinkTargetType is
* set to DYNAMIC_LIBRARY which causes Link.java to include "-shared" in the linker options.
*
* @param ruleContext the rule context to determine the native deps library
* @param linkParams the {@link CcLinkParams} for the rule, collected with linkstatic = 1 and
* linkshared = 1
* @return the native deps library runfiles. If the transitive deps closure of the rule contains
* no native code libraries, its fields are null.
*/
public static Artifact maybeCreateAndroidNativeDepsAction(final RuleContext ruleContext,
CcLinkParams linkParams, final BuildConfiguration configuration,
CcToolchainProvider toolchain) {
if (linkParams.getLibraries().isEmpty()) {
return null;
}
PathFragment labelName = new PathFragment(ruleContext.getLabel().getName());
Artifact nativeDeps = ruleContext.getUniqueDirectoryArtifact(ANDROID_UNIQUE_DIR,
labelName.replaceName("lib" + labelName.getBaseName() + ".so"),
configuration.getBinDirectory());
return createNativeDepsAction(
ruleContext,
linkParams, /** extraLinkOpts */
ImmutableList.<String>of(),
configuration,
toolchain,
nativeDeps,
configuration.getBinDirectory(),
/*useDynamicRuntime*/ false)
.getLibrary();
}
private static NativeDepsRunfiles createNativeDepsAction(
final RuleContext ruleContext,
CcLinkParams linkParams,
Collection<String> extraLinkOpts,
BuildConfiguration configuration,
CcToolchainProvider toolchain,
Artifact nativeDeps,
Root bindirIfShared,
boolean useDynamicRuntime) {
Preconditions.checkState(
ruleContext.isLegalFragment(CppConfiguration.class),
"%s does not have access to CppConfiguration",
ruleContext.getRule().getRuleClass());
List<String> linkopts = new ArrayList<>(extraLinkOpts);
linkopts.addAll(linkParams.flattenedLinkopts());
Map<Artifact, ImmutableList<Artifact>> linkstamps =
CppHelper.resolveLinkstamps(ruleContext, linkParams);
List<Artifact> buildInfoArtifacts = linkstamps.isEmpty()
? ImmutableList.<Artifact>of()
: ruleContext.getBuildInfo(CppBuildInfo.KEY);
boolean shareNativeDeps = configuration.getFragment(CppConfiguration.class).shareNativeDeps();
NestedSet<LibraryToLink> linkerInputs = linkParams.getLibraries();
Artifact sharedLibrary = shareNativeDeps
? ruleContext.getShareableArtifact(getSharedNativeDepsPath(
LinkerInputs.toLibraryArtifacts(linkerInputs),
linkopts, linkstamps.keySet(), buildInfoArtifacts,
ruleContext.getFeatures()),
ruleContext.getConfiguration().getBinDirectory())
: nativeDeps;
CppLinkAction.Builder builder = new CppLinkAction.Builder(
ruleContext, sharedLibrary, configuration, toolchain);
if (useDynamicRuntime) {
builder.setRuntimeInputs(
toolchain.getDynamicRuntimeLinkMiddleman(), toolchain.getDynamicRuntimeLinkInputs());
} else {
builder.setRuntimeInputs(
toolchain.getStaticRuntimeLinkMiddleman(), toolchain.getStaticRuntimeLinkInputs());
}
CppLinkAction linkAction =
builder
.setLinkArtifactFactory(SHAREABLE_LINK_ARTIFACT_FACTORY)
.setCrosstoolInputs(toolchain.getLink())
.addLibraries(linkerInputs)
.setLinkType(LinkTargetType.DYNAMIC_LIBRARY)
.setLinkStaticness(LinkStaticness.MOSTLY_STATIC)
.addLinkopts(linkopts)
.setNativeDeps(true)
.addLinkstamps(linkstamps)
.build();
ruleContext.registerAction(linkAction);
Artifact linkerOutput = linkAction.getPrimaryOutput();
if (shareNativeDeps) {
// Collect dynamic-linker-resolvable symlinks for C++ runtime library dependencies.
// Note we only need these symlinks when --share_native_deps is on, as shared native deps
// mangle path names such that the library's conventional _solib RPATH entry
// no longer resolves (because the target directory's relative depth gets lost).
List<Artifact> runtimeSymlinks;
if (useDynamicRuntime) {
runtimeSymlinks = new LinkedList<>();
for (final Artifact runtimeInput : toolchain.getDynamicRuntimeLinkInputs()) {
final Artifact runtimeSymlink =
ruleContext.getPackageRelativeArtifact(
getRuntimeLibraryPath(ruleContext, runtimeInput), bindirIfShared);
// Since runtime library symlinks are underneath the target's output directory and
// multiple targets may share the same output directory, we need to make sure this
// symlink's generating action is only set once.
ruleContext.registerAction(
new SymlinkAction(ruleContext.getActionOwner(), runtimeInput, runtimeSymlink, null));
runtimeSymlinks.add(runtimeSymlink);
}
} else {
runtimeSymlinks = ImmutableList.of();
}
ruleContext.registerAction(
new SymlinkAction(ruleContext.getActionOwner(), linkerOutput, nativeDeps, null));
return new NativeDepsRunfiles(nativeDeps, runtimeSymlinks);
}
return new NativeDepsRunfiles(linkerOutput, ImmutableList.<Artifact>of());
}
/**
* Returns the path, relative to the runfiles prefix, of a runtime library
* symlink for the native library for the specified rule.
*/
private static PathFragment getRuntimeLibraryPath(RuleContext ruleContext, Artifact lib) {
PathFragment relativePath = new PathFragment(ruleContext.getLabel().getName());
PathFragment libParentDir =
relativePath.replaceName(lib.getExecPath().getParentDirectory().getBaseName());
String libName = lib.getExecPath().getBaseName();
return new PathFragment(libParentDir, new PathFragment(libName));
}
/**
* Returns the path of the shared native library. The name must be
* generated based on the rule-specific inputs to the link actions. At this
* point this includes order-sensitive list of linker inputs and options
* collected from the transitive closure and linkstamp-related artifacts that
* are compiled during linking. All those inputs can be affected by modifying
* target attributes (srcs/deps/stamp/etc). However, target build
* configuration can be ignored since it will either change output directory
* (in case of different configuration instances) or will not affect anything
* (if two targets use same configuration). Final goal is for all native
* libraries that use identical linker command to use same output name.
*
* <p>TODO(bazel-team): (2010) Currently process of identifying parameters that can
* affect native library name is manual and should be kept in sync with the
* code in the CppLinkAction.Builder/CppLinkAction/Link classes which are
* responsible for generating linker command line. Ideally we should reuse
* generated command line for both purposes - selecting a name of the
* native library and using it as link action payload. For now, correctness
* of the method below is only ensured by validations in the
* CppLinkAction.Builder.build() method.
*/
private static PathFragment getSharedNativeDepsPath(Iterable<Artifact> linkerInputs,
Collection<String> linkopts, Iterable<Artifact> linkstamps,
Iterable<Artifact> buildInfoArtifacts, Collection<String> features) {
Fingerprint fp = new Fingerprint();
for (Artifact input : linkerInputs) {
fp.addString(input.getExecPathString());
}
fp.addStrings(linkopts);
for (Artifact input : linkstamps) {
fp.addString(input.getExecPathString());
}
for (Artifact input : buildInfoArtifacts) {
fp.addString(input.getExecPathString());
}
for (String feature : features) {
fp.addStrings(feature);
}
return new PathFragment(
"_nativedeps/" + fp.hexDigestAndReset() + ".so");
}
}
| src/main/java/com/google/devtools/build/lib/rules/nativedeps/NativeDepsHelper.java | // Copyright 2015 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.rules.nativedeps;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.devtools.build.lib.Constants;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.actions.Root;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.actions.SymlinkAction;
import com.google.devtools.build.lib.analysis.config.BuildConfiguration;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.rules.cpp.CcLinkParams;
import com.google.devtools.build.lib.rules.cpp.CcToolchainProvider;
import com.google.devtools.build.lib.rules.cpp.CppBuildInfo;
import com.google.devtools.build.lib.rules.cpp.CppConfiguration;
import com.google.devtools.build.lib.rules.cpp.CppHelper;
import com.google.devtools.build.lib.rules.cpp.CppLinkAction;
import com.google.devtools.build.lib.rules.cpp.Link.LinkStaticness;
import com.google.devtools.build.lib.rules.cpp.Link.LinkTargetType;
import com.google.devtools.build.lib.rules.cpp.LinkerInputs;
import com.google.devtools.build.lib.rules.cpp.LinkerInputs.LibraryToLink;
import com.google.devtools.build.lib.util.Fingerprint;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Helper class to create a dynamic library for rules which support integration with native code.
*
* <p>This library gets created by the build system by linking all C++ libraries in the transitive
* closure of the dependencies into a standalone dynamic library, with some exceptions. It usually
* does not include neverlink libraries or C++ binaries (or their transitive dependencies). Note
* that some rules are implicitly neverlink.
*/
public abstract class NativeDepsHelper {
/**
* An implementation of {@link
* com.google.devtools.build.lib.rules.cpp.CppLinkAction.LinkArtifactFactory} that can create
* artifacts anywhere.
*
* <p>Necessary because the actions of nativedeps libraries should be shareable, and thus cannot
* be under the package directory.
*/
private static final CppLinkAction.LinkArtifactFactory SHAREABLE_LINK_ARTIFACT_FACTORY =
new CppLinkAction.LinkArtifactFactory() {
@Override
public Artifact create(RuleContext ruleContext, PathFragment rootRelativePath) {
return ruleContext.getShareableArtifact(rootRelativePath,
ruleContext.getConfiguration().getBinDirectory());
}
};
private NativeDepsHelper() {}
/**
* Creates an Action to create a dynamic library by linking all native code
* (C/C++) libraries in the transitive dependency closure of a rule.
*
* <p>This is used for all native code in a rule's dependencies, regardless of type.
*
* <p>We link the native deps in the equivalent of linkstatic=1, linkshared=1
* mode.
*
* <p>linkstatic=1 means mostly-static mode, i.e. we select the ".a" (or
* ".pic.a") files, but we don't include "-static" in linkopts.
*
* <p>linkshared=1 means we prefer the ".pic.a" files to the ".a" files, and
* the LinkTargetType is set to DYNAMIC_LIBRARY which causes Link.java to
* include "-shared" in the linker options.
*
* @param ruleContext the rule context to determine the native library
* @param linkParams the {@link CcLinkParams} for the rule, collected with
* linkstatic = 1 and linkshared = 1
* @param extraLinkOpts additional parameters to the linker
* @param includeMalloc whether or not to link in the rule's malloc dependency
* @param configuration the {@link BuildConfiguration} to run the link action under
* @return the native library runfiles. If the transitive deps closure of
* the rule contains no native code libraries, its fields are null.
*/
public static NativeDepsRunfiles maybeCreateNativeDepsAction(final RuleContext ruleContext,
CcLinkParams linkParams, Collection<String> extraLinkOpts, boolean includeMalloc,
final BuildConfiguration configuration) {
if (includeMalloc) {
// Add in the custom malloc dependency if it was requested.
CcLinkParams.Builder linkParamsBuilder = CcLinkParams.builder(true, true);
linkParamsBuilder.addTransitiveArgs(linkParams);
linkParamsBuilder.addTransitiveTarget(CppHelper.mallocForTarget(ruleContext));
linkParams = linkParamsBuilder.build();
}
if (linkParams.getLibraries().isEmpty()) {
return NativeDepsRunfiles.EMPTY;
}
PathFragment relativePath = new PathFragment(ruleContext.getLabel().getName());
PathFragment nativeDepsPath = relativePath.replaceName(
relativePath.getBaseName() + Constants.NATIVE_DEPS_LIB_SUFFIX + ".so");
Artifact nativeDeps = ruleContext.getPackageRelativeArtifact(nativeDepsPath,
configuration.getBinDirectory());
return createNativeDepsAction(
ruleContext,
linkParams,
extraLinkOpts,
configuration,
CppHelper.getToolchain(ruleContext),
nativeDeps,
ruleContext.getConfiguration().getBinDirectory(), /*useDynamicRuntime*/
true);
}
private static final String ANDROID_UNIQUE_DIR = "nativedeps";
/**
* Creates an Action to create a dynamic library for Android by linking all native code (C/C++)
* libraries in the transitive dependency closure of a rule.
*
* <p>We link the native deps in the equivalent of linkstatic=1, linkshared=1 mode.
*
* <p>linkstatic=1 means mostly-static mode, i.e. we select the ".a" (or ".pic.a") files, but we
* don't include "-static" in linkopts.
*
* <p>linkshared=1 means we prefer the ".pic.a" files to the ".a" files, and the LinkTargetType is
* set to DYNAMIC_LIBRARY which causes Link.java to include "-shared" in the linker options.
*
* @param ruleContext the rule context to determine the native deps library
* @param linkParams the {@link CcLinkParams} for the rule, collected with linkstatic = 1 and
* linkshared = 1
* @return the native deps library runfiles. If the transitive deps closure of the rule contains
* no native code libraries, its fields are null.
*/
public static Artifact maybeCreateAndroidNativeDepsAction(final RuleContext ruleContext,
CcLinkParams linkParams, final BuildConfiguration configuration,
CcToolchainProvider toolchain) {
if (linkParams.getLibraries().isEmpty()) {
return null;
}
PathFragment labelName = new PathFragment(ruleContext.getLabel().getName());
Artifact nativeDeps = ruleContext.getUniqueDirectoryArtifact(ANDROID_UNIQUE_DIR,
labelName.replaceName("lib" + labelName.getBaseName() + ".so"),
configuration.getBinDirectory());
return createNativeDepsAction(
ruleContext,
linkParams, /** extraLinkOpts */
ImmutableList.<String>of(),
configuration,
toolchain,
nativeDeps,
configuration.getBinDirectory(),
/*useDynamicRuntime*/ false)
.getLibrary();
}
private static NativeDepsRunfiles createNativeDepsAction(
final RuleContext ruleContext,
CcLinkParams linkParams,
Collection<String> extraLinkOpts,
BuildConfiguration configuration,
CcToolchainProvider toolchain,
Artifact nativeDeps,
Root bindirIfShared,
boolean useDynamicRuntime) {
Preconditions.checkState(
ruleContext.isLegalFragment(CppConfiguration.class),
"%s does not have access to CppConfiguration",
ruleContext.getRule().getRuleClass());
List<String> linkopts = new ArrayList<>(extraLinkOpts);
linkopts.addAll(linkParams.flattenedLinkopts());
Map<Artifact, ImmutableList<Artifact>> linkstamps =
CppHelper.resolveLinkstamps(ruleContext, linkParams);
List<Artifact> buildInfoArtifacts = linkstamps.isEmpty()
? ImmutableList.<Artifact>of()
: ruleContext.getBuildInfo(CppBuildInfo.KEY);
boolean shareNativeDeps = configuration.getFragment(CppConfiguration.class).shareNativeDeps();
NestedSet<LibraryToLink> linkerInputs = linkParams.getLibraries();
Artifact sharedLibrary = shareNativeDeps
? ruleContext.getShareableArtifact(getSharedNativeDepsPath(
LinkerInputs.toLibraryArtifacts(linkerInputs),
linkopts, linkstamps.keySet(), buildInfoArtifacts,
ruleContext.getFeatures()),
ruleContext.getConfiguration().getBinDirectory())
: nativeDeps;
CppLinkAction.Builder builder = new CppLinkAction.Builder(
ruleContext, sharedLibrary, configuration, toolchain);
if (useDynamicRuntime) {
builder.setRuntimeInputs(
toolchain.getDynamicRuntimeLinkMiddleman(), toolchain.getDynamicRuntimeLinkInputs());
} else {
builder.setRuntimeInputs(
toolchain.getStaticRuntimeLinkMiddleman(), toolchain.getStaticRuntimeLinkInputs());
}
CppLinkAction linkAction =
builder
.setLinkArtifactFactory(SHAREABLE_LINK_ARTIFACT_FACTORY)
.setCrosstoolInputs(toolchain.getLink())
.addLibraries(linkerInputs)
.setLinkType(LinkTargetType.DYNAMIC_LIBRARY)
.setLinkStaticness(LinkStaticness.MOSTLY_STATIC)
.addLinkopts(linkopts)
.setNativeDeps(true)
.addLinkstamps(linkstamps)
.build();
ruleContext.registerAction(linkAction);
Artifact linkerOutput = linkAction.getPrimaryOutput();
if (shareNativeDeps) {
// Collect dynamic-linker-resolvable symlinks for C++ runtime library dependencies.
// Note we only need these symlinks when --share_native_deps is on, as shared native deps
// mangle path names such that the library's conventional _solib RPATH entry
// no longer resolves (because the target directory's relative depth gets lost).
List<Artifact> runtimeSymlinks;
if (useDynamicRuntime) {
runtimeSymlinks = new LinkedList<>();
for (final Artifact runtimeInput : toolchain.getDynamicRuntimeLinkInputs()) {
final Artifact runtimeSymlink =
ruleContext.getPackageRelativeArtifact(
getRuntimeLibraryPath(ruleContext, runtimeInput), bindirIfShared);
// Since runtime library symlinks are underneath the target's output directory and
// multiple targets may share the same output directory, we need to make sure this
// symlink's generating action is only set once.
ruleContext.registerAction(
new SymlinkAction(ruleContext.getActionOwner(), runtimeInput, runtimeSymlink, null));
runtimeSymlinks.add(runtimeSymlink);
}
} else {
runtimeSymlinks = ImmutableList.of();
}
ruleContext.registerAction(
new SymlinkAction(ruleContext.getActionOwner(), linkerOutput, nativeDeps, null));
return new NativeDepsRunfiles(nativeDeps, runtimeSymlinks);
}
return new NativeDepsRunfiles(linkerOutput, ImmutableList.<Artifact>of());
}
/**
* Returns the path, relative to the runfiles prefix, of a runtime library
* symlink for the native library for the specified rule.
*/
private static PathFragment getRuntimeLibraryPath(RuleContext ruleContext, Artifact lib) {
PathFragment relativePath = new PathFragment(ruleContext.getLabel().getName());
PathFragment libParentDir =
relativePath.replaceName(lib.getExecPath().getParentDirectory().getBaseName());
String libName = lib.getExecPath().getBaseName();
return new PathFragment(libParentDir, new PathFragment(libName));
}
/**
* Returns the path of the shared native library. The name must be
* generated based on the rule-specific inputs to the link actions. At this
* point this includes order-sensitive list of linker inputs and options
* collected from the transitive closure and linkstamp-related artifacts that
* are compiled during linking. All those inputs can be affected by modifying
* target attributes (srcs/deps/stamp/etc). However, target build
* configuration can be ignored since it will either change output directory
* (in case of different configuration instances) or will not affect anything
* (if two targets use same configuration). Final goal is for all native
* libraries that use identical linker command to use same output name.
*
* <p>TODO(bazel-team): (2010) Currently process of identifying parameters that can
* affect native library name is manual and should be kept in sync with the
* code in the CppLinkAction.Builder/CppLinkAction/Link classes which are
* responsible for generating linker command line. Ideally we should reuse
* generated command line for both purposes - selecting a name of the
* native library and using it as link action payload. For now, correctness
* of the method below is only ensured by validations in the
* CppLinkAction.Builder.build() method.
*/
private static PathFragment getSharedNativeDepsPath(Iterable<Artifact> linkerInputs,
Collection<String> linkopts, Iterable<Artifact> linkstamps,
Iterable<Artifact> buildInfoArtifacts, Collection<String> features) {
Fingerprint fp = new Fingerprint();
for (Artifact input : linkerInputs) {
fp.addString(input.getExecPathString());
}
fp.addStrings(linkopts);
for (Artifact input : linkstamps) {
fp.addString(input.getExecPathString());
}
for (Artifact input : buildInfoArtifacts) {
fp.addString(input.getExecPathString());
}
for (String feature : features) {
fp.addStrings(feature);
}
return new PathFragment(
Constants.NATIVE_DEPS_LIB_SUFFIX + "/" + fp.hexDigestAndReset() + ".so");
}
}
| Inline the native deps suffix constant in one location.
Only one for now, as we need to migrate internally.
--
MOS_MIGRATED_REVID=102477370
| src/main/java/com/google/devtools/build/lib/rules/nativedeps/NativeDepsHelper.java | Inline the native deps suffix constant in one location. |
|
Java | apache-2.0 | 26237771f44acef87ca72869d0278c504c0ef997 | 0 | coupang/pinpoint,denzelsN/pinpoint,denzelsN/pinpoint,dawidmalina/pinpoint,Xylus/pinpoint,KimTaehee/pinpoint,lioolli/pinpoint,lioolli/pinpoint,carpedm20/pinpoint,andyspan/pinpoint,barneykim/pinpoint,masonmei/pinpoint,cit-lab/pinpoint,philipz/pinpoint,sjmittal/pinpoint,minwoo-jung/pinpoint,masonmei/pinpoint,InfomediaLtd/pinpoint,cit-lab/pinpoint,wziyong/pinpoint,jaehong-kim/pinpoint,majinkai/pinpoint,barneykim/pinpoint,suraj-raturi/pinpoint,PerfGeeks/pinpoint,cijung/pinpoint,carpedm20/pinpoint,chenguoxi1985/pinpoint,carpedm20/pinpoint,KRDeNaT/pinpoint,cit-lab/pinpoint,Xylus/pinpoint,emeroad/pinpoint,sjmittal/pinpoint,nstopkimsk/pinpoint,87439247/pinpoint,krishnakanthpps/pinpoint,hcapitaine/pinpoint,PerfGeeks/pinpoint,Allive1/pinpoint,jaehong-kim/pinpoint,wziyong/pinpoint,87439247/pinpoint,sjmittal/pinpoint,emeroad/pinpoint,breadval/pinpoint,krishnakanthpps/pinpoint,andyspan/pinpoint,koo-taejin/pinpoint,krishnakanthpps/pinpoint,InfomediaLtd/pinpoint,jaehong-kim/pinpoint,naver/pinpoint,breadval/pinpoint,Allive1/pinpoint,majinkai/pinpoint,nstopkimsk/pinpoint,breadval/pinpoint,denzelsN/pinpoint,masonmei/pinpoint,Skkeem/pinpoint,InfomediaLtd/pinpoint,chenguoxi1985/pinpoint,Allive1/pinpoint,lioolli/pinpoint,Skkeem/pinpoint,cijung/pinpoint,jaehong-kim/pinpoint,cijung/pinpoint,citywander/pinpoint,tsyma/pinpoint,minwoo-jung/pinpoint,eBaoTech/pinpoint,coupang/pinpoint,cijung/pinpoint,coupang/pinpoint,krishnakanthpps/pinpoint,philipz/pinpoint,chenguoxi1985/pinpoint,denzelsN/pinpoint,87439247/pinpoint,majinkai/pinpoint,breadval/pinpoint,nstopkimsk/pinpoint,InfomediaLtd/pinpoint,eBaoTech/pinpoint,gspandy/pinpoint,eBaoTech/pinpoint,masonmei/pinpoint,wziyong/pinpoint,emeroad/pinpoint,masonmei/pinpoint,citywander/pinpoint,andyspan/pinpoint,hcapitaine/pinpoint,shuvigoss/pinpoint,Allive1/pinpoint,sbcoba/pinpoint,emeroad/pinpoint,philipz/pinpoint,coupang/pinpoint,eBaoTech/pinpoint,barneykim/pinpoint,citywander/pinpoint,andyspan/pinpoint,philipz/pinpoint,eBaoTech/pinpoint,coupang/pinpoint,barneykim/pinpoint,denzelsN/pinpoint,Xylus/pinpoint,jiaqifeng/pinpoint,suraj-raturi/pinpoint,andyspan/pinpoint,sbcoba/pinpoint,shuvigoss/pinpoint,lioolli/pinpoint,tsyma/pinpoint,naver/pinpoint,barneykim/pinpoint,jiaqifeng/pinpoint,KimTaehee/pinpoint,carpedm20/pinpoint,nstopkimsk/pinpoint,denzelsN/pinpoint,jiaqifeng/pinpoint,dawidmalina/pinpoint,sjmittal/pinpoint,dawidmalina/pinpoint,naver/pinpoint,hcapitaine/pinpoint,Skkeem/pinpoint,barneykim/pinpoint,InfomediaLtd/pinpoint,nstopkimsk/pinpoint,denzelsN/pinpoint,sbcoba/pinpoint,majinkai/pinpoint,breadval/pinpoint,suraj-raturi/pinpoint,PerfGeeks/pinpoint,emeroad/pinpoint,coupang/pinpoint,sjmittal/pinpoint,andyspan/pinpoint,cit-lab/pinpoint,krishnakanthpps/pinpoint,suraj-raturi/pinpoint,minwoo-jung/pinpoint,cit-lab/pinpoint,KRDeNaT/pinpoint,minwoo-jung/pinpoint,sjmittal/pinpoint,shuvigoss/pinpoint,nstopkimsk/pinpoint,jiaqifeng/pinpoint,87439247/pinpoint,tsyma/pinpoint,breadval/pinpoint,koo-taejin/pinpoint,Skkeem/pinpoint,KimTaehee/pinpoint,tsyma/pinpoint,eBaoTech/pinpoint,hcapitaine/pinpoint,hcapitaine/pinpoint,KimTaehee/pinpoint,cit-lab/pinpoint,Skkeem/pinpoint,cijung/pinpoint,shuvigoss/pinpoint,suraj-raturi/pinpoint,Allive1/pinpoint,chenguoxi1985/pinpoint,Xylus/pinpoint,cijung/pinpoint,sbcoba/pinpoint,philipz/pinpoint,jaehong-kim/pinpoint,dawidmalina/pinpoint,citywander/pinpoint,KRDeNaT/pinpoint,chenguoxi1985/pinpoint,majinkai/pinpoint,Xylus/pinpoint,87439247/pinpoint,tsyma/pinpoint,koo-taejin/pinpoint,KimTaehee/pinpoint,suraj-raturi/pinpoint,sbcoba/pinpoint,koo-taejin/pinpoint,koo-taejin/pinpoint,KRDeNaT/pinpoint,minwoo-jung/pinpoint,wziyong/pinpoint,dawidmalina/pinpoint,Xylus/pinpoint,hcapitaine/pinpoint,jiaqifeng/pinpoint,dawidmalina/pinpoint,KRDeNaT/pinpoint,Skkeem/pinpoint,citywander/pinpoint,barneykim/pinpoint,lioolli/pinpoint,jaehong-kim/pinpoint,philipz/pinpoint,emeroad/pinpoint,wziyong/pinpoint,citywander/pinpoint,shuvigoss/pinpoint,KRDeNaT/pinpoint,wziyong/pinpoint,lioolli/pinpoint,krishnakanthpps/pinpoint,minwoo-jung/pinpoint,carpedm20/pinpoint,Allive1/pinpoint,KimTaehee/pinpoint,chenguoxi1985/pinpoint,naver/pinpoint,Xylus/pinpoint,jiaqifeng/pinpoint,masonmei/pinpoint,PerfGeeks/pinpoint,gspandy/pinpoint,gspandy/pinpoint,tsyma/pinpoint,87439247/pinpoint,PerfGeeks/pinpoint,naver/pinpoint,gspandy/pinpoint,PerfGeeks/pinpoint,InfomediaLtd/pinpoint,koo-taejin/pinpoint,shuvigoss/pinpoint,gspandy/pinpoint,sbcoba/pinpoint,majinkai/pinpoint,gspandy/pinpoint | package com.nhn.pinpoint.web.vo.linechart.agentstat;
import java.util.HashMap;
import java.util.Map;
import com.nhn.pinpoint.thrift.dto.TAgentStat;
import com.nhn.pinpoint.thrift.dto.TAgentStat._Fields;
import com.nhn.pinpoint.thrift.dto.TStatWithCmsCollector;
import com.nhn.pinpoint.thrift.dto.TStatWithG1Collector;
import com.nhn.pinpoint.thrift.dto.TStatWithParallelCollector;
import com.nhn.pinpoint.thrift.dto.TStatWithSerialCollector;
import com.nhn.pinpoint.web.vo.linechart.LineChart;
import com.nhn.pinpoint.web.vo.linechart.SampledLineChart;
/**
* @author harebox
*/
public class AgentStatChartGroup {
private String type;
private Map<String, LineChart> charts = new HashMap<String, LineChart>();
public void addData(TAgentStat data, int sampleRate) {
if (data == null) {
return;
}
// 먼저 메시지에 포함된 데이터 타입을 알아낸다.
_Fields type = data.getSetField();
Object typeObject = data.getFieldValue(type);
// TODO profiler에서 한 것 처럼 리팩토링 해야 한다.
switch (type) {
case CMS:
TStatWithCmsCollector cms = (TStatWithCmsCollector) typeObject;
for (TStatWithCmsCollector._Fields each : TStatWithCmsCollector.metaDataMap.keySet()) {
Object fieldValue = cms.getFieldValue(each);
if (! (fieldValue instanceof Long)) {
continue;
}
if (! charts.containsKey(each.getFieldName())) {
charts.put(each.getFieldName(), new SampledLineChart(sampleRate));
}
LineChart chart = charts.get(each.getFieldName());
chart.addPoint(new Long[]{ cms.getTimestamp(), (Long) fieldValue });
}
break;
case G1:
TStatWithG1Collector g1 = (TStatWithG1Collector) typeObject;
for (TStatWithG1Collector._Fields each : TStatWithG1Collector.metaDataMap.keySet()) {
Object fieldValue = g1.getFieldValue(each);
if (! (fieldValue instanceof Long)) {
continue;
}
if (! charts.containsKey(each.getFieldName())) {
charts.put(each.getFieldName(), new SampledLineChart(sampleRate));
}
LineChart chart = charts.get(each.getFieldName());
chart.addPoint(new Long[]{ g1.getTimestamp(), (Long) fieldValue });
}
break;
case PARALLEL:
TStatWithParallelCollector parallel = (TStatWithParallelCollector) typeObject;
for (TStatWithParallelCollector._Fields each : TStatWithParallelCollector.metaDataMap.keySet()) {
Object fieldValue = parallel.getFieldValue(each);
if (! (fieldValue instanceof Long)) {
continue;
}
if (! charts.containsKey(each.getFieldName())) {
charts.put(each.getFieldName(), new SampledLineChart(sampleRate));
}
LineChart chart = charts.get(each.getFieldName());
Long[] point = new Long[]{ parallel.getTimestamp(), (Long) fieldValue };
chart.addPoint(point);
}
break;
case SERIAL:
TStatWithSerialCollector serial = (TStatWithSerialCollector) typeObject;
for (TStatWithSerialCollector._Fields each : TStatWithSerialCollector.metaDataMap.keySet()) {
Object fieldValue = serial.getFieldValue(each);
if (! (fieldValue instanceof Long)) {
continue;
}
if (! charts.containsKey(each.getFieldName())) {
charts.put(each.getFieldName(), new SampledLineChart(sampleRate));
}
LineChart chart = charts.get(each.getFieldName());
chart.addPoint(new Long[]{ serial.getTimestamp(), (Long) fieldValue });
}
break;
}
this.type = type.getFieldName();
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Map<String, LineChart> getCharts() {
return charts;
}
public void setCharts(Map<String, LineChart> charts) {
this.charts = charts;
}
} | src/main/java/com/nhn/pinpoint/web/vo/linechart/agentstat/AgentStatChartGroup.java | package com.nhn.pinpoint.web.vo.linechart.agentstat;
import java.util.HashMap;
import java.util.Map;
import com.nhn.pinpoint.thrift.dto.TAgentStat;
import com.nhn.pinpoint.thrift.dto.TAgentStat._Fields;
import com.nhn.pinpoint.thrift.dto.TStatWithCmsCollector;
import com.nhn.pinpoint.thrift.dto.TStatWithG1Collector;
import com.nhn.pinpoint.thrift.dto.TStatWithParallelCollector;
import com.nhn.pinpoint.web.vo.linechart.LineChart;
import com.nhn.pinpoint.web.vo.linechart.SampledLineChart;
/**
* @author harebox
*/
public class AgentStatChartGroup {
private String type;
private Map<String, LineChart> charts = new HashMap<String, LineChart>();
public void addData(TAgentStat data, int sampleRate) {
if (data == null) {
return;
}
// 먼저 메시지에 포함된 데이터 타입을 알아낸다.
_Fields type = data.getSetField();
Object typeObject = data.getFieldValue(type);
// TODO profiler에서 한 것 처럼 리팩토링 해야 한다.
switch (type) {
case CMS:
TStatWithCmsCollector cms = (TStatWithCmsCollector) typeObject;
for (TStatWithCmsCollector._Fields each : TStatWithCmsCollector.metaDataMap.keySet()) {
Object fieldValue = cms.getFieldValue(each);
if (! (fieldValue instanceof Long)) {
continue;
}
if (! charts.containsKey(each.getFieldName())) {
charts.put(each.getFieldName(), new SampledLineChart(sampleRate));
}
LineChart chart = charts.get(each.getFieldName());
chart.addPoint(new Long[]{ cms.getTimestamp(), (Long) fieldValue });
}
break;
case G1:
TStatWithG1Collector g1 = (TStatWithG1Collector) typeObject;
for (TStatWithG1Collector._Fields each : TStatWithG1Collector.metaDataMap.keySet()) {
Object fieldValue = g1.getFieldValue(each);
if (! (fieldValue instanceof Long)) {
continue;
}
if (! charts.containsKey(each.getFieldName())) {
charts.put(each.getFieldName(), new SampledLineChart(sampleRate));
}
LineChart chart = charts.get(each.getFieldName());
chart.addPoint(new Long[]{ g1.getTimestamp(), (Long) fieldValue });
}
break;
case PARALLEL:
TStatWithParallelCollector parallel = (TStatWithParallelCollector) typeObject;
for (TStatWithParallelCollector._Fields each : TStatWithParallelCollector.metaDataMap.keySet()) {
Object fieldValue = parallel.getFieldValue(each);
if (! (fieldValue instanceof Long)) {
continue;
}
if (! charts.containsKey(each.getFieldName())) {
charts.put(each.getFieldName(), new SampledLineChart(sampleRate));
}
LineChart chart = charts.get(each.getFieldName());
Long[] point = new Long[]{ parallel.getTimestamp(), (Long) fieldValue };
chart.addPoint(point);
}
break;
case SERIAL:
TStatWithG1Collector serial = (TStatWithG1Collector) typeObject;
for (TStatWithG1Collector._Fields each : TStatWithG1Collector.metaDataMap.keySet()) {
Object fieldValue = serial.getFieldValue(each);
if (! (fieldValue instanceof Long)) {
continue;
}
if (! charts.containsKey(each.getFieldName())) {
charts.put(each.getFieldName(), new SampledLineChart(sampleRate));
}
LineChart chart = charts.get(each.getFieldName());
chart.addPoint(new Long[]{ serial.getTimestamp(), (Long) fieldValue });
}
break;
}
this.type = type.getFieldName();
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Map<String, LineChart> getCharts() {
return charts;
}
public void setCharts(Map<String, LineChart> charts) {
this.charts = charts;
}
} | [김훈민] [PINPOINT-213] PinPoint Spy
git-svn-id: 7358e302d50fd4045a689b8bedf0763179db032e@2661 84d0f5b1-2673-498c-a247-62c4ff18d310
| src/main/java/com/nhn/pinpoint/web/vo/linechart/agentstat/AgentStatChartGroup.java | [김훈민] [PINPOINT-213] PinPoint Spy |
|
Java | apache-2.0 | 8376eddf50f757ae1bc8e27d1457d60a4845a7a5 | 0 | apache/solr,apache/solr,apache/solr,apache/solr,apache/solr | package org.apache.lucene.analysis;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.util.CloseableThreadLocal;
import java.io.Closeable;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
/**
* An Analyzer builds TokenStreams, which analyze text. It thus represents a
* policy for extracting index terms from text.
* <p>
* In order to define what analysis is done, subclasses must define their
* {@link TokenStreamComponents TokenStreamComponents} in {@link #createComponents(String, Reader)}.
* The components are then reused in each call to {@link #tokenStream(String, Reader)}.
* <p>
* Simple example:
* <pre class="prettyprint">
* Analyzer analyzer = new Analyzer() {
* {@literal @Override}
* protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
* Tokenizer source = new FooTokenizer(reader);
* TokenStream filter = new FooFilter(source);
* filter = new BarFilter(filter);
* return new TokenStreamComponents(source, filter);
* }
* };
* </pre>
* For more examples, see the {@link org.apache.lucene.analysis Analysis package documentation}.
* <p>
* For some concrete implementations bundled with Lucene, look in the analysis modules:
* <ul>
* <li><a href="{@docRoot}/../analyzers-common/overview-summary.html">Common</a>:
* Analyzers for indexing content in different languages and domains.
* <li><a href="{@docRoot}/../analyzers-icu/overview-summary.html">ICU</a>:
* Exposes functionality from ICU to Apache Lucene.
* <li><a href="{@docRoot}/../analyzers-kuromoji/overview-summary.html">Kuromoji</a>:
* Morphological analyzer for Japanese text.
* <li><a href="{@docRoot}/../analyzers-morfologik/overview-summary.html">Morfologik</a>:
* Dictionary-driven lemmatization for the Polish language.
* <li><a href="{@docRoot}/../analyzers-phonetic/overview-summary.html">Phonetic</a>:
* Analysis for indexing phonetic signatures (for sounds-alike search).
* <li><a href="{@docRoot}/../analyzers-smartcn/overview-summary.html">Smart Chinese</a>:
* Analyzer for Simplified Chinese, which indexes words.
* <li><a href="{@docRoot}/../analyzers-stempel/overview-summary.html">Stempel</a>:
* Algorithmic Stemmer for the Polish Language.
* <li><a href="{@docRoot}/../analyzers-uima/overview-summary.html">UIMA</a>:
* Analysis integration with Apache UIMA.
* </ul>
*/
public abstract class Analyzer implements Closeable {
private final ReuseStrategy reuseStrategy;
// non final as it gets nulled if closed; pkg private for access by ReuseStrategy's final helper methods:
CloseableThreadLocal<Object> storedValue = new CloseableThreadLocal<Object>();
/**
* Create a new Analyzer, reusing the same set of components per-thread
* across calls to {@link #tokenStream(String, Reader)}.
*/
public Analyzer() {
this(GLOBAL_REUSE_STRATEGY);
}
/**
* Expert: create a new Analyzer with a custom {@link ReuseStrategy}.
* <p>
* NOTE: if you just want to reuse on a per-field basis, its easier to
* use a subclass of {@link AnalyzerWrapper} such as
* <a href="{@docRoot}/../analyzers-common/org/apache/lucene/analysis/miscellaneous/PerFieldAnalyzerWrapper.html">
* PerFieldAnalyerWrapper</a> instead.
*/
public Analyzer(ReuseStrategy reuseStrategy) {
this.reuseStrategy = reuseStrategy;
}
/**
* Creates a new {@link TokenStreamComponents} instance for this analyzer.
*
* @param fieldName
* the name of the fields content passed to the
* {@link TokenStreamComponents} sink as a reader
* @param reader
* the reader passed to the {@link Tokenizer} constructor
* @return the {@link TokenStreamComponents} for this analyzer.
*/
protected abstract TokenStreamComponents createComponents(String fieldName,
Reader reader);
/**
* Returns a TokenStream suitable for <code>fieldName</code>, tokenizing
* the contents of <code>reader</code>.
* <p>
* This method uses {@link #createComponents(String, Reader)} to obtain an
* instance of {@link TokenStreamComponents}. It returns the sink of the
* components and stores the components internally. Subsequent calls to this
* method will reuse the previously stored components after resetting them
* through {@link TokenStreamComponents#setReader(Reader)}.
* <p>
* <b>NOTE:</b> After calling this method, the consumer must follow the
* workflow described in {@link TokenStream} to properly consume its contents.
* See the {@link org.apache.lucene.analysis Analysis package documentation} for
* some examples demonstrating this.
*
* <b>NOTE:</b> If your data is available as a {@code String}, use
* {@link #tokenStream(String, String)} which reuses a {@code StringReader}-like
* instance internally.
*
* @param fieldName the name of the field the created TokenStream is used for
* @param reader the reader the streams source reads from
* @return TokenStream for iterating the analyzed content of <code>reader</code>
* @throws AlreadyClosedException if the Analyzer is closed.
* @throws IOException if an i/o error occurs.
* @see #tokenStream(String, String)
*/
public final TokenStream tokenStream(final String fieldName,
final Reader reader) throws IOException {
TokenStreamComponents components = reuseStrategy.getReusableComponents(this, fieldName);
final Reader r = initReader(fieldName, reader);
if (components == null) {
components = createComponents(fieldName, r);
reuseStrategy.setReusableComponents(this, fieldName, components);
} else {
components.setReader(r);
}
return components.getTokenStream();
}
/**
* Returns a TokenStream suitable for <code>fieldName</code>, tokenizing
* the contents of <code>text</code>.
* <p>
* This method uses {@link #createComponents(String, Reader)} to obtain an
* instance of {@link TokenStreamComponents}. It returns the sink of the
* components and stores the components internally. Subsequent calls to this
* method will reuse the previously stored components after resetting them
* through {@link TokenStreamComponents#setReader(Reader)}.
* <p>
* <b>NOTE:</b> After calling this method, the consumer must follow the
* workflow described in {@link TokenStream} to properly consume its contents.
* See the {@link org.apache.lucene.analysis Analysis package documentation} for
* some examples demonstrating this.
*
* @param fieldName the name of the field the created TokenStream is used for
* @param text the String the streams source reads from
* @return TokenStream for iterating the analyzed content of <code>reader</code>
* @throws AlreadyClosedException if the Analyzer is closed.
* @throws IOException if an i/o error occurs (may rarely happen for strings).
* @see #tokenStream(String, Reader)
*/
public final TokenStream tokenStream(final String fieldName, final String text) throws IOException {
TokenStreamComponents components = reuseStrategy.getReusableComponents(this, fieldName);
@SuppressWarnings("resource") final ReusableStringReader strReader =
(components == null || components.reusableStringReader == null) ?
new ReusableStringReader() : components.reusableStringReader;
strReader.setValue(text);
final Reader r = initReader(fieldName, strReader);
if (components == null) {
components = createComponents(fieldName, r);
reuseStrategy.setReusableComponents(this, fieldName, components);
} else {
components.setReader(r);
}
components.reusableStringReader = strReader;
return components.getTokenStream();
}
/**
* Override this if you want to add a CharFilter chain.
* <p>
* The default implementation returns <code>reader</code>
* unchanged.
*
* @param fieldName IndexableField name being indexed
* @param reader original Reader
* @return reader, optionally decorated with CharFilter(s)
*/
protected Reader initReader(String fieldName, Reader reader) {
return reader;
}
/**
* Invoked before indexing a IndexableField instance if
* terms have already been added to that field. This allows custom
* analyzers to place an automatic position increment gap between
* IndexbleField instances using the same field name. The default value
* position increment gap is 0. With a 0 position increment gap and
* the typical default token position increment of 1, all terms in a field,
* including across IndexableField instances, are in successive positions, allowing
* exact PhraseQuery matches, for instance, across IndexableField instance boundaries.
*
* @param fieldName IndexableField name being indexed.
* @return position increment gap, added to the next token emitted from {@link #tokenStream(String,Reader)}.
* This value must be {@code >= 0}.
*/
public int getPositionIncrementGap(String fieldName) {
return 0;
}
/**
* Just like {@link #getPositionIncrementGap}, except for
* Token offsets instead. By default this returns 1.
* This method is only called if the field
* produced at least one token for indexing.
*
* @param fieldName the field just indexed
* @return offset gap, added to the next token emitted from {@link #tokenStream(String,Reader)}.
* This value must be {@code >= 0}.
*/
public int getOffsetGap(String fieldName) {
return 1;
}
/**
* Returns the used {@link ReuseStrategy}.
*/
public final ReuseStrategy getReuseStrategy() {
return reuseStrategy;
}
/** Frees persistent resources used by this Analyzer */
@Override
public void close() {
if (storedValue != null) {
storedValue.close();
storedValue = null;
}
}
/**
* This class encapsulates the outer components of a token stream. It provides
* access to the source ({@link Tokenizer}) and the outer end (sink), an
* instance of {@link TokenFilter} which also serves as the
* {@link TokenStream} returned by
* {@link Analyzer#tokenStream(String, Reader)}.
*/
public static class TokenStreamComponents {
/**
* Original source of the tokens.
*/
protected final Tokenizer source;
/**
* Sink tokenstream, such as the outer tokenfilter decorating
* the chain. This can be the source if there are no filters.
*/
protected final TokenStream sink;
/** Internal cache only used by {@link Analyzer#tokenStream(String, String)}. */
transient ReusableStringReader reusableStringReader;
/**
* Creates a new {@link TokenStreamComponents} instance.
*
* @param source
* the analyzer's tokenizer
* @param result
* the analyzer's resulting token stream
*/
public TokenStreamComponents(final Tokenizer source,
final TokenStream result) {
this.source = source;
this.sink = result;
}
/**
* Creates a new {@link TokenStreamComponents} instance.
*
* @param source
* the analyzer's tokenizer
*/
public TokenStreamComponents(final Tokenizer source) {
this.source = source;
this.sink = source;
}
/**
* Resets the encapsulated components with the given reader. If the components
* cannot be reset, an Exception should be thrown.
*
* @param reader
* a reader to reset the source component
* @throws IOException
* if the component's reset method throws an {@link IOException}
*/
protected void setReader(final Reader reader) throws IOException {
source.setReader(reader);
}
/**
* Returns the sink {@link TokenStream}
*
* @return the sink {@link TokenStream}
*/
public TokenStream getTokenStream() {
return sink;
}
/**
* Returns the component's {@link Tokenizer}
*
* @return Component's {@link Tokenizer}
*/
public Tokenizer getTokenizer() {
return source;
}
}
/**
* Strategy defining how TokenStreamComponents are reused per call to
* {@link Analyzer#tokenStream(String, java.io.Reader)}.
*/
public static abstract class ReuseStrategy {
/** Sole constructor. (For invocation by subclass constructors, typically implicit.) */
public ReuseStrategy() {}
/**
* Gets the reusable TokenStreamComponents for the field with the given name.
*
* @param analyzer Analyzer from which to get the reused components. Use
* {@link #getStoredValue(Analyzer)} and {@link #setStoredValue(Analyzer, Object)}
* to access the data on the Analyzer.
* @param fieldName Name of the field whose reusable TokenStreamComponents
* are to be retrieved
* @return Reusable TokenStreamComponents for the field, or {@code null}
* if there was no previous components for the field
*/
public abstract TokenStreamComponents getReusableComponents(Analyzer analyzer, String fieldName);
/**
* Stores the given TokenStreamComponents as the reusable components for the
* field with the give name.
*
* @param fieldName Name of the field whose TokenStreamComponents are being set
* @param components TokenStreamComponents which are to be reused for the field
*/
public abstract void setReusableComponents(Analyzer analyzer, String fieldName, TokenStreamComponents components);
/**
* Returns the currently stored value.
*
* @return Currently stored value or {@code null} if no value is stored
* @throws AlreadyClosedException if the Analyzer is closed.
*/
protected final Object getStoredValue(Analyzer analyzer) {
if (analyzer.storedValue == null) {
throw new AlreadyClosedException("this Analyzer is closed");
}
return analyzer.storedValue.get();
}
/**
* Sets the stored value.
*
* @param storedValue Value to store
* @throws AlreadyClosedException if the Analyzer is closed.
*/
protected final void setStoredValue(Analyzer analyzer, Object storedValue) {
if (analyzer.storedValue == null) {
throw new AlreadyClosedException("this Analyzer is closed");
}
analyzer.storedValue.set(storedValue);
}
}
/**
* A predefined {@link ReuseStrategy} that reuses the same components for
* every field.
*/
public static final ReuseStrategy GLOBAL_REUSE_STRATEGY = new ReuseStrategy() {
@Override
public TokenStreamComponents getReusableComponents(Analyzer analyzer, String fieldName) {
return (TokenStreamComponents) getStoredValue(analyzer);
}
@Override
public void setReusableComponents(Analyzer analyzer, String fieldName, TokenStreamComponents components) {
setStoredValue(analyzer, components);
}
};
/**
* A predefined {@link ReuseStrategy} that reuses components per-field by
* maintaining a Map of TokenStreamComponent per field name.
*/
public static final ReuseStrategy PER_FIELD_REUSE_STRATEGY = new ReuseStrategy() {
@SuppressWarnings("unchecked")
@Override
public TokenStreamComponents getReusableComponents(Analyzer analyzer, String fieldName) {
Map<String, TokenStreamComponents> componentsPerField = (Map<String, TokenStreamComponents>) getStoredValue(analyzer);
return componentsPerField != null ? componentsPerField.get(fieldName) : null;
}
@SuppressWarnings("unchecked")
@Override
public void setReusableComponents(Analyzer analyzer, String fieldName, TokenStreamComponents components) {
Map<String, TokenStreamComponents> componentsPerField = (Map<String, TokenStreamComponents>) getStoredValue(analyzer);
if (componentsPerField == null) {
componentsPerField = new HashMap<String, TokenStreamComponents>();
setStoredValue(analyzer, componentsPerField);
}
componentsPerField.put(fieldName, components);
}
};
}
| lucene/core/src/java/org/apache/lucene/analysis/Analyzer.java | package org.apache.lucene.analysis;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.util.CloseableThreadLocal;
import java.io.Closeable;
import java.io.IOException;
import java.io.Reader;
import java.util.HashMap;
import java.util.Map;
/**
* An Analyzer builds TokenStreams, which analyze text. It thus represents a
* policy for extracting index terms from text.
* <p>
* In order to define what analysis is done, subclasses must define their
* {@link TokenStreamComponents TokenStreamComponents} in {@link #createComponents(String, Reader)}.
* The components are then reused in each call to {@link #tokenStream(String, Reader)}.
* <p>
* Simple example:
* <pre class="prettyprint">
* Analyzer analyzer = new Analyzer() {
* {@literal @Override}
* protected TokenStreamComponents createComponents(String fieldName, Reader reader) {
* Tokenizer source = new FooTokenizer(reader);
* TokenStream filter = new FooFilter(source);
* filter = new BarFilter(filter);
* return new TokenStreamComponents(source, filter);
* }
* };
* </pre>
* For more examples, see the {@link org.apache.lucene.analysis Analysis package documentation}.
* <p>
* For some concrete implementations bundled with Lucene, look in the analysis modules:
* <ul>
* <li><a href="{@docRoot}/../analyzers-common/overview-summary.html">Common</a>:
* Analyzers for indexing content in different languages and domains.
* <li><a href="{@docRoot}/../analyzers-icu/overview-summary.html">ICU</a>:
* Exposes functionality from ICU to Apache Lucene.
* <li><a href="{@docRoot}/../analyzers-kuromoji/overview-summary.html">Kuromoji</a>:
* Morphological analyzer for Japanese text.
* <li><a href="{@docRoot}/../analyzers-morfologik/overview-summary.html">Morfologik</a>:
* Dictionary-driven lemmatization for the Polish language.
* <li><a href="{@docRoot}/../analyzers-phonetic/overview-summary.html">Phonetic</a>:
* Analysis for indexing phonetic signatures (for sounds-alike search).
* <li><a href="{@docRoot}/../analyzers-smartcn/overview-summary.html">Smart Chinese</a>:
* Analyzer for Simplified Chinese, which indexes words.
* <li><a href="{@docRoot}/../analyzers-stempel/overview-summary.html">Stempel</a>:
* Algorithmic Stemmer for the Polish Language.
* <li><a href="{@docRoot}/../analyzers-uima/overview-summary.html">UIMA</a>:
* Analysis integration with Apache UIMA.
* </ul>
*/
public abstract class Analyzer implements Closeable {
private final ReuseStrategy reuseStrategy;
// non final as it gets nulled if closed; pkg private for access by ReuseStrategy's final helper methods:
CloseableThreadLocal<Object> storedValue = new CloseableThreadLocal<Object>();
/**
* Create a new Analyzer, reusing the same set of components per-thread
* across calls to {@link #tokenStream(String, Reader)}.
*/
public Analyzer() {
this(GLOBAL_REUSE_STRATEGY);
}
/**
* Expert: create a new Analyzer with a custom {@link ReuseStrategy}.
* <p>
* NOTE: if you just want to reuse on a per-field basis, its easier to
* use a subclass of {@link AnalyzerWrapper} such as
* <a href="{@docRoot}/../analyzers-common/org/apache/lucene/analysis/miscellaneous/PerFieldAnalyzerWrapper.html">
* PerFieldAnalyerWrapper</a> instead.
*/
public Analyzer(ReuseStrategy reuseStrategy) {
this.reuseStrategy = reuseStrategy;
}
/**
* Creates a new {@link TokenStreamComponents} instance for this analyzer.
*
* @param fieldName
* the name of the fields content passed to the
* {@link TokenStreamComponents} sink as a reader
* @param reader
* the reader passed to the {@link Tokenizer} constructor
* @return the {@link TokenStreamComponents} for this analyzer.
*/
protected abstract TokenStreamComponents createComponents(String fieldName,
Reader reader);
/**
* Returns a TokenStream suitable for <code>fieldName</code>, tokenizing
* the contents of <code>reader</code>.
* <p>
* This method uses {@link #createComponents(String, Reader)} to obtain an
* instance of {@link TokenStreamComponents}. It returns the sink of the
* components and stores the components internally. Subsequent calls to this
* method will reuse the previously stored components after resetting them
* through {@link TokenStreamComponents#setReader(Reader)}.
* <p>
* <b>NOTE:</b> After calling this method, the consumer must follow the
* workflow described in {@link TokenStream} to properly consume its contents.
* See the {@link org.apache.lucene.analysis Analysis package documentation} for
* some examples demonstrating this.
*
* <b>NOTE:</b> If your data is available as a {@code String}, use
* {@link #tokenStream(String, String)} which reuses a {@code StringReader}-like
* instance internally.
*
* @param fieldName the name of the field the created TokenStream is used for
* @param reader the reader the streams source reads from
* @return TokenStream for iterating the analyzed content of <code>reader</code>
* @throws AlreadyClosedException if the Analyzer is closed.
* @throws IOException if an i/o error occurs.
* @see #tokenStream(String, String)
*/
public final TokenStream tokenStream(final String fieldName,
final Reader reader) throws IOException {
TokenStreamComponents components = reuseStrategy.getReusableComponents(this, fieldName);
final Reader r = initReader(fieldName, reader);
if (components == null) {
components = createComponents(fieldName, r);
reuseStrategy.setReusableComponents(this, fieldName, components);
} else {
components.setReader(r);
}
return components.getTokenStream();
}
/**
* Returns a TokenStream suitable for <code>fieldName</code>, tokenizing
* the contents of <code>text</code>.
* <p>
* This method uses {@link #createComponents(String, Reader)} to obtain an
* instance of {@link TokenStreamComponents}. It returns the sink of the
* components and stores the components internally. Subsequent calls to this
* method will reuse the previously stored components after resetting them
* through {@link TokenStreamComponents#setReader(Reader)}.
* <p>
* <b>NOTE:</b> After calling this method, the consumer must follow the
* workflow described in {@link TokenStream} to properly consume its contents.
* See the {@link org.apache.lucene.analysis Analysis package documentation} for
* some examples demonstrating this.
*
* @param fieldName the name of the field the created TokenStream is used for
* @param text the String the streams source reads from
* @return TokenStream for iterating the analyzed content of <code>reader</code>
* @throws AlreadyClosedException if the Analyzer is closed.
* @throws IOException if an i/o error occurs (may rarely happen for strings).
* @see #tokenStream(String, Reader)
*/
public final TokenStream tokenStream(final String fieldName, final String text) throws IOException {
TokenStreamComponents components = reuseStrategy.getReusableComponents(this, fieldName);
@SuppressWarnings("resource") final ReusableStringReader strReader =
(components == null || components.reusableStringReader == null) ?
new ReusableStringReader() : components.reusableStringReader;
strReader.setValue(text);
final Reader r = initReader(fieldName, strReader);
if (components == null) {
components = createComponents(fieldName, r);
reuseStrategy.setReusableComponents(this, fieldName, components);
} else {
components.setReader(r);
}
components.reusableStringReader = strReader;
return components.getTokenStream();
}
/**
* Override this if you want to add a CharFilter chain.
* <p>
* The default implementation returns <code>reader</code>
* unchanged.
*
* @param fieldName IndexableField name being indexed
* @param reader original Reader
* @return reader, optionally decorated with CharFilter(s)
*/
protected Reader initReader(String fieldName, Reader reader) {
return reader;
}
/**
* Invoked before indexing a IndexableField instance if
* terms have already been added to that field. This allows custom
* analyzers to place an automatic position increment gap between
* IndexbleField instances using the same field name. The default value
* position increment gap is 0. With a 0 position increment gap and
* the typical default token position increment of 1, all terms in a field,
* including across IndexableField instances, are in successive positions, allowing
* exact PhraseQuery matches, for instance, across IndexableField instance boundaries.
*
* @param fieldName IndexableField name being indexed.
* @return position increment gap, added to the next token emitted from {@link #tokenStream(String,Reader)}.
* This value must be {@code >= 0}.
*/
public int getPositionIncrementGap(String fieldName) {
return 0;
}
/**
* Just like {@link #getPositionIncrementGap}, except for
* Token offsets instead. By default this returns 1.
* This method is only called if the field
* produced at least one token for indexing.
*
* @param fieldName the field just indexed
* @return offset gap, added to the next token emitted from {@link #tokenStream(String,Reader)}.
* This value must be {@code >= 0}.
*/
public int getOffsetGap(String fieldName) {
return 1;
}
/**
* Returns the used {@link ReuseStrategy}.
*/
public final ReuseStrategy getReuseStrategy() {
return reuseStrategy;
}
/** Frees persistent resources used by this Analyzer */
@Override
public void close() {
if (storedValue != null) {
storedValue.close();
storedValue = null;
}
}
/**
* This class encapsulates the outer components of a token stream. It provides
* access to the source ({@link Tokenizer}) and the outer end (sink), an
* instance of {@link TokenFilter} which also serves as the
* {@link TokenStream} returned by
* {@link Analyzer#tokenStream(String, Reader)}.
*/
public static class TokenStreamComponents {
/**
* Original source of the tokens.
*/
protected final Tokenizer source;
/**
* Sink tokenstream, such as the outer tokenfilter decorating
* the chain. This can be the source if there are no filters.
*/
protected final TokenStream sink;
/** Internal cache only used by {@link Analyzer#tokenStream(String, String)}. */
transient ReusableStringReader reusableStringReader;
/**
* Creates a new {@link TokenStreamComponents} instance.
*
* @param source
* the analyzer's tokenizer
* @param result
* the analyzer's resulting token stream
*/
public TokenStreamComponents(final Tokenizer source,
final TokenStream result) {
this.source = source;
this.sink = result;
}
/**
* Creates a new {@link TokenStreamComponents} instance.
*
* @param source
* the analyzer's tokenizer
*/
public TokenStreamComponents(final Tokenizer source) {
this.source = source;
this.sink = source;
}
/**
* Resets the encapsulated components with the given reader. If the components
* cannot be reset, an Exception should be thrown.
*
* @param reader
* a reader to reset the source component
* @throws IOException
* if the component's reset method throws an {@link IOException}
*/
protected void setReader(final Reader reader) throws IOException {
source.setReader(reader);
}
/**
* Returns the sink {@link TokenStream}
*
* @return the sink {@link TokenStream}
*/
public TokenStream getTokenStream() {
return sink;
}
/**
* Returns the component's {@link Tokenizer}
*
* @return Component's {@link Tokenizer}
*/
public Tokenizer getTokenizer() {
return source;
}
}
/**
* Strategy defining how TokenStreamComponents are reused per call to
* {@link Analyzer#tokenStream(String, java.io.Reader)}.
*/
public static abstract class ReuseStrategy {
/** Sole constructor. (For invocation by subclass constructors, typically implicit.) */
public ReuseStrategy() {}
/**
* Gets the reusable TokenStreamComponents for the field with the given name.
*
* @param analyzer Analyzer from which to get the reused components. Use
* {@link #getStoredValue(Analyzer)} and {@link #setStoredValue(Analyzer, Object)}
* to access the data on the Analyzer.
* @param fieldName Name of the field whose reusable TokenStreamComponents
* are to be retrieved
* @return Reusable TokenStreamComponents for the field, or {@code null}
* if there was no previous components for the field
*/
public abstract TokenStreamComponents getReusableComponents(Analyzer analyzer, String fieldName);
/**
* Stores the given TokenStreamComponents as the reusable components for the
* field with the give name.
*
* @param fieldName Name of the field whose TokenStreamComponents are being set
* @param components TokenStreamComponents which are to be reused for the field
*/
public abstract void setReusableComponents(Analyzer analyzer, String fieldName, TokenStreamComponents components);
/**
* Returns the currently stored value.
*
* @return Currently stored value or {@code null} if no value is stored
* @throws AlreadyClosedException if the Analyzer is closed.
*/
protected final Object getStoredValue(Analyzer analyzer) {
if (analyzer.storedValue == null) {
throw new AlreadyClosedException("this Analyzer is closed");
}
return analyzer.storedValue.get();
}
/**
* Sets the stored value.
*
* @param storedValue Value to store
* @throws AlreadyClosedException if the Analyzer is closed.
*/
protected final void setStoredValue(Analyzer analyzer, Object storedValue) {
if (analyzer.storedValue == null) {
throw new AlreadyClosedException("this Analyzer is closed");
}
analyzer.storedValue.set(storedValue);
}
}
/**
* A predefined {@link ReuseStrategy} that reuses the same components for
* every field.
*/
public static final ReuseStrategy GLOBAL_REUSE_STRATEGY = new GlobalReuseStrategy();
/**
* Implementation of {@link ReuseStrategy} that reuses the same components for
* every field.
* @deprecated This implementation class will be hidden in Lucene 5.0.
* Use {@link Analyzer#GLOBAL_REUSE_STRATEGY} instead!
*/
@Deprecated
public final static class GlobalReuseStrategy extends ReuseStrategy {
/** Sole constructor. (For invocation by subclass constructors, typically implicit.)
* @deprecated Don't create instances of this class, use {@link Analyzer#GLOBAL_REUSE_STRATEGY} */
@Deprecated
public GlobalReuseStrategy() {}
@Override
public TokenStreamComponents getReusableComponents(Analyzer analyzer, String fieldName) {
return (TokenStreamComponents) getStoredValue(analyzer);
}
@Override
public void setReusableComponents(Analyzer analyzer, String fieldName, TokenStreamComponents components) {
setStoredValue(analyzer, components);
}
}
/**
* A predefined {@link ReuseStrategy} that reuses components per-field by
* maintaining a Map of TokenStreamComponent per field name.
*/
public static final ReuseStrategy PER_FIELD_REUSE_STRATEGY = new PerFieldReuseStrategy();
/**
* Implementation of {@link ReuseStrategy} that reuses components per-field by
* maintaining a Map of TokenStreamComponent per field name.
* @deprecated This implementation class will be hidden in Lucene 5.0.
* Use {@link Analyzer#PER_FIELD_REUSE_STRATEGY} instead!
*/
@Deprecated
public static class PerFieldReuseStrategy extends ReuseStrategy {
/** Sole constructor. (For invocation by subclass constructors, typically implicit.)
* @deprecated Don't create instances of this class, use {@link Analyzer#PER_FIELD_REUSE_STRATEGY} */
@Deprecated
public PerFieldReuseStrategy() {}
@SuppressWarnings("unchecked")
@Override
public TokenStreamComponents getReusableComponents(Analyzer analyzer, String fieldName) {
Map<String, TokenStreamComponents> componentsPerField = (Map<String, TokenStreamComponents>) getStoredValue(analyzer);
return componentsPerField != null ? componentsPerField.get(fieldName) : null;
}
@SuppressWarnings("unchecked")
@Override
public void setReusableComponents(Analyzer analyzer, String fieldName, TokenStreamComponents components) {
Map<String, TokenStreamComponents> componentsPerField = (Map<String, TokenStreamComponents>) getStoredValue(analyzer);
if (componentsPerField == null) {
componentsPerField = new HashMap<String, TokenStreamComponents>();
setStoredValue(analyzer, componentsPerField);
}
componentsPerField.put(fieldName, components);
}
}
}
| LUCENE-5170: Remove deprecated code
git-svn-id: 308d55f399f3bd9aa0560a10e81a003040006c48@1513914 13f79535-47bb-0310-9956-ffa450edef68
| lucene/core/src/java/org/apache/lucene/analysis/Analyzer.java | LUCENE-5170: Remove deprecated code |
|
Java | apache-2.0 | 87491020bc0418ba2888fb8e0dae4f9b266e6a18 | 0 | catholicon/jackrabbit-oak,alexkli/jackrabbit-oak,anchela/jackrabbit-oak,francescomari/jackrabbit-oak,alexparvulescu/jackrabbit-oak,francescomari/jackrabbit-oak,alexkli/jackrabbit-oak,catholicon/jackrabbit-oak,stillalex/jackrabbit-oak,chetanmeh/jackrabbit-oak,code-distillery/jackrabbit-oak,catholicon/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,catholicon/jackrabbit-oak,chetanmeh/jackrabbit-oak,stillalex/jackrabbit-oak,stillalex/jackrabbit-oak,alexkli/jackrabbit-oak,francescomari/jackrabbit-oak,catholicon/jackrabbit-oak,anchela/jackrabbit-oak,francescomari/jackrabbit-oak,alexparvulescu/jackrabbit-oak,alexparvulescu/jackrabbit-oak,alexkli/jackrabbit-oak,code-distillery/jackrabbit-oak,alexparvulescu/jackrabbit-oak,chetanmeh/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,chetanmeh/jackrabbit-oak,anchela/jackrabbit-oak,alexkli/jackrabbit-oak,alexparvulescu/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,stillalex/jackrabbit-oak,stillalex/jackrabbit-oak,code-distillery/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,code-distillery/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,code-distillery/jackrabbit-oak,anchela/jackrabbit-oak,chetanmeh/jackrabbit-oak,francescomari/jackrabbit-oak,anchela/jackrabbit-oak | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.security.user;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.jcr.RepositoryException;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.spi.security.user.UserConstants;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.plugins.memory.PropertyBuilder;
import com.google.common.collect.Iterators;
import static org.apache.jackrabbit.oak.api.Type.NAME;
/**
* @see MembershipProvider to more details.
*/
public class MembershipWriter {
static final int DEFAULT_MEMBERSHIP_THRESHHOLD = 100;
/**
* size of the membership threshold after which a new overflow node is created.
*/
private int membershipSizeThreshold = DEFAULT_MEMBERSHIP_THRESHHOLD;
public void setMembershipSizeThreshold(int membershipSizeThreshold) {
this.membershipSizeThreshold = membershipSizeThreshold;
}
/**
* Adds a new member to the given {@code groupTree}.
*
* @param groupTree the group to add the member to
* @param memberContentId the id of the new member
* @return {@code true} if the member was added
* @throws RepositoryException if an error occurs
*/
boolean addMember(Tree groupTree, String memberContentId) throws RepositoryException {
Map<String, String> m = Maps.newHashMapWithExpectedSize(1);
m.put(memberContentId, "-");
return addMembers(groupTree, m).isEmpty();
}
/**
* Adds a new member to the given {@code groupTree}.
*
* @param groupTree the group to add the member to
* @param memberIds the ids of the new members as map of 'contentId':'memberId'
* @return the set of member IDs that was not successfully processed.
* @throws RepositoryException if an error occurs
*/
Set<String> addMembers(@Nonnull Tree groupTree, @Nonnull Map<String, String> memberIds) throws RepositoryException {
// check all possible rep:members properties for the new member and also find the one with the least values
Tree membersList = groupTree.getChild(UserConstants.REP_MEMBERS_LIST);
Iterator<Tree> trees = Iterators.concat(
Iterators.singletonIterator(groupTree),
membersList.getChildren().iterator()
);
Set<String> failed = new HashSet<String>(memberIds.size());
int bestCount = membershipSizeThreshold;
PropertyState bestProperty = null;
Tree bestTree = null;
// remove existing memberIds from the map and find best-matching tree
// for the insertion of the new members.
while (trees.hasNext() && !memberIds.isEmpty()) {
Tree t = trees.next();
PropertyState refs = t.getProperty(UserConstants.REP_MEMBERS);
if (refs != null) {
int numRefs = 0;
for (String ref : refs.getValue(Type.WEAKREFERENCES)) {
String id = memberIds.remove(ref);
if (id != null) {
failed.add(id);
if (memberIds.isEmpty()) {
break;
}
}
numRefs++;
}
if (numRefs < bestCount) {
bestCount = numRefs;
bestProperty = refs;
bestTree = t;
}
}
}
// update member content structure by starting inserting new member IDs
// with the best-matching property and create new member-ref-nodes as needed.
if (!memberIds.isEmpty()) {
PropertyBuilder<String> propertyBuilder;
int propCnt;
if (bestProperty == null) {
// we don't have a good candidate to store the new members.
// so there are no members at all or all are full
if (!groupTree.hasProperty(UserConstants.REP_MEMBERS)) {
bestTree = groupTree;
} else {
bestTree = createMemberRefTree(groupTree, membersList);
}
propertyBuilder = PropertyBuilder.array(Type.WEAKREFERENCE, UserConstants.REP_MEMBERS);
propCnt = 0;
} else {
propertyBuilder = PropertyBuilder.copy(Type.WEAKREFERENCE, bestProperty);
propCnt = bestCount;
}
// if adding all new members to best-property would exceed the threshold
// the new ids need to be distributed to different member-ref-nodes
// for simplicity this is achieved by introducing new tree(s)
if ((propCnt + memberIds.size()) > membershipSizeThreshold) {
while (!memberIds.isEmpty()) {
Set s = new HashSet();
Iterator it = memberIds.keySet().iterator();
while (propCnt < membershipSizeThreshold && it.hasNext()) {
s.add(it.next());
it.remove();
propCnt++;
}
propertyBuilder.addValues(s);
bestTree.setProperty(propertyBuilder.getPropertyState());
if (it.hasNext()) {
// continue filling the next (new) node + propertyBuilder pair
propCnt = 0;
bestTree = createMemberRefTree(groupTree, membersList);
propertyBuilder = PropertyBuilder.array(Type.WEAKREFERENCE, UserConstants.REP_MEMBERS);
}
}
} else {
propertyBuilder.addValues(memberIds.keySet());
bestTree.setProperty(propertyBuilder.getPropertyState());
}
}
return failed;
}
private static Tree createMemberRefTree(@Nonnull Tree groupTree, @Nonnull Tree membersList) {
if (!membersList.exists()) {
membersList = groupTree.addChild(UserConstants.REP_MEMBERS_LIST);
membersList.setProperty(JcrConstants.JCR_PRIMARYTYPE, UserConstants.NT_REP_MEMBER_REFERENCES_LIST, NAME);
}
Tree refTree = membersList.addChild(nextRefNodeName(membersList));
refTree.setProperty(JcrConstants.JCR_PRIMARYTYPE, UserConstants.NT_REP_MEMBER_REFERENCES, NAME);
return refTree;
}
private static String nextRefNodeName(@Nonnull Tree membersList) {
// keep node names linear
int i = 0;
String name = String.valueOf(i);
while (membersList.hasChild(name)) {
name = String.valueOf(++i);
}
return name;
}
/**
* Removes the member from the given group.
*
* @param groupTree group to remove the member from
* @param memberContentId member to remove
* @return {@code true} if the member was removed.
*/
boolean removeMember(@Nonnull Tree groupTree, @Nonnull String memberContentId) {
Map<String, String> m = Maps.newHashMapWithExpectedSize(1);
m.put(memberContentId, "-");
return removeMembers(groupTree, m).isEmpty();
}
/**
* Removes the members from the given group.
*
* @param groupTree group to remove the member from
* @param memberIds Map of 'contentId':'memberId' of all members that need to be removed.
* @return the set of member IDs that was not successfully processed.
*/
Set<String> removeMembers(@Nonnull Tree groupTree, @Nonnull Map<String, String> memberIds) {
Tree membersList = groupTree.getChild(UserConstants.REP_MEMBERS_LIST);
Iterator<Tree> trees = Iterators.concat(
Iterators.singletonIterator(groupTree),
membersList.getChildren().iterator()
);
while (trees.hasNext() && !memberIds.isEmpty()) {
Tree t = trees.next();
PropertyState refs = t.getProperty(UserConstants.REP_MEMBERS);
if (refs != null) {
PropertyBuilder<String> prop = PropertyBuilder.copy(Type.WEAKREFERENCE, refs);
Iterator<Map.Entry<String,String>> it = memberIds.entrySet().iterator();
while (it.hasNext() && !prop.isEmpty()) {
String memberContentId = it.next().getKey();
if (prop.hasValue(memberContentId)) {
prop.removeValue(memberContentId);
it.remove();
}
}
if (prop.isEmpty()) {
if (t == groupTree) {
t.removeProperty(UserConstants.REP_MEMBERS);
} else {
t.remove();
}
} else {
t.setProperty(prop.getPropertyState());
}
}
}
return Sets.newHashSet(memberIds.values());
}
/**
* Sets the given set of members to the specified group. this method is only used by the migration code.
*
* @param group node builder of group
* @param members set of content ids to set
*/
public void setMembers(@Nonnull NodeBuilder group, @Nonnull Set<String> members) {
group.removeProperty(UserConstants.REP_MEMBERS);
if (group.hasChildNode(UserConstants.REP_MEMBERS)) {
group.getChildNode(UserConstants.REP_MEMBERS).remove();
}
PropertyBuilder<String> prop = null;
NodeBuilder refList = null;
NodeBuilder node = group;
int count = 0;
int numNodes = 0;
for (String ref : members) {
if (prop == null) {
prop = PropertyBuilder.array(Type.WEAKREFERENCE, UserConstants.REP_MEMBERS);
}
prop.addValue(ref);
count++;
if (count > membershipSizeThreshold) {
node.setProperty(prop.getPropertyState());
prop = null;
if (refList == null) {
// create intermediate structure
refList = group.child(UserConstants.REP_MEMBERS_LIST);
refList.setProperty(JcrConstants.JCR_PRIMARYTYPE, UserConstants.NT_REP_MEMBER_REFERENCES_LIST, NAME);
}
node = refList.child(String.valueOf(numNodes++));
node.setProperty(JcrConstants.JCR_PRIMARYTYPE, UserConstants.NT_REP_MEMBER_REFERENCES, NAME);
}
}
if (prop != null) {
node.setProperty(prop.getPropertyState());
}
}
} | oak-core/src/main/java/org/apache/jackrabbit/oak/security/user/MembershipWriter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jackrabbit.oak.security.user;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nonnull;
import javax.jcr.RepositoryException;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.apache.jackrabbit.JcrConstants;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.api.Type;
import org.apache.jackrabbit.oak.spi.security.user.UserConstants;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.apache.jackrabbit.oak.plugins.memory.PropertyBuilder;
import com.google.common.collect.Iterators;
import static org.apache.jackrabbit.oak.api.Type.NAME;
/**
* @see MembershipProvider to more details.
*/
public class MembershipWriter {
static final int DEFAULT_MEMBERSHIP_THRESHHOLD = 100;
/**
* size of the membership threshold after which a new overflow node is created.
*/
private int membershipSizeThreshold = DEFAULT_MEMBERSHIP_THRESHHOLD;
public void setMembershipSizeThreshold(int membershipSizeThreshold) {
this.membershipSizeThreshold = membershipSizeThreshold;
}
/**
* Adds a new member to the given {@code groupTree}.
*
* @param groupTree the group to add the member to
* @param memberContentId the id of the new member
* @return {@code true} if the member was added
* @throws RepositoryException if an error occurs
*/
boolean addMember(Tree groupTree, String memberContentId) throws RepositoryException {
Map<String, String> m = Maps.newHashMapWithExpectedSize(1);
m.put(memberContentId, "-");
return addMembers(groupTree, m).isEmpty();
}
/**
* Adds a new member to the given {@code groupTree}.
*
* @param groupTree the group to add the member to
* @param memberIds the ids of the new members as map of 'contentId':'memberId'
* @return the set of member IDs that was not successfully processed.
* @throws RepositoryException if an error occurs
*/
Set<String> addMembers(@Nonnull Tree groupTree, @Nonnull Map<String, String> memberIds) throws RepositoryException {
// check all possible rep:members properties for the new member and also find the one with the least values
Tree membersList = groupTree.getChild(UserConstants.REP_MEMBERS_LIST);
Iterator<Tree> trees = Iterators.concat(
Iterators.singletonIterator(groupTree),
membersList.getChildren().iterator()
);
Set<String> failed = new HashSet<String>(memberIds.size());
int bestCount = membershipSizeThreshold;
PropertyState bestProperty = null;
Tree bestTree = null;
// remove existing memberIds from the map and find best-matching tree
// for the insertion of the new members.
while (trees.hasNext() && !memberIds.isEmpty()) {
Tree t = trees.next();
PropertyState refs = t.getProperty(UserConstants.REP_MEMBERS);
if (refs != null) {
int numRefs = 0;
for (String ref : refs.getValue(Type.WEAKREFERENCES)) {
String id = memberIds.remove(ref);
if (id != null) {
failed.add(id);
if (memberIds.isEmpty()) {
break;
}
}
numRefs++;
}
if (numRefs < bestCount) {
bestCount = numRefs;
bestProperty = refs;
bestTree = t;
}
}
}
// update member content structure by starting inserting new member IDs
// with the best-matching property and create new member-ref-nodes as needed.
if (!memberIds.isEmpty()) {
PropertyBuilder<String> propertyBuilder;
int propCnt;
if (bestProperty == null) {
// we don't have a good candidate to store the new members.
// so there are no members at all or all are full
if (!groupTree.hasProperty(UserConstants.REP_MEMBERS)) {
bestTree = groupTree;
} else {
bestTree = createMemberRefTree(groupTree, membersList);
}
propertyBuilder = PropertyBuilder.array(Type.WEAKREFERENCE, UserConstants.REP_MEMBERS);
propCnt = 0;
} else {
propertyBuilder = PropertyBuilder.copy(Type.WEAKREFERENCE, bestProperty);
propCnt = bestCount;
}
// if adding all new members to best-property would exceed the threshold
// the new ids need to be distributed to different member-ref-nodes
// for simplicity this is achieved by introducing new tree(s)
if ((propCnt + memberIds.size()) > membershipSizeThreshold) {
while (!memberIds.isEmpty()) {
Set s = new HashSet();
Iterator it = memberIds.keySet().iterator();
while (propCnt < membershipSizeThreshold && it.hasNext()) {
s.add(it.next());
it.remove();
propCnt++;
}
propertyBuilder.addValues(s);
bestTree.setProperty(propertyBuilder.getPropertyState());
if (it.hasNext()) {
// continue filling the next (new) node + propertyBuilder pair
propCnt = 0;
bestTree = createMemberRefTree(groupTree, membersList);
propertyBuilder = PropertyBuilder.array(Type.WEAKREFERENCE, UserConstants.REP_MEMBERS);
}
}
} else {
propertyBuilder.addValues(memberIds.keySet());
bestTree.setProperty(propertyBuilder.getPropertyState());
}
}
return failed;
}
private static Tree createMemberRefTree(@Nonnull Tree groupTree, @Nonnull Tree membersList) {
if (!membersList.exists()) {
membersList = groupTree.addChild(UserConstants.REP_MEMBERS_LIST);
membersList.setProperty(JcrConstants.JCR_PRIMARYTYPE, UserConstants.NT_REP_MEMBER_REFERENCES_LIST, NAME);
}
Tree refTree = membersList.addChild(nextRefNodeName(membersList));
refTree.setProperty(JcrConstants.JCR_PRIMARYTYPE, UserConstants.NT_REP_MEMBER_REFERENCES, NAME);
return refTree;
}
private static String nextRefNodeName(@Nonnull Tree membersList) {
// keep node names linear
int i = 0;
String name = String.valueOf(i);
while (membersList.hasChild(name)) {
name = String.valueOf(++i);
}
return name;
}
/**
* Removes the member from the given group.
*
* @param groupTree group to remove the member from
* @param memberContentId member to remove
* @return {@code true} if the member was removed.
*/
boolean removeMember(@Nonnull Tree groupTree, @Nonnull String memberContentId) {
Map<String, String> m = Maps.newHashMapWithExpectedSize(1);
m.put(memberContentId, "-");
return removeMembers(groupTree, m).isEmpty();
}
/**
* Removes the members from the given group.
*
* @param groupTree group to remove the member from
* @param memberIds Map of 'contentId':'memberId' of all members that need to be removed.
* @return the set of member IDs that was not successfully processed.
*/
Set<String> removeMembers(@Nonnull Tree groupTree, @Nonnull Map<String, String> memberIds) {
Tree membersList = groupTree.getChild(UserConstants.REP_MEMBERS_LIST);
Iterator<Tree> trees = Iterators.concat(
Iterators.singletonIterator(groupTree),
membersList.getChildren().iterator()
);
while (trees.hasNext() && !memberIds.isEmpty()) {
Tree t = trees.next();
PropertyState refs = t.getProperty(UserConstants.REP_MEMBERS);
if (refs != null) {
PropertyBuilder<String> prop = PropertyBuilder.copy(Type.WEAKREFERENCE, refs);
Iterator<Map.Entry<String,String>> memberEntries = memberIds.entrySet().iterator();
while (memberEntries.hasNext()) {
String memberContentId = memberEntries.next().getKey();
if (prop.hasValue(memberContentId)) {
prop.removeValue(memberContentId);
if (prop.isEmpty()) {
if (t == groupTree) {
t.removeProperty(UserConstants.REP_MEMBERS);
} else {
t.remove();
}
} else {
t.setProperty(prop.getPropertyState());
}
memberEntries.remove();
}
}
}
}
return Sets.newHashSet(memberIds.values());
}
/**
* Sets the given set of members to the specified group. this method is only used by the migration code.
*
* @param group node builder of group
* @param members set of content ids to set
*/
public void setMembers(@Nonnull NodeBuilder group, @Nonnull Set<String> members) {
group.removeProperty(UserConstants.REP_MEMBERS);
if (group.hasChildNode(UserConstants.REP_MEMBERS)) {
group.getChildNode(UserConstants.REP_MEMBERS).remove();
}
PropertyBuilder<String> prop = null;
NodeBuilder refList = null;
NodeBuilder node = group;
int count = 0;
int numNodes = 0;
for (String ref : members) {
if (prop == null) {
prop = PropertyBuilder.array(Type.WEAKREFERENCE, UserConstants.REP_MEMBERS);
}
prop.addValue(ref);
count++;
if (count > membershipSizeThreshold) {
node.setProperty(prop.getPropertyState());
prop = null;
if (refList == null) {
// create intermediate structure
refList = group.child(UserConstants.REP_MEMBERS_LIST);
refList.setProperty(JcrConstants.JCR_PRIMARYTYPE, UserConstants.NT_REP_MEMBER_REFERENCES_LIST, NAME);
}
node = refList.child(String.valueOf(numNodes++));
node.setProperty(JcrConstants.JCR_PRIMARYTYPE, UserConstants.NT_REP_MEMBER_REFERENCES, NAME);
}
}
if (prop != null) {
node.setProperty(prop.getPropertyState());
}
}
} | OAK-5939 : MembershipWriter.removeMembers writes back too often
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1787077 13f79535-47bb-0310-9956-ffa450edef68
| oak-core/src/main/java/org/apache/jackrabbit/oak/security/user/MembershipWriter.java | OAK-5939 : MembershipWriter.removeMembers writes back too often |
|
Java | apache-2.0 | 57a52638ea2aafc0f77f2152f5cd72c82710baae | 0 | davidmoten/rxjava2-jdbc,davidmoten/rxjava2-jdbc,davidmoten/rxjava2-jdbc | package org.davidmoten.rx.jdbc.pool;
import java.sql.Connection;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import javax.sql.DataSource;
import org.davidmoten.rx.jdbc.ConnectionProvider;
import org.davidmoten.rx.jdbc.Util;
import org.davidmoten.rx.jdbc.pool.internal.HealthCheckPredicate;
import org.davidmoten.rx.jdbc.pool.internal.PooledConnection;
import org.davidmoten.rx.jdbc.pool.internal.SerializedConnectionListener;
import org.davidmoten.rx.pool.Member;
import org.davidmoten.rx.pool.NonBlockingPool;
import org.davidmoten.rx.pool.Pool;
import com.github.davidmoten.guavamini.Preconditions;
import io.reactivex.Scheduler;
import io.reactivex.Single;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;
import io.reactivex.internal.schedulers.ExecutorScheduler;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.Schedulers;
public final class NonBlockingConnectionPool implements Pool<Connection> {
private final AtomicReference<NonBlockingPool<Connection>> pool = new AtomicReference<>();
NonBlockingConnectionPool(org.davidmoten.rx.pool.NonBlockingPool.Builder<Connection> builder) {
pool.set(builder.build());
}
public static Builder<NonBlockingConnectionPool> builder() {
return new Builder<NonBlockingConnectionPool>(x -> x);
}
public static final class Builder<T> {
private ConnectionProvider cp;
private Predicate<? super Connection> healthCheck = c -> true;
private int maxPoolSize = 5;
private long idleTimeBeforeHealthCheckMs = 60000;
private long maxIdleTimeMs = 30 * 60000;
private long connectionRetryIntervalMs = 30000;
private Consumer<? super Connection> disposer = Util::closeSilently;
private Scheduler scheduler = null;
private Properties properties = new Properties();
private final Function<NonBlockingConnectionPool, T> transform;
private String url;
private Consumer<? super Optional<Throwable>> c;
public Builder(Function<NonBlockingConnectionPool, T> transform) {
this.transform = transform;
}
/**
* Sets the provider of {@link Connection} objects to be used by the pool.
*
* @param cp
* connection provider
* @return this
*/
public Builder<T> connectionProvider(ConnectionProvider cp) {
this.cp = cp;
return this;
}
/**
* Sets the provider of {@link Connection} objects to be used by the pool.
*
* @param ds
* dataSource that providers Connections
* @return this
*/
public Builder<T> connectionProvider(DataSource ds) {
return connectionProvider(Util.connectionProvider(ds));
}
/**
* Sets the jdbc url of the {@link Connection} objects to be used by the pool.
*
* @param url
* jdbc url
* @return this
*/
public Builder<T> url(String url) {
this.url = url;
return this;
}
/**
* Sets the JDBC properties that will be passed to
* {@link java.sql.DriverManager#getConnection}. The properties will only be
* used if the {@code url} has been set in the builder.
*
* @param properties
* the jdbc properties
* @return this
*/
public Builder<T> properties(Properties properties) {
this.properties = properties;
return this;
}
/**
* Adds the given property specified by key and value to the JDBC properties
* that will be passed to {@link java.sql.DriverManager#getConnection}. The
* properties will only be used if the {@code url} has been set in the builder.
*
* @param key
* property key
* @param value
* property value
* @return this
*/
public Builder<T> property(Object key, Object value) {
this.properties.put(key, value);
return this;
}
/**
* Sets the max time a {@link Connection} can be idle (checked in to pool)
* before it is released from the pool (the Connection is closed).
*
* @param duration
* the period before which an idle Connection is released from the
* pool (closed).
* @param unit
* time unit
* @return this
*/
public Builder<T> maxIdleTime(long duration, TimeUnit unit) {
this.maxIdleTimeMs = unit.toMillis(duration);
return this;
}
/**
* Sets the minimum time that a connection must be idle (checked in) before on
* the next checkout its validity is checked using the health check function. If
* the health check fails then the Connection is closed (ignoring error) and
* released from the pool. Another Connection is then scheduled for creation
* (using the createRetryInterval delay).
*
* @param duration
* minimum time a connection must be idle before its validity is
* checked on checkout from the pool
* @param unit
* time unit
* @return this
*/
public Builder<T> idleTimeBeforeHealthCheck(long duration, TimeUnit unit) {
this.idleTimeBeforeHealthCheckMs = unit.toMillis(duration);
return this;
}
/**
* Sets the retry interval in the case that creating/reestablishing a
* {@link Connection} for use in the pool fails.
*
* @param duration
* Connection creation retry interval
* @param unit
* time unit
* @return this
*/
public Builder<T> connectionRetryInterval(long duration, TimeUnit unit) {
this.connectionRetryIntervalMs = unit.toMillis(duration);
return this;
}
/**
* Sets the health check for a Connection in the pool that is run only if the
* time since the last checkout of this Connection finished is more than
* idleTimeBeforeHealthCheck and a checkout of this Connection has just been
* requested.
*
* @param healthCheck
* check to run on Connection. Returns true if and only if the
* Connection is valid/healthy.
* @return this
*/
public Builder<T> healthCheck(Predicate<? super Connection> healthCheck) {
this.healthCheck = healthCheck;
return this;
}
/**
* Sets the health check for a Connection in the pool that is run only if the
* time since the last checkout of this Connection finished is more than
* idleTimeBeforeHealthCheck and a checkout of this Connection has just been
* requested.
*
* @param databaseType
* the check to run is chosen based on the database type
* @return this
*/
public Builder<T> healthCheck(DatabaseType databaseType) {
return healthCheck(databaseType.healthCheck());
}
/**
* Sets the health check for a Connection in the pool that is run only if the
* time since the last checkout of this Connection finished is more than
* idleTimeBeforeHealthCheck and a checkout of this Connection has just been
* requested.
*
* @param sql
* sql to run to check the validity of the connection. If the sql is
* run without error then the connection is assumed healthy.
* @return this
*/
public Builder<T> healthCheck(String sql) {
return healthCheck(new HealthCheckPredicate(sql));
}
/**
* Sets a listener for connection success and failure. Success and failure
* events are reported serially to the listener. If the consumer throws it will
* be reported to {@code RxJavaPlugins.onError}. This consumer should not block
* otherwise it will block the connection pool itself.
*
* @param c
* listener for connection events
* @return this
*/
public Builder<T> connnectionListener(Consumer<? super Optional<Throwable>> c) {
Preconditions.checkArgument(c != null, "listener can only be set once");
this.c = c;
return this;
}
/**
* Sets the maximum connection pool size. Default is 5.
*
* @param maxPoolSize
* maximum number of connections in the pool
* @return this
*/
public Builder<T> maxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
return this;
}
/**
* Sets the scheduler used for emitting connections (must be scheduled to
* another thread to break the chain of stack calls otherwise can get
* StackOverflowError) and for scheduling timeouts and retries. Defaults to
* {@code Schedulers.from(Executors.newFixedThreadPool(maxPoolSize))}. Do not
* set the scheduler to {@code Schedulers.trampoline()} because queries will
* block waiting for timeout workers. Also, do not use a single-threaded
* {@link Scheduler} because you may encounter {@link StackOverflowError}.
*
* @param scheduler
* scheduler to use for emitting connections and for scheduling
* timeouts and retries. Defaults to
* {@code Schedulers.from(Executors.newFixedThreadPool(maxPoolSize))}.
* Do not use {@code Schedulers.trampoline()}.
* @throws IllegalArgumentException
* if trampoline specified
* @return this
*/
public Builder<T> scheduler(Scheduler scheduler) {
Preconditions.checkArgument(scheduler != Schedulers.trampoline(),
"do not use trampoline scheduler because of risk of stack overflow");
this.scheduler = scheduler;
return this;
}
public T build() {
if (scheduler == null) {
ExecutorService executor = Executors.newFixedThreadPool(maxPoolSize);
scheduler = new ExecutorScheduler(executor);
}
if (url != null) {
cp = Util.connectionProvider(url, properties);
}
Consumer<Optional<Throwable>> listener;
if (c == null) {
listener = null;
} else {
listener = new SerializedConnectionListener(c);
}
NonBlockingConnectionPool p = new NonBlockingConnectionPool(NonBlockingPool //
.factory(() -> {
try {
Connection con = cp.get();
if (listener != null) {
try {
listener.accept(Optional.empty());
} catch (Throwable e) {
RxJavaPlugins.onError(e);
}
}
return con;
} catch (Throwable e) {
if (listener != null) {
try {
listener.accept(Optional.of(e));
} catch (Throwable e2) {
RxJavaPlugins.onError(e2);
}
}
throw e;
}
}) //
.checkinDecorator((con, checkin) -> new PooledConnection(con, checkin)) //
.idleTimeBeforeHealthCheck(idleTimeBeforeHealthCheckMs, TimeUnit.MILLISECONDS) //
.maxIdleTime(maxIdleTimeMs, TimeUnit.MILLISECONDS) //
.createRetryInterval(connectionRetryIntervalMs, TimeUnit.MILLISECONDS) //
.scheduler(scheduler) //
.disposer(disposer)//
.healthCheck(healthCheck) //
.scheduler(scheduler) //
.maxSize(maxPoolSize) //
);
return transform.apply(p);
}
}
@Override
public Single<Member<Connection>> member() {
return pool.get().member();
}
@Override
public void close() {
pool.get().close();
}
}
| rxjava2-jdbc/src/main/java/org/davidmoten/rx/jdbc/pool/NonBlockingConnectionPool.java | package org.davidmoten.rx.jdbc.pool;
import java.sql.Connection;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import javax.sql.DataSource;
import org.davidmoten.rx.jdbc.ConnectionProvider;
import org.davidmoten.rx.jdbc.Util;
import org.davidmoten.rx.jdbc.pool.internal.HealthCheckPredicate;
import org.davidmoten.rx.jdbc.pool.internal.PooledConnection;
import org.davidmoten.rx.jdbc.pool.internal.SerializedConnectionListener;
import org.davidmoten.rx.pool.Member;
import org.davidmoten.rx.pool.NonBlockingPool;
import org.davidmoten.rx.pool.Pool;
import com.github.davidmoten.guavamini.Preconditions;
import io.reactivex.Scheduler;
import io.reactivex.Single;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Predicate;
import io.reactivex.internal.schedulers.ExecutorScheduler;
import io.reactivex.plugins.RxJavaPlugins;
import io.reactivex.schedulers.Schedulers;
public final class NonBlockingConnectionPool implements Pool<Connection> {
private final AtomicReference<NonBlockingPool<Connection>> pool = new AtomicReference<>();
NonBlockingConnectionPool(org.davidmoten.rx.pool.NonBlockingPool.Builder<Connection> builder) {
pool.set(builder.build());
}
public static Builder<NonBlockingConnectionPool> builder() {
return new Builder<NonBlockingConnectionPool>(x -> x);
}
public static final class Builder<T> {
private ConnectionProvider cp;
private Predicate<? super Connection> healthCheck = c -> true;
private int maxPoolSize = 5;
private long idleTimeBeforeHealthCheckMs = 60000;
private long maxIdleTimeMs = 30 * 60000;
private long connectionRetryIntervalMs = 30000;
private Consumer<? super Connection> disposer = Util::closeSilently;
private Scheduler scheduler = null;
private Properties properties = new Properties();
private final Function<NonBlockingConnectionPool, T> transform;
private String url;
private Consumer<? super Optional<Throwable>> c;
public Builder(Function<NonBlockingConnectionPool, T> transform) {
this.transform = transform;
}
/**
* Sets the provider of {@link Connection} objects to be used by the pool.
*
* @param cp
* connection provider
* @return this
*/
public Builder<T> connectionProvider(ConnectionProvider cp) {
this.cp = cp;
return this;
}
/**
* Sets the provider of {@link Connection} objects to be used by the pool.
*
* @param ds
* dataSource that providers Connections
* @return this
*/
public Builder<T> connectionProvider(DataSource ds) {
return connectionProvider(Util.connectionProvider(ds));
}
/**
* Sets the jdbc url of the {@link Connection} objects to be used by the pool.
*
* @param url
* jdbc url
* @return this
*/
public Builder<T> url(String url) {
this.url = url;
return this;
}
/**
* Sets the JDBC properties that will be passed to
* {@link java.sql.DriverManager#getConnection}. The properties will only be
* used if the {@code url} has been set in the builder.
*
* @param properties
* the jdbc properties
* @return this
*/
public Builder<T> properties(Properties properties) {
this.properties = properties;
return this;
}
/**
* Adds the given property specified by key and value to the JDBC properties
* that will be passed to {@link java.sql.DriverManager#getConnection}. The
* properties will only be used if the {@code url} has been set in the builder.
*
* @param key
* property key
* @param value
* property value
* @return this
*/
public Builder<T> property(Object key, Object value) {
this.properties.put(key, value);
return this;
}
/**
* Sets the max time a {@link Connection} can be idle (checked in to pool)
* before it is released from the pool (the Connection is closed).
*
* @param duration
* the period before which an idle Connection is released from the
* pool (closed).
* @param unit
* time unit
* @return this
*/
public Builder<T> maxIdleTime(long duration, TimeUnit unit) {
this.maxIdleTimeMs = unit.toMillis(duration);
return this;
}
/**
* Sets the minimum time that a connection must be idle (checked in) before on
* the next checkout its validity is checked using the health check function. If
* the health check fails then the Connection is closed (ignoring error) and
* released from the pool. Another Connection is then scheduled for creation
* (using the createRetryInterval delay).
*
* @param duration
* minimum time a connection must be idle before its validity is
* checked on checkout from the pool
* @param unit
* time unit
* @return this
*/
public Builder<T> idleTimeBeforeHealthCheck(long duration, TimeUnit unit) {
this.idleTimeBeforeHealthCheckMs = unit.toMillis(duration);
return this;
}
/**
* Sets the retry interval in the case that creating/reestablishing a
* {@link Connection} for use in the pool fails.
*
* @param duration
* Connection creation retry interval
* @param unit
* time unit
* @return this
*/
public Builder<T> connectionRetryInterval(long duration, TimeUnit unit) {
this.connectionRetryIntervalMs = unit.toMillis(duration);
return this;
}
/**
* Sets the health check for a Connection in the pool that is run only if the
* time since the last checkout of this Connection finished is more than
* idleTimeBeforeHealthCheck and a checkout of this Connection has just been
* requested.
*
* @param healthCheck
* check to run on Connection. Returns true if and only if the
* Connection is valid/healthy.
* @return this
*/
public Builder<T> healthCheck(Predicate<? super Connection> healthCheck) {
this.healthCheck = healthCheck;
return this;
}
/**
* Sets the health check for a Connection in the pool that is run only if the
* time since the last checkout of this Connection finished is more than
* idleTimeBeforeHealthCheck and a checkout of this Connection has just been
* requested.
*
* @param databaseType
* the check to run is chosen based on the database type
* @return this
*/
public Builder<T> healthCheck(DatabaseType databaseType) {
return healthCheck(databaseType.healthCheck());
}
/**
* Sets the health check for a Connection in the pool that is run only if the
* time since the last checkout of this Connection finished is more than
* idleTimeBeforeHealthCheck and a checkout of this Connection has just been
* requested.
*
* @param sql
* sql to run to check the validity of the connection. If the sql is
* run without error then the connection is assumed healthy.
* @return this
*/
public Builder<T> healthCheck(String sql) {
return healthCheck(new HealthCheckPredicate(sql));
}
/**
* Sets a listener for connection success and failure. Success and failure
* events are reported serially to the listener. If the consumer throws it will
* be reported to {@code RxJavaPlugins.onError}.
*
* @param c
* listener for connection events
* @return this
*/
public Builder<T> connnectionListener(Consumer<? super Optional<Throwable>> c) {
Preconditions.checkArgument(c != null, "listener can only be set once");
this.c = c;
return this;
}
/**
* Sets the maximum connection pool size. Default is 5.
*
* @param maxPoolSize
* maximum number of connections in the pool
* @return this
*/
public Builder<T> maxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
return this;
}
/**
* Sets the scheduler used for emitting connections (must be scheduled to
* another thread to break the chain of stack calls otherwise can get
* StackOverflowError) and for scheduling timeouts and retries. Defaults to
* {@code Schedulers.from(Executors.newFixedThreadPool(maxPoolSize))}. Do not
* set the scheduler to {@code Schedulers.trampoline()} because queries will
* block waiting for timeout workers. Also, do not use a single-threaded
* {@link Scheduler} because you may encounter {@link StackOverflowError}.
*
* @param scheduler
* scheduler to use for emitting connections and for scheduling
* timeouts and retries. Defaults to
* {@code Schedulers.from(Executors.newFixedThreadPool(maxPoolSize))}.
* Do not use {@code Schedulers.trampoline()}.
* @throws IllegalArgumentException
* if trampoline specified
* @return this
*/
public Builder<T> scheduler(Scheduler scheduler) {
Preconditions.checkArgument(scheduler != Schedulers.trampoline(),
"do not use trampoline scheduler because of risk of stack overflow");
this.scheduler = scheduler;
return this;
}
public T build() {
if (scheduler == null) {
ExecutorService executor = Executors.newFixedThreadPool(maxPoolSize);
scheduler = new ExecutorScheduler(executor);
}
if (url != null) {
cp = Util.connectionProvider(url, properties);
}
Consumer<Optional<Throwable>> listener;
if (c == null) {
listener = null;
} else {
listener = new SerializedConnectionListener(c);
}
NonBlockingConnectionPool p = new NonBlockingConnectionPool(NonBlockingPool //
.factory(() -> {
try {
Connection con = cp.get();
if (listener != null) {
try {
listener.accept(Optional.empty());
} catch (Throwable e) {
RxJavaPlugins.onError(e);
}
}
return con;
} catch (Throwable e) {
if (listener != null) {
try {
listener.accept(Optional.of(e));
} catch (Throwable e2) {
RxJavaPlugins.onError(e2);
}
}
throw e;
}
}) //
.checkinDecorator((con, checkin) -> new PooledConnection(con, checkin)) //
.idleTimeBeforeHealthCheck(idleTimeBeforeHealthCheckMs, TimeUnit.MILLISECONDS) //
.maxIdleTime(maxIdleTimeMs, TimeUnit.MILLISECONDS) //
.createRetryInterval(connectionRetryIntervalMs, TimeUnit.MILLISECONDS) //
.scheduler(scheduler) //
.disposer(disposer)//
.healthCheck(healthCheck) //
.scheduler(scheduler) //
.maxSize(maxPoolSize) //
);
return transform.apply(p);
}
}
@Override
public Single<Member<Connection>> member() {
return pool.get().member();
}
@Override
public void close() {
pool.get().close();
}
}
| add javadoc
| rxjava2-jdbc/src/main/java/org/davidmoten/rx/jdbc/pool/NonBlockingConnectionPool.java | add javadoc |
|
Java | apache-2.0 | 5671b0c332c2278b0e029465ec53e556e8ba2c26 | 0 | neo4j-contrib/neo4j-apoc-procedures,neo4j-contrib/neo4j-apoc-procedures,neo4j-contrib/neo4j-apoc-procedures,neo4j-contrib/neo4j-apoc-procedures | package apoc.util;
import com.github.dockerjava.api.exception.NotFoundException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.gradle.tooling.BuildLauncher;
import org.gradle.tooling.GradleConnector;
import org.gradle.tooling.ProjectConnection;
import org.neo4j.driver.Record;
import org.neo4j.driver.Session;
import org.testcontainers.containers.ContainerFetchException;
import org.testcontainers.utility.MountableFile;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static apoc.util.TestUtil.printFullStackTrace;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class TestContainerUtil {
public enum Neo4jVersion {
ENTERPRISE,
COMMUNITY
}
// read neo4j version from build.gradle
public static final String neo4jEnterpriseDockerImageVersion = System.getProperty("neo4jDockerImage");
public static final String neo4jCommunityDockerImageVersion = System.getProperty("neo4jCommunityDockerImage");
private TestContainerUtil() {}
private static File baseDir = Paths.get(".").toFile();
public static TestcontainersCausalCluster createEnterpriseCluster(int numOfCoreInstances, int numberOfReadReplica, Map<String, Object> neo4jConfig, Map<String, String> envSettings) {
return TestcontainersCausalCluster.create(numOfCoreInstances, numberOfReadReplica, Duration.ofMinutes(4), neo4jConfig, envSettings);
}
public static Neo4jContainerExtension createDB(Neo4jVersion version, File baseDir, boolean withLogging) {
return switch(version) {
case ENTERPRISE -> createEnterpriseDB(baseDir, withLogging);
case COMMUNITY -> createCommunityDB(baseDir, withLogging);
};
}
public static Neo4jContainerExtension createEnterpriseDB(boolean withLogging) {
return createEnterpriseDB(baseDir, withLogging);
}
public static Neo4jContainerExtension createEnterpriseDB(File baseDir, boolean withLogging) {
return createNeo4jContainer(neo4jEnterpriseDockerImageVersion, baseDir, withLogging );
}
public static Neo4jContainerExtension createCommunityDB(File baseDir, boolean withLogging) {
return createNeo4jContainer(neo4jCommunityDockerImageVersion, baseDir, withLogging );
}
private static Neo4jContainerExtension createNeo4jContainer(String dockerImage, File baseDir, boolean withLogging) {
executeGradleTasks(baseDir, "shadowJar");
// We define the container with external volumes
File importFolder = new File("import");
importFolder.mkdirs();
// use a separate folder for mounting plugins jar - build/libs might contain other jars as well.
File pluginsFolder = new File(baseDir, "build/plugins");
pluginsFolder.mkdirs();
Collection<File> files = FileUtils.listFiles(new File(baseDir, "build/libs"), new WildcardFileFilter(Arrays.asList("*-all.jar", "*-core.jar")), null);
for (File file: files) {
try {
FileUtils.copyFileToDirectory(file, pluginsFolder);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
String canonicalPath = null;
try {
canonicalPath = importFolder.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("neo4jDockerImageVersion = " + dockerImage);
Neo4jContainerExtension neo4jContainer = new Neo4jContainerExtension(dockerImage)
.withPlugins(MountableFile.forHostPath(pluginsFolder.toPath()))
.withAdminPassword("apoc")
.withEnv("NEO4J_dbms_memory_heap_max__size", "512M")
.withEnv("NEO4J_dbms_memory_pagecache_size", "256M")
.withEnv("apoc.export.file.enabled", "true")
.withNeo4jConfig("dbms.security.procedures.unrestricted", "apoc.*")
.withFileSystemBind(canonicalPath, "/var/lib/neo4j/import") // map the "target/import" dir as the Neo4j's import dir
.withEnv("NEO4J_ACCEPT_LICENSE_AGREEMENT", "yes")
// .withDebugger() // uncomment this line for remote debbuging inside docker's neo4j instance
.withCreateContainerCmdModifier(cmd -> cmd.withMemory(2024 * 1024 * 1024l))
// set uid if possible - export tests do write to "/import"
.withCreateContainerCmdModifier(cmd -> {
try {
Process p = Runtime.getRuntime().exec("id -u");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = br.readLine();
p.waitFor();
p.destroy();
cmd.withUser(s);
} catch (Exception e) {
System.out.println("Exception while assign cmd user to docker container:\n" + ExceptionUtils.getStackTrace(e));
// ignore since it may fail depending on operating system
}
});
if (withLogging) {
neo4jContainer.withLogging();
}
return neo4jContainer;
}
public static void executeGradleTasks(File baseDir, String... tasks) {
try (ProjectConnection connection = GradleConnector.newConnector()
.forProjectDirectory(baseDir)
.useBuildDistribution()
.connect()) {
// String version = connection.getModel(ProjectPublications.class).getPublications().getAt(0).getId().getVersion();
BuildLauncher buildLauncher = connection.newBuild().forTasks(tasks);
String neo4jVersionOverride = System.getenv("NEO4JVERSION");
System.out.println("neo4jVersionOverride = " + neo4jVersionOverride);
if (neo4jVersionOverride != null) {
buildLauncher = buildLauncher.addArguments("-P", "neo4jVersionOverride=" + neo4jVersionOverride);
}
String localMaven = System.getenv("LOCAL_MAVEN");
System.out.println("localMaven = " + localMaven);
if (localMaven != null) {
buildLauncher = buildLauncher.addArguments("-D", "maven.repo.local=" + localMaven);
}
buildLauncher.run();
}
}
public static void executeGradleTasks(String... tasks) {
executeGradleTasks(baseDir, tasks);
}
public static void testCall(Session session, String call, Map<String,Object> params, Consumer<Map<String, Object>> consumer) {
testResult(session, call, params, (res) -> {
try {
assertNotNull("result should be not null", res);
assertTrue("result should be not empty", res.hasNext());
Map<String, Object> row = res.next();
consumer.accept(row);
assertFalse("result should not have next", res.hasNext());
} catch(Throwable t) {
printFullStackTrace(t);
throw t;
}
});
}
public static void testCall(Session session, String call, Consumer<Map<String, Object>> consumer) {
testCall(session, call, null, consumer);
}
public static void testResult(Session session, String call, Consumer<Iterator<Map<String, Object>>> resultConsumer) {
testResult(session, call, null, resultConsumer);
}
public static void testResult(Session session, String call, Map<String,Object> params, Consumer<Iterator<Map<String, Object>>> resultConsumer) {
session.writeTransaction(tx -> {
Map<String, Object> p = (params == null) ? Collections.<String, Object>emptyMap() : params;
resultConsumer.accept(tx.run(call, p).list().stream().map(Record::asMap).collect(Collectors.toList()).iterator());
tx.commit();
return null;
});
}
public static void testCallInReadTransaction(Session session, String call, Consumer<Map<String, Object>> consumer) {
testCallInReadTransaction(session, call, null, consumer);
}
public static void testCallInReadTransaction(Session session, String call, Map<String,Object> params, Consumer<Map<String, Object>> consumer) {
testResultInReadTransaction(session, call, params, (res) -> {
try {
assertNotNull("result should be not null", res);
assertTrue("result should be not empty", res.hasNext());
Map<String, Object> row = res.next();
consumer.accept(row);
assertFalse("result should not have next", res.hasNext());
} catch(Throwable t) {
printFullStackTrace(t);
throw t;
}
});
}
public static void testResultInReadTransaction(Session session, String call, Consumer<Iterator<Map<String, Object>>> resultConsumer) {
testResultInReadTransaction(session, call, null, resultConsumer);
}
public static void testResultInReadTransaction(Session session, String call, Map<String,Object> params, Consumer<Iterator<Map<String, Object>>> resultConsumer) {
session.readTransaction(tx -> {
Map<String, Object> p = (params == null) ? Collections.<String, Object>emptyMap() : params;
resultConsumer.accept(tx.run(call, p).list().stream().map(Record::asMap).collect(Collectors.toList()).iterator());
tx.commit();
return null;
});
}
public static <T> T singleResultFirstColumn(Session session, String cypher, Map<String,Object> params) {
return (T) session.writeTransaction(tx -> tx.run(cypher, params).single().fields().get(0).value().asObject());
}
public static <T> T singleResultFirstColumn(Session session, String cypher) {
return singleResultFirstColumn(session, cypher, Map.of());
}
public static boolean isDockerImageAvailable(Exception ex) {
final Throwable cause = ex.getCause();
final Throwable rootCause = ExceptionUtils.getRootCause(ex);
return !(cause instanceof ContainerFetchException && rootCause instanceof NotFoundException);
}
}
| test-utils/src/main/java/apoc/util/TestContainerUtil.java | package apoc.util;
import com.github.dockerjava.api.exception.NotFoundException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.gradle.tooling.BuildLauncher;
import org.gradle.tooling.GradleConnector;
import org.gradle.tooling.ProjectConnection;
import org.neo4j.driver.Record;
import org.neo4j.driver.Session;
import org.testcontainers.containers.ContainerFetchException;
import org.testcontainers.utility.MountableFile;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import static apoc.util.TestUtil.printFullStackTrace;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
public class TestContainerUtil {
public enum Neo4jVersion {
ENTERPRISE,
COMMUNITY
}
// read neo4j version from build.gradle
public static final String neo4jEnterpriseDockerImageVersion = System.getProperty("neo4jDockerImage");
public static final String neo4jCommunityDockerImageVersion = System.getProperty("neo4jCommunityDockerImage");
private TestContainerUtil() {}
private static File baseDir = Paths.get(".").toFile();
public static TestcontainersCausalCluster createEnterpriseCluster(int numOfCoreInstances, int numberOfReadReplica, Map<String, Object> neo4jConfig, Map<String, String> envSettings) {
return TestcontainersCausalCluster.create(numOfCoreInstances, numberOfReadReplica, Duration.ofMinutes(4), neo4jConfig, envSettings);
}
public static Neo4jContainerExtension createDB(Neo4jVersion version, File baseDir, boolean withLogging) {
return switch(version) {
case ENTERPRISE -> createEnterpriseDB(baseDir, withLogging);
case COMMUNITY -> createCommunityDB(baseDir, withLogging);
};
}
public static Neo4jContainerExtension createEnterpriseDB(boolean withLogging) {
return createEnterpriseDB(baseDir, withLogging);
}
public static Neo4jContainerExtension createEnterpriseDB(File baseDir, boolean withLogging) {
return createNeo4jContainer(neo4jEnterpriseDockerImageVersion, baseDir, withLogging );
}
public static Neo4jContainerExtension createCommunityDB(File baseDir, boolean withLogging) {
return createNeo4jContainer(neo4jCommunityDockerImageVersion, baseDir, withLogging );
}
private static Neo4jContainerExtension createNeo4jContainer(String dockerImage, File baseDir, boolean withLogging) {
executeGradleTasks(baseDir, "shadowJar");
// We define the container with external volumes
File importFolder = new File("import");
importFolder.mkdirs();
// use a separate folder for mounting plugins jar - build/libs might contain other jars as well.
File pluginsFolder = new File(baseDir, "build/plugins");
pluginsFolder.mkdirs();
Collection<File> files = FileUtils.listFiles(new File(baseDir, "build/libs"), new WildcardFileFilter(Arrays.asList("*-all.jar", "*-core.jar")), null);
for (File file: files) {
try {
FileUtils.copyFileToDirectory(file, pluginsFolder);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
String canonicalPath = null;
try {
canonicalPath = importFolder.getCanonicalPath();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("neo4jDockerImageVersion = " + dockerImage);
Neo4jContainerExtension neo4jContainer = new Neo4jContainerExtension(dockerImage)
.withPlugins(MountableFile.forHostPath(pluginsFolder.toPath()))
.withAdminPassword("apoc")
.withEnv("NEO4J_dbms_memory_heap_max__size", "512M")
.withEnv("NEO4J_dbms_memory_pagecache_size", "256M")
.withEnv("apoc.export.file.enabled", "true")
.withNeo4jConfig("dbms.security.procedures.unrestricted", "apoc.*")
.withFileSystemBind(canonicalPath, "/var/lib/neo4j/import") // map the "target/import" dir as the Neo4j's import dir
.withEnv("NEO4J_ACCEPT_LICENSE_AGREEMENT", "yes")
// .withDebugger() // uncomment this line for remote debbuging inside docker's neo4j instance
.withCreateContainerCmdModifier(cmd -> cmd.withMemory(1024 * 1024 * 1024l))
// set uid if possible - export tests do write to "/import"
.withCreateContainerCmdModifier(cmd -> {
try {
Process p = Runtime.getRuntime().exec("id -u");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s = br.readLine();
p.waitFor();
p.destroy();
cmd.withUser(s);
} catch (Exception e) {
System.out.println("Exception while assign cmd user to docker container:\n" + ExceptionUtils.getStackTrace(e));
// ignore since it may fail depending on operating system
}
});
if (withLogging) {
neo4jContainer.withLogging();
}
return neo4jContainer;
}
public static void executeGradleTasks(File baseDir, String... tasks) {
try (ProjectConnection connection = GradleConnector.newConnector()
.forProjectDirectory(baseDir)
.useBuildDistribution()
.connect()) {
// String version = connection.getModel(ProjectPublications.class).getPublications().getAt(0).getId().getVersion();
BuildLauncher buildLauncher = connection.newBuild().forTasks(tasks);
String neo4jVersionOverride = System.getenv("NEO4JVERSION");
System.out.println("neo4jVersionOverride = " + neo4jVersionOverride);
if (neo4jVersionOverride != null) {
buildLauncher = buildLauncher.addArguments("-P", "neo4jVersionOverride=" + neo4jVersionOverride);
}
String localMaven = System.getenv("LOCAL_MAVEN");
System.out.println("localMaven = " + localMaven);
if (localMaven != null) {
buildLauncher = buildLauncher.addArguments("-D", "maven.repo.local=" + localMaven);
}
buildLauncher.run();
}
}
public static void executeGradleTasks(String... tasks) {
executeGradleTasks(baseDir, tasks);
}
public static void testCall(Session session, String call, Map<String,Object> params, Consumer<Map<String, Object>> consumer) {
testResult(session, call, params, (res) -> {
try {
assertNotNull("result should be not null", res);
assertTrue("result should be not empty", res.hasNext());
Map<String, Object> row = res.next();
consumer.accept(row);
assertFalse("result should not have next", res.hasNext());
} catch(Throwable t) {
printFullStackTrace(t);
throw t;
}
});
}
public static void testCall(Session session, String call, Consumer<Map<String, Object>> consumer) {
testCall(session, call, null, consumer);
}
public static void testResult(Session session, String call, Consumer<Iterator<Map<String, Object>>> resultConsumer) {
testResult(session, call, null, resultConsumer);
}
public static void testResult(Session session, String call, Map<String,Object> params, Consumer<Iterator<Map<String, Object>>> resultConsumer) {
session.writeTransaction(tx -> {
Map<String, Object> p = (params == null) ? Collections.<String, Object>emptyMap() : params;
resultConsumer.accept(tx.run(call, p).list().stream().map(Record::asMap).collect(Collectors.toList()).iterator());
tx.commit();
return null;
});
}
public static void testCallInReadTransaction(Session session, String call, Consumer<Map<String, Object>> consumer) {
testCallInReadTransaction(session, call, null, consumer);
}
public static void testCallInReadTransaction(Session session, String call, Map<String,Object> params, Consumer<Map<String, Object>> consumer) {
testResultInReadTransaction(session, call, params, (res) -> {
try {
assertNotNull("result should be not null", res);
assertTrue("result should be not empty", res.hasNext());
Map<String, Object> row = res.next();
consumer.accept(row);
assertFalse("result should not have next", res.hasNext());
} catch(Throwable t) {
printFullStackTrace(t);
throw t;
}
});
}
public static void testResultInReadTransaction(Session session, String call, Consumer<Iterator<Map<String, Object>>> resultConsumer) {
testResultInReadTransaction(session, call, null, resultConsumer);
}
public static void testResultInReadTransaction(Session session, String call, Map<String,Object> params, Consumer<Iterator<Map<String, Object>>> resultConsumer) {
session.readTransaction(tx -> {
Map<String, Object> p = (params == null) ? Collections.<String, Object>emptyMap() : params;
resultConsumer.accept(tx.run(call, p).list().stream().map(Record::asMap).collect(Collectors.toList()).iterator());
tx.commit();
return null;
});
}
public static <T> T singleResultFirstColumn(Session session, String cypher, Map<String,Object> params) {
return (T) session.writeTransaction(tx -> tx.run(cypher, params).single().fields().get(0).value().asObject());
}
public static <T> T singleResultFirstColumn(Session session, String cypher) {
return singleResultFirstColumn(session, cypher, Map.of());
}
public static boolean isDockerImageAvailable(Exception ex) {
final Throwable cause = ex.getCause();
final Throwable rootCause = ExceptionUtils.getRootCause(ex);
return !(cause instanceof ContainerFetchException && rootCause instanceof NotFoundException);
}
}
| Attempt to fix TeamCity build
- Increase memory for the container
(cherry picked from commit 1c70a9aaaa8b7886db8766f65cb13f91f96260f5)
| test-utils/src/main/java/apoc/util/TestContainerUtil.java | Attempt to fix TeamCity build |
|
Java | apache-2.0 | 520e87d6ea476efa5971b1f6cbbe612fda6cc81c | 0 | joansmith/pdfbox,mathieufortin01/pdfbox,mdamt/pdfbox,joansmith/pdfbox,mdamt/pdfbox,torakiki/sambox,BezrukovM/veraPDF-pdfbox,gavanx/pdflearn,benmccann/pdfbox,BezrukovM/veraPDF-pdfbox,ChunghwaTelecom/pdfbox,mathieufortin01/pdfbox,ZhenyaM/veraPDF-pdfbox,veraPDF/veraPDF-pdfbox,benmccann/pdfbox,torakiki/sambox,gavanx/pdflearn,ChunghwaTelecom/pdfbox,veraPDF/veraPDF-pdfbox,ZhenyaM/veraPDF-pdfbox | /*****************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
package org.apache.pdfbox.preflight.xobject;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_GRAPHIC_TRANSPARENCY_SMASK;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_GRAPHIC_UNEXPECTED_KEY;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_GRAPHIC_UNEXPECTED_VALUE_FOR_KEY;
import static org.apache.pdfbox.preflight.PreflightConstants.TRANSPARENCY_DICTIONARY_VALUE_SOFT_MASK_NONE;
import static org.apache.pdfbox.preflight.PreflightConstants.XOBJECT_DICTIONARY_VALUE_SUBTYPE_POSTSCRIPT;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.preflight.PreflightContext;
import org.apache.pdfbox.preflight.ValidationResult.ValidationError;
import org.apache.pdfbox.preflight.exception.ValidationException;
import org.apache.pdfbox.preflight.utils.COSUtils;
/**
* This class processes commons validations of XObjects.
*/
public abstract class AbstractXObjValidator implements XObjectValidator
{
/**
* The XObject to validate as a COSStream.
*/
protected COSStream xobject = null;
/**
* The validation context which contains useful information to process validation.
*/
protected PreflightContext context = null;
/**
* The PDF document as COSDocument.
*/
protected COSDocument cosDocument = null;
public AbstractXObjValidator(PreflightContext context, COSStream xobj)
{
this.xobject = xobj;
this.context = context;
this.cosDocument = context.getDocument().getDocument();
}
/**
* This method checks the SMask entry in the XObject dictionary. According to the PDF Reference, a SMask in a
* XObject is a Stream. So if it is not null, it should be an error but a SMask with the name None is authorized in
* the PDF/A Specification 6.4. If the validation fails (SMask not null and different from None), the error list is
* updated with the error code ERROR_GRAPHIC_TRANSPARENCY_SMASK (2.2.2).
*
*/
protected void checkSMask()
{
COSBase smask = xobject.getItem(COSName.SMASK);
if (smask != null
&& !(COSUtils.isString(smask, cosDocument) && TRANSPARENCY_DICTIONARY_VALUE_SOFT_MASK_NONE
.equals(COSUtils.getAsString(smask, cosDocument))))
{
context.addValidationError(new ValidationError(ERROR_GRAPHIC_TRANSPARENCY_SMASK,
"Soft Mask must be null or None ["+xobject.toString()+"]"));
}
}
/**
* According the ISO 190005:1-2005 specification, a XObject can't have an OPI entry in its dictionary. If the
* XObject has a OPI entry, the error list is updated with the error code ERROR_GRAPHIC_UNEXPECTED_KEY (2.3).
*
*/
protected void checkOPI()
{
// 6.2.4 and 6.2.5 no OPI
if (this.xobject.getItem(COSName.getPDFName("OPI")) != null)
{
context.addValidationError(new ValidationError(ERROR_GRAPHIC_UNEXPECTED_KEY, "Unexpected 'OPI' Key"));
}
}
/**
* According the ISO 190005:1-2005 specification, a XObject can't have an Ref entry in its dictionary. If the
* XObject has a Ref entry, the error list is updated with the error code ERROR_GRAPHIC_UNEXPECTED_KEY (2.3).
*
*/
protected void checkReferenceXObject()
{
// 6.2.6 No reference XObject
if (this.xobject.getItem("Ref") != null)
{
context.addValidationError(new ValidationError(ERROR_GRAPHIC_UNEXPECTED_KEY,
"No reference XObject allowed in PDF/A"));
}
}
/**
* According the ISO 190005:1-2005 specification, PostScript XObjects are forbidden. If the XObject is a PostScript
* XObject, the error list is updated with the error code ERROR_GRAPHIC_UNEXPECTED_VALUE_FOR_KEY (2.3.2).
*
* To know whether the object is a Postscript XObject, "Subtype" and "Subtype2" entries are checked.
*/
protected void checkPostscriptXObject()
{
// 6.2.7 No PostScript XObjects
String subtype = this.xobject.getNameAsString(COSName.SUBTYPE);
if (XOBJECT_DICTIONARY_VALUE_SUBTYPE_POSTSCRIPT.equals(subtype))
{
context.addValidationError(new ValidationError(ERROR_GRAPHIC_UNEXPECTED_VALUE_FOR_KEY,
"No Postscript XObject allowed in PDF/A"));
return;
}
if (this.xobject.getItem(COSName.getPDFName("Subtype2")) != null)
{
context.addValidationError(new ValidationError(ERROR_GRAPHIC_UNEXPECTED_VALUE_FOR_KEY,
"No Postscript XObject allowed in PDF/A (Subtype2)"));
return;
}
}
/**
* This method checks if required fields are present.
*
*/
protected abstract void checkMandatoryFields();
/*
* (non-Javadoc)
*
* @see net.awl.edoc.pdfa.validation.graphics.XObjectValidator#validate()
*/
@Override
public void validate() throws ValidationException
{
checkMandatoryFields();
checkOPI();
checkSMask();
checkReferenceXObject();
checkPostscriptXObject();
}
}
| preflight/src/main/java/org/apache/pdfbox/preflight/xobject/AbstractXObjValidator.java | /*****************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
package org.apache.pdfbox.preflight.xobject;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_GRAPHIC_TRANSPARENCY_SMASK;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_GRAPHIC_UNEXPECTED_KEY;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_GRAPHIC_UNEXPECTED_VALUE_FOR_KEY;
import static org.apache.pdfbox.preflight.PreflightConstants.TRANSPARENCY_DICTIONARY_VALUE_SOFT_MASK_NONE;
import static org.apache.pdfbox.preflight.PreflightConstants.XOBJECT_DICTIONARY_VALUE_SUBTYPE_POSTSCRIPT;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.preflight.PreflightContext;
import org.apache.pdfbox.preflight.ValidationResult.ValidationError;
import org.apache.pdfbox.preflight.exception.ValidationException;
import org.apache.pdfbox.preflight.utils.COSUtils;
/**
* This class processes commons validations of XObjects.
*/
public abstract class AbstractXObjValidator implements XObjectValidator
{
/**
* The XObject to validate as a COSStream.
*/
protected COSStream xobject = null;
/**
* The validation context which contains useful information to process validation.
*/
protected PreflightContext context = null;
/**
* The PDF document as COSDocument.
*/
protected COSDocument cosDocument = null;
public AbstractXObjValidator(PreflightContext context, COSStream xobj)
{
this.xobject = xobj;
this.context = context;
this.cosDocument = context.getDocument().getDocument();
}
/**
* This method checks the SMask entry in the XObject dictionary. According to the PDF Reference, a SMask in a
* XObject is a Stream. So if it is not null, it should be an error but a SMask with the name None is authorized in
* the PDF/A Specification 6.4. If the validation fails (SMask not null and different from None), the error list is
* updated with the error code ERROR_GRAPHIC_TRANSPARENCY_SMASK (2.2.2).
*
*/
protected void checkSMask()
{
COSBase smask = xobject.getItem(COSName.SMASK);
if (smask != null
&& !(COSUtils.isString(smask, cosDocument) && TRANSPARENCY_DICTIONARY_VALUE_SOFT_MASK_NONE
.equals(COSUtils.getAsString(smask, cosDocument))))
{
context.addValidationError(new ValidationError(ERROR_GRAPHIC_TRANSPARENCY_SMASK,
"Soft Mask must be null or None ["+xobject.toString()+"]"));
}
}
/**
* According the ISO 190005:1-2005 specification, a XObject can't have an OPI entry in its dictionary. If the
* XObject has a OPI entry, the error list is updated with the error code ERROR_GRAPHIC_UNEXPECTED_KEY (2.3).
*
*/
protected void checkOPI()
{
// 6.2.4 and 6.2.5 no OPI
if (this.xobject.getItem(COSName.getPDFName("OPI")) != null)
{
context.addValidationError(new ValidationError(ERROR_GRAPHIC_UNEXPECTED_KEY, "Unexpected 'OPI' Key"));
}
}
/**
* According the ISO 190005:1-2005 specification, a XObject can't have an Ref entry in its dictionary. If the
* XObject has a Ref entry, the error list is updated with the error code ERROR_GRAPHIC_UNEXPECTED_KEY (2.3).
*
*/
protected void checkReferenceXObject()
{
// 6.2.6 No reference xobject
if (this.xobject.getItem("Ref") != null)
{
context.addValidationError(new ValidationError(ERROR_GRAPHIC_UNEXPECTED_KEY,
"No reference Xobject allowed in PDF/A"));
}
}
/**
* According the ISO 190005:1-2005 specification, PostSCript XObject are forbidden. If the XObject is a PostScript
* XObject, the error list is updated with the error code ERROR_GRAPHIC_UNEXPECTED_VALUE_FOR_KEY (2.3.2).
*
* To know the if the object a Postscript XObject, "Subtype" and "Subtype2" entries are checked.
*/
protected void checkPostscriptXObject()
{
// 6.2.7 No PostScript XObjects
String subtype = this.xobject.getNameAsString(COSName.SUBTYPE);
if (subtype != null && XOBJECT_DICTIONARY_VALUE_SUBTYPE_POSTSCRIPT.equals(subtype))
{
context.addValidationError(new ValidationError(ERROR_GRAPHIC_UNEXPECTED_VALUE_FOR_KEY,
"No Postscript Xobject allowed in PDF/A"));
return;
}
if (this.xobject.getItem(COSName.getPDFName("Subtype2")) != null)
{
context.addValidationError(new ValidationError(ERROR_GRAPHIC_UNEXPECTED_VALUE_FOR_KEY,
"No Postscript Xobject allowed in PDF/A (Subtype2)"));
return;
}
}
/**
* This method checks if required fields are present.
*
*/
protected abstract void checkMandatoryFields();
/*
* (non-Javadoc)
*
* @see net.awl.edoc.pdfa.validation.graphics.XObjectValidator#validate()
*/
public void validate() throws ValidationException
{
checkMandatoryFields();
checkOPI();
checkSMask();
checkReferenceXObject();
checkPostscriptXObject();
}
}
| PDFBOX-2576: remove unneeded null check
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1647683 13f79535-47bb-0310-9956-ffa450edef68
| preflight/src/main/java/org/apache/pdfbox/preflight/xobject/AbstractXObjValidator.java | PDFBOX-2576: remove unneeded null check |
|
Java | apache-2.0 | 379cc9e8950e145ec4a0bc3758088cad25169801 | 0 | medvector/educational-plugin,medvector/educational-plugin,medvector/educational-plugin,medvector/educational-plugin,medvector/educational-plugin | package com.jetbrains.edu.coursecreator;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.EditorTestUtil;
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase;
import com.jetbrains.edu.learning.StudyTaskManager;
import com.jetbrains.edu.learning.StudyUtils;
import com.jetbrains.edu.learning.courseFormat.*;
import com.jetbrains.edu.learning.courseFormat.tasks.Task;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.ComparisonFailure;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class CCTestCase extends CodeInsightFixtureTestCase {
private static final Logger LOG = Logger.getInstance(CCTestCase.class);
@Nullable
public static RangeHighlighter getHighlighter(MarkupModel model, AnswerPlaceholder placeholder) {
for (RangeHighlighter highlighter : model.getAllHighlighters()) {
int endOffset = placeholder.getOffset() + placeholder.getRealLength();
if (highlighter.getStartOffset() == placeholder.getOffset() && highlighter.getEndOffset() == endOffset) {
return highlighter;
}
}
return null;
}
protected static void checkHighlighters(TaskFile taskFile, MarkupModel markupModel) {
for (AnswerPlaceholder answerPlaceholder : taskFile.getActivePlaceholders()) {
if (getHighlighter(markupModel, answerPlaceholder) == null) {
throw new AssertionError("No highlighter for placeholder: " + CCTestsUtil.getPlaceholderPresentation(answerPlaceholder));
}
}
}
public void checkByFile(TaskFile taskFile, String fileName, boolean useLength) {
Pair<Document, List<AnswerPlaceholder>> placeholders = getPlaceholders(fileName, useLength, true);
String message = "Placeholders don't match";
if (taskFile.getActivePlaceholders().size() != placeholders.second.size()) {
throw new ComparisonFailure(message,
CCTestsUtil.getPlaceholdersPresentation(taskFile.getActivePlaceholders()),
CCTestsUtil.getPlaceholdersPresentation(placeholders.second));
}
for (AnswerPlaceholder answerPlaceholder : placeholders.getSecond()) {
AnswerPlaceholder placeholder = taskFile.getAnswerPlaceholder(answerPlaceholder.getOffset());
if (!CCTestsUtil.comparePlaceholders(placeholder, answerPlaceholder)) {
throw new ComparisonFailure(message,
CCTestsUtil.getPlaceholdersPresentation(taskFile.getActivePlaceholders()),
CCTestsUtil.getPlaceholdersPresentation(placeholders.second));
}
}
}
@Override
protected String getBasePath() {
return "/community/python/educational-core/testData";
}
@Override
protected void setUp() throws Exception {
super.setUp();
Course course = new Course();
course.setName("test course");
StudyTaskManager.getInstance(getProject()).setCourse(course);
Lesson lesson = new Lesson();
lesson.setName("lesson1");
Task task = new Task();
task.setName("task1");
task.setIndex(1);
lesson.addTask(task);
lesson.setIndex(1);
course.addLesson(lesson);
course.setCourseMode(CCUtils.COURSE_MODE);
course.initCourse(false);
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
try {
VirtualFile lesson1 = myFixture.getProject().getBaseDir().createChildDirectory(this, "lesson1");
lesson1.createChildDirectory(this, "task1");
}
catch (IOException e) {
//ignore
}
}
});
}
protected VirtualFile copyFileToTask(String name) {
return myFixture.copyFileToProject(name, FileUtil.join(getProject().getBasePath(), "lesson1", "task1", name));
}
protected VirtualFile configureByTaskFile(String name) {
Task task = StudyTaskManager.getInstance(getProject()).getCourse().getLessons().get(0).getTaskList().get(0);
TaskFile taskFile = new TaskFile();
taskFile.setTask(task);
task.getTaskFiles().put(name, taskFile);
VirtualFile file = copyFileToTask(name);
taskFile.name = name;
myFixture.configureFromExistingVirtualFile(file);
Document document = FileDocumentManager.getInstance().getDocument(file);
for (AnswerPlaceholder placeholder : getPlaceholders(document, false)) {
taskFile.addAnswerPlaceholder(placeholder);
}
taskFile.sortAnswerPlaceholders();
StudyUtils.drawAllAnswerPlaceholders(myFixture.getEditor(), taskFile);
return file;
}
private static List<AnswerPlaceholder> getPlaceholders(Document document, boolean useLength) {
final List<AnswerPlaceholder> placeholders = new ArrayList<>();
new WriteCommandAction(null) {
@Override
protected void run(@NotNull Result result) {
final String openingTagRx = "<placeholder( taskText=\"(.+?)\")?( possibleAnswer=\"(.+?)\")?( hint=\"(.+?)\")?>";
final String closingTagRx = "</placeholder>";
CharSequence text = document.getCharsSequence();
final Matcher openingMatcher = Pattern.compile(openingTagRx).matcher(text);
final Matcher closingMatcher = Pattern.compile(closingTagRx).matcher(text);
int pos = 0;
while (openingMatcher.find(pos)) {
AnswerPlaceholder answerPlaceholder = new AnswerPlaceholder();
AnswerPlaceholderSubtaskInfo subtaskInfo = new AnswerPlaceholderSubtaskInfo();
answerPlaceholder.getSubtaskInfos().put(0, subtaskInfo);
answerPlaceholder.setUseLength(useLength);
String taskText = openingMatcher.group(2);
if (taskText != null) {
answerPlaceholder.setTaskText(taskText);
answerPlaceholder.setLength(taskText.length());
}
String possibleAnswer = openingMatcher.group(4);
if (possibleAnswer != null) {
answerPlaceholder.setPossibleAnswer(possibleAnswer);
}
String hint = openingMatcher.group(6);
if (hint != null) {
answerPlaceholder.setHints(Collections.singletonList(hint));
}
answerPlaceholder.setOffset(openingMatcher.start());
if (!closingMatcher.find(openingMatcher.end())) {
LOG.error("No matching closing tag found");
}
if (useLength) {
answerPlaceholder.setLength(closingMatcher.start() - openingMatcher.end());
} else {
if (possibleAnswer == null) {
answerPlaceholder.setPossibleAnswer(document.getText(TextRange.create(openingMatcher.end(), closingMatcher.start())));
}
}
document.deleteString(closingMatcher.start(), closingMatcher.end());
document.deleteString(openingMatcher.start(), openingMatcher.end());
FileDocumentManager.getInstance().saveDocument(document);
placeholders.add(answerPlaceholder);
pos = answerPlaceholder.getOffset() + answerPlaceholder.getRealLength();
}
}
}.execute();
return placeholders;
}
public Pair<Document, List<AnswerPlaceholder>> getPlaceholders(String name) {
return getPlaceholders(name, true, false);
}
public Pair<Document, List<AnswerPlaceholder>> getPlaceholders(String name, boolean useLength, boolean removeMarkers) {
VirtualFile resultFile = LocalFileSystem.getInstance().findFileByPath(getTestDataPath() + "/" + name);
Document document = FileDocumentManager.getInstance().getDocument(resultFile);
Document tempDocument = EditorFactory.getInstance().createDocument(document.getCharsSequence());
if (removeMarkers) {
EditorTestUtil.extractCaretAndSelectionMarkers(tempDocument);
}
List<AnswerPlaceholder> placeholders = getPlaceholders(tempDocument, useLength);
return Pair.create(tempDocument, placeholders);
}
}
| educational-core/testSrc/com/jetbrains/edu/coursecreator/CCTestCase.java | package com.jetbrains.edu.coursecreator;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.markup.MarkupModel;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.testFramework.EditorTestUtil;
import com.intellij.testFramework.fixtures.CodeInsightFixtureTestCase;
import com.jetbrains.edu.learning.StudyTaskManager;
import com.jetbrains.edu.learning.StudyUtils;
import com.jetbrains.edu.learning.courseFormat.*;
import com.jetbrains.edu.learning.courseFormat.tasks.Task;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.ComparisonFailure;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class CCTestCase extends CodeInsightFixtureTestCase {
private static final Logger LOG = Logger.getInstance(CCTestCase.class);
@Nullable
public static RangeHighlighter getHighlighter(MarkupModel model, AnswerPlaceholder placeholder) {
for (RangeHighlighter highlighter : model.getAllHighlighters()) {
int endOffset = placeholder.getOffset() + placeholder.getRealLength();
if (highlighter.getStartOffset() == placeholder.getOffset() && highlighter.getEndOffset() == endOffset) {
return highlighter;
}
}
return null;
}
protected static void checkHighlighters(TaskFile taskFile, MarkupModel markupModel) {
for (AnswerPlaceholder answerPlaceholder : taskFile.getActivePlaceholders()) {
if (getHighlighter(markupModel, answerPlaceholder) == null) {
throw new AssertionError("No highlighter for placeholder: " + CCTestsUtil.getPlaceholderPresentation(answerPlaceholder));
}
}
}
public void checkByFile(TaskFile taskFile, String fileName, boolean useLength) {
Pair<Document, List<AnswerPlaceholder>> placeholders = getPlaceholders(fileName, useLength, true);
String message = "Placeholders don't match";
if (taskFile.getActivePlaceholders().size() != placeholders.second.size()) {
throw new ComparisonFailure(message,
CCTestsUtil.getPlaceholdersPresentation(taskFile.getActivePlaceholders()),
CCTestsUtil.getPlaceholdersPresentation(placeholders.second));
}
for (AnswerPlaceholder answerPlaceholder : placeholders.getSecond()) {
AnswerPlaceholder placeholder = taskFile.getAnswerPlaceholder(answerPlaceholder.getOffset());
if (!CCTestsUtil.comparePlaceholders(placeholder, answerPlaceholder)) {
throw new ComparisonFailure(message,
CCTestsUtil.getPlaceholdersPresentation(taskFile.getActivePlaceholders()),
CCTestsUtil.getPlaceholdersPresentation(placeholders.second));
}
}
}
@Override
protected String getBasePath() {
return "/community/python/educational-core/testData";
}
@Override
protected void setUp() throws Exception {
super.setUp();
Course course = new Course();
course.setName("test course");
StudyTaskManager.getInstance(getProject()).setCourse(course);
Lesson lesson = new Lesson();
lesson.setName("lesson1");
Task task = new Task();
task.setName("task1");
task.setIndex(1);
lesson.addTask(task);
lesson.setIndex(1);
course.addLesson(lesson);
course.setCourseMode(CCUtils.COURSE_MODE);
course.initCourse(false);
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
try {
VirtualFile lesson1 = myFixture.getProject().getBaseDir().createChildDirectory(this, "lesson1");
lesson1.createChildDirectory(this, "task1");
}
catch (IOException e) {
//ignore
}
}
});
}
protected VirtualFile copyFileToTask(String name) {
return myFixture.copyFileToProject(name, FileUtil.join(getProject().getBasePath(), "lesson1", "task1", name));
}
protected VirtualFile configureByTaskFile(String name) {
Task task = StudyTaskManager.getInstance(getProject()).getCourse().getLessons().get(0).getTaskList().get(0);
TaskFile taskFile = new TaskFile();
taskFile.setTask(task);
task.getTaskFiles().put(name, taskFile);
VirtualFile file = copyFileToTask(name);
taskFile.name = name;
myFixture.configureFromExistingVirtualFile(file);
Document document = FileDocumentManager.getInstance().getDocument(file);
for (AnswerPlaceholder placeholder : getPlaceholders(document, false)) {
taskFile.addAnswerPlaceholder(placeholder);
}
taskFile.sortAnswerPlaceholders();
StudyUtils.drawAllAnswerPlaceholders(myFixture.getEditor(), taskFile);
return file;
}
private static List<AnswerPlaceholder> getPlaceholders(Document document, boolean useLength) {
final List<AnswerPlaceholder> placeholders = new ArrayList<>();
new WriteCommandAction(null) {
@Override
protected void run(@NotNull Result result) {
final String openingTagRx = "<placeholder( taskText=\"(.+?)\")?( possibleAnswer=\"(.+?)\")?( hint=\"(.+?)\")?>";
final String closingTagRx = "</placeholder>";
CharSequence text = document.getCharsSequence();
final Matcher openingMatcher = Pattern.compile(openingTagRx).matcher(text);
final Matcher closingMatcher = Pattern.compile(closingTagRx).matcher(text);
int pos = 0;
while (openingMatcher.find(pos)) {
AnswerPlaceholder answerPlaceholder = new AnswerPlaceholder();
AnswerPlaceholderSubtaskInfo subtaskInfo = new AnswerPlaceholderSubtaskInfo();
answerPlaceholder.getSubtaskInfos().put(0, subtaskInfo);
answerPlaceholder.setUseLength(useLength);
String taskText = openingMatcher.group(2);
if (taskText != null) {
answerPlaceholder.setTaskText(taskText);
answerPlaceholder.setLength(taskText.length());
}
String possibleAnswer = openingMatcher.group(4);
if (possibleAnswer != null) {
answerPlaceholder.setPossibleAnswer(possibleAnswer);
}
String hint = openingMatcher.group(6);
if (hint != null) {
answerPlaceholder.setHints(Collections.singletonList(hint));
}
answerPlaceholder.setOffset(openingMatcher.start());
if (!closingMatcher.find(openingMatcher.end())) {
LOG.error("No matching closing tag found");
}
if (useLength) {
answerPlaceholder.setLength(closingMatcher.start() - openingMatcher.end());
} else {
if (possibleAnswer == null) {
answerPlaceholder.setPossibleAnswer(document.getText(TextRange.create(openingMatcher.end(), closingMatcher.start())));
}
}
document.deleteString(closingMatcher.start(), closingMatcher.end());
document.deleteString(openingMatcher.start(), openingMatcher.end());
placeholders.add(answerPlaceholder);
pos = answerPlaceholder.getOffset() + answerPlaceholder.getRealLength();
}
}
}.execute();
return placeholders;
}
public Pair<Document, List<AnswerPlaceholder>> getPlaceholders(String name) {
return getPlaceholders(name, true, false);
}
public Pair<Document, List<AnswerPlaceholder>> getPlaceholders(String name, boolean useLength, boolean removeMarkers) {
VirtualFile resultFile = LocalFileSystem.getInstance().findFileByPath(getTestDataPath() + "/" + name);
Document document = FileDocumentManager.getInstance().getDocument(resultFile);
Document tempDocument = EditorFactory.getInstance().createDocument(document.getCharsSequence());
if (removeMarkers) {
EditorTestUtil.extractCaretAndSelectionMarkers(tempDocument);
}
List<AnswerPlaceholder> placeholders = getPlaceholders(tempDocument, useLength);
return Pair.create(tempDocument, placeholders);
}
}
| fixed tests
| educational-core/testSrc/com/jetbrains/edu/coursecreator/CCTestCase.java | fixed tests |
|
Java | apache-2.0 | 69741ea6e34adba810b1878e0eabf3045395152d | 0 | westlinkin/AndroidLocalizationer | /*
* Copyright 2014 Wesley Lin
*
* 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 data.task;
import action.ConvertToOtherLanguages;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import data.Log;
import data.SerializeUtil;
import data.StorageDataKey;
import language_engine.TranslationEngineType;
import language_engine.bing.BingTranslationApi;
import module.AndroidString;
import module.FilterRule;
import module.SupportedLanguages;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Wesley Lin on 12/1/14.
*/
public class GetTranslationTask extends Task.Backgroundable{
private List<SupportedLanguages> selectedLanguages;
private final List<AndroidString> androidStrings;
private double indicatorFractionFrame;
private TranslationEngineType translationEngineType;
private boolean override;
private VirtualFile clickedFile;
private static final String BingIdInvalid = "Invalid client id or client secret, " +
"please check them <html><a href=\"https://datamarket.azure.com/developer/applications\">here</a></html>";
private static final String BingQuotaExceeded = "Microsoft Translator quota exceeded, " +
"please check your data usage <html><a href=\"https://datamarket.azure.com/account/datasets\">here</a></html>";
private String errorMsg = null;
public GetTranslationTask(Project project, String title,
List<SupportedLanguages> selectedLanguages,
List<AndroidString> androidStrings,
TranslationEngineType translationEngineType,
boolean override,
VirtualFile clickedFile) {
super(project, title);
this.selectedLanguages = selectedLanguages;
this.androidStrings = androidStrings;
this.translationEngineType = translationEngineType;
this.indicatorFractionFrame = 1.0d / (double)(this.selectedLanguages.size());
this.override = override;
this.clickedFile = clickedFile;
}
@Override
public void run(ProgressIndicator indicator) {
for (int i = 0; i < selectedLanguages.size(); i++) {
SupportedLanguages language = selectedLanguages.get(i);
List<AndroidString> translationResult = getTranslationEngineResult(
filterAndroidString(androidStrings, language, override),
language,
SupportedLanguages.English,
translationEngineType
);
indicator.setFraction(indicatorFractionFrame * (double)(i));
indicator.setText("Translating to " + language.getLanguageEnglishDisplayName()
+ " (" + language.getLanguageDisplayName() + ")");
String fileName = getValueResourcePath(language);
List<AndroidString> fileContent = getTargetAndroidStrings(androidStrings, translationResult, fileName, override);
writeAndroidStringToLocal(myProject, fileName, fileContent);
}
}
@Override
public void onSuccess() {
if (errorMsg == null || errorMsg.isEmpty())
return;
ConvertToOtherLanguages.showErrorDialog(getProject(), errorMsg);
}
private String getValueResourcePath(SupportedLanguages language) {
String resPath = clickedFile.getPath().substring(0,
clickedFile.getPath().indexOf("/res/") + "/res/".length());
return resPath + "values-" + language.getAndroidStringFolderNameSuffix()
+ "/" + clickedFile.getName();
}
private List<AndroidString> getTranslationEngineResult(@NotNull List<AndroidString> needToTranslatedString,
@NotNull SupportedLanguages targetLanguageCode,
@NotNull SupportedLanguages sourceLanguageCode,
TranslationEngineType translationEngineType) {
List<String> querys = AndroidString.getAndroidStringValues(needToTranslatedString);
List<String> result = null;
switch (translationEngineType) {
case Bing:
String accessToken = BingTranslationApi.getAccessToken();
if (accessToken == null) {
errorMsg = BingIdInvalid;
return null;
}
result = BingTranslationApi.getTranslatedStringArrays(accessToken, querys, sourceLanguageCode, targetLanguageCode);
if ((result == null || result.isEmpty()) && !querys.isEmpty()) {
errorMsg = BingQuotaExceeded;
return null;
}
break;
case Google:
// todo
break;
}
List<AndroidString> translatedAndroidStrings = new ArrayList<AndroidString>();
for (int i = 0; i < needToTranslatedString.size(); i++) {
translatedAndroidStrings.add(new AndroidString(
needToTranslatedString.get(i).getKey(), result.get(i)));
}
return translatedAndroidStrings;
}
private List<AndroidString> filterAndroidString(List<AndroidString> origin,
SupportedLanguages language,
boolean override) {
List<AndroidString> result = new ArrayList<AndroidString>();
VirtualFile targetStringFile = LocalFileSystem.getInstance().findFileByPath(
getValueResourcePath(language));
List<AndroidString> targetAndroidStrings = new ArrayList<AndroidString>();
if (targetStringFile != null) {
try {
targetAndroidStrings = AndroidString.getAndroidStringsList(targetStringFile.contentsToByteArray());
} catch (IOException e1) {
e1.printStackTrace();
}
}
String rulesString = PropertiesComponent.getInstance().getValue(StorageDataKey.SettingFilterRules);
List<FilterRule> filterRules = new ArrayList<FilterRule>();
if (rulesString == null) {
filterRules.add(FilterRule.DefaultFilterRule);
} else {
filterRules = SerializeUtil.deserializeFilterRuleList(rulesString);
}
// Log.i("targetAndroidString: " + targetAndroidStrings.toString());
for (AndroidString androidString : origin) {
// filter rules
if (FilterRule.inFilterRule(androidString.getKey(), filterRules))
continue;
// override
if (!override && !targetAndroidStrings.isEmpty()) {
// check if there is the androidString in this file
// if there is, filter it
if (isAndroidStringListContainsKey(targetAndroidStrings, androidString.getKey())) {
continue;
}
}
result.add(androidString);
}
return result;
}
private static List<AndroidString> getTargetAndroidStrings(List<AndroidString> sourceAndroidStrings,
List<AndroidString> translatedAndroidStrings,
String fileName,
boolean override) {
if(translatedAndroidStrings == null) {
translatedAndroidStrings = new ArrayList<AndroidString>();
}
VirtualFile existenceFile = LocalFileSystem.getInstance().findFileByPath(fileName);
List<AndroidString> existenceAndroidStrings = null;
if (existenceFile != null && !override) {
try {
existenceAndroidStrings = AndroidString.getAndroidStringsList(existenceFile.contentsToByteArray());
} catch (IOException e) {
e.printStackTrace();
}
} else {
existenceAndroidStrings = new ArrayList<AndroidString>();
}
Log.i("sourceAndroidStrings: " + sourceAndroidStrings,
"translatedAndroidStrings: " + translatedAndroidStrings,
"existenceAndroidStrings: " + existenceAndroidStrings);
List<AndroidString> targetAndroidStrings = new ArrayList<AndroidString>();
for(int i = 0; i < sourceAndroidStrings.size(); i ++) {
AndroidString string = sourceAndroidStrings.get(i);
AndroidString resultString = new AndroidString(string);
// if override is checked, skip setting the existence value, for performance issue
if (!override) {
String existenceValue = getAndroidStringValueInList(existenceAndroidStrings, resultString.getKey());
if (existenceValue != null) {
resultString.setValue(existenceValue);
}
}
String translatedValue = getAndroidStringValueInList(translatedAndroidStrings, resultString.getKey());
if (translatedValue != null) {
resultString.setValue(translatedValue);
}
targetAndroidStrings.add(resultString);
}
Log.i("targetAndroidStrings: " + targetAndroidStrings);
return targetAndroidStrings;
}
private static void writeAndroidStringToLocal(final Project myProject, String filePath, List<AndroidString> fileContent) {
File file = new File(filePath);
final VirtualFile virtualFile;
boolean fileExits = true;
try {
file.getParentFile().mkdirs();
if (!file.exists()) {
fileExits = false;
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write(getFileContent(fileContent));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fileExits) {
virtualFile = LocalFileSystem.getInstance().findFileByIoFile(file);
if (virtualFile == null)
return;
virtualFile.refresh(true, false, new Runnable() {
@Override
public void run() {
openFileInEditor(myProject, virtualFile);
}
});
} else {
virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
openFileInEditor(myProject, virtualFile);
}
}
private static void openFileInEditor(Project myProject, @Nullable final VirtualFile file) {
if (file == null)
return;
// todo: probably not the best practice here
try {
final FileEditorManager editorManager = FileEditorManager.getInstance(myProject);
editorManager.openFile(file, true);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
private static String getFileContent(List<AndroidString> fileContent) {
String xmlHeader = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
String stringResourceHeader = "<resources>\n\n";
String stringResourceTail = "</resources>\n";
StringBuilder sb = new StringBuilder();
sb.append(xmlHeader).append(stringResourceHeader);
for (AndroidString androidString : fileContent) {
sb.append("\t").append(androidString.toString()).append("\n");
}
sb.append("\n").append(stringResourceTail);
return sb.toString();
}
private static boolean isAndroidStringListContainsKey(List<AndroidString> androidStrings, String key) {
List<String> keys = AndroidString.getAndroidStringKeys(androidStrings);
return keys.contains(key);
}
public static String getAndroidStringValueInList(List<AndroidString> androidStrings, String key) {
for (AndroidString androidString : androidStrings) {
if (androidString.getKey().equals(key)) {
return androidString.getValue();
}
}
return null;
}
}
| src/data/task/GetTranslationTask.java | /*
* Copyright 2014 Wesley Lin
*
* 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 data.task;
import action.ConvertToOtherLanguages;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import data.Key;
import data.Log;
import data.SerializeUtil;
import data.StorageDataKey;
import language_engine.TranslationEngineType;
import language_engine.bing.BingTranslationApi;
import module.AndroidString;
import module.FilterRule;
import module.SupportedLanguages;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by Wesley Lin on 12/1/14.
*/
public class GetTranslationTask extends Task.Backgroundable{
private List<SupportedLanguages> selectedLanguages;
private final List<AndroidString> androidStrings;
private double indicatorFractionFrame;
private TranslationEngineType translationEngineType;
private boolean override;
private VirtualFile clickedFile;
private static final String BingIdInvalid = "Invalid client id or client secret, " +
"please check them <html><a href=\"https://datamarket.azure.com/developer/applications\">here</a></html>";
private static final String BingQuotaExceeded = "Microsoft Translator quota exceeded, " +
"please check your data usage <html><a href=\"https://datamarket.azure.com/account/datasets\">here</a></html>";
private String errorMsg = null;
public GetTranslationTask(Project project, String title,
List<SupportedLanguages> selectedLanguages,
List<AndroidString> androidStrings,
TranslationEngineType translationEngineType,
boolean override,
VirtualFile clickedFile) {
super(project, title);
this.selectedLanguages = selectedLanguages;
this.androidStrings = androidStrings;
this.translationEngineType = translationEngineType;
this.indicatorFractionFrame = 1.0d / (double)(this.selectedLanguages.size());
this.override = override;
this.clickedFile = clickedFile;
}
@Override
public void run(ProgressIndicator indicator) {
for (int i = 0; i < selectedLanguages.size(); i++) {
SupportedLanguages language = selectedLanguages.get(i);
// if no strings need to be translated, skip
if (AndroidString.getAndroidStringValues(
filterAndroidString(androidStrings, language, override)).isEmpty())
continue;
List<AndroidString> translationResult = getTranslationEngineResult(
filterAndroidString(androidStrings, language, override),
language,
SupportedLanguages.English,
translationEngineType
);
indicator.setFraction(indicatorFractionFrame * (double)(i));
indicator.setText("Translating to " + language.getLanguageEnglishDisplayName()
+ " (" + language.getLanguageDisplayName() + ")");
if (translationResult == null) {
return;
}
String fileName = getValueResourcePath(language);
List<AndroidString> fileContent = getTargetAndroidStrings(androidStrings, translationResult, fileName, override);
writeAndroidStringToLocal(myProject, fileName, fileContent);
}
}
@Override
public void onSuccess() {
if (errorMsg == null || errorMsg.isEmpty())
return;
ConvertToOtherLanguages.showErrorDialog(getProject(), errorMsg);
}
private String getValueResourcePath(SupportedLanguages language) {
String resPath = clickedFile.getPath().substring(0,
clickedFile.getPath().indexOf("/res/") + "/res/".length());
return resPath + "values-" + language.getAndroidStringFolderNameSuffix()
+ "/" + clickedFile.getName();
}
private List<AndroidString> getTranslationEngineResult(@NotNull List<AndroidString> needToTranslatedString,
@NotNull SupportedLanguages targetLanguageCode,
@NotNull SupportedLanguages sourceLanguageCode,
TranslationEngineType translationEngineType) {
List<String> querys = AndroidString.getAndroidStringValues(needToTranslatedString);
List<String> result = null;
switch (translationEngineType) {
case Bing:
String accessToken = BingTranslationApi.getAccessToken();
if (accessToken == null) {
errorMsg = BingIdInvalid;
return null;
}
result = BingTranslationApi.getTranslatedStringArrays(accessToken, querys, sourceLanguageCode, targetLanguageCode);
if (result == null || result.isEmpty()) {
errorMsg = BingQuotaExceeded;
return null;
}
break;
case Google:
// todo
break;
}
List<AndroidString> translatedAndroidStrings = new ArrayList<AndroidString>();
for (int i = 0; i < needToTranslatedString.size(); i++) {
translatedAndroidStrings.add(new AndroidString(
needToTranslatedString.get(i).getKey(), result.get(i)));
}
return translatedAndroidStrings;
}
private List<AndroidString> filterAndroidString(List<AndroidString> origin,
SupportedLanguages language,
boolean override) {
List<AndroidString> result = new ArrayList<AndroidString>();
VirtualFile targetStringFile = LocalFileSystem.getInstance().findFileByPath(
getValueResourcePath(language));
List<AndroidString> targetAndroidStrings = new ArrayList<AndroidString>();
if (targetStringFile != null) {
try {
targetAndroidStrings = AndroidString.getAndroidStringsList(targetStringFile.contentsToByteArray());
} catch (IOException e1) {
e1.printStackTrace();
}
}
String rulesString = PropertiesComponent.getInstance().getValue(StorageDataKey.SettingFilterRules);
List<FilterRule> filterRules = new ArrayList<FilterRule>();
if (rulesString == null) {
filterRules.add(FilterRule.DefaultFilterRule);
} else {
filterRules = SerializeUtil.deserializeFilterRuleList(rulesString);
}
// Log.i("targetAndroidString: " + targetAndroidStrings.toString());
for (AndroidString androidString : origin) {
// filter rules
if (FilterRule.inFilterRule(androidString.getKey(), filterRules))
continue;
// override
if (!override && !targetAndroidStrings.isEmpty()) {
// check if there is the androidString in this file
// if there is, filter it
if (isAndroidStringListContainsKey(targetAndroidStrings, androidString.getKey())) {
continue;
}
}
result.add(androidString);
}
return result;
}
private static List<AndroidString> getTargetAndroidStrings(List<AndroidString> sourceAndroidStrings,
List<AndroidString> translatedAndroidStrings,
String fileName,
boolean override) {
VirtualFile existenceFile = LocalFileSystem.getInstance().findFileByPath(fileName);
List<AndroidString> existenceAndroidStrings = null;
if (existenceFile != null && !override) {
try {
existenceAndroidStrings = AndroidString.getAndroidStringsList(existenceFile.contentsToByteArray());
} catch (IOException e) {
e.printStackTrace();
}
} else {
existenceAndroidStrings = new ArrayList<AndroidString>();
}
Log.i("sourceAndroidStrings: " + sourceAndroidStrings,
"translatedAndroidStrings: " + translatedAndroidStrings,
"existenceAndroidStrings: " + existenceAndroidStrings);
List<AndroidString> targetAndroidStrings = new ArrayList<AndroidString>();
for(int i = 0; i < sourceAndroidStrings.size(); i ++) {
AndroidString string = sourceAndroidStrings.get(i);
AndroidString resultString = new AndroidString(string);
// if override is checked, skip setting the existence value, for performance issue
if (!override) {
String existenceValue = getAndroidStringValueInList(existenceAndroidStrings, resultString.getKey());
if (existenceValue != null) {
resultString.setValue(existenceValue);
}
}
String translatedValue = getAndroidStringValueInList(translatedAndroidStrings, resultString.getKey());
if (translatedValue != null) {
resultString.setValue(translatedValue);
}
targetAndroidStrings.add(resultString);
}
Log.i("sourceAndroidStrings: " + sourceAndroidStrings);
return targetAndroidStrings;
}
private static void writeAndroidStringToLocal(final Project myProject, String filePath, List<AndroidString> fileContent) {
File file = new File(filePath);
final VirtualFile virtualFile;
boolean fileExits = true;
try {
file.getParentFile().mkdirs();
if (!file.exists()) {
fileExits = false;
file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file.getAbsoluteFile());
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write(getFileContent(fileContent));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fileExits) {
virtualFile = LocalFileSystem.getInstance().findFileByIoFile(file);
if (virtualFile == null)
return;
virtualFile.refresh(true, false, new Runnable() {
@Override
public void run() {
openFileInEditor(myProject, virtualFile);
}
});
} else {
virtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(file);
openFileInEditor(myProject, virtualFile);
}
}
private static void openFileInEditor(Project myProject, @Nullable final VirtualFile file) {
if (file == null)
return;
// todo: probably not the best practice here
try {
final FileEditorManager editorManager = FileEditorManager.getInstance(myProject);
editorManager.openFile(file, true);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
private static String getFileContent(List<AndroidString> fileContent) {
String xmlHeader = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
String stringResourceHeader = "<resources>\n\n";
String stringResourceTail = "</resources>\n";
StringBuilder sb = new StringBuilder();
sb.append(xmlHeader).append(stringResourceHeader);
for (AndroidString androidString : fileContent) {
sb.append("\t").append(androidString.toString()).append("\n");
}
sb.append("\n").append(stringResourceTail);
return sb.toString();
}
private static boolean isAndroidStringListContainsKey(List<AndroidString> androidStrings, String key) {
List<String> keys = AndroidString.getAndroidStringKeys(androidStrings);
return keys.contains(key);
}
public static String getAndroidStringValueInList(List<AndroidString> androidStrings, String key) {
for (AndroidString androidString : androidStrings) {
if (androidString.getKey().equals(key)) {
return androidString.getValue();
}
}
return null;
}
}
| delete skiping translation process for no strings need to be translated reason; fix bug: show quota exceed error dialog wrongly
| src/data/task/GetTranslationTask.java | delete skiping translation process for no strings need to be translated reason; fix bug: show quota exceed error dialog wrongly |
|
Java | apache-2.0 | c91b6765f4c829a18fc64f1c613516d87db63dba | 0 | codescale/logging-log4j2,apache/logging-log4j2,xnslong/logging-log4j2,apache/logging-log4j2,xnslong/logging-log4j2,GFriedrich/logging-log4j2,codescale/logging-log4j2,GFriedrich/logging-log4j2,xnslong/logging-log4j2,codescale/logging-log4j2,GFriedrich/logging-log4j2,apache/logging-log4j2 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.core.async;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.CoreLoggerContexts;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.DefaultConfiguration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class AsyncLoggerConfigTest {
@BeforeClass
public static void beforeClass() {
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerConfigTest.xml");
}
@Test
public void testAdditivity() throws Exception {
final File file = new File("target", "AsyncLoggerConfigTest.log");
assertTrue("Deleted old file before test", !file.exists() || file.delete());
final Logger log = LogManager.getLogger("com.foo.Bar");
final String msg = "Additive logging: 2 for the price of 1!";
log.info(msg);
CoreLoggerContexts.stopLoggerContext(file); // stop async thread
final BufferedReader reader = new BufferedReader(new FileReader(file));
final String line1 = reader.readLine();
final String line2 = reader.readLine();
reader.close();
file.delete();
assertNotNull("line1", line1);
assertNotNull("line2", line2);
assertTrue("line1 correct", line1.contains(msg));
assertTrue("line2 correct", line2.contains(msg));
final String location = "testAdditivity";
assertTrue("location", line1.contains(location) || line2.contains(location));
}
@Test
public void testIncludeLocationDefaultsToFalse() {
final LoggerConfig rootLoggerConfig =
AsyncLoggerConfig.RootLogger.createLogger(
null, "INFO", null, new AppenderRef[0], null, new DefaultConfiguration(), null);
assertFalse("Include location should default to false for async logggers",
rootLoggerConfig.isIncludeLocation());
final LoggerConfig loggerConfig =
AsyncLoggerConfig.createLogger(
null, "INFO", "com.foo.Bar", null, new AppenderRef[0], null, new DefaultConfiguration(),
null);
assertFalse("Include location should default to false for async logggers",
loggerConfig.isIncludeLocation());
}
}
| log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache license, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the license for the specific language governing permissions and
* limitations under the license.
*/
package org.apache.logging.log4j.core.async;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.CoreLoggerContexts;
import org.apache.logging.log4j.core.config.AppenderRef;
import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.DefaultConfiguration;
import org.apache.logging.log4j.core.config.LoggerConfig;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class AsyncLoggerConfigTest {
@BeforeClass
public static void beforeClass() {
System.setProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY, "AsyncLoggerConfigTest.xml");
}
@Test
public void testAdditivity() throws Exception {
final File file = new File("target", "AsyncLoggerConfigTest.log");
assertTrue("Deleted old file before test", !file.exists() || file.delete());
final Logger log = LogManager.getLogger("com.foo.Bar");
final String msg = "Additive logging: 2 for the price of 1!";
log.info(msg);
CoreLoggerContexts.stopLoggerContext(file); // stop async thread
final BufferedReader reader = new BufferedReader(new FileReader(file));
final String line1 = reader.readLine();
final String line2 = reader.readLine();
reader.close();
file.delete();
assertNotNull("line1", line1);
assertNotNull("line2", line2);
assertTrue("line1 correct", line1.contains(msg));
assertTrue("line2 correct", line2.contains(msg));
final String location = "testAdditivity";
assertTrue("location", line1.contains(location) || line2.contains(location));
}
@Test
public void testIncludeLocationDefaultsToFalse() {
final LoggerConfig rootLoggerConfig =
AsyncLoggerConfig.RootLogger.createLogger(
null, "INFO", null, new AppenderRef[0], null, new DefaultConfiguration(), null);
assertFalse("Include location should default to false for async logggers",
rootLoggerConfig.isIncludeLocation());
final LoggerConfig loggerConfig =
AsyncLoggerConfig.createLogger(
null, "INFO", "com.foo.Bar", null, new AppenderRef[0], null, new DefaultConfiguration(),
null);
assertFalse("Include location should default to false for async logggers",
loggerConfig.isIncludeLocation());
}
}
| removed trailing whitespace
| log4j-core/src/test/java/org/apache/logging/log4j/core/async/AsyncLoggerConfigTest.java | removed trailing whitespace |
|
Java | mit | 7fafe53edf39802ad65f6ea40671664cec51fe10 | 0 | auth0/jwks-rsa-java | package com.auth0.jwk;
import com.google.common.base.MoreObjects;
import com.google.common.collect.Maps;
import org.apache.commons.codec.binary.Base64;
import java.math.BigInteger;
import java.security.AlgorithmParameters;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Represents a JSON Web Key (JWK) used to verify the signature of JWTs
*/
@SuppressWarnings("WeakerAccess")
public class Jwk {
private static final String ALGORITHM_RSA = "RSA";
private static final String ALGORITHM_ELLIPTIC_CURVE = "EC";
private static final String ELLIPTIC_CURVE_TYPE_P256 = "P-256";
private static final String ELLIPTIC_CURVE_TYPE_P384 = "P-384";
private static final String ELLIPTIC_CURVE_TYPE_P521 = "P-521";
private final String id;
private final String type;
private final String algorithm;
private final String usage;
private final List<String> operations;
private final String certificateUrl;
private final List<String> certificateChain;
private final String certificateThumbprint;
private final Map<String, Object> additionalAttributes;
/**
* Creates a new Jwk
*
* @param id kid
* @param type kyt
* @param algorithm alg
* @param usage use
* @param operations key_ops
* @param certificateUrl x5u
* @param certificateChain x5c
* @param certificateThumbprint x5t
* @param additionalAttributes additional attributes not part of the standard ones
*/
@SuppressWarnings("WeakerAccess")
public Jwk(String id, String type, String algorithm, String usage, List<String> operations, String certificateUrl, List<String> certificateChain, String certificateThumbprint, Map<String, Object> additionalAttributes) {
this.id = id;
this.type = type;
this.algorithm = algorithm;
this.usage = usage;
this.operations = operations;
this.certificateUrl = certificateUrl;
this.certificateChain = certificateChain;
this.certificateThumbprint = certificateThumbprint;
this.additionalAttributes = additionalAttributes;
}
/**
* Creates a new Jwk
*
* @param id
* @param type
* @param algorithm
* @param usage
* @param operations
* @param certificateUrl
* @param certificateChain
* @param certificateThumbprint
* @param additionalAttributes
* @deprecated The specification states that the 'key_ops' (operations) parameter contains an array value.
* Use {@link #Jwk(String, String, String, String, List, String, List, String, Map)}
*/
@Deprecated
@SuppressWarnings("WeakerAccess")
public Jwk(String id, String type, String algorithm, String usage, String operations, String certificateUrl, List<String> certificateChain, String certificateThumbprint, Map<String, Object> additionalAttributes) {
this(id, type, algorithm, usage, Collections.singletonList(operations), certificateUrl, certificateChain, certificateThumbprint, additionalAttributes);
}
@SuppressWarnings("unchecked")
public static Jwk fromValues(Map<String, Object> map) {
Map<String, Object> values = Maps.newHashMap(map);
String kid = (String) values.remove("kid");
String kty = (String) values.remove("kty");
String alg = (String) values.remove("alg");
String use = (String) values.remove("use");
Object keyOps = values.remove("key_ops");
String x5u = (String) values.remove("x5u");
List<String> x5c = (List<String>) values.remove("x5c");
String x5t = (String) values.remove("x5t");
if (kty == null) {
throw new IllegalArgumentException("Attributes " + map + " are not from a valid jwk");
}
if (keyOps instanceof String) {
return new Jwk(kid, kty, alg, use, (String) keyOps, x5u, x5c, x5t, values);
} else {
return new Jwk(kid, kty, alg, use, (List<String>) keyOps, x5u, x5c, x5t, values);
}
}
@SuppressWarnings("WeakerAccess")
public String getId() {
return id;
}
@SuppressWarnings("WeakerAccess")
public String getType() {
return type;
}
@SuppressWarnings("WeakerAccess")
public String getAlgorithm() {
return algorithm;
}
@SuppressWarnings("WeakerAccess")
public String getUsage() {
return usage;
}
@SuppressWarnings("WeakerAccess")
public String getOperations() {
if (operations == null || operations.isEmpty()) {
return null;
}
StringBuilder sb = new StringBuilder();
String delimiter = ",";
for (String operation : operations) {
sb.append(operation);
sb.append(delimiter);
}
String ops = sb.toString();
return ops.substring(0, ops.length() - delimiter.length());
}
@SuppressWarnings("WeakerAccess")
public List<String> getOperationsAsList() {
return operations;
}
@SuppressWarnings("WeakerAccess")
public String getCertificateUrl() {
return certificateUrl;
}
@SuppressWarnings("WeakerAccess")
public List<String> getCertificateChain() {
return certificateChain;
}
@SuppressWarnings("WeakerAccess")
public String getCertificateThumbprint() {
return certificateThumbprint;
}
public Map<String, Object> getAdditionalAttributes() {
return additionalAttributes;
}
/**
* Returns a {@link PublicKey} if the {@code 'alg'} is {@code 'RSA'} or {@code 'EC'}
*
* @return a public key
* @throws InvalidPublicKeyException if the key cannot be built or the key type is not a supported type of RSA or EC
*/
@SuppressWarnings("WeakerAccess")
public PublicKey getPublicKey() throws InvalidPublicKeyException {
PublicKey publicKey = null;
switch (type) {
case ALGORITHM_RSA:
try {
KeyFactory kf = KeyFactory.getInstance(ALGORITHM_RSA);
BigInteger modulus = new BigInteger(1, Base64.decodeBase64(stringValue("n")));
BigInteger exponent = new BigInteger(1, Base64.decodeBase64(stringValue("e")));
publicKey = kf.generatePublic(new RSAPublicKeySpec(modulus, exponent));
} catch (InvalidKeySpecException e) {
throw new InvalidPublicKeyException("Invalid public key", e);
} catch (NoSuchAlgorithmException e) {
throw new InvalidPublicKeyException("Invalid algorithm to generate key", e);
}
break;
case ALGORITHM_ELLIPTIC_CURVE:
try {
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_ELLIPTIC_CURVE);
ECPoint ecPoint = new ECPoint(new BigInteger(Base64.decodeBase64(stringValue("x"))),
new BigInteger(Base64.decodeBase64(stringValue("y"))));
AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(ALGORITHM_ELLIPTIC_CURVE);
switch (stringValue("crv")) {
case ELLIPTIC_CURVE_TYPE_P256:
algorithmParameters.init(new ECGenParameterSpec("secp256r1"));
break;
case ELLIPTIC_CURVE_TYPE_P384:
algorithmParameters.init(new ECGenParameterSpec("secp384r1"));
break;
case ELLIPTIC_CURVE_TYPE_P521:
algorithmParameters.init(new ECGenParameterSpec("secp521r1"));
break;
default:
throw new InvalidPublicKeyException("Invalid or unsupported curve type " + stringValue("crv"));
}
ECParameterSpec ecParameterSpec = algorithmParameters.getParameterSpec(ECParameterSpec.class);
ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(ecPoint, ecParameterSpec);
publicKey = keyFactory.generatePublic(ecPublicKeySpec);
} catch (InvalidParameterSpecException e) {
throw new InvalidPublicKeyException("Invalid public key", e);
} catch (NoSuchAlgorithmException e) {
throw new InvalidPublicKeyException("Invalid algorithm to generate key", e);
} catch (InvalidKeySpecException e) {
throw new InvalidPublicKeyException("Invalid public key", e);
}
break;
default:
throw new InvalidPublicKeyException("The key type of " + type + " is not supported", null);
}
return publicKey;
}
private String stringValue(String key) {
return (String) additionalAttributes.get(key);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("kid", id)
.add("kyt", type)
.add("alg", algorithm)
.add("use", usage)
.add("extras", additionalAttributes)
.toString();
}
}
| src/main/java/com/auth0/jwk/Jwk.java | package com.auth0.jwk;
import com.google.common.base.MoreObjects;
import com.google.common.collect.Maps;
import org.apache.commons.codec.binary.Base64;
import java.math.BigInteger;
import java.security.AlgorithmParameters;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.spec.ECGenParameterSpec;
import java.security.spec.ECParameterSpec;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.RSAPublicKeySpec;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* Represents a JSON Web Key (JWK) used to verify the signature of JWTs
*/
@SuppressWarnings("WeakerAccess")
public class Jwk {
private static final String ALGORITHM_RSA = "RSA";
private static final String ALGORITHM_ELLIPTIC_CURVE = "EC";
private static final String ELLIPTIC_CURVE_TYPE_P256 = "P-256";
private static final String ELLIPTIC_CURVE_TYPE_P384 = "P-384";
private static final String ELLIPTIC_CURVE_TYPE_P521 = "P-521";
private final String id;
private final String type;
private final String algorithm;
private final String usage;
private final List<String> operations;
private final String certificateUrl;
private final List<String> certificateChain;
private final String certificateThumbprint;
private final Map<String, Object> additionalAttributes;
/**
* Creates a new Jwk
*
* @param id kid
* @param type kyt
* @param algorithm alg
* @param usage use
* @param operations key_ops
* @param certificateUrl x5u
* @param certificateChain x5c
* @param certificateThumbprint x5t
* @param additionalAttributes additional attributes not part of the standard ones
*/
@SuppressWarnings("WeakerAccess")
public Jwk(String id, String type, String algorithm, String usage, List<String> operations, String certificateUrl, List<String> certificateChain, String certificateThumbprint, Map<String, Object> additionalAttributes) {
this.id = id;
this.type = type;
this.algorithm = algorithm;
this.usage = usage;
this.operations = operations;
this.certificateUrl = certificateUrl;
this.certificateChain = certificateChain;
this.certificateThumbprint = certificateThumbprint;
this.additionalAttributes = additionalAttributes;
}
/**
* Creates a new Jwk
*
* @param id
* @param type
* @param algorithm
* @param usage
* @param operations
* @param certificateUrl
* @param certificateChain
* @param certificateThumbprint
* @param additionalAttributes
* @deprecated The specification states that the 'key_ops' (operations) parameter contains an array value.
* Use {@link #Jwk(String, String, String, String, List, String, List, String, Map)}
*/
@Deprecated
@SuppressWarnings("WeakerAccess")
public Jwk(String id, String type, String algorithm, String usage, String operations, String certificateUrl, List<String> certificateChain, String certificateThumbprint, Map<String, Object> additionalAttributes) {
this(id, type, algorithm, usage, Collections.singletonList(operations), certificateUrl, certificateChain, certificateThumbprint, additionalAttributes);
}
@SuppressWarnings("unchecked")
public static Jwk fromValues(Map<String, Object> map) {
Map<String, Object> values = Maps.newHashMap(map);
String kid = (String) values.remove("kid");
String kty = (String) values.remove("kty");
String alg = (String) values.remove("alg");
String use = (String) values.remove("use");
Object keyOps = values.remove("key_ops");
String x5u = (String) values.remove("x5u");
List<String> x5c = (List<String>) values.remove("x5c");
String x5t = (String) values.remove("x5t");
if (kty == null) {
throw new IllegalArgumentException("Attributes " + map + " are not from a valid jwk");
}
if (keyOps instanceof String) {
return new Jwk(kid, kty, alg, use, (String) keyOps, x5u, x5c, x5t, values);
} else {
return new Jwk(kid, kty, alg, use, (List<String>) keyOps, x5u, x5c, x5t, values);
}
}
@SuppressWarnings("WeakerAccess")
public String getId() {
return id;
}
@SuppressWarnings("WeakerAccess")
public String getType() {
return type;
}
@SuppressWarnings("WeakerAccess")
public String getAlgorithm() {
return algorithm;
}
@SuppressWarnings("WeakerAccess")
public String getUsage() {
return usage;
}
@SuppressWarnings("WeakerAccess")
public String getOperations() {
if (operations == null || operations.isEmpty()) {
return null;
}
StringBuilder sb = new StringBuilder();
String delimiter = ",";
for (String operation : operations) {
sb.append(operation);
sb.append(delimiter);
}
String ops = sb.toString();
return ops.substring(0, ops.length() - delimiter.length());
}
@SuppressWarnings("WeakerAccess")
public List<String> getOperationsAsList() {
return operations;
}
@SuppressWarnings("WeakerAccess")
public String getCertificateUrl() {
return certificateUrl;
}
@SuppressWarnings("WeakerAccess")
public List<String> getCertificateChain() {
return certificateChain;
}
@SuppressWarnings("WeakerAccess")
public String getCertificateThumbprint() {
return certificateThumbprint;
}
public Map<String, Object> getAdditionalAttributes() {
return additionalAttributes;
}
/**
* Returns a {@link PublicKey} if the {@code 'alg'} is {@code 'RSA'}
*
* @return a public key
* @throws InvalidPublicKeyException if the key cannot be built or the key type is not RSA
*/
@SuppressWarnings("WeakerAccess")
public PublicKey getPublicKey() throws InvalidPublicKeyException {
PublicKey publicKey = null;
switch (type) {
case ALGORITHM_RSA:
try {
KeyFactory kf = KeyFactory.getInstance(ALGORITHM_RSA);
BigInteger modulus = new BigInteger(1, Base64.decodeBase64(stringValue("n")));
BigInteger exponent = new BigInteger(1, Base64.decodeBase64(stringValue("e")));
publicKey = kf.generatePublic(new RSAPublicKeySpec(modulus, exponent));
} catch (InvalidKeySpecException e) {
throw new InvalidPublicKeyException("Invalid public key", e);
} catch (NoSuchAlgorithmException e) {
throw new InvalidPublicKeyException("Invalid algorithm to generate key", e);
}
break;
case ALGORITHM_ELLIPTIC_CURVE:
try {
KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM_ELLIPTIC_CURVE);
ECPoint ecPoint = new ECPoint(new BigInteger(Base64.decodeBase64(stringValue("x"))),
new BigInteger(Base64.decodeBase64(stringValue("y"))));
AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(ALGORITHM_ELLIPTIC_CURVE);
switch (stringValue("crv")) {
case ELLIPTIC_CURVE_TYPE_P256:
algorithmParameters.init(new ECGenParameterSpec("secp256r1"));
break;
case ELLIPTIC_CURVE_TYPE_P384:
algorithmParameters.init(new ECGenParameterSpec("secp384r1"));
break;
case ELLIPTIC_CURVE_TYPE_P521:
algorithmParameters.init(new ECGenParameterSpec("secp521r1"));
break;
default:
throw new InvalidPublicKeyException("Invalid or unsupported curve type " + stringValue("crv"));
}
ECParameterSpec ecParameterSpec = algorithmParameters.getParameterSpec(ECParameterSpec.class);
ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(ecPoint, ecParameterSpec);
publicKey = keyFactory.generatePublic(ecPublicKeySpec);
} catch (InvalidParameterSpecException e) {
throw new InvalidPublicKeyException("Invalid public key", e);
} catch (NoSuchAlgorithmException e) {
throw new InvalidPublicKeyException("Invalid algorithm to generate key", e);
} catch (InvalidKeySpecException e) {
throw new InvalidPublicKeyException("Invalid public key", e);
}
break;
default:
throw new InvalidPublicKeyException("The key type of " + type + " is not supported", null);
}
return publicKey;
}
private String stringValue(String key) {
return (String) additionalAttributes.get(key);
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("kid", id)
.add("kyt", type)
.add("alg", algorithm)
.add("use", usage)
.add("extras", additionalAttributes)
.toString();
}
}
| Update javadoc for Jwk getPublicKey method to reflect support for Elliptic Curve and RSA
| src/main/java/com/auth0/jwk/Jwk.java | Update javadoc for Jwk getPublicKey method to reflect support for Elliptic Curve and RSA |
|
Java | mit | 8a9adcf562130b46533c57d3a6961c1a715ff9a5 | 0 | savichris/spongycastle,sergeypayu/bc-java,onessimofalconi/bc-java,sonork/spongycastle,FAU-Inf2/spongycastle,sergeypayu/bc-java,savichris/spongycastle,partheinstein/bc-java,open-keychain/spongycastle,sergeypayu/bc-java,FAU-Inf2/spongycastle,iseki-masaya/spongycastle,partheinstein/bc-java,onessimofalconi/bc-java,iseki-masaya/spongycastle,isghe/bc-java,sonork/spongycastle,lesstif/spongycastle,open-keychain/spongycastle,open-keychain/spongycastle,Skywalker-11/spongycastle,bcgit/bc-java,Skywalker-11/spongycastle,lesstif/spongycastle,isghe/bc-java,bcgit/bc-java,FAU-Inf2/spongycastle,onessimofalconi/bc-java,Skywalker-11/spongycastle,lesstif/spongycastle,sonork/spongycastle,partheinstein/bc-java,isghe/bc-java,savichris/spongycastle,iseki-masaya/spongycastle,bcgit/bc-java | package org.bouncycastle.math.ec;
import java.math.BigInteger;
import java.util.Random;
import org.bouncycastle.util.BigIntegers;
/**
* base class for an elliptic curve
*/
public abstract class ECCurve
{
public static final int COORD_AFFINE = 0;
public static final int COORD_HOMOGENEOUS = 1;
public static final int COORD_JACOBIAN = 2;
public static final int COORD_JACOBIAN_CHUDNOVSKY = 3;
public static final int COORD_JACOBIAN_MODIFIED = 4;
public class Config
{
protected int coord = COORD_AFFINE;
protected ECMultiplier multiplier;
public Config setCoordinateSystem(int coord)
{
this.coord = coord;
return this;
}
public Config setMultiplier(ECMultiplier multiplier)
{
this.multiplier = multiplier;
return this;
}
public ECCurve create()
{
if (!supportsCoordinateSystem(coord))
{
throw new UnsupportedOperationException("unsupported coordinate system");
}
ECCurve c = createCurve(Config.this);
if (c == ECCurve.this)
{
throw new IllegalStateException("implementation returned current curve");
}
return c;
}
}
protected ECFieldElement a, b;
protected int coord = COORD_AFFINE;
protected ECMultiplier multiplier = null;
public abstract int getFieldSize();
public abstract ECFieldElement fromBigInteger(BigInteger x);
public Config configure()
{
return new Config();
}
public ECPoint createPoint(BigInteger x, BigInteger y)
{
return createPoint(x, y, false);
}
protected abstract ECCurve createCurve(Config builder);
protected ECMultiplier createDefaultMultiplier()
{
return new DoubleAddMultiplier();
}
public boolean supportsCoordinateSystem(int coord)
{
return coord == COORD_AFFINE;
}
/**
* @deprecated per-point compression property will be removed, use {@link #createPoint(BigInteger, BigInteger)}
* and refer {@link ECPoint#getEncoded(boolean)}
*/
public abstract ECPoint createPoint(BigInteger x, BigInteger y, boolean withCompression);
public ECPoint importPoint(ECPoint p)
{
if (this == p.getCurve())
{
return p;
}
if (p.isInfinity())
{
return getInfinity();
}
// TODO Default behaviour could be improved if the two curves have the same coordinate system by copying any Z coordinates.
p = p.normalize();
return createPoint(p.getAffineXCoord().toBigInteger(), p.getAffineYCoord().toBigInteger(), p.withCompression);
}
public abstract ECPoint getInfinity();
public ECFieldElement getA()
{
return a;
}
public ECFieldElement getB()
{
return b;
}
public int getCoordinateSystem()
{
return coord;
}
protected abstract ECPoint decompressPoint(int yTilde, BigInteger X1);
/**
* Sets the default <code>ECMultiplier</code>, unless already set.
*/
public ECMultiplier getMultiplier()
{
if (this.multiplier == null)
{
this.multiplier = createDefaultMultiplier();
}
return this.multiplier;
}
/**
* Decode a point on this curve from its ASN.1 encoding. The different
* encodings are taken account of, including point compression for
* <code>F<sub>p</sub></code> (X9.62 s 4.2.1 pg 17).
* @return The decoded point.
*/
public ECPoint decodePoint(byte[] encoded)
{
ECPoint p = null;
int expectedLength = (getFieldSize() + 7) / 8;
switch (encoded[0])
{
case 0x00: // infinity
{
if (encoded.length != 1)
{
throw new IllegalArgumentException("Incorrect length for infinity encoding");
}
p = getInfinity();
break;
}
case 0x02: // compressed
case 0x03: // compressed
{
if (encoded.length != (expectedLength + 1))
{
throw new IllegalArgumentException("Incorrect length for compressed encoding");
}
int yTilde = encoded[0] & 1;
BigInteger X = BigIntegers.fromUnsignedByteArray(encoded, 1, expectedLength);
p = decompressPoint(yTilde, X);
break;
}
case 0x04: // uncompressed
case 0x06: // hybrid
case 0x07: // hybrid
{
if (encoded.length != (2 * expectedLength + 1))
{
throw new IllegalArgumentException("Incorrect length for uncompressed/hybrid encoding");
}
BigInteger X = BigIntegers.fromUnsignedByteArray(encoded, 1, expectedLength);
BigInteger Y = BigIntegers.fromUnsignedByteArray(encoded, 1 + expectedLength, expectedLength);
p = createPoint(X, Y);
break;
}
default:
throw new IllegalArgumentException("Invalid point encoding 0x" + Integer.toString(encoded[0], 16));
}
return p;
}
/**
* Elliptic curve over Fp
*/
public static class Fp extends ECCurve
{
BigInteger q, r;
ECPoint.Fp infinity;
public Fp(BigInteger q, BigInteger a, BigInteger b)
{
this.q = q;
this.r = ECFieldElement.Fp.calculateResidue(q);
this.infinity = new ECPoint.Fp(this, null, null);
this.a = fromBigInteger(a);
this.b = fromBigInteger(b);
}
protected Fp(BigInteger q, BigInteger r, ECFieldElement a, ECFieldElement b)
{
this.q = q;
this.r = r;
this.infinity = new ECPoint.Fp(this, null, null);
this.a = a;
this.b = b;
}
public ECCurve createCurve(Config builder)
{
Fp c = new Fp(q, r, a, b);
c.coord = builder.coord;
c.multiplier = builder.multiplier;
return c;
}
public boolean supportsCoordinateSystem(int coord)
{
switch (coord)
{
case COORD_AFFINE:
case COORD_JACOBIAN:
return true;
default:
return false;
}
}
public BigInteger getQ()
{
return q;
}
public int getFieldSize()
{
return q.bitLength();
}
public ECFieldElement fromBigInteger(BigInteger x)
{
return new ECFieldElement.Fp(this.q, this.r, x);
}
public ECPoint createPoint(BigInteger x, BigInteger y, boolean withCompression)
{
return new ECPoint.Fp(this, fromBigInteger(x), fromBigInteger(y), withCompression);
}
public ECPoint importPoint(ECPoint p)
{
if (this != p.getCurve() && getCoordinateSystem() == COORD_JACOBIAN && !p.isInfinity())
{
switch (p.getCurve().getCoordinateSystem())
{
case COORD_JACOBIAN:
case COORD_JACOBIAN_CHUDNOVSKY:
case COORD_JACOBIAN_MODIFIED:
return new ECPoint.Fp(this,
fromBigInteger(p.x.toBigInteger()),
fromBigInteger(p.y.toBigInteger()),
new ECFieldElement[]{ fromBigInteger(p.zs[0].toBigInteger()) });
default:
break;
}
}
return super.importPoint(p);
}
protected ECPoint decompressPoint(int yTilde, BigInteger X1)
{
ECFieldElement x = fromBigInteger(X1);
ECFieldElement alpha = x.multiply(x.square().add(a)).add(b);
ECFieldElement beta = alpha.sqrt();
//
// if we can't find a sqrt we haven't got a point on the
// curve - run!
//
if (beta == null)
{
throw new RuntimeException("Invalid point compression");
}
BigInteger betaValue = beta.toBigInteger();
if (betaValue.testBit(0) != (yTilde == 1))
{
// Use the other root
beta = fromBigInteger(q.subtract(betaValue));
}
return new ECPoint.Fp(this, x, beta, true);
}
public ECPoint getInfinity()
{
return infinity;
}
public boolean equals(
Object anObject)
{
if (anObject == this)
{
return true;
}
if (!(anObject instanceof ECCurve.Fp))
{
return false;
}
ECCurve.Fp other = (ECCurve.Fp) anObject;
return this.q.equals(other.q)
&& a.equals(other.a) && b.equals(other.b);
}
public int hashCode()
{
return a.hashCode() ^ b.hashCode() ^ q.hashCode();
}
}
/**
* Elliptic curves over F2m. The Weierstrass equation is given by
* <code>y<sup>2</sup> + xy = x<sup>3</sup> + ax<sup>2</sup> + b</code>.
*/
public static class F2m extends ECCurve
{
/**
* The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>.
*/
private int m; // can't be final - JDK 1.1
/**
* TPB: The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction polynomial
* <code>f(z)</code>.<br>
* PPB: The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k1; // can't be final - JDK 1.1
/**
* TPB: Always set to <code>0</code><br>
* PPB: The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k2; // can't be final - JDK 1.1
/**
* TPB: Always set to <code>0</code><br>
* PPB: The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k3; // can't be final - JDK 1.1
/**
* The order of the base point of the curve.
*/
private BigInteger n; // can't be final - JDK 1.1
/**
* The cofactor of the curve.
*/
private BigInteger h; // can't be final - JDK 1.1
/**
* The point at infinity on this curve.
*/
private ECPoint.F2m infinity; // can't be final - JDK 1.1
/**
* The parameter <code>μ</code> of the elliptic curve if this is
* a Koblitz curve.
*/
private byte mu = 0;
/**
* The auxiliary values <code>s<sub>0</sub></code> and
* <code>s<sub>1</sub></code> used for partial modular reduction for
* Koblitz curves.
*/
private BigInteger[] si = null;
/**
* Constructor for Trinomial Polynomial Basis (TPB).
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction
* polynomial <code>f(z)</code>.
* @param a The coefficient <code>a</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param b The coefficient <code>b</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
*/
public F2m(
int m,
int k,
BigInteger a,
BigInteger b)
{
this(m, k, 0, 0, a, b, null, null);
}
/**
* Constructor for Trinomial Polynomial Basis (TPB).
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction
* polynomial <code>f(z)</code>.
* @param a The coefficient <code>a</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param b The coefficient <code>b</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param n The order of the main subgroup of the elliptic curve.
* @param h The cofactor of the elliptic curve, i.e.
* <code>#E<sub>a</sub>(F<sub>2<sup>m</sup></sub>) = h * n</code>.
*/
public F2m(
int m,
int k,
BigInteger a,
BigInteger b,
BigInteger n,
BigInteger h)
{
this(m, k, 0, 0, a, b, n, h);
}
/**
* Constructor for Pentanomial Polynomial Basis (PPB).
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param a The coefficient <code>a</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param b The coefficient <code>b</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
*/
public F2m(
int m,
int k1,
int k2,
int k3,
BigInteger a,
BigInteger b)
{
this(m, k1, k2, k3, a, b, null, null);
}
/**
* Constructor for Pentanomial Polynomial Basis (PPB).
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param a The coefficient <code>a</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param b The coefficient <code>b</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param n The order of the main subgroup of the elliptic curve.
* @param h The cofactor of the elliptic curve, i.e.
* <code>#E<sub>a</sub>(F<sub>2<sup>m</sup></sub>) = h * n</code>.
*/
public F2m(
int m,
int k1,
int k2,
int k3,
BigInteger a,
BigInteger b,
BigInteger n,
BigInteger h)
{
this.m = m;
this.k1 = k1;
this.k2 = k2;
this.k3 = k3;
this.n = n;
this.h = h;
if (k1 == 0)
{
throw new IllegalArgumentException("k1 must be > 0");
}
if (k2 == 0)
{
if (k3 != 0)
{
throw new IllegalArgumentException("k3 must be 0 if k2 == 0");
}
}
else
{
if (k2 <= k1)
{
throw new IllegalArgumentException("k2 must be > k1");
}
if (k3 <= k2)
{
throw new IllegalArgumentException("k3 must be > k2");
}
}
this.a = fromBigInteger(a);
this.b = fromBigInteger(b);
this.infinity = new ECPoint.F2m(this, null, null);
}
protected F2m(int m, int k1, int k2, int k3, ECFieldElement a, ECFieldElement b, BigInteger n, BigInteger h)
{
this.m = m;
this.k1 = k1;
this.k2 = k2;
this.k3 = k3;
this.n = n;
this.h = h;
this.a = a;
this.b = b;
this.infinity = new ECPoint.F2m(this, null, null);
}
public ECCurve createCurve(Config builder)
{
F2m c = new F2m(m, k1, k2, k3, a, b, n, h);
c.coord = builder.coord;
c.multiplier = builder.multiplier;
return c;
}
protected ECMultiplier createDefaultMultiplier()
{
return isKoblitz() ? new WTauNafMultiplier() : new WNafMultiplier();
}
public int getFieldSize()
{
return m;
}
public ECFieldElement fromBigInteger(BigInteger x)
{
return new ECFieldElement.F2m(this.m, this.k1, this.k2, this.k3, x);
}
public ECPoint createPoint(BigInteger x, BigInteger y, boolean withCompression)
{
return new ECPoint.F2m(this, fromBigInteger(x), fromBigInteger(y), withCompression);
}
public ECPoint getInfinity()
{
return infinity;
}
/**
* Returns true if this is a Koblitz curve (ABC curve).
* @return true if this is a Koblitz curve (ABC curve), false otherwise
*/
public boolean isKoblitz()
{
return n != null && h != null && a.bitLength() <= 1 && b.bitLength() == 1;
}
/**
* Returns the parameter <code>μ</code> of the elliptic curve.
* @return <code>μ</code> of the elliptic curve.
* @throws IllegalArgumentException if the given ECCurve is not a
* Koblitz curve.
*/
synchronized byte getMu()
{
if (mu == 0)
{
mu = Tnaf.getMu(this);
}
return mu;
}
/**
* @return the auxiliary values <code>s<sub>0</sub></code> and
* <code>s<sub>1</sub></code> used for partial modular reduction for
* Koblitz curves.
*/
synchronized BigInteger[] getSi()
{
if (si == null)
{
si = Tnaf.getSi(this);
}
return si;
}
/**
* Decompresses a compressed point P = (xp, yp) (X9.62 s 4.2.2).
*
* @param yTilde
* ~yp, an indication bit for the decompression of yp.
* @param X1
* The field element xp.
* @return the decompressed point.
*/
protected ECPoint decompressPoint(int yTilde, BigInteger X1)
{
ECFieldElement xp = fromBigInteger(X1);
ECFieldElement yp = null;
if (X1.signum() == 0)
{
yp = (ECFieldElement.F2m)b;
for (int i = 0; i < m - 1; i++)
{
yp = yp.square();
}
}
else
{
ECFieldElement beta = xp.add(a).add(b.multiply(xp.square().invert()));
ECFieldElement z = solveQuadraticEquation(beta);
if (z == null)
{
throw new IllegalArgumentException("Invalid point compression");
}
if (z.testBitZero() != (yTilde == 1))
{
z = z.add(fromBigInteger(ECConstants.ONE));
}
yp = xp.multiply(z);
}
return new ECPoint.F2m(this, xp, yp, true);
}
/**
* Solves a quadratic equation <code>z<sup>2</sup> + z = beta</code>(X9.62
* D.1.6) The other solution is <code>z + 1</code>.
*
* @param beta
* The value to solve the quadratic equation for.
* @return the solution for <code>z<sup>2</sup> + z = beta</code> or
* <code>null</code> if no solution exists.
*/
private ECFieldElement solveQuadraticEquation(ECFieldElement beta)
{
if (beta.isZero())
{
return beta;
}
ECFieldElement zeroElement = fromBigInteger(ECConstants.ZERO);
ECFieldElement z = null;
ECFieldElement gamma = null;
Random rand = new Random();
do
{
ECFieldElement t = fromBigInteger(new BigInteger(m, rand));
z = zeroElement;
ECFieldElement w = beta;
for (int i = 1; i <= m - 1; i++)
{
ECFieldElement w2 = w.square();
z = z.square().add(w2.multiply(t));
w = w2.add(beta);
}
if (!w.isZero())
{
return null;
}
gamma = z.square().add(z);
}
while (gamma.isZero());
return z;
}
public boolean equals(
Object anObject)
{
if (anObject == this)
{
return true;
}
if (!(anObject instanceof ECCurve.F2m))
{
return false;
}
ECCurve.F2m other = (ECCurve.F2m)anObject;
return (this.m == other.m) && (this.k1 == other.k1)
&& (this.k2 == other.k2) && (this.k3 == other.k3)
&& a.equals(other.a) && b.equals(other.b);
}
public int hashCode()
{
return this.a.hashCode() ^ this.b.hashCode() ^ m ^ k1 ^ k2 ^ k3;
}
public int getM()
{
return m;
}
/**
* Return true if curve uses a Trinomial basis.
*
* @return true if curve Trinomial, false otherwise.
*/
public boolean isTrinomial()
{
return k2 == 0 && k3 == 0;
}
public int getK1()
{
return k1;
}
public int getK2()
{
return k2;
}
public int getK3()
{
return k3;
}
public BigInteger getN()
{
return n;
}
public BigInteger getH()
{
return h;
}
}
}
| core/src/main/java/org/bouncycastle/math/ec/ECCurve.java | package org.bouncycastle.math.ec;
import java.math.BigInteger;
import java.util.Random;
import org.bouncycastle.util.BigIntegers;
/**
* base class for an elliptic curve
*/
public abstract class ECCurve
{
public static final int COORD_AFFINE = 0;
public static final int COORD_HOMOGENEOUS = 1;
public static final int COORD_JACOBIAN = 2;
public static final int COORD_JACOBIAN_CHUDNOVSKY = 3;
public static final int COORD_JACOBIAN_MODIFIED = 4;
public class Config
{
protected int coord = COORD_AFFINE;
protected ECMultiplier multiplier;
public Config setCoordinateSystem(int coord)
{
this.coord = coord;
return this;
}
public Config setMultiplier(ECMultiplier multiplier)
{
this.multiplier = multiplier;
return this;
}
public ECCurve create()
{
if (!supportsCoordinateSystem(coord))
{
throw new UnsupportedOperationException("unsupported coordinate system");
}
ECCurve c = createCurve(Config.this);
if (c == ECCurve.this)
{
throw new IllegalStateException("implementation returned current curve");
}
return c;
}
}
protected ECFieldElement a, b;
protected int coord = COORD_AFFINE;
protected ECMultiplier multiplier = null;
public abstract int getFieldSize();
public abstract ECFieldElement fromBigInteger(BigInteger x);
public Config configure()
{
return new Config();
}
public ECPoint createPoint(BigInteger x, BigInteger y)
{
return createPoint(x, y, false);
}
protected abstract ECCurve createCurve(Config builder);
protected ECMultiplier createDefaultMultiplier()
{
return new DoubleAddMultiplier();
}
public boolean supportsCoordinateSystem(int coord)
{
return coord == COORD_AFFINE;
}
/**
* @deprecated per-point compression property will be removed, use {@link #createPoint(BigInteger, BigInteger)}
* and refer {@link ECPoint#getEncoded(boolean)}
*/
public abstract ECPoint createPoint(BigInteger x, BigInteger y, boolean withCompression);
public ECPoint importPoint(ECPoint p)
{
if (this == p.getCurve())
{
return p;
}
// TODO Default behaviour could be improved if the two curves have the same coordinate system by copying any Z coordinates.
p = p.normalize();
return createPoint(p.getAffineXCoord().toBigInteger(), p.getAffineYCoord().toBigInteger(), p.withCompression);
}
public abstract ECPoint getInfinity();
public ECFieldElement getA()
{
return a;
}
public ECFieldElement getB()
{
return b;
}
public int getCoordinateSystem()
{
return coord;
}
protected abstract ECPoint decompressPoint(int yTilde, BigInteger X1);
/**
* Sets the default <code>ECMultiplier</code>, unless already set.
*/
public ECMultiplier getMultiplier()
{
if (this.multiplier == null)
{
this.multiplier = createDefaultMultiplier();
}
return this.multiplier;
}
/**
* Decode a point on this curve from its ASN.1 encoding. The different
* encodings are taken account of, including point compression for
* <code>F<sub>p</sub></code> (X9.62 s 4.2.1 pg 17).
* @return The decoded point.
*/
public ECPoint decodePoint(byte[] encoded)
{
ECPoint p = null;
int expectedLength = (getFieldSize() + 7) / 8;
switch (encoded[0])
{
case 0x00: // infinity
{
if (encoded.length != 1)
{
throw new IllegalArgumentException("Incorrect length for infinity encoding");
}
p = getInfinity();
break;
}
case 0x02: // compressed
case 0x03: // compressed
{
if (encoded.length != (expectedLength + 1))
{
throw new IllegalArgumentException("Incorrect length for compressed encoding");
}
int yTilde = encoded[0] & 1;
BigInteger X = BigIntegers.fromUnsignedByteArray(encoded, 1, expectedLength);
p = decompressPoint(yTilde, X);
break;
}
case 0x04: // uncompressed
case 0x06: // hybrid
case 0x07: // hybrid
{
if (encoded.length != (2 * expectedLength + 1))
{
throw new IllegalArgumentException("Incorrect length for uncompressed/hybrid encoding");
}
BigInteger X = BigIntegers.fromUnsignedByteArray(encoded, 1, expectedLength);
BigInteger Y = BigIntegers.fromUnsignedByteArray(encoded, 1 + expectedLength, expectedLength);
p = createPoint(X, Y);
break;
}
default:
throw new IllegalArgumentException("Invalid point encoding 0x" + Integer.toString(encoded[0], 16));
}
return p;
}
/**
* Elliptic curve over Fp
*/
public static class Fp extends ECCurve
{
BigInteger q, r;
ECPoint.Fp infinity;
public Fp(BigInteger q, BigInteger a, BigInteger b)
{
this.q = q;
this.r = ECFieldElement.Fp.calculateResidue(q);
this.infinity = new ECPoint.Fp(this, null, null);
this.a = fromBigInteger(a);
this.b = fromBigInteger(b);
}
protected Fp(BigInteger q, BigInteger r, ECFieldElement a, ECFieldElement b)
{
this.q = q;
this.r = r;
this.infinity = new ECPoint.Fp(this, null, null);
this.a = a;
this.b = b;
}
public ECCurve createCurve(Config builder)
{
Fp c = new Fp(q, r, a, b);
c.coord = builder.coord;
c.multiplier = builder.multiplier;
return c;
}
public boolean supportsCoordinateSystem(int coord)
{
switch (coord)
{
case COORD_AFFINE:
case COORD_JACOBIAN:
return true;
default:
return false;
}
}
public BigInteger getQ()
{
return q;
}
public int getFieldSize()
{
return q.bitLength();
}
public ECFieldElement fromBigInteger(BigInteger x)
{
return new ECFieldElement.Fp(this.q, this.r, x);
}
public ECPoint createPoint(BigInteger x, BigInteger y, boolean withCompression)
{
return new ECPoint.Fp(this, fromBigInteger(x), fromBigInteger(y), withCompression);
}
public ECPoint importPoint(ECPoint p)
{
if (this != p.getCurve() && getCoordinateSystem() == COORD_JACOBIAN)
{
switch (p.getCurve().getCoordinateSystem())
{
case COORD_JACOBIAN:
case COORD_JACOBIAN_CHUDNOVSKY:
case COORD_JACOBIAN_MODIFIED:
return new ECPoint.Fp(this,
fromBigInteger(p.x.toBigInteger()),
fromBigInteger(p.y.toBigInteger()),
new ECFieldElement[]{ fromBigInteger(p.zs[0].toBigInteger()) });
default:
break;
}
}
return super.importPoint(p);
}
protected ECPoint decompressPoint(int yTilde, BigInteger X1)
{
ECFieldElement x = fromBigInteger(X1);
ECFieldElement alpha = x.multiply(x.square().add(a)).add(b);
ECFieldElement beta = alpha.sqrt();
//
// if we can't find a sqrt we haven't got a point on the
// curve - run!
//
if (beta == null)
{
throw new RuntimeException("Invalid point compression");
}
BigInteger betaValue = beta.toBigInteger();
if (betaValue.testBit(0) != (yTilde == 1))
{
// Use the other root
beta = fromBigInteger(q.subtract(betaValue));
}
return new ECPoint.Fp(this, x, beta, true);
}
public ECPoint getInfinity()
{
return infinity;
}
public boolean equals(
Object anObject)
{
if (anObject == this)
{
return true;
}
if (!(anObject instanceof ECCurve.Fp))
{
return false;
}
ECCurve.Fp other = (ECCurve.Fp) anObject;
return this.q.equals(other.q)
&& a.equals(other.a) && b.equals(other.b);
}
public int hashCode()
{
return a.hashCode() ^ b.hashCode() ^ q.hashCode();
}
}
/**
* Elliptic curves over F2m. The Weierstrass equation is given by
* <code>y<sup>2</sup> + xy = x<sup>3</sup> + ax<sup>2</sup> + b</code>.
*/
public static class F2m extends ECCurve
{
/**
* The exponent <code>m</code> of <code>F<sub>2<sup>m</sup></sub></code>.
*/
private int m; // can't be final - JDK 1.1
/**
* TPB: The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction polynomial
* <code>f(z)</code>.<br>
* PPB: The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k1; // can't be final - JDK 1.1
/**
* TPB: Always set to <code>0</code><br>
* PPB: The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k2; // can't be final - JDK 1.1
/**
* TPB: Always set to <code>0</code><br>
* PPB: The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.<br>
*/
private int k3; // can't be final - JDK 1.1
/**
* The order of the base point of the curve.
*/
private BigInteger n; // can't be final - JDK 1.1
/**
* The cofactor of the curve.
*/
private BigInteger h; // can't be final - JDK 1.1
/**
* The point at infinity on this curve.
*/
private ECPoint.F2m infinity; // can't be final - JDK 1.1
/**
* The parameter <code>μ</code> of the elliptic curve if this is
* a Koblitz curve.
*/
private byte mu = 0;
/**
* The auxiliary values <code>s<sub>0</sub></code> and
* <code>s<sub>1</sub></code> used for partial modular reduction for
* Koblitz curves.
*/
private BigInteger[] si = null;
/**
* Constructor for Trinomial Polynomial Basis (TPB).
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction
* polynomial <code>f(z)</code>.
* @param a The coefficient <code>a</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param b The coefficient <code>b</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
*/
public F2m(
int m,
int k,
BigInteger a,
BigInteger b)
{
this(m, k, 0, 0, a, b, null, null);
}
/**
* Constructor for Trinomial Polynomial Basis (TPB).
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k The integer <code>k</code> where <code>x<sup>m</sup> +
* x<sup>k</sup> + 1</code> represents the reduction
* polynomial <code>f(z)</code>.
* @param a The coefficient <code>a</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param b The coefficient <code>b</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param n The order of the main subgroup of the elliptic curve.
* @param h The cofactor of the elliptic curve, i.e.
* <code>#E<sub>a</sub>(F<sub>2<sup>m</sup></sub>) = h * n</code>.
*/
public F2m(
int m,
int k,
BigInteger a,
BigInteger b,
BigInteger n,
BigInteger h)
{
this(m, k, 0, 0, a, b, n, h);
}
/**
* Constructor for Pentanomial Polynomial Basis (PPB).
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param a The coefficient <code>a</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param b The coefficient <code>b</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
*/
public F2m(
int m,
int k1,
int k2,
int k3,
BigInteger a,
BigInteger b)
{
this(m, k1, k2, k3, a, b, null, null);
}
/**
* Constructor for Pentanomial Polynomial Basis (PPB).
* @param m The exponent <code>m</code> of
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param k1 The integer <code>k1</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k2 The integer <code>k2</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param k3 The integer <code>k3</code> where <code>x<sup>m</sup> +
* x<sup>k3</sup> + x<sup>k2</sup> + x<sup>k1</sup> + 1</code>
* represents the reduction polynomial <code>f(z)</code>.
* @param a The coefficient <code>a</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param b The coefficient <code>b</code> in the Weierstrass equation
* for non-supersingular elliptic curves over
* <code>F<sub>2<sup>m</sup></sub></code>.
* @param n The order of the main subgroup of the elliptic curve.
* @param h The cofactor of the elliptic curve, i.e.
* <code>#E<sub>a</sub>(F<sub>2<sup>m</sup></sub>) = h * n</code>.
*/
public F2m(
int m,
int k1,
int k2,
int k3,
BigInteger a,
BigInteger b,
BigInteger n,
BigInteger h)
{
this.m = m;
this.k1 = k1;
this.k2 = k2;
this.k3 = k3;
this.n = n;
this.h = h;
if (k1 == 0)
{
throw new IllegalArgumentException("k1 must be > 0");
}
if (k2 == 0)
{
if (k3 != 0)
{
throw new IllegalArgumentException("k3 must be 0 if k2 == 0");
}
}
else
{
if (k2 <= k1)
{
throw new IllegalArgumentException("k2 must be > k1");
}
if (k3 <= k2)
{
throw new IllegalArgumentException("k3 must be > k2");
}
}
this.a = fromBigInteger(a);
this.b = fromBigInteger(b);
this.infinity = new ECPoint.F2m(this, null, null);
}
protected F2m(int m, int k1, int k2, int k3, ECFieldElement a, ECFieldElement b, BigInteger n, BigInteger h)
{
this.m = m;
this.k1 = k1;
this.k2 = k2;
this.k3 = k3;
this.n = n;
this.h = h;
this.a = a;
this.b = b;
this.infinity = new ECPoint.F2m(this, null, null);
}
public ECCurve createCurve(Config builder)
{
F2m c = new F2m(m, k1, k2, k3, a, b, n, h);
c.coord = builder.coord;
c.multiplier = builder.multiplier;
return c;
}
protected ECMultiplier createDefaultMultiplier()
{
return isKoblitz() ? new WTauNafMultiplier() : new WNafMultiplier();
}
public int getFieldSize()
{
return m;
}
public ECFieldElement fromBigInteger(BigInteger x)
{
return new ECFieldElement.F2m(this.m, this.k1, this.k2, this.k3, x);
}
public ECPoint createPoint(BigInteger x, BigInteger y, boolean withCompression)
{
return new ECPoint.F2m(this, fromBigInteger(x), fromBigInteger(y), withCompression);
}
public ECPoint getInfinity()
{
return infinity;
}
/**
* Returns true if this is a Koblitz curve (ABC curve).
* @return true if this is a Koblitz curve (ABC curve), false otherwise
*/
public boolean isKoblitz()
{
return n != null && h != null && a.bitLength() <= 1 && b.bitLength() == 1;
}
/**
* Returns the parameter <code>μ</code> of the elliptic curve.
* @return <code>μ</code> of the elliptic curve.
* @throws IllegalArgumentException if the given ECCurve is not a
* Koblitz curve.
*/
synchronized byte getMu()
{
if (mu == 0)
{
mu = Tnaf.getMu(this);
}
return mu;
}
/**
* @return the auxiliary values <code>s<sub>0</sub></code> and
* <code>s<sub>1</sub></code> used for partial modular reduction for
* Koblitz curves.
*/
synchronized BigInteger[] getSi()
{
if (si == null)
{
si = Tnaf.getSi(this);
}
return si;
}
/**
* Decompresses a compressed point P = (xp, yp) (X9.62 s 4.2.2).
*
* @param yTilde
* ~yp, an indication bit for the decompression of yp.
* @param X1
* The field element xp.
* @return the decompressed point.
*/
protected ECPoint decompressPoint(int yTilde, BigInteger X1)
{
ECFieldElement xp = fromBigInteger(X1);
ECFieldElement yp = null;
if (X1.signum() == 0)
{
yp = (ECFieldElement.F2m)b;
for (int i = 0; i < m - 1; i++)
{
yp = yp.square();
}
}
else
{
ECFieldElement beta = xp.add(a).add(b.multiply(xp.square().invert()));
ECFieldElement z = solveQuadraticEquation(beta);
if (z == null)
{
throw new IllegalArgumentException("Invalid point compression");
}
if (z.testBitZero() != (yTilde == 1))
{
z = z.add(fromBigInteger(ECConstants.ONE));
}
yp = xp.multiply(z);
}
return new ECPoint.F2m(this, xp, yp, true);
}
/**
* Solves a quadratic equation <code>z<sup>2</sup> + z = beta</code>(X9.62
* D.1.6) The other solution is <code>z + 1</code>.
*
* @param beta
* The value to solve the quadratic equation for.
* @return the solution for <code>z<sup>2</sup> + z = beta</code> or
* <code>null</code> if no solution exists.
*/
private ECFieldElement solveQuadraticEquation(ECFieldElement beta)
{
if (beta.isZero())
{
return beta;
}
ECFieldElement zeroElement = fromBigInteger(ECConstants.ZERO);
ECFieldElement z = null;
ECFieldElement gamma = null;
Random rand = new Random();
do
{
ECFieldElement t = fromBigInteger(new BigInteger(m, rand));
z = zeroElement;
ECFieldElement w = beta;
for (int i = 1; i <= m - 1; i++)
{
ECFieldElement w2 = w.square();
z = z.square().add(w2.multiply(t));
w = w2.add(beta);
}
if (!w.isZero())
{
return null;
}
gamma = z.square().add(z);
}
while (gamma.isZero());
return z;
}
public boolean equals(
Object anObject)
{
if (anObject == this)
{
return true;
}
if (!(anObject instanceof ECCurve.F2m))
{
return false;
}
ECCurve.F2m other = (ECCurve.F2m)anObject;
return (this.m == other.m) && (this.k1 == other.k1)
&& (this.k2 == other.k2) && (this.k3 == other.k3)
&& a.equals(other.a) && b.equals(other.b);
}
public int hashCode()
{
return this.a.hashCode() ^ this.b.hashCode() ^ m ^ k1 ^ k2 ^ k3;
}
public int getM()
{
return m;
}
/**
* Return true if curve uses a Trinomial basis.
*
* @return true if curve Trinomial, false otherwise.
*/
public boolean isTrinomial()
{
return k2 == 0 && k3 == 0;
}
public int getK1()
{
return k1;
}
public int getK2()
{
return k2;
}
public int getK3()
{
return k3;
}
public BigInteger getN()
{
return n;
}
public BigInteger getH()
{
return h;
}
}
}
| Handle infinity in importPoint | core/src/main/java/org/bouncycastle/math/ec/ECCurve.java | Handle infinity in importPoint |
|
Java | mit | 572f973f69a8e99c0479f7496fb111ee87aa1d2e | 0 | curiosone-bot/curiosone-core | package com.github.bot.curiosone.core.analysis;
import com.github.bot.curiosone.core.nlp.Phrase;
/**
* Handles phrasal emotion analysis.
* Provides a single public static method to calculate the emotion of a given Phrase.
*/
public class EmotionAnalysis {
/**
* Private constructor.
*/
private EmotionAnalysis() {}
/**
* Performs an emotion analysis of the provided Phrase.
* @param phrase
* the Phrase to be analysed.
* @return a String representation of the calculated emotion. Supports "sad", "happy" and "angry"
* @see com.github.bot.curiosone.core.nlp.Phrase
*/
public static String getEmotion(Phrase phrase) {
double score = TokenScorer.calculateScore(phrase.getTokens());
if (score <= -0.5) {
return "angry";
}
if (score < 0) {
return "sad";
}
return "happy";
}
}
| src/main/java/com/github/bot/curiosone/core/analysis/EmotionAnalysis.java | package com.github.bot.curiosone.core.analysis;
import com.github.bot.curiosone.core.nlp.Phrase;
/**
* Handles emotion analysis for a Phrase.
* Provides a single public static method to perform to calculate the emotion of a given Phrase.
*/
public class EmotionAnalysis {
/**
* Private constructor.
*/
private EmotionAnalysis() {}
/**
* Performs an emotion analysis of the provided Phrase.
* @param phrase the Phrase to be analysed.
* @return a String representation of the calculated emotion. Supports "sad", "happy" and "angry"
*/
public static String getEmotion(Phrase phrase) {
double score = TokenScorer.calculateScore(phrase.getTokens());
if (score <= -0.5) {
return "angry";
}
if (score < 0) {
return "sad";
}
return "happy";
}
}
| improve EmotionAnalysis javadoc
| src/main/java/com/github/bot/curiosone/core/analysis/EmotionAnalysis.java | improve EmotionAnalysis javadoc |
|
Java | mit | 039f4093a01ec446893e3b2261bdf1b60efaa2eb | 0 | cucumber-ltd/cucumber-pro-plugin-jvm,cucumber-ltd/cucumber-pro-plugin-jvm | package io.cucumber.pro.environment;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Bamboo prefixes all environment variables with `bamboo_`. This class
* strips them off.
*/
public class BambooEnvironmentVariables {
private static Pattern BAMBOO_PATTERN = Pattern.compile("^bamboo_(.+)");
public Map<String, String> convert(Map<String, String> env) {
Map<String, String> result = new HashMap<>();
for (String key : env.keySet()) {
Matcher matcher = BAMBOO_PATTERN.matcher(key);
if (matcher.lookingAt()) {
String value = env.get(key);
String strippedVar = matcher.group(1);
result.put(strippedVar, value);
}
}
result.putAll(env);
return result;
}
}
| src/main/java/io/cucumber/pro/environment/BambooEnvironmentVariables.java | package io.cucumber.pro.environment;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Bamboo prefixes all environment variables with `bamboo_`. This class
* strips them off.
*/
public class BambooEnvironmentVariables {
private static Pattern BAMBOO_PATTERN = Pattern.compile("^bamboo_(.+)");
public Map<String, String> convert(Map<String, String> env) {
Map<String, String> result = new HashMap<>();
SortedSet<String> vars = new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String v1, String v2) {
if (BAMBOO_PATTERN.matcher(v1).lookingAt()) return -1;
if (BAMBOO_PATTERN.matcher(v2).lookingAt()) return 1;
return 0;
}
});
vars.addAll(env.keySet());
for (String key : vars) {
Matcher matcher = BAMBOO_PATTERN.matcher(key);
if (matcher.lookingAt()) {
String value = env.get(key);
String strippedVar = matcher.group(1);
result.put(strippedVar, value);
}
}
result.putAll(env);
return result;
}
}
| Simplify bamboo filtering
| src/main/java/io/cucumber/pro/environment/BambooEnvironmentVariables.java | Simplify bamboo filtering |
|
Java | mit | 53bc636dfdfa468f2e9f280760782bc3ff78aa28 | 0 | commercetools/commercetools-payone-integration,commercetools/commercetools-payone-integration | package com.commercetools.pspadapter.payone.domain.ctp;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.sphere.sdk.models.LocalizedString;
import io.sphere.sdk.models.TextInputHint;
import io.sphere.sdk.payments.commands.updateactions.AddInterfaceInteraction;
import io.sphere.sdk.queries.PagedQueryResult;
import io.sphere.sdk.types.DateTimeType;
import io.sphere.sdk.types.FieldDefinition;
import io.sphere.sdk.types.StringType;
import io.sphere.sdk.types.Type;
import io.sphere.sdk.types.TypeDraftBuilder;
import io.sphere.sdk.types.commands.TypeCreateCommand;
import io.sphere.sdk.types.queries.TypeQuery;
/**
* @author Jan Wolter
*/
public class CustomTypeBuilder {
// TODO jw: not that custom, general type for all PSPs, move somewhere else
public static final String PAYMENT_CREDIT_CARD = "payment-CREDIT_CARD";
public static final String CARD_DATA_PLACEHOLDER_FIELD = "cardDataPlaceholder";
public static final String PAYONE_INTERACTION_REQUEST = "PAYONE_INTERACTION_REQUEST";
public static final String PAYONE_INTERACTION_RESPONSE = "PAYONE_INTERACTION_RESPONSE";
public static final String PAYONE_INTERACTION_REDIRECT = "PAYONE_INTERACTION_REDIRECT";
public static final String PAYONE_INTERACTION_NOTIFICATION = "PAYONE_INTERACTION_NOTIFICATION";
public static final String PAYONE_INTERACTION_TEMPORARY_ERROR = "PAYONE_INTERACTION_TEMPORARY_ERROR";
public static final String PAYONE_UNSUPPORTED_TRANSACTION = "PAYONE_UNSUPPORTED_TRANSACTION";
public static final String TIMESTAMP_FIELD = "timestamp";
public static final String TRANSACTION_ID_FIELD = "transactionId";
public static final String REQUEST_FIELD = "request";
public static final String RESPONSE_FIELD = "response";
public static final String REDIRECT_URL = "redirectUrl";
public static final String NOTIFICATION_FIELD = "notification";
public static final String MESSAGE_FIELD = "message";
public static final boolean REQUIRED = true;
final BlockingClient client;
public CustomTypeBuilder(final BlockingClient client) {
this.client = client;
}
public void run() {
createPaymentProviderAgnosticTypes();
createPayoneSpecificTypes();
}
private void createPaymentProviderAgnosticTypes() {
}
private void createPayoneSpecificTypes() {
final FieldDefinition timestampField = FieldDefinition.of(
DateTimeType.of(),
TIMESTAMP_FIELD,
LocalizedString.ofEnglishLocale(TIMESTAMP_FIELD),
REQUIRED,
TextInputHint.SINGLE_LINE);
final FieldDefinition transactionIdField = FieldDefinition.of(
StringType.of(),
TRANSACTION_ID_FIELD,
LocalizedString.ofEnglishLocale(TRANSACTION_ID_FIELD),
REQUIRED,
TextInputHint.SINGLE_LINE);
createInteractionRequest(timestampField, transactionIdField);
createInteractionResponse(timestampField, transactionIdField);
createInteractionRedirect(timestampField, transactionIdField);
createInteractionNotification(timestampField, transactionIdField);
createInteractionTemporaryError(timestampField, transactionIdField);
}
private Type createInteractionRequest(final FieldDefinition timestampField, final FieldDefinition transactionIdField) {
return createType(PAYONE_INTERACTION_REQUEST, ImmutableList.of(timestampField, transactionIdField, createMultiLineStringFieldDefinition(REQUEST_FIELD)));
}
private Type createInteractionResponse(final FieldDefinition timestampField, final FieldDefinition transactionIdField) {
return createType(PAYONE_INTERACTION_RESPONSE, ImmutableList.of(timestampField, transactionIdField, createMultiLineStringFieldDefinition(RESPONSE_FIELD)));
}
private Type createInteractionRedirect(final FieldDefinition timestampField, final FieldDefinition transactionIdField) {
return createType(PAYONE_INTERACTION_REDIRECT,
ImmutableList.of(timestampField, transactionIdField, createSingleLineStringFieldDefinition(REDIRECT_URL), createMultiLineStringFieldDefinition(RESPONSE_FIELD)));
}
private Type createInteractionTemporaryError(final FieldDefinition timestampField, final FieldDefinition transactionIdField) {
return createType(PAYONE_INTERACTION_TEMPORARY_ERROR, ImmutableList.of(timestampField, transactionIdField, createMultiLineStringFieldDefinition(RESPONSE_FIELD)));
}
private Type createInteractionNotification(final FieldDefinition timestampField, final FieldDefinition transactionIdField) {
return createType(PAYONE_INTERACTION_NOTIFICATION, ImmutableList.of(timestampField, transactionIdField, createMultiLineStringFieldDefinition(NOTIFICATION_FIELD)));
}
private Type createPayoneUnsupportedTransaction(final FieldDefinition timestampField, final FieldDefinition transactionIdField) {
final FieldDefinition messageField = FieldDefinition.of(
StringType.of(),
MESSAGE_FIELD,
LocalizedString.ofEnglishLocale(MESSAGE_FIELD),
REQUIRED,
TextInputHint.SINGLE_LINE);
return createType(PAYONE_UNSUPPORTED_TRANSACTION, ImmutableList.of(timestampField, transactionIdField, createSingleLineStringFieldDefinition(MESSAGE_FIELD)));
}
private Type createType(String typeKey, ImmutableList<FieldDefinition> fieldDefinitions) {
// TODO replace with cache
final PagedQueryResult<Type> result = client.complete(
TypeQuery.of()
.withPredicates(m -> m.key().is(typeKey))
.withLimit(1));
if (result.getTotal() == 0) {
return client.complete(TypeCreateCommand.of(TypeDraftBuilder.of(
typeKey,
LocalizedString.ofEnglishLocale(typeKey),
ImmutableSet.of(AddInterfaceInteraction.resourceTypeId()))
.fieldDefinitions(
fieldDefinitions)
.build()));
}
else {
return result.getResults().get(0);
}
}
private FieldDefinition createSingleLineStringFieldDefinition(final String fieldName) {
return createFieldDefinition(fieldName, TextInputHint.SINGLE_LINE);
}
private FieldDefinition createMultiLineStringFieldDefinition(final String fieldName) {
return createFieldDefinition(fieldName, TextInputHint.MULTI_LINE);
}
private FieldDefinition createFieldDefinition(final String fieldName, TextInputHint inputHint) {
return FieldDefinition.of(
StringType.of(),
fieldName,
LocalizedString.ofEnglishLocale(fieldName),
REQUIRED,
inputHint);
}
}
| service/src/main/java/com/commercetools/pspadapter/payone/domain/ctp/CustomTypeBuilder.java | package com.commercetools.pspadapter.payone.domain.ctp;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import io.sphere.sdk.models.LocalizedString;
import io.sphere.sdk.models.TextInputHint;
import io.sphere.sdk.payments.commands.updateactions.AddInterfaceInteraction;
import io.sphere.sdk.queries.PagedQueryResult;
import io.sphere.sdk.types.DateTimeType;
import io.sphere.sdk.types.FieldDefinition;
import io.sphere.sdk.types.StringType;
import io.sphere.sdk.types.Type;
import io.sphere.sdk.types.TypeDraftBuilder;
import io.sphere.sdk.types.commands.TypeCreateCommand;
import io.sphere.sdk.types.queries.TypeQuery;
/**
* @author Jan Wolter
*/
public class CustomTypeBuilder {
// TODO jw: not that custom, general type for all PSPs, move somewhere else
public static final String PAYMENT_CREDIT_CARD = "payment-CREDIT_CARD";
public static final String CARD_DATA_PLACEHOLDER_FIELD = "cardDataPlaceholder";
public static final String PAYONE_INTERACTION_REQUEST = "PAYONE_INTERACTION_REQUEST";
public static final String PAYONE_INTERACTION_RESPONSE = "PAYONE_INTERACTION_RESPONSE";
public static final String PAYONE_INTERACTION_REDIRECT = "PAYONE_INTERACTION_REDIRECT";
public static final String PAYONE_INTERACTION_NOTIFICATION = "PAYONE_INTERACTION_NOTIFICATION";
public static final String PAYONE_INTERACTION_TEMPORARY_ERROR = "PAYONE_INTERACTION_TEMPORARY_ERROR";
public static final String PAYONE_UNSUPPORTED_TRANSACTION = "PAYONE_UNSUPPORTED_TRANSACTION";
public static final String TIMESTAMP_FIELD = "timestamp";
public static final String TRANSACTION_ID_FIELD = "transactionId";
public static final String REQUEST_FIELD = "request";
public static final String RESPONSE_FIELD = "response";
public static final String REDIRECT_URL = "redirectUrl";
public static final String NOTIFICATION_FIELD = "notification";
public static final String MESSAGE_FIELD = "message";
public static final boolean REQUIRED = true;
final BlockingClient client;
public CustomTypeBuilder(final BlockingClient client) {
this.client = client;
}
public void run() {
final FieldDefinition timestampField = FieldDefinition.of(
DateTimeType.of(),
TIMESTAMP_FIELD,
LocalizedString.ofEnglishLocale(TIMESTAMP_FIELD),
REQUIRED,
TextInputHint.SINGLE_LINE);
final FieldDefinition transactionIdField = FieldDefinition.of(
StringType.of(),
TRANSACTION_ID_FIELD,
LocalizedString.ofEnglishLocale(TRANSACTION_ID_FIELD),
REQUIRED,
TextInputHint.SINGLE_LINE);
createInteractionRequest(timestampField, transactionIdField);
createInteractionResponse(timestampField, transactionIdField);
createInteractionRedirect(timestampField, transactionIdField);
createInteractionNotification(timestampField, transactionIdField);
createInteractionTemporaryError(timestampField, transactionIdField);
}
private Type createInteractionRequest(final FieldDefinition timestampField, final FieldDefinition transactionIdField) {
return createType(PAYONE_INTERACTION_REQUEST, ImmutableList.of(timestampField, transactionIdField, createMultiLineStringFieldDefinition(REQUEST_FIELD)));
}
private Type createInteractionResponse(final FieldDefinition timestampField, final FieldDefinition transactionIdField) {
return createType(PAYONE_INTERACTION_RESPONSE, ImmutableList.of(timestampField, transactionIdField, createMultiLineStringFieldDefinition(RESPONSE_FIELD)));
}
private Type createInteractionRedirect(final FieldDefinition timestampField, final FieldDefinition transactionIdField) {
return createType(PAYONE_INTERACTION_REDIRECT,
ImmutableList.of(timestampField, transactionIdField, createSingleLineStringFieldDefinition(REDIRECT_URL), createMultiLineStringFieldDefinition(RESPONSE_FIELD)));
}
private Type createInteractionTemporaryError(final FieldDefinition timestampField, final FieldDefinition transactionIdField) {
return createType(PAYONE_INTERACTION_TEMPORARY_ERROR, ImmutableList.of(timestampField, transactionIdField, createMultiLineStringFieldDefinition(RESPONSE_FIELD)));
}
private Type createInteractionNotification(final FieldDefinition timestampField, final FieldDefinition transactionIdField) {
return createType(PAYONE_INTERACTION_NOTIFICATION, ImmutableList.of(timestampField, transactionIdField, createMultiLineStringFieldDefinition(NOTIFICATION_FIELD)));
}
private Type createPayoneUnsupportedTransaction(final FieldDefinition timestampField, final FieldDefinition transactionIdField) {
final FieldDefinition messageField = FieldDefinition.of(
StringType.of(),
MESSAGE_FIELD,
LocalizedString.ofEnglishLocale(MESSAGE_FIELD),
REQUIRED,
TextInputHint.SINGLE_LINE);
return createType(PAYONE_UNSUPPORTED_TRANSACTION, ImmutableList.of(timestampField, transactionIdField, createSingleLineStringFieldDefinition(MESSAGE_FIELD)));
}
private Type createType(String typeKey, ImmutableList<FieldDefinition> fieldDefinitions) {
// TODO replace with cache
final PagedQueryResult<Type> result = client.complete(
TypeQuery.of()
.withPredicates(m -> m.key().is(typeKey))
.withLimit(1));
if (result.getTotal() == 0) {
return client.complete(TypeCreateCommand.of(TypeDraftBuilder.of(
typeKey,
LocalizedString.ofEnglishLocale(typeKey),
ImmutableSet.of(AddInterfaceInteraction.resourceTypeId()))
.fieldDefinitions(
fieldDefinitions)
.build()));
}
else {
return result.getResults().get(0);
}
}
private FieldDefinition createSingleLineStringFieldDefinition(final String fieldName) {
return createFieldDefinition(fieldName, TextInputHint.SINGLE_LINE);
}
private FieldDefinition createMultiLineStringFieldDefinition(final String fieldName) {
return createFieldDefinition(fieldName, TextInputHint.MULTI_LINE);
}
private FieldDefinition createFieldDefinition(final String fieldName, TextInputHint inputHint) {
return FieldDefinition.of(
StringType.of(),
fieldName,
LocalizedString.ofEnglishLocale(fieldName),
REQUIRED,
inputHint);
}
}
| [WIP] prepare CustomTypeBuilder to create payment provider agnostic types
| service/src/main/java/com/commercetools/pspadapter/payone/domain/ctp/CustomTypeBuilder.java | [WIP] prepare CustomTypeBuilder to create payment provider agnostic types |
|
Java | mit | 6d48f9df8d9aeca9d6ded71c5f2eb3ef162890bb | 0 | kerrickstaley/wssh,kerrickstaley/wssh,kerrickstaley/wssh,kerrickstaley/wssh | package wssh.io;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.concurrent.ConcurrentLinkedQueue;
public class SSHInputStream extends InputStream
{
private ConcurrentLinkedQueue<Byte> toSend;
public SSHInputStream()
{
this.toSend = new ConcurrentLinkedQueue<Byte>();
}
/** @Override */
synchronized public int read()
{
System.out.println("SSHInputStream - begin reading byte");
while (toSend.isEmpty())
{
System.out.println("SSHInputStream - thread waits for input");
try
{
this.wait();
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("SSHInputStream - thread notified");
}
System.out.println("SSHInputStream - thread reads input: " + toSend.peek().intValue() + "(" + ((char) toSend.peek().intValue()) + ")");
return this.toSend.poll().intValue();
}
synchronized public void write(String input)
{
System.out.println("SSHInputStream - begin insert to byte array");
boolean wasEmpty = this.toSend.isEmpty();
input = SSHInputStream.unescapeString(input);
// Convert to UTF-8
try
{
byte[] b = input.getBytes("UTF-8");
for (int i = 0; i < input.length(); i += 1)
{
this.toSend.offer(Byte.valueOf(b[i]));
}
if (wasEmpty)
{
System.out.println("SSHInputStream - Waking up waiting threads, if any");
this.notify();
}
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("SSHInputStream - end insert to byte array");
}
// Based off of Apache Commons StringEscapeUtils::unescapeJava
protected static String unescapeString(String str)
{
int size = str.length();
StringWriter writer = new StringWriter(size);
StringBuffer unicode = new StringBuffer(4);
boolean hadSlash = false;
boolean inUnicode = false;
for (int i = 0; i < size; i += 1)
{
char ch = str.charAt(i);
// We've already started reading unicode character
if (inUnicode)
{
unicode.append(ch);
// We've read all four hex values
if (unicode.length() == 4)
{
try
{
int value = Integer.parseInt(unicode.toString(), 16);
writer.write((char) value);
unicode.setLength(0);
inUnicode = false;
hadSlash = false;
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
}
continue;
}
// Handle escaped value
if (hadSlash)
{
hadSlash = false;
if (ch == '\\')
{
writer.write('\\');
}
else if (ch == '\'')
{
writer.write('\'');
}
else if (ch == '\"')
{
writer.write('"');
}
else if (ch == 'r')
{
writer.write('\r');
}
else if (ch == 'f')
{
writer.write('\f');
}
else if (ch == 't')
{
writer.write('\t');
}
else if (ch == 'n')
{
writer.write('\n');
}
else if (ch == 'b')
{
writer.write('\b');
}
else if (ch == 'u')
{
// Unicode parsing
inUnicode = true;
}
else
{
writer.write(ch);
}
continue;
}
else if (ch == '\\')
{
hadSlash = true;
continue;
}
writer.write(ch);
}
// Slash (\) at the end of string. Output it
if (hadSlash)
{
writer.write('\\');
}
return writer.toString();
}
}
| server/src/wssh/io/SSHInputStream.java | package wssh.io;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.concurrent.ConcurrentLinkedQueue;
public class SSHInputStream extends InputStream
{
private ConcurrentLinkedQueue<Byte> toSend;
public SSHInputStream()
{
this.toSend = new ConcurrentLinkedQueue<Byte>();
}
/** @Override */
synchronized public int read()
{
System.out.println("SSHInputStream - begin reading byte");
while (toSend.isEmpty())
{
System.out.println("SSHInputStream - thread waits for input");
try
{
this.wait();
}
catch (Exception e)
{
e.printStackTrace();
}
System.out.println("SSHInputStream - thread notified");
}
System.out.println("SSHInputStream - thread reads input: " + toSend.peek().intValue() + "(" + ((char) toSend.peek().intValue()) + ")");
return this.toSend.poll().intValue();
}
synchronized public void write(String input)
{
System.out.println("SSHInputStream - begin insert to byte array");
boolean wasEmpty = this.toSend.isEmpty();
input = SSHInputStream.unescapeString(input);
for (int i = 0; i < input.length(); i++)
{
char strChar = input.charAt(i);
this.toSend.offer(Byte.valueOf((byte) (strChar&0x00FF))); // low byte
this.toSend.offer(Byte.valueOf((byte) ((strChar&0xFF00)>>8))); // high byte
}
// Convert to UTF-8
/* try
{
byte[] b = input.getBytes("UTF-8");
for (int i = 0; i < input.length(); i += 1)
{
this.toSend.offer(Byte.valueOf(b[i]));
}
*/
if (wasEmpty)
{
System.out.println("SSHInputStream - Waking up waiting threads, if any");
this.notify();
}
/* }
catch (Exception e)
{
e.printStackTrace();
}
*/
System.out.println("SSHInputStream - end insert to byte array");
}
// Based off of Apache Commons StringEscapeUtils::unescapeJava
protected static String unescapeString(String str)
{
int size = str.length();
StringWriter writer = new StringWriter(size);
StringBuffer unicode = new StringBuffer(4);
boolean hadSlash = false;
boolean inUnicode = false;
for (int i = 0; i < size; i += 1)
{
char ch = str.charAt(i);
// We've already started reading unicode character
if (inUnicode)
{
unicode.append(ch);
// We've read all four hex values
if (unicode.length() == 4)
{
try
{
int value = Integer.parseInt(unicode.toString(), 16);
writer.write((char) value);
unicode.setLength(0);
inUnicode = false;
hadSlash = false;
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
}
continue;
}
// Handle escaped value
if (hadSlash)
{
hadSlash = false;
if (ch == '\\')
{
writer.write('\\');
}
else if (ch == '\'')
{
writer.write('\'');
}
else if (ch == '\"')
{
writer.write('"');
}
else if (ch == 'r')
{
writer.write('\r');
}
else if (ch == 'f')
{
writer.write('\f');
}
else if (ch == 't')
{
writer.write('\t');
}
else if (ch == 'n')
{
writer.write('\n');
}
else if (ch == 'b')
{
writer.write('\b');
}
else if (ch == 'u')
{
// Unicode parsing
inUnicode = true;
}
else
{
writer.write(ch);
}
continue;
}
else if (ch == '\\')
{
hadSlash = true;
continue;
}
writer.write(ch);
}
// Slash (\) at the end of string. Output it
if (hadSlash)
{
writer.write('\\');
}
return writer.toString();
}
}
| Back to UTF-8
| server/src/wssh/io/SSHInputStream.java | Back to UTF-8 |
|
Java | mit | f87fa23ccf8f6e6886bb051f8450a856e0628d3e | 0 | scottnguyen/revlo-java-client | package com.revlo.requests;
import lombok.Builder;
import lombok.Data;
import java.util.Map;
import java.util.HashMap;
@Builder @Data
public class GetRedemptionsRequest implements Request {
private Integer page;
private Boolean completed;
private Boolean refunded;
private Integer rewardId;
public Map<String,String> params() {
Map<String,String> hash = new HashMap<>();
if (getPage() != null) {
hash.put("page", getPage().toString());
}
if (getCompleted() != null) {
hash.put("completed", getCompleted().toString());
}
if (getRefunded() != null) {
hash.put("refunded", getRefunded().toString());
}
if (getRewardId() != null) {
hash.put("reward_id", getRewardId().toString());
}
return hash;
}
@Override
public String payload() {
return "";
}
}
| src/main/java/com/revlo/requests/GetRedemptionsRequest.java | package com.revlo.requests;
import lombok.Builder;
import lombok.Data;
import java.util.Map;
import java.util.HashMap;
@Builder @Data
public class GetRedemptionsRequest implements Request {
private Integer page;
private Boolean completed;
private Boolean refunded;
public Map<String,String> params() {
Map<String,String> hash = new HashMap<>();
if (getPage() != null) {
hash.put("page", getPage().toString());
}
if (getCompleted() != null) {
hash.put("completed", getCompleted().toString());
}
if (getRefunded() != null) {
hash.put("refunded", getRefunded().toString());
}
return hash;
}
@Override
public String payload() {
return "";
}
}
| Add reward_id optional param
| src/main/java/com/revlo/requests/GetRedemptionsRequest.java | Add reward_id optional param |
|
Java | mit | 5094e6e97b079be4418aa9481fa9afa666994f2c | 0 | PhilippHeuer/twitch4j | package com.github.twitch4j.pubsub;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.philippheuer.events4j.core.EventManager;
import com.github.twitch4j.common.config.ProxyConfig;
import com.github.twitch4j.common.enums.CommandPermission;
import com.github.twitch4j.common.events.domain.EventUser;
import com.github.twitch4j.common.events.user.PrivateMessageEvent;
import com.github.twitch4j.common.util.CryptoUtils;
import com.github.twitch4j.common.util.ExponentialBackoffStrategy;
import com.github.twitch4j.common.util.TimeUtils;
import com.github.twitch4j.common.util.TwitchUtils;
import com.github.twitch4j.common.util.TypeConvert;
import com.github.twitch4j.pubsub.domain.*;
import com.github.twitch4j.pubsub.enums.PubSubType;
import com.github.twitch4j.pubsub.enums.TMIConnectionState;
import com.github.twitch4j.pubsub.events.*;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketFactory;
import com.neovisionaries.ws.client.WebSocketFrame;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Twitch PubSub
*/
@Slf4j
public class TwitchPubSub implements ITwitchPubSub {
public static final int REQUIRED_THREAD_COUNT = 1;
private static final Pattern LISTEN_AUTH_TOKEN = Pattern.compile("(\\{.*\"type\"\\s*?:\\s*?\"LISTEN\".*\"data\"\\s*?:\\s*?\\{.*\"auth_token\"\\s*?:\\s*?\").+(\".*}\\s*?})");
/**
* EventManager
*/
@Getter
private final EventManager eventManager;
/**
* The WebSocket Server
*/
private static final String WEB_SOCKET_SERVER = "wss://pubsub-edge.twitch.tv:443";
/**
* WebSocket Client
*/
@Setter(AccessLevel.NONE)
private volatile WebSocket webSocket;
/**
* The connection state
* Default: ({@link TMIConnectionState#DISCONNECTED})
*/
private volatile TMIConnectionState connectionState = TMIConnectionState.DISCONNECTED;
/**
* Whether {@link #flushCommand} is currently executing
*/
private final AtomicBoolean flushing = new AtomicBoolean();
/**
* Whether an expedited flush has already been submitted
*/
private final AtomicBoolean flushRequested = new AtomicBoolean();
/**
* The {@link Runnable} for flushing the {@link #commandQueue}
*/
private final Runnable flushCommand;
/**
* Command Queue Thread
*/
protected final Future<?> queueTask;
/**
* Heartbeat Thread
*/
protected final Future<?> heartbeatTask;
/**
* is Closed?
*/
protected volatile boolean isClosed = false;
/**
* Command Queue
*/
protected final BlockingQueue<String> commandQueue = new ArrayBlockingQueue<>(200);
/**
* Holds the subscribed topics in case we need to reconnect
*/
protected final Set<PubSubRequest> subscribedTopics = ConcurrentHashMap.newKeySet();
/**
* Last Ping send (1 minute delay before sending the first ping)
*/
protected volatile long lastPing = TimeUtils.getCurrentTimeInMillis() - 4 * 60 * 1000;
/**
* Last Pong received
*/
protected volatile long lastPong = TimeUtils.getCurrentTimeInMillis();
/**
* Thread Pool Executor
*/
protected final ScheduledExecutorService taskExecutor;
/**
* Bot Owner IDs
*/
private final Collection<String> botOwnerIds;
/**
* WebSocket Factory
*/
protected final WebSocketFactory webSocketFactory;
/**
* Helper class to compute delays between connection retries.
* <p>
* Configured to (approximately) emulate first-party clients:
* <ul>
* <li>initially waits one second</li>
* <li>plus a small random jitter</li>
* <li>doubles the backoff period on subsequent failures</li>
* <li>up to a maximum backoff threshold of 2 minutes</li>
* </ul>
*
* @see <a href="https://dev.twitch.tv/docs/pubsub#connection-management">Official documentation - Handling Connection Failures</a>
*/
protected final ExponentialBackoffStrategy backoff = ExponentialBackoffStrategy.builder()
.immediateFirst(false)
.baseMillis(Duration.ofSeconds(1).toMillis())
.jitter(true)
.multiplier(2.0)
.maximumBackoff(Duration.ofMinutes(2).toMillis())
.build();
/**
* Calls {@link ExponentialBackoffStrategy#reset()} upon a successful websocket connection
*/
private volatile Future<?> backoffClearer;
/**
* Constructor
*
* @param eventManager EventManager
* @param taskExecutor ScheduledThreadPoolExecutor
* @param proxyConfig ProxyConfig
* @param botOwnerIds Bot Owner IDs
*/
public TwitchPubSub(EventManager eventManager, ScheduledThreadPoolExecutor taskExecutor, ProxyConfig proxyConfig, Collection<String> botOwnerIds) {
this.taskExecutor = taskExecutor;
this.botOwnerIds = botOwnerIds;
this.eventManager = eventManager;
// register with serviceMediator
this.eventManager.getServiceMediator().addService("twitch4j-pubsub", this);
// WebSocket Factory and proxy settings
this.webSocketFactory = new WebSocketFactory();
if (proxyConfig != null)
proxyConfig.applyWs(webSocketFactory.getProxySettings());
// connect
this.connect();
// Run heartbeat every 4 minutes
heartbeatTask = taskExecutor.scheduleAtFixedRate(() -> {
if (isClosed || connectionState != TMIConnectionState.CONNECTED)
return;
PubSubRequest request = new PubSubRequest();
request.setType(PubSubType.PING);
sendCommand(TypeConvert.objectToJson(request));
log.debug("PubSub: Sending PING!");
lastPing = TimeUtils.getCurrentTimeInMillis();
}, 0, 4L, TimeUnit.MINUTES);
// Runnable for flushing the command queue
this.flushCommand = () -> {
// Only allow a single thread to flush at a time
if (flushing.getAndSet(true))
return;
// Attempt to flush the queue
while (!isClosed) {
try {
// check for missing pong response
if (lastPong < lastPing && TimeUtils.getCurrentTimeInMillis() >= lastPing + 10000) {
log.warn("PubSub: Didn't receive a PONG response in time, reconnecting to obtain a connection to a different server.");
reconnect();
break;
}
// If connected, send one message from the queue
if (connectionState.equals(TMIConnectionState.CONNECTED)) {
String command = commandQueue.poll();
if (command != null) {
sendCommand(command);
// Logging
if (log.isDebugEnabled()) {
Matcher matcher = LISTEN_AUTH_TOKEN.matcher(command);
String cmd = matcher.find() ? matcher.group(1) + "\u2022\u2022\u2022" + matcher.group(2) : command;
log.debug("Processed command from queue: [{}].", cmd);
}
} else {
break; // try again later
}
} else {
break; // try again later
}
} catch (Exception ex) {
log.error("PubSub: Unexpected error in worker thread", ex);
break;
}
}
// Indicate that flushing has completed
flushRequested.set(false);
flushing.set(false);
};
// queue command worker
this.queueTask = taskExecutor.scheduleWithFixedDelay(flushCommand, 0, 2500L, TimeUnit.MILLISECONDS);
log.debug("PubSub: Started Queue Worker Thread");
}
/**
* Connecting to IRC-WS
*/
@Synchronized
public void connect() {
if (connectionState.equals(TMIConnectionState.DISCONNECTED) || connectionState.equals(TMIConnectionState.RECONNECTING)) {
try {
// Change Connection State
connectionState = TMIConnectionState.CONNECTING;
// Recreate Socket if state does not equal CREATED
createWebSocket();
// Reset last ping to avoid edge case loop where reconnect occurred after sending PING but before receiving PONG
this.lastPong = TimeUtils.getCurrentTimeInMillis();
this.lastPing = lastPong - 4 * 60 * 1000;
// Connect to IRC WebSocket
this.webSocket.connect();
} catch (Exception ex) {
log.error("PubSub: Connection to Twitch PubSub failed: {} - Retrying ...", ex.getMessage());
if (backoffClearer != null) {
try {
backoffClearer.cancel(false);
} catch (Exception ignored) {
}
}
// Sleep before trying to reconnect
try {
backoff.sleep();
} catch (Exception ignored) {
} finally {
// reconnect
reconnect();
}
}
}
}
/**
* Disconnecting from WebSocket
*/
@Synchronized
public void disconnect() {
if (connectionState.equals(TMIConnectionState.CONNECTED)) {
connectionState = TMIConnectionState.DISCONNECTING;
}
connectionState = TMIConnectionState.DISCONNECTED;
// CleanUp
if (webSocket != null) {
this.webSocket.clearListeners();
this.webSocket.disconnect();
this.webSocket = null;
}
if (backoffClearer != null) {
backoffClearer.cancel(false);
}
}
/**
* Reconnecting to WebSocket
*/
@Synchronized
public void reconnect() {
connectionState = TMIConnectionState.RECONNECTING;
disconnect();
connect();
}
/**
* Recreate the WebSocket and the listeners
*/
@Synchronized
private void createWebSocket() {
try {
// WebSocket
this.webSocket = webSocketFactory.createSocket(WEB_SOCKET_SERVER);
// WebSocket Listeners
this.webSocket.clearListeners();
this.webSocket.addListener(new WebSocketAdapter() {
@Override
public void onConnected(WebSocket ws, Map<String, List<String>> headers) {
log.info("Connecting to Twitch PubSub {}", WEB_SOCKET_SERVER);
// Connection Success
connectionState = TMIConnectionState.CONNECTED;
backoffClearer = taskExecutor.schedule(() -> {
if (connectionState == TMIConnectionState.CONNECTED)
backoff.reset();
}, 30, TimeUnit.SECONDS);
log.info("Connected to Twitch PubSub {}", WEB_SOCKET_SERVER);
// resubscribe to all topics after disconnect
// This involves nonce reuse, which is bad cryptography, but not a serious problem for this context
// To avoid reuse, we can:
// 0) stop other threads from updating subscribedTopics
// 1) create a new PubSubRequest for each element of subscribedTopics (with a new nonce)
// 2) clear subscribedTopics
// 3) allow other threads to update subscribedTopics again
// 4) send unlisten requests for the old elements of subscribedTopics (optional?)
// 5) call listenOnTopic for each new PubSubRequest
subscribedTopics.forEach(topic -> queueRequest(topic));
}
@Override
public void onTextMessage(WebSocket ws, String text) {
try {
log.trace("Received WebSocketMessage: " + text);
// parse message
PubSubResponse message = TypeConvert.jsonToObject(text, PubSubResponse.class);
if (message.getType().equals(PubSubType.MESSAGE)) {
String topic = message.getData().getTopic();
String[] topicParts = StringUtils.split(topic, '.');
String topicName = topicParts[0];
String lastTopicIdentifier = topicParts[topicParts.length - 1];
String type = message.getData().getMessage().getType();
JsonNode msgData = message.getData().getMessage().getMessageData();
String rawMessage = message.getData().getMessage().getRawMessage();
// Handle Messages
if ("channel-bits-events-v2".equals(topicName)) {
eventManager.publish(new ChannelBitsEvent(TypeConvert.convertValue(msgData, ChannelBitsData.class)));
} else if ("channel-bits-badge-unlocks".equals(topicName)) {
eventManager.publish(new ChannelBitsBadgeUnlockEvent(TypeConvert.jsonToObject(rawMessage, BitsBadgeData.class)));
} else if ("channel-subscribe-events-v1".equals(topicName)) {
eventManager.publish(new ChannelSubscribeEvent(TypeConvert.jsonToObject(rawMessage, SubscriptionData.class)));
} else if ("channel-commerce-events-v1".equals(topicName)) {
eventManager.publish(new ChannelCommerceEvent(TypeConvert.jsonToObject(rawMessage, CommerceData.class)));
} else if ("whispers".equals(topicName) && (type.equals("whisper_sent") || type.equals("whisper_received"))) {
// Whisper data is escaped Json cast into a String
JsonNode msgDataParsed = TypeConvert.jsonToObject(msgData.asText(), JsonNode.class);
//TypeReference<T> allows type parameters (unlike Class<T>) and avoids needing @SuppressWarnings("unchecked")
Map<String, Object> tags = TypeConvert.convertValue(msgDataParsed.path("tags"), new TypeReference<Map<String, Object>>() {});
String fromId = msgDataParsed.get("from_id").asText();
String displayName = (String) tags.get("display_name");
EventUser eventUser = new EventUser(fromId, displayName);
String body = msgDataParsed.get("body").asText();
Set<CommandPermission> permissions = TwitchUtils.getPermissionsFromTags(tags, new HashMap<>(), fromId, botOwnerIds);
PrivateMessageEvent privateMessageEvent = new PrivateMessageEvent(eventUser, body, permissions);
eventManager.publish(privateMessageEvent);
} else if ("automod-levels-modification".equals(topicName) && topicParts.length > 1) {
if ("automod_levels_modified".equals(type)) {
AutomodLevelsModified data = TypeConvert.convertValue(msgData, AutomodLevelsModified.class);
eventManager.publish(new AutomodLevelsModifiedEvent(lastTopicIdentifier, data));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("automod-queue".equals(topicName)) {
if (topicParts.length == 3 && "automod_caught_message".equalsIgnoreCase(type)) {
AutomodCaughtMessageData data = TypeConvert.convertValue(msgData, AutomodCaughtMessageData.class);
eventManager.publish(new AutomodCaughtMessageEvent(topicParts[2], data));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("community-boost-events-v1".equals(topicName)) {
if ("community-boost-progression".equals(type)) {
CommunityBoostProgression progression = TypeConvert.convertValue(msgData, CommunityBoostProgression.class);
eventManager.publish(new CommunityBoostProgressionEvent(progression));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("community-points-channel-v1".equals(topicName) || "channel-points-channel-v1".equals(topicName)) {
String timestampText = msgData.path("timestamp").asText();
Instant instant = Instant.parse(timestampText);
switch (type) {
case "reward-redeemed":
ChannelPointsRedemption redemption = TypeConvert.convertValue(msgData.path("redemption"), ChannelPointsRedemption.class);
eventManager.publish(new RewardRedeemedEvent(instant, redemption));
break;
case "redemption-status-update":
ChannelPointsRedemption updatedRedemption = TypeConvert.convertValue(msgData.path("redemption"), ChannelPointsRedemption.class);
eventManager.publish(new RedemptionStatusUpdateEvent(instant, updatedRedemption));
break;
case "custom-reward-created":
ChannelPointsReward newReward = TypeConvert.convertValue(msgData.path("new_reward"), ChannelPointsReward.class);
eventManager.publish(new CustomRewardCreatedEvent(instant, newReward));
break;
case "custom-reward-updated":
ChannelPointsReward updatedReward = TypeConvert.convertValue(msgData.path("updated_reward"), ChannelPointsReward.class);
eventManager.publish(new CustomRewardUpdatedEvent(instant, updatedReward));
break;
case "custom-reward-deleted":
ChannelPointsReward deletedReward = TypeConvert.convertValue(msgData.path("deleted_reward"), ChannelPointsReward.class);
eventManager.publish(new CustomRewardDeletedEvent(instant, deletedReward));
break;
case "update-redemption-statuses-progress":
RedemptionProgress redemptionProgress = TypeConvert.convertValue(msgData.path("progress"), RedemptionProgress.class);
eventManager.publish(new UpdateRedemptionProgressEvent(instant, redemptionProgress));
break;
case "update-redemption-statuses-finished":
RedemptionProgress redemptionFinished = TypeConvert.convertValue(msgData.path("progress"), RedemptionProgress.class);
eventManager.publish(new UpdateRedemptionFinishedEvent(instant, redemptionFinished));
break;
case "community-goal-contribution":
CommunityGoalContribution contribution = TypeConvert.convertValue(msgData.path("contribution"), CommunityGoalContribution.class);
eventManager.publish(new CommunityGoalContributionEvent(instant, contribution));
break;
default:
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
break;
}
} else if ("crowd-chant-channel-v1".equals(topicName)) {
if ("crowd-chant-created".equals(type)) {
CrowdChantCreatedEvent event = TypeConvert.convertValue(msgData, CrowdChantCreatedEvent.class);
eventManager.publish(event);
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("raid".equals(topicName)) {
switch (type) {
case "raid_go_v2":
eventManager.publish(TypeConvert.jsonToObject(rawMessage, RaidGoEvent.class));
break;
case "raid_update_v2":
eventManager.publish(TypeConvert.jsonToObject(rawMessage, RaidUpdateEvent.class));
break;
case "raid_cancel_v2":
eventManager.publish(TypeConvert.jsonToObject(rawMessage, RaidCancelEvent.class));
break;
default:
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
break;
}
} else if ("chat_moderator_actions".equals(topicName) && topicParts.length > 1) {
switch (type) {
case "moderation_action":
ChatModerationAction modAction = TypeConvert.convertValue(msgData, ChatModerationAction.class);
eventManager.publish(new ChatModerationEvent(lastTopicIdentifier, modAction));
break;
case "channel_terms_action":
ChannelTermsAction termsAction = TypeConvert.convertValue(msgData, ChannelTermsAction.class);
eventManager.publish(new ChannelTermsEvent(lastTopicIdentifier, termsAction));
break;
case "approve_unban_request":
case "deny_unban_request":
ModeratorUnbanRequestAction unbanRequestAction = TypeConvert.convertValue(msgData, ModeratorUnbanRequestAction.class);
eventManager.publish(new ModUnbanRequestActionEvent(lastTopicIdentifier, unbanRequestAction));
break;
default:
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
break;
}
} else if ("following".equals(topicName) && topicParts.length > 1) {
final FollowingData data = TypeConvert.jsonToObject(rawMessage, FollowingData.class);
eventManager.publish(new FollowingEvent(lastTopicIdentifier, data));
} else if ("hype-train-events-v1".equals(topicName) && topicParts.length > 2 && "rewards".equals(topicParts[1])) {
eventManager.publish(new HypeTrainRewardsEvent(TypeConvert.convertValue(msgData, HypeTrainRewardsData.class)));
} else if ("hype-train-events-v1".equals(topicName) && topicParts.length > 1) {
switch (type) {
case "hype-train-approaching":
final HypeTrainApproaching approachData = TypeConvert.convertValue(msgData, HypeTrainApproaching.class);
eventManager.publish(new HypeTrainApproachingEvent(approachData));
break;
case "hype-train-start":
final HypeTrainStart startData = TypeConvert.convertValue(msgData, HypeTrainStart.class);
eventManager.publish(new HypeTrainStartEvent(startData));
break;
case "hype-train-progression":
final HypeProgression progressionData = TypeConvert.convertValue(msgData, HypeProgression.class);
eventManager.publish(new HypeTrainProgressionEvent(lastTopicIdentifier, progressionData));
break;
case "hype-train-level-up":
final HypeLevelUp levelUpData = TypeConvert.convertValue(msgData, HypeLevelUp.class);
eventManager.publish(new HypeTrainLevelUpEvent(lastTopicIdentifier, levelUpData));
break;
case "hype-train-end":
final HypeTrainEnd endData = TypeConvert.convertValue(msgData, HypeTrainEnd.class);
eventManager.publish(new HypeTrainEndEvent(lastTopicIdentifier, endData));
break;
case "hype-train-conductor-update":
final HypeTrainConductor conductorData = TypeConvert.convertValue(msgData, HypeTrainConductor.class);
eventManager.publish(new HypeTrainConductorUpdateEvent(lastTopicIdentifier, conductorData));
break;
case "hype-train-cooldown-expiration":
eventManager.publish(new HypeTrainCooldownExpirationEvent(lastTopicIdentifier));
break;
default:
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
break;
}
} else if ("community-points-user-v1".equals(topicName)) {
switch (type) {
case "points-earned":
final ChannelPointsEarned pointsEarned = TypeConvert.convertValue(msgData, ChannelPointsEarned.class);
eventManager.publish(new PointsEarnedEvent(pointsEarned));
break;
case "claim-available":
final ClaimData claimAvailable = TypeConvert.convertValue(msgData, ClaimData.class);
eventManager.publish(new ClaimAvailableEvent(claimAvailable));
break;
case "claim-claimed":
final ClaimData claimClaimed = TypeConvert.convertValue(msgData, ClaimData.class);
eventManager.publish(new ClaimClaimedEvent(claimClaimed));
break;
case "points-spent":
final PointsSpent pointsSpent = TypeConvert.convertValue(msgData, PointsSpent.class);
eventManager.publish(new PointsSpentEvent(pointsSpent));
break;
case "reward-redeemed":
final ChannelPointsRedemption redemption = TypeConvert.convertValue(msgData.path("redemption"), ChannelPointsRedemption.class);
eventManager.publish(new RewardRedeemedEvent(Instant.parse(msgData.path("timestamp").asText()), redemption));
break;
case "global-last-viewed-content-updated":
case "channel-last-viewed-content-updated":
// unimportant
break;
default:
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
break;
}
} else if ("leaderboard-events-v1".equals(topicName)) {
final Leaderboard leaderboard = TypeConvert.jsonToObject(rawMessage, Leaderboard.class);
switch (leaderboard.getIdentifier().getDomain()) {
case "bits-usage-by-channel-v1":
eventManager.publish(new BitsLeaderboardEvent(leaderboard));
break;
case "sub-gifts-sent":
eventManager.publish(new SubLeaderboardEvent(leaderboard));
break;
default:
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
break;
}
} else if ("user-moderation-notifications".equals(topicName)) {
if (topicParts.length == 3 && "automod_caught_message".equalsIgnoreCase(type)) {
UserAutomodCaughtMessage data = TypeConvert.convertValue(msgData, UserAutomodCaughtMessage.class);
eventManager.publish(new UserAutomodCaughtMessageEvent(topicParts[1], topicParts[2], data));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("polls".equals(topicName)) {
PollData pollData = TypeConvert.convertValue(msgData.path("poll"), PollData.class);
eventManager.publish(new PollsEvent(type, pollData));
} else if ("predictions-channel-v1".equals(topicName)) {
if ("event-created".equals(type)) {
eventManager.publish(TypeConvert.convertValue(msgData, PredictionCreatedEvent.class));
} else if ("event-updated".equals(type)) {
eventManager.publish(TypeConvert.convertValue(msgData, PredictionUpdatedEvent.class));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("predictions-user-v1".equals(topicName)) {
if ("prediction-made".equals(type)) {
eventManager.publish(TypeConvert.convertValue(msgData, UserPredictionMadeEvent.class));
} else if ("prediction-result".equals(type)) {
eventManager.publish(TypeConvert.convertValue(msgData, UserPredictionResultEvent.class));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("friendship".equals(topicName)) {
eventManager.publish(new FriendshipEvent(TypeConvert.jsonToObject(rawMessage, FriendshipData.class)));
} else if ("presence".equals(topicName) && topicParts.length > 1) {
if ("presence".equalsIgnoreCase(type)) {
eventManager.publish(new UserPresenceEvent(TypeConvert.convertValue(msgData, PresenceData.class)));
} else if ("settings".equalsIgnoreCase(type)) {
PresenceSettings presenceSettings = TypeConvert.convertValue(msgData, PresenceSettings.class);
eventManager.publish(new PresenceSettingsEvent(lastTopicIdentifier, presenceSettings));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("radio-events-v1".equals(topicName)) {
eventManager.publish(new RadioEvent(TypeConvert.jsonToObject(rawMessage, RadioData.class)));
} else if ("channel-sub-gifts-v1".equals(topicName)) {
eventManager.publish(new ChannelSubGiftEvent(TypeConvert.jsonToObject(rawMessage, SubGiftData.class)));
} else if ("channel-cheer-events-public-v1".equals(topicName) && topicParts.length > 1) {
if ("cheerbomb".equalsIgnoreCase(type)) {
CheerbombData cheerbomb = TypeConvert.convertValue(msgData, CheerbombData.class);
eventManager.publish(new CheerbombEvent(lastTopicIdentifier, cheerbomb));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("onsite-notifications".equals(topicName) && topicParts.length > 1) {
if ("create-notification".equalsIgnoreCase(type)) {
eventManager.publish(new OnsiteNotificationCreationEvent(TypeConvert.convertValue(msgData, CreateNotificationData.class)));
} else if ("update-summary".equalsIgnoreCase(type)) {
UpdateSummaryData data = TypeConvert.convertValue(msgData, UpdateSummaryData.class);
eventManager.publish(new UpdateOnsiteNotificationSummaryEvent(lastTopicIdentifier, data));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if (("video-playback-by-id".equals(topicName) || "video-playback".equals(topicName)) && topicParts.length > 1) {
boolean hasId = topicName.endsWith("d");
VideoPlaybackData data = TypeConvert.jsonToObject(rawMessage, VideoPlaybackData.class);
eventManager.publish(new VideoPlaybackEvent(hasId ? lastTopicIdentifier : null, hasId ? null : lastTopicIdentifier, data));
} else if ("channel-unban-requests".equals(topicName) && topicParts.length == 3) {
String userId = topicParts[1];
String channelId = topicParts[2];
if ("create_unban_request".equals(type)) {
CreatedUnbanRequest request = TypeConvert.convertValue(msgData, CreatedUnbanRequest.class);
eventManager.publish(new ChannelUnbanRequestCreateEvent(userId, channelId, request));
} else if ("update_unban_request".equals(type)) {
UpdatedUnbanRequest request = TypeConvert.convertValue(msgData, UpdatedUnbanRequest.class);
eventManager.publish(new ChannelUnbanRequestUpdateEvent(userId, channelId, request));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("user-unban-requests".equals(topicName) && topicParts.length == 3) {
String userId = topicParts[1];
String channelId = topicParts[2];
if ("update_unban_request".equals(type)) {
UpdatedUnbanRequest request = TypeConvert.convertValue(msgData, UpdatedUnbanRequest.class);
eventManager.publish(new UserUnbanRequestUpdateEvent(userId, channelId, request));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if (message.getType().equals(PubSubType.RESPONSE)) {
eventManager.publish(new PubSubListenResponseEvent(message.getNonce(), message.getError()));
// topic subscription success or failed, response to listen command
// System.out.println(message.toString());
if (message.getError().length() > 0) {
if (message.getError().equalsIgnoreCase("ERR_BADAUTH")) {
log.error("PubSub: You used a invalid oauth token to subscribe to the topic. Please use a token that is authorized for the specified channel.");
} else {
log.error("PubSub: Failed to subscribe to topic - [" + message.getError() + "]");
}
}
} else if (message.getType().equals(PubSubType.PONG)) {
log.debug("PubSub: Received PONG response!");
lastPong = TimeUtils.getCurrentTimeInMillis();
} else if (message.getType().equals(PubSubType.RECONNECT)) {
log.warn("PubSub: Server instance we're connected to will go down for maintenance soon, reconnecting to obtain a new connection!");
reconnect();
} else {
// unknown message
log.debug("PubSub: Unknown Message Type: " + message);
}
} catch (Exception ex) {
log.warn("PubSub: Unparsable Message: " + text + " - [" + ex.getMessage() + "]");
ex.printStackTrace();
}
}
@Override
public void onDisconnected(WebSocket websocket,
WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame,
boolean closedByServer) {
if (!connectionState.equals(TMIConnectionState.DISCONNECTING)) {
log.info("Connection to Twitch PubSub lost (WebSocket)! Retrying soon ...");
// connection lost - reconnecting
if (backoffClearer != null) backoffClearer.cancel(false);
taskExecutor.schedule(() -> reconnect(), backoff.get(), TimeUnit.MILLISECONDS);
} else {
connectionState = TMIConnectionState.DISCONNECTED;
log.info("Disconnected from Twitch PubSub (WebSocket)!");
}
}
});
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
}
/**
* Send WS Message
*
* @param command IRC Command
*/
private void sendCommand(String command) {
// will send command if connection has been established
if (connectionState.equals(TMIConnectionState.CONNECTED) || connectionState.equals(TMIConnectionState.CONNECTING)) {
// command will be uppercase.
this.webSocket.sendText(command);
} else {
log.warn("Can't send IRC-WS Command [{}]", command);
}
}
/**
* Queue PubSub request
*
* @param request PubSub request (or Topic)
*/
private void queueRequest(PubSubRequest request) {
commandQueue.add(TypeConvert.objectToJson(request));
// Expedite command execution if we aren't already flushing the queue and another expedition hasn't already been requested
if (!flushing.get() && !flushRequested.getAndSet(true))
taskExecutor.schedule(this.flushCommand, 50L, TimeUnit.MILLISECONDS); // allow for some accumulation of requests before flushing
}
@Override
public PubSubSubscription listenOnTopic(PubSubRequest request) {
if (subscribedTopics.add(request))
queueRequest(request);
return new PubSubSubscription(request);
}
@Override
public boolean unsubscribeFromTopic(PubSubSubscription subscription) {
PubSubRequest request = subscription.getRequest();
if (request.getType() != PubSubType.LISTEN) {
log.warn("Cannot unsubscribe using request with unexpected type: {}", request.getType());
return false;
}
boolean removed = subscribedTopics.remove(request);
if (!removed) {
log.warn("Not subscribed to topic: {}", request);
return false;
}
// use data from original request and send UNLISTEN
PubSubRequest unlistenRequest = new PubSubRequest();
unlistenRequest.setType(PubSubType.UNLISTEN);
unlistenRequest.setNonce(CryptoUtils.generateNonce(30));
unlistenRequest.setData(request.getData());
queueRequest(unlistenRequest);
return true;
}
/**
* Close
*/
@Override
public void close() {
if (!isClosed) {
isClosed = true;
heartbeatTask.cancel(false);
queueTask.cancel(false);
disconnect();
}
}
}
| pubsub/src/main/java/com/github/twitch4j/pubsub/TwitchPubSub.java | package com.github.twitch4j.pubsub;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.github.philippheuer.events4j.core.EventManager;
import com.github.twitch4j.common.config.ProxyConfig;
import com.github.twitch4j.common.enums.CommandPermission;
import com.github.twitch4j.common.events.domain.EventUser;
import com.github.twitch4j.common.events.user.PrivateMessageEvent;
import com.github.twitch4j.common.util.CryptoUtils;
import com.github.twitch4j.common.util.ExponentialBackoffStrategy;
import com.github.twitch4j.common.util.TimeUtils;
import com.github.twitch4j.common.util.TwitchUtils;
import com.github.twitch4j.common.util.TypeConvert;
import com.github.twitch4j.pubsub.domain.*;
import com.github.twitch4j.pubsub.enums.PubSubType;
import com.github.twitch4j.pubsub.enums.TMIConnectionState;
import com.github.twitch4j.pubsub.events.*;
import com.neovisionaries.ws.client.WebSocket;
import com.neovisionaries.ws.client.WebSocketAdapter;
import com.neovisionaries.ws.client.WebSocketFactory;
import com.neovisionaries.ws.client.WebSocketFrame;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import java.time.Duration;
import java.time.Instant;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Twitch PubSub
*/
@Slf4j
public class TwitchPubSub implements ITwitchPubSub {
public static final int REQUIRED_THREAD_COUNT = 1;
private static final Pattern LISTEN_AUTH_TOKEN = Pattern.compile("(\\{.*\"type\"\\s*?:\\s*?\"LISTEN\".*\"data\"\\s*?:\\s*?\\{.*\"auth_token\"\\s*?:\\s*?\").+(\".*}\\s*?})");
/**
* EventManager
*/
@Getter
private final EventManager eventManager;
/**
* The WebSocket Server
*/
private static final String WEB_SOCKET_SERVER = "wss://pubsub-edge.twitch.tv:443";
/**
* WebSocket Client
*/
@Setter(AccessLevel.NONE)
private volatile WebSocket webSocket;
/**
* The connection state
* Default: ({@link TMIConnectionState#DISCONNECTED})
*/
private volatile TMIConnectionState connectionState = TMIConnectionState.DISCONNECTED;
/**
* Whether {@link #flushCommand} is currently executing
*/
private final AtomicBoolean flushing = new AtomicBoolean();
/**
* Whether an expedited flush has already been submitted
*/
private final AtomicBoolean flushRequested = new AtomicBoolean();
/**
* The {@link Runnable} for flushing the {@link #commandQueue}
*/
private final Runnable flushCommand;
/**
* Command Queue Thread
*/
protected final Future<?> queueTask;
/**
* Heartbeat Thread
*/
protected final Future<?> heartbeatTask;
/**
* is Closed?
*/
protected volatile boolean isClosed = false;
/**
* Command Queue
*/
protected final BlockingQueue<String> commandQueue = new ArrayBlockingQueue<>(200);
/**
* Holds the subscribed topics in case we need to reconnect
*/
protected final Set<PubSubRequest> subscribedTopics = ConcurrentHashMap.newKeySet();
/**
* Last Ping send (1 minute delay before sending the first ping)
*/
protected volatile long lastPing = TimeUtils.getCurrentTimeInMillis() - 4 * 60 * 1000;
/**
* Last Pong received
*/
protected volatile long lastPong = TimeUtils.getCurrentTimeInMillis();
/**
* Thread Pool Executor
*/
protected final ScheduledExecutorService taskExecutor;
/**
* Bot Owner IDs
*/
private final Collection<String> botOwnerIds;
/**
* WebSocket Factory
*/
protected final WebSocketFactory webSocketFactory;
/**
* Helper class to compute delays between connection retries.
* <p>
* Configured to (approximately) emulate first-party clients:
* <ul>
* <li>initially waits one second</li>
* <li>plus a small random jitter</li>
* <li>doubles the backoff period on subsequent failures</li>
* <li>up to a maximum backoff threshold of 2 minutes</li>
* </ul>
*
* @see <a href="https://dev.twitch.tv/docs/pubsub#connection-management">Official documentation - Handling Connection Failures</a>
*/
protected final ExponentialBackoffStrategy backoff = ExponentialBackoffStrategy.builder()
.immediateFirst(false)
.baseMillis(Duration.ofSeconds(1).toMillis())
.jitter(true)
.multiplier(2.0)
.maximumBackoff(Duration.ofMinutes(2).toMillis())
.build();
/**
* Calls {@link ExponentialBackoffStrategy#reset()} upon a successful websocket connection
*/
private volatile Future<?> backoffClearer;
/**
* Constructor
*
* @param eventManager EventManager
* @param taskExecutor ScheduledThreadPoolExecutor
* @param proxyConfig ProxyConfig
* @param botOwnerIds Bot Owner IDs
*/
public TwitchPubSub(EventManager eventManager, ScheduledThreadPoolExecutor taskExecutor, ProxyConfig proxyConfig, Collection<String> botOwnerIds) {
this.taskExecutor = taskExecutor;
this.botOwnerIds = botOwnerIds;
this.eventManager = eventManager;
// register with serviceMediator
this.eventManager.getServiceMediator().addService("twitch4j-pubsub", this);
// WebSocket Factory and proxy settings
this.webSocketFactory = new WebSocketFactory();
if (proxyConfig != null)
proxyConfig.applyWs(webSocketFactory.getProxySettings());
// connect
this.connect();
// Run heartbeat every 4 minutes
heartbeatTask = taskExecutor.scheduleAtFixedRate(() -> {
if (isClosed || connectionState != TMIConnectionState.CONNECTED)
return;
PubSubRequest request = new PubSubRequest();
request.setType(PubSubType.PING);
sendCommand(TypeConvert.objectToJson(request));
log.debug("PubSub: Sending PING!");
lastPing = TimeUtils.getCurrentTimeInMillis();
}, 0, 4L, TimeUnit.MINUTES);
// Runnable for flushing the command queue
this.flushCommand = () -> {
// Only allow a single thread to flush at a time
if (flushing.getAndSet(true))
return;
// Attempt to flush the queue
while (!isClosed) {
try {
// check for missing pong response
if (lastPong < lastPing && TimeUtils.getCurrentTimeInMillis() >= lastPing + 10000) {
log.warn("PubSub: Didn't receive a PONG response in time, reconnecting to obtain a connection to a different server.");
reconnect();
break;
}
// If connected, send one message from the queue
if (connectionState.equals(TMIConnectionState.CONNECTED)) {
String command = commandQueue.poll();
if (command != null) {
sendCommand(command);
// Logging
if (log.isDebugEnabled()) {
Matcher matcher = LISTEN_AUTH_TOKEN.matcher(command);
String cmd = matcher.find() ? matcher.group(1) + "\u2022\u2022\u2022" + matcher.group(2) : command;
log.debug("Processed command from queue: [{}].", cmd);
}
} else {
break; // try again later
}
} else {
break; // try again later
}
} catch (Exception ex) {
log.error("PubSub: Unexpected error in worker thread", ex);
break;
}
}
// Indicate that flushing has completed
flushRequested.set(false);
flushing.set(false);
};
// queue command worker
this.queueTask = taskExecutor.scheduleWithFixedDelay(flushCommand, 0, 2500L, TimeUnit.MILLISECONDS);
log.debug("PubSub: Started Queue Worker Thread");
}
/**
* Connecting to IRC-WS
*/
@Synchronized
public void connect() {
if (connectionState.equals(TMIConnectionState.DISCONNECTED) || connectionState.equals(TMIConnectionState.RECONNECTING)) {
try {
// Change Connection State
connectionState = TMIConnectionState.CONNECTING;
// Recreate Socket if state does not equal CREATED
createWebSocket();
// Reset last ping to avoid edge case loop where reconnect occurred after sending PING but before receiving PONG
this.lastPing = TimeUtils.getCurrentTimeInMillis() - 4 * 60 * 1000;
// Connect to IRC WebSocket
this.webSocket.connect();
} catch (Exception ex) {
log.error("PubSub: Connection to Twitch PubSub failed: {} - Retrying ...", ex.getMessage());
if (backoffClearer != null) {
try {
backoffClearer.cancel(false);
} catch (Exception ignored) {
}
}
// Sleep before trying to reconnect
try {
backoff.sleep();
} catch (Exception ignored) {
} finally {
// reconnect
reconnect();
}
}
}
}
/**
* Disconnecting from WebSocket
*/
@Synchronized
public void disconnect() {
if (connectionState.equals(TMIConnectionState.CONNECTED)) {
connectionState = TMIConnectionState.DISCONNECTING;
}
connectionState = TMIConnectionState.DISCONNECTED;
// CleanUp
if (webSocket != null) {
this.webSocket.clearListeners();
this.webSocket.disconnect();
this.webSocket = null;
}
if (backoffClearer != null) {
backoffClearer.cancel(false);
}
}
/**
* Reconnecting to WebSocket
*/
@Synchronized
public void reconnect() {
connectionState = TMIConnectionState.RECONNECTING;
disconnect();
connect();
}
/**
* Recreate the WebSocket and the listeners
*/
@Synchronized
private void createWebSocket() {
try {
// WebSocket
this.webSocket = webSocketFactory.createSocket(WEB_SOCKET_SERVER);
// WebSocket Listeners
this.webSocket.clearListeners();
this.webSocket.addListener(new WebSocketAdapter() {
@Override
public void onConnected(WebSocket ws, Map<String, List<String>> headers) {
log.info("Connecting to Twitch PubSub {}", WEB_SOCKET_SERVER);
// Connection Success
connectionState = TMIConnectionState.CONNECTED;
backoffClearer = taskExecutor.schedule(() -> {
if (connectionState == TMIConnectionState.CONNECTED)
backoff.reset();
}, 30, TimeUnit.SECONDS);
log.info("Connected to Twitch PubSub {}", WEB_SOCKET_SERVER);
// resubscribe to all topics after disconnect
// This involves nonce reuse, which is bad cryptography, but not a serious problem for this context
// To avoid reuse, we can:
// 0) stop other threads from updating subscribedTopics
// 1) create a new PubSubRequest for each element of subscribedTopics (with a new nonce)
// 2) clear subscribedTopics
// 3) allow other threads to update subscribedTopics again
// 4) send unlisten requests for the old elements of subscribedTopics (optional?)
// 5) call listenOnTopic for each new PubSubRequest
subscribedTopics.forEach(topic -> queueRequest(topic));
}
@Override
public void onTextMessage(WebSocket ws, String text) {
try {
log.trace("Received WebSocketMessage: " + text);
// parse message
PubSubResponse message = TypeConvert.jsonToObject(text, PubSubResponse.class);
if (message.getType().equals(PubSubType.MESSAGE)) {
String topic = message.getData().getTopic();
String[] topicParts = StringUtils.split(topic, '.');
String topicName = topicParts[0];
String lastTopicIdentifier = topicParts[topicParts.length - 1];
String type = message.getData().getMessage().getType();
JsonNode msgData = message.getData().getMessage().getMessageData();
String rawMessage = message.getData().getMessage().getRawMessage();
// Handle Messages
if ("channel-bits-events-v2".equals(topicName)) {
eventManager.publish(new ChannelBitsEvent(TypeConvert.convertValue(msgData, ChannelBitsData.class)));
} else if ("channel-bits-badge-unlocks".equals(topicName)) {
eventManager.publish(new ChannelBitsBadgeUnlockEvent(TypeConvert.jsonToObject(rawMessage, BitsBadgeData.class)));
} else if ("channel-subscribe-events-v1".equals(topicName)) {
eventManager.publish(new ChannelSubscribeEvent(TypeConvert.jsonToObject(rawMessage, SubscriptionData.class)));
} else if ("channel-commerce-events-v1".equals(topicName)) {
eventManager.publish(new ChannelCommerceEvent(TypeConvert.jsonToObject(rawMessage, CommerceData.class)));
} else if ("whispers".equals(topicName) && (type.equals("whisper_sent") || type.equals("whisper_received"))) {
// Whisper data is escaped Json cast into a String
JsonNode msgDataParsed = TypeConvert.jsonToObject(msgData.asText(), JsonNode.class);
//TypeReference<T> allows type parameters (unlike Class<T>) and avoids needing @SuppressWarnings("unchecked")
Map<String, Object> tags = TypeConvert.convertValue(msgDataParsed.path("tags"), new TypeReference<Map<String, Object>>() {});
String fromId = msgDataParsed.get("from_id").asText();
String displayName = (String) tags.get("display_name");
EventUser eventUser = new EventUser(fromId, displayName);
String body = msgDataParsed.get("body").asText();
Set<CommandPermission> permissions = TwitchUtils.getPermissionsFromTags(tags, new HashMap<>(), fromId, botOwnerIds);
PrivateMessageEvent privateMessageEvent = new PrivateMessageEvent(eventUser, body, permissions);
eventManager.publish(privateMessageEvent);
} else if ("automod-levels-modification".equals(topicName) && topicParts.length > 1) {
if ("automod_levels_modified".equals(type)) {
AutomodLevelsModified data = TypeConvert.convertValue(msgData, AutomodLevelsModified.class);
eventManager.publish(new AutomodLevelsModifiedEvent(lastTopicIdentifier, data));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("automod-queue".equals(topicName)) {
if (topicParts.length == 3 && "automod_caught_message".equalsIgnoreCase(type)) {
AutomodCaughtMessageData data = TypeConvert.convertValue(msgData, AutomodCaughtMessageData.class);
eventManager.publish(new AutomodCaughtMessageEvent(topicParts[2], data));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("community-boost-events-v1".equals(topicName)) {
if ("community-boost-progression".equals(type)) {
CommunityBoostProgression progression = TypeConvert.convertValue(msgData, CommunityBoostProgression.class);
eventManager.publish(new CommunityBoostProgressionEvent(progression));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("community-points-channel-v1".equals(topicName) || "channel-points-channel-v1".equals(topicName)) {
String timestampText = msgData.path("timestamp").asText();
Instant instant = Instant.parse(timestampText);
switch (type) {
case "reward-redeemed":
ChannelPointsRedemption redemption = TypeConvert.convertValue(msgData.path("redemption"), ChannelPointsRedemption.class);
eventManager.publish(new RewardRedeemedEvent(instant, redemption));
break;
case "redemption-status-update":
ChannelPointsRedemption updatedRedemption = TypeConvert.convertValue(msgData.path("redemption"), ChannelPointsRedemption.class);
eventManager.publish(new RedemptionStatusUpdateEvent(instant, updatedRedemption));
break;
case "custom-reward-created":
ChannelPointsReward newReward = TypeConvert.convertValue(msgData.path("new_reward"), ChannelPointsReward.class);
eventManager.publish(new CustomRewardCreatedEvent(instant, newReward));
break;
case "custom-reward-updated":
ChannelPointsReward updatedReward = TypeConvert.convertValue(msgData.path("updated_reward"), ChannelPointsReward.class);
eventManager.publish(new CustomRewardUpdatedEvent(instant, updatedReward));
break;
case "custom-reward-deleted":
ChannelPointsReward deletedReward = TypeConvert.convertValue(msgData.path("deleted_reward"), ChannelPointsReward.class);
eventManager.publish(new CustomRewardDeletedEvent(instant, deletedReward));
break;
case "update-redemption-statuses-progress":
RedemptionProgress redemptionProgress = TypeConvert.convertValue(msgData.path("progress"), RedemptionProgress.class);
eventManager.publish(new UpdateRedemptionProgressEvent(instant, redemptionProgress));
break;
case "update-redemption-statuses-finished":
RedemptionProgress redemptionFinished = TypeConvert.convertValue(msgData.path("progress"), RedemptionProgress.class);
eventManager.publish(new UpdateRedemptionFinishedEvent(instant, redemptionFinished));
break;
case "community-goal-contribution":
CommunityGoalContribution contribution = TypeConvert.convertValue(msgData.path("contribution"), CommunityGoalContribution.class);
eventManager.publish(new CommunityGoalContributionEvent(instant, contribution));
break;
default:
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
break;
}
} else if ("crowd-chant-channel-v1".equals(topicName)) {
if ("crowd-chant-created".equals(type)) {
CrowdChantCreatedEvent event = TypeConvert.convertValue(msgData, CrowdChantCreatedEvent.class);
eventManager.publish(event);
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("raid".equals(topicName)) {
switch (type) {
case "raid_go_v2":
eventManager.publish(TypeConvert.jsonToObject(rawMessage, RaidGoEvent.class));
break;
case "raid_update_v2":
eventManager.publish(TypeConvert.jsonToObject(rawMessage, RaidUpdateEvent.class));
break;
case "raid_cancel_v2":
eventManager.publish(TypeConvert.jsonToObject(rawMessage, RaidCancelEvent.class));
break;
default:
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
break;
}
} else if ("chat_moderator_actions".equals(topicName) && topicParts.length > 1) {
switch (type) {
case "moderation_action":
ChatModerationAction modAction = TypeConvert.convertValue(msgData, ChatModerationAction.class);
eventManager.publish(new ChatModerationEvent(lastTopicIdentifier, modAction));
break;
case "channel_terms_action":
ChannelTermsAction termsAction = TypeConvert.convertValue(msgData, ChannelTermsAction.class);
eventManager.publish(new ChannelTermsEvent(lastTopicIdentifier, termsAction));
break;
case "approve_unban_request":
case "deny_unban_request":
ModeratorUnbanRequestAction unbanRequestAction = TypeConvert.convertValue(msgData, ModeratorUnbanRequestAction.class);
eventManager.publish(new ModUnbanRequestActionEvent(lastTopicIdentifier, unbanRequestAction));
break;
default:
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
break;
}
} else if ("following".equals(topicName) && topicParts.length > 1) {
final FollowingData data = TypeConvert.jsonToObject(rawMessage, FollowingData.class);
eventManager.publish(new FollowingEvent(lastTopicIdentifier, data));
} else if ("hype-train-events-v1".equals(topicName) && topicParts.length > 2 && "rewards".equals(topicParts[1])) {
eventManager.publish(new HypeTrainRewardsEvent(TypeConvert.convertValue(msgData, HypeTrainRewardsData.class)));
} else if ("hype-train-events-v1".equals(topicName) && topicParts.length > 1) {
switch (type) {
case "hype-train-approaching":
final HypeTrainApproaching approachData = TypeConvert.convertValue(msgData, HypeTrainApproaching.class);
eventManager.publish(new HypeTrainApproachingEvent(approachData));
break;
case "hype-train-start":
final HypeTrainStart startData = TypeConvert.convertValue(msgData, HypeTrainStart.class);
eventManager.publish(new HypeTrainStartEvent(startData));
break;
case "hype-train-progression":
final HypeProgression progressionData = TypeConvert.convertValue(msgData, HypeProgression.class);
eventManager.publish(new HypeTrainProgressionEvent(lastTopicIdentifier, progressionData));
break;
case "hype-train-level-up":
final HypeLevelUp levelUpData = TypeConvert.convertValue(msgData, HypeLevelUp.class);
eventManager.publish(new HypeTrainLevelUpEvent(lastTopicIdentifier, levelUpData));
break;
case "hype-train-end":
final HypeTrainEnd endData = TypeConvert.convertValue(msgData, HypeTrainEnd.class);
eventManager.publish(new HypeTrainEndEvent(lastTopicIdentifier, endData));
break;
case "hype-train-conductor-update":
final HypeTrainConductor conductorData = TypeConvert.convertValue(msgData, HypeTrainConductor.class);
eventManager.publish(new HypeTrainConductorUpdateEvent(lastTopicIdentifier, conductorData));
break;
case "hype-train-cooldown-expiration":
eventManager.publish(new HypeTrainCooldownExpirationEvent(lastTopicIdentifier));
break;
default:
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
break;
}
} else if ("community-points-user-v1".equals(topicName)) {
switch (type) {
case "points-earned":
final ChannelPointsEarned pointsEarned = TypeConvert.convertValue(msgData, ChannelPointsEarned.class);
eventManager.publish(new PointsEarnedEvent(pointsEarned));
break;
case "claim-available":
final ClaimData claimAvailable = TypeConvert.convertValue(msgData, ClaimData.class);
eventManager.publish(new ClaimAvailableEvent(claimAvailable));
break;
case "claim-claimed":
final ClaimData claimClaimed = TypeConvert.convertValue(msgData, ClaimData.class);
eventManager.publish(new ClaimClaimedEvent(claimClaimed));
break;
case "points-spent":
final PointsSpent pointsSpent = TypeConvert.convertValue(msgData, PointsSpent.class);
eventManager.publish(new PointsSpentEvent(pointsSpent));
break;
case "reward-redeemed":
final ChannelPointsRedemption redemption = TypeConvert.convertValue(msgData.path("redemption"), ChannelPointsRedemption.class);
eventManager.publish(new RewardRedeemedEvent(Instant.parse(msgData.path("timestamp").asText()), redemption));
break;
case "global-last-viewed-content-updated":
case "channel-last-viewed-content-updated":
// unimportant
break;
default:
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
break;
}
} else if ("leaderboard-events-v1".equals(topicName)) {
final Leaderboard leaderboard = TypeConvert.jsonToObject(rawMessage, Leaderboard.class);
switch (leaderboard.getIdentifier().getDomain()) {
case "bits-usage-by-channel-v1":
eventManager.publish(new BitsLeaderboardEvent(leaderboard));
break;
case "sub-gifts-sent":
eventManager.publish(new SubLeaderboardEvent(leaderboard));
break;
default:
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
break;
}
} else if ("user-moderation-notifications".equals(topicName)) {
if (topicParts.length == 3 && "automod_caught_message".equalsIgnoreCase(type)) {
UserAutomodCaughtMessage data = TypeConvert.convertValue(msgData, UserAutomodCaughtMessage.class);
eventManager.publish(new UserAutomodCaughtMessageEvent(topicParts[1], topicParts[2], data));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("polls".equals(topicName)) {
PollData pollData = TypeConvert.convertValue(msgData.path("poll"), PollData.class);
eventManager.publish(new PollsEvent(type, pollData));
} else if ("predictions-channel-v1".equals(topicName)) {
if ("event-created".equals(type)) {
eventManager.publish(TypeConvert.convertValue(msgData, PredictionCreatedEvent.class));
} else if ("event-updated".equals(type)) {
eventManager.publish(TypeConvert.convertValue(msgData, PredictionUpdatedEvent.class));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("predictions-user-v1".equals(topicName)) {
if ("prediction-made".equals(type)) {
eventManager.publish(TypeConvert.convertValue(msgData, UserPredictionMadeEvent.class));
} else if ("prediction-result".equals(type)) {
eventManager.publish(TypeConvert.convertValue(msgData, UserPredictionResultEvent.class));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("friendship".equals(topicName)) {
eventManager.publish(new FriendshipEvent(TypeConvert.jsonToObject(rawMessage, FriendshipData.class)));
} else if ("presence".equals(topicName) && topicParts.length > 1) {
if ("presence".equalsIgnoreCase(type)) {
eventManager.publish(new UserPresenceEvent(TypeConvert.convertValue(msgData, PresenceData.class)));
} else if ("settings".equalsIgnoreCase(type)) {
PresenceSettings presenceSettings = TypeConvert.convertValue(msgData, PresenceSettings.class);
eventManager.publish(new PresenceSettingsEvent(lastTopicIdentifier, presenceSettings));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("radio-events-v1".equals(topicName)) {
eventManager.publish(new RadioEvent(TypeConvert.jsonToObject(rawMessage, RadioData.class)));
} else if ("channel-sub-gifts-v1".equals(topicName)) {
eventManager.publish(new ChannelSubGiftEvent(TypeConvert.jsonToObject(rawMessage, SubGiftData.class)));
} else if ("channel-cheer-events-public-v1".equals(topicName) && topicParts.length > 1) {
if ("cheerbomb".equalsIgnoreCase(type)) {
CheerbombData cheerbomb = TypeConvert.convertValue(msgData, CheerbombData.class);
eventManager.publish(new CheerbombEvent(lastTopicIdentifier, cheerbomb));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("onsite-notifications".equals(topicName) && topicParts.length > 1) {
if ("create-notification".equalsIgnoreCase(type)) {
eventManager.publish(new OnsiteNotificationCreationEvent(TypeConvert.convertValue(msgData, CreateNotificationData.class)));
} else if ("update-summary".equalsIgnoreCase(type)) {
UpdateSummaryData data = TypeConvert.convertValue(msgData, UpdateSummaryData.class);
eventManager.publish(new UpdateOnsiteNotificationSummaryEvent(lastTopicIdentifier, data));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if (("video-playback-by-id".equals(topicName) || "video-playback".equals(topicName)) && topicParts.length > 1) {
boolean hasId = topicName.endsWith("d");
VideoPlaybackData data = TypeConvert.jsonToObject(rawMessage, VideoPlaybackData.class);
eventManager.publish(new VideoPlaybackEvent(hasId ? lastTopicIdentifier : null, hasId ? null : lastTopicIdentifier, data));
} else if ("channel-unban-requests".equals(topicName) && topicParts.length == 3) {
String userId = topicParts[1];
String channelId = topicParts[2];
if ("create_unban_request".equals(type)) {
CreatedUnbanRequest request = TypeConvert.convertValue(msgData, CreatedUnbanRequest.class);
eventManager.publish(new ChannelUnbanRequestCreateEvent(userId, channelId, request));
} else if ("update_unban_request".equals(type)) {
UpdatedUnbanRequest request = TypeConvert.convertValue(msgData, UpdatedUnbanRequest.class);
eventManager.publish(new ChannelUnbanRequestUpdateEvent(userId, channelId, request));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if ("user-unban-requests".equals(topicName) && topicParts.length == 3) {
String userId = topicParts[1];
String channelId = topicParts[2];
if ("update_unban_request".equals(type)) {
UpdatedUnbanRequest request = TypeConvert.convertValue(msgData, UpdatedUnbanRequest.class);
eventManager.publish(new UserUnbanRequestUpdateEvent(userId, channelId, request));
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else {
log.warn("Unparsable Message: " + message.getType() + "|" + message.getData());
}
} else if (message.getType().equals(PubSubType.RESPONSE)) {
eventManager.publish(new PubSubListenResponseEvent(message.getNonce(), message.getError()));
// topic subscription success or failed, response to listen command
// System.out.println(message.toString());
if (message.getError().length() > 0) {
if (message.getError().equalsIgnoreCase("ERR_BADAUTH")) {
log.error("PubSub: You used a invalid oauth token to subscribe to the topic. Please use a token that is authorized for the specified channel.");
} else {
log.error("PubSub: Failed to subscribe to topic - [" + message.getError() + "]");
}
}
} else if (message.getType().equals(PubSubType.PONG)) {
log.debug("PubSub: Received PONG response!");
lastPong = TimeUtils.getCurrentTimeInMillis();
} else if (message.getType().equals(PubSubType.RECONNECT)) {
log.warn("PubSub: Server instance we're connected to will go down for maintenance soon, reconnecting to obtain a new connection!");
reconnect();
} else {
// unknown message
log.debug("PubSub: Unknown Message Type: " + message);
}
} catch (Exception ex) {
log.warn("PubSub: Unparsable Message: " + text + " - [" + ex.getMessage() + "]");
ex.printStackTrace();
}
}
@Override
public void onDisconnected(WebSocket websocket,
WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame,
boolean closedByServer) {
if (!connectionState.equals(TMIConnectionState.DISCONNECTING)) {
log.info("Connection to Twitch PubSub lost (WebSocket)! Retrying soon ...");
// connection lost - reconnecting
if (backoffClearer != null) backoffClearer.cancel(false);
taskExecutor.schedule(() -> reconnect(), backoff.get(), TimeUnit.MILLISECONDS);
} else {
connectionState = TMIConnectionState.DISCONNECTED;
log.info("Disconnected from Twitch PubSub (WebSocket)!");
}
}
});
} catch (Exception ex) {
log.error(ex.getMessage(), ex);
}
}
/**
* Send WS Message
*
* @param command IRC Command
*/
private void sendCommand(String command) {
// will send command if connection has been established
if (connectionState.equals(TMIConnectionState.CONNECTED) || connectionState.equals(TMIConnectionState.CONNECTING)) {
// command will be uppercase.
this.webSocket.sendText(command);
} else {
log.warn("Can't send IRC-WS Command [{}]", command);
}
}
/**
* Queue PubSub request
*
* @param request PubSub request (or Topic)
*/
private void queueRequest(PubSubRequest request) {
commandQueue.add(TypeConvert.objectToJson(request));
// Expedite command execution if we aren't already flushing the queue and another expedition hasn't already been requested
if (!flushing.get() && !flushRequested.getAndSet(true))
taskExecutor.schedule(this.flushCommand, 50L, TimeUnit.MILLISECONDS); // allow for some accumulation of requests before flushing
}
@Override
public PubSubSubscription listenOnTopic(PubSubRequest request) {
if (subscribedTopics.add(request))
queueRequest(request);
return new PubSubSubscription(request);
}
@Override
public boolean unsubscribeFromTopic(PubSubSubscription subscription) {
PubSubRequest request = subscription.getRequest();
if (request.getType() != PubSubType.LISTEN) {
log.warn("Cannot unsubscribe using request with unexpected type: {}", request.getType());
return false;
}
boolean removed = subscribedTopics.remove(request);
if (!removed) {
log.warn("Not subscribed to topic: {}", request);
return false;
}
// use data from original request and send UNLISTEN
PubSubRequest unlistenRequest = new PubSubRequest();
unlistenRequest.setType(PubSubType.UNLISTEN);
unlistenRequest.setNonce(CryptoUtils.generateNonce(30));
unlistenRequest.setData(request.getData());
queueRequest(unlistenRequest);
return true;
}
/**
* Close
*/
@Override
public void close() {
if (!isClosed) {
isClosed = true;
heartbeatTask.cancel(false);
queueTask.cancel(false);
disconnect();
}
}
}
| fix: resolve another rare pubsub looping edge case (#411)
| pubsub/src/main/java/com/github/twitch4j/pubsub/TwitchPubSub.java | fix: resolve another rare pubsub looping edge case (#411) |
|
Java | mit | 2331d3388fc2c797a9564bb762a0780575a8b67e | 0 | osiam/connector4java | /*
* Copyright (C) 2013 tarent AG
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.osiam.resources.scim;
/**
* Some needed Constants
*/
public interface Constants {
String USER_CORE_SCHEMA = "urn:scim:schemas:core:2.0:User";
String GROUP_CORE_SCHEMA = "urn:scim:schemas:core:2.0:Group";
String LIST_RESPONSE_CORE_SCHEMA = "urn:ietf:params:scim:api:messages:2.0:ListResponse";
String SERVICE_PROVIDER_CORE_SCHEMA = "urn:scim:schemas:core:2.0:ServiceProviderConfig";
int MAX_RESULT = 100;
}
| scim-schema/src/main/java/org/osiam/resources/scim/Constants.java | /*
* Copyright (C) 2013 tarent AG
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.osiam.resources.scim;
/**
* Some needed Constants
*/
public interface Constants {
String USER_CORE_SCHEMA = "urn:scim:schemas:core:2.0:User";
String GROUP_CORE_SCHEMA = "urn:scim:schemas:core:2.0:Group";
String SERVICE_PROVIDER_CORE_SCHEMA = "urn:scim:schemas:core:2.0:ServiceProviderConfig";
int MAX_RESULT = 100;
} | Introduce Constant representing ListResponse
Related to osiam/resource-server#33
| scim-schema/src/main/java/org/osiam/resources/scim/Constants.java | Introduce Constant representing ListResponse |
|
Java | agpl-3.0 | 35ee6aee29f136ddacfbef563f36d6370efc180c | 0 | imCodePartnerAB/imcms,imCodePartnerAB/imcms,imCodePartnerAB/imcms | package com.imcode.imcms.domain.service.api;
import com.imcode.imcms.WebAppSpringTestConfig;
import com.imcode.imcms.api.CategoryAlreadyExistsException;
import com.imcode.imcms.domain.dto.CategoryDTO;
import com.imcode.imcms.domain.dto.CategoryTypeDTO;
import com.imcode.imcms.domain.service.CategoryService;
import com.imcode.imcms.domain.service.CategoryTypeService;
import com.imcode.imcms.model.Category;
import com.imcode.imcms.model.CategoryType;
import com.imcode.imcms.persistence.entity.CategoryTypeJPA;
import com.imcode.imcms.persistence.repository.CategoryTypeRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertThrows;
@Transactional
public class CategoryTypeServiceTest extends WebAppSpringTestConfig {
@Autowired
private CategoryTypeService categoryTypeService;
@Autowired
private CategoryTypeRepository categoryTypeRepository;
@Autowired
private CategoryService categoryService;
@Test
public void get_When_CategoryTypeExists_Expect_Found() {
final CategoryTypeDTO categoryTypeDTO = createCategoryType();
final Optional<CategoryType> foundType = categoryTypeService.get(categoryTypeDTO.getId());
assertTrue(foundType.isPresent());
assertEquals(foundType.get(), categoryTypeDTO);
}
@Test
public void getAll_WhenCategoryTypeExists_Expected_CorrectEntities() {
categoryTypeRepository.deleteAll();
assertTrue(categoryTypeRepository.findAll().isEmpty());
final List<CategoryType> categoryTypes = categoriesTypesInit(2);
assertEquals(categoryTypes.size(), categoryTypeService.getAll().size());
assertNotNull(categoryTypeService.getAll());
}
@Test
public void create_When_CategoryTypeNotExists_Expected_Saved() {
final CategoryTypeDTO categoryTypeDTO = createCategoryType();
assertNotNull(categoryTypeDTO);
assertTrue(categoryTypeService.getAll().contains(categoryTypeDTO));
}
@Test
public void create_When_CategoryTypeNameAlreadyExists_Expected_CorrectException() {
final CategoryTypeDTO categoryTypeDTO = createCategoryType();
assertNotNull(categoryTypeDTO);
final CategoryType categoryType = new CategoryTypeJPA(
categoryTypeDTO.getName(), 0, false, false
);
assertThrows(DataIntegrityViolationException.class, () -> categoryTypeService.create(categoryType));
}
@Test
public void create_When_CategoryTypeNameEmpty_Expected_CorrectException() {
final CategoryType categoryType = new CategoryTypeJPA(
null, "", 0, false, false
);
assertThrows(IllegalArgumentException.class, () -> categoryTypeService.create(categoryType));
}
@Test
public void update_When_CategoryTypeExists_Expected_UpdateEntity() {
final CategoryTypeDTO categoryTypeDTO = createCategoryType();
categoryTypeDTO.setName("Other Test Name");
final CategoryType updated = categoryTypeService.update(categoryTypeDTO);
assertNotNull(updated);
assertEquals(categoryTypeDTO.getId(), updated.getId());
}
@Test
public void update_When_CategoryTypeNameDuplicated_Expected_CorrectException() {
final List<CategoryType> categoryTypes = categoriesTypesInit(2);
final CategoryType categoryType = categoryTypes.get(0);
categoryType.setName(categoryTypes.get(1).getName());
assertEquals(categoryType.getName(), categoryTypes.get(1).getName());
assertThrows(DataIntegrityViolationException.class, () -> categoryTypeService.update(categoryType));
}
@Test
public void delete_When_CategoryTypeHasNotCategories_Expected_Deleted() {
final CategoryTypeDTO categoryTypeDTO = createCategoryType();
final Integer savedId = categoryTypeDTO.getId();
Optional<CategoryType> foundType = categoryTypeService.get(savedId);
assertTrue(foundType.isPresent());
categoryTypeService.delete(foundType.get().getId());
foundType = categoryTypeService.get(savedId);
assertFalse(foundType.isPresent());
}
@Test
public void delete_When_CategoriesExists_Expected_CorrectException() {
final CategoryTypeDTO categoryTypeDTO = createCategoryType();
createCategory(categoryTypeDTO);
assertThrows(CategoryAlreadyExistsException.class, () -> categoryTypeService.delete(categoryTypeDTO.getId()));
}
private CategoryTypeDTO createCategoryType() {
String name = "test_type_name" + System.currentTimeMillis();
int maxChoices = 0;
boolean inherited = false;
boolean imageArchive = false;
final CategoryTypeJPA categoryType = new CategoryTypeJPA(
null, name, maxChoices, inherited, imageArchive
);
return new CategoryTypeDTO(categoryTypeService.create(categoryType));
}
private List<CategoryType> categoriesTypesInit(int countElements) {
return IntStream.range(0, countElements)
.mapToObj(i -> new CategoryTypeJPA("CategoryType" + i + "Name", 0, false, false))
.map(categoryTypeRepository::saveAndFlush)
.collect(Collectors.toList());
}
private Category createCategory(CategoryTypeDTO categoryTypeDTO) {
final CategoryDTO categoryDTO = new CategoryDTO(
null, "name", "description", "url", categoryTypeDTO
);
return categoryService.save(categoryDTO);
}
}
| src/test/java/com/imcode/imcms/domain/service/api/CategoryTypeServiceTest.java | package com.imcode.imcms.domain.service.api;
import com.imcode.imcms.WebAppSpringTestConfig;
import com.imcode.imcms.api.CategoryAlreadyExistsException;
import com.imcode.imcms.domain.dto.CategoryDTO;
import com.imcode.imcms.domain.dto.CategoryTypeDTO;
import com.imcode.imcms.domain.service.CategoryService;
import com.imcode.imcms.domain.service.CategoryTypeService;
import com.imcode.imcms.model.Category;
import com.imcode.imcms.model.CategoryType;
import com.imcode.imcms.persistence.entity.CategoryTypeJPA;
import com.imcode.imcms.persistence.repository.CategoryTypeRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static org.junit.Assert.*;
import static org.junit.jupiter.api.Assertions.assertThrows;
@Transactional
public class CategoryTypeServiceTest extends WebAppSpringTestConfig {
@Autowired
private CategoryTypeService categoryTypeService;
@Autowired
private CategoryTypeRepository categoryTypeRepository;
@Autowired
private CategoryService categoryService;
@Test
public void get_When_CategoryTypeExists_Expect_Found() {
CategoryTypeDTO categoryTypeDTO = createCategoryType();
final Optional<CategoryType> foundType = categoryTypeService.get(categoryTypeDTO.getId());
assertTrue(foundType.isPresent());
assertEquals(foundType.get(), categoryTypeDTO);
}
@Test
public void getAll_WhenCategoryTypeExists_Expected_CorrectEntities() {
categoryTypeRepository.deleteAll();
assertTrue(categoryTypeRepository.findAll().isEmpty());
final List<CategoryType> categoryTypes = categoriesTypesInit(2);
assertEquals(categoryTypes.size(), categoryTypeService.getAll().size());
assertNotNull(categoryTypeService.getAll());
}
@Test
public void create_When_CategoryTypeNotExists_Expected_Saved() {
CategoryTypeDTO categoryTypeDTO = createCategoryType();
assertNotNull(categoryTypeDTO);
assertTrue(categoryTypeService.getAll().contains(categoryTypeDTO));
}
@Test
public void create_When_CategoryTypeNameAlreadyExists_Expected_CorrectException() {
CategoryTypeDTO categoryTypeDTO = createCategoryType();
assertNotNull(categoryTypeDTO);
final CategoryType categoryType = new CategoryTypeJPA(
categoryTypeDTO.getName(), 0, false, false
);
assertThrows(DataIntegrityViolationException.class, () -> categoryTypeService.create(categoryType));
}
@Test
public void create_When_CategoryTypeNameEmpty_Expected_CorrectException() {
final CategoryType categoryType = new CategoryTypeJPA(
null, "", 0, false, false
);
assertThrows(IllegalArgumentException.class, () -> categoryTypeService.create(categoryType));
}
@Test
public void update_When_CategoryTypeExists_Expected_UpdateEntity() {
CategoryTypeDTO categoryTypeDTO = createCategoryType();
categoryTypeDTO.setName("Other Test Name");
final CategoryType updated = categoryTypeService.update(categoryTypeDTO);
assertNotNull(updated);
assertEquals(categoryTypeDTO.getId(), updated.getId());
}
@Test
public void update_When_CategoryTypeNameDuplicated_Expected_CorrectException() {
final CategoryTypeDTO categoryTypeDTO1 = createCategoryType();
final CategoryTypeDTO categoryTypeDTO2 = createCategoryType();
assertNotEquals(categoryTypeDTO1, categoryTypeDTO2);
categoryTypeDTO1.setName(categoryTypeDTO2.getName());
assertEquals(categoryTypeDTO1.getName(), categoryTypeDTO2.getName());
assertThrows(DataIntegrityViolationException.class, () -> categoryTypeService.update(categoryTypeDTO1));
}
@Test
public void delete_When_CategoryTypeHasNotCategories_Expected_Deleted() {
final CategoryTypeDTO categoryTypeDTO = createCategoryType();
final Integer savedId = categoryTypeDTO.getId();
Optional<CategoryType> foundType = categoryTypeService.get(savedId);
assertTrue(foundType.isPresent());
categoryTypeService.delete(foundType.get().getId());
foundType = categoryTypeService.get(savedId);
assertFalse(foundType.isPresent());
}
@Test
public void delete_When_CategoriesExists_Expected_CorrectException() {
final CategoryTypeDTO categoryTypeDTO = createCategoryType();
createCategory(categoryTypeDTO);
assertThrows(CategoryAlreadyExistsException.class, () -> categoryTypeService.delete(categoryTypeDTO.getId()));
}
private CategoryTypeDTO createCategoryType() {
String name = "test_type_name" + System.currentTimeMillis();
int maxChoices = 0;
boolean inherited = false;
boolean imageArchive = false;
final CategoryTypeJPA categoryType = new CategoryTypeJPA(
null, name, maxChoices, inherited, imageArchive
);
return new CategoryTypeDTO(categoryTypeService.create(categoryType));
}
private List<CategoryType> categoriesTypesInit(int countElements) {
return IntStream.range(0, countElements)
.mapToObj(i -> new CategoryTypeJPA("CategoryType" + i + "Name", 0, false, false))
.map(categoryTypeRepository::saveAndFlush)
.collect(Collectors.toList());
}
private Category createCategory(CategoryTypeDTO categoryTypeDTO) {
final CategoryDTO categoryDTO = new CategoryDTO(
null, "name", "description", "url", categoryTypeDTO
);
return categoryService.save(categoryDTO);
}
}
| IMCMS-335 New design to super admin page: categories tab
- Refactor and fixed update test
| src/test/java/com/imcode/imcms/domain/service/api/CategoryTypeServiceTest.java | IMCMS-335 New design to super admin page: categories tab - Refactor and fixed update test |
|
Java | apache-2.0 | 7e375a5cfc6a9ceefde02e5699c1cd112b92fc36 | 0 | korpling/ANNIS,amir-zeldes/ANNIS,korpling/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,korpling/ANNIS,zangsir/ANNIS,zangsir/ANNIS,zangsir/ANNIS,zangsir/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,pixeldrama/ANNIS,korpling/ANNIS,korpling/ANNIS,zangsir/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,amir-zeldes/ANNIS,pixeldrama/ANNIS,pixeldrama/ANNIS | /*
* Copyright 2011 Corpuslinguistic working group Humboldt University Berlin
*
* 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 annis.libgui;
import annis.libgui.media.MediaController;
import annis.libgui.visualizers.VisualizerPlugin;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import com.google.common.hash.Hashing;
import com.sun.jersey.api.client.Client;
import com.vaadin.annotations.Theme;
import com.vaadin.server.ClassResource;
import com.vaadin.server.RequestHandler;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinResponse;
import com.vaadin.server.VaadinService;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.UI;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.xeoh.plugins.base.Plugin;
import net.xeoh.plugins.base.PluginManager;
import net.xeoh.plugins.base.impl.PluginManagerFactory;
import net.xeoh.plugins.base.util.PluginManagerUtil;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
import org.slf4j.LoggerFactory;
import org.slf4j.bridge.SLF4JBridgeHandler;
import org.vaadin.cssinject.CSSInject;
/**
* Basic UI functionality.
*
* This class allows to out source some common tasks like initialization of
* the logging framework or the plugin loading to this base class.
*/
@Theme("annis")
public class AnnisBaseUI extends UI implements PluginSystem, Serializable
{
static
{
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
}
private static final org.slf4j.Logger log = LoggerFactory.getLogger(
AnnisBaseUI.class);
public final static String USER_KEY = "annis.gui.AnnisBaseUI:USER_KEY";
public final static String USER_LOGIN_ERROR = "annis.gui.AnnisBaseUI:USER_LOGIN_ERROR";
public final static String CONTEXT_PATH = "annis.gui.AnnisBaseUI:CONTEXT_PATH";
public final static String WEBSERVICEURL_KEY = "annis.gui.AnnisBaseUI:WEBSERVICEURL_KEY";
public final static String CITATION_KEY = "annis.gui.AnnisBaseUI:CITATION_KEY";
private transient PluginManager pluginManager;
private static final Map<String, VisualizerPlugin> visualizerRegistry =
Collections.synchronizedMap(new HashMap<String, VisualizerPlugin>());
private static final Map<String, Date> resourceAddedDate =
Collections.synchronizedMap(new HashMap<String, Date>());
private Properties versionProperties;
private transient MediaController mediaController;
private transient ObjectMapper jsonMapper;
private transient TreeSet<String> alreadyAddedCSS;
private final Lock pushThrottleLock = new ReentrantLock();
private transient Timer pushTimer;
private long lastPushTime;
public static final long MINIMUM_PUSH_WAIT_TIME = 1000;
private AtomicInteger pushCounter = new AtomicInteger();
private transient TimerTask pushTask;
@Override
protected void init(VaadinRequest request)
{
initLogging();
// load some additional properties from our ANNIS configuration
loadApplicationProperties("annis-gui.properties");
// store the webservice URL property explicitly in the session in order to
// access it from the "external" servlets
getSession().getSession().setAttribute(WEBSERVICEURL_KEY,
getSession().getAttribute(Helper.KEY_WEB_SERVICE_URL));
getSession().setAttribute(CONTEXT_PATH, request.getContextPath());
// get version of ANNIS
ClassResource res = new ClassResource(AnnisBaseUI.class, "version.properties");
versionProperties = new Properties();
try
{
versionProperties.load(res.getStream().getStream());
getSession().setAttribute("annis-version", getVersion());
}
catch (Exception ex)
{
log.error(null, ex);
}
initPlugins();
checkIfRemoteLoggedIn(request);
getSession().addRequestHandler(new RemoteUserRequestHandler());
}
/**
* Given an configuration file name (might include directory) this function
* returns all locations for this file in the "ANNIS configuration system".
*
* The files in the result list do not necessarily exist.
*
* These locations are the
* - base installation: WEB-INF/conf/ folder of the deployment.
* - global configuration: $ANNIS_CFG environment variable value or /etc/annis/ if not set
* - user configuration: ~/.annis/
* @param configFile The file path of the configuration file relative to the base config folder.
* @return list of files or directories in the order in which they should be processed (most important is last)
*/
protected List<File> getAllConfigLocations(String configFile)
{
LinkedList<File> locations = new LinkedList<File>();
// first load everything from the base application
locations.add(new File(VaadinService.getCurrent().getBaseDirectory(),
"/WEB-INF/conf/" + configFile));
// next everything from the global config
// When ANNIS_CFG environment variable is set use this value or default to
// "/etc/annis/
String globalConfigDir = System.getenv("ANNIS_CFG");
if (globalConfigDir == null)
{
globalConfigDir = "/etc/annis";
}
locations.add(new File(globalConfigDir + "/" + configFile));
// the final and most specific user configuration is in the users home directory
locations.add(new File(
System.getProperty("user.home") + "/.annis/" + configFile));
return locations;
}
protected void loadApplicationProperties(String configFile)
{
List<File> locations = getAllConfigLocations(configFile);
// load properties in the right order
for(File f : locations)
{
loadPropertyFile(f);
}
}
protected Map<String, InstanceConfig> loadInstanceConfig()
{
TreeMap<String, InstanceConfig> result = new TreeMap<String, InstanceConfig>();
// get a list of all directories that contain instance informations
List<File> locations = getAllConfigLocations("instances");
for(File root : locations)
{
if(root.isDirectory())
{
// get all sub-files ending on ".json"
File[] instanceFiles =
root.listFiles((FilenameFilter) new SuffixFileFilter(".json"));
for(File i : instanceFiles)
{
if(i.isFile() && i.canRead())
{
try
{
InstanceConfig config = getJsonMapper().readValue(i, InstanceConfig.class);
String name = StringUtils.removeEnd(i.getName(), ".json");
config.setInstanceName(name);
result.put(name, config);
}
catch (IOException ex)
{
log.warn("could not parsing instance config: " + ex.getMessage());
}
}
}
}
}
// always provide a default instance
if(!result.containsKey("default"))
{
InstanceConfig cfgDefault = new InstanceConfig();
cfgDefault.setInstanceDisplayName("ANNIS");
result.put("default", cfgDefault);
}
return result;
}
private void loadPropertyFile(File f)
{
if(f.canRead() && f.isFile())
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(f);
Properties p = new Properties();
p.load(fis);
// copy all properties to the session
for(String name : p.stringPropertyNames())
{
getSession().setAttribute(name, p.getProperty(name));
}
}
catch(IOException ex)
{
}
finally
{
if(fis != null)
{
try
{
fis.close();
}
catch(IOException ex)
{
log.error("could not close stream", ex);
}
}
}
}
}
protected final void initLogging()
{
try
{
List<File> logbackFiles = getAllConfigLocations("gui-logback.xml");
InputStream inStream = null;
if(!logbackFiles.isEmpty())
{
try
{
inStream = new FileInputStream(logbackFiles.get(logbackFiles.size()-1));
}
catch(FileNotFoundException ex)
{
// well no logging no error...
}
}
if(inStream == null)
{
ClassResource res = new ClassResource(AnnisBaseUI.class, "logback.xml");
inStream = res.getStream().getStream();
}
if (inStream != null)
{
LoggerContext context = (LoggerContext) LoggerFactory.
getILoggerFactory();
JoranConfigurator jc = new JoranConfigurator();
jc.setContext(context);
context.reset();
context.putProperty("webappHome",
VaadinService.getCurrent().getBaseDirectory().getAbsolutePath());
// load config file
jc.doConfigure(inStream);
}
}
catch (JoranException ex)
{
log.error("init logging failed", ex);
}
}
public String getBuildRevision()
{
String result = versionProperties.getProperty("build_revision", "");
return result;
}
public String getVersion()
{
String rev = getBuildRevision();
Date date = getBuildDate();
StringBuilder result = new StringBuilder();
result.append(getVersionNumber());
if (!"".equals(rev) || date != null)
{
result.append(" (");
boolean added = false;
if (!"".equals(rev))
{
result.append("rev. ");
result.append(rev);
added = true;
}
if (date != null)
{
result.append(added ? ", built " : "");
SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
result.append(d.format(date));
}
result.append(")");
}
return result.toString();
}
public String getVersionNumber()
{
return versionProperties.getProperty("version", "UNKNOWNVERSION");
}
public Date getBuildDate()
{
Date result = null;
try
{
DateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
result = format.parse(versionProperties.getProperty("build_date"));
}
catch (Exception ex)
{
log.debug(null, ex);
}
return result;
}
/**
* Override this method to append additional plugins to the internal {@link PluginManager}.
*
* The default implementation is empty
* (thus you don't need to call {@code super.addCustomUIPlugins(...)}).
* @param pluginManager
*/
protected void addCustomUIPlugins(PluginManager pluginManager)
{
// default: do nothing
}
private void initPlugins()
{
log.info("Adding plugins");
pluginManager = PluginManagerFactory.createPluginManager();
addCustomUIPlugins(pluginManager);
File baseDir = VaadinService.getCurrent().getBaseDirectory();
File builtin = new File(baseDir, "WEB-INF/lib/annis-visualizers-"
+ getVersionNumber() + ".jar");
pluginManager.addPluginsFrom(builtin.toURI());
log.info("added plugins from {}", builtin.getPath());
File basicPlugins = new File(baseDir, "WEB-INF/plugins");
if (basicPlugins.isDirectory())
{
pluginManager.addPluginsFrom(basicPlugins.toURI());
log.info("added plugins from {}", basicPlugins.getPath());
}
String globalPlugins = System.getenv("ANNIS_PLUGINS");
if (globalPlugins != null)
{
pluginManager.addPluginsFrom(new File(globalPlugins).toURI());
log.info("added plugins from {}", globalPlugins);
}
StringBuilder listOfPlugins = new StringBuilder();
listOfPlugins.append("loaded plugins:\n");
PluginManagerUtil util = new PluginManagerUtil(pluginManager);
for (Plugin p : util.getPlugins())
{
listOfPlugins.append(p.getClass().getName()).append("\n");
}
log.info(listOfPlugins.toString());
Collection<VisualizerPlugin> visualizers = util.getPlugins(
VisualizerPlugin.class);
for (VisualizerPlugin vis : visualizers)
{
visualizerRegistry.put(vis.getShortName(), vis);
resourceAddedDate.put(vis.getShortName(), new Date());
}
}
private void checkIfRemoteLoggedIn(VaadinRequest request)
{
// check if we are logged in using an external authentification mechanism
// like Schibboleth
String remoteUser = request.getRemoteUser();
if(remoteUser != null)
{
// treat as anonymous user
Client client = Helper.createRESTClient();;
Helper.setUser(new AnnisUser(remoteUser, client, true));
}
}
@Override
public void push()
{
pushThrottleLock.lock();
try
{
long currentTime = System.currentTimeMillis();
long timeSinceLastPush = currentTime - lastPushTime;
if (pushTask == null)
{
if (timeSinceLastPush >= MINIMUM_PUSH_WAIT_TIME)
{
// push directly
super.push();
lastPushTime = System.currentTimeMillis();
log.debug("direct push #{} executed", pushCounter.getAndIncrement());
}
else
{
// schedule a new task
long waitTime = Math.max(0, MINIMUM_PUSH_WAIT_TIME - timeSinceLastPush);
pushTask = new TimerTask()
{
@Override
public void run()
{
pushThrottleLock.lock();
try
{
AnnisBaseUI.super.push();
lastPushTime = System.currentTimeMillis();
pushTask = null;
log.debug("Throttled push #{} executed", pushCounter.
getAndIncrement());
}
finally
{
pushThrottleLock.unlock();
}
}
};
getPushTimer().schedule(pushTask, waitTime);
log.debug("Push scheduled to be executed in {} ms", waitTime);
}
}
else
{
log.debug("no push executed since another one is already running");
}
}
finally
{
pushThrottleLock.unlock();
}
}
public Timer getPushTimer()
{
if(pushTimer == null)
{
pushTimer = new Timer("Push Timer");
}
return pushTimer;
}
@Override
public void close()
{
if (pluginManager != null)
{
pluginManager.shutdown();
}
super.close();
}
/**
* Inject CSS into the UI.
* This function will not add multiple style-elements if the
* exact CSS string was already added.
* @param cssContent
*/
public void injectUniqueCSS(String cssContent)
{
if(alreadyAddedCSS == null)
{
alreadyAddedCSS = new TreeSet<String>();
}
String hashForCssContent = Hashing.md5().hashString(cssContent).toString();
if(!alreadyAddedCSS.contains(hashForCssContent))
{
CSSInject cssInject = new CSSInject(UI.getCurrent());
cssInject.setStyles(cssContent);
alreadyAddedCSS.add(hashForCssContent);
}
}
@Override
public PluginManager getPluginManager()
{
if (pluginManager == null)
{
initPlugins();
}
return pluginManager;
}
@Override
public VisualizerPlugin getVisualizer(String shortName)
{
return visualizerRegistry.get(shortName);
}
public ObjectMapper getJsonMapper()
{
if(jsonMapper == null)
{
jsonMapper = new ObjectMapper();
// configure json object mapper
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
jsonMapper.setAnnotationIntrospector(introspector);
// the json should be human readable
jsonMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT,
true);
}
return jsonMapper;
}
private class RemoteUserRequestHandler implements RequestHandler
{
@Override
public boolean handleRequest(VaadinSession session, VaadinRequest request,
VaadinResponse response) throws IOException
{
checkIfRemoteLoggedIn(request);
// we never write any information in this handler
return false;
}
}
} | annis-libgui/src/main/java/annis/libgui/AnnisBaseUI.java | /*
* Copyright 2011 Corpuslinguistic working group Humboldt University Berlin
*
* 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 annis.libgui;
import annis.libgui.media.MediaController;
import annis.libgui.visualizers.VisualizerPlugin;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import com.google.common.hash.Hashing;
import com.sun.jersey.api.client.Client;
import com.vaadin.annotations.Theme;
import com.vaadin.server.ClassResource;
import com.vaadin.server.RequestHandler;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinResponse;
import com.vaadin.server.VaadinService;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.UI;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.xeoh.plugins.base.Plugin;
import net.xeoh.plugins.base.PluginManager;
import net.xeoh.plugins.base.impl.PluginManagerFactory;
import net.xeoh.plugins.base.util.PluginManagerUtil;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.map.AnnotationIntrospector;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;
import org.slf4j.LoggerFactory;
import org.slf4j.bridge.SLF4JBridgeHandler;
import org.vaadin.cssinject.CSSInject;
/**
* Basic UI functionality.
*
* This class allows to out source some common tasks like initialization of
* the logging framework or the plugin loading to this base class.
*/
@Theme("annis")
public class AnnisBaseUI extends UI implements PluginSystem, Serializable
{
static
{
SLF4JBridgeHandler.removeHandlersForRootLogger();
SLF4JBridgeHandler.install();
}
private static final org.slf4j.Logger log = LoggerFactory.getLogger(
AnnisBaseUI.class);
public final static String USER_KEY = "annis.gui.AnnisBaseUI:USER_KEY";
public final static String USER_LOGIN_ERROR = "annis.gui.AnnisBaseUI:USER_LOGIN_ERROR";
public final static String CONTEXT_PATH = "annis.gui.AnnisBaseUI:CONTEXT_PATH";
public final static String WEBSERVICEURL_KEY = "annis.gui.AnnisBaseUI:WEBSERVICEURL_KEY";
public final static String CITATION_KEY = "annis.gui.AnnisBaseUI:CITATION_KEY";
private transient PluginManager pluginManager;
private static final Map<String, VisualizerPlugin> visualizerRegistry =
Collections.synchronizedMap(new HashMap<String, VisualizerPlugin>());
private static final Map<String, Date> resourceAddedDate =
Collections.synchronizedMap(new HashMap<String, Date>());
private Properties versionProperties;
private transient MediaController mediaController;
private transient ObjectMapper jsonMapper;
private transient TreeSet<String> alreadyAddedCSS;
private final Lock pushThrottleLock = new ReentrantLock();
private transient Timer pushTimer;
private long lastPushTime;
public static final long MINIMUM_PUSH_WAIT_TIME = 1000;
private AtomicInteger pushCounter = new AtomicInteger();
private transient TimerTask pushTask;
private transient Properties remoteUserPasswords = new Properties();
@Override
protected void init(VaadinRequest request)
{
initLogging();
// load some additional properties from our ANNIS configuration
loadApplicationProperties("annis-gui.properties");
loadRemoteUserPasswords();
// store the webservice URL property explicitly in the session in order to
// access it from the "external" servlets
getSession().getSession().setAttribute(WEBSERVICEURL_KEY,
getSession().getAttribute(Helper.KEY_WEB_SERVICE_URL));
getSession().setAttribute(CONTEXT_PATH, request.getContextPath());
// get version of ANNIS
ClassResource res = new ClassResource(AnnisBaseUI.class, "version.properties");
versionProperties = new Properties();
try
{
versionProperties.load(res.getStream().getStream());
getSession().setAttribute("annis-version", getVersion());
}
catch (Exception ex)
{
log.error(null, ex);
}
initPlugins();
checkIfRemoteLoggedIn(request);
getSession().addRequestHandler(new RemoteUserRequestHandler());
}
private void loadRemoteUserPasswords()
{
remoteUserPasswords = new Properties();
List<File> locations = getAllConfigLocations("remote-users.properties");
for(File f : locations)
{
if(f.isFile() && f.canRead())
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(f);
try
{
remoteUserPasswords.load(fis);
}
catch(IOException ex)
{
log.warn("could not read a remote-users.properties file", ex);
}
}
catch (FileNotFoundException ex)
{
log.warn("remote user file not found, even it was existing just moments ago", ex);
}
finally
{
try
{
if(fis != null)
{
fis.close();
}
}
catch (IOException ex)
{
log.error(null, ex);
}
}
}
} // end for each found file
}
/**
* Given an configuration file name (might include directory) this function
* returns all locations for this file in the "ANNIS configuration system".
*
* The files in the result list do not necessarily exist.
*
* These locations are the
* - base installation: WEB-INF/conf/ folder of the deployment.
* - global configuration: $ANNIS_CFG environment variable value or /etc/annis/ if not set
* - user configuration: ~/.annis/
* @param configFile The file path of the configuration file relative to the base config folder.
* @return list of files or directories in the order in which they should be processed (most important is last)
*/
protected List<File> getAllConfigLocations(String configFile)
{
LinkedList<File> locations = new LinkedList<File>();
// first load everything from the base application
locations.add(new File(VaadinService.getCurrent().getBaseDirectory(),
"/WEB-INF/conf/" + configFile));
// next everything from the global config
// When ANNIS_CFG environment variable is set use this value or default to
// "/etc/annis/
String globalConfigDir = System.getenv("ANNIS_CFG");
if (globalConfigDir == null)
{
globalConfigDir = "/etc/annis";
}
locations.add(new File(globalConfigDir + "/" + configFile));
// the final and most specific user configuration is in the users home directory
locations.add(new File(
System.getProperty("user.home") + "/.annis/" + configFile));
return locations;
}
protected void loadApplicationProperties(String configFile)
{
List<File> locations = getAllConfigLocations(configFile);
// load properties in the right order
for(File f : locations)
{
loadPropertyFile(f);
}
}
protected Map<String, InstanceConfig> loadInstanceConfig()
{
TreeMap<String, InstanceConfig> result = new TreeMap<String, InstanceConfig>();
// get a list of all directories that contain instance informations
List<File> locations = getAllConfigLocations("instances");
for(File root : locations)
{
if(root.isDirectory())
{
// get all sub-files ending on ".json"
File[] instanceFiles =
root.listFiles((FilenameFilter) new SuffixFileFilter(".json"));
for(File i : instanceFiles)
{
if(i.isFile() && i.canRead())
{
try
{
InstanceConfig config = getJsonMapper().readValue(i, InstanceConfig.class);
String name = StringUtils.removeEnd(i.getName(), ".json");
config.setInstanceName(name);
result.put(name, config);
}
catch (IOException ex)
{
log.warn("could not parsing instance config: " + ex.getMessage());
}
}
}
}
}
// always provide a default instance
if(!result.containsKey("default"))
{
InstanceConfig cfgDefault = new InstanceConfig();
cfgDefault.setInstanceDisplayName("ANNIS");
result.put("default", cfgDefault);
}
return result;
}
private void loadPropertyFile(File f)
{
if(f.canRead() && f.isFile())
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(f);
Properties p = new Properties();
p.load(fis);
// copy all properties to the session
for(String name : p.stringPropertyNames())
{
getSession().setAttribute(name, p.getProperty(name));
}
}
catch(IOException ex)
{
}
finally
{
if(fis != null)
{
try
{
fis.close();
}
catch(IOException ex)
{
log.error("could not close stream", ex);
}
}
}
}
}
protected final void initLogging()
{
try
{
List<File> logbackFiles = getAllConfigLocations("gui-logback.xml");
InputStream inStream = null;
if(!logbackFiles.isEmpty())
{
try
{
inStream = new FileInputStream(logbackFiles.get(logbackFiles.size()-1));
}
catch(FileNotFoundException ex)
{
// well no logging no error...
}
}
if(inStream == null)
{
ClassResource res = new ClassResource(AnnisBaseUI.class, "logback.xml");
inStream = res.getStream().getStream();
}
if (inStream != null)
{
LoggerContext context = (LoggerContext) LoggerFactory.
getILoggerFactory();
JoranConfigurator jc = new JoranConfigurator();
jc.setContext(context);
context.reset();
context.putProperty("webappHome",
VaadinService.getCurrent().getBaseDirectory().getAbsolutePath());
// load config file
jc.doConfigure(inStream);
}
}
catch (JoranException ex)
{
log.error("init logging failed", ex);
}
}
public String getBuildRevision()
{
String result = versionProperties.getProperty("build_revision", "");
return result;
}
public String getVersion()
{
String rev = getBuildRevision();
Date date = getBuildDate();
StringBuilder result = new StringBuilder();
result.append(getVersionNumber());
if (!"".equals(rev) || date != null)
{
result.append(" (");
boolean added = false;
if (!"".equals(rev))
{
result.append("rev. ");
result.append(rev);
added = true;
}
if (date != null)
{
result.append(added ? ", built " : "");
SimpleDateFormat d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
result.append(d.format(date));
}
result.append(")");
}
return result.toString();
}
public String getVersionNumber()
{
return versionProperties.getProperty("version", "UNKNOWNVERSION");
}
public Date getBuildDate()
{
Date result = null;
try
{
DateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
result = format.parse(versionProperties.getProperty("build_date"));
}
catch (Exception ex)
{
log.debug(null, ex);
}
return result;
}
/**
* Override this method to append additional plugins to the internal {@link PluginManager}.
*
* The default implementation is empty
* (thus you don't need to call {@code super.addCustomUIPlugins(...)}).
* @param pluginManager
*/
protected void addCustomUIPlugins(PluginManager pluginManager)
{
// default: do nothing
}
private void initPlugins()
{
log.info("Adding plugins");
pluginManager = PluginManagerFactory.createPluginManager();
addCustomUIPlugins(pluginManager);
File baseDir = VaadinService.getCurrent().getBaseDirectory();
File builtin = new File(baseDir, "WEB-INF/lib/annis-visualizers-"
+ getVersionNumber() + ".jar");
pluginManager.addPluginsFrom(builtin.toURI());
log.info("added plugins from {}", builtin.getPath());
File basicPlugins = new File(baseDir, "WEB-INF/plugins");
if (basicPlugins.isDirectory())
{
pluginManager.addPluginsFrom(basicPlugins.toURI());
log.info("added plugins from {}", basicPlugins.getPath());
}
String globalPlugins = System.getenv("ANNIS_PLUGINS");
if (globalPlugins != null)
{
pluginManager.addPluginsFrom(new File(globalPlugins).toURI());
log.info("added plugins from {}", globalPlugins);
}
StringBuilder listOfPlugins = new StringBuilder();
listOfPlugins.append("loaded plugins:\n");
PluginManagerUtil util = new PluginManagerUtil(pluginManager);
for (Plugin p : util.getPlugins())
{
listOfPlugins.append(p.getClass().getName()).append("\n");
}
log.info(listOfPlugins.toString());
Collection<VisualizerPlugin> visualizers = util.getPlugins(
VisualizerPlugin.class);
for (VisualizerPlugin vis : visualizers)
{
visualizerRegistry.put(vis.getShortName(), vis);
resourceAddedDate.put(vis.getShortName(), new Date());
}
}
private void checkIfRemoteLoggedIn(VaadinRequest request)
{
// check if we are logged in using an external authentification mechanism
// like Schibboleth
String remoteUser = request.getRemoteUser();
if(remoteUser != null)
{
String password = null;
if(remoteUserPasswords != null)
{
password = remoteUserPasswords.getProperty(remoteUser, null);
}
Client client;
if(password == null)
{
// treat as anonymous user
client = Helper.createRESTClient();
}
else
{
// use the provided password
client = Helper.createRESTClient(remoteUser, password);
}
Helper.setUser(new AnnisUser(remoteUser, client, true));
}
}
@Override
public void push()
{
pushThrottleLock.lock();
try
{
long currentTime = System.currentTimeMillis();
long timeSinceLastPush = currentTime - lastPushTime;
if (pushTask == null)
{
if (timeSinceLastPush >= MINIMUM_PUSH_WAIT_TIME)
{
// push directly
super.push();
lastPushTime = System.currentTimeMillis();
log.debug("direct push #{} executed", pushCounter.getAndIncrement());
}
else
{
// schedule a new task
long waitTime = Math.max(0, MINIMUM_PUSH_WAIT_TIME - timeSinceLastPush);
pushTask = new TimerTask()
{
@Override
public void run()
{
pushThrottleLock.lock();
try
{
AnnisBaseUI.super.push();
lastPushTime = System.currentTimeMillis();
pushTask = null;
log.debug("Throttled push #{} executed", pushCounter.
getAndIncrement());
}
finally
{
pushThrottleLock.unlock();
}
}
};
getPushTimer().schedule(pushTask, waitTime);
log.debug("Push scheduled to be executed in {} ms", waitTime);
}
}
else
{
log.debug("no push executed since another one is already running");
}
}
finally
{
pushThrottleLock.unlock();
}
}
public Timer getPushTimer()
{
if(pushTimer == null)
{
pushTimer = new Timer("Push Timer");
}
return pushTimer;
}
@Override
public void close()
{
if (pluginManager != null)
{
pluginManager.shutdown();
}
super.close();
}
/**
* Inject CSS into the UI.
* This function will not add multiple style-elements if the
* exact CSS string was already added.
* @param cssContent
*/
public void injectUniqueCSS(String cssContent)
{
if(alreadyAddedCSS == null)
{
alreadyAddedCSS = new TreeSet<String>();
}
String hashForCssContent = Hashing.md5().hashString(cssContent).toString();
if(!alreadyAddedCSS.contains(hashForCssContent))
{
CSSInject cssInject = new CSSInject(UI.getCurrent());
cssInject.setStyles(cssContent);
alreadyAddedCSS.add(hashForCssContent);
}
}
@Override
public PluginManager getPluginManager()
{
if (pluginManager == null)
{
initPlugins();
}
return pluginManager;
}
@Override
public VisualizerPlugin getVisualizer(String shortName)
{
return visualizerRegistry.get(shortName);
}
public ObjectMapper getJsonMapper()
{
if(jsonMapper == null)
{
jsonMapper = new ObjectMapper();
// configure json object mapper
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
jsonMapper.setAnnotationIntrospector(introspector);
// the json should be human readable
jsonMapper.configure(SerializationConfig.Feature.INDENT_OUTPUT,
true);
}
return jsonMapper;
}
private class RemoteUserRequestHandler implements RequestHandler
{
@Override
public boolean handleRequest(VaadinSession session, VaadinRequest request,
VaadinResponse response) throws IOException
{
checkIfRemoteLoggedIn(request);
// we never write any information in this handler
return false;
}
}
} | do not implement the insecure "auto-login" feature
| annis-libgui/src/main/java/annis/libgui/AnnisBaseUI.java | do not implement the insecure "auto-login" feature |
|
Java | apache-2.0 | 4b84c125dc5e858c017f2af2d83c5cebd7de3ef8 | 0 | allotria/intellij-community,ivan-fedorov/intellij-community,da1z/intellij-community,clumsy/intellij-community,vladmm/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,izonder/intellij-community,retomerz/intellij-community,supersven/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,signed/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,dslomov/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,robovm/robovm-studio,adedayo/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,jagguli/intellij-community,signed/intellij-community,signed/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,samthor/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,xfournet/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,retomerz/intellij-community,izonder/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,michaelgallacher/intellij-community,diorcety/intellij-community,kdwink/intellij-community,holmes/intellij-community,blademainer/intellij-community,retomerz/intellij-community,Lekanich/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,da1z/intellij-community,fnouama/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,ryano144/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,alphafoobar/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,petteyg/intellij-community,asedunov/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,samthor/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,samthor/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,kool79/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,clumsy/intellij-community,Distrotech/intellij-community,adedayo/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,FHannes/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,slisson/intellij-community,jagguli/intellij-community,retomerz/intellij-community,hurricup/intellij-community,diorcety/intellij-community,ryano144/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,signed/intellij-community,kool79/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,MER-GROUP/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,apixandru/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,supersven/intellij-community,nicolargo/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,samthor/intellij-community,FHannes/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,caot/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,asedunov/intellij-community,vladmm/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,caot/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,clumsy/intellij-community,semonte/intellij-community,jagguli/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,petteyg/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,petteyg/intellij-community,clumsy/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,da1z/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,supersven/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,asedunov/intellij-community,signed/intellij-community,tmpgit/intellij-community,izonder/intellij-community,izonder/intellij-community,kool79/intellij-community,holmes/intellij-community,Distrotech/intellij-community,caot/intellij-community,adedayo/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,diorcety/intellij-community,FHannes/intellij-community,semonte/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,caot/intellij-community,ThiagoGarciaAlves/intellij-community,kool79/intellij-community,amith01994/intellij-community,supersven/intellij-community,blademainer/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,xfournet/intellij-community,vladmm/intellij-community,ryano144/intellij-community,slisson/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,petteyg/intellij-community,slisson/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,dslomov/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,caot/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,allotria/intellij-community,vladmm/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,amith01994/intellij-community,apixandru/intellij-community,FHannes/intellij-community,vladmm/intellij-community,amith01994/intellij-community,signed/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,da1z/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,wreckJ/intellij-community,holmes/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,jagguli/intellij-community,kool79/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,nicolargo/intellij-community,holmes/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,Lekanich/intellij-community,Lekanich/intellij-community,kool79/intellij-community,holmes/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,diorcety/intellij-community,hurricup/intellij-community,signed/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,da1z/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,signed/intellij-community,kdwink/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,da1z/intellij-community,kdwink/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,dslomov/intellij-community,jagguli/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,ivan-fedorov/intellij-community,xfournet/intellij-community,dslomov/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,semonte/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,pwoodworth/intellij-community,allotria/intellij-community,hurricup/intellij-community,MichaelNedzelsky/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,retomerz/intellij-community,adedayo/intellij-community,ibinti/intellij-community,xfournet/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,diorcety/intellij-community,adedayo/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,ftomassetti/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,caot/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,caot/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,signed/intellij-community,kool79/intellij-community,caot/intellij-community,akosyakov/intellij-community,supersven/intellij-community,allotria/intellij-community,kdwink/intellij-community,MER-GROUP/intellij-community,amith01994/intellij-community,diorcety/intellij-community,signed/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,retomerz/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,akosyakov/intellij-community,asedunov/intellij-community,tmpgit/intellij-community,allotria/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,ThiagoGarciaAlves/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,suncycheng/intellij-community,slisson/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,kdwink/intellij-community,FHannes/intellij-community,jagguli/intellij-community,robovm/robovm-studio,asedunov/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,retomerz/intellij-community,amith01994/intellij-community,robovm/robovm-studio,ibinti/intellij-community,vvv1559/intellij-community,semonte/intellij-community,dslomov/intellij-community,holmes/intellij-community,robovm/robovm-studio,holmes/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,izonder/intellij-community,fitermay/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,amith01994/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,semonte/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,caot/intellij-community,adedayo/intellij-community,lucafavatella/intellij-community,fnouama/intellij-community,muntasirsyed/intellij-community,mglukhikh/intellij-community,alphafoobar/intellij-community,wreckJ/intellij-community,amith01994/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,kool79/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,nicolargo/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,nicolargo/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,suncycheng/intellij-community,jagguli/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,hurricup/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,MER-GROUP/intellij-community,petteyg/intellij-community,blademainer/intellij-community,da1z/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,caot/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,supersven/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,blademainer/intellij-community,allotria/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,salguarnieri/intellij-community,jagguli/intellij-community,allotria/intellij-community,diorcety/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,xfournet/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,blademainer/intellij-community,izonder/intellij-community,dslomov/intellij-community,fitermay/intellij-community,signed/intellij-community,petteyg/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,SerCeMan/intellij-community,robovm/robovm-studio,pwoodworth/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,samthor/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,gnuhub/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,diorcety/intellij-community,adedayo/intellij-community,diorcety/intellij-community,slisson/intellij-community,petteyg/intellij-community,amith01994/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,da1z/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,kool79/intellij-community,supersven/intellij-community,clumsy/intellij-community,allotria/intellij-community,supersven/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,slisson/intellij-community,kdwink/intellij-community,slisson/intellij-community,ibinti/intellij-community,signed/intellij-community,clumsy/intellij-community,apixandru/intellij-community,da1z/intellij-community,dslomov/intellij-community,hurricup/intellij-community,signed/intellij-community,petteyg/intellij-community | /*
* Copyright 2000-2013 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 com.intellij.indentation;
import com.intellij.lang.ASTNode;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.PsiParser;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* User: Andrey.Vokin
* Date: 3/20/12
*/
public abstract class AbstractIndentParser implements PsiParser {
protected PsiBuilder myBuilder;
protected int myCurrentIndent;
protected HashMap<PsiBuilder.Marker, Integer> myIndents;
protected HashMap<PsiBuilder.Marker, Boolean> myNewLines;
protected boolean myNewLine = true;
@NotNull
public ASTNode parse(IElementType root, PsiBuilder builder) {
myNewLines = new HashMap<PsiBuilder.Marker, Boolean>();
myIndents = new HashMap<PsiBuilder.Marker, Integer>();
myBuilder = builder;
parseRoot(root);
return myBuilder.getTreeBuilt();
}
protected abstract void parseRoot(IElementType root);
public PsiBuilder.Marker mark(boolean couldBeRolledBack) {
final PsiBuilder.Marker marker = myBuilder.mark();
if (couldBeRolledBack) {
myIndents.put(marker, myCurrentIndent);
myNewLines.put(marker, myNewLine);
}
return marker;
}
public PsiBuilder.Marker mark() {
return mark(false);
}
public void done(@NotNull final PsiBuilder.Marker marker, @NotNull final IElementType elementType) {
myIndents.remove(marker);
myNewLines.remove(marker);
marker.done(elementType);
}
public static void collapse(@NotNull final PsiBuilder.Marker marker, @NotNull final IElementType elementType) {
marker.collapse(elementType);
}
protected static void drop(@NotNull final PsiBuilder.Marker marker) {
marker.drop();
}
protected void rollbackTo(@NotNull final PsiBuilder.Marker marker) {
if (myIndents.get(marker) == null) {
throw new RuntimeException("Parser can't rollback marker that was created by mark() method, use mark(true) instead");
}
myCurrentIndent = myIndents.get(marker);
myNewLine = myNewLines.get(marker);
myIndents.remove(marker);
myNewLines.remove(marker);
marker.rollbackTo();
}
protected boolean eof() {
return myBuilder.eof();
}
protected int getCurrentOffset() {
return myBuilder.getCurrentOffset();
}
public int getCurrentIndent() {
return myCurrentIndent;
}
protected void error(String message) {
myBuilder.error(message);
}
@Nullable
public IElementType getTokenType() {
return myBuilder.getTokenType();
}
protected static boolean tokenIn(@Nullable final IElementType elementType, IElementType... tokens) {
for (IElementType token : tokens) {
if (elementType == token) {
return true;
}
}
return false;
}
protected boolean currentTokenIn(IElementType... tokens) {
return tokenIn(getTokenType(), tokens);
}
protected boolean currentTokenIn(@NotNull final TokenSet tokenSet) {
return tokenSet.contains(getTokenType());
}
protected static boolean tokenIn(@Nullable final IElementType elementType, @NotNull final TokenSet tokenSet) {
return tokenSet.contains(elementType);
}
@NotNull
protected String getTokenText() {
String result = myBuilder.getTokenText();
if (result == null) {
result = "";
}
return result;
}
protected boolean expect(@NotNull final IElementType elementType) {
return expect(elementType, "Expected: " + elementType);
}
protected boolean expect(@NotNull final IElementType elementType, String expectedMessage) {
if (getTokenType() == elementType) {
advance();
return true;
}
error(expectedMessage);
return false;
}
@Nullable
public IElementType lookAhead(int step) {
return myBuilder.lookAhead(step);
}
@Nullable
public IElementType rawLookup(int step) {
return myBuilder.rawLookup(step);
}
public boolean isNewLine() {
return myNewLine;
}
public void advance() {
final String tokenText = myBuilder.getTokenText();
final int tokenLength = tokenText == null ? 0 : tokenText.length();
final int whiteSpaceStart = getCurrentOffset() + tokenLength;
myBuilder.advanceLexer();
final int whiteSpaceEnd = getCurrentOffset();
final String whiteSpaceText = myBuilder.getOriginalText().subSequence(whiteSpaceStart, whiteSpaceEnd).toString();
int i = whiteSpaceText.lastIndexOf('\n');
if (i >= 0) {
myCurrentIndent = whiteSpaceText.length() - i - 1;
myNewLine = true;
}
else {
myNewLine = false;
}
}
protected void advanceUntil(TokenSet tokenSet) {
while (getTokenType() != null && !isNewLine() && !tokenSet.contains(getTokenType())) {
advance();
}
}
protected void advanceUntilEol() {
advanceUntil(TokenSet.EMPTY);
}
protected void errorUntil(TokenSet tokenSet, String message) {
PsiBuilder.Marker errorMarker = mark();
advanceUntil(tokenSet);
errorMarker.error(message);
}
protected void errorUntilEol(String message) {
PsiBuilder.Marker errorMarker = mark();
advanceUntilEol();
errorMarker.error(message);
}
protected void expectEolOrEof() {
if (!isNewLine() && !eof()) {
errorUntilEol("End of line expected");
}
}
protected abstract IElementType getIndentElementType();
protected abstract IElementType getEolElementType();
}
| platform/lang-impl/src/com/intellij/indentation/AbstractIndentParser.java | package com.intellij.indentation;
import com.intellij.lang.ASTNode;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.PsiParser;
import com.intellij.psi.TokenType;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.tree.TokenSet;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* User: Andrey.Vokin
* Date: 3/20/12
*/
public abstract class AbstractIndentParser implements PsiParser {
protected PsiBuilder myBuilder;
protected int myCurrentIndent;
protected HashMap<PsiBuilder.Marker, Integer> myIndents;
protected HashMap<PsiBuilder.Marker, Boolean> myNewLines;
protected boolean myNewLine = true;
@NotNull
public ASTNode parse(IElementType root, PsiBuilder builder) {
myNewLines = new HashMap<PsiBuilder.Marker, Boolean>();
myIndents = new HashMap<PsiBuilder.Marker, Integer>();
myBuilder = builder;
parseRoot(root);
return myBuilder.getTreeBuilt();
}
protected abstract void parseRoot(IElementType root);
public PsiBuilder.Marker mark(boolean couldBeRolledBack) {
final PsiBuilder.Marker marker = myBuilder.mark();
if (couldBeRolledBack) {
myIndents.put(marker, myCurrentIndent);
myNewLines.put(marker, myNewLine);
}
return marker;
}
public PsiBuilder.Marker mark() {
return mark(false);
}
public void done(@NotNull final PsiBuilder.Marker marker, @NotNull final IElementType elementType) {
myIndents.remove(marker);
myNewLines.remove(marker);
marker.done(elementType);
}
public static void collapse(@NotNull final PsiBuilder.Marker marker, @NotNull final IElementType elementType) {
marker.collapse(elementType);
}
protected static void drop(@NotNull final PsiBuilder.Marker marker) {
marker.drop();
}
protected void rollbackTo(@NotNull final PsiBuilder.Marker marker) {
if (myIndents.get(marker) == null) {
throw new RuntimeException("Parser can't rollback marker that was created by mark() method, use mark(true) instead");
}
myCurrentIndent = myIndents.get(marker);
myNewLine = myNewLines.get(marker);
myIndents.remove(marker);
myNewLines.remove(marker);
marker.rollbackTo();
}
protected boolean eof() {
return myBuilder.eof();
}
protected int getCurrentOffset() {
return myBuilder.getCurrentOffset();
}
public int getCurrentIndent() {
return myCurrentIndent;
}
protected void error(String message) {
myBuilder.error(message);
}
@Nullable
public IElementType getTokenType() {
return myBuilder.getTokenType();
}
protected static boolean tokenIn(@Nullable final IElementType elementType, IElementType... tokens) {
for (IElementType token : tokens) {
if (elementType == token) {
return true;
}
}
return false;
}
protected boolean currentTokenIn(IElementType... tokens) {
return tokenIn(getTokenType(), tokens);
}
protected boolean currentTokenIn(@NotNull final TokenSet tokenSet) {
return tokenSet.contains(getTokenType());
}
protected static boolean tokenIn(@Nullable final IElementType elementType, @NotNull final TokenSet tokenSet) {
return tokenIn(elementType, tokenSet.getTypes());
}
@NotNull
protected String getTokenText() {
String result = myBuilder.getTokenText();
if (result == null) {
result = "";
}
return result;
}
protected boolean expect(@NotNull final IElementType elementType) {
return expect(elementType, "Expected: " + elementType);
}
protected boolean expect(@NotNull final IElementType elementType, String expectedMessage) {
if (getTokenType() == elementType) {
advance();
return true;
}
error(expectedMessage);
return false;
}
@Nullable
public IElementType lookAhead(int step) {
return myBuilder.lookAhead(step);
}
@Nullable
public IElementType rawLookup(int step) {
return myBuilder.rawLookup(step);
}
public boolean isNewLine() {
return myNewLine;
}
public void advance() {
final String tokenText = myBuilder.getTokenText();
final int tokenLength = tokenText == null ? 0 : tokenText.length();
final int whiteSpaceStart = getCurrentOffset() + tokenLength;
myBuilder.advanceLexer();
final int whiteSpaceEnd = getCurrentOffset();
final String whiteSpaceText = myBuilder.getOriginalText().subSequence(whiteSpaceStart, whiteSpaceEnd).toString();
int i = whiteSpaceText.lastIndexOf('\n');
if (i >= 0) {
myCurrentIndent = whiteSpaceText.length() - i - 1;
myNewLine = true;
}
else {
myNewLine = false;
}
}
protected void advanceUntil(TokenSet tokenSet) {
while (getTokenType() != null && !isNewLine() && !tokenSet.contains(getTokenType())) {
advance();
}
}
protected void advanceUntilEol() {
advanceUntil(TokenSet.EMPTY);
}
protected void errorUntil(TokenSet tokenSet, String message) {
PsiBuilder.Marker errorMarker = mark();
advanceUntil(tokenSet);
errorMarker.error(message);
}
protected void errorUntilEol(String message) {
PsiBuilder.Marker errorMarker = mark();
advanceUntilEol();
errorMarker.error(message);
}
protected void expectEolOrEof() {
if (!isNewLine() && !eof()) {
errorUntilEol("End of line expected");
}
}
protected abstract IElementType getIndentElementType();
protected abstract IElementType getEolElementType();
}
| CSS: extract methods for skipping lazy parseble elements
| platform/lang-impl/src/com/intellij/indentation/AbstractIndentParser.java | CSS: extract methods for skipping lazy parseble elements |
|
Java | apache-2.0 | dc4eac545468ada53e78c12aa2d374241885785d | 0 | IHTSDO/rf2-to-rf1-conversion,IHTSDO/rf2-to-rf1-conversion | package org.ihtsdo.snomed.rf2torf1conversion;
import static org.ihtsdo.snomed.rf2torf1conversion.GlobalUtils.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.ihtsdo.snomed.rf2torf1conversion.pojo.Concept;
import org.ihtsdo.snomed.rf2torf1conversion.pojo.ConceptDeserializer;
import org.ihtsdo.snomed.rf2torf1conversion.pojo.LateralityIndicator;
import org.ihtsdo.snomed.rf2torf1conversion.pojo.QualifyingRelationshipAttribute;
import org.ihtsdo.snomed.rf2torf1conversion.pojo.QualifyingRelationshipRule;
import org.ihtsdo.snomed.rf2torf1conversion.pojo.RF1SchemaConstants;
import org.ihtsdo.snomed.rf2torf1conversion.pojo.RF2SchemaConstants;
import com.google.common.base.Stopwatch;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class ConversionManager implements RF2SchemaConstants, RF1SchemaConstants {
File intRf2Archive;
File extRf2Archive;
File unzipLocation = null;
File additionalFilesLocation = null;
File previousRF1Location;
boolean useRelationshipIds = false;
DBManager db;
String intReleaseDate;
String extReleaseDate;
boolean includeHistory = true;
boolean includeAllQualifyingRelationships = false;
boolean includeLateralityIndicators = true; //Laterality is now obligatory
boolean isBeta = false;
boolean onlyHistory = false;
boolean isExtension = false;
boolean goInteractive = false;
boolean isSnapshotConversion = false;
Edition edition;
private String EXT = "EXT";
private String LNG = "LNG";
private String MOD = "MOD";
private String DATE = "DATE";
private String OUT = "OUT";
private String TYPE = "TYPE";
private String outputFolderTemplate = "SnomedCT_OUT_MOD_DATE";
private String ANCIENT_HISTORY = "/sct1_ComponentHistory_Core_INT_20130731.txt";
private String QUALIFYING_RULES = "/qualifying_relationship_rules.json";
private String AVAILABLE_SUBSET_IDS = "/available_sctids_partition_03.txt";
private String AVAILABLE_RELATIONSHIP_IDS = "/available_sctids_partition_02.txt";
private String RELATIONSHIP_FILENAME = "SnomedCT_OUT_MOD_DATE/Terminology/Content/sct1_Relationships_Core_MOD_DATE.txt";
private String BETA_PREFIX = "x";
Set<File> filesLoaded = new HashSet<File>();
private Long[] subsetIds;
private Long maxPreviousSubsetId = null;
private int previousSubsetVersion = 29; //Taken from 20160131 RF1 International Release
private static final String RELEASE_NOTES = "SnomedCTReleaseNotes";
private static final String DOCUMENTATION_DIR = "Documentation/";
private static final String LATERALITY_SNAPSHOT_TEMPLATE = "der2_Refset_SimpleSnapshot_MOD_DATE.txt";
private static final int SUFFICIENT_LATERALITY_DATA = 10;
enum Edition { INTERNATIONAL, SPANISH, US, SG };
class Dialect {
String langRefSetId;
String langCode;
Dialect (String langRefSetId, String langCode) {
this.langRefSetId = langRefSetId;
this.langCode = langCode;
}
}
public final Dialect dialectSg = new Dialect ("9011000132109","sg"); //Singapore English
public final Dialect dialectEs = new Dialect ("450828004","es"); //Latin American Spanish
public final Dialect dialectGb = new Dialect ("900000000000508004","en-GB");
public final Dialect dialectUs = new Dialect ("900000000000509007","en-US");
class EditionConfig {
String editionName;
String langCode;
String module;
String outputName;
boolean historyAvailable;
Dialect[] dialects;
EditionConfig (String editionName, String language, String module, String outputName, boolean historyAvailable, Dialect[] dialects) {
this.editionName = editionName;
this.outputName = outputName;
this.langCode = language;
this.module = module;
this.historyAvailable = historyAvailable;
this.dialects = dialects;
}
}
private static final String EDITION_DETERMINER = "sct2_Description_EXTTYPE-LNG_MOD_DATE.txt";
static Map<Edition, EditionConfig> knownEditionMap = new HashMap<Edition, EditionConfig>();
{
//Edition Config values: editionName, language, module, outputName, dialects[]
knownEditionMap.put(Edition.INTERNATIONAL, new EditionConfig("", "en", "INT", "RF1Release", true, new Dialect[]{dialectGb, dialectUs})); //International Edition has no Extension name
knownEditionMap.put(Edition.SPANISH, new EditionConfig("SpanishExtension", "es", "INT", "SpanishRelease-es", true ,new Dialect[]{dialectEs}));
knownEditionMap.put(Edition.US, new EditionConfig("", "en", "US1000124", "RF1Release", false, new Dialect[]{dialectGb, dialectUs}));
knownEditionMap.put(Edition.SG, new EditionConfig("", "en-SG", "SG1000132", "RF1Release", true, new Dialect[]{dialectGb, dialectUs, dialectSg}));
}
static Map<String, String> editionfileToTable = new HashMap<String, String>();
{
editionfileToTable.put("sct2_Concept_EXTTYPE_MOD_DATE.txt", "rf2_concept_sv");
editionfileToTable.put("sct2_Relationship_EXTTYPE_MOD_DATE.txt", "rf2_rel_sv");
editionfileToTable.put("sct2_StatedRelationship_EXTTYPE_MOD_DATE.txt", "rf2_rel_sv");
editionfileToTable.put("sct2_Identifier_EXTTYPE_MOD_DATE.txt", "rf2_identifier_sv");
//Extensions can use a mix of International and their own descriptions
editionfileToTable.put(EDITION_DETERMINER, "rf2_term_sv");
//We need to know the International Preferred Term if the Extension doesn't specify one
editionfileToTable.put("der2_cRefset_LanguageEXTTYPE-LNG_MOD_DATE.txt", "rf2_crefset_sv");
//Concepts still need inactivation reasons from the International Edition
editionfileToTable.put("der2_cRefset_AssociationEXTTYPE_MOD_DATE.txt", "rf2_crefset_sv");
editionfileToTable.put("der2_cRefset_AttributeValueEXTTYPE_MOD_DATE.txt", "rf2_crefset_sv");
//CTV3 and SNOMED RT Identifiers come from the International Edition
editionfileToTable.put("der2_sRefset_SimpleMapEXTTYPE_MOD_DATE.txt", "rf2_srefset_sv");
//intfileToTable.put("der2_iissscRefset_ComplexEXTMapTYPE_MOD_DATE.txt", "rf2_iissscrefset_sv");
//intfileToTable.put("der2_iisssccRefset_ExtendedMapEXTTYPE_MOD_DATE.txt", "rf2_iisssccrefset_sv");
}
static Map<String, String> extensionfileToTable = new HashMap<String, String>();
{
//Extension could supplement any file in international edition
extensionfileToTable.putAll(editionfileToTable);
extensionfileToTable.put(EDITION_DETERMINER, "rf2_term_sv");
extensionfileToTable.put("sct2_TextDefinition_EXTTYPE-LNG_MOD_DATE.txt", "rf2_def_sv");
extensionfileToTable.put("der2_cRefset_AssociationEXTTYPE_MOD_DATE.txt", "rf2_crefset_sv");
extensionfileToTable.put("der2_cRefset_AttributeValueEXTTYPE_MOD_DATE.txt", "rf2_crefset_sv");
extensionfileToTable.put("der2_Refset_SimpleEXTTYPE_MOD_DATE.txt", "rf2_refset_sv");
extensionfileToTable.put("der2_cRefset_LanguageEXTTYPE-LNG_MOD_DATE.txt", "rf2_crefset_sv");
extensionfileToTable.put("der2_sRefset_SimpleMapEXTTYPE_MOD_DATE.txt", "rf2_srefset_sv");
//extfileToTable.put("der2_iissscRefset_ComplexEXTMapTYPE_MOD_DATE.txt", "rf2_iissscrefset_sv");
//extfileToTable.put("der2_iisssccRefset_ExtendedMapEXTTYPE_MOD_DATE.txt", "rf2_iisssccrefset_sv");
extensionfileToTable.put("der2_cciRefset_RefsetDescriptorEXTTYPE_MOD_DATE.txt", "rf2_ccirefset_sv");
extensionfileToTable.put("der2_ciRefset_DescriptionTypeEXTTYPE_MOD_DATE.txt", "rf2_cirefset_sv");
extensionfileToTable.put("der2_ssRefset_ModuleDependencyEXTTYPE_MOD_DATE.txt", "rf2_ssrefset_sv");
}
public static Map<String, String>intExportMap = new HashMap<String, String>();
{
// The slashes will be replaced with the OS appropriate separator at export time
intExportMap.put(outputFolderTemplate + "/Terminology/Content/sct1_Concepts_Core_MOD_DATE.txt",
"select CONCEPTID, CONCEPTSTATUS, FULLYSPECIFIEDNAME, CTV3ID, SNOMEDID, ISPRIMITIVE from rf21_concept");
intExportMap
.put(RELATIONSHIP_FILENAME,
"select RELATIONSHIPID,CONCEPTID1,RELATIONSHIPTYPE,CONCEPTID2,CHARACTERISTICTYPE,REFINABILITY,RELATIONSHIPGROUP from rf21_rel");
}
public static Map<String, String> extExportMap = new HashMap<String, String>();
{
// The slashes will be replaced with the OS appropriate separator at export time
extExportMap
.put(outputFolderTemplate + "/Terminology/Content/sct1_Descriptions_LNG_MOD_DATE.txt",
"select DESCRIPTIONID, DESCRIPTIONSTATUS, CONCEPTID, TERM, INITIALCAPITALSTATUS, DESC_TYPE as DESCRIPTIONTYPE, LANGUAGECODE from rf21_term");
extExportMap.put(outputFolderTemplate + "/Terminology/History/sct1_References_Core_MOD_DATE.txt",
"select COMPONENTID, REFERENCETYPE, REFERENCEDID from rf21_REFERENCE");
extExportMap
.put(outputFolderTemplate + "/Resources/StatedRelationships/res1_StatedRelationships_Core_MOD_DATE.txt",
"select RELATIONSHIPID,CONCEPTID1,RELATIONSHIPTYPE,CONCEPTID2,CHARACTERISTICTYPE,REFINABILITY,RELATIONSHIPGROUP from rf21_stated_rel");
}
public static void main(String[] args) throws RF1ConversionException {
//Set Windows Line separator as that's an RF1 standard
System.setProperty("line.separator", "\r\n");
ConversionManager cm = new ConversionManager();
cm.doRf2toRf1Conversion(args);
}
private void doRf2toRf1Conversion(String[] args) throws RF1ConversionException {
File tempDBLocation = Files.createTempDir();
init(args, tempDBLocation);
createDatabaseSchema();
File intLoadingArea = null;
File extLoadingArea = null;
File exportArea = null;
Stopwatch stopwatch = Stopwatch.createStarted();
String completionStatus = "failed";
try {
print("\nExtracting RF2 International Edition Data...");
intLoadingArea = unzipArchive(intRf2Archive);
intReleaseDate = findDateInString(intLoadingArea.listFiles()[0].getName(), false);
extReleaseDate = intReleaseDate;
determineEdition(intLoadingArea, intReleaseDate);
if (extRf2Archive != null) {
print("\nExtracting RF2 Extension Data...");
extLoadingArea = unzipArchive(extRf2Archive);
extReleaseDate = findDateInString(extLoadingArea.listFiles()[0].getName(), false);
determineEdition(extLoadingArea, extReleaseDate);
isExtension = true;
}
String releaseDate = isExtension ? extReleaseDate : intReleaseDate;
File loadingArea = isExtension ? extLoadingArea : intLoadingArea;
int releaseIndex = calculateReleaseIndex(releaseDate);
EditionConfig config = knownEditionMap.get(edition);
//Laterality indicators are now obligatory
loadLateralityIndicators(intLoadingArea, intReleaseDate, config);
int newSubsetVersion = 0;
if (previousRF1Location != null) {
useRelationshipIds = true;
//This will allow us to set up SubsetIds (using available_sctids_partition_03)
//And a map of existing relationship Ids to use for reconciliation
loadPreviousRF1(config);
//Initialise a set of available SCTIDS
InputStream availableRelIds = ConversionManager.class.getResourceAsStream(AVAILABLE_RELATIONSHIP_IDS);
RF1Constants.intialiseAvailableRelationships(availableRelIds);
newSubsetVersion = previousSubsetVersion + 1;
} else {
useDeterministicSubsetIds(releaseIndex, config);
newSubsetVersion = previousSubsetVersion + releaseIndex;
}
db.runStatement("SET @useRelationshipIds = " + useRelationshipIds);
setSubsetIds(newSubsetVersion);
long targetOperationCount = getTargetOperationCount();
if (onlyHistory) {
targetOperationCount = 250;
} else if (isExtension) {
targetOperationCount = includeHistory? targetOperationCount : 388;
} else {
targetOperationCount = includeHistory? targetOperationCount : 391;
}
setTargetOperationCount(targetOperationCount);
completeOutputMap(config);
db.runStatement("SET @langCode = '" + config.langCode + "'");
db.runStatement("SET @langRefSet = '" + config.dialects[0].langRefSetId + "'");
print("\nLoading " + edition.toString() +" common RF2 Data...");
loadRF2Data(intLoadingArea, config, intReleaseDate, editionfileToTable);
//Load the rest of the files from the same loading area if International Release, otherwise use the extensionLoading Area
print("\nLoading " + edition +" specific RF2 Data...");
loadRF2Data(loadingArea, config, releaseDate, extensionfileToTable);
debug("\nCreating RF2 indexes...");
db.executeResource("create_rf2_indexes.sql");
if (!onlyHistory) {
print("\nCalculating RF2 snapshot...");
calculateRF2Snapshot(releaseDate);
}
print("\nConverting RF2 to RF1...");
convert(config);
print("\nExporting RF1 to file...");
exportArea = Files.createTempDir();
exportRF1Data(intExportMap, releaseDate, intReleaseDate, knownEditionMap.get(edition), exportArea);
exportRF1Data(extExportMap, releaseDate, releaseDate, knownEditionMap.get(edition), exportArea);
//Relationship file uses the international release date, even for extensions. Well, the Spanish one anyway.
//But we also need the extension release date for the top level directory
String filePath = getQualifyingRelationshipFilepath(intReleaseDate, extReleaseDate, knownEditionMap.get(edition), exportArea);
if (includeAllQualifyingRelationships || includeLateralityIndicators) {
print("\nLoading Inferred Relationship Hierarchy for Qualifying Relationship computation...");
loadRelationshipHierarchy(knownEditionMap.get(Edition.INTERNATIONAL), intLoadingArea);
}
if (includeAllQualifyingRelationships) {
print ("\nGenerating qualifying relationships");
Set<QualifyingRelationshipAttribute> ruleAttributes = loadQualifyingRelationshipRules();
generateQualifyingRelationships(ruleAttributes, filePath);
}
if (includeLateralityIndicators) {
print ("\nGenerating laterality qualifying relationships");
generateLateralityRelationships(filePath);
}
boolean documentationIncluded = false;
if (additionalFilesLocation != null) {
documentationIncluded = includeAdditionalFiles(exportArea, releaseDate, knownEditionMap.get(edition));
}
if (!documentationIncluded) {
pullDocumentationFromRF2(loadingArea, exportArea, releaseDate, knownEditionMap.get(edition));
}
print("\nZipping archive");
createArchive(exportArea);
completionStatus = "completed";
} finally {
print("\nProcess " + completionStatus + " in " + stopwatch + " after completing " + getProgress() + "/" + getTargetOperationCount()
+ " operations.");
if (goInteractive) {
doInteractive();
}
try {
print(RF1Constants.getRelationshipIdUsageSummary());
} catch (Exception e){}
print("Cleaning up resources...");
try {
db.shutDown(true); // Also deletes all files
if (tempDBLocation != null && tempDBLocation.exists()) {
tempDBLocation.delete();
}
} catch (Exception e) {
debug("Error while cleaning up database " + tempDBLocation.getPath() + e.getMessage());
}
try {
if (intLoadingArea != null && intLoadingArea.exists()) {
FileUtils.deleteDirectory(intLoadingArea);
}
if (extLoadingArea != null && extLoadingArea.exists()) {
FileUtils.deleteDirectory(extLoadingArea);
}
if (exportArea != null && exportArea.exists()) {
FileUtils.deleteDirectory(exportArea);
}
} catch (Exception e) {
debug("Error while cleaning up loading/export Areas " + e.getMessage());
}
}
}
private void doInteractive() {
boolean quitDetected = false;
StringBuilder buff = new StringBuilder();
try (Scanner in = new Scanner(System.in)) {
print ("Enter sql command to run, terminate with semicolon or type quit; to finish");
while (!quitDetected) {
buff.append(in.nextLine().trim());
if (buff.length() > 1 && buff.charAt(buff.length()-1) == ';') {
String command = buff.toString();
if (command.equalsIgnoreCase("quit;")) {
quitDetected = true;
} else {
try{
db.runStatement(command.toString());
} catch (Exception e) {
e.printStackTrace();
}
buff.setLength(0);
}
} else {
buff.append(" ");
}
}
}
}
private void completeOutputMap(EditionConfig editionConfig) {
if (isExtension) {
String archiveName = "SnomedCT_OUT_MOD_DATE";
String folderName = "Language-" + editionConfig.langCode;
String fileRoot = archiveName + File.separator + "Subsets" + File.separator + folderName + File.separator;
String fileName = "der1_SubsetMembers_"+ editionConfig.langCode + "_MOD_DATE.txt";
extExportMap.put(fileRoot + fileName,
"select s.SubsetId, s.MemberID, s.MemberStatus, s.LinkedID from rf21_SUBSETS s, rf21_SUBSETLIST sl where s.SubsetOriginalId = sl.subsetOriginalId AND sl.languageCode = ''" + editionConfig.langCode + "'';");
fileName = "der1_Subsets_" + editionConfig.langCode + "_MOD_DATE.txt";
extExportMap.put(fileRoot + fileName,
"select sl.* from rf21_SUBSETLIST sl where languagecode = ''" + editionConfig.langCode + "'';");
extExportMap.put("SnomedCT_OUT_MOD_DATE/Resources/TextDefinitions/sct1_TextDefinitions_LNG_MOD_DATE.txt",
"select * from rf21_DEF");
} else {
extExportMap.put("SnomedCT_OUT_MOD_DATE/Resources/TextDefinitions/sct1_TextDefinitions_en-US_MOD_DATE.txt",
"select * from rf21_DEF");
extExportMap
.put("SnomedCT_OUT_MOD_DATE/Subsets/Language-en-GB/der1_SubsetMembers_en-GB_MOD_DATE.txt",
"select s.SubsetId, s.MemberID, s.MemberStatus, s.LinkedID from rf21_SUBSETS s, rf21_SUBSETLIST sl where s.SubsetOriginalId = sl.subsetOriginalId AND sl.languageCode in (''en'',''en-GB'')");
extExportMap.put("SnomedCT_OUT_MOD_DATE/Subsets/Language-en-GB/der1_Subsets_en-GB_MOD_DATE.txt",
"select sl.* from rf21_SUBSETLIST sl where languagecode like ''%GB%''");
extExportMap
.put("SnomedCT_OUT_MOD_DATE/Subsets/Language-en-US/der1_SubsetMembers_en-US_MOD_DATE.txt",
"select s.SubsetId, s.MemberID, s.MemberStatus, s.LinkedID from rf21_SUBSETS s, rf21_SUBSETLIST sl where s.SubsetOriginalId = sl.subsetOriginalId AND sl.languageCode in (''en'',''en-US'')");
extExportMap.put("SnomedCT_RF1Release_MOD_DATE/Subsets/Language-en-US/der1_Subsets_en-US_MOD_DATE.txt",
"select sl.* from rf21_SUBSETLIST sl where languagecode like ''%US%''");
}
if (includeHistory) {
extExportMap.put("SnomedCT_OUT_MOD_DATE/Terminology/History/sct1_ComponentHistory_Core_MOD_DATE.txt",
"select COMPONENTID, RELEASEVERSION, CHANGETYPE, STATUS, REASON from rf21_COMPONENTHISTORY");
}
}
private void determineEdition(File loadingArea, String releaseDate) throws RF1ConversionException {
//Loop through known editions and see if EDITION_DETERMINER file is present
for (Map.Entry<Edition, EditionConfig> thisEdition : knownEditionMap.entrySet())
for (File thisFile : loadingArea.listFiles()) {
EditionConfig parts = thisEdition.getValue();
String target = EDITION_DETERMINER.replace(EXT, parts.editionName)
.replace(LNG, parts.langCode)
.replace(MOD, parts.module)
.replace(DATE, releaseDate)
.replace(TYPE, isSnapshotConversion ? "Snapshot" : "Full");
if (thisFile.getName().equals(target)) {
this.edition = thisEdition.getKey();
return;
}
}
throw new RF1ConversionException ("Failed to find file matching any known edition: " + EDITION_DETERMINER + " in " + loadingArea.getAbsolutePath());
}
private File unzipArchive(File archive) throws RF1ConversionException {
File tempDir = null;
try {
if (unzipLocation != null) {
tempDir = java.nio.file.Files.createTempDirectory(unzipLocation.toPath(), "rf2-to-rf1-").toFile();
} else {
// Work in the traditional temp file location for the OS
tempDir = Files.createTempDir();
}
} catch (IOException e) {
throw new RF1ConversionException("Unable to create temporary directory for archive extration");
}
// We only need to work with the full files
// ...mostly, we also need the Snapshot Relationship file in order to work out the Qualifying Relationships
// Also we'll take the documentation pdf
String match = isSnapshotConversion ? "Snapshot" : "Full";
unzipFlat(archive, tempDir, new String[]{ match, "sct2_Relationship_Snapshot","der2_Refset_SimpleSnapshot",RELEASE_NOTES});
return tempDir;
}
private void createDatabaseSchema() throws RF1ConversionException {
print("Creating database schema");
db.executeResource("create_rf2_schema.sql");
}
private void calculateRF2Snapshot(String releaseDate) throws RF1ConversionException {
String setDateSql = "SET @RDATE = " + releaseDate;
db.runStatement(setDateSql);
db.executeResource("create_rf2_snapshot.sql");
db.executeResource("populate_subset_2_refset.sql");
}
private void convert(EditionConfig config) throws RF1ConversionException {
db.executeResource("create_rf1_schema.sql");
if (includeHistory && config.historyAvailable) {
db.executeResource("populate_rf1_historical.sql");
} else {
print("\nSkipping generation of RF1 History. Set -h parameter if this is required (selected Editions only).");
}
if (!onlyHistory) {
db.executeResource("populate_rf1.sql");
if (isExtension) {
db.executeResource("populate_rf1_ext_descriptions.sql");
} else {
db.executeResource("populate_rf1_int_descriptions.sql");
}
db.executeResource("populate_rf1_associations.sql");
if (useRelationshipIds) {
db.executeResource("populate_rf1_rel_ids.sql");
}
}
}
private void init(String[] args, File dbLocation) throws RF1ConversionException {
if (args.length < 1) {
print("Usage: java ConversionManager [-v] [-h] [-b] [-i] [-a <additional files location>] [-p <previous RF1 archive] [-u <unzip location>] <rf2 archive location> [<rf2 extension archive>]");
print(" b - beta indicator, causes an x to be prepended to output filenames");
print(" p - previous RF1 archive required for SubsetId and Relationship Id generation");
exit();
}
boolean isUnzipLocation = false;
boolean isAdditionalFilesLocation = false;
boolean isPreviousRF1Location = false;
for (String thisArg : args) {
if (thisArg.equals("-v")) {
GlobalUtils.verbose = true;
} else if (thisArg.equals("-i")) {
goInteractive = true;
} else if (thisArg.equals("-s")) {
//New feature, currently undocumented until proven.
print ("Option set to perform conversion on Snapshot files. No history will be produced.");
isSnapshotConversion = true;
includeHistory = false;
if (onlyHistory) {
throw new RF1ConversionException("History is not possible with a snapshot conversion");
}
} else if (thisArg.equals("-H")) {
includeHistory = true;
onlyHistory = true;
if (isSnapshotConversion) {
throw new RF1ConversionException("History is not possible with a snapshot conversion");
}
} else if (thisArg.equals("-b")) {
isBeta = true;
}else if (thisArg.equals("-u")) {
isUnzipLocation = true;
} else if (thisArg.equals("-a")) {
isAdditionalFilesLocation = true;
} else if (thisArg.equals("-p")) {
isPreviousRF1Location = true;
} else if (thisArg.equals("-q")) {
//The rule file for generating these relationships is currently incomplete and incorrect.
includeAllQualifyingRelationships = true;
} else if (isUnzipLocation) {
unzipLocation = new File(thisArg);
if (!unzipLocation.isDirectory()) {
throw new RF1ConversionException(thisArg + " is an invalid location to unzip archive to!");
}
isUnzipLocation = false;
} else if (isAdditionalFilesLocation) {
additionalFilesLocation = new File(thisArg);
if (!additionalFilesLocation.isDirectory()) {
throw new RF1ConversionException(thisArg + " is an invalid location to find additional files.");
}
isAdditionalFilesLocation = false;
} else if (isPreviousRF1Location) {
previousRF1Location = new File(thisArg);
if (!previousRF1Location.exists() || !previousRF1Location.canRead()) {
throw new RF1ConversionException(thisArg + " does not appear to be a valid RF1 archive.");
}
isPreviousRF1Location = false;
} else if (intRf2Archive == null){
File possibleArchive = new File(thisArg);
if (possibleArchive.exists() && !possibleArchive.isDirectory() && possibleArchive.canRead()) {
intRf2Archive = possibleArchive;
}
} else {
File possibleArchive = new File(thisArg);
if (possibleArchive.exists() && !possibleArchive.isDirectory() && possibleArchive.canRead()) {
extRf2Archive = possibleArchive;
}
}
}
if (intRf2Archive == null) {
print("Unable to load RF2 Archive: " + args[args.length - 1]);
exit();
}
db = new DBManager();
db.init(dbLocation);
}
private void loadRF2Data(File loadingArea, EditionConfig config, String releaseDate, Map<String, String> fileToTable) throws RF1ConversionException {
// We can do the load in parallel. Only 3 threads because heavily I/O
db.startParallelProcessing(3);
String releaseType = isSnapshotConversion ? "Snapshot":"Full";
for (Map.Entry<String, String> entry : fileToTable.entrySet()) {
// Replace DATE in the filename with the actual release date
String fileName = entry.getKey().replace(DATE, releaseDate)
.replace(EXT, config.editionName)
.replace(LNG, config.langCode)
.replace(MOD, config.module)
.replace(TYPE, releaseType);
File file = new File(loadingArea + File.separator + fileName);
//Only load each file once
if (filesLoaded.contains(file)) {
debug ("Skipping " + file.getName() + " already loaded as a common file.");
} else if (file.exists()) {
db.load(file, entry.getValue());
filesLoaded.add(file);
} else {
print("\nWarning, skipping load of file " + file.getName() + " - not present");
}
}
db.finishParallelProcessing();
}
private void exportRF1Data(Map<String, String> exportMap, String packageReleaseDate, String fileReleaseDate, EditionConfig config, File exportArea) throws RF1ConversionException {
// We can do the export in parallel. Only 3 threads because heavily I/O
db.startParallelProcessing(3);
for (Map.Entry<String, String> entry : exportMap.entrySet()) {
// Replace DATE in the filename with the actual release date
String fileName = entry.getKey().replaceFirst(DATE, packageReleaseDate)
.replace(DATE, fileReleaseDate)
.replace(OUT, config.outputName)
.replace(LNG, config.langCode)
.replace(MOD, config.module);
fileName = modifyFilenameIfBeta(fileName);
String filePath = exportArea + File.separator + fileName;
//If we're doing the history file, then we need to prepend the static
//resource file
InputStream isInclude = null;
if (includeHistory && fileName.contains("ComponentHistory")) {
isInclude = ConversionManager.class.getResourceAsStream(ANCIENT_HISTORY);
if (isInclude == null) {
throw new RF1ConversionException("Unable to obtain history file: " + ANCIENT_HISTORY);
}
}
db.export(filePath, entry.getValue(), isInclude);
}
db.finishParallelProcessing();
}
private String modifyFilenameIfBeta(String fileName) {
if (isBeta) {
//Beta prefix before the file shortname, but also for the leading directory
int lastSlash = fileName.lastIndexOf(File.separator) + 1;
fileName = BETA_PREFIX + fileName.substring(0,lastSlash) + BETA_PREFIX + fileName.substring(lastSlash);
}
return fileName;
}
private void loadRelationshipHierarchy(EditionConfig config, File intLoadingArea) throws RF1ConversionException {
String fileName = intLoadingArea.getAbsolutePath() + File.separator + "sct2_Relationship_Snapshot_MOD_DATE.txt";
fileName = fileName.replace(DATE, intReleaseDate)
.replace(MOD, config.module);
GraphLoader gl = new GraphLoader (fileName);
gl.loadRelationships();
}
private Set<QualifyingRelationshipAttribute> loadQualifyingRelationshipRules() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Concept.class, new ConceptDeserializer());
Gson gson = gsonBuilder.create();
InputStream jsonStream = ConversionManager.class.getResourceAsStream(QUALIFYING_RULES);
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(jsonStream));
Type listType = new TypeToken<Set<QualifyingRelationshipAttribute>>() {}.getType();
Set<QualifyingRelationshipAttribute> attributes = gson.fromJson(jsonReader, listType);
return attributes;
}
/**
* This is a temporary measure until we can get the Laterality Reference published as a refset.
* at which point it will stop being an external file
* @param loadingArea
*/
private void loadLateralityIndicators(File loadingArea, String releaseDate, EditionConfig config) throws RF1ConversionException {
String targetFilename = LATERALITY_SNAPSHOT_TEMPLATE.replace(DATE, releaseDate).replace(MOD, config.module);
File lateralityFile = new File(loadingArea.getAbsolutePath() + File.separator + targetFilename);
boolean sufficientDataReadOK = true;
if (!lateralityFile.canRead()) {
debug ("Could not find " + targetFilename + " among " + GlobalUtils.listDirectory(loadingArea));
sufficientDataReadOK = false;
} else {
int linesRead = 0;
try (BufferedReader br = new BufferedReader(new FileReader(lateralityFile))) {
String line;
boolean firstLine = true;
while ((line = br.readLine()) != null) {
if (!firstLine) {
String[] columns = line.split(FIELD_DELIMITER);
if (columns[SIMP_IDX_ACTIVE].equals("1") && columns[SIMP_IDX_REFSETID].equals(LATERALITY_REFSET_ID)) {
LateralityIndicator.registerIndicator(columns[SIMP_IDX_REFCOMPID]);
linesRead++;
}
} else {
firstLine = false;
}
}
if (linesRead < SUFFICIENT_LATERALITY_DATA) {
sufficientDataReadOK = false;
}
} catch (IOException ioe) {
throw new RF1ConversionException ("Unable to import laterality reference file " + lateralityFile.getAbsolutePath(), ioe);
}
}
if (!sufficientDataReadOK && useRelationshipIds) {
String msg = "Laterality Reference Set not detected/available/sufficient in Simple Refset Snapshot: " + targetFilename + ".\nThis refset is compulsory in this version of the RF2 to RF1 converter, if Relationship IDs are to be generated.";
print("\n" + msg);
throw new RF1ConversionException (msg);
}
}
private void generateQualifyingRelationships(
Set<QualifyingRelationshipAttribute> ruleAttributes, String filePath) throws RF1ConversionException {
//For each attribute, work through each rule creating rules for self and all children of starting points,
//except for exceptions
try(FileWriter fw = new FileWriter(filePath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
for (QualifyingRelationshipAttribute thisAttribute : ruleAttributes) {
StringBuffer commonRF1 = new StringBuffer().append(FIELD_DELIMITER)
.append(thisAttribute.getType().getSctId()).append(FIELD_DELIMITER)
.append(thisAttribute.getDestination().getSctId()).append(FIELD_DELIMITER)
.append("1\t")//Qualifying Rel type
.append(thisAttribute.getRefinability()).append("\t0"); //Refineable, Group 0
for (QualifyingRelationshipRule thisRule : thisAttribute.getRules()) {
Set<Concept> potentialApplications = thisRule.getStartPoint().getAllDescendents(Concept.DEPTH_NOT_SET);
Collection<Concept> ruleAppliedTo = CollectionUtils.subtract(potentialApplications, thisRule.getExceptions());
for (Concept thisException : thisRule.getExceptions()) {
Set<Concept> exceptionDescendents = thisException.getAllDescendents(Concept.DEPTH_NOT_SET);
ruleAppliedTo = CollectionUtils.subtract(ruleAppliedTo, exceptionDescendents);
}
//Now the remaining concepts that the rules applies to can be written out to file
for (Concept thisConcept : ruleAppliedTo) {
//Concept may already have this attribute as a defining relationship, skip if so.
if (!thisConcept.hasAttribute(thisAttribute)) {
String rf1Line = FIELD_DELIMITER + thisConcept.getSctId() + commonRF1;
out.println(rf1Line);
}
}
}
}
} catch (IOException e) {
throw new RF1ConversionException ("Failure while outputting Qualifying Relationships: " + e.toString());
}
}
private void generateLateralityRelationships(String filePath) throws RF1ConversionException {
//Check every concept to see if has a laterality indicator, and doesn't already have that
//attribute as a defining relationship
Set<Concept> allConcepts = Concept.getConcept(SNOMED_ROOT_CONCEPT).getAllDescendents(Concept.DEPTH_NOT_SET);
StringBuffer commonRF1 = new StringBuffer().append(FIELD_DELIMITER)
.append(LATERALITY_ATTRIB).append(FIELD_DELIMITER)
.append(SIDE_VALUE).append(FIELD_DELIMITER)
.append("1\t")//Qualifying Rel type
.append(RF1Constants.MUST_REFINE).append("\t0"); //Refineable, Group 0
Concept lat = Concept.getConcept(Long.parseLong(LATERALITY_ATTRIB));
Concept side = Concept.getConcept(Long.parseLong(SIDE_VALUE));
QualifyingRelationshipAttribute LateralityAttribute = new QualifyingRelationshipAttribute (lat, side, RF1Constants.MUST_REFINE);
try(FileWriter fw = new FileWriter(filePath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
for (Concept thisConcept : allConcepts) {
if (LateralityIndicator.hasLateralityIndicator(thisConcept.getSctId())) {
if (!thisConcept.hasAttribute(LateralityAttribute)) {
String relId = ""; //Default is to blank relationship ids
if (useRelationshipIds) {
relId = RF1Constants.lookupRelationshipId(thisConcept.getSctId().toString(),
LATERALITY_ATTRIB,
SIDE_VALUE,
UNGROUPED,
false); //working with inferred relationship ids
}
String rf1Line = relId + FIELD_DELIMITER + thisConcept.getSctId() + commonRF1;
out.println(rf1Line);
}
}
}
}catch (IOException e){
throw new RF1ConversionException ("Failure while output Laterality Relationships: " + e.toString());
}
}
private String getQualifyingRelationshipFilepath(String intReleaseDate,
String extReleaseDate, EditionConfig config, File exportArea) throws RF1ConversionException {
// Replace the top level Date with the Extension Date, and the
// Relationship file with the extension release date
String fileName = RELATIONSHIP_FILENAME.replaceFirst(DATE, extReleaseDate)
.replace(DATE, intReleaseDate)
.replace(OUT, config.outputName)
.replace(LNG, config.langCode)
.replace(MOD, config.module);
fileName = modifyFilenameIfBeta(fileName);
String filePath = exportArea + File.separator + fileName;
File outputFile = new File(filePath);
try{
if (!outputFile.exists()) {
outputFile.getParentFile().mkdirs();
outputFile.createNewFile();
}
} catch (IOException e) {
throw new RF1ConversionException("Unable to create file for Qualifying Relationships: " + e);
}
return filePath;
}
private boolean includeAdditionalFiles(File outputDirectory, String releaseDate, EditionConfig editionConfig){
Map<String, String> targetLocation = new HashMap<String, String>();
boolean documentationIncluded = false;
targetLocation.put(".pdf", DOCUMENTATION_DIR);
targetLocation.put("KeyIndex_", "Resources/Indexes/");
targetLocation.put("Canonical", "Resources/Canonical Table/");
String rootPath = getOutputRootPath(outputDirectory, releaseDate, editionConfig);
File[] directoryListing = additionalFilesLocation.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
String childFilename = child.getName();
//Do we know to put this file in a particular location?
//otherwise path will remain the root path
for (String match : targetLocation.keySet()) {
if (childFilename.contains(match)) {
childFilename = targetLocation.get(match) + childFilename;
break;
}
}
//Ensure path exists for where file is being copied to
File copiedFile = new File (rootPath + childFilename);
copiedFile.getParentFile().mkdirs();
try {
FileUtils.copyFile(child, copiedFile);
print ("Copied additional file to " + copiedFile.getAbsolutePath());
if (copiedFile.getName().contains(RELEASE_NOTES)) {
documentationIncluded = true;
}
} catch (IOException e) {
print ("Unable to copy additional file " + childFilename + " due to " + e.getMessage());
}
}
}
return documentationIncluded;
}
private String getOutputRootPath(File outputDirectory, String releaseDate,
EditionConfig config) {
String rootPath = outputDirectory.getAbsolutePath()
+ File.separator
+ (isBeta?BETA_PREFIX:"")
+ outputFolderTemplate
+ File.separator;
rootPath = rootPath.replace(OUT, config.outputName)
.replace(DATE, releaseDate)
.replace(MOD, config.module);
return rootPath;
}
private void loadPreviousRF1(EditionConfig config) throws RF1ConversionException {
int previousRelFilesLoaded = 0;
try {
ZipInputStream zis = new ZipInputStream(new FileInputStream(previousRF1Location));
ZipEntry ze = zis.getNextEntry();
try {
while (ze != null) {
if (!ze.isDirectory()) {
Path p = Paths.get(ze.getName());
String fileName = p.getFileName().toString();
if (fileName.contains("der1_Subsets")) {
updateSubsetIds(zis, config);
} else if (fileName.contains("sct1_Relationships")) {
//We need to use static methods here so that H2 can access as functions.
print ("\nLoading previous RF1 inferred relationships");
RF1Constants.loadPreviousRelationships(zis, false);
previousRelFilesLoaded++;
}else if (fileName.contains("res1_StatedRelationships")) {
print ("\nLoading previous RF1 stated relationships");
RF1Constants.loadPreviousRelationships(zis, true);
previousRelFilesLoaded++;
}
}
ze = zis.getNextEntry();
}
} finally {
zis.closeEntry();
zis.close();
}
} catch (IOException e) {
throw new RF1ConversionException("Failed to load previous RF1 archive " + previousRF1Location.getName(), e);
}
if (previousRelFilesLoaded != 2) {
throw new RF1ConversionException("Expected to load 2 previous relationship files, instead loaded " + previousRelFilesLoaded );
}
}
private void updateSubsetIds(ZipInputStream zis, EditionConfig config) throws NumberFormatException, IOException {
//This function will also pick up and set the previous subset version
Long subsetId = loadSubsetsFile(zis);
//Do we need to recover a new set of subsetIds?
if (maxPreviousSubsetId == null || subsetId > maxPreviousSubsetId) {
maxPreviousSubsetId = subsetId;
InputStream is = ConversionManager.class.getResourceAsStream(AVAILABLE_SUBSET_IDS);
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))){
String line;
int subsetIdsSet = 0;
subsetIds = new Long[config.dialects.length];
while ((line = br.readLine()) != null && subsetIdsSet < config.dialects.length) {
Long thisAvailableSubsetId = Long.parseLong(line.trim());
if (thisAvailableSubsetId.compareTo(maxPreviousSubsetId) > 0) {
debug ("Obtaining new Subset Ids from resource file");
subsetIds[subsetIdsSet] = thisAvailableSubsetId;
subsetIdsSet++;
}
}
}
}
}
/*
* @return the greatest subsetId in the file
*/
private Long loadSubsetsFile(ZipInputStream zis) throws IOException {
Long maxSubsetIdInFile = null;
BufferedReader br = new BufferedReader(new InputStreamReader(zis, StandardCharsets.UTF_8));
String line;
boolean isFirstLine = true;
while ((line = br.readLine()) != null) {
if (isFirstLine) {
isFirstLine = false;
continue;
}
String[] lineItems = line.split(FIELD_DELIMITER);
//SubsetId is the first column
Long thisSubsetId = Long.parseLong(lineItems[RF1_IDX_SUBSETID]);
if (maxSubsetIdInFile == null || thisSubsetId > maxSubsetIdInFile) {
maxSubsetIdInFile = thisSubsetId;
}
//SubsetVersion is the 3rd
int thisSubsetVersion = Integer.parseInt(lineItems[RF1_IDX_SUBSETVERSION]);
if (thisSubsetVersion > previousSubsetVersion) {
previousSubsetVersion = thisSubsetVersion;
}
}
return maxSubsetIdInFile;
}
private void useDeterministicSubsetIds(int releaseIndex, EditionConfig config) throws RF1ConversionException {
try {
InputStream is = ConversionManager.class.getResourceAsStream(AVAILABLE_SUBSET_IDS);
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))){
String line;
int subsetIdsSet = 0;
subsetIds = new Long[config.dialects.length];
int filePos = 0;
while ((line = br.readLine()) != null && subsetIdsSet < config.dialects.length) {
filePos++;
Long thisAvailableSubsetId = Long.parseLong(line.trim());
if (filePos >= releaseIndex) {
debug ("Obtaining new Subset Ids from resource file");
subsetIds[subsetIdsSet] = thisAvailableSubsetId;
subsetIdsSet++;
}
}
}
} catch (IOException e) {
throw new RF1ConversionException("Unable to determine new subset Ids",e);
}
}
private void setSubsetIds(int newSubsetVersion) {
for (int i=0 ; i<subsetIds.length; i++) {
db.runStatement("SET @SUBSETID_" + (i+1) + " = " + subsetIds[i]);
}
db.runStatement("SET @SUBSET_VERSION = " + newSubsetVersion);
}
int calculateReleaseIndex(String releaseDate) {
//returns a number that can be used when a previous release is not available
//to give an incrementing variable that we can use to move through the SCTID 02 & 03 files
int year = Integer.parseInt(releaseDate.substring(0, 4));
int month = Integer.parseInt(releaseDate.substring(4,6));
int index = ((year - 2016)*10) + month;
return index;
}
private void pullDocumentationFromRF2(File loadingArea, File exportArea, String releaseDate, EditionConfig editionConfig) {
FileFilter fileFilter = new WildcardFileFilter("*" + RELEASE_NOTES + "*");
File[] files = loadingArea.listFiles(fileFilter);
String outputRootPath = getOutputRootPath(exportArea, releaseDate, editionConfig);
String destDir = outputRootPath + File.separator + DOCUMENTATION_DIR + File.separator;
for (File file : files) {
try{
File destFile = new File (destDir + file.getName());
FileUtils.copyFile(file, destFile);
} catch (IOException e) {
debug ("Failed to copy " + file + " to destination area: " + e.toString());
}
}
}
}
| src/main/java/org/ihtsdo/snomed/rf2torf1conversion/ConversionManager.java | package org.ihtsdo.snomed.rf2torf1conversion;
import static org.ihtsdo.snomed.rf2torf1conversion.GlobalUtils.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.ihtsdo.snomed.rf2torf1conversion.pojo.Concept;
import org.ihtsdo.snomed.rf2torf1conversion.pojo.ConceptDeserializer;
import org.ihtsdo.snomed.rf2torf1conversion.pojo.LateralityIndicator;
import org.ihtsdo.snomed.rf2torf1conversion.pojo.QualifyingRelationshipAttribute;
import org.ihtsdo.snomed.rf2torf1conversion.pojo.QualifyingRelationshipRule;
import org.ihtsdo.snomed.rf2torf1conversion.pojo.RF1SchemaConstants;
import org.ihtsdo.snomed.rf2torf1conversion.pojo.RF2SchemaConstants;
import com.google.common.base.Stopwatch;
import com.google.common.io.Files;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class ConversionManager implements RF2SchemaConstants, RF1SchemaConstants {
File intRf2Archive;
File extRf2Archive;
File unzipLocation = null;
File additionalFilesLocation = null;
File previousRF1Location;
boolean useRelationshipIds = false;
DBManager db;
String intReleaseDate;
String extReleaseDate;
boolean includeHistory = true;
boolean includeAllQualifyingRelationships = false;
boolean includeLateralityIndicators = true; //Laterality is now obligatory
boolean isBeta = false;
boolean onlyHistory = false;
boolean isExtension = false;
boolean goInteractive = false;
boolean isSnapshotConversion = false;
Edition edition;
private String EXT = "EXT";
private String LNG = "LNG";
private String MOD = "MOD";
private String DATE = "DATE";
private String OUT = "OUT";
private String TYPE = "TYPE";
private String outputFolderTemplate = "SnomedCT_OUT_MOD_DATE";
private String ANCIENT_HISTORY = "/sct1_ComponentHistory_Core_INT_20130731.txt";
private String QUALIFYING_RULES = "/qualifying_relationship_rules.json";
private String AVAILABLE_SUBSET_IDS = "/available_sctids_partition_03.txt";
private String AVAILABLE_RELATIONSHIP_IDS = "/available_sctids_partition_02.txt";
private String RELATIONSHIP_FILENAME = "SnomedCT_OUT_MOD_DATE/Terminology/Content/sct1_Relationships_Core_MOD_DATE.txt";
private String BETA_PREFIX = "x";
Set<File> filesLoaded = new HashSet<File>();
private Long[] subsetIds;
private Long maxPreviousSubsetId = null;
private int previousSubsetVersion = 29; //Taken from 20160131 RF1 International Release
private static final String RELEASE_NOTES = "SnomedCTReleaseNotes";
private static final String DOCUMENTATION_DIR = "Documentation/";
private static final String LATERALITY_SNAPSHOT_TEMPLATE = "der2_Refset_SimpleSnapshot_MOD_DATE.txt";
private static final int SUFFICIENT_LATERALITY_DATA = 10;
enum Edition { INTERNATIONAL, SPANISH, US, SG };
class Dialect {
String langRefSetId;
String langCode;
Dialect (String langRefSetId, String langCode) {
this.langRefSetId = langRefSetId;
this.langCode = langCode;
}
}
public final Dialect dialectSg = new Dialect ("9011000132109","sg"); //Singapore English
public final Dialect dialectEs = new Dialect ("450828004","es"); //Latin American Spanish
public final Dialect dialectGb = new Dialect ("900000000000508004","en-GB");
public final Dialect dialectUs = new Dialect ("900000000000509007","en-US");
class EditionConfig {
String editionName;
String langCode;
String module;
String outputName;
boolean historyAvailable;
Dialect[] dialects;
EditionConfig (String editionName, String language, String module, String outputName, boolean historyAvailable, Dialect[] dialects) {
this.editionName = editionName;
this.outputName = outputName;
this.langCode = language;
this.module = module;
this.historyAvailable = historyAvailable;
this.dialects = dialects;
}
}
private static final String EDITION_DETERMINER = "sct2_Description_EXTTYPE-LNG_MOD_DATE.txt";
static Map<Edition, EditionConfig> knownEditionMap = new HashMap<Edition, EditionConfig>();
{
//Edition Config values: editionName, language, module, outputName, dialects[]
knownEditionMap.put(Edition.INTERNATIONAL, new EditionConfig("", "en", "INT", "RF1Release", true, new Dialect[]{dialectGb, dialectUs})); //International Edition has no Extension name
knownEditionMap.put(Edition.SPANISH, new EditionConfig("SpanishExtension", "es", "INT", "SpanishRelease-es", true ,new Dialect[]{dialectEs}));
knownEditionMap.put(Edition.US, new EditionConfig("", "en", "US1000124", "RF1Release", false, new Dialect[]{dialectGb, dialectUs}));
knownEditionMap.put(Edition.SG, new EditionConfig("", "en-SG", "SG1000132", "RF1Release", true, new Dialect[]{dialectGb, dialectUs, dialectSg}));
}
static Map<String, String> editionfileToTable = new HashMap<String, String>();
{
editionfileToTable.put("sct2_Concept_EXTTYPE_MOD_DATE.txt", "rf2_concept_sv");
editionfileToTable.put("sct2_Relationship_EXTTYPE_MOD_DATE.txt", "rf2_rel_sv");
editionfileToTable.put("sct2_StatedRelationship_EXTTYPE_MOD_DATE.txt", "rf2_rel_sv");
editionfileToTable.put("sct2_Identifier_EXTTYPE_MOD_DATE.txt", "rf2_identifier_sv");
//Extensions can use a mix of International and their own descriptions
editionfileToTable.put(EDITION_DETERMINER, "rf2_term_sv");
//We need to know the International Preferred Term if the Extension doesn't specify one
editionfileToTable.put("der2_cRefset_LanguageEXTTYPE-LNG_MOD_DATE.txt", "rf2_crefset_sv");
//Concepts still need inactivation reasons from the International Edition
editionfileToTable.put("der2_cRefset_AssociationReferenceEXTTYPE_MOD_DATE.txt", "rf2_crefset_sv");
editionfileToTable.put("der2_cRefset_AttributeValueEXTTYPE_MOD_DATE.txt", "rf2_crefset_sv");
//CTV3 and SNOMED RT Identifiers come from the International Edition
editionfileToTable.put("der2_sRefset_SimpleMapEXTTYPE_MOD_DATE.txt", "rf2_srefset_sv");
//intfileToTable.put("der2_iissscRefset_ComplexEXTMapTYPE_MOD_DATE.txt", "rf2_iissscrefset_sv");
//intfileToTable.put("der2_iisssccRefset_ExtendedMapEXTTYPE_MOD_DATE.txt", "rf2_iisssccrefset_sv");
}
static Map<String, String> extensionfileToTable = new HashMap<String, String>();
{
//Extension could supplement any file in international edition
extensionfileToTable.putAll(editionfileToTable);
extensionfileToTable.put(EDITION_DETERMINER, "rf2_term_sv");
extensionfileToTable.put("sct2_TextDefinition_EXTTYPE-LNG_MOD_DATE.txt", "rf2_def_sv");
extensionfileToTable.put("der2_cRefset_AssociationReferenceEXTTYPE_MOD_DATE.txt", "rf2_crefset_sv");
extensionfileToTable.put("der2_cRefset_AttributeValueEXTTYPE_MOD_DATE.txt", "rf2_crefset_sv");
extensionfileToTable.put("der2_Refset_SimpleEXTTYPE_MOD_DATE.txt", "rf2_refset_sv");
extensionfileToTable.put("der2_cRefset_LanguageEXTTYPE-LNG_MOD_DATE.txt", "rf2_crefset_sv");
extensionfileToTable.put("der2_sRefset_SimpleMapEXTTYPE_MOD_DATE.txt", "rf2_srefset_sv");
//extfileToTable.put("der2_iissscRefset_ComplexEXTMapTYPE_MOD_DATE.txt", "rf2_iissscrefset_sv");
//extfileToTable.put("der2_iisssccRefset_ExtendedMapEXTTYPE_MOD_DATE.txt", "rf2_iisssccrefset_sv");
extensionfileToTable.put("der2_cciRefset_RefsetDescriptorEXTTYPE_MOD_DATE.txt", "rf2_ccirefset_sv");
extensionfileToTable.put("der2_ciRefset_DescriptionTypeEXTTYPE_MOD_DATE.txt", "rf2_cirefset_sv");
extensionfileToTable.put("der2_ssRefset_ModuleDependencyEXTTYPE_MOD_DATE.txt", "rf2_ssrefset_sv");
}
public static Map<String, String>intExportMap = new HashMap<String, String>();
{
// The slashes will be replaced with the OS appropriate separator at export time
intExportMap.put(outputFolderTemplate + "/Terminology/Content/sct1_Concepts_Core_MOD_DATE.txt",
"select CONCEPTID, CONCEPTSTATUS, FULLYSPECIFIEDNAME, CTV3ID, SNOMEDID, ISPRIMITIVE from rf21_concept");
intExportMap
.put(RELATIONSHIP_FILENAME,
"select RELATIONSHIPID,CONCEPTID1,RELATIONSHIPTYPE,CONCEPTID2,CHARACTERISTICTYPE,REFINABILITY,RELATIONSHIPGROUP from rf21_rel");
}
public static Map<String, String> extExportMap = new HashMap<String, String>();
{
// The slashes will be replaced with the OS appropriate separator at export time
extExportMap
.put(outputFolderTemplate + "/Terminology/Content/sct1_Descriptions_LNG_MOD_DATE.txt",
"select DESCRIPTIONID, DESCRIPTIONSTATUS, CONCEPTID, TERM, INITIALCAPITALSTATUS, DESC_TYPE as DESCRIPTIONTYPE, LANGUAGECODE from rf21_term");
extExportMap.put(outputFolderTemplate + "/Terminology/History/sct1_References_Core_MOD_DATE.txt",
"select COMPONENTID, REFERENCETYPE, REFERENCEDID from rf21_REFERENCE");
extExportMap
.put(outputFolderTemplate + "/Resources/StatedRelationships/res1_StatedRelationships_Core_MOD_DATE.txt",
"select RELATIONSHIPID,CONCEPTID1,RELATIONSHIPTYPE,CONCEPTID2,CHARACTERISTICTYPE,REFINABILITY,RELATIONSHIPGROUP from rf21_stated_rel");
}
public static void main(String[] args) throws RF1ConversionException {
//Set Windows Line separator as that's an RF1 standard
System.setProperty("line.separator", "\r\n");
ConversionManager cm = new ConversionManager();
cm.doRf2toRf1Conversion(args);
}
private void doRf2toRf1Conversion(String[] args) throws RF1ConversionException {
File tempDBLocation = Files.createTempDir();
init(args, tempDBLocation);
createDatabaseSchema();
File intLoadingArea = null;
File extLoadingArea = null;
File exportArea = null;
Stopwatch stopwatch = Stopwatch.createStarted();
String completionStatus = "failed";
try {
print("\nExtracting RF2 International Edition Data...");
intLoadingArea = unzipArchive(intRf2Archive);
intReleaseDate = findDateInString(intLoadingArea.listFiles()[0].getName(), false);
extReleaseDate = intReleaseDate;
determineEdition(intLoadingArea, intReleaseDate);
if (extRf2Archive != null) {
print("\nExtracting RF2 Extension Data...");
extLoadingArea = unzipArchive(extRf2Archive);
extReleaseDate = findDateInString(extLoadingArea.listFiles()[0].getName(), false);
determineEdition(extLoadingArea, extReleaseDate);
isExtension = true;
}
String releaseDate = isExtension ? extReleaseDate : intReleaseDate;
File loadingArea = isExtension ? extLoadingArea : intLoadingArea;
int releaseIndex = calculateReleaseIndex(releaseDate);
EditionConfig config = knownEditionMap.get(edition);
//Laterality indicators are now obligatory
loadLateralityIndicators(intLoadingArea, intReleaseDate, config);
int newSubsetVersion = 0;
if (previousRF1Location != null) {
useRelationshipIds = true;
//This will allow us to set up SubsetIds (using available_sctids_partition_03)
//And a map of existing relationship Ids to use for reconciliation
loadPreviousRF1(config);
//Initialise a set of available SCTIDS
InputStream availableRelIds = ConversionManager.class.getResourceAsStream(AVAILABLE_RELATIONSHIP_IDS);
RF1Constants.intialiseAvailableRelationships(availableRelIds);
newSubsetVersion = previousSubsetVersion + 1;
} else {
useDeterministicSubsetIds(releaseIndex, config);
newSubsetVersion = previousSubsetVersion + releaseIndex;
}
db.runStatement("SET @useRelationshipIds = " + useRelationshipIds);
setSubsetIds(newSubsetVersion);
long targetOperationCount = getTargetOperationCount();
if (onlyHistory) {
targetOperationCount = 250;
} else if (isExtension) {
targetOperationCount = includeHistory? targetOperationCount : 388;
} else {
targetOperationCount = includeHistory? targetOperationCount : 391;
}
setTargetOperationCount(targetOperationCount);
completeOutputMap(config);
db.runStatement("SET @langCode = '" + config.langCode + "'");
db.runStatement("SET @langRefSet = '" + config.dialects[0].langRefSetId + "'");
print("\nLoading " + edition.toString() +" common RF2 Data...");
loadRF2Data(intLoadingArea, config, intReleaseDate, editionfileToTable);
//Load the rest of the files from the same loading area if International Release, otherwise use the extensionLoading Area
print("\nLoading " + edition +" specific RF2 Data...");
loadRF2Data(loadingArea, config, releaseDate, extensionfileToTable);
debug("\nCreating RF2 indexes...");
db.executeResource("create_rf2_indexes.sql");
if (!onlyHistory) {
print("\nCalculating RF2 snapshot...");
calculateRF2Snapshot(releaseDate);
}
print("\nConverting RF2 to RF1...");
convert(config);
print("\nExporting RF1 to file...");
exportArea = Files.createTempDir();
exportRF1Data(intExportMap, releaseDate, intReleaseDate, knownEditionMap.get(edition), exportArea);
exportRF1Data(extExportMap, releaseDate, releaseDate, knownEditionMap.get(edition), exportArea);
//Relationship file uses the international release date, even for extensions. Well, the Spanish one anyway.
//But we also need the extension release date for the top level directory
String filePath = getQualifyingRelationshipFilepath(intReleaseDate, extReleaseDate, knownEditionMap.get(edition), exportArea);
if (includeAllQualifyingRelationships || includeLateralityIndicators) {
print("\nLoading Inferred Relationship Hierarchy for Qualifying Relationship computation...");
loadRelationshipHierarchy(knownEditionMap.get(Edition.INTERNATIONAL), intLoadingArea);
}
if (includeAllQualifyingRelationships) {
print ("\nGenerating qualifying relationships");
Set<QualifyingRelationshipAttribute> ruleAttributes = loadQualifyingRelationshipRules();
generateQualifyingRelationships(ruleAttributes, filePath);
}
if (includeLateralityIndicators) {
print ("\nGenerating laterality qualifying relationships");
generateLateralityRelationships(filePath);
}
boolean documentationIncluded = false;
if (additionalFilesLocation != null) {
documentationIncluded = includeAdditionalFiles(exportArea, releaseDate, knownEditionMap.get(edition));
}
if (!documentationIncluded) {
pullDocumentationFromRF2(loadingArea, exportArea, releaseDate, knownEditionMap.get(edition));
}
print("\nZipping archive");
createArchive(exportArea);
completionStatus = "completed";
} finally {
print("\nProcess " + completionStatus + " in " + stopwatch + " after completing " + getProgress() + "/" + getTargetOperationCount()
+ " operations.");
if (goInteractive) {
doInteractive();
}
try {
print(RF1Constants.getRelationshipIdUsageSummary());
} catch (Exception e){}
print("Cleaning up resources...");
try {
db.shutDown(true); // Also deletes all files
if (tempDBLocation != null && tempDBLocation.exists()) {
tempDBLocation.delete();
}
} catch (Exception e) {
debug("Error while cleaning up database " + tempDBLocation.getPath() + e.getMessage());
}
try {
if (intLoadingArea != null && intLoadingArea.exists()) {
FileUtils.deleteDirectory(intLoadingArea);
}
if (extLoadingArea != null && extLoadingArea.exists()) {
FileUtils.deleteDirectory(extLoadingArea);
}
if (exportArea != null && exportArea.exists()) {
FileUtils.deleteDirectory(exportArea);
}
} catch (Exception e) {
debug("Error while cleaning up loading/export Areas " + e.getMessage());
}
}
}
private void doInteractive() {
boolean quitDetected = false;
StringBuilder buff = new StringBuilder();
try (Scanner in = new Scanner(System.in)) {
print ("Enter sql command to run, terminate with semicolon or type quit; to finish");
while (!quitDetected) {
buff.append(in.nextLine().trim());
if (buff.length() > 1 && buff.charAt(buff.length()-1) == ';') {
String command = buff.toString();
if (command.equalsIgnoreCase("quit;")) {
quitDetected = true;
} else {
try{
db.runStatement(command.toString());
} catch (Exception e) {
e.printStackTrace();
}
buff.setLength(0);
}
} else {
buff.append(" ");
}
}
}
}
private void completeOutputMap(EditionConfig editionConfig) {
if (isExtension) {
String archiveName = "SnomedCT_OUT_MOD_DATE";
String folderName = "Language-" + editionConfig.langCode;
String fileRoot = archiveName + File.separator + "Subsets" + File.separator + folderName + File.separator;
String fileName = "der1_SubsetMembers_"+ editionConfig.langCode + "_MOD_DATE.txt";
extExportMap.put(fileRoot + fileName,
"select s.SubsetId, s.MemberID, s.MemberStatus, s.LinkedID from rf21_SUBSETS s, rf21_SUBSETLIST sl where s.SubsetOriginalId = sl.subsetOriginalId AND sl.languageCode = ''" + editionConfig.langCode + "'';");
fileName = "der1_Subsets_" + editionConfig.langCode + "_MOD_DATE.txt";
extExportMap.put(fileRoot + fileName,
"select sl.* from rf21_SUBSETLIST sl where languagecode = ''" + editionConfig.langCode + "'';");
extExportMap.put("SnomedCT_OUT_MOD_DATE/Resources/TextDefinitions/sct1_TextDefinitions_LNG_MOD_DATE.txt",
"select * from rf21_DEF");
} else {
extExportMap.put("SnomedCT_OUT_MOD_DATE/Resources/TextDefinitions/sct1_TextDefinitions_en-US_MOD_DATE.txt",
"select * from rf21_DEF");
extExportMap
.put("SnomedCT_OUT_MOD_DATE/Subsets/Language-en-GB/der1_SubsetMembers_en-GB_MOD_DATE.txt",
"select s.SubsetId, s.MemberID, s.MemberStatus, s.LinkedID from rf21_SUBSETS s, rf21_SUBSETLIST sl where s.SubsetOriginalId = sl.subsetOriginalId AND sl.languageCode in (''en'',''en-GB'')");
extExportMap.put("SnomedCT_OUT_MOD_DATE/Subsets/Language-en-GB/der1_Subsets_en-GB_MOD_DATE.txt",
"select sl.* from rf21_SUBSETLIST sl where languagecode like ''%GB%''");
extExportMap
.put("SnomedCT_OUT_MOD_DATE/Subsets/Language-en-US/der1_SubsetMembers_en-US_MOD_DATE.txt",
"select s.SubsetId, s.MemberID, s.MemberStatus, s.LinkedID from rf21_SUBSETS s, rf21_SUBSETLIST sl where s.SubsetOriginalId = sl.subsetOriginalId AND sl.languageCode in (''en'',''en-US'')");
extExportMap.put("SnomedCT_RF1Release_MOD_DATE/Subsets/Language-en-US/der1_Subsets_en-US_MOD_DATE.txt",
"select sl.* from rf21_SUBSETLIST sl where languagecode like ''%US%''");
}
if (includeHistory) {
extExportMap.put("SnomedCT_OUT_MOD_DATE/Terminology/History/sct1_ComponentHistory_Core_MOD_DATE.txt",
"select COMPONENTID, RELEASEVERSION, CHANGETYPE, STATUS, REASON from rf21_COMPONENTHISTORY");
}
}
private void determineEdition(File loadingArea, String releaseDate) throws RF1ConversionException {
//Loop through known editions and see if EDITION_DETERMINER file is present
for (Map.Entry<Edition, EditionConfig> thisEdition : knownEditionMap.entrySet())
for (File thisFile : loadingArea.listFiles()) {
EditionConfig parts = thisEdition.getValue();
String target = EDITION_DETERMINER.replace(EXT, parts.editionName)
.replace(LNG, parts.langCode)
.replace(MOD, parts.module)
.replace(DATE, releaseDate)
.replace(TYPE, isSnapshotConversion ? "Snapshot" : "Full");
if (thisFile.getName().equals(target)) {
this.edition = thisEdition.getKey();
return;
}
}
throw new RF1ConversionException ("Failed to find file matching any known edition: " + EDITION_DETERMINER + " in " + loadingArea.getAbsolutePath());
}
private File unzipArchive(File archive) throws RF1ConversionException {
File tempDir = null;
try {
if (unzipLocation != null) {
tempDir = java.nio.file.Files.createTempDirectory(unzipLocation.toPath(), "rf2-to-rf1-").toFile();
} else {
// Work in the traditional temp file location for the OS
tempDir = Files.createTempDir();
}
} catch (IOException e) {
throw new RF1ConversionException("Unable to create temporary directory for archive extration");
}
// We only need to work with the full files
// ...mostly, we also need the Snapshot Relationship file in order to work out the Qualifying Relationships
// Also we'll take the documentation pdf
String match = isSnapshotConversion ? "Snapshot" : "Full";
unzipFlat(archive, tempDir, new String[]{ match, "sct2_Relationship_Snapshot","der2_Refset_SimpleSnapshot",RELEASE_NOTES});
return tempDir;
}
private void createDatabaseSchema() throws RF1ConversionException {
print("Creating database schema");
db.executeResource("create_rf2_schema.sql");
}
private void calculateRF2Snapshot(String releaseDate) throws RF1ConversionException {
String setDateSql = "SET @RDATE = " + releaseDate;
db.runStatement(setDateSql);
db.executeResource("create_rf2_snapshot.sql");
db.executeResource("populate_subset_2_refset.sql");
}
private void convert(EditionConfig config) throws RF1ConversionException {
db.executeResource("create_rf1_schema.sql");
if (includeHistory && config.historyAvailable) {
db.executeResource("populate_rf1_historical.sql");
} else {
print("\nSkipping generation of RF1 History. Set -h parameter if this is required (selected Editions only).");
}
if (!onlyHistory) {
db.executeResource("populate_rf1.sql");
if (isExtension) {
db.executeResource("populate_rf1_ext_descriptions.sql");
} else {
db.executeResource("populate_rf1_int_descriptions.sql");
}
db.executeResource("populate_rf1_associations.sql");
if (useRelationshipIds) {
db.executeResource("populate_rf1_rel_ids.sql");
}
}
}
private void init(String[] args, File dbLocation) throws RF1ConversionException {
if (args.length < 1) {
print("Usage: java ConversionManager [-v] [-h] [-b] [-i] [-a <additional files location>] [-p <previous RF1 archive] [-u <unzip location>] <rf2 archive location> [<rf2 extension archive>]");
print(" b - beta indicator, causes an x to be prepended to output filenames");
print(" p - previous RF1 archive required for SubsetId and Relationship Id generation");
exit();
}
boolean isUnzipLocation = false;
boolean isAdditionalFilesLocation = false;
boolean isPreviousRF1Location = false;
for (String thisArg : args) {
if (thisArg.equals("-v")) {
GlobalUtils.verbose = true;
} else if (thisArg.equals("-i")) {
goInteractive = true;
} else if (thisArg.equals("-s")) {
//New feature, currently undocumented until proven.
print ("Option set to perform conversion on Snapshot files. No history will be produced.");
isSnapshotConversion = true;
includeHistory = false;
if (onlyHistory) {
throw new RF1ConversionException("History is not possible with a snapshot conversion");
}
} else if (thisArg.equals("-H")) {
includeHistory = true;
onlyHistory = true;
if (isSnapshotConversion) {
throw new RF1ConversionException("History is not possible with a snapshot conversion");
}
} else if (thisArg.equals("-b")) {
isBeta = true;
}else if (thisArg.equals("-u")) {
isUnzipLocation = true;
} else if (thisArg.equals("-a")) {
isAdditionalFilesLocation = true;
} else if (thisArg.equals("-p")) {
isPreviousRF1Location = true;
} else if (thisArg.equals("-q")) {
//The rule file for generating these relationships is currently incomplete and incorrect.
includeAllQualifyingRelationships = true;
} else if (isUnzipLocation) {
unzipLocation = new File(thisArg);
if (!unzipLocation.isDirectory()) {
throw new RF1ConversionException(thisArg + " is an invalid location to unzip archive to!");
}
isUnzipLocation = false;
} else if (isAdditionalFilesLocation) {
additionalFilesLocation = new File(thisArg);
if (!additionalFilesLocation.isDirectory()) {
throw new RF1ConversionException(thisArg + " is an invalid location to find additional files.");
}
isAdditionalFilesLocation = false;
} else if (isPreviousRF1Location) {
previousRF1Location = new File(thisArg);
if (!previousRF1Location.exists() || !previousRF1Location.canRead()) {
throw new RF1ConversionException(thisArg + " does not appear to be a valid RF1 archive.");
}
isPreviousRF1Location = false;
} else if (intRf2Archive == null){
File possibleArchive = new File(thisArg);
if (possibleArchive.exists() && !possibleArchive.isDirectory() && possibleArchive.canRead()) {
intRf2Archive = possibleArchive;
}
} else {
File possibleArchive = new File(thisArg);
if (possibleArchive.exists() && !possibleArchive.isDirectory() && possibleArchive.canRead()) {
extRf2Archive = possibleArchive;
}
}
}
if (intRf2Archive == null) {
print("Unable to load RF2 Archive: " + args[args.length - 1]);
exit();
}
db = new DBManager();
db.init(dbLocation);
}
private void loadRF2Data(File loadingArea, EditionConfig config, String releaseDate, Map<String, String> fileToTable) throws RF1ConversionException {
// We can do the load in parallel. Only 3 threads because heavily I/O
db.startParallelProcessing(3);
String releaseType = isSnapshotConversion ? "Snapshot":"Full";
for (Map.Entry<String, String> entry : fileToTable.entrySet()) {
// Replace DATE in the filename with the actual release date
String fileName = entry.getKey().replace(DATE, releaseDate)
.replace(EXT, config.editionName)
.replace(LNG, config.langCode)
.replace(MOD, config.module)
.replace(TYPE, releaseType);
File file = new File(loadingArea + File.separator + fileName);
//Only load each file once
if (filesLoaded.contains(file)) {
debug ("Skipping " + file.getName() + " already loaded as a common file.");
} else if (file.exists()) {
db.load(file, entry.getValue());
filesLoaded.add(file);
} else {
print("\nWarning, skipping load of file " + file.getName() + " - not present");
}
}
db.finishParallelProcessing();
}
private void exportRF1Data(Map<String, String> exportMap, String packageReleaseDate, String fileReleaseDate, EditionConfig config, File exportArea) throws RF1ConversionException {
// We can do the export in parallel. Only 3 threads because heavily I/O
db.startParallelProcessing(3);
for (Map.Entry<String, String> entry : exportMap.entrySet()) {
// Replace DATE in the filename with the actual release date
String fileName = entry.getKey().replaceFirst(DATE, packageReleaseDate)
.replace(DATE, fileReleaseDate)
.replace(OUT, config.outputName)
.replace(LNG, config.langCode)
.replace(MOD, config.module);
fileName = modifyFilenameIfBeta(fileName);
String filePath = exportArea + File.separator + fileName;
//If we're doing the history file, then we need to prepend the static
//resource file
InputStream isInclude = null;
if (includeHistory && fileName.contains("ComponentHistory")) {
isInclude = ConversionManager.class.getResourceAsStream(ANCIENT_HISTORY);
if (isInclude == null) {
throw new RF1ConversionException("Unable to obtain history file: " + ANCIENT_HISTORY);
}
}
db.export(filePath, entry.getValue(), isInclude);
}
db.finishParallelProcessing();
}
private String modifyFilenameIfBeta(String fileName) {
if (isBeta) {
//Beta prefix before the file shortname, but also for the leading directory
int lastSlash = fileName.lastIndexOf(File.separator) + 1;
fileName = BETA_PREFIX + fileName.substring(0,lastSlash) + BETA_PREFIX + fileName.substring(lastSlash);
}
return fileName;
}
private void loadRelationshipHierarchy(EditionConfig config, File intLoadingArea) throws RF1ConversionException {
String fileName = intLoadingArea.getAbsolutePath() + File.separator + "sct2_Relationship_Snapshot_MOD_DATE.txt";
fileName = fileName.replace(DATE, intReleaseDate)
.replace(MOD, config.module);
GraphLoader gl = new GraphLoader (fileName);
gl.loadRelationships();
}
private Set<QualifyingRelationshipAttribute> loadQualifyingRelationshipRules() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Concept.class, new ConceptDeserializer());
Gson gson = gsonBuilder.create();
InputStream jsonStream = ConversionManager.class.getResourceAsStream(QUALIFYING_RULES);
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(jsonStream));
Type listType = new TypeToken<Set<QualifyingRelationshipAttribute>>() {}.getType();
Set<QualifyingRelationshipAttribute> attributes = gson.fromJson(jsonReader, listType);
return attributes;
}
/**
* This is a temporary measure until we can get the Laterality Reference published as a refset.
* at which point it will stop being an external file
* @param loadingArea
*/
private void loadLateralityIndicators(File loadingArea, String releaseDate, EditionConfig config) throws RF1ConversionException {
String targetFilename = LATERALITY_SNAPSHOT_TEMPLATE.replace(DATE, releaseDate).replace(MOD, config.module);
File lateralityFile = new File(loadingArea.getAbsolutePath() + File.separator + targetFilename);
boolean sufficientDataReadOK = true;
if (!lateralityFile.canRead()) {
debug ("Could not find " + targetFilename + " among " + GlobalUtils.listDirectory(loadingArea));
sufficientDataReadOK = false;
} else {
int linesRead = 0;
try (BufferedReader br = new BufferedReader(new FileReader(lateralityFile))) {
String line;
boolean firstLine = true;
while ((line = br.readLine()) != null) {
if (!firstLine) {
String[] columns = line.split(FIELD_DELIMITER);
if (columns[SIMP_IDX_ACTIVE].equals("1") && columns[SIMP_IDX_REFSETID].equals(LATERALITY_REFSET_ID)) {
LateralityIndicator.registerIndicator(columns[SIMP_IDX_REFCOMPID]);
linesRead++;
}
} else {
firstLine = false;
}
}
if (linesRead < SUFFICIENT_LATERALITY_DATA) {
sufficientDataReadOK = false;
}
} catch (IOException ioe) {
throw new RF1ConversionException ("Unable to import laterality reference file " + lateralityFile.getAbsolutePath(), ioe);
}
}
if (!sufficientDataReadOK && useRelationshipIds) {
String msg = "Laterality Reference Set not detected/available/sufficient in Simple Refset Snapshot: " + targetFilename + ".\nThis refset is compulsory in this version of the RF2 to RF1 converter, if Relationship IDs are to be generated.";
print("\n" + msg);
throw new RF1ConversionException (msg);
}
}
private void generateQualifyingRelationships(
Set<QualifyingRelationshipAttribute> ruleAttributes, String filePath) throws RF1ConversionException {
//For each attribute, work through each rule creating rules for self and all children of starting points,
//except for exceptions
try(FileWriter fw = new FileWriter(filePath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
for (QualifyingRelationshipAttribute thisAttribute : ruleAttributes) {
StringBuffer commonRF1 = new StringBuffer().append(FIELD_DELIMITER)
.append(thisAttribute.getType().getSctId()).append(FIELD_DELIMITER)
.append(thisAttribute.getDestination().getSctId()).append(FIELD_DELIMITER)
.append("1\t")//Qualifying Rel type
.append(thisAttribute.getRefinability()).append("\t0"); //Refineable, Group 0
for (QualifyingRelationshipRule thisRule : thisAttribute.getRules()) {
Set<Concept> potentialApplications = thisRule.getStartPoint().getAllDescendents(Concept.DEPTH_NOT_SET);
Collection<Concept> ruleAppliedTo = CollectionUtils.subtract(potentialApplications, thisRule.getExceptions());
for (Concept thisException : thisRule.getExceptions()) {
Set<Concept> exceptionDescendents = thisException.getAllDescendents(Concept.DEPTH_NOT_SET);
ruleAppliedTo = CollectionUtils.subtract(ruleAppliedTo, exceptionDescendents);
}
//Now the remaining concepts that the rules applies to can be written out to file
for (Concept thisConcept : ruleAppliedTo) {
//Concept may already have this attribute as a defining relationship, skip if so.
if (!thisConcept.hasAttribute(thisAttribute)) {
String rf1Line = FIELD_DELIMITER + thisConcept.getSctId() + commonRF1;
out.println(rf1Line);
}
}
}
}
} catch (IOException e) {
throw new RF1ConversionException ("Failure while outputting Qualifying Relationships: " + e.toString());
}
}
private void generateLateralityRelationships(String filePath) throws RF1ConversionException {
//Check every concept to see if has a laterality indicator, and doesn't already have that
//attribute as a defining relationship
Set<Concept> allConcepts = Concept.getConcept(SNOMED_ROOT_CONCEPT).getAllDescendents(Concept.DEPTH_NOT_SET);
StringBuffer commonRF1 = new StringBuffer().append(FIELD_DELIMITER)
.append(LATERALITY_ATTRIB).append(FIELD_DELIMITER)
.append(SIDE_VALUE).append(FIELD_DELIMITER)
.append("1\t")//Qualifying Rel type
.append(RF1Constants.MUST_REFINE).append("\t0"); //Refineable, Group 0
Concept lat = Concept.getConcept(Long.parseLong(LATERALITY_ATTRIB));
Concept side = Concept.getConcept(Long.parseLong(SIDE_VALUE));
QualifyingRelationshipAttribute LateralityAttribute = new QualifyingRelationshipAttribute (lat, side, RF1Constants.MUST_REFINE);
try(FileWriter fw = new FileWriter(filePath, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
for (Concept thisConcept : allConcepts) {
if (LateralityIndicator.hasLateralityIndicator(thisConcept.getSctId())) {
if (!thisConcept.hasAttribute(LateralityAttribute)) {
String relId = ""; //Default is to blank relationship ids
if (useRelationshipIds) {
relId = RF1Constants.lookupRelationshipId(thisConcept.getSctId().toString(),
LATERALITY_ATTRIB,
SIDE_VALUE,
UNGROUPED,
false); //working with inferred relationship ids
}
String rf1Line = relId + FIELD_DELIMITER + thisConcept.getSctId() + commonRF1;
out.println(rf1Line);
}
}
}
}catch (IOException e){
throw new RF1ConversionException ("Failure while output Laterality Relationships: " + e.toString());
}
}
private String getQualifyingRelationshipFilepath(String intReleaseDate,
String extReleaseDate, EditionConfig config, File exportArea) throws RF1ConversionException {
// Replace the top level Date with the Extension Date, and the
// Relationship file with the extension release date
String fileName = RELATIONSHIP_FILENAME.replaceFirst(DATE, extReleaseDate)
.replace(DATE, intReleaseDate)
.replace(OUT, config.outputName)
.replace(LNG, config.langCode)
.replace(MOD, config.module);
fileName = modifyFilenameIfBeta(fileName);
String filePath = exportArea + File.separator + fileName;
File outputFile = new File(filePath);
try{
if (!outputFile.exists()) {
outputFile.getParentFile().mkdirs();
outputFile.createNewFile();
}
} catch (IOException e) {
throw new RF1ConversionException("Unable to create file for Qualifying Relationships: " + e);
}
return filePath;
}
private boolean includeAdditionalFiles(File outputDirectory, String releaseDate, EditionConfig editionConfig){
Map<String, String> targetLocation = new HashMap<String, String>();
boolean documentationIncluded = false;
targetLocation.put(".pdf", DOCUMENTATION_DIR);
targetLocation.put("KeyIndex_", "Resources/Indexes/");
targetLocation.put("Canonical", "Resources/Canonical Table/");
String rootPath = getOutputRootPath(outputDirectory, releaseDate, editionConfig);
File[] directoryListing = additionalFilesLocation.listFiles();
if (directoryListing != null) {
for (File child : directoryListing) {
String childFilename = child.getName();
//Do we know to put this file in a particular location?
//otherwise path will remain the root path
for (String match : targetLocation.keySet()) {
if (childFilename.contains(match)) {
childFilename = targetLocation.get(match) + childFilename;
break;
}
}
//Ensure path exists for where file is being copied to
File copiedFile = new File (rootPath + childFilename);
copiedFile.getParentFile().mkdirs();
try {
FileUtils.copyFile(child, copiedFile);
print ("Copied additional file to " + copiedFile.getAbsolutePath());
if (copiedFile.getName().contains(RELEASE_NOTES)) {
documentationIncluded = true;
}
} catch (IOException e) {
print ("Unable to copy additional file " + childFilename + " due to " + e.getMessage());
}
}
}
return documentationIncluded;
}
private String getOutputRootPath(File outputDirectory, String releaseDate,
EditionConfig config) {
String rootPath = outputDirectory.getAbsolutePath()
+ File.separator
+ (isBeta?BETA_PREFIX:"")
+ outputFolderTemplate
+ File.separator;
rootPath = rootPath.replace(OUT, config.outputName)
.replace(DATE, releaseDate)
.replace(MOD, config.module);
return rootPath;
}
private void loadPreviousRF1(EditionConfig config) throws RF1ConversionException {
int previousRelFilesLoaded = 0;
try {
ZipInputStream zis = new ZipInputStream(new FileInputStream(previousRF1Location));
ZipEntry ze = zis.getNextEntry();
try {
while (ze != null) {
if (!ze.isDirectory()) {
Path p = Paths.get(ze.getName());
String fileName = p.getFileName().toString();
if (fileName.contains("der1_Subsets")) {
updateSubsetIds(zis, config);
} else if (fileName.contains("sct1_Relationships")) {
//We need to use static methods here so that H2 can access as functions.
print ("\nLoading previous RF1 inferred relationships");
RF1Constants.loadPreviousRelationships(zis, false);
previousRelFilesLoaded++;
}else if (fileName.contains("res1_StatedRelationships")) {
print ("\nLoading previous RF1 stated relationships");
RF1Constants.loadPreviousRelationships(zis, true);
previousRelFilesLoaded++;
}
}
ze = zis.getNextEntry();
}
} finally {
zis.closeEntry();
zis.close();
}
} catch (IOException e) {
throw new RF1ConversionException("Failed to load previous RF1 archive " + previousRF1Location.getName(), e);
}
if (previousRelFilesLoaded != 2) {
throw new RF1ConversionException("Expected to load 2 previous relationship files, instead loaded " + previousRelFilesLoaded );
}
}
private void updateSubsetIds(ZipInputStream zis, EditionConfig config) throws NumberFormatException, IOException {
//This function will also pick up and set the previous subset version
Long subsetId = loadSubsetsFile(zis);
//Do we need to recover a new set of subsetIds?
if (maxPreviousSubsetId == null || subsetId > maxPreviousSubsetId) {
maxPreviousSubsetId = subsetId;
InputStream is = ConversionManager.class.getResourceAsStream(AVAILABLE_SUBSET_IDS);
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))){
String line;
int subsetIdsSet = 0;
subsetIds = new Long[config.dialects.length];
while ((line = br.readLine()) != null && subsetIdsSet < config.dialects.length) {
Long thisAvailableSubsetId = Long.parseLong(line.trim());
if (thisAvailableSubsetId.compareTo(maxPreviousSubsetId) > 0) {
debug ("Obtaining new Subset Ids from resource file");
subsetIds[subsetIdsSet] = thisAvailableSubsetId;
subsetIdsSet++;
}
}
}
}
}
/*
* @return the greatest subsetId in the file
*/
private Long loadSubsetsFile(ZipInputStream zis) throws IOException {
Long maxSubsetIdInFile = null;
BufferedReader br = new BufferedReader(new InputStreamReader(zis, StandardCharsets.UTF_8));
String line;
boolean isFirstLine = true;
while ((line = br.readLine()) != null) {
if (isFirstLine) {
isFirstLine = false;
continue;
}
String[] lineItems = line.split(FIELD_DELIMITER);
//SubsetId is the first column
Long thisSubsetId = Long.parseLong(lineItems[RF1_IDX_SUBSETID]);
if (maxSubsetIdInFile == null || thisSubsetId > maxSubsetIdInFile) {
maxSubsetIdInFile = thisSubsetId;
}
//SubsetVersion is the 3rd
int thisSubsetVersion = Integer.parseInt(lineItems[RF1_IDX_SUBSETVERSION]);
if (thisSubsetVersion > previousSubsetVersion) {
previousSubsetVersion = thisSubsetVersion;
}
}
return maxSubsetIdInFile;
}
private void useDeterministicSubsetIds(int releaseIndex, EditionConfig config) throws RF1ConversionException {
try {
InputStream is = ConversionManager.class.getResourceAsStream(AVAILABLE_SUBSET_IDS);
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))){
String line;
int subsetIdsSet = 0;
subsetIds = new Long[config.dialects.length];
int filePos = 0;
while ((line = br.readLine()) != null && subsetIdsSet < config.dialects.length) {
filePos++;
Long thisAvailableSubsetId = Long.parseLong(line.trim());
if (filePos >= releaseIndex) {
debug ("Obtaining new Subset Ids from resource file");
subsetIds[subsetIdsSet] = thisAvailableSubsetId;
subsetIdsSet++;
}
}
}
} catch (IOException e) {
throw new RF1ConversionException("Unable to determine new subset Ids",e);
}
}
private void setSubsetIds(int newSubsetVersion) {
for (int i=0 ; i<subsetIds.length; i++) {
db.runStatement("SET @SUBSETID_" + (i+1) + " = " + subsetIds[i]);
}
db.runStatement("SET @SUBSET_VERSION = " + newSubsetVersion);
}
int calculateReleaseIndex(String releaseDate) {
//returns a number that can be used when a previous release is not available
//to give an incrementing variable that we can use to move through the SCTID 02 & 03 files
int year = Integer.parseInt(releaseDate.substring(0, 4));
int month = Integer.parseInt(releaseDate.substring(4,6));
int index = ((year - 2016)*10) + month;
return index;
}
private void pullDocumentationFromRF2(File loadingArea, File exportArea, String releaseDate, EditionConfig editionConfig) {
FileFilter fileFilter = new WildcardFileFilter("*" + RELEASE_NOTES + "*");
File[] files = loadingArea.listFiles(fileFilter);
String outputRootPath = getOutputRootPath(exportArea, releaseDate, editionConfig);
String destDir = outputRootPath + File.separator + DOCUMENTATION_DIR + File.separator;
for (File file : files) {
try{
File destFile = new File (destDir + file.getName());
FileUtils.copyFile(file, destFile);
} catch (IOException e) {
debug ("Failed to copy " + file + " to destination area: " + e.toString());
}
}
}
}
| Change der2_cRefset_AssociationReference file to der2_cRefset_Association
| src/main/java/org/ihtsdo/snomed/rf2torf1conversion/ConversionManager.java | Change der2_cRefset_AssociationReference file to der2_cRefset_Association |
|
Java | apache-2.0 | aa18d0739d7e281dff7cfc769b3535b262a5be7a | 0 | phax/ph-oton,phax/ph-oton,phax/ph-oton | /**
* Copyright (C) 2014-2016 Philip Helger (www.helger.com)
* philip[at]helger[dot]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.helger.photon.core.go;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.function.Consumer;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.ELockType;
import com.helger.commons.annotation.MustBeLocked;
import com.helger.commons.annotation.Nonempty;
import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.collection.CollectionHelper;
import com.helger.commons.microdom.IMicroDocument;
import com.helger.commons.microdom.IMicroElement;
import com.helger.commons.microdom.MicroDocument;
import com.helger.commons.state.EChange;
import com.helger.commons.string.StringHelper;
import com.helger.commons.string.StringParser;
import com.helger.commons.string.ToStringGenerator;
import com.helger.commons.url.SimpleURL;
import com.helger.photon.basic.app.dao.impl.AbstractSimpleDAO;
import com.helger.photon.basic.app.dao.impl.DAOException;
import com.helger.photon.basic.app.menu.IMenuTree;
import com.helger.photon.basic.app.request.ApplicationRequestManager;
import com.helger.photon.basic.app.request.IRequestManager;
import com.helger.photon.core.mgr.PhotonCoreManager;
import com.helger.photon.core.url.LinkHelper;
import com.helger.web.scope.IRequestWebScopeWithoutResponse;
import com.helger.web.scope.mgr.WebScopeManager;
/**
* Manager for {@link GoMappingItem} objects.
*
* @author Philip Helger
*/
@ThreadSafe
public class GoMappingManager extends AbstractSimpleDAO
{
public static final boolean DEFAULT_EDITABLE = true;
private static final String ELEMENT_ROOT = "gomappings";
private static final String ELEMENT_EXTERNAL = "external";
private static final String ELEMENT_INTERNAL = "internal";
private static final String ATTR_KEY = "key";
private static final String ATTR_HREF = "href";
private static final String ATTR_EDITABLE = "editable";
private static final Logger s_aLogger = LoggerFactory.getLogger (GoMappingManager.class);
@GuardedBy ("m_aRWLock")
private final Map <String, GoMappingItem> m_aMap = new HashMap <> ();
public GoMappingManager (@Nullable final String sFilename) throws DAOException
{
super (sFilename);
initialRead ();
}
@Nonnull
private static String _unifyKey (@Nonnull final String sKey)
{
return sKey.toLowerCase (Locale.US);
}
@MustBeLocked (ELockType.WRITE)
private EChange _addItem (@Nonnull final GoMappingItem aItem, final boolean bAllowOverwrite)
{
ValueEnforcer.notNull (aItem, "Item");
final String sKey = _unifyKey (aItem.getKey ());
final GoMappingItem aOldItem = m_aMap.get (sKey);
if (aOldItem != null)
{
if (bAllowOverwrite)
{
// Same item as before
if (aOldItem.equals (aItem))
return EChange.UNCHANGED;
}
else
throw new IllegalArgumentException ("Another go-mapping with the key '" + sKey + "' is already registered!");
}
m_aMap.put (sKey, aItem);
return EChange.CHANGED;
}
public static void readFromXML (@Nonnull final IMicroDocument aDoc, @Nonnull final Consumer <GoMappingItem> aCallback)
{
ValueEnforcer.notNull (aDoc, "Doc");
ValueEnforcer.notNull (aCallback, "Callback");
for (final IMicroElement eItem : aDoc.getDocumentElement ().getAllChildElements ())
{
final String sTagName = eItem.getTagName ();
final String sKey = eItem.getAttributeValue (ATTR_KEY);
final String sHref = eItem.getAttributeValue (ATTR_HREF);
final String sIsEditable = eItem.getAttributeValue (ATTR_EDITABLE);
final boolean bIsEditable = StringParser.parseBool (sIsEditable, DEFAULT_EDITABLE);
if (ELEMENT_EXTERNAL.equals (sTagName))
aCallback.accept (new GoMappingItem (sKey, false, sHref, bIsEditable));
else
if (ELEMENT_INTERNAL.equals (sTagName))
aCallback.accept (new GoMappingItem (sKey, true, sHref, bIsEditable));
else
s_aLogger.error ("Unsupported go-mapping tag '" + sTagName + "'");
}
}
@Override
protected EChange onRead (@Nonnull final IMicroDocument aDoc)
{
readFromXML (aDoc, aCurrentObject -> _addItem (aCurrentObject, false));
return EChange.UNCHANGED;
}
@Override
protected IMicroDocument createWriteData ()
{
final String sContextPath = WebScopeManager.getGlobalScope ().getContextPath ();
final IMicroDocument ret = new MicroDocument ();
final IMicroElement eRoot = ret.appendElement (ELEMENT_ROOT);
for (final GoMappingItem aItem : CollectionHelper.getSortedByKey (m_aMap).values ())
{
if (aItem.isInternal ())
{
final IMicroElement eItem = eRoot.appendElement (ELEMENT_INTERNAL);
eItem.setAttribute (ATTR_KEY, aItem.getKey ());
// Remove the context path, when deserializing stuff
eItem.setAttribute (ATTR_HREF, StringHelper.trimStart (aItem.getTargetURLAsString (), sContextPath));
}
else
{
final IMicroElement eItem = eRoot.appendElement (ELEMENT_EXTERNAL);
eItem.setAttribute (ATTR_KEY, aItem.getKey ());
eItem.setAttribute (ATTR_HREF, aItem.getTargetURLAsString ());
}
}
return ret;
}
public void reload ()
{
m_aRWLock.writeLocked ( () -> {
m_aMap.clear ();
try
{
initialRead ();
}
catch (final DAOException ex)
{
throw new IllegalStateException ("Failed to reload go-mappings", ex);
}
});
s_aLogger.info ("Reloaded " + m_aMap.size () + " go-mappings!");
}
@Nonnull
public EChange addItem (@Nonnull @Nonempty final String sKey,
final boolean bIsInternal,
@Nonnull @Nonempty final String sTargetURL,
final boolean bIsEditable)
{
return addItem (new GoMappingItem (sKey, bIsInternal, sTargetURL, bIsEditable));
}
@Nonnull
public EChange addItem (@Nonnull final GoMappingItem aItem)
{
ValueEnforcer.notNull (aItem, "Item");
final String sRealKey = _unifyKey (aItem.getKey ());
return m_aRWLock.writeLocked ( () -> {
if (m_aMap.containsKey (sRealKey))
return EChange.UNCHANGED;
_addItem (aItem, false);
markAsChanged ();
return EChange.CHANGED;
});
}
@Nonnull
public EChange setItem (@Nonnull @Nonempty final String sKey,
final boolean bIsInternal,
@Nonnull @Nonempty final String sTargetURL,
final boolean bIsEditable)
{
return setItem (new GoMappingItem (sKey, bIsInternal, sTargetURL, bIsEditable));
}
@Nonnull
public EChange setItem (@Nonnull final GoMappingItem aItem)
{
ValueEnforcer.notNull (aItem, "Item");
return m_aRWLock.writeLocked ( () -> {
// Allow overwrite
if (_addItem (aItem, true).isUnchanged ())
return EChange.UNCHANGED;
markAsChanged ();
return EChange.CHANGED;
});
}
@Nonnull
public EChange removeItem (@Nullable final String sKey)
{
if (StringHelper.hasNoText (sKey))
return EChange.UNCHANGED;
final String sRealKey = _unifyKey (sKey);
return m_aRWLock.writeLocked ( () -> {
if (m_aMap.remove (sRealKey) == null)
return EChange.UNCHANGED;
markAsChanged ();
return EChange.CHANGED;
});
}
@Nonnull
public EChange removeAllItems ()
{
return m_aRWLock.writeLocked ( () -> {
if (m_aMap.isEmpty ())
return EChange.UNCHANGED;
m_aMap.clear ();
markAsChanged ();
return EChange.CHANGED;
});
}
public boolean containsItemWithKey (@Nullable final String sKey)
{
if (StringHelper.hasNoText (sKey))
return false;
final String sRealKey = _unifyKey (sKey);
return m_aRWLock.readLocked ( () -> m_aMap.containsKey (sRealKey));
}
@Nullable
public GoMappingItem getItemOfKey (@Nullable final String sKey)
{
if (StringHelper.hasNoText (sKey))
return null;
final String sRealKey = _unifyKey (sKey);
return m_aRWLock.readLocked ( () -> m_aMap.get (sRealKey));
}
@Nonnegative
public int getItemCount ()
{
return m_aRWLock.readLocked ( () -> m_aMap.size ());
}
@Nonnull
@ReturnsMutableCopy
public Map <String, GoMappingItem> getAllItems ()
{
return m_aRWLock.readLocked ( () -> CollectionHelper.newMap (m_aMap));
}
/**
* Check whether all internal go links, that point to a page use existing menu
* item IDs
*
* @param aMenuTree
* The menu tree to search. May not be <code>null</code>.
* @param aErrorCallback
* The callback that is invoked for all invalid {@link GoMappingItem}
* objects.
* @return The number of errors occurred. Always ≥ 0.
*/
@Nonnegative
public int checkInternalMappings (@Nonnull final IMenuTree aMenuTree,
@Nonnull final Consumer <GoMappingItem> aErrorCallback)
{
ValueEnforcer.notNull (aMenuTree, "MenuTree");
ValueEnforcer.notNull (aErrorCallback, "ErrorCallback");
final IRequestManager aARM = ApplicationRequestManager.getRequestMgr ();
return m_aRWLock.readLocked ( () -> {
int nCount = 0;
int nErrors = 0;
for (final GoMappingItem aItem : m_aMap.values ())
if (aItem.isInternal ())
{
// Get value of "menu item" parameter and check for existence
final String sParamValue = aARM.getMenuItemFromURL (aItem.getTargetURLReadonly ());
if (sParamValue != null)
{
++nCount;
if (aMenuTree.getItemWithID (sParamValue) == null)
{
++nErrors;
aErrorCallback.accept (aItem);
}
}
}
if (nErrors == 0)
s_aLogger.info ("Successfully checked " + nCount + " internal go-mappings for consistency");
else
s_aLogger.warn ("Checked " +
nCount +
" internal go-mappings for consistency and found " +
nErrors +
" errors!");
return nErrors;
});
}
@Override
public String toString ()
{
return new ToStringGenerator (this).append ("map", m_aMap).toString ();
}
/**
* This method is ONLY to be used within the MenuManager, since the renderer
* takes care, that the link to the menu item is handled correctly even if no
* session information are present.
*
* @param sKey
* Go mapping key. May neither be <code>null</code> nor empty.
* @return <code>/webapp-context/go/<i>key</i></code>. Never <code>null</code>
*/
@Nonnull
public static SimpleURL getGoLinkForMenuItem (@Nonnull @Nonempty final String sKey)
{
ValueEnforcer.notEmpty (sKey, "Key");
if (PhotonCoreManager.getGoMappingMgr ().getItemOfKey (sKey) == null)
s_aLogger.warn ("Building URL from invalid go-mapping item '" + sKey + "'");
return LinkHelper.getURLWithContext (GoServlet.SERVLET_DEFAULT_NAME + "/" + sKey);
}
/**
* @param aRequestScope
* Current request scope. May not be <code>null</code>.
* @param sKey
* Go mapping key. May neither be <code>null</code> nor empty.
* @return <code>/webapp-context/go/<i>key</i></code>. Never <code>null</code>
*/
@Nonnull
public static SimpleURL getGoLink (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope,
@Nonnull @Nonempty final String sKey)
{
ValueEnforcer.notEmpty (sKey, "Key");
if (PhotonCoreManager.getGoMappingMgr ().getItemOfKey (sKey) == null)
s_aLogger.warn ("Building URL from invalid go-mapping item '" + sKey + "'");
return LinkHelper.getURLWithContext (aRequestScope, GoServlet.SERVLET_DEFAULT_NAME + "/" + sKey);
}
}
| ph-oton-core/src/main/java/com/helger/photon/core/go/GoMappingManager.java | /**
* Copyright (C) 2014-2016 Philip Helger (www.helger.com)
* philip[at]helger[dot]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.helger.photon.core.go;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.function.Consumer;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.GuardedBy;
import javax.annotation.concurrent.ThreadSafe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.ELockType;
import com.helger.commons.annotation.MustBeLocked;
import com.helger.commons.annotation.Nonempty;
import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.collection.CollectionHelper;
import com.helger.commons.microdom.IMicroDocument;
import com.helger.commons.microdom.IMicroElement;
import com.helger.commons.microdom.MicroDocument;
import com.helger.commons.state.EChange;
import com.helger.commons.string.StringHelper;
import com.helger.commons.string.StringParser;
import com.helger.commons.string.ToStringGenerator;
import com.helger.commons.url.SimpleURL;
import com.helger.photon.basic.app.dao.impl.AbstractSimpleDAO;
import com.helger.photon.basic.app.dao.impl.DAOException;
import com.helger.photon.basic.app.menu.IMenuTree;
import com.helger.photon.basic.app.request.ApplicationRequestManager;
import com.helger.photon.basic.app.request.IRequestManager;
import com.helger.photon.core.mgr.PhotonCoreManager;
import com.helger.photon.core.url.LinkHelper;
import com.helger.web.scope.IRequestWebScopeWithoutResponse;
import com.helger.web.scope.mgr.WebScopeManager;
/**
* Manager for {@link GoMappingItem} objects.
*
* @author Philip Helger
*/
@ThreadSafe
public class GoMappingManager extends AbstractSimpleDAO
{
public static final boolean DEFAULT_EDITABLE = true;
private static final String ELEMENT_ROOT = "gomappings";
private static final String ELEMENT_EXTERNAL = "external";
private static final String ELEMENT_INTERNAL = "internal";
private static final String ATTR_KEY = "key";
private static final String ATTR_HREF = "href";
private static final String ATTR_EDITABLE = "editable";
private static final Logger s_aLogger = LoggerFactory.getLogger (GoMappingManager.class);
@GuardedBy ("m_aRWLock")
private final Map <String, GoMappingItem> m_aMap = new HashMap <> ();
public GoMappingManager (@Nullable final String sFilename) throws DAOException
{
super (sFilename);
initialRead ();
}
@Nonnull
private static String _unifyKey (@Nonnull final String sKey)
{
return sKey.toLowerCase (Locale.US);
}
@MustBeLocked (ELockType.WRITE)
private EChange _addItem (@Nonnull final GoMappingItem aItem, final boolean bAllowOverwrite)
{
ValueEnforcer.notNull (aItem, "Item");
final String sKey = _unifyKey (aItem.getKey ());
final GoMappingItem aOldItem = m_aMap.get (sKey);
if (aOldItem != null)
{
if (bAllowOverwrite)
{
// Same item as before
if (aOldItem.equals (aItem))
return EChange.UNCHANGED;
}
else
throw new IllegalArgumentException ("Another go-mapping with the key '" + sKey + "' is already registered!");
}
m_aMap.put (sKey, aItem);
return EChange.CHANGED;
}
public static void readFromXML (@Nonnull final IMicroDocument aDoc, @Nonnull final Consumer <GoMappingItem> aCallback)
{
ValueEnforcer.notNull (aDoc, "Doc");
ValueEnforcer.notNull (aCallback, "Callback");
for (final IMicroElement eItem : aDoc.getDocumentElement ().getAllChildElements ())
{
final String sTagName = eItem.getTagName ();
final String sKey = eItem.getAttributeValue (ATTR_KEY);
final String sHref = eItem.getAttributeValue (ATTR_HREF);
final String sIsEditable = eItem.getAttributeValue (ATTR_EDITABLE);
final boolean bIsEditable = StringParser.parseBool (sIsEditable, DEFAULT_EDITABLE);
if (ELEMENT_EXTERNAL.equals (sTagName))
aCallback.accept (new GoMappingItem (sKey, false, sHref, bIsEditable));
else
if (ELEMENT_INTERNAL.equals (sTagName))
aCallback.accept (new GoMappingItem (sKey, true, sHref, bIsEditable));
else
s_aLogger.error ("Unsupported go-mapping tag '" + sTagName + "'");
}
}
@Override
protected EChange onRead (@Nonnull final IMicroDocument aDoc)
{
readFromXML (aDoc, aCurrentObject -> _addItem (aCurrentObject, false));
return EChange.UNCHANGED;
}
@Override
protected IMicroDocument createWriteData ()
{
final String sContextPath = WebScopeManager.getGlobalScope ().getContextPath ();
final IMicroDocument ret = new MicroDocument ();
final IMicroElement eRoot = ret.appendElement (ELEMENT_ROOT);
for (final GoMappingItem aItem : CollectionHelper.getSortedByKey (m_aMap).values ())
{
if (aItem.isInternal ())
{
final IMicroElement eItem = eRoot.appendElement (ELEMENT_INTERNAL);
eItem.setAttribute (ATTR_KEY, aItem.getKey ());
// Remove the context path, when deserializing stuff
eItem.setAttribute (ATTR_HREF, StringHelper.trimStart (aItem.getTargetURLAsString (), sContextPath));
}
else
{
final IMicroElement eItem = eRoot.appendElement (ELEMENT_EXTERNAL);
eItem.setAttribute (ATTR_KEY, aItem.getKey ());
eItem.setAttribute (ATTR_HREF, aItem.getTargetURLAsString ());
}
}
return ret;
}
public void reload ()
{
try
{
m_aRWLock.writeLockedThrowing ( () -> {
m_aMap.clear ();
initialRead ();
});
s_aLogger.info ("Reloaded " + m_aMap.size () + " go-mappings!");
}
catch (final DAOException ex)
{
throw new IllegalStateException ("Failed to reload go-mappings", ex);
}
}
@Nonnull
public EChange addItem (@Nonnull @Nonempty final String sKey,
final boolean bIsInternal,
@Nonnull @Nonempty final String sTargetURL,
final boolean bIsEditable)
{
return addItem (new GoMappingItem (sKey, bIsInternal, sTargetURL, bIsEditable));
}
@Nonnull
public EChange addItem (@Nonnull final GoMappingItem aItem)
{
ValueEnforcer.notNull (aItem, "Item");
final String sRealKey = _unifyKey (aItem.getKey ());
return m_aRWLock.writeLocked ( () -> {
if (m_aMap.containsKey (sRealKey))
return EChange.UNCHANGED;
_addItem (aItem, false);
markAsChanged ();
return EChange.CHANGED;
});
}
@Nonnull
public EChange setItem (@Nonnull @Nonempty final String sKey,
final boolean bIsInternal,
@Nonnull @Nonempty final String sTargetURL,
final boolean bIsEditable)
{
return setItem (new GoMappingItem (sKey, bIsInternal, sTargetURL, bIsEditable));
}
@Nonnull
public EChange setItem (@Nonnull final GoMappingItem aItem)
{
ValueEnforcer.notNull (aItem, "Item");
return m_aRWLock.writeLocked ( () -> {
// Allow overwrite
if (_addItem (aItem, true).isUnchanged ())
return EChange.UNCHANGED;
markAsChanged ();
return EChange.CHANGED;
});
}
@Nonnull
public EChange removeItem (@Nullable final String sKey)
{
if (StringHelper.hasNoText (sKey))
return EChange.UNCHANGED;
final String sRealKey = _unifyKey (sKey);
return m_aRWLock.writeLocked ( () -> {
if (m_aMap.remove (sRealKey) == null)
return EChange.UNCHANGED;
markAsChanged ();
return EChange.CHANGED;
});
}
@Nonnull
public EChange removeAllItems ()
{
return m_aRWLock.writeLocked ( () -> {
if (m_aMap.isEmpty ())
return EChange.UNCHANGED;
m_aMap.clear ();
markAsChanged ();
return EChange.CHANGED;
});
}
public boolean containsItemWithKey (@Nullable final String sKey)
{
if (StringHelper.hasNoText (sKey))
return false;
final String sRealKey = _unifyKey (sKey);
return m_aRWLock.readLocked ( () -> m_aMap.containsKey (sRealKey));
}
@Nullable
public GoMappingItem getItemOfKey (@Nullable final String sKey)
{
if (StringHelper.hasNoText (sKey))
return null;
final String sRealKey = _unifyKey (sKey);
return m_aRWLock.readLocked ( () -> m_aMap.get (sRealKey));
}
@Nonnegative
public int getItemCount ()
{
return m_aRWLock.readLocked ( () -> m_aMap.size ());
}
@Nonnull
@ReturnsMutableCopy
public Map <String, GoMappingItem> getAllItems ()
{
return m_aRWLock.readLocked ( () -> CollectionHelper.newMap (m_aMap));
}
/**
* Check whether all internal go links, that point to a page use existing menu
* item IDs
*
* @param aMenuTree
* The menu tree to search. May not be <code>null</code>.
* @throws IllegalStateException
* If at least one menu item is not present
*/
public void checkInternalMappings (@Nonnull final IMenuTree aMenuTree)
{
ValueEnforcer.notNull (aMenuTree, "MenuTree");
final IRequestManager aARM = ApplicationRequestManager.getRequestMgr ();
m_aRWLock.readLocked ( () -> {
int nCount = 0;
for (final GoMappingItem aItem : m_aMap.values ())
if (aItem.isInternal ())
{
// Get value of "menu item" parameter and check for existence
final String sParamValue = aARM.getMenuItemFromURL (aItem.getTargetURLReadonly ());
if (sParamValue != null)
{
++nCount;
if (aMenuTree.getItemWithID (sParamValue) == null)
throw new IllegalStateException ("Go-mapping item " + aItem + " is invalid");
}
}
s_aLogger.info ("Successfully checked " + nCount + " internal go-mappings for consistency");
});
}
@Override
public String toString ()
{
return new ToStringGenerator (this).append ("map", m_aMap).toString ();
}
/**
* This method is ONLY to be used within the MenuManager, since the renderer
* takes care, that the link to the menu item is handled correctly even if no
* session information are present.
*
* @param sKey
* Go mapping key. May neither be <code>null</code> nor empty.
* @return <code>/webapp-context/go/<i>key</i></code>. Never <code>null</code>
*/
@Nonnull
public static SimpleURL getGoLinkForMenuItem (@Nonnull @Nonempty final String sKey)
{
ValueEnforcer.notEmpty (sKey, "Key");
if (PhotonCoreManager.getGoMappingMgr ().getItemOfKey (sKey) == null)
s_aLogger.warn ("Building URL from invalid go-mapping item '" + sKey + "'");
return LinkHelper.getURLWithContext (GoServlet.SERVLET_DEFAULT_NAME + "/" + sKey);
}
/**
* @param aRequestScope
* Current request scope. May not be <code>null</code>.
* @param sKey
* Go mapping key. May neither be <code>null</code> nor empty.
* @return <code>/webapp-context/go/<i>key</i></code>. Never <code>null</code>
*/
@Nonnull
public static SimpleURL getGoLink (@Nonnull final IRequestWebScopeWithoutResponse aRequestScope,
@Nonnull @Nonempty final String sKey)
{
ValueEnforcer.notEmpty (sKey, "Key");
if (PhotonCoreManager.getGoMappingMgr ().getItemOfKey (sKey) == null)
s_aLogger.warn ("Building URL from invalid go-mapping item '" + sKey + "'");
return LinkHelper.getURLWithContext (aRequestScope, GoServlet.SERVLET_DEFAULT_NAME + "/" + sKey);
}
}
| Changed API | ph-oton-core/src/main/java/com/helger/photon/core/go/GoMappingManager.java | Changed API |
|
Java | apache-2.0 | f298ce36ee2a56b6cabee6831b59ef7848b5e00d | 0 | ceylon/ceylon-js,ceylon/ceylon-js,ceylon/ceylon-js | package com.redhat.ceylon.compiler.js;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.redhat.ceylon.compiler.loader.MetamodelGenerator;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
/** A convenience class to help with the handling of certain type declarations. */
public class TypeUtils {
final TypeDeclaration tuple;
final TypeDeclaration iterable;
final TypeDeclaration sequential;
final TypeDeclaration numeric;
final TypeDeclaration _integer;
final TypeDeclaration _float;
final TypeDeclaration _null;
final TypeDeclaration anything;
final TypeDeclaration callable;
final TypeDeclaration empty;
final TypeDeclaration metaClass;
TypeUtils(Module languageModule) {
com.redhat.ceylon.compiler.typechecker.model.Package pkg = languageModule.getPackage("ceylon.language");
tuple = (TypeDeclaration)pkg.getMember("Tuple", null, false);
iterable = (TypeDeclaration)pkg.getMember("Iterable", null, false);
sequential = (TypeDeclaration)pkg.getMember("Sequential", null, false);
numeric = (TypeDeclaration)pkg.getMember("Numeric", null, false);
_integer = (TypeDeclaration)pkg.getMember("Integer", null, false);
_float = (TypeDeclaration)pkg.getMember("Float", null, false);
_null = (TypeDeclaration)pkg.getMember("Null", null, false);
anything = (TypeDeclaration)pkg.getMember("Anything", null, false);
callable = (TypeDeclaration)pkg.getMember("Callable", null, false);
empty = (TypeDeclaration)pkg.getMember("Empty", null, false);
pkg = languageModule.getPackage("ceylon.language.metamodel");
metaClass = (TypeDeclaration)pkg.getMember("Class", null, false);
}
/** Prints the type arguments, usually for their reification. */
public static void printTypeArguments(Node node, Map<TypeParameter,ProducedType> targs, GenerateJsVisitor gen) {
gen.out("{");
boolean first = true;
for (Map.Entry<TypeParameter,ProducedType> e : targs.entrySet()) {
if (first) {
first = false;
} else {
gen.out(",");
}
gen.out(e.getKey().getName(), ":");
ProducedType pt = e.getValue();
TypeDeclaration d = pt.getDeclaration();
boolean composite = d instanceof UnionType || d instanceof IntersectionType;
boolean hasParams = pt.getTypeArgumentList() != null && !pt.getTypeArgumentList().isEmpty();
boolean closeBracket = false;
if (composite) {
outputTypeList(node, d, gen, true);
} else if (d instanceof TypeParameter) {
resolveTypeParameter(node, (TypeParameter)d, gen);
} else {
gen.out("{t:");
outputQualifiedTypename(
gen.isImported(node == null ? null : node.getUnit().getPackage(), pt.getDeclaration()),
pt, gen);
closeBracket = true;
}
if (hasParams) {
gen.out(",a:");
printTypeArguments(node, pt.getTypeArguments(), gen);
}
if (closeBracket) {
gen.out("}");
}
}
gen.out("}");
}
static void outputQualifiedTypename(final boolean imported, ProducedType pt, GenerateJsVisitor gen) {
TypeDeclaration t = pt.getDeclaration();
final String qname = t.getQualifiedNameString();
if (qname.equals("ceylon.language::Nothing")) {
//Hack in the model means hack here as well
gen.out(GenerateJsVisitor.getClAlias(), "Nothing");
} else if (qname.equals("ceylon.language::null") || qname.equals("ceylon.language::Null")) {
gen.out(GenerateJsVisitor.getClAlias(), "Null");
} else if (pt.isUnknown()) {
gen.out(GenerateJsVisitor.getClAlias(), "Anything");
} else {
if (t.isAlias()) {
t = t.getExtendedTypeDeclaration();
}
boolean qual = false;
if (t.getScope() instanceof ClassOrInterface) {
List<ClassOrInterface> parents = new ArrayList<>();
ClassOrInterface parent = (ClassOrInterface)t.getScope();
parents.add(0, parent);
while (parent.getScope() instanceof ClassOrInterface) {
parent = (ClassOrInterface)parent.getScope();
parents.add(0, parent);
}
qual = true;
for (ClassOrInterface p : parents) {
gen.out(gen.getNames().name(p), ".");
}
} else if (imported) {
//This wasn't needed but now we seem to get imported decls with no package when compiling ceylon.language.metamodel types
final String modAlias = gen.getNames().moduleAlias(t.getUnit().getPackage().getModule());
if (modAlias != null && !modAlias.isEmpty()) {
gen.out(modAlias, ".");
}
qual = true;
}
String tname = gen.getNames().name(t);
if (!qual && isReservedTypename(tname)) {
gen.out(tname, "$");
} else {
gen.out(tname);
}
}
}
/** Prints out an object with a type constructor under the property "t" and its type arguments under
* the property "a", or a union/intersection type with "u" or "i" under property "t" and the list
* of types that compose it in an array under the property "l", or a type parameter as a reference to
* already existing params. */
static void typeNameOrList(Node node, ProducedType pt, GenerateJsVisitor gen, boolean typeReferences) {
TypeDeclaration type = pt.getDeclaration();
if (type.isAlias()) {
type = type.getExtendedTypeDeclaration();
}
boolean unionIntersection = type instanceof UnionType
|| type instanceof IntersectionType;
if (unionIntersection) {
outputTypeList(node, type, gen, typeReferences);
} else if (typeReferences) {
if (type instanceof TypeParameter) {
resolveTypeParameter(node, (TypeParameter)type, gen);
} else {
gen.out("{t:");
outputQualifiedTypename(gen.isImported(node == null ? null : node.getUnit().getPackage(), type), pt, gen);
if (!pt.getTypeArgumentList().isEmpty()) {
gen.out(",a:");
printTypeArguments(node, pt.getTypeArguments(), gen);
}
gen.out("}");
}
} else {
gen.out("'", type.getQualifiedNameString(), "'");
}
}
/** Appends an object with the type's type and list of union/intersection types. */
static void outputTypeList(Node node, TypeDeclaration type, GenerateJsVisitor gen, boolean typeReferences) {
gen.out("{ t:'");
final List<ProducedType> subs;
if (type instanceof IntersectionType) {
gen.out("i");
subs = type.getSatisfiedTypes();
} else {
gen.out("u");
subs = type.getCaseTypes();
}
gen.out("', l:[");
boolean first = true;
for (ProducedType t : subs) {
if (!first) gen.out(",");
typeNameOrList(node, t, gen, typeReferences);
first = false;
}
gen.out("]}");
}
/** Finds the owner of the type parameter and outputs a reference to the corresponding type argument. */
static void resolveTypeParameter(Node node, TypeParameter tp, GenerateJsVisitor gen) {
Scope parent = node.getScope();
while (parent != null && parent != tp.getContainer()) {
parent = parent.getScope();
}
if (tp.getContainer() instanceof ClassOrInterface) {
if (parent == tp.getContainer()) {
if (((ClassOrInterface)tp.getContainer()).isAlias()) {
//when resolving for aliases we just take the type arguments from the alias call
gen.out("$$targs$$.", tp.getName());
} else {
gen.self((ClassOrInterface)tp.getContainer());
gen.out(".$$targs$$.", tp.getName());
}
} else {
//This can happen in expressions such as Singleton(n) when n is dynamic
gen.out("{/*NO PARENT*/t:", GenerateJsVisitor.getClAlias(), "Anything}");
}
} else {
//it has to be a method, right?
//We need to find the index of the parameter where the argument occurs
//...and it could be null...
int plistCount = -1;
ProducedType type = null;
for (Iterator<ParameterList> iter0 = ((Method)tp.getContainer()).getParameterLists().iterator();
type == null && iter0.hasNext();) {
plistCount++;
for (Iterator<Parameter> iter1 = iter0.next().getParameters().iterator();
type == null && iter1.hasNext();) {
if (type == null) {
type = typeContainsTypeParameter(iter1.next().getType(), tp);
}
}
}
//The ProducedType that we find corresponds to a parameter, whose type can be:
//A type parameter in the method, in which case we just use the argument's type (may be null)
//A component of a union/intersection type, in which case we just use the argument's type (may be null)
//A type argument of the argument's type, in which case we must get the reified generic from the argument
if (tp.getContainer() == parent) {
gen.out("$$$mptypes.", tp.getName());
} else {
gen.out("/*METHOD TYPEPARM plist ", Integer.toString(plistCount), "#",
tp.getName(), "*/'", type.getProducedTypeQualifiedName(), "'");
}
}
}
static ProducedType typeContainsTypeParameter(ProducedType td, TypeParameter tp) {
TypeDeclaration d = td.getDeclaration();
if (d == tp) {
return td;
} else if (d instanceof UnionType || d instanceof IntersectionType) {
List<ProducedType> comps = td.getCaseTypes();
if (comps == null) comps = td.getSupertypes();
for (ProducedType sub : comps) {
td = typeContainsTypeParameter(sub, tp);
if (td != null) {
return td;
}
}
} else if (d instanceof ClassOrInterface) {
for (ProducedType sub : td.getTypeArgumentList()) {
if (typeContainsTypeParameter(sub, tp) != null) {
return td;
}
}
}
return null;
}
static boolean isReservedTypename(String typeName) {
return JsCompiler.compilingLanguageModule && (typeName.equals("Object") || typeName.equals("Number")
|| typeName.equals("Array")) || typeName.equals("String") || typeName.equals("Boolean");
}
/** Find the type with the specified declaration among the specified type's supertypes, case types, satisfied types, etc. */
static ProducedType findSupertype(TypeDeclaration d, ProducedType pt) {
if (pt.getDeclaration().equals(d)) {
return pt;
}
List<ProducedType> list = pt.getSupertypes() == null ? pt.getCaseTypes() : pt.getSupertypes();
for (ProducedType t : list) {
if (t.getDeclaration().equals(d)) {
return t;
}
}
return null;
}
static Map<TypeParameter, ProducedType> matchTypeParametersWithArguments(List<TypeParameter> params, List<ProducedType> targs) {
if (params != null && targs != null && params.size() == targs.size()) {
HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>();
for (int i = 0; i < targs.size(); i++) {
r.put(params.get(i), targs.get(i));
}
return r;
}
return null;
}
Map<TypeParameter, ProducedType> wrapAsIterableArguments(ProducedType pt) {
HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>();
r.put(iterable.getTypeParameters().get(0), pt);
r.put(iterable.getTypeParameters().get(1), _null.getType());
return r;
}
static boolean isUnknown(ProducedType pt) {
return pt == null || pt.isUnknown();
}
static boolean isUnknown(Parameter param) {
return param == null || param.getTypeDeclaration() == null || param.getTypeDeclaration().getQualifiedNameString().equals("UnknownType");
}
static boolean isUnknown(Declaration d) {
return d == null || d.getQualifiedNameString().equals("UnknownType");
}
/** Generates the code to throw an Exception if a dynamic object is not of the specified type. */
static void generateDynamicCheck(Tree.Term term, final ProducedType t, final GenerateJsVisitor gen) {
String tmp = gen.getNames().createTempVariable();
gen.out("(", tmp, "=");
term.visit(gen);
gen.out(",", GenerateJsVisitor.getClAlias(), "isOfType(", tmp, ",");
TypeUtils.typeNameOrList(term, t, gen, true);
gen.out(")?", tmp, ":", GenerateJsVisitor.getClAlias(), "throwexc('dynamic objects cannot be used here'))");
}
static void encodeParameterListForRuntime(ParameterList plist, GenerateJsVisitor gen) {
boolean first = true;
gen.out("[");
for (Parameter p : plist.getParameters()) {
if (first) first=false; else gen.out(",");
gen.out("{", MetamodelGenerator.KEY_NAME, ":'", p.getNameAsString(), "',");
gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',");
if (p.isSequenced()) {
gen.out("seq:1,");
}
if (p.isDefaulted()) {
gen.out(MetamodelGenerator.KEY_DEFAULT, ":1,");
}
gen.out(MetamodelGenerator.KEY_TYPE, ":");
metamodelTypeNameOrList(gen.getCurrentPackage(), p.getType(), gen);
gen.out("}");
}
gen.out("]");
}
/** This method encodes the type parameters of a Tuple (taken from a Callable) in the same way
* as a parameter list for runtime. */
void encodeTupleAsParameterListForRuntime(ProducedType _callable, GenerateJsVisitor gen) {
if (!_callable.getProducedTypeQualifiedName().startsWith("ceylon.language::Callable<")) {
gen.out("[/*WARNING: got ", _callable.getProducedTypeQualifiedName(), " instead of Callable*/]");
return;
}
List<ProducedType> targs = _callable.getTypeArgumentList();
if (targs == null || targs.size() != 2) {
gen.out("[/*WARNING: missing argument types for Callable*/]");
return;
}
ProducedType _tuple = targs.get(1);
gen.out("[");
int pos = 1;
while (!(empty.equals(_tuple.getDeclaration()) || _tuple.getDeclaration() instanceof TypeParameter)) {
if (pos > 1) gen.out(",");
gen.out("{", MetamodelGenerator.KEY_NAME, ":'p", Integer.toString(pos++), "',");
gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',");
gen.out(MetamodelGenerator.KEY_TYPE, ":");
if (tuple.equals(_tuple.getDeclaration())) {
metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(1), gen);
_tuple = _tuple.getTypeArgumentList().get(2);
} else if (sequential.equals(_tuple.getDeclaration())) {
metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(0), gen);
_tuple = _tuple.getTypeArgumentList().get(0);
} else {
System.out.println("WTF? Tuple is actually " + _tuple.getProducedTypeQualifiedName() + ", " + _tuple.getClass().getName());
if (pos > 100) {
System.exit(1);
}
}
gen.out("}");
}
gen.out("]");
}
/** Output a metamodel map for runtime use. */
static void encodeForRuntime(final Declaration d, final Tree.AnnotationList annotations, final GenerateJsVisitor gen) {
gen.out("{mod:$$METAMODEL$$");
List<TypeParameter> tparms = null;
List<ProducedType> satisfies = null;
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getTypeParameters();
if (((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType() != null) {
gen.out(",'super':");
metamodelTypeNameOrList(d.getUnit().getPackage(),
((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType(), gen);
}
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getSatisfiedTypes();
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getTypeParameters();
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes();
} else if (d instanceof MethodOrValue) {
gen.out(",", MetamodelGenerator.KEY_TYPE, ":");
//This needs a new setting to resolve types but not type parameters
metamodelTypeNameOrList(d.getUnit().getPackage(), ((MethodOrValue)d).getType(), gen);
if (d instanceof Method) {
gen.out(",", MetamodelGenerator.KEY_PARAMS, ":");
//Parameter types of the first parameter list
encodeParameterListForRuntime(((Method)d).getParameterLists().get(0), gen);
tparms = ((Method) d).getTypeParameters();
}
}
if (d.isMember()) {
gen.out(",$cont:", gen.getNames().name((Declaration)d.getContainer()));
}
if (tparms != null && !tparms.isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{");
boolean first = true;
for(TypeParameter tp : tparms) {
if (!first)gen.out(",");
first=false;
gen.out(tp.getName(), ":{");
if (tp.isCovariant()) {
gen.out("'var':'out',");
} else if (tp.isContravariant()) {
gen.out("'var':'in',");
}
List<ProducedType> typelist = tp.getSatisfiedTypes();
if (typelist != null && !typelist.isEmpty()) {
gen.out("'satisfies':[");
boolean first2 = true;
for (ProducedType st : typelist) {
if (!first2)gen.out(",");
first2=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
typelist = tp.getCaseTypes();
if (typelist != null && !typelist.isEmpty()) {
gen.out("'of':[");
boolean first3 = true;
for (ProducedType st : typelist) {
if (!first3)gen.out(",");
first3=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (tp.getDefaultTypeArgument() != null) {
gen.out(",'def':");
metamodelTypeNameOrList(d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen);
}
gen.out("}");
}
gen.out("}");
}
if (satisfies != null) {
gen.out(",satisfies:[");
boolean first = true;
for (ProducedType st : satisfies) {
if (!first)gen.out(",");
first=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (annotations != null && !annotations.getAnnotations().isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":function(){return[");
boolean first = true;
for (Tree.Annotation a : annotations.getAnnotations()) {
//Filter out the obvious ones, FOR NOW
if (first) first=false; else gen.out(",");
gen.getInvoker().generateInvocation(a);
}
gen.out("];}");
}
gen.out(",pkg:'", d.getUnit().getPackage().getNameAsString(), "',d:$$METAMODEL$$['");
gen.out(d.getUnit().getPackage().getNameAsString(), "']");
if (d.isToplevel()) {
gen.out("['", d.getName(), "']");
} else {
ArrayList<String> path = new ArrayList<>();
Declaration p = d;
while (p instanceof Declaration) {
path.add(0, p.getName());
//Build the path in reverse
if (!p.isToplevel()) {
if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
path.add(0, p.isAnonymous() ? "$o" : "$c");
} else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
path.add(0, "$i");
} else if (p instanceof Method) {
path.add(0, "$m");
} else {
path.add(0, "$at");
}
}
Scope s = p.getContainer();
while (s != null && s instanceof Declaration == false) {
s = s.getContainer();
}
p = (Declaration)s;
}
//Output path
for (String part : path) {
gen.out("['", part, "']");
}
}
gen.out("}");
}
/** Prints out an object with a type constructor under the property "t" and its type arguments under
* the property "a", or a union/intersection type with "u" or "i" under property "t" and the list
* of types that compose it in an array under the property "l", or a type parameter as a reference to
* already existing params. */
static void metamodelTypeNameOrList(final com.redhat.ceylon.compiler.typechecker.model.Package pkg,
ProducedType pt, GenerateJsVisitor gen) {
if (pt == null) {
//In dynamic blocks we sometimes get a null producedType
pt = ((TypeDeclaration)pkg.getModule().getLanguageModule().getDirectPackage(
"ceylon.language").getDirectMember("Anything", null, false)).getType();
}
TypeDeclaration type = pt.getDeclaration();
if (type.isAlias()) {
type = type.getExtendedTypeDeclaration();
}
boolean unionIntersection = type instanceof UnionType
|| type instanceof IntersectionType;
if (unionIntersection) {
outputMetamodelTypeList(pkg, pt, gen);
} else if (type instanceof TypeParameter) {
gen.out("'", type.getNameAsString(), "'");
} else {
gen.out("{t:");
outputQualifiedTypename(gen.isImported(pkg, type), pt, gen);
//Type Parameters
if (!pt.getTypeArgumentList().isEmpty()) {
gen.out(",a:{");
boolean first = true;
for (Map.Entry<TypeParameter, ProducedType> e : pt.getTypeArguments().entrySet()) {
if (first) first=false; else gen.out(",");
gen.out(e.getKey().getNameAsString(), ":");
metamodelTypeNameOrList(pkg, e.getValue(), gen);
}
gen.out("}");
}
gen.out("}");
}
}
/** Appends an object with the type's type and list of union/intersection types. */
static void outputMetamodelTypeList(final com.redhat.ceylon.compiler.typechecker.model.Package pkg,
ProducedType pt, GenerateJsVisitor gen) {
TypeDeclaration type = pt.getDeclaration();
gen.out("{ t:'");
final List<ProducedType> subs;
if (type instanceof IntersectionType) {
gen.out("i");
subs = type.getSatisfiedTypes();
} else {
gen.out("u");
subs = type.getCaseTypes();
}
gen.out("', l:[");
boolean first = true;
for (ProducedType t : subs) {
if (!first) gen.out(",");
metamodelTypeNameOrList(pkg, t, gen);
first = false;
}
gen.out("]}");
}
ProducedType tupleFromParameters(List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params) {
if (params == null || params.isEmpty()) {
return empty.getType();
}
ProducedType tt = empty.getType();
ProducedType et = null;
for (int i = params.size()-1; i>=0; i--) {
com.redhat.ceylon.compiler.typechecker.model.Parameter p = params.get(i);
if (et == null) {
et = p.getType();
} else {
UnionType ut = new UnionType(p.getUnit());
ArrayList<ProducedType> types = new ArrayList<>();
if (et.getCaseTypes() == null || et.getCaseTypes().isEmpty()) {
types.add(et);
} else {
types.addAll(et.getCaseTypes());
}
types.add(p.getType());
ut.setCaseTypes(types);
et = ut.getType();
}
Map<TypeParameter,ProducedType> args = new HashMap<>();
for (TypeParameter tp : tuple.getTypeParameters()) {
if ("First".equals(tp.getName())) {
args.put(tp, p.getType());
} else if ("Element".equals(tp.getName())) {
args.put(tp, et);
} else if ("Rest".equals(tp.getName())) {
args.put(tp, tt);
}
}
if (i == params.size()-1) {
tt = tuple.getType();
}
tt = tt.substitute(args);
}
return tt;
}
}
| src/main/java/com/redhat/ceylon/compiler/js/TypeUtils.java | package com.redhat.ceylon.compiler.js;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.redhat.ceylon.compiler.loader.MetamodelGenerator;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.IntersectionType;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Parameter;
import com.redhat.ceylon.compiler.typechecker.model.ParameterList;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.UnionType;
import com.redhat.ceylon.compiler.typechecker.tree.Node;
import com.redhat.ceylon.compiler.typechecker.tree.Tree;
/** A convenience class to help with the handling of certain type declarations. */
public class TypeUtils {
final TypeDeclaration tuple;
final TypeDeclaration iterable;
final TypeDeclaration sequential;
final TypeDeclaration numeric;
final TypeDeclaration _integer;
final TypeDeclaration _float;
final TypeDeclaration _null;
final TypeDeclaration anything;
final TypeDeclaration callable;
final TypeDeclaration empty;
final TypeDeclaration metaClass;
TypeUtils(Module languageModule) {
com.redhat.ceylon.compiler.typechecker.model.Package pkg = languageModule.getPackage("ceylon.language");
tuple = (TypeDeclaration)pkg.getMember("Tuple", null, false);
iterable = (TypeDeclaration)pkg.getMember("Iterable", null, false);
sequential = (TypeDeclaration)pkg.getMember("Sequential", null, false);
numeric = (TypeDeclaration)pkg.getMember("Numeric", null, false);
_integer = (TypeDeclaration)pkg.getMember("Integer", null, false);
_float = (TypeDeclaration)pkg.getMember("Float", null, false);
_null = (TypeDeclaration)pkg.getMember("Null", null, false);
anything = (TypeDeclaration)pkg.getMember("Anything", null, false);
callable = (TypeDeclaration)pkg.getMember("Callable", null, false);
empty = (TypeDeclaration)pkg.getMember("Empty", null, false);
pkg = languageModule.getPackage("ceylon.language.metamodel");
metaClass = (TypeDeclaration)pkg.getMember("Class", null, false);
}
/** Prints the type arguments, usually for their reification. */
public static void printTypeArguments(Node node, Map<TypeParameter,ProducedType> targs, GenerateJsVisitor gen) {
gen.out("{");
boolean first = true;
for (Map.Entry<TypeParameter,ProducedType> e : targs.entrySet()) {
if (first) {
first = false;
} else {
gen.out(",");
}
gen.out(e.getKey().getName(), ":");
ProducedType pt = e.getValue();
TypeDeclaration d = pt.getDeclaration();
boolean composite = d instanceof UnionType || d instanceof IntersectionType;
boolean hasParams = pt.getTypeArgumentList() != null && !pt.getTypeArgumentList().isEmpty();
boolean closeBracket = false;
if (composite) {
outputTypeList(node, d, gen, true);
} else if (d instanceof TypeParameter) {
resolveTypeParameter(node, (TypeParameter)d, gen);
} else {
gen.out("{t:");
outputQualifiedTypename(
gen.isImported(node == null ? null : node.getUnit().getPackage(), pt.getDeclaration()),
pt, gen);
closeBracket = true;
}
if (hasParams) {
gen.out(",a:");
printTypeArguments(node, pt.getTypeArguments(), gen);
}
if (closeBracket) {
gen.out("}");
}
}
gen.out("}");
}
static void outputQualifiedTypename(final boolean imported, ProducedType pt, GenerateJsVisitor gen) {
TypeDeclaration t = pt.getDeclaration();
final String qname = t.getQualifiedNameString();
if (qname.equals("ceylon.language::Nothing")) {
//Hack in the model means hack here as well
gen.out(GenerateJsVisitor.getClAlias(), "Nothing");
} else if (qname.equals("ceylon.language::null") || qname.equals("ceylon.language::Null")) {
gen.out(GenerateJsVisitor.getClAlias(), "Null");
} else if (pt.isUnknown()) {
gen.out(GenerateJsVisitor.getClAlias(), "Anything");
} else {
if (t.isAlias()) {
t = t.getExtendedTypeDeclaration();
}
boolean qual = false;
if (t.getScope() instanceof ClassOrInterface) {
List<ClassOrInterface> parents = new ArrayList<>();
ClassOrInterface parent = (ClassOrInterface)t.getScope();
parents.add(0, parent);
while (parent.getScope() instanceof ClassOrInterface) {
parent = (ClassOrInterface)parent.getScope();
parents.add(0, parent);
}
qual = true;
for (ClassOrInterface p : parents) {
gen.out(gen.getNames().name(p), ".");
}
} else if (imported) {
//This wasn't needed but now we seem to get imported decls with no package when compiling ceylon.language.metamodel types
final String modAlias = gen.getNames().moduleAlias(t.getUnit().getPackage().getModule());
if (modAlias != null && !modAlias.isEmpty()) {
gen.out(modAlias, ".");
}
qual = true;
}
String tname = gen.getNames().name(t);
if (!qual && isReservedTypename(tname)) {
gen.out(tname, "$");
} else {
gen.out(tname);
}
}
}
/** Prints out an object with a type constructor under the property "t" and its type arguments under
* the property "a", or a union/intersection type with "u" or "i" under property "t" and the list
* of types that compose it in an array under the property "l", or a type parameter as a reference to
* already existing params. */
static void typeNameOrList(Node node, ProducedType pt, GenerateJsVisitor gen, boolean typeReferences) {
TypeDeclaration type = pt.getDeclaration();
if (type.isAlias()) {
type = type.getExtendedTypeDeclaration();
}
boolean unionIntersection = type instanceof UnionType
|| type instanceof IntersectionType;
if (unionIntersection) {
outputTypeList(node, type, gen, typeReferences);
} else if (typeReferences) {
if (type instanceof TypeParameter) {
resolveTypeParameter(node, (TypeParameter)type, gen);
} else {
gen.out("{t:");
outputQualifiedTypename(gen.isImported(node == null ? null : node.getUnit().getPackage(), type), pt, gen);
if (!pt.getTypeArgumentList().isEmpty()) {
gen.out(",a:");
printTypeArguments(node, pt.getTypeArguments(), gen);
}
gen.out("}");
}
} else {
gen.out("'", type.getQualifiedNameString(), "'");
}
}
/** Appends an object with the type's type and list of union/intersection types. */
static void outputTypeList(Node node, TypeDeclaration type, GenerateJsVisitor gen, boolean typeReferences) {
gen.out("{ t:'");
final List<ProducedType> subs;
if (type instanceof IntersectionType) {
gen.out("i");
subs = type.getSatisfiedTypes();
} else {
gen.out("u");
subs = type.getCaseTypes();
}
gen.out("', l:[");
boolean first = true;
for (ProducedType t : subs) {
if (!first) gen.out(",");
typeNameOrList(node, t, gen, typeReferences);
first = false;
}
gen.out("]}");
}
/** Finds the owner of the type parameter and outputs a reference to the corresponding type argument. */
static void resolveTypeParameter(Node node, TypeParameter tp, GenerateJsVisitor gen) {
Scope parent = node.getScope();
while (parent != null && parent != tp.getContainer()) {
parent = parent.getScope();
}
if (tp.getContainer() instanceof ClassOrInterface) {
if (parent == tp.getContainer()) {
if (((ClassOrInterface)tp.getContainer()).isAlias()) {
//when resolving for aliases we just take the type arguments from the alias call
gen.out("$$targs$$.", tp.getName());
} else {
gen.self((ClassOrInterface)tp.getContainer());
gen.out(".$$targs$$.", tp.getName());
}
} else {
//This can happen in expressions such as Singleton(n) when n is dynamic
gen.out("{/*NO PARENT*/t:", GenerateJsVisitor.getClAlias(), "Anything}");
}
} else {
//it has to be a method, right?
//We need to find the index of the parameter where the argument occurs
//...and it could be null...
int plistCount = -1;
ProducedType type = null;
for (Iterator<ParameterList> iter0 = ((Method)tp.getContainer()).getParameterLists().iterator();
type == null && iter0.hasNext();) {
plistCount++;
for (Iterator<Parameter> iter1 = iter0.next().getParameters().iterator();
type == null && iter1.hasNext();) {
if (type == null) {
type = typeContainsTypeParameter(iter1.next().getType(), tp);
}
}
}
//The ProducedType that we find corresponds to a parameter, whose type can be:
//A type parameter in the method, in which case we just use the argument's type (may be null)
//A component of a union/intersection type, in which case we just use the argument's type (may be null)
//A type argument of the argument's type, in which case we must get the reified generic from the argument
if (tp.getContainer() == parent) {
gen.out("$$$mptypes.", tp.getName());
} else {
gen.out("/*METHOD TYPEPARM plist ", Integer.toString(plistCount), "#",
tp.getName(), "*/'", type.getProducedTypeQualifiedName(), "'");
}
}
}
static ProducedType typeContainsTypeParameter(ProducedType td, TypeParameter tp) {
TypeDeclaration d = td.getDeclaration();
if (d == tp) {
return td;
} else if (d instanceof UnionType || d instanceof IntersectionType) {
List<ProducedType> comps = td.getCaseTypes();
if (comps == null) comps = td.getSupertypes();
for (ProducedType sub : comps) {
td = typeContainsTypeParameter(sub, tp);
if (td != null) {
return td;
}
}
} else if (d instanceof ClassOrInterface) {
for (ProducedType sub : td.getTypeArgumentList()) {
if (typeContainsTypeParameter(sub, tp) != null) {
return td;
}
}
}
return null;
}
static boolean isReservedTypename(String typeName) {
return JsCompiler.compilingLanguageModule && (typeName.equals("Object") || typeName.equals("Number")
|| typeName.equals("Array")) || typeName.equals("String") || typeName.equals("Boolean");
}
/** Find the type with the specified declaration among the specified type's supertypes, case types, satisfied types, etc. */
static ProducedType findSupertype(TypeDeclaration d, ProducedType pt) {
if (pt.getDeclaration().equals(d)) {
return pt;
}
List<ProducedType> list = pt.getSupertypes() == null ? pt.getCaseTypes() : pt.getSupertypes();
for (ProducedType t : list) {
if (t.getDeclaration().equals(d)) {
return t;
}
}
return null;
}
static Map<TypeParameter, ProducedType> matchTypeParametersWithArguments(List<TypeParameter> params, List<ProducedType> targs) {
if (params != null && targs != null && params.size() == targs.size()) {
HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>();
for (int i = 0; i < targs.size(); i++) {
r.put(params.get(i), targs.get(i));
}
return r;
}
return null;
}
Map<TypeParameter, ProducedType> wrapAsIterableArguments(ProducedType pt) {
HashMap<TypeParameter, ProducedType> r = new HashMap<TypeParameter, ProducedType>();
r.put(iterable.getTypeParameters().get(0), pt);
r.put(iterable.getTypeParameters().get(1), _null.getType());
return r;
}
static boolean isUnknown(ProducedType pt) {
return pt == null || pt.isUnknown();
}
static boolean isUnknown(Parameter param) {
return param == null || param.getTypeDeclaration() == null || param.getTypeDeclaration().getQualifiedNameString().equals("UnknownType");
}
static boolean isUnknown(Declaration d) {
return d == null || d.getQualifiedNameString().equals("UnknownType");
}
/** Generates the code to throw an Exception if a dynamic object is not of the specified type. */
static void generateDynamicCheck(Tree.Term term, final ProducedType t, final GenerateJsVisitor gen) {
String tmp = gen.getNames().createTempVariable();
gen.out("(", tmp, "=");
term.visit(gen);
gen.out(",", GenerateJsVisitor.getClAlias(), "isOfType(", tmp, ",");
TypeUtils.typeNameOrList(term, t, gen, true);
gen.out(")?", tmp, ":", GenerateJsVisitor.getClAlias(), "throwexc('dynamic objects cannot be used here'))");
}
static void encodeParameterListForRuntime(ParameterList plist, GenerateJsVisitor gen) {
boolean first = true;
gen.out("[");
for (Parameter p : plist.getParameters()) {
if (first) first=false; else gen.out(",");
gen.out("{", MetamodelGenerator.KEY_NAME, ":'", p.getNameAsString(), "',");
gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',");
if (p.isSequenced()) {
gen.out("seq:1,");
}
if (p.isDefaulted()) {
gen.out(MetamodelGenerator.KEY_DEFAULT, ":1,");
}
gen.out(MetamodelGenerator.KEY_TYPE, ":");
metamodelTypeNameOrList(gen.getCurrentPackage(), p.getType(), gen);
gen.out("}");
}
gen.out("]");
}
/** This method encodes the type parameters of a Tuple (taken from a Callable) in the same way
* as a parameter list for runtime. */
void encodeTupleAsParameterListForRuntime(ProducedType _callable, GenerateJsVisitor gen) {
if (!_callable.getProducedTypeQualifiedName().startsWith("ceylon.language::Callable<")) {
gen.out("[/*WARNING: got ", _callable.getProducedTypeQualifiedName(), " instead of Callable*/]");
return;
}
List<ProducedType> targs = _callable.getTypeArgumentList();
if (targs == null || targs.size() != 2) {
gen.out("[/*WARNING: missing argument types for Callable*/]");
return;
}
ProducedType _tuple = targs.get(1);
gen.out("[");
int pos = 1;
while (!(empty.equals(_tuple.getDeclaration()) || _tuple.getDeclaration() instanceof TypeParameter)) {
if (pos > 1) gen.out(",");
gen.out("{", MetamodelGenerator.KEY_NAME, ":'p", Integer.toString(pos++), "',");
gen.out(MetamodelGenerator.KEY_METATYPE, ":'", MetamodelGenerator.METATYPE_PARAMETER, "',");
gen.out(MetamodelGenerator.KEY_TYPE, ":");
if (tuple.equals(_tuple.getDeclaration())) {
metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(1), gen);
_tuple = _tuple.getTypeArgumentList().get(2);
} else if (sequential.equals(_tuple.getDeclaration())) {
metamodelTypeNameOrList(gen.getCurrentPackage(), _tuple.getTypeArgumentList().get(0), gen);
_tuple = _tuple.getTypeArgumentList().get(0);
} else {
System.out.println("WTF? Tuple is actually " + _tuple.getProducedTypeQualifiedName() + ", " + _tuple.getClass().getName());
if (pos > 100) {
System.exit(1);
}
}
gen.out("}");
}
gen.out("]");
}
/** Output a metamodel map for runtime use. */
static void encodeForRuntime(final Declaration d, final Tree.AnnotationList annotations, final GenerateJsVisitor gen) {
gen.out("{mod:$$METAMODEL$$");
List<TypeParameter> tparms = null;
List<ProducedType> satisfies = null;
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getTypeParameters();
if (((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType() != null) {
gen.out(",'super':");
metamodelTypeNameOrList(d.getUnit().getPackage(),
((com.redhat.ceylon.compiler.typechecker.model.Class) d).getExtendedType(), gen);
}
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Class) d).getSatisfiedTypes();
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
tparms = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getTypeParameters();
satisfies = ((com.redhat.ceylon.compiler.typechecker.model.Interface) d).getSatisfiedTypes();
} else if (d instanceof Method) {
gen.out(",", MetamodelGenerator.KEY_TYPE, ":");
//This needs a new setting to resolve types but not type parameters
metamodelTypeNameOrList(d.getUnit().getPackage(), ((Method)d).getType(), gen);
gen.out(",", MetamodelGenerator.KEY_PARAMS, ":");
//Parameter types of the first parameter list
encodeParameterListForRuntime(((Method)d).getParameterLists().get(0), gen);
tparms = ((Method) d).getTypeParameters();
}
if (tparms != null && !tparms.isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_TYPE_PARAMS, ":{");
boolean first = true;
for(TypeParameter tp : tparms) {
if (!first)gen.out(",");
first=false;
gen.out(tp.getName(), ":{");
if (tp.isCovariant()) {
gen.out("'var':'out',");
} else if (tp.isContravariant()) {
gen.out("'var':'in',");
}
List<ProducedType> typelist = tp.getSatisfiedTypes();
if (typelist != null && !typelist.isEmpty()) {
gen.out("'satisfies':[");
boolean first2 = true;
for (ProducedType st : typelist) {
if (!first2)gen.out(",");
first2=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
typelist = tp.getCaseTypes();
if (typelist != null && !typelist.isEmpty()) {
gen.out("'of':[");
boolean first3 = true;
for (ProducedType st : typelist) {
if (!first3)gen.out(",");
first3=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (tp.getDefaultTypeArgument() != null) {
gen.out(",'def':");
metamodelTypeNameOrList(d.getUnit().getPackage(), tp.getDefaultTypeArgument(), gen);
}
gen.out("}");
}
gen.out("}");
}
if (satisfies != null) {
gen.out(",satisfies:[");
boolean first = true;
for (ProducedType st : satisfies) {
if (!first)gen.out(",");
first=false;
metamodelTypeNameOrList(d.getUnit().getPackage(), st, gen);
}
gen.out("]");
}
if (annotations != null && !annotations.getAnnotations().isEmpty()) {
gen.out(",", MetamodelGenerator.KEY_ANNOTATIONS, ":function(){return[");
boolean first = true;
for (Tree.Annotation a : annotations.getAnnotations()) {
//Filter out the obvious ones, FOR NOW
if (first) first=false; else gen.out(",");
gen.getInvoker().generateInvocation(a);
}
gen.out("];}");
}
gen.out(",pkg:'", d.getUnit().getPackage().getNameAsString(), "',d:$$METAMODEL$$['");
gen.out(d.getUnit().getPackage().getNameAsString(), "']");
if (d.isToplevel()) {
gen.out("['", d.getName(), "']");
} else {
ArrayList<String> path = new ArrayList<>();
Declaration p = d;
while (p instanceof Declaration) {
path.add(0, p.getName());
//Build the path in reverse
if (!p.isToplevel()) {
if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
path.add(0, p.isAnonymous() ? "$o" : "$c");
} else if (p instanceof com.redhat.ceylon.compiler.typechecker.model.Interface) {
path.add(0, "$i");
} else if (p instanceof Method) {
path.add(0, "$m");
} else {
path.add(0, "$at");
}
}
Scope s = p.getContainer();
while (s != null && s instanceof Declaration == false) {
s = s.getContainer();
}
p = (Declaration)s;
}
//Output path
for (String part : path) {
gen.out("['", part, "']");
}
}
gen.out("}");
}
/** Prints out an object with a type constructor under the property "t" and its type arguments under
* the property "a", or a union/intersection type with "u" or "i" under property "t" and the list
* of types that compose it in an array under the property "l", or a type parameter as a reference to
* already existing params. */
static void metamodelTypeNameOrList(final com.redhat.ceylon.compiler.typechecker.model.Package pkg,
ProducedType pt, GenerateJsVisitor gen) {
if (pt == null) {
//In dynamic blocks we sometimes get a null producedType
pt = ((TypeDeclaration)pkg.getModule().getLanguageModule().getDirectPackage(
"ceylon.language").getDirectMember("Anything", null, false)).getType();
}
TypeDeclaration type = pt.getDeclaration();
if (type.isAlias()) {
type = type.getExtendedTypeDeclaration();
}
boolean unionIntersection = type instanceof UnionType
|| type instanceof IntersectionType;
if (unionIntersection) {
outputMetamodelTypeList(pkg, pt, gen);
} else if (type instanceof TypeParameter) {
gen.out("'", type.getNameAsString(), "'");
} else {
gen.out("{t:");
outputQualifiedTypename(gen.isImported(pkg, type), pt, gen);
//Type Parameters
if (!pt.getTypeArgumentList().isEmpty()) {
gen.out(",a:{");
boolean first = true;
for (Map.Entry<TypeParameter, ProducedType> e : pt.getTypeArguments().entrySet()) {
if (first) first=false; else gen.out(",");
gen.out(e.getKey().getNameAsString(), ":");
metamodelTypeNameOrList(pkg, e.getValue(), gen);
}
gen.out("}");
}
gen.out("}");
}
}
/** Appends an object with the type's type and list of union/intersection types. */
static void outputMetamodelTypeList(final com.redhat.ceylon.compiler.typechecker.model.Package pkg,
ProducedType pt, GenerateJsVisitor gen) {
TypeDeclaration type = pt.getDeclaration();
gen.out("{ t:'");
final List<ProducedType> subs;
if (type instanceof IntersectionType) {
gen.out("i");
subs = type.getSatisfiedTypes();
} else {
gen.out("u");
subs = type.getCaseTypes();
}
gen.out("', l:[");
boolean first = true;
for (ProducedType t : subs) {
if (!first) gen.out(",");
metamodelTypeNameOrList(pkg, t, gen);
first = false;
}
gen.out("]}");
}
ProducedType tupleFromParameters(List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params) {
if (params == null || params.isEmpty()) {
return empty.getType();
}
ProducedType tt = empty.getType();
ProducedType et = null;
for (int i = params.size()-1; i>=0; i--) {
com.redhat.ceylon.compiler.typechecker.model.Parameter p = params.get(i);
if (et == null) {
et = p.getType();
} else {
UnionType ut = new UnionType(p.getUnit());
ArrayList<ProducedType> types = new ArrayList<>();
if (et.getCaseTypes() == null || et.getCaseTypes().isEmpty()) {
types.add(et);
} else {
types.addAll(et.getCaseTypes());
}
types.add(p.getType());
ut.setCaseTypes(types);
et = ut.getType();
}
Map<TypeParameter,ProducedType> args = new HashMap<>();
for (TypeParameter tp : tuple.getTypeParameters()) {
if ("First".equals(tp.getName())) {
args.put(tp, p.getType());
} else if ("Element".equals(tp.getName())) {
args.put(tp, et);
} else if ("Rest".equals(tp.getName())) {
args.put(tp, tt);
}
}
if (i == params.size()-1) {
tt = tuple.getType();
}
tt = tt.substitute(args);
}
return tt;
}
}
| Add missing metamodel info for attributes and members #196
| src/main/java/com/redhat/ceylon/compiler/js/TypeUtils.java | Add missing metamodel info for attributes and members #196 |
|
Java | apache-2.0 | 28aaca71a6ffb3daafc80792b0cf46e74b3b24b5 | 0 | Jonathan727/javarosa,Jonathan727/javarosa,Jonathan727/javarosa | /*
* Copyright (C) 2009 JavaRosa
*
* 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.javarosa.entity.model.view;
import java.util.Date;
import java.util.Vector;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import org.javarosa.core.model.utils.DateUtils;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.storage.Persistable;
import org.javarosa.entity.api.EntitySelectController;
import org.javarosa.entity.model.Entity;
import org.javarosa.j2me.log.CrashHandler;
import org.javarosa.j2me.log.HandledCommandListener;
import org.javarosa.j2me.log.HandledPItemStateListener;
import de.enough.polish.ui.Container;
import de.enough.polish.ui.FramedForm;
import de.enough.polish.ui.Item;
import de.enough.polish.ui.StringItem;
import de.enough.polish.ui.TextField;
import de.enough.polish.ui.UiAccess;
public class EntitySelectView<E extends Persistable> extends FramedForm implements HandledPItemStateListener, HandledCommandListener {
//#if javarosa.patientselect.formfactor == nokia-s40 or javarosa.patientselect.formfactor == sony-k610i
//# private static final int MAX_ROWS_ON_SCREEN = 5;
//# private static final int SCROLL_INCREMENT = 4;
//#elif javarosa.patientselect.formfactor == generic-mcs
//note: should have a real target for 2700c; shouldn't be using generic-mcs
//# private static final int MAX_ROWS_ON_SCREEN = 6;
//# private static final int SCROLL_INCREMENT = 5;
//#else
private static final int MAX_ROWS_ON_SCREEN = 10;
private static final int SCROLL_INCREMENT = 5;
//#endif
public static final int NEW_DISALLOWED = 0;
public static final int NEW_IN_LIST = 1;
public static final int NEW_IN_MENU = 2;
private static final int INDEX_NEW = -1;
//behavior configuration options
public boolean wrapAround = false; //TODO: support this
public int newMode = NEW_IN_LIST;
private EntitySelectController<E> controller;
private Entity<E> entityPrototype;
private String baseTitle;
private TextField tf;
private Command exitCmd;
private Command sortCmd;
private Command newCmd;
private int firstIndex;
private int selectedIndex;
private String sortField;
private Vector<Integer> rowIDs; //index into data corresponding to current matches
public EntitySelectView (EntitySelectController<E> controller, Entity<E> entityPrototype, String title, int newMode) {
super(title);
this.baseTitle = title;
this.controller = controller;
this.entityPrototype = entityPrototype;
this.newMode = newMode;
this.sortField = getDefaultSortField();
tf = new TextField("Find: ", "", 20, TextField.ANY);
tf.setInputMode(TextField.MODE_UPPERCASE);
tf.setItemStateListener(this);
append(Graphics.BOTTOM, tf);
exitCmd = new Command("Cancel", Command.CANCEL, 4);
sortCmd = new Command("Sort", Command.SCREEN, 3);
addCommand(exitCmd);
if (getNumSortFields() > 1) {
addCommand(sortCmd);
}
if (newMode == NEW_IN_MENU) {
newCmd = new Command("New " + entityPrototype.entityType(), Command.SCREEN, 4);
addCommand(newCmd);
}
this.setCommandListener(this);
rowIDs = new Vector<Integer>();
this.setScrollYOffset(0, false);
}
public void init () {
selectedIndex = 0;
firstIndex = 0;
refresh();
}
public void refresh () {
refresh(-1);
}
public void refresh (int selectedEntity) {
if (selectedEntity == -1)
selectedEntity = getSelectedEntity();
getMatches(tf.getText());
selectEntity(selectedEntity);
refreshList();
}
public void show () {
this.setActiveFrame(Graphics.BOTTOM);
controller.setView(this);
}
private void getMatches (String key) {
rowIDs = controller.search(key);
sortRows();
if (newMode == NEW_IN_LIST) {
rowIDs.addElement(new Integer(INDEX_NEW));
}
}
private void stepIndex (boolean increment) {
selectedIndex += (increment ? 1 : -1);
if (selectedIndex < 0) {
selectedIndex = 0;
} else if (selectedIndex >= rowIDs.size()) {
selectedIndex = rowIDs.size() - 1;
}
if (selectedIndex < firstIndex) {
firstIndex -= SCROLL_INCREMENT;
if (firstIndex < 0)
firstIndex = 0;
} else if (selectedIndex >= firstIndex + MAX_ROWS_ON_SCREEN) {
firstIndex += SCROLL_INCREMENT;
//don't believe i need to do any clipping in this case
}
}
private int getSelectedEntity () {
int selectedEntityID = -1;
//save off old selected item
if (!listIsEmpty()) {
int rowID = rowID(selectedIndex);
if (rowID != INDEX_NEW) {
selectedEntityID = controller.getRecordID(rowID(selectedIndex));
}
}
return selectedEntityID;
}
private int numMatches () {
return rowIDs.size() - (newMode == NEW_IN_LIST ? 1 : 0);
}
private boolean listIsEmpty () {
return numMatches() <= 0;
}
private int rowID (int i) {
return rowIDs.elementAt(i).intValue();
}
private void selectEntity (int entityID) {
//if old selected item is in new search result, select it, else select first match
selectedIndex = 0;
if (entityID != -1) {
for (int i = 0; i < rowIDs.size(); i++) {
int rowID = rowID(i);
if (rowID != INDEX_NEW) {
if (controller.getRecordID(rowID) == entityID) {
selectedIndex = i;
}
}
}
}
//position selected item in center of visible list
firstIndex = selectedIndex - MAX_ROWS_ON_SCREEN / 2;
if (firstIndex < 0)
firstIndex = 0;
}
private void refreshList () {
container.clear();
this.setTitle(baseTitle + " (" + numMatches() + ")");
//#style patselTitleRow
Container title = new Container(false);
applyStyle(title, STYLE_TITLE);
String[] titleData = controller.getTitleData();
for (int j = 0; j < titleData.length; j++) {
//#style patselCell
StringItem str = new StringItem("", titleData[j]);
applyStyle(str, STYLE_CELL);
title.add(str);
}
this.append(title);
if (listIsEmpty()) {
this.append( new StringItem("", "(No matches)"));
}
for (int i = firstIndex; i < rowIDs.size() && i < firstIndex + MAX_ROWS_ON_SCREEN; i++) {
Container row;
int rowID = rowID(i);
if (i == selectedIndex) {
//#style patselSelectedRow
row = new Container(false);
applyStyle(row, STYLE_SELECTED);
} else if (i % 2 == 0) {
//#style patselEvenRow
row = new Container(false);
applyStyle(row, STYLE_EVEN);
} else {
//#style patselOddRow
row = new Container(false);
applyStyle(row, STYLE_ODD);
}
if (rowID == INDEX_NEW) {
row.add(new StringItem("", "Add New " + entityPrototype.entityType()));
} else {
String[] rowData = controller.getDataFields(rowID);
for (int j = 0; j < rowData.length; j++) {
//#style patselCell
StringItem str = new StringItem("", rowData[j]);
applyStyle(str, STYLE_CELL);
row.add(str);
}
}
append(row);
}
setActiveFrame(Graphics.BOTTOM);
}
private static final int STYLE_TITLE = 0;
private static final int STYLE_CELL = 1;
private static final int STYLE_EVEN = 2;
private static final int STYLE_ODD = 3;
private static final int STYLE_SELECTED = 4;
private void applyStyle(Item i, int type) {
if (entityPrototype.getStyleKey() == null) {
return;
}
//#foreach esstyle in javarosa.patientselect.types
if("${esstyle}".equals(entityPrototype.getStyleKey())) {
switch(type) {
case STYLE_TITLE:
//#style ${esstyle}SelectTitleRow, patselTitleRow
UiAccess.setStyle(i);
break;
case STYLE_CELL:
//#style ${esstyle}SelectCell, patselCell
UiAccess.setStyle(i);
break;
case STYLE_EVEN:
//#style ${esstyle}SelectEvenRow, patselEvenRow
UiAccess.setStyle(i);
break;
case STYLE_ODD:
//#style ${esstyle}SelectOddRow, patselOddRow
UiAccess.setStyle(i);
break;
case STYLE_SELECTED:
//#style ${esstyle}SelectSelectedRow, patselSelectedRow
UiAccess.setStyle(i);
break;
}
}
//#next esstyle
}
//needs no exception wrapping
protected boolean handleKeyPressed(int keyCode, int gameAction) {
//Supress these actions, letting the propogates screws up scrolling on some platforms.
if (gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) {
return true;
} else if (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8) {
return true;
}
return super.handleKeyPressed(keyCode, gameAction);
}
protected boolean handleKeyReleased(int keyCode, int gameAction) {
try {
if (gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) {
stepIndex(false);
refreshList();
return true;
} else if (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8) {
stepIndex(true);
refreshList();
return true;
} else if (gameAction == Canvas.FIRE && keyCode != Canvas.KEY_NUM5) {
processSelect();
return true;
}
} catch (Exception e) {
Logger.die("gui-keyup", e);
}
return super.handleKeyReleased(keyCode, gameAction);
}
private void processSelect() {
if (rowIDs.size() > 0) {
int rowID = rowID(selectedIndex);
if (rowID == INDEX_NEW) {
controller.newEntity();
} else {
controller.itemSelected(rowID);
}
}
}
public void itemStateChanged(Item i) {
CrashHandler.itemStateChanged(this, i);
}
public void _itemStateChanged(Item item) {
if (item == tf) {
refresh();
}
}
public void changeSort (String sortField) {
this.sortField = sortField;
refresh();
}
public String getSortField () {
return sortField;
}
//can't believe i'm writing a .. sort function
private void sortRows () {
for (int i = rowIDs.size() - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
int rowA = rowID(j);
int rowB = rowID(j + 1);
if (compare(controller.getEntity(rowA), controller.getEntity(rowB)) > 0) {
rowIDs.setElementAt(new Integer(rowB), j);
rowIDs.setElementAt(new Integer(rowA), j + 1);
}
}
}
}
private int compare (Entity<E> eA, Entity<E> eB) {
if (sortField == null) {
return 0;
}
Object valA = eA.getSortKey(sortField);
Object valB = eB.getSortKey(sortField);
return compareVal(valA, valB);
}
private int compareVal (Object valA, Object valB) {
if (valA == null && valB == null) {
return 0;
} else if (valA == null) {
return 1;
} else if (valB == null) {
return -1;
}
if (valA instanceof Integer) {
return compareInt(((Integer)valA).intValue(), ((Integer)valB).intValue());
} else if (valA instanceof Long) {
return compareInt(((Long)valA).longValue(), ((Long)valB).longValue());
} else if (valA instanceof Double) {
return compareFloat(((Double)valA).doubleValue(), ((Double)valB).doubleValue());
} else if (valA instanceof String) {
return compareStr((String)valA, (String)valB);
} else if (valA instanceof Date) {
return compareInt((int)DateUtils.daysSinceEpoch((Date)valA), (int)DateUtils.daysSinceEpoch((Date)valB));
} else if (valA instanceof Object[]) {
Object[] arrA = (Object[])valA;
Object[] arrB = (Object[])valB;
for (int i = 0; i < arrA.length && i < arrB.length; i++) {
int cmp = compareVal(arrA[i], arrB[i]);
if (cmp != 0)
return cmp;
}
return compareInt(arrA.length, arrB.length);
} else {
throw new RuntimeException ("Don't know how to order type [" + valA.getClass().getName() + "]; only int, long, double, string, and date are supported");
}
}
private int compareInt (long a, long b) {
return (a == b ? 0 : (a < b ? -1 : 1));
}
private int compareFloat (double a, double b) {
return (a == b ? 0 : (a < b ? -1 : 1));
}
private int compareStr (String a, String b) {
return a.compareTo(b);
}
private int getNumSortFields () {
String[] fields = entityPrototype.getSortFields();
return (fields == null ? 0 : fields.length);
}
private String getDefaultSortField () {
return (getNumSortFields() == 0 ? null : entityPrototype.getSortFields()[0]);
}
public void commandAction(Command c, Displayable d) {
CrashHandler.commandAction(this, c, d);
}
public void _commandAction(Command cmd, Displayable d) {
if (d == this) {
if (cmd == exitCmd) {
controller.exit();
} else if (cmd == sortCmd) {
EntitySelectSortPopup<E> pssw = new EntitySelectSortPopup<E>(this, controller, entityPrototype);
pssw.show();
} else if (cmd == newCmd) {
controller.newEntity();
}
}
}
//#if polish.hasPointerEvents
//#
//# private int selectedIndexFromScreen (int i) {
//# return firstIndex + i;
//# }
//#
//# protected boolean handlePointerPressed (int x, int y) {
//# boolean handled = false;
//#
//# try {
//#
//# int screenIndex = 0;
//# for (int i = 0; i < this.container.size(); i++) {
//# Item item = this.container.getItems()[i];
//# if (item instanceof Container) {
//# if (this.container.isInItemArea(x - this.container.getAbsoluteX(), y - this.container.getAbsoluteY(), item)) {
//# selectedIndex = selectedIndexFromScreen(screenIndex);
//# refreshList();
//# processSelect();
//#
//# handled = true;
//# break;
//# }
//#
//# screenIndex++;
//# }
//# }
//#
//# } catch (Exception e) {
//# IncidentLogger.die("gui-ptrdown", e);
//# }
//#
//# if (handled) {
//# return true;
//# } else {
//# return super.handlePointerPressed(x, y);
//# }
//# }
//#
//#endif
}
| j2me/entity-select/src/org/javarosa/entity/model/view/EntitySelectView.java | /*
* Copyright (C) 2009 JavaRosa
*
* 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.javarosa.entity.model.view;
import java.util.Date;
import java.util.Vector;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import org.javarosa.core.model.utils.DateUtils;
import org.javarosa.core.services.Logger;
import org.javarosa.core.services.storage.Persistable;
import org.javarosa.entity.api.EntitySelectController;
import org.javarosa.entity.model.Entity;
import org.javarosa.j2me.log.CrashHandler;
import org.javarosa.j2me.log.HandledCommandListener;
import org.javarosa.j2me.log.HandledPItemStateListener;
import de.enough.polish.ui.Container;
import de.enough.polish.ui.FramedForm;
import de.enough.polish.ui.Item;
import de.enough.polish.ui.StringItem;
import de.enough.polish.ui.TextField;
import de.enough.polish.ui.UiAccess;
public class EntitySelectView<E extends Persistable> extends FramedForm implements HandledPItemStateListener, HandledCommandListener {
//#if javarosa.patientselect.formfactor == nokia-s40 or javarosa.patientselect.formfactor == sony-k610i
//# private static final int MAX_ROWS_ON_SCREEN = 5;
//# private static final int SCROLL_INCREMENT = 4;
//#else
private static final int MAX_ROWS_ON_SCREEN = 10;
private static final int SCROLL_INCREMENT = 5;
//#endif
public static final int NEW_DISALLOWED = 0;
public static final int NEW_IN_LIST = 1;
public static final int NEW_IN_MENU = 2;
private static final int INDEX_NEW = -1;
//behavior configuration options
public boolean wrapAround = false; //TODO: support this
public int newMode = NEW_IN_LIST;
private EntitySelectController<E> controller;
private Entity<E> entityPrototype;
private String baseTitle;
private TextField tf;
private Command exitCmd;
private Command sortCmd;
private Command newCmd;
private int firstIndex;
private int selectedIndex;
private String sortField;
private Vector<Integer> rowIDs; //index into data corresponding to current matches
public EntitySelectView (EntitySelectController<E> controller, Entity<E> entityPrototype, String title, int newMode) {
super(title);
this.baseTitle = title;
this.controller = controller;
this.entityPrototype = entityPrototype;
this.newMode = newMode;
this.sortField = getDefaultSortField();
tf = new TextField("Find: ", "", 20, TextField.ANY);
tf.setInputMode(TextField.MODE_UPPERCASE);
tf.setItemStateListener(this);
append(Graphics.BOTTOM, tf);
exitCmd = new Command("Cancel", Command.CANCEL, 4);
sortCmd = new Command("Sort", Command.SCREEN, 3);
addCommand(exitCmd);
if (getNumSortFields() > 1) {
addCommand(sortCmd);
}
if (newMode == NEW_IN_MENU) {
newCmd = new Command("New " + entityPrototype.entityType(), Command.SCREEN, 4);
addCommand(newCmd);
}
this.setCommandListener(this);
rowIDs = new Vector<Integer>();
this.setScrollYOffset(0, false);
}
public void init () {
selectedIndex = 0;
firstIndex = 0;
refresh();
}
public void refresh () {
refresh(-1);
}
public void refresh (int selectedEntity) {
if (selectedEntity == -1)
selectedEntity = getSelectedEntity();
getMatches(tf.getText());
selectEntity(selectedEntity);
refreshList();
}
public void show () {
this.setActiveFrame(Graphics.BOTTOM);
controller.setView(this);
}
private void getMatches (String key) {
rowIDs = controller.search(key);
sortRows();
if (newMode == NEW_IN_LIST) {
rowIDs.addElement(new Integer(INDEX_NEW));
}
}
private void stepIndex (boolean increment) {
selectedIndex += (increment ? 1 : -1);
if (selectedIndex < 0) {
selectedIndex = 0;
} else if (selectedIndex >= rowIDs.size()) {
selectedIndex = rowIDs.size() - 1;
}
if (selectedIndex < firstIndex) {
firstIndex -= SCROLL_INCREMENT;
if (firstIndex < 0)
firstIndex = 0;
} else if (selectedIndex >= firstIndex + MAX_ROWS_ON_SCREEN) {
firstIndex += SCROLL_INCREMENT;
//don't believe i need to do any clipping in this case
}
}
private int getSelectedEntity () {
int selectedEntityID = -1;
//save off old selected item
if (!listIsEmpty()) {
int rowID = rowID(selectedIndex);
if (rowID != INDEX_NEW) {
selectedEntityID = controller.getRecordID(rowID(selectedIndex));
}
}
return selectedEntityID;
}
private int numMatches () {
return rowIDs.size() - (newMode == NEW_IN_LIST ? 1 : 0);
}
private boolean listIsEmpty () {
return numMatches() <= 0;
}
private int rowID (int i) {
return rowIDs.elementAt(i).intValue();
}
private void selectEntity (int entityID) {
//if old selected item is in new search result, select it, else select first match
selectedIndex = 0;
if (entityID != -1) {
for (int i = 0; i < rowIDs.size(); i++) {
int rowID = rowID(i);
if (rowID != INDEX_NEW) {
if (controller.getRecordID(rowID) == entityID) {
selectedIndex = i;
}
}
}
}
//position selected item in center of visible list
firstIndex = selectedIndex - MAX_ROWS_ON_SCREEN / 2;
if (firstIndex < 0)
firstIndex = 0;
}
private void refreshList () {
container.clear();
this.setTitle(baseTitle + " (" + numMatches() + ")");
//#style patselTitleRow
Container title = new Container(false);
applyStyle(title, STYLE_TITLE);
String[] titleData = controller.getTitleData();
for (int j = 0; j < titleData.length; j++) {
//#style patselCell
StringItem str = new StringItem("", titleData[j]);
applyStyle(str, STYLE_CELL);
title.add(str);
}
this.append(title);
if (listIsEmpty()) {
this.append( new StringItem("", "(No matches)"));
}
for (int i = firstIndex; i < rowIDs.size() && i < firstIndex + MAX_ROWS_ON_SCREEN; i++) {
Container row;
int rowID = rowID(i);
if (i == selectedIndex) {
//#style patselSelectedRow
row = new Container(false);
applyStyle(row, STYLE_SELECTED);
} else if (i % 2 == 0) {
//#style patselEvenRow
row = new Container(false);
applyStyle(row, STYLE_EVEN);
} else {
//#style patselOddRow
row = new Container(false);
applyStyle(row, STYLE_ODD);
}
if (rowID == INDEX_NEW) {
row.add(new StringItem("", "Add New " + entityPrototype.entityType()));
} else {
String[] rowData = controller.getDataFields(rowID);
for (int j = 0; j < rowData.length; j++) {
//#style patselCell
StringItem str = new StringItem("", rowData[j]);
applyStyle(str, STYLE_CELL);
row.add(str);
}
}
append(row);
}
setActiveFrame(Graphics.BOTTOM);
}
private static final int STYLE_TITLE = 0;
private static final int STYLE_CELL = 1;
private static final int STYLE_EVEN = 2;
private static final int STYLE_ODD = 3;
private static final int STYLE_SELECTED = 4;
private void applyStyle(Item i, int type) {
if (entityPrototype.getStyleKey() == null) {
return;
}
//#foreach esstyle in javarosa.patientselect.types
if("${esstyle}".equals(entityPrototype.getStyleKey())) {
switch(type) {
case STYLE_TITLE:
//#style ${esstyle}SelectTitleRow, patselTitleRow
UiAccess.setStyle(i);
break;
case STYLE_CELL:
//#style ${esstyle}SelectCell, patselCell
UiAccess.setStyle(i);
break;
case STYLE_EVEN:
//#style ${esstyle}SelectEvenRow, patselEvenRow
UiAccess.setStyle(i);
break;
case STYLE_ODD:
//#style ${esstyle}SelectOddRow, patselOddRow
UiAccess.setStyle(i);
break;
case STYLE_SELECTED:
//#style ${esstyle}SelectSelectedRow, patselSelectedRow
UiAccess.setStyle(i);
break;
}
}
//#next esstyle
}
//needs no exception wrapping
protected boolean handleKeyPressed(int keyCode, int gameAction) {
//Supress these actions, letting the propogates screws up scrolling on some platforms.
if (gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) {
return true;
} else if (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8) {
return true;
}
return super.handleKeyPressed(keyCode, gameAction);
}
protected boolean handleKeyReleased(int keyCode, int gameAction) {
try {
if (gameAction == Canvas.UP && keyCode != Canvas.KEY_NUM2) {
stepIndex(false);
refreshList();
return true;
} else if (gameAction == Canvas.DOWN && keyCode != Canvas.KEY_NUM8) {
stepIndex(true);
refreshList();
return true;
} else if (gameAction == Canvas.FIRE && keyCode != Canvas.KEY_NUM5) {
processSelect();
return true;
}
} catch (Exception e) {
Logger.die("gui-keyup", e);
}
return super.handleKeyReleased(keyCode, gameAction);
}
private void processSelect() {
if (rowIDs.size() > 0) {
int rowID = rowID(selectedIndex);
if (rowID == INDEX_NEW) {
controller.newEntity();
} else {
controller.itemSelected(rowID);
}
}
}
public void itemStateChanged(Item i) {
CrashHandler.itemStateChanged(this, i);
}
public void _itemStateChanged(Item item) {
if (item == tf) {
refresh();
}
}
public void changeSort (String sortField) {
this.sortField = sortField;
refresh();
}
public String getSortField () {
return sortField;
}
//can't believe i'm writing a .. sort function
private void sortRows () {
for (int i = rowIDs.size() - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
int rowA = rowID(j);
int rowB = rowID(j + 1);
if (compare(controller.getEntity(rowA), controller.getEntity(rowB)) > 0) {
rowIDs.setElementAt(new Integer(rowB), j);
rowIDs.setElementAt(new Integer(rowA), j + 1);
}
}
}
}
private int compare (Entity<E> eA, Entity<E> eB) {
if (sortField == null) {
return 0;
}
Object valA = eA.getSortKey(sortField);
Object valB = eB.getSortKey(sortField);
return compareVal(valA, valB);
}
private int compareVal (Object valA, Object valB) {
if (valA == null && valB == null) {
return 0;
} else if (valA == null) {
return 1;
} else if (valB == null) {
return -1;
}
if (valA instanceof Integer) {
return compareInt(((Integer)valA).intValue(), ((Integer)valB).intValue());
} else if (valA instanceof Long) {
return compareInt(((Long)valA).longValue(), ((Long)valB).longValue());
} else if (valA instanceof Double) {
return compareFloat(((Double)valA).doubleValue(), ((Double)valB).doubleValue());
} else if (valA instanceof String) {
return compareStr((String)valA, (String)valB);
} else if (valA instanceof Date) {
return compareInt((int)DateUtils.daysSinceEpoch((Date)valA), (int)DateUtils.daysSinceEpoch((Date)valB));
} else if (valA instanceof Object[]) {
Object[] arrA = (Object[])valA;
Object[] arrB = (Object[])valB;
for (int i = 0; i < arrA.length && i < arrB.length; i++) {
int cmp = compareVal(arrA[i], arrB[i]);
if (cmp != 0)
return cmp;
}
return compareInt(arrA.length, arrB.length);
} else {
throw new RuntimeException ("Don't know how to order type [" + valA.getClass().getName() + "]; only int, long, double, string, and date are supported");
}
}
private int compareInt (long a, long b) {
return (a == b ? 0 : (a < b ? -1 : 1));
}
private int compareFloat (double a, double b) {
return (a == b ? 0 : (a < b ? -1 : 1));
}
private int compareStr (String a, String b) {
return a.compareTo(b);
}
private int getNumSortFields () {
String[] fields = entityPrototype.getSortFields();
return (fields == null ? 0 : fields.length);
}
private String getDefaultSortField () {
return (getNumSortFields() == 0 ? null : entityPrototype.getSortFields()[0]);
}
public void commandAction(Command c, Displayable d) {
CrashHandler.commandAction(this, c, d);
}
public void _commandAction(Command cmd, Displayable d) {
if (d == this) {
if (cmd == exitCmd) {
controller.exit();
} else if (cmd == sortCmd) {
EntitySelectSortPopup<E> pssw = new EntitySelectSortPopup<E>(this, controller, entityPrototype);
pssw.show();
} else if (cmd == newCmd) {
controller.newEntity();
}
}
}
//#if polish.hasPointerEvents
//#
//# private int selectedIndexFromScreen (int i) {
//# return firstIndex + i;
//# }
//#
//# protected boolean handlePointerPressed (int x, int y) {
//# boolean handled = false;
//#
//# try {
//#
//# int screenIndex = 0;
//# for (int i = 0; i < this.container.size(); i++) {
//# Item item = this.container.getItems()[i];
//# if (item instanceof Container) {
//# if (this.container.isInItemArea(x - this.container.getAbsoluteX(), y - this.container.getAbsoluteY(), item)) {
//# selectedIndex = selectedIndexFromScreen(screenIndex);
//# refreshList();
//# processSelect();
//#
//# handled = true;
//# break;
//# }
//#
//# screenIndex++;
//# }
//# }
//#
//# } catch (Exception e) {
//# IncidentLogger.die("gui-ptrdown", e);
//# }
//#
//# if (handled) {
//# return true;
//# } else {
//# return super.handlePointerPressed(x, y);
//# }
//# }
//#
//#endif
}
| fix scrolling for 2700c (reusing generic-mcs form factor)
| j2me/entity-select/src/org/javarosa/entity/model/view/EntitySelectView.java | fix scrolling for 2700c (reusing generic-mcs form factor) |
|
Java | apache-2.0 | c7464090f81647fb335768696e271e72b90d0c4a | 0 | kalaspuffar/pdfbox,apache/pdfbox,apache/pdfbox,kalaspuffar/pdfbox | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.rendering;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.TexturePaint;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.GeneralPath;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.font.PDCIDFontType0;
import org.apache.pdfbox.pdmodel.font.PDCIDFontType2;
import org.apache.pdfbox.pdmodel.graphics.color.PDPattern;
import org.apache.pdfbox.pdmodel.graphics.image.PDImage;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDAbstractPattern;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDShadingPattern;
import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1CFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.PDLineDashPattern;
import org.apache.pdfbox.pdmodel.graphics.state.PDSoftMask;
import org.apache.pdfbox.pdmodel.graphics.blend.SoftMaskPaint;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDTilingPattern;
import org.apache.pdfbox.pdmodel.graphics.shading.PDShading;
import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.util.Matrix;
import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine;
import org.apache.pdfbox.util.Vector;
/**
* Paints a page in a PDF document to a Graphics context.
*
* @author Ben Litchfield
*/
public final class PageDrawer extends PDFGraphicsStreamEngine
{
private static final Log LOG = LogFactory.getLog(PageDrawer.class);
// parent document renderer
private final PDFRenderer renderer;
// the graphics device to draw to, xform is the initial transform of the device (i.e. DPI)
private Graphics2D graphics;
private AffineTransform xform;
// the page box to draw (usually the crop box but may be another)
PDRectangle pageSize;
// clipping winding rule used for the clipping path
private int clipWindingRule = -1;
private GeneralPath linePath = new GeneralPath();
// last clipping path
private Area lastClip;
// buffered clipping area for text being drawn
private Area textClippingArea;
private final Map<PDFont, Glyph2D> fontGlyph2D = new HashMap<PDFont, Glyph2D>();
/**
* Constructor.
*
* @param renderer renderer to render the page.
* @param page the page that is to be rendered.
* @throws IOException If there is an error loading properties from the file.
*/
public PageDrawer(PDFRenderer renderer, PDPage page) throws IOException
{
super(page);
this.renderer = renderer;
}
/**
* Returns the parent renderer.
*/
public PDFRenderer getRenderer()
{
return renderer;
}
/**
* Sets high-quality rendering hints on the current Graphics2D.
*/
private void setRenderingHints()
{
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
/**
* Draws the page to the requested context.
*
* @param g The graphics context to draw onto.
* @param pageSize The size of the page to draw.
* @throws IOException If there is an IO error while drawing the page.
*/
public void drawPage(Graphics g, PDRectangle pageSize) throws IOException
{
graphics = (Graphics2D) g;
xform = graphics.getTransform();
this.pageSize = pageSize;
setRenderingHints();
graphics.translate(0, (int) pageSize.getHeight());
graphics.scale(1, -1);
// TODO use getStroke() to set the initial stroke
graphics.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
// adjust for non-(0,0) crop box
graphics.translate(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY());
processPage(getPage());
for (PDAnnotation annotation : getPage().getAnnotations())
{
showAnnotation(annotation);
}
graphics = null;
}
/**
* Draws the pattern stream to the requested context.
*
* @param g The graphics context to draw onto.
* @param pattern The tiling pattern to be used.
* @param colorSpace color space for this tiling.
* @param color color for this tiling.
* @param patternMatrix the pattern matrix
* @throws IOException If there is an IO error while drawing the page.
*/
public void drawTilingPattern(Graphics2D g, PDTilingPattern pattern, PDColorSpace colorSpace,
PDColor color, Matrix patternMatrix) throws IOException
{
Graphics2D oldGraphics = graphics;
graphics = g;
GeneralPath oldLinePath = linePath;
linePath = new GeneralPath();
Area oldLastClip = lastClip;
lastClip = null;
setRenderingHints();
processTilingPattern(pattern, color, colorSpace, patternMatrix);
graphics = oldGraphics;
linePath = oldLinePath;
lastClip = oldLastClip;
}
/**
* Returns an AWT paint for the given PDColor.
*/
private Paint getPaint(PDColor color) throws IOException
{
PDColorSpace colorSpace = color.getColorSpace();
if (!(colorSpace instanceof PDPattern))
{
float[] rgb = colorSpace.toRGB(color.getComponents());
return new Color(rgb[0], rgb[1], rgb[2]);
}
else
{
PDPattern patternSpace = (PDPattern)colorSpace;
PDAbstractPattern pattern = patternSpace.getPattern(color);
if (pattern instanceof PDTilingPattern)
{
PDTilingPattern tilingPattern = (PDTilingPattern) pattern;
if (tilingPattern.getPaintType() == PDTilingPattern.PAINT_COLORED)
{
// colored tiling pattern
return new TilingPaint(this, tilingPattern, xform);
}
else
{
// uncolored tiling pattern
return new TilingPaint(this, tilingPattern,
patternSpace.getUnderlyingColorSpace(), color, xform);
}
}
else
{
PDShadingPattern shadingPattern = (PDShadingPattern)pattern;
PDShading shading = shadingPattern.getShading();
if (shading == null)
{
LOG.error("shadingPattern is null, will be filled with transparency");
return new Color(0,0,0,0);
}
return shading.toPaint(Matrix.concatenate(getInitialMatrix(),
shadingPattern.getMatrix()));
}
}
}
// sets the clipping path using caching for performance, we track lastClip manually because
// Graphics2D#getClip() returns a new object instead of the same one passed to setClip
private void setClip()
{
Area clippingPath = getGraphicsState().getCurrentClippingPath();
if (clippingPath != lastClip)
{
graphics.setClip(clippingPath);
lastClip = clippingPath;
}
}
@Override
public void beginText() throws IOException
{
setClip();
}
@Override
protected void showText(byte[] string) throws IOException
{
PDGraphicsState state = getGraphicsState();
RenderingMode renderingMode = state.getTextState().getRenderingMode();
// buffer the text clip because it represents a single clipping area
if (renderingMode.isClip())
{
textClippingArea = new Area();
}
super.showText(string);
// apply the buffered clip as one area
if (renderingMode.isClip())
{
state.intersectClippingPath(textClippingArea);
textClippingArea = null;
}
}
@Override
protected void showFontGlyph(Matrix textRenderingMatrix, PDFont font, int code, String unicode,
Vector displacement) throws IOException
{
AffineTransform at = textRenderingMatrix.createAffineTransform();
at.concatenate(font.getFontMatrix().createAffineTransform());
Glyph2D glyph2D = createGlyph2D(font);
drawGlyph2D(glyph2D, font, code, displacement, at);
}
/**
* Render the font using the Glyph2D interface.
*
* @param glyph2D the Glyph2D implementation provided a GeneralPath for each glyph
* @param font the font
* @param code character code
* @param displacement the glyph's displacement (advance)
* @param at the transformation
* @throws IOException if something went wrong
*/
private void drawGlyph2D(Glyph2D glyph2D, PDFont font, int code, Vector displacement,
AffineTransform at) throws IOException
{
PDGraphicsState state = getGraphicsState();
RenderingMode renderingMode = state.getTextState().getRenderingMode();
GeneralPath path = glyph2D.getPathForCharacterCode(code);
if (path != null)
{
// stretch non-embedded glyph if it does not match the width contained in the PDF
if (!font.isEmbedded())
{
float fontWidth = font.getWidthFromFont(code);
if (fontWidth > 0 && // ignore spaces
Math.abs(fontWidth - displacement.getX() * 1000) > 0.0001)
{
float pdfWidth = displacement.getX() * 1000;
at.scale(pdfWidth / fontWidth, 1);
}
}
// render glyph
Shape glyph = at.createTransformedShape(path);
if (renderingMode.isFill())
{
graphics.setComposite(state.getNonStrokingJavaComposite());
graphics.setPaint(getNonStrokingPaint());
setClip();
graphics.fill(glyph);
}
if (renderingMode.isStroke())
{
graphics.setComposite(state.getStrokingJavaComposite());
graphics.setPaint(getStrokingPaint());
graphics.setStroke(getStroke());
setClip();
graphics.draw(glyph);
}
if (renderingMode.isClip())
{
textClippingArea.add(new Area(glyph));
}
}
}
/**
* Provide a Glyph2D for the given font.
*
* @param font the font
* @return the implementation of the Glyph2D interface for the given font
* @throws IOException if something went wrong
*/
private Glyph2D createGlyph2D(PDFont font) throws IOException
{
// Is there already a Glyph2D for the given font?
if (fontGlyph2D.containsKey(font))
{
return fontGlyph2D.get(font);
}
Glyph2D glyph2D = null;
if (font instanceof PDTrueTypeFont)
{
PDTrueTypeFont ttfFont = (PDTrueTypeFont)font;
glyph2D = new TTFGlyph2D(ttfFont); // TTF is never null
}
else if (font instanceof PDType1Font)
{
PDType1Font pdType1Font = (PDType1Font)font;
glyph2D = new Type1Glyph2D(pdType1Font); // T1 is never null
}
else if (font instanceof PDType1CFont)
{
PDType1CFont type1CFont = (PDType1CFont)font;
glyph2D = new Type1Glyph2D(type1CFont);
}
else if (font instanceof PDType0Font)
{
PDType0Font type0Font = (PDType0Font) font;
if (type0Font.getDescendantFont() instanceof PDCIDFontType2)
{
glyph2D = new TTFGlyph2D(type0Font); // TTF is never null
}
else if (type0Font.getDescendantFont() instanceof PDCIDFontType0)
{
// a Type0 CIDFont contains CFF font
PDCIDFontType0 cidType0Font = (PDCIDFontType0)type0Font.getDescendantFont();
glyph2D = new CIDType0Glyph2D(cidType0Font); // todo: could be null (need incorporate fallback)
}
}
else
{
throw new IllegalStateException("Bad font type: " + font.getClass().getSimpleName());
}
// cache the Glyph2D instance
if (glyph2D != null)
{
fontGlyph2D.put(font, glyph2D);
}
if (glyph2D == null)
{
// todo: make sure this never happens
throw new UnsupportedOperationException("No font for " + font.getName());
}
return glyph2D;
}
@Override
public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3)
{
// to ensure that the path is created in the right direction, we have to create
// it by combining single lines instead of creating a simple rectangle
linePath.moveTo((float) p0.getX(), (float) p0.getY());
linePath.lineTo((float) p1.getX(), (float) p1.getY());
linePath.lineTo((float) p2.getX(), (float) p2.getY());
linePath.lineTo((float) p3.getX(), (float) p3.getY());
// close the subpath instead of adding the last line so that a possible set line
// cap style isn't taken into account at the "beginning" of the rectangle
linePath.closePath();
}
/**
* Generates AWT raster for a soft mask
*
* @param softMask soft mask
* @return AWT raster for soft mask
* @throws IOException
*/
private Raster createSoftMaskRaster(PDSoftMask softMask) throws IOException
{
TransparencyGroup transparencyGroup = new TransparencyGroup(softMask.getGroup(), true);
COSName subtype = softMask.getSubType();
if (COSName.ALPHA.equals(subtype))
{
return transparencyGroup.getAlphaRaster();
}
else if (COSName.LUMINOSITY.equals(subtype))
{
return transparencyGroup.getLuminosityRaster();
}
else
{
throw new IOException("Invalid soft mask subtype.");
}
}
private Paint applySoftMaskToPaint(Paint parentPaint, PDSoftMask softMask) throws IOException
{
if (softMask != null)
{
return new SoftMaskPaint(parentPaint, createSoftMaskRaster(softMask));
}
else
{
return parentPaint;
}
}
// returns the stroking AWT Paint
private Paint getStrokingPaint() throws IOException
{
return applySoftMaskToPaint(
getPaint(getGraphicsState().getStrokingColor()),
getGraphicsState().getSoftMask());
}
// returns the non-stroking AWT Paint
private Paint getNonStrokingPaint() throws IOException
{
return getPaint(getGraphicsState().getNonStrokingColor());
}
// create a new stroke based on the current CTM and the current stroke
private BasicStroke getStroke()
{
PDGraphicsState state = getGraphicsState();
// apply the CTM
float lineWidth = transformWidth(state.getLineWidth());
// minimum line width as used by Adobe Reader
if (lineWidth < 0.25)
{
lineWidth = 0.25f;
}
PDLineDashPattern dashPattern = state.getLineDashPattern();
int phaseStart = dashPattern.getPhase();
float[] dashArray = dashPattern.getDashArray();
if (dashArray != null)
{
// apply the CTM
for (int i = 0; i < dashArray.length; ++i)
{
// minimum line dash width avoids JVM crash, see PDFBOX-2373
dashArray[i] = Math.max(transformWidth(dashArray[i]), 0.016f);
}
phaseStart = (int)transformWidth(phaseStart);
// empty dash array is illegal
if (dashArray.length == 0)
{
dashArray = null;
}
}
return new BasicStroke(lineWidth, state.getLineCap(), state.getLineJoin(),
state.getMiterLimit(), dashArray, phaseStart);
}
@Override
public void strokePath() throws IOException
{
graphics.setComposite(getGraphicsState().getStrokingJavaComposite());
graphics.setPaint(getStrokingPaint());
graphics.setStroke(getStroke());
setClip();
graphics.draw(linePath);
linePath.reset();
}
@Override
public void fillPath(int windingRule) throws IOException
{
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
graphics.setPaint(getNonStrokingPaint());
setClip();
linePath.setWindingRule(windingRule);
// disable anti-aliasing for rectangular paths, this is a workaround to avoid small stripes
// which occur when solid fills are used to simulate piecewise gradients, see PDFBOX-2302
boolean isRectangular = isRectangular(linePath);
if (isRectangular)
{
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
}
graphics.fill(linePath);
linePath.reset();
if (isRectangular)
{
// JDK 1.7 has a bug where rendering hints are reset by the above call to
// the setRenderingHint method, so we re-set all hints, see PDFBOX-2302
setRenderingHints();
}
}
/**
* Returns true if the given path is rectangular.
*/
private boolean isRectangular(GeneralPath path)
{
PathIterator iter = path.getPathIterator(null);
double[] coords = new double[6];
int count = 0;
int[] xs = new int[4];
int[] ys = new int[4];
while (!iter.isDone())
{
switch(iter.currentSegment(coords))
{
case PathIterator.SEG_MOVETO:
if (count == 0)
{
xs[count] = (int)Math.floor(coords[0]);
ys[count] = (int)Math.floor(coords[1]);
}
else
{
return false;
}
count++;
break;
case PathIterator.SEG_LINETO:
if (count < 4)
{
xs[count] = (int)Math.floor(coords[0]);
ys[count] = (int)Math.floor(coords[1]);
}
else
{
return false;
}
count++;
break;
case PathIterator.SEG_CUBICTO:
return false;
case PathIterator.SEG_CLOSE:
break;
}
iter.next();
}
if (count == 4)
{
return xs[0] == xs[1] || xs[0] == xs[2] ||
ys[0] == ys[1] || ys[0] == ys[3];
}
return false;
}
/**
* Fills and then strokes the path.
*
* @param windingRule The winding rule this path will use.
* @throws IOException If there is an IO error while filling the path.
*/
@Override
public void fillAndStrokePath(int windingRule) throws IOException
{
// TODO can we avoid cloning the path?
GeneralPath path = (GeneralPath)linePath.clone();
fillPath(windingRule);
linePath = path;
strokePath();
}
@Override
public void clip(int windingRule)
{
// the clipping path will not be updated until the succeeding painting operator is called
clipWindingRule = windingRule;
}
@Override
public void moveTo(float x, float y)
{
linePath.moveTo(x, y);
}
@Override
public void lineTo(float x, float y)
{
linePath.lineTo(x, y);
}
@Override
public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3)
{
linePath.curveTo(x1, y1, x2, y2, x3, y3);
}
@Override
public Point2D.Float getCurrentPoint()
{
Point2D current = linePath.getCurrentPoint();
return new Point2D.Float((float)current.getX(), (float)current.getY());
}
@Override
public void closePath()
{
linePath.closePath();
}
@Override
public void endPath()
{
if (clipWindingRule != -1)
{
linePath.setWindingRule(clipWindingRule);
getGraphicsState().intersectClippingPath(linePath);
clipWindingRule = -1;
}
linePath.reset();
}
@Override
public void drawImage(PDImage pdImage) throws IOException
{
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
AffineTransform at = ctm.createAffineTransform();
if (!pdImage.getInterpolate())
{
boolean isScaledUp = pdImage.getWidth() < Math.round(at.getScaleX()) ||
pdImage.getHeight() < Math.round(at.getScaleY());
// if the image is scaled down, we use smooth interpolation, eg PDFBOX-2364
// only when scaled up do we use nearest neighbour, eg PDFBOX-2302 / mori-cvpr01.pdf
// stencils are excluded from this rule (see survey.pdf)
if (isScaledUp || pdImage.isStencil())
{
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
}
}
if (pdImage.isStencil())
{
// fill the image with paint
PDColor color = getGraphicsState().getNonStrokingColor();
BufferedImage image = pdImage.getStencilImage(getPaint(color));
// draw the image
drawBufferedImage(image, at);
}
else
{
// draw the image
drawBufferedImage(pdImage.getImage(), at);
}
if (!pdImage.getInterpolate())
{
// JDK 1.7 has a bug where rendering hints are reset by the above call to
// the setRenderingHint method, so we re-set all hints, see PDFBOX-2302
setRenderingHints();
}
}
public void drawBufferedImage(BufferedImage image, AffineTransform at) throws IOException
{
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
setClip();
PDSoftMask softMask = getGraphicsState().getSoftMask();
if( softMask != null )
{
AffineTransform imageTransform = new AffineTransform(at);
imageTransform.scale(1, -1);
imageTransform.translate(0, -1);
Paint awtPaint = new TexturePaint(image,
new Rectangle2D.Double(imageTransform.getTranslateX(), imageTransform.getTranslateY(),
imageTransform.getScaleX(), imageTransform.getScaleY()));
awtPaint = applySoftMaskToPaint(awtPaint, softMask);
graphics.setPaint(awtPaint);
Rectangle2D unitRect = new Rectangle2D.Float(0, 0, 1, 1);
graphics.fill(at.createTransformedShape(unitRect));
}
else
{
int width = image.getWidth(null);
int height = image.getHeight(null);
AffineTransform imageTransform = new AffineTransform(at);
imageTransform.scale(1.0 / width, -1.0 / height);
imageTransform.translate(0, -height);
graphics.drawImage(image, imageTransform, null);
}
}
@Override
public void shadingFill(COSName shadingName) throws IOException
{
PDShading shading = getResources().getShading(shadingName);
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
Paint paint = shading.toPaint(ctm);
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
graphics.setPaint(paint);
graphics.setClip(null);
lastClip = null;
graphics.fill(getGraphicsState().getCurrentClippingPath());
}
@Override
public void showAnnotation(PDAnnotation annotation) throws IOException
{
lastClip = null;
//TODO support more annotation flags (Invisible, NoZoom, NoRotate)
int deviceType = graphics.getDeviceConfiguration().getDevice().getType();
if (deviceType == GraphicsDevice.TYPE_PRINTER && !annotation.isPrinted())
{
return;
}
if (deviceType == GraphicsDevice.TYPE_RASTER_SCREEN && annotation.isNoView())
{
return;
}
if (annotation.isHidden())
{
return;
}
super.showAnnotation(annotation);
}
@Override
public void showTransparencyGroup(PDFormXObject form) throws IOException
{
TransparencyGroup group = new TransparencyGroup(form, false);
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
setClip();
// both the DPI xform and the CTM were already applied to the group, so all we do
// here is draw it directly onto the Graphics2D device at the appropriate position
PDRectangle bbox = group.getBBox();
AffineTransform prev = graphics.getTransform();
float x = bbox.getLowerLeftX();
float y = pageSize.getHeight() - bbox.getLowerLeftY() - bbox.getHeight();
graphics.setTransform(AffineTransform.getTranslateInstance(x * xform.getScaleX(),
y * xform.getScaleY()));
PDSoftMask softMask = getGraphicsState().getSoftMask();
if (softMask != null)
{
BufferedImage image = group.getImage();
Paint awtPaint = new TexturePaint(image,
new Rectangle2D.Float(0, 0, image.getWidth(), image.getHeight()));
awtPaint = applySoftMaskToPaint(awtPaint, softMask); // todo: PDFBOX-994 problem here?
graphics.setPaint(awtPaint);
graphics.fill(new Rectangle2D.Float(0, 0, bbox.getWidth() * (float)xform.getScaleX(),
bbox.getHeight() * (float)xform.getScaleY()));
}
else
{
graphics.drawImage(group.getImage(), null, null);
}
graphics.setTransform(prev);
}
/**
* Transparency group.
**/
private final class TransparencyGroup
{
private final BufferedImage image;
private final PDRectangle bbox;
private final int minX;
private final int minY;
private final int width;
private final int height;
/**
* Creates a buffered image for a transparency group result.
*/
private TransparencyGroup(PDFormXObject form, boolean isSoftMask) throws IOException
{
Graphics2D g2dOriginal = graphics;
Area lastClipOriginal = lastClip;
// get the CTM x Form Matrix transform
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
Matrix transform = Matrix.concatenate(ctm, form.getMatrix());
// transform the bbox
GeneralPath transformedBox = form.getBBox().transform(transform);
// clip the bbox to prevent giant bboxes from consuming all memory
Area clip = (Area)getGraphicsState().getCurrentClippingPath().clone();
clip.intersect(new Area(transformedBox));
Rectangle2D clipRect = clip.getBounds2D();
this.bbox = new PDRectangle((float)clipRect.getX(), (float)clipRect.getY(),
(float)clipRect.getWidth(), (float)clipRect.getHeight());
// apply the underlying Graphics2D device's DPI transform
Shape deviceClip = xform.createTransformedShape(clip);
Rectangle2D bounds = deviceClip.getBounds2D();
minX = (int) Math.floor(bounds.getMinX());
minY = (int) Math.floor(bounds.getMinY());
int maxX = (int) Math.floor(bounds.getMaxX()) + 1;
int maxY = (int) Math.floor(bounds.getMaxY()) + 1;
width = maxX - minX;
height = maxY - minY;
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // FIXME - color space
Graphics2D g = image.createGraphics();
// flip y-axis
g.translate(0, height);
g.scale(1, -1);
// apply device transform (DPI)
g.transform(xform);
// adjust the origin
g.translate(-clipRect.getX(), -clipRect.getY());
graphics = g;
try
{
if (isSoftMask)
{
processSoftMask(form);
}
else
{
processTransparencyGroup(form);
}
}
finally
{
lastClip = lastClipOriginal;
graphics.dispose();
graphics = g2dOriginal;
}
}
public BufferedImage getImage()
{
return image;
}
public PDRectangle getBBox()
{
return bbox;
}
public Raster getAlphaRaster()
{
return image.getAlphaRaster();
}
public Raster getLuminosityRaster()
{
BufferedImage gray = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Graphics g = gray.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return gray.getRaster();
}
}
}
| pdfbox/src/main/java/org/apache/pdfbox/rendering/PageDrawer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.rendering;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.Paint;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.TexturePaint;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.GeneralPath;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.Raster;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.font.PDCIDFontType0;
import org.apache.pdfbox.pdmodel.font.PDCIDFontType2;
import org.apache.pdfbox.pdmodel.graphics.color.PDPattern;
import org.apache.pdfbox.pdmodel.graphics.image.PDImage;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDAbstractPattern;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDShadingPattern;
import org.apache.pdfbox.pdmodel.graphics.state.RenderingMode;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDTrueTypeFont;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1CFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.PDLineDashPattern;
import org.apache.pdfbox.pdmodel.graphics.state.PDSoftMask;
import org.apache.pdfbox.pdmodel.graphics.blend.SoftMaskPaint;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDColorSpace;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.pdmodel.graphics.pattern.PDTilingPattern;
import org.apache.pdfbox.pdmodel.graphics.shading.PDShading;
import org.apache.pdfbox.pdmodel.graphics.state.PDGraphicsState;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotation;
import org.apache.pdfbox.util.Matrix;
import org.apache.pdfbox.contentstream.PDFGraphicsStreamEngine;
import org.apache.pdfbox.util.Vector;
/**
* Paints a page in a PDF document to a Graphics context.
*
* @author Ben Litchfield
*/
public final class PageDrawer extends PDFGraphicsStreamEngine
{
private static final Log LOG = LogFactory.getLog(PageDrawer.class);
// parent document renderer
private final PDFRenderer renderer;
// the graphics device to draw to, xform is the initial transform of the device (i.e. DPI)
private Graphics2D graphics;
private AffineTransform xform;
// the page box to draw (usually the crop box but may be another)
PDRectangle pageSize;
// clipping winding rule used for the clipping path
private int clipWindingRule = -1;
private GeneralPath linePath = new GeneralPath();
// last clipping path
private Area lastClip;
// buffered clipping area for text being drawn
private Area textClippingArea;
private final Map<PDFont, Glyph2D> fontGlyph2D = new HashMap<PDFont, Glyph2D>();
/**
* Constructor.
*
* @param renderer renderer to render the page.
* @param page the page that is to be rendered.
* @throws IOException If there is an error loading properties from the file.
*/
public PageDrawer(PDFRenderer renderer, PDPage page) throws IOException
{
super(page);
this.renderer = renderer;
}
/**
* Returns the parent renderer.
*/
public PDFRenderer getRenderer()
{
return renderer;
}
/**
* Sets high-quality rendering hints on the current Graphics2D.
*/
private void setRenderingHints()
{
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
}
/**
* Draws the page to the requested context.
*
* @param g The graphics context to draw onto.
* @param pageSize The size of the page to draw.
* @throws IOException If there is an IO error while drawing the page.
*/
public void drawPage(Graphics g, PDRectangle pageSize) throws IOException
{
graphics = (Graphics2D) g;
xform = graphics.getTransform();
this.pageSize = pageSize;
setRenderingHints();
graphics.translate(0, (int) pageSize.getHeight());
graphics.scale(1, -1);
// TODO use getStroke() to set the initial stroke
graphics.setStroke(new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER));
// adjust for non-(0,0) crop box
graphics.translate(-pageSize.getLowerLeftX(), -pageSize.getLowerLeftY());
processPage(getPage());
for (PDAnnotation annotation : getPage().getAnnotations())
{
showAnnotation(annotation);
}
graphics = null;
}
/**
* Draws the pattern stream to the requested context.
*
* @param g The graphics context to draw onto.
* @param pattern The tiling pattern to be used.
* @param colorSpace color space for this tiling.
* @param color color for this tiling.
* @param patternMatrix the pattern matrix
* @throws IOException If there is an IO error while drawing the page.
*/
public void drawTilingPattern(Graphics2D g, PDTilingPattern pattern, PDColorSpace colorSpace,
PDColor color, Matrix patternMatrix) throws IOException
{
Graphics2D oldGraphics = graphics;
graphics = g;
GeneralPath oldLinePath = linePath;
linePath = new GeneralPath();
Area oldLastClip = lastClip;
lastClip = null;
setRenderingHints();
processTilingPattern(pattern, color, colorSpace, patternMatrix);
graphics = oldGraphics;
linePath = oldLinePath;
lastClip = oldLastClip;
}
/**
* Returns an AWT paint for the given PDColor.
*/
private Paint getPaint(PDColor color) throws IOException
{
PDColorSpace colorSpace = color.getColorSpace();
if (!(colorSpace instanceof PDPattern))
{
float[] rgb = colorSpace.toRGB(color.getComponents());
return new Color(rgb[0], rgb[1], rgb[2]);
}
else
{
PDPattern patternSpace = (PDPattern)colorSpace;
PDAbstractPattern pattern = patternSpace.getPattern(color);
if (pattern instanceof PDTilingPattern)
{
PDTilingPattern tilingPattern = (PDTilingPattern) pattern;
if (tilingPattern.getPaintType() == PDTilingPattern.PAINT_COLORED)
{
// colored tiling pattern
return new TilingPaint(this, tilingPattern, xform);
}
else
{
// uncolored tiling pattern
return new TilingPaint(this, tilingPattern,
patternSpace.getUnderlyingColorSpace(), color, xform);
}
}
else
{
PDShadingPattern shadingPattern = (PDShadingPattern)pattern;
PDShading shading = shadingPattern.getShading();
if (shading == null)
{
LOG.error("shadingPattern is null, will be filled with transparency");
return new Color(0,0,0,0);
}
return shading.toPaint(Matrix.concatenate(getInitialMatrix(),
shadingPattern.getMatrix()));
}
}
}
// sets the clipping path using caching for performance, we track lastClip manually because
// Graphics2D#getClip() returns a new object instead of the same one passed to setClip
private void setClip()
{
Area clippingPath = getGraphicsState().getCurrentClippingPath();
if (clippingPath != lastClip)
{
graphics.setClip(clippingPath);
lastClip = clippingPath;
}
}
@Override
public void beginText() throws IOException
{
setClip();
}
@Override
protected void showText(byte[] string) throws IOException
{
PDGraphicsState state = getGraphicsState();
RenderingMode renderingMode = state.getTextState().getRenderingMode();
// buffer the text clip because it represents a single clipping area
if (renderingMode.isClip())
{
textClippingArea = new Area();
}
super.showText(string);
// apply the buffered clip as one area
if (renderingMode.isClip())
{
state.intersectClippingPath(textClippingArea);
textClippingArea = null;
}
}
@Override
protected void showFontGlyph(Matrix textRenderingMatrix, PDFont font, int code, String unicode,
Vector displacement) throws IOException
{
AffineTransform at = textRenderingMatrix.createAffineTransform();
at.concatenate(font.getFontMatrix().createAffineTransform());
Glyph2D glyph2D = createGlyph2D(font);
drawGlyph2D(glyph2D, font, code, displacement, at);
}
/**
* Render the font using the Glyph2D interface.
*
* @param glyph2D the Glyph2D implementation provided a GeneralPath for each glyph
* @param font the font
* @param code character code
* @param displacement the glyph's displacement (advance)
* @param at the transformation
* @throws IOException if something went wrong
*/
private void drawGlyph2D(Glyph2D glyph2D, PDFont font, int code, Vector displacement,
AffineTransform at) throws IOException
{
PDGraphicsState state = getGraphicsState();
RenderingMode renderingMode = state.getTextState().getRenderingMode();
GeneralPath path = glyph2D.getPathForCharacterCode(code);
if (path != null)
{
// stretch non-embedded glyph if it does not match the width contained in the PDF
if (!font.isEmbedded())
{
float fontWidth = font.getWidthFromFont(code);
if (fontWidth > 0 && // ignore spaces
Math.abs(fontWidth - displacement.getX() * 1000) > 0.0001)
{
float pdfWidth = displacement.getX() * 1000;
at.scale(pdfWidth / fontWidth, 1);
}
}
// render glyph
Shape glyph = at.createTransformedShape(path);
if (renderingMode.isFill())
{
graphics.setComposite(state.getNonStrokingJavaComposite());
graphics.setPaint(getNonStrokingPaint());
setClip();
graphics.fill(glyph);
}
if (renderingMode.isStroke())
{
graphics.setComposite(state.getStrokingJavaComposite());
graphics.setPaint(getStrokingPaint());
graphics.setStroke(getStroke());
setClip();
graphics.draw(glyph);
}
if (renderingMode.isClip())
{
textClippingArea.add(new Area(glyph));
}
}
}
/**
* Provide a Glyph2D for the given font.
*
* @param font the font
* @return the implementation of the Glyph2D interface for the given font
* @throws IOException if something went wrong
*/
private Glyph2D createGlyph2D(PDFont font) throws IOException
{
// Is there already a Glyph2D for the given font?
if (fontGlyph2D.containsKey(font))
{
return fontGlyph2D.get(font);
}
Glyph2D glyph2D = null;
if (font instanceof PDTrueTypeFont)
{
PDTrueTypeFont ttfFont = (PDTrueTypeFont)font;
glyph2D = new TTFGlyph2D(ttfFont); // TTF is never null
}
else if (font instanceof PDType1Font)
{
PDType1Font pdType1Font = (PDType1Font)font;
glyph2D = new Type1Glyph2D(pdType1Font); // T1 is never null
}
else if (font instanceof PDType1CFont)
{
PDType1CFont type1CFont = (PDType1CFont)font;
glyph2D = new Type1Glyph2D(type1CFont);
}
else if (font instanceof PDType0Font)
{
PDType0Font type0Font = (PDType0Font) font;
if (type0Font.getDescendantFont() instanceof PDCIDFontType2)
{
glyph2D = new TTFGlyph2D(type0Font); // TTF is never null
}
else if (type0Font.getDescendantFont() instanceof PDCIDFontType0)
{
// a Type0 CIDFont contains CFF font
PDCIDFontType0 cidType0Font = (PDCIDFontType0)type0Font.getDescendantFont();
glyph2D = new CIDType0Glyph2D(cidType0Font); // todo: could be null (need incorporate fallback)
}
}
else
{
throw new IllegalStateException("Bad font type: " + font.getClass().getSimpleName());
}
// cache the Glyph2D instance
if (glyph2D != null)
{
fontGlyph2D.put(font, glyph2D);
}
if (glyph2D == null)
{
// todo: make sure this never happens
throw new UnsupportedOperationException("No font for " + font.getName());
}
return glyph2D;
}
@Override
public void appendRectangle(Point2D p0, Point2D p1, Point2D p2, Point2D p3)
{
// to ensure that the path is created in the right direction, we have to create
// it by combining single lines instead of creating a simple rectangle
linePath.moveTo((float) p0.getX(), (float) p0.getY());
linePath.lineTo((float) p1.getX(), (float) p1.getY());
linePath.lineTo((float) p2.getX(), (float) p2.getY());
linePath.lineTo((float) p3.getX(), (float) p3.getY());
// close the subpath instead of adding the last line so that a possible set line
// cap style isn't taken into account at the "beginning" of the rectangle
linePath.closePath();
}
/**
* Generates AWT raster for a soft mask
*
* @param softMask soft mask
* @return AWT raster for soft mask
* @throws IOException
*/
private Raster createSoftMaskRaster(PDSoftMask softMask) throws IOException
{
TransparencyGroup transparencyGroup = new TransparencyGroup(softMask.getGroup(), true);
COSName subtype = softMask.getSubType();
if (COSName.ALPHA.equals(subtype))
{
return transparencyGroup.getAlphaRaster();
}
else if (COSName.LUMINOSITY.equals(subtype))
{
return transparencyGroup.getLuminosityRaster();
}
else
{
throw new IOException("Invalid soft mask subtype.");
}
}
private Paint applySoftMaskToPaint(Paint parentPaint, PDSoftMask softMask) throws IOException
{
if (softMask != null)
{
return new SoftMaskPaint(parentPaint, createSoftMaskRaster(softMask));
}
else
{
return parentPaint;
}
}
// returns the stroking AWT Paint
private Paint getStrokingPaint() throws IOException
{
return applySoftMaskToPaint(
getPaint(getGraphicsState().getStrokingColor()),
getGraphicsState().getSoftMask());
}
// returns the non-stroking AWT Paint
private Paint getNonStrokingPaint() throws IOException
{
return getPaint(getGraphicsState().getNonStrokingColor());
}
// create a new stroke based on the current CTM and the current stroke
private BasicStroke getStroke()
{
PDGraphicsState state = getGraphicsState();
// apply the CTM
float lineWidth = transformWidth(state.getLineWidth());
// minimum line width as used by Adobe Reader
if (lineWidth < 0.25)
{
lineWidth = 0.25f;
}
PDLineDashPattern dashPattern = state.getLineDashPattern();
int phaseStart = dashPattern.getPhase();
float[] dashArray = dashPattern.getDashArray();
if (dashArray != null)
{
// apply the CTM
for (int i = 0; i < dashArray.length; ++i)
{
// minimum line dash width avoids JVM crash, see PDFBOX-2373
dashArray[i] = Math.max(transformWidth(dashArray[i]), 0.25f);
}
phaseStart = (int)transformWidth(phaseStart);
// empty dash array is illegal
if (dashArray.length == 0)
{
dashArray = null;
}
}
return new BasicStroke(lineWidth, state.getLineCap(), state.getLineJoin(),
state.getMiterLimit(), dashArray, phaseStart);
}
@Override
public void strokePath() throws IOException
{
graphics.setComposite(getGraphicsState().getStrokingJavaComposite());
graphics.setPaint(getStrokingPaint());
graphics.setStroke(getStroke());
setClip();
graphics.draw(linePath);
linePath.reset();
}
@Override
public void fillPath(int windingRule) throws IOException
{
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
graphics.setPaint(getNonStrokingPaint());
setClip();
linePath.setWindingRule(windingRule);
// disable anti-aliasing for rectangular paths, this is a workaround to avoid small stripes
// which occur when solid fills are used to simulate piecewise gradients, see PDFBOX-2302
boolean isRectangular = isRectangular(linePath);
if (isRectangular)
{
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
}
graphics.fill(linePath);
linePath.reset();
if (isRectangular)
{
// JDK 1.7 has a bug where rendering hints are reset by the above call to
// the setRenderingHint method, so we re-set all hints, see PDFBOX-2302
setRenderingHints();
}
}
/**
* Returns true if the given path is rectangular.
*/
private boolean isRectangular(GeneralPath path)
{
PathIterator iter = path.getPathIterator(null);
double[] coords = new double[6];
int count = 0;
int[] xs = new int[4];
int[] ys = new int[4];
while (!iter.isDone())
{
switch(iter.currentSegment(coords))
{
case PathIterator.SEG_MOVETO:
if (count == 0)
{
xs[count] = (int)Math.floor(coords[0]);
ys[count] = (int)Math.floor(coords[1]);
}
else
{
return false;
}
count++;
break;
case PathIterator.SEG_LINETO:
if (count < 4)
{
xs[count] = (int)Math.floor(coords[0]);
ys[count] = (int)Math.floor(coords[1]);
}
else
{
return false;
}
count++;
break;
case PathIterator.SEG_CUBICTO:
return false;
case PathIterator.SEG_CLOSE:
break;
}
iter.next();
}
if (count == 4)
{
return xs[0] == xs[1] || xs[0] == xs[2] ||
ys[0] == ys[1] || ys[0] == ys[3];
}
return false;
}
/**
* Fills and then strokes the path.
*
* @param windingRule The winding rule this path will use.
* @throws IOException If there is an IO error while filling the path.
*/
@Override
public void fillAndStrokePath(int windingRule) throws IOException
{
// TODO can we avoid cloning the path?
GeneralPath path = (GeneralPath)linePath.clone();
fillPath(windingRule);
linePath = path;
strokePath();
}
@Override
public void clip(int windingRule)
{
// the clipping path will not be updated until the succeeding painting operator is called
clipWindingRule = windingRule;
}
@Override
public void moveTo(float x, float y)
{
linePath.moveTo(x, y);
}
@Override
public void lineTo(float x, float y)
{
linePath.lineTo(x, y);
}
@Override
public void curveTo(float x1, float y1, float x2, float y2, float x3, float y3)
{
linePath.curveTo(x1, y1, x2, y2, x3, y3);
}
@Override
public Point2D.Float getCurrentPoint()
{
Point2D current = linePath.getCurrentPoint();
return new Point2D.Float((float)current.getX(), (float)current.getY());
}
@Override
public void closePath()
{
linePath.closePath();
}
@Override
public void endPath()
{
if (clipWindingRule != -1)
{
linePath.setWindingRule(clipWindingRule);
getGraphicsState().intersectClippingPath(linePath);
clipWindingRule = -1;
}
linePath.reset();
}
@Override
public void drawImage(PDImage pdImage) throws IOException
{
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
AffineTransform at = ctm.createAffineTransform();
if (!pdImage.getInterpolate())
{
boolean isScaledUp = pdImage.getWidth() < Math.round(at.getScaleX()) ||
pdImage.getHeight() < Math.round(at.getScaleY());
// if the image is scaled down, we use smooth interpolation, eg PDFBOX-2364
// only when scaled up do we use nearest neighbour, eg PDFBOX-2302 / mori-cvpr01.pdf
// stencils are excluded from this rule (see survey.pdf)
if (isScaledUp || pdImage.isStencil())
{
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
}
}
if (pdImage.isStencil())
{
// fill the image with paint
PDColor color = getGraphicsState().getNonStrokingColor();
BufferedImage image = pdImage.getStencilImage(getPaint(color));
// draw the image
drawBufferedImage(image, at);
}
else
{
// draw the image
drawBufferedImage(pdImage.getImage(), at);
}
if (!pdImage.getInterpolate())
{
// JDK 1.7 has a bug where rendering hints are reset by the above call to
// the setRenderingHint method, so we re-set all hints, see PDFBOX-2302
setRenderingHints();
}
}
public void drawBufferedImage(BufferedImage image, AffineTransform at) throws IOException
{
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
setClip();
PDSoftMask softMask = getGraphicsState().getSoftMask();
if( softMask != null )
{
AffineTransform imageTransform = new AffineTransform(at);
imageTransform.scale(1, -1);
imageTransform.translate(0, -1);
Paint awtPaint = new TexturePaint(image,
new Rectangle2D.Double(imageTransform.getTranslateX(), imageTransform.getTranslateY(),
imageTransform.getScaleX(), imageTransform.getScaleY()));
awtPaint = applySoftMaskToPaint(awtPaint, softMask);
graphics.setPaint(awtPaint);
Rectangle2D unitRect = new Rectangle2D.Float(0, 0, 1, 1);
graphics.fill(at.createTransformedShape(unitRect));
}
else
{
int width = image.getWidth(null);
int height = image.getHeight(null);
AffineTransform imageTransform = new AffineTransform(at);
imageTransform.scale(1.0 / width, -1.0 / height);
imageTransform.translate(0, -height);
graphics.drawImage(image, imageTransform, null);
}
}
@Override
public void shadingFill(COSName shadingName) throws IOException
{
PDShading shading = getResources().getShading(shadingName);
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
Paint paint = shading.toPaint(ctm);
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
graphics.setPaint(paint);
graphics.setClip(null);
lastClip = null;
graphics.fill(getGraphicsState().getCurrentClippingPath());
}
@Override
public void showAnnotation(PDAnnotation annotation) throws IOException
{
lastClip = null;
//TODO support more annotation flags (Invisible, NoZoom, NoRotate)
int deviceType = graphics.getDeviceConfiguration().getDevice().getType();
if (deviceType == GraphicsDevice.TYPE_PRINTER && !annotation.isPrinted())
{
return;
}
if (deviceType == GraphicsDevice.TYPE_RASTER_SCREEN && annotation.isNoView())
{
return;
}
if (annotation.isHidden())
{
return;
}
super.showAnnotation(annotation);
}
@Override
public void showTransparencyGroup(PDFormXObject form) throws IOException
{
TransparencyGroup group = new TransparencyGroup(form, false);
graphics.setComposite(getGraphicsState().getNonStrokingJavaComposite());
setClip();
// both the DPI xform and the CTM were already applied to the group, so all we do
// here is draw it directly onto the Graphics2D device at the appropriate position
PDRectangle bbox = group.getBBox();
AffineTransform prev = graphics.getTransform();
float x = bbox.getLowerLeftX();
float y = pageSize.getHeight() - bbox.getLowerLeftY() - bbox.getHeight();
graphics.setTransform(AffineTransform.getTranslateInstance(x * xform.getScaleX(),
y * xform.getScaleY()));
PDSoftMask softMask = getGraphicsState().getSoftMask();
if (softMask != null)
{
BufferedImage image = group.getImage();
Paint awtPaint = new TexturePaint(image,
new Rectangle2D.Float(0, 0, image.getWidth(), image.getHeight()));
awtPaint = applySoftMaskToPaint(awtPaint, softMask); // todo: PDFBOX-994 problem here?
graphics.setPaint(awtPaint);
graphics.fill(new Rectangle2D.Float(0, 0, bbox.getWidth() * (float)xform.getScaleX(),
bbox.getHeight() * (float)xform.getScaleY()));
}
else
{
graphics.drawImage(group.getImage(), null, null);
}
graphics.setTransform(prev);
}
/**
* Transparency group.
**/
private final class TransparencyGroup
{
private final BufferedImage image;
private final PDRectangle bbox;
private final int minX;
private final int minY;
private final int width;
private final int height;
/**
* Creates a buffered image for a transparency group result.
*/
private TransparencyGroup(PDFormXObject form, boolean isSoftMask) throws IOException
{
Graphics2D g2dOriginal = graphics;
Area lastClipOriginal = lastClip;
// get the CTM x Form Matrix transform
Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
Matrix transform = Matrix.concatenate(ctm, form.getMatrix());
// transform the bbox
GeneralPath transformedBox = form.getBBox().transform(transform);
// clip the bbox to prevent giant bboxes from consuming all memory
Area clip = (Area)getGraphicsState().getCurrentClippingPath().clone();
clip.intersect(new Area(transformedBox));
Rectangle2D clipRect = clip.getBounds2D();
this.bbox = new PDRectangle((float)clipRect.getX(), (float)clipRect.getY(),
(float)clipRect.getWidth(), (float)clipRect.getHeight());
// apply the underlying Graphics2D device's DPI transform
Shape deviceClip = xform.createTransformedShape(clip);
Rectangle2D bounds = deviceClip.getBounds2D();
minX = (int) Math.floor(bounds.getMinX());
minY = (int) Math.floor(bounds.getMinY());
int maxX = (int) Math.floor(bounds.getMaxX()) + 1;
int maxY = (int) Math.floor(bounds.getMaxY()) + 1;
width = maxX - minX;
height = maxY - minY;
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); // FIXME - color space
Graphics2D g = image.createGraphics();
// flip y-axis
g.translate(0, height);
g.scale(1, -1);
// apply device transform (DPI)
g.transform(xform);
// adjust the origin
g.translate(-clipRect.getX(), -clipRect.getY());
graphics = g;
try
{
if (isSoftMask)
{
processSoftMask(form);
}
else
{
processTransparencyGroup(form);
}
}
finally
{
lastClip = lastClipOriginal;
graphics.dispose();
graphics = g2dOriginal;
}
}
public BufferedImage getImage()
{
return image;
}
public PDRectangle getBBox()
{
return bbox;
}
public Raster getAlphaRaster()
{
return image.getAlphaRaster();
}
public Raster getLuminosityRaster()
{
BufferedImage gray = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
Graphics g = gray.getGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return gray.getRaster();
}
}
}
| PDFBOX-2373: set lower threshhold in order to minimize differences
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1657760 13f79535-47bb-0310-9956-ffa450edef68
| pdfbox/src/main/java/org/apache/pdfbox/rendering/PageDrawer.java | PDFBOX-2373: set lower threshhold in order to minimize differences |
|
Java | apache-2.0 | a25ca23a2c4208ceb8dbd9f5b8b8e79ac3eb1521 | 0 | jibaro/jitsi,pplatek/jitsi,gpolitis/jitsi,laborautonomo/jitsi,jibaro/jitsi,jitsi/jitsi,marclaporte/jitsi,iant-gmbh/jitsi,laborautonomo/jitsi,gpolitis/jitsi,ringdna/jitsi,mckayclarey/jitsi,bebo/jitsi,level7systems/jitsi,HelioGuilherme66/jitsi,jibaro/jitsi,martin7890/jitsi,laborautonomo/jitsi,martin7890/jitsi,pplatek/jitsi,level7systems/jitsi,bebo/jitsi,jibaro/jitsi,laborautonomo/jitsi,bebo/jitsi,tuijldert/jitsi,459below/jitsi,bebo/jitsi,martin7890/jitsi,pplatek/jitsi,procandi/jitsi,ibauersachs/jitsi,iant-gmbh/jitsi,damencho/jitsi,marclaporte/jitsi,tuijldert/jitsi,martin7890/jitsi,HelioGuilherme66/jitsi,laborautonomo/jitsi,procandi/jitsi,bhatvv/jitsi,HelioGuilherme66/jitsi,marclaporte/jitsi,iant-gmbh/jitsi,gpolitis/jitsi,jitsi/jitsi,jitsi/jitsi,damencho/jitsi,dkcreinoso/jitsi,cobratbq/jitsi,iant-gmbh/jitsi,459below/jitsi,tuijldert/jitsi,damencho/jitsi,damencho/jitsi,level7systems/jitsi,dkcreinoso/jitsi,459below/jitsi,dkcreinoso/jitsi,cobratbq/jitsi,bhatvv/jitsi,iant-gmbh/jitsi,459below/jitsi,mckayclarey/jitsi,459below/jitsi,mckayclarey/jitsi,marclaporte/jitsi,ringdna/jitsi,cobratbq/jitsi,ibauersachs/jitsi,bhatvv/jitsi,dkcreinoso/jitsi,gpolitis/jitsi,bhatvv/jitsi,ringdna/jitsi,jitsi/jitsi,ibauersachs/jitsi,jibaro/jitsi,ibauersachs/jitsi,bhatvv/jitsi,procandi/jitsi,gpolitis/jitsi,pplatek/jitsi,tuijldert/jitsi,level7systems/jitsi,cobratbq/jitsi,procandi/jitsi,jitsi/jitsi,martin7890/jitsi,ibauersachs/jitsi,ringdna/jitsi,marclaporte/jitsi,bebo/jitsi,ringdna/jitsi,damencho/jitsi,mckayclarey/jitsi,procandi/jitsi,HelioGuilherme66/jitsi,dkcreinoso/jitsi,level7systems/jitsi,pplatek/jitsi,tuijldert/jitsi,cobratbq/jitsi,mckayclarey/jitsi,HelioGuilherme66/jitsi | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.sip;
import java.util.*;
import javax.sdp.*;
import javax.sip.*;
import javax.sip.address.*;
import javax.sip.header.*;
import javax.sip.message.*;
import gov.nist.javax.sip.stack.*;
import net.java.sip.communicator.impl.protocol.sip.sdp.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.service.protocol.media.*;
import net.java.sip.communicator.util.*;
import org.jitsi.service.configuration.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.service.neomedia.MediaType;
/**
* A SIP implementation of the abstract <tt>Call</tt> class encapsulating SIP
* dialogs.
*
* @author Emil Ivov
* @author Hristo Terezov
*/
public class CallSipImpl
extends MediaAwareCall<CallPeerSipImpl,
OperationSetBasicTelephonySipImpl,
ProtocolProviderServiceSipImpl>
implements CallPeerListener
{
/**
* Our class logger.
*/
private static final Logger logger = Logger.getLogger(CallSipImpl.class);
/**
* When starting call we may have quality preferences we must use
* for the call.
*/
private QualityPreset initialQualityPreferences;
/**
* A reference to the <tt>SipMessageFactory</tt> instance that we should
* use when creating requests.
*/
private final SipMessageFactory messageFactory;
/**
* The name of the property under which the user may specify the number of
* milliseconds for the initial interval for retransmissions of response
* 180.
*/
private static final String RETRANSMITS_RINGING_INTERVAL
= "net.java.sip.communicator.impl.protocol.sip"
+ ".RETRANSMITS_RINGING_INTERVAL";
/**
* The default amount of time (in milliseconds) for the initial interval for
* retransmissions of response 180.
*/
private static final int DEFAULT_RETRANSMITS_RINGING_INTERVAL = 500;
/**
* Maximum number of retransmissions that will be sent.
*/
private static final int MAX_RETRANSMISSIONS = 3;
/**
* The amount of time (in milliseconds) for the initial interval for
* retransmissions of response 180.
*/
private final int retransmitsRingingInterval;
/**
* Crates a CallSipImpl instance belonging to <tt>sourceProvider</tt> and
* initiated by <tt>CallCreator</tt>.
*
* @param parentOpSet a reference to the operation set that's creating us
* and that we would be able to use for even dispatching.
*/
protected CallSipImpl(OperationSetBasicTelephonySipImpl parentOpSet)
{
super(parentOpSet);
this.messageFactory = getProtocolProvider().getMessageFactory();
ConfigurationService cfg = SipActivator.getConfigurationService();
int retransmitsRingingInterval = DEFAULT_RETRANSMITS_RINGING_INTERVAL;
if (cfg != null)
{
retransmitsRingingInterval
= cfg.getInt(
RETRANSMITS_RINGING_INTERVAL,
retransmitsRingingInterval);
}
this.retransmitsRingingInterval = retransmitsRingingInterval;
//let's add ourselves to the calls repo. we are doing it ourselves just
//to make sure that no one ever forgets.
parentOpSet.getActiveCallsRepository().addCall(this);
}
/**
* {@inheritDoc}
*
* Re-INVITEs the <tt>CallPeer</tt>s associated with this
* <tt>CallSipImpl</tt> in order to include/exclude the "isfocus"
* parameter in the Contact header.
*/
@Override
protected void conferenceFocusChanged(boolean oldValue, boolean newValue)
{
try
{
reInvite();
}
catch (OperationFailedException ofe)
{
logger.info("Failed to re-INVITE this Call: " + this, ofe);
}
finally
{
super.conferenceFocusChanged(oldValue, newValue);
}
}
/**
* Returns <tt>true</tt> if <tt>dialog</tt> matches the jain sip dialog
* established with one of the peers in this call.
*
* @param dialog the dialog whose corresponding peer we're looking for.
*
* @return true if this call contains a call peer whose jain sip
* dialog is the same as the specified and false otherwise.
*/
public boolean contains(Dialog dialog)
{
return findCallPeer(dialog) != null;
}
/**
* Creates a new call peer associated with <tt>containingTransaction</tt>
*
* @param containingTransaction the transaction that created the call peer.
* @param sourceProvider the provider that the containingTransaction belongs
* to.
* @return a new instance of a <tt>CallPeerSipImpl</tt> corresponding
* to the <tt>containingTransaction</tt>.
*/
private CallPeerSipImpl createCallPeerFor(
Transaction containingTransaction,
SipProvider sourceProvider)
{
CallPeerSipImpl callPeer
= new CallPeerSipImpl(
containingTransaction.getDialog().getRemoteParty(),
this,
containingTransaction,
sourceProvider);
addCallPeer(callPeer);
boolean incomingCall
= (containingTransaction instanceof ServerTransaction);
callPeer.setState(
incomingCall
? CallPeerState.INCOMING_CALL
: CallPeerState.INITIATING_CALL);
// if this was the first peer we added in this call then the call is
// new and we also need to notify everyone of its creation.
if(getCallPeerCount() == 1)
{
Map<MediaType, MediaDirection> mediaDirections
= new HashMap<MediaType, MediaDirection>();
mediaDirections.put(MediaType.AUDIO, MediaDirection.INACTIVE);
mediaDirections.put(MediaType.VIDEO, MediaDirection.INACTIVE);
boolean hasZrtp = false;
boolean hasSdes = false;
//this check is not mandatory catch all to skip if a problem exists
try
{
// lets check the supported media types.
// for this call
Request inviteReq = containingTransaction.getRequest();
if(inviteReq != null && inviteReq.getRawContent() != null)
{
String sdpStr = SdpUtils.getContentAsString(inviteReq);
SessionDescription sesDescr
= SdpUtils.parseSdpString(sdpStr);
List<MediaDescription> remoteDescriptions
= SdpUtils.extractMediaDescriptions(sesDescr);
for (MediaDescription mediaDescription : remoteDescriptions)
{
MediaType mediaType
= SdpUtils.getMediaType(mediaDescription);
mediaDirections.put(
mediaType,
SdpUtils.getDirection(mediaDescription));
// hasZrtp?
if (!hasZrtp)
{
hasZrtp
= (mediaDescription.getAttribute(
SdpUtils.ZRTP_HASH_ATTR)
!= null);
}
// hasSdes?
if (!hasSdes)
{
@SuppressWarnings("unchecked")
Vector<Attribute> attrs
= mediaDescription.getAttributes(true);
for (Attribute attr : attrs)
{
try
{
if ("crypto".equals(attr.getName()))
{
hasSdes = true;
break;
}
}
catch (SdpParseException spe)
{
logger.error(
"Failed to parse SDP attribute",
spe);
}
}
}
}
}
}
catch(Throwable t)
{
logger.warn("Error getting media types", t);
}
getParentOperationSet().fireCallEvent(
incomingCall
? CallEvent.CALL_RECEIVED
: CallEvent.CALL_INITIATED,
this,
mediaDirections);
if(hasZrtp)
{
callPeer.getMediaHandler().addAdvertisedEncryptionMethod(
SrtpControlType.ZRTP);
}
if(hasSdes)
{
callPeer.getMediaHandler().addAdvertisedEncryptionMethod(
SrtpControlType.SDES);
}
}
return callPeer;
}
/**
* Returns the call peer whose associated jain sip dialog matches
* <tt>dialog</tt>.
*
* @param dialog the jain sip dialog whose corresponding peer we're looking
* for.
* @return the call peer whose jain sip dialog is the same as the specified
* or null if no such call peer was found.
*/
public CallPeerSipImpl findCallPeer(Dialog dialog)
{
Iterator<CallPeerSipImpl> callPeers = this.getCallPeers();
if (logger.isTraceEnabled())
{
logger.trace("Looking for peer with dialog: " + dialog
+ "among " + getCallPeerCount() + " calls");
}
while (callPeers.hasNext())
{
CallPeerSipImpl cp = callPeers.next();
if (cp.getDialog() == dialog)
{
if (logger.isTraceEnabled())
logger.trace("Returning cp=" + cp);
return cp;
}
else
{
if (logger.isTraceEnabled())
logger.trace("Ignoring cp=" + cp + " because cp.dialog="
+ cp.getDialog() + " while dialog=" + dialog);
}
}
return null;
}
/**
* Returns a reference to the <tt>ProtocolProviderServiceSipImpl</tt>
* instance that created this call.
*
* @return a reference to the <tt>ProtocolProviderServiceSipImpl</tt>
* instance that created this call.
*/
@Override
public ProtocolProviderServiceSipImpl getProtocolProvider()
{
return super.getProtocolProvider();
}
/**
* Creates a <tt>CallPeerSipImpl</tt> from <tt>calleeAddress</tt> and sends
* them an invite request. The invite request will be initialized according
* to any relevant parameters in the <tt>cause</tt> message (if different
* from <tt>null</tt>) that is the reason for creating this call.
*
* @param calleeAddress the party that we would like to invite to this call.
* @param cause the message (e.g. a Refer request), that is the reason for
* this invite or <tt>null</tt> if this is a user-initiated invitation
*
* @return the newly created <tt>CallPeer</tt> corresponding to
* <tt>calleeAddress</tt>. All following state change events will be
* delivered through this call peer.
*
* @throws OperationFailedException with the corresponding code if we fail
* to create the call.
*/
public CallPeerSipImpl invite(Address calleeAddress,
javax.sip.message.Message cause)
throws OperationFailedException
{
// create the invite request
Request invite
= messageFactory.createInviteRequest(calleeAddress, cause);
// Transaction
ClientTransaction inviteTransaction = null;
SipProvider jainSipProvider
= getProtocolProvider().getDefaultJainSipProvider();
try
{
inviteTransaction = jainSipProvider.getNewClientTransaction(invite);
}
catch (TransactionUnavailableException ex)
{
ProtocolProviderServiceSipImpl.throwOperationFailedException(
"Failed to create inviteTransaction.\n"
+ "This is most probably a network connection error.",
OperationFailedException.INTERNAL_ERROR, ex, logger);
}
// create the call peer
CallPeerSipImpl callPeer
= createCallPeerFor(inviteTransaction, jainSipProvider);
CallPeerMediaHandlerSipImpl mediaHandler = callPeer.getMediaHandler();
/* enable video if it is a videocall */
mediaHandler.setLocalVideoTransmissionEnabled(localVideoAllowed);
if(initialQualityPreferences != null)
{
// we are in situation where we init the call and we cannot
// determine whether the other party supports changing quality
// so we force it
mediaHandler.setSupportQualityControls(true);
mediaHandler.getQualityControl().setRemoteSendMaxPreset(
initialQualityPreferences);
}
try
{
callPeer.invite();
}
catch(OperationFailedException ex)
{
// if inviting call peer fail for some reason, change its state
// if not already filed
callPeer.setState(CallPeerState.FAILED);
throw ex;
}
return callPeer;
}
/**
* Creates a new call and sends a RINGING response.
*
* @param jainSipProvider the provider containing
* <tt>sourceTransaction</tt>.
* @param serverTran the transaction containing the received request.
*
* @return CallPeerSipImpl the newly created call peer (the one that sent
* the INVITE).
*/
public CallPeerSipImpl processInvite(SipProvider jainSipProvider,
ServerTransaction serverTran)
{
Request invite = serverTran.getRequest();
final CallPeerSipImpl peer
= createCallPeerFor(serverTran, jainSipProvider);
CallInfoHeader infoHeader
= (CallInfoHeader) invite.getHeader(CallInfoHeader.NAME);
// Sets an alternative impp address if such is available in the
// call-info header.
String alternativeIMPPAddress = null;
if (infoHeader != null
&& infoHeader.getParameter("purpose") != null
&& infoHeader.getParameter("purpose").equals("impp"))
{
alternativeIMPPAddress = infoHeader.getInfo().toString();
}
if (alternativeIMPPAddress != null)
peer.setAlternativeIMPPAddress(alternativeIMPPAddress);
//send a ringing response
Response response = null;
try
{
if (logger.isTraceEnabled())
logger.trace("will send ringing response: ");
response = messageFactory.createResponse(Response.RINGING, invite);
serverTran.sendResponse(response);
if(serverTran instanceof SIPTransaction
&& !((SIPTransaction)serverTran).isReliable()
&& peer.getState().equals(CallPeerState.INCOMING_CALL))
{
final Timer timer = new Timer();
CallPeerAdapter stateListener = new CallPeerAdapter()
{
@Override
public void peerStateChanged(CallPeerChangeEvent evt)
{
if(!evt.getNewValue()
.equals(CallPeerState.INCOMING_CALL))
{
timer.cancel();
peer.removeCallPeerListener(this);
}
}
};
int interval = retransmitsRingingInterval;
int delay = 0;
for(int i = 0; i < MAX_RETRANSMISSIONS; i++)
{
delay += interval;
timer.schedule(new RingingResponseTask(response,
serverTran, peer, timer, stateListener), delay);
interval *= 2;
}
peer.addCallPeerListener(stateListener);
}
if (logger.isDebugEnabled())
logger.debug("sent a ringing response: " + response);
}
catch (Exception ex)
{
logger.error("Error while trying to send a request", ex);
peer.setState(CallPeerState.FAILED,
"Internal Error: " + ex.getMessage());
return peer;
}
return peer;
}
/**
* Processes an incoming INVITE that is meant to replace an existing
* <tt>CallPeerSipImpl</tt> that is participating in this call. Typically
* this would happen as a result of an attended transfer.
*
* @param jainSipProvider the JAIN-SIP <tt>SipProvider</tt> that received
* the request.
* @param serverTransaction the transaction containing the INVITE request.
* @param callPeerToReplace a reference to the <tt>CallPeer</tt> that this
* INVITE is trying to replace.
*/
public void processReplacingInvite(SipProvider jainSipProvider,
ServerTransaction serverTransaction,
CallPeerSipImpl callPeerToReplace)
{
CallPeerSipImpl newCallPeer
= createCallPeerFor(serverTransaction, jainSipProvider);
try
{
newCallPeer.answer();
}
catch (OperationFailedException ex)
{
logger.error(
"Failed to auto-answer the referred call peer "
+ newCallPeer,
ex);
/*
* RFC 3891 says an appropriate error response MUST be returned
* and callPeerToReplace must be left unchanged.
*/
//TODO should we send a response here?
return;
}
//we just accepted the new peer and if we got here then it went well
//now let's hangup the other call.
try
{
callPeerToReplace.hangup();
}
catch (OperationFailedException ex)
{
logger.error("Failed to hangup the referer "
+ callPeerToReplace, ex);
callPeerToReplace.setState(
CallPeerState.FAILED, "Internal Error: " + ex);
}
}
/**
* Sends a re-INVITE request to all <tt>CallPeer</tt>s to reflect possible
* changes in the media setup (video start/stop, ...).
*
* @throws OperationFailedException if a problem occurred during the SDP
* generation or there was a network problem
*/
public void reInvite() throws OperationFailedException
{
Iterator<CallPeerSipImpl> peers = getCallPeers();
while (peers.hasNext())
peers.next().sendReInvite();
}
/**
* Set a quality preferences we may use when we start the call.
* @param qualityPreferences the initial quality preferences.
*/
public void setInitialQualityPreferences(QualityPreset qualityPreferences)
{
this.initialQualityPreferences = qualityPreferences;
}
/**
* Task that will retransmit ringing response
*/
private class RingingResponseTask
extends TimerTask
{
/**
* The response that will be sent
*/
private final Response response;
/**
* The transaction containing the received request.
*/
private final ServerTransaction serverTran;
/**
* The peer corresponding to the transaction.
*/
private final CallPeerSipImpl peer;
/**
* The timer that starts the task.
*/
private final Timer timer;
/**
* Listener for the state of the peer.
*/
private CallPeerAdapter stateListener;
/**
* Create ringing response task.
* @param response the response.
* @param serverTran the transaction.
* @param peer the peer.
* @param timer the timer.
* @param stateListener the state listener.
*/
RingingResponseTask(Response response, ServerTransaction serverTran,
CallPeerSipImpl peer, Timer timer, CallPeerAdapter stateListener)
{
this.response = response;
this.serverTran = serverTran;
this.peer = peer;
this.timer = timer;
this.stateListener = stateListener;
}
/**
* Sends the ringing response.
*/
@Override
public void run()
{
try
{
serverTran.sendResponse(response);
}
catch (Exception ex)
{
timer.cancel();
peer.removeCallPeerListener(stateListener);
}
}
}
}
| src/net/java/sip/communicator/impl/protocol/sip/CallSipImpl.java | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.protocol.sip;
import java.util.*;
import javax.sdp.*;
import javax.sip.*;
import javax.sip.address.*;
import javax.sip.header.*;
import javax.sip.message.*;
import gov.nist.javax.sip.stack.*;
import net.java.sip.communicator.impl.protocol.sip.sdp.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.service.protocol.media.*;
import net.java.sip.communicator.util.*;
import org.jitsi.service.configuration.*;
import org.jitsi.service.neomedia.*;
import org.jitsi.service.neomedia.MediaType;
/**
* A SIP implementation of the abstract <tt>Call</tt> class encapsulating SIP
* dialogs.
*
* @author Emil Ivov
* @author Hristo Terezov
*/
public class CallSipImpl
extends MediaAwareCall<CallPeerSipImpl,
OperationSetBasicTelephonySipImpl,
ProtocolProviderServiceSipImpl>
implements CallPeerListener
{
/**
* Our class logger.
*/
private static final Logger logger = Logger.getLogger(CallSipImpl.class);
/**
* When starting call we may have quality preferences we must use
* for the call.
*/
private QualityPreset initialQualityPreferences;
/**
* A reference to the <tt>SipMessageFactory</tt> instance that we should
* use when creating requests.
*/
private final SipMessageFactory messageFactory;
/**
* The name of the property under which the user may specify the number of
* milliseconds for the initial interval for retransmissions of response
* 180.
*/
private static final String RETRANSMITS_RINGING_INTERVAL
= "net.java.sip.communicator.impl.protocol.sip"
+ ".RETRANSMITS_RINGING_INTERVAL";
/**
* The default amount of time (in milliseconds) for the initial interval for
* retransmissions of response 180.
*/
private static final int DEFAULT_RETRANSMITS_RINGING_INTERVAL = 500;
/**
* Maximum number of retransmissions that will be sent.
*/
private static final int MAX_RETRANSMISSIONS = 3;
/**
* The amount of time (in milliseconds) for the initial interval for
* retransmissions of response 180.
*/
private final int retransmitsRingingInterval;
/**
* Crates a CallSipImpl instance belonging to <tt>sourceProvider</tt> and
* initiated by <tt>CallCreator</tt>.
*
* @param parentOpSet a reference to the operation set that's creating us
* and that we would be able to use for even dispatching.
*/
protected CallSipImpl(OperationSetBasicTelephonySipImpl parentOpSet)
{
super(parentOpSet);
this.messageFactory = getProtocolProvider().getMessageFactory();
ConfigurationService cfg = SipActivator.getConfigurationService();
int retransmitsRingingInterval = DEFAULT_RETRANSMITS_RINGING_INTERVAL;
if (cfg != null)
{
retransmitsRingingInterval
= cfg.getInt(
RETRANSMITS_RINGING_INTERVAL,
retransmitsRingingInterval);
}
this.retransmitsRingingInterval = retransmitsRingingInterval;
//let's add ourselves to the calls repo. we are doing it ourselves just
//to make sure that no one ever forgets.
parentOpSet.getActiveCallsRepository().addCall(this);
}
/**
* {@inheritDoc}
*
* Re-INVITEs the <tt>CallPeer</tt>s associated with this
* <tt>CallSipImpl</tt> in order to include/exclude the "isfocus"
* parameter in the Contact header.
*/
@Override
protected void conferenceFocusChanged(boolean oldValue, boolean newValue)
{
try
{
reInvite();
}
catch (OperationFailedException ofe)
{
logger.info("Failed to re-INVITE this Call: " + this, ofe);
}
finally
{
super.conferenceFocusChanged(oldValue, newValue);
}
}
/**
* Returns <tt>true</tt> if <tt>dialog</tt> matches the jain sip dialog
* established with one of the peers in this call.
*
* @param dialog the dialog whose corresponding peer we're looking for.
*
* @return true if this call contains a call peer whose jain sip
* dialog is the same as the specified and false otherwise.
*/
public boolean contains(Dialog dialog)
{
return findCallPeer(dialog) != null;
}
/**
* Creates a new call peer associated with <tt>containingTransaction</tt>
*
* @param containingTransaction the transaction that created the call peer.
* @param sourceProvider the provider that the containingTransaction belongs
* to.
* @return a new instance of a <tt>CallPeerSipImpl</tt> corresponding
* to the <tt>containingTransaction</tt>.
*/
private CallPeerSipImpl createCallPeerFor(
Transaction containingTransaction,
SipProvider sourceProvider)
{
CallPeerSipImpl callPeer
= new CallPeerSipImpl(
containingTransaction.getDialog().getRemoteParty(),
this,
containingTransaction,
sourceProvider);
addCallPeer(callPeer);
boolean incomingCall
= (containingTransaction instanceof ServerTransaction);
callPeer.setState(
incomingCall
? CallPeerState.INCOMING_CALL
: CallPeerState.INITIATING_CALL);
// if this was the first peer we added in this call then the call is
// new and we also need to notify everyone of its creation.
if(getCallPeerCount() == 1)
{
Map<MediaType, MediaDirection> mediaDirections
= new HashMap<MediaType, MediaDirection>();
mediaDirections.put(MediaType.AUDIO, MediaDirection.INACTIVE);
mediaDirections.put(MediaType.VIDEO, MediaDirection.INACTIVE);
boolean hasZrtp = false;
boolean hasSdes = false;
//this check is not mandatory catch all to skip if a problem exists
try
{
// lets check the supported media types.
// for this call
Request inviteReq = containingTransaction.getRequest();
if(inviteReq != null && inviteReq.getRawContent() != null)
{
String sdpStr = SdpUtils.getContentAsString(inviteReq);
SessionDescription sesDescr
= SdpUtils.parseSdpString(sdpStr);
List<MediaDescription> remoteDescriptions
= SdpUtils.extractMediaDescriptions(sesDescr);
for (MediaDescription mediaDescription : remoteDescriptions)
{
MediaType mediaType
= SdpUtils.getMediaType(mediaDescription);
mediaDirections.put(
mediaType,
SdpUtils.getDirection(mediaDescription));
// hasZrtp?
if (!hasZrtp)
{
hasZrtp
= (mediaDescription.getAttribute(
SdpUtils.ZRTP_HASH_ATTR)
!= null);
}
// hasSdes?
if (!hasSdes)
{
@SuppressWarnings("unchecked")
Vector<Attribute> attrs
= mediaDescription.getAttributes(true);
for (Attribute attr : attrs)
{
try
{
if ("crypto".equals(attr.getName()))
{
hasSdes = true;
break;
}
}
catch (SdpParseException spe)
{
logger.error(
"Failed to parse SDP attribute",
spe);
}
}
}
}
}
}
catch(Throwable t)
{
logger.warn("Error getting media types", t);
}
getParentOperationSet().fireCallEvent(
incomingCall
? CallEvent.CALL_RECEIVED
: CallEvent.CALL_INITIATED,
this,
mediaDirections);
if(hasZrtp)
{
callPeer.getMediaHandler().addAdvertisedEncryptionMethod(
SrtpControlType.ZRTP);
}
if(hasSdes)
{
callPeer.getMediaHandler().addAdvertisedEncryptionMethod(
SrtpControlType.SDES);
}
}
return callPeer;
}
/**
* Returns the call peer whose associated jain sip dialog matches
* <tt>dialog</tt>.
*
* @param dialog the jain sip dialog whose corresponding peer we're looking
* for.
* @return the call peer whose jain sip dialog is the same as the specified
* or null if no such call peer was found.
*/
public CallPeerSipImpl findCallPeer(Dialog dialog)
{
Iterator<CallPeerSipImpl> callPeers = this.getCallPeers();
if (logger.isTraceEnabled())
{
logger.trace("Looking for peer with dialog: " + dialog
+ "among " + getCallPeerCount() + " calls");
}
while (callPeers.hasNext())
{
CallPeerSipImpl cp = callPeers.next();
if (cp.getDialog() == dialog)
{
if (logger.isTraceEnabled())
logger.trace("Returning cp=" + cp);
return cp;
}
else
{
if (logger.isTraceEnabled())
logger.trace("Ignoring cp=" + cp + " because cp.dialog="
+ cp.getDialog() + " while dialog=" + dialog);
}
}
return null;
}
/**
* Returns a reference to the <tt>ProtocolProviderServiceSipImpl</tt>
* instance that created this call.
*
* @return a reference to the <tt>ProtocolProviderServiceSipImpl</tt>
* instance that created this call.
*/
@Override
public ProtocolProviderServiceSipImpl getProtocolProvider()
{
return super.getProtocolProvider();
}
/**
* Creates a <tt>CallPeerSipImpl</tt> from <tt>calleeAddress</tt> and sends
* them an invite request. The invite request will be initialized according
* to any relevant parameters in the <tt>cause</tt> message (if different
* from <tt>null</tt>) that is the reason for creating this call.
*
* @param calleeAddress the party that we would like to invite to this call.
* @param cause the message (e.g. a Refer request), that is the reason for
* this invite or <tt>null</tt> if this is a user-initiated invitation
*
* @return the newly created <tt>CallPeer</tt> corresponding to
* <tt>calleeAddress</tt>. All following state change events will be
* delivered through this call peer.
*
* @throws OperationFailedException with the corresponding code if we fail
* to create the call.
*/
public CallPeerSipImpl invite(Address calleeAddress,
javax.sip.message.Message cause)
throws OperationFailedException
{
// create the invite request
Request invite
= messageFactory.createInviteRequest(calleeAddress, cause);
// Transaction
ClientTransaction inviteTransaction = null;
SipProvider jainSipProvider
= getProtocolProvider().getDefaultJainSipProvider();
try
{
inviteTransaction = jainSipProvider.getNewClientTransaction(invite);
}
catch (TransactionUnavailableException ex)
{
ProtocolProviderServiceSipImpl.throwOperationFailedException(
"Failed to create inviteTransaction.\n"
+ "This is most probably a network connection error.",
OperationFailedException.INTERNAL_ERROR, ex, logger);
}
// create the call peer
CallPeerSipImpl callPeer
= createCallPeerFor(inviteTransaction, jainSipProvider);
CallPeerMediaHandlerSipImpl mediaHandler = callPeer.getMediaHandler();
/* enable video if it is a videocall */
mediaHandler.setLocalVideoTransmissionEnabled(localVideoAllowed);
if(initialQualityPreferences != null)
{
// we are in situation where we init the call and we cannot
// determine whether the other party supports changing quality
// so we force it
mediaHandler.setSupportQualityControls(true);
mediaHandler.getQualityControl().setRemoteSendMaxPreset(
initialQualityPreferences);
}
try
{
callPeer.invite();
}
catch(OperationFailedException ex)
{
// if inviting call peer fail for some reason, change its state
// if not already filed
callPeer.setState(CallPeerState.FAILED);
throw ex;
}
return callPeer;
}
/**
* Creates a new call and sends a RINGING response.
*
* @param jainSipProvider the provider containing
* <tt>sourceTransaction</tt>.
* @param serverTran the transaction containing the received request.
*
* @return CallPeerSipImpl the newly created call peer (the one that sent
* the INVITE).
*/
public CallPeerSipImpl processInvite(SipProvider jainSipProvider,
ServerTransaction serverTran)
{
Request invite = serverTran.getRequest();
final CallPeerSipImpl peer
= createCallPeerFor(serverTran, jainSipProvider);
CallInfoHeader infoHeader
= (CallInfoHeader) invite.getHeader(CallInfoHeader.NAME);
// Sets an alternative impp address if such is available in the
// call-info header.
String alternativeIMPPAddress = null;
if (infoHeader != null
&& infoHeader.getParameter("purpose") != null
&& infoHeader.getParameter("purpose").equals("impp"))
{
alternativeIMPPAddress = infoHeader.getInfo().toString();
}
if (alternativeIMPPAddress != null)
peer.setAlternativeIMPPAddress(alternativeIMPPAddress);
//send a ringing response
Response response = null;
try
{
if (logger.isTraceEnabled())
logger.trace("will send ringing response: ");
response = messageFactory.createResponse(Response.RINGING, invite);
serverTran.sendResponse(response);
if(serverTran instanceof SIPTransaction
&& !((SIPTransaction)serverTran).isReliable())
{
final Timer timer = new Timer();
CallPeerAdapter stateListener = new CallPeerAdapter()
{
@Override
public void peerStateChanged(CallPeerChangeEvent evt)
{
if(!evt.getNewValue()
.equals(CallPeerState.INCOMING_CALL))
{
timer.cancel();
peer.removeCallPeerListener(this);
}
}
};
int interval = retransmitsRingingInterval;
int delay = 0;
for(int i = 0; i < MAX_RETRANSMISSIONS; i++)
{
delay += interval;
timer.schedule(new RingingResponseTask(response,
serverTran, peer, timer, stateListener), delay);
interval *= 2;
}
peer.addCallPeerListener(stateListener);
}
if (logger.isDebugEnabled())
logger.debug("sent a ringing response: " + response);
}
catch (Exception ex)
{
logger.error("Error while trying to send a request", ex);
peer.setState(CallPeerState.FAILED,
"Internal Error: " + ex.getMessage());
return peer;
}
return peer;
}
/**
* Processes an incoming INVITE that is meant to replace an existing
* <tt>CallPeerSipImpl</tt> that is participating in this call. Typically
* this would happen as a result of an attended transfer.
*
* @param jainSipProvider the JAIN-SIP <tt>SipProvider</tt> that received
* the request.
* @param serverTransaction the transaction containing the INVITE request.
* @param callPeerToReplace a reference to the <tt>CallPeer</tt> that this
* INVITE is trying to replace.
*/
public void processReplacingInvite(SipProvider jainSipProvider,
ServerTransaction serverTransaction,
CallPeerSipImpl callPeerToReplace)
{
CallPeerSipImpl newCallPeer
= createCallPeerFor(serverTransaction, jainSipProvider);
try
{
newCallPeer.answer();
}
catch (OperationFailedException ex)
{
logger.error(
"Failed to auto-answer the referred call peer "
+ newCallPeer,
ex);
/*
* RFC 3891 says an appropriate error response MUST be returned
* and callPeerToReplace must be left unchanged.
*/
//TODO should we send a response here?
return;
}
//we just accepted the new peer and if we got here then it went well
//now let's hangup the other call.
try
{
callPeerToReplace.hangup();
}
catch (OperationFailedException ex)
{
logger.error("Failed to hangup the referer "
+ callPeerToReplace, ex);
callPeerToReplace.setState(
CallPeerState.FAILED, "Internal Error: " + ex);
}
}
/**
* Sends a re-INVITE request to all <tt>CallPeer</tt>s to reflect possible
* changes in the media setup (video start/stop, ...).
*
* @throws OperationFailedException if a problem occurred during the SDP
* generation or there was a network problem
*/
public void reInvite() throws OperationFailedException
{
Iterator<CallPeerSipImpl> peers = getCallPeers();
while (peers.hasNext())
peers.next().sendReInvite();
}
/**
* Set a quality preferences we may use when we start the call.
* @param qualityPreferences the initial quality preferences.
*/
public void setInitialQualityPreferences(QualityPreset qualityPreferences)
{
this.initialQualityPreferences = qualityPreferences;
}
/**
* Task that will retransmit ringing response
*/
private class RingingResponseTask
extends TimerTask
{
/**
* The response that will be sent
*/
private final Response response;
/**
* The transaction containing the received request.
*/
private final ServerTransaction serverTran;
/**
* The peer corresponding to the transaction.
*/
private final CallPeerSipImpl peer;
/**
* The timer that starts the task.
*/
private final Timer timer;
/**
* Listener for the state of the peer.
*/
private CallPeerAdapter stateListener;
/**
* Create ringing response task.
* @param response the response.
* @param serverTran the transaction.
* @param peer the peer.
* @param timer the timer.
* @param stateListener the state listener.
*/
RingingResponseTask(Response response, ServerTransaction serverTran,
CallPeerSipImpl peer, Timer timer, CallPeerAdapter stateListener)
{
this.response = response;
this.serverTran = serverTran;
this.peer = peer;
this.timer = timer;
this.stateListener = stateListener;
}
/**
* Sends the ringing response.
*/
@Override
public void run()
{
try
{
serverTran.sendResponse(response);
}
catch (Exception ex)
{
timer.cancel();
peer.removeCallPeerListener(stateListener);
}
}
}
}
| Fixes issue with sending ringing responses when the client auto rejected the call.
| src/net/java/sip/communicator/impl/protocol/sip/CallSipImpl.java | Fixes issue with sending ringing responses when the client auto rejected the call. |
|
Java | apache-2.0 | df7abc1f3dc21a76018da729c8975c51d5212a0a | 0 | WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules | package org.labkey.wnprc_ehr.updates;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.labkey.api.module.Module;
import org.labkey.api.module.ModuleContext;
import org.reflections.Reflections;
import java.lang.reflect.Modifier;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Utility class for executing non-schema-related updates to the WNPRC module
*/
public class ModuleUpdate
{
/**
* Logger for logging the logs
*/
private static final Logger LOG = Logger.getLogger(ModuleUpdate.class);
private static Set<Updater> UPDATERS;
/**
* Executes the after update step of each applicable updater in the package
*
* @param ctx Module update context from LabKey
*/
public static void doAfterUpdate(ModuleContext ctx)
{
getApplicableUpdaters(ctx).forEach(x -> x.doAfterUpdate(ctx));
}
/**
* Executes the before update step of each applicable updater in the package
*
* @param ctx Module update context from LabKey
*/
public static void doBeforeUpdate(ModuleContext ctx)
{
getApplicableUpdaters(ctx).forEach(x -> x.doBeforeUpdate(ctx));
}
/**
* Executes the version update step of each applicable updater in the package
*
* @param ctx Module update context from LabKey
*/
public static void doVersionUpdate(ModuleContext ctx)
{
getApplicableUpdaters(ctx).forEach(x -> x.doVersionUpdate(ctx));
}
/**
* Executes any deferred update action that needs to wait until the module has started
*
* @param ctx Module update context from LabKey
*/
public static void onStartup(ModuleContext ctx, Module module)
{
getApplicableUpdaters(ctx).forEach(x -> x.onStartup(ctx, module));
}
/**
* Uses reflection to retrieve the set of all the updaters currently in the module classpath (thread-safe).
*
* @return Set of instances of all updater implementations in the classpath
*/
private static Set<? extends Updater> getAllUpdaters()
{
if (UPDATERS == null)
{
synchronized (ModuleUpdate.class)
{
// double null check for thread safety. one thread might create the object while
// another is in the lock wait
if (UPDATERS == null)
{
LOG.debug("caching list of available Updater implementations");
UPDATERS = new Reflections(ModuleUpdate.class.getPackage().getName())
.getSubTypesOf(Updater.class).stream()
.filter(c -> !Modifier.isAbstract(c.getModifiers()))
.map(c -> {
try
{
return c.getConstructor().newInstance();
}
catch (Exception e)
{
LOG.warn(String.format("unable to create module updater from class: class=%s", c.getCanonicalName()), e);
return null;
}
})
.filter(Objects::nonNull)
.sorted()
.collect(Collectors.toSet());
LOG.debug(String.format("found %d Updater implementations for the cache", UPDATERS.size()));
}
}
}
return UPDATERS;
}
/**
* Returns a stream of all applicable updaters from the current Java module based on the passed context
*
* @param ctx Module update context from LabKey
* @return Stream of {@link Updater} objects to execute
*/
private static Stream<? extends Updater> getApplicableUpdaters(ModuleContext ctx)
{
return getAllUpdaters().stream().filter(x -> x.applies(ctx));
}
/**
* Utility interface for applying individual, non-schema-related module updates
*/
interface Updater extends Comparable<Updater>
{
/**
* Indicates whether a particular update applies given the passed context
*
* @param ctx Module context from LabKey
* @return True if this updater should be executed, false otherwise
*/
boolean applies(ModuleContext ctx);
/**
* Executes the after update step of this update
*
* @param ctx Module context from LabKey
*/
void doAfterUpdate(ModuleContext ctx);
/**
* Executes the before update step of this update
*
* @param ctx Module context from LabKey
*/
void doBeforeUpdate(ModuleContext ctx);
/**
* Executes the version update step of this update
*
* @param ctx Module context from LabKey
*/
void doVersionUpdate(ModuleContext ctx);
/**
* Returns the "target" version to which this updater is intended to update.
*
* @return Target version number (e.g., 15.15)
*/
double getTargetVersion();
/**
* Executes any deferred actions that need to be done after startup
*
* @param ctx Module context from LabKey
*/
void onStartup(ModuleContext ctx, Module module);
}
/**
* Base implementation of the {@link Updater} interface that defines the sort order based on the
* target version and defaults the check for applying the module to a comparison of the target
* version and the module context's original version.
*/
static abstract class ComparableUpdater implements Updater
{
@Override
public boolean applies(ModuleContext ctx)
{
return ctx.getOriginalVersion() < this.getTargetVersion();
}
@Override
public int compareTo(@NotNull ModuleUpdate.Updater o)
{
return Double.compare(this.getTargetVersion(), o.getTargetVersion());
}
}
}
| WNPRC_EHR/src/java/org/labkey/wnprc_ehr/updates/ModuleUpdate.java | package org.labkey.wnprc_ehr.updates;
import org.apache.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import org.labkey.api.module.Module;
import org.labkey.api.module.ModuleContext;
import org.reflections.Reflections;
import java.util.Objects;
import java.util.stream.Stream;
/**
* Utility class for executing non-schema-related updates to the WNPRC module
*/
public class ModuleUpdate
{
/**
* Logger for logging the logs
*/
private static Logger LOG = Logger.getLogger(ModuleUpdate.class);
/**
* Executes the after update step of each applicable updater in the package
*
* @param ctx Module update context from LabKey
*/
public static void doAfterUpdate(ModuleContext ctx)
{
getApplicableUpdaters(ctx).forEach(x -> x.doAfterUpdate(ctx));
}
/**
* Executes the before update step of each applicable updater in the package
*
* @param ctx Module update context from LabKey
*/
public static void doBeforeUpdate(ModuleContext ctx)
{
getApplicableUpdaters(ctx).forEach(x -> x.doBeforeUpdate(ctx));
}
/**
* Executes the version update step of each applicable updater in the package
*
* @param ctx Module update context from LabKey
*/
public static void doVersionUpdate(ModuleContext ctx)
{
getApplicableUpdaters(ctx).forEach(x -> x.doVersionUpdate(ctx));
}
/**
* Executes any deferred update action that needs to wait until the module has started
*
* @param ctx Module update context from LabKey
*/
public static void onStartup(ModuleContext ctx, Module module)
{
getApplicableUpdaters(ctx).forEach(x -> x.onStartup(ctx, module));
}
/**
* Returns a stream of all applicable updaters from the current Java module based on the passed context
*
* @param ctx Module update context from LabKey
* @return Stream of {@link Updater} objects to execute
*/
private static Stream<? extends Updater> getApplicableUpdaters(ModuleContext ctx)
{
return new Reflections(ModuleUpdate.class.getPackage().getName())
.getSubTypesOf(Updater.class).stream()
.map(c -> {
try
{
return c.getConstructor().newInstance();
}
catch (Exception e)
{
LOG.warn(String.format("unable to create module updater from class: class=%s", c.getCanonicalName()), e);
return null;
}
})
.filter(Objects::nonNull)
.filter(x -> x.applies(ctx))
.sorted();
}
/**
* Utility interface for applying individual, non-schema-related module updates
*/
interface Updater extends Comparable<Updater>
{
/**
* Indicates whether a particular update applies given the passed context
*
* @param ctx Module context from LabKey
* @return True if this updater should be executed, false otherwise
*/
boolean applies(ModuleContext ctx);
/**
* Executes the after update step of this update
*
* @param ctx Module context from LabKey
*/
void doAfterUpdate(ModuleContext ctx);
/**
* Executes the before update step of this update
*
* @param ctx Module context from LabKey
*/
void doBeforeUpdate(ModuleContext ctx);
/**
* Executes the version update step of this update
*
* @param ctx Module context from LabKey
*/
void doVersionUpdate(ModuleContext ctx);
/**
* Returns the "target" version to which this updater is intended to update.
*
* @return Target version number (e.g., 15.15)
*/
double getTargetVersion();
/**
* Executes any deferred actions that need to be done after startup
*
* @param ctx Module context from LabKey
*/
void onStartup(ModuleContext ctx, Module module);
}
/**
* Base implementation of the {@link Updater} interface that defines the sort order based on the
* target version and defaults the check for applying the module to a comparison of the target
* version and the module context's original version.
*/
static abstract class ComparableUpdater implements Updater
{
@Override
public boolean applies(ModuleContext ctx)
{
return ctx.getOriginalVersion() < this.getTargetVersion();
}
@Override
public int compareTo(@NotNull ModuleUpdate.Updater o)
{
return Double.compare(this.getTargetVersion(), o.getTargetVersion());
}
}
}
| caching the reflected updater classes, and skipping abstract ones
| WNPRC_EHR/src/java/org/labkey/wnprc_ehr/updates/ModuleUpdate.java | caching the reflected updater classes, and skipping abstract ones |
|
Java | apache-2.0 | 78c60f37719d7c399ef36d8160d071f16d225775 | 0 | babble/babble,babble/babble,babble/babble,babble/babble,babble/babble,babble/babble | // RubyJxpSource.java
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ed.lang.ruby;
import java.io.*;
import java.util.Set;
import java.util.HashSet;
import org.jruby.Ruby;
import org.jruby.RubyIO;
import org.jruby.ast.Node;
import org.jruby.internal.runtime.GlobalVariables;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.ThreadContext;
import org.jruby.util.KCode;
import ed.appserver.JSFileLibrary;
import ed.appserver.jxp.JxpSource;
import ed.io.StreamUtil;
import ed.js.JSObject;
import ed.js.JSFunction;
import ed.js.engine.Scope;
import ed.net.httpserver.HttpResponse;
import ed.util.Dependency;
public class RubyJxpSource extends JxpSource {
static final boolean DEBUG = Boolean.getBoolean("DEBUG.RB");
/** Determines what major version of Ruby to compile: 1.8 (false) or YARV/1.9 (true). **/
public static final boolean YARV_COMPILE = false;
public RubyJxpSource(File f , JSFileLibrary lib) {
_file = f;
_lib = lib;
_runtime = Ruby.newInstance();
}
protected String getContent() throws IOException {
return StreamUtil.readFully(_file);
}
protected InputStream getInputStream() throws FileNotFoundException {
return new FileInputStream(_file);
}
public long lastUpdated(Set<Dependency> visitedDeps) {
return _file.lastModified();
}
public String getName() {
return _file.toString();
}
public File getFile() {
return _file;
}
public synchronized JSFunction getFunction() throws IOException {
final Node code = _getCode(); // Parsed Ruby code
return new ed.js.func.JSFunctionCalls0() {
public Object call(Scope s , Object unused[]) {
_setGlobals(s);
// See the second part of JRuby's Ruby.executeScript(String, String)
ThreadContext context = _runtime.getCurrentContext();
String oldFile = context.getFile();
int oldLine = context.getLine();
try {
context.setFile(code.getPosition().getFile());
context.setLine(code.getPosition().getStartLine());
return _runtime.runNormally(code, YARV_COMPILE);
} finally {
context.setFile(oldFile);
context.setLine(oldLine);
}
}
};
}
private Node _getCode() throws IOException {
final long lastModified = _file.lastModified();
if (_code == null || _lastCompile < lastModified) {
// See the first part of JRuby's Ruby.executeScript(String, String)
String script = getContent();
byte[] bytes;
try {
bytes = script.getBytes(KCode.NONE.getKCode());
} catch (UnsupportedEncodingException e) {
bytes = script.getBytes();
}
_code = _runtime.parseInline(new ByteArrayInputStream(bytes), _file.getPath(), null);
_lastCompile = lastModified;
}
return _code;
}
private void _setGlobals(Scope s) {
GlobalVariables g = _runtime.getGlobalVariables();
// Set stdout so that print/puts statements output to the right place
g.set("$stdout", new RubyIO(_runtime, _getOutputStream(s)));
// Turn all JSObject scope variables into Ruby global variables
Set<String> alreadySeen = new HashSet<String>();
while (s != null) {
for (String key : s.keySet()) {
if (alreadySeen.contains(key)) // Use most "local" version of var
continue;
Object val = s.get(key);
if (DEBUG)
System.err.println("about to set $" + key + "; class = " + (val == null ? "<null>" : val.getClass().getName()));
String name = "$" + key;
g.set(name, RubyObjectWrapper.create(s, _runtime, val, name));
alreadySeen.add(key);
}
s = s.getParent();
}
}
// Return an output stream that sends output to the HTTP response's output stream.
private OutputStream _getOutputStream(Scope s) {
HttpResponse response = (HttpResponse)s.get("response");
return new RubyJxpOutputStream(response.getWriter());
}
private final File _file;
private final JSFileLibrary _lib;
private final Ruby _runtime;
private Node _code;
private long _lastCompile;
}
| src/main/ed/lang/ruby/RubyJxpSource.java | // RubyJxpSource.java
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ed.lang.ruby;
import java.io.*;
import java.util.Set;
import org.jruby.Ruby;
import org.jruby.RubyIO;
import org.jruby.ast.Node;
import org.jruby.internal.runtime.GlobalVariables;
import org.jruby.javasupport.JavaEmbedUtils;
import org.jruby.runtime.ThreadContext;
import org.jruby.util.KCode;
import ed.appserver.JSFileLibrary;
import ed.appserver.jxp.JxpSource;
import ed.io.StreamUtil;
import ed.js.JSObject;
import ed.js.JSFunction;
import ed.js.engine.Scope;
import ed.net.httpserver.HttpResponse;
import ed.util.Dependency;
public class RubyJxpSource extends JxpSource {
static final boolean DEBUG = Boolean.getBoolean("DEBUG.RB");
/** Determines what major version of Ruby to compile: 1.8 (false) or YARV/1.9 (true). **/
public static final boolean YARV_COMPILE = false;
public RubyJxpSource(File f , JSFileLibrary lib) {
_file = f;
_lib = lib;
_runtime = Ruby.newInstance();
}
protected String getContent() throws IOException {
return StreamUtil.readFully(_file);
}
protected InputStream getInputStream() throws FileNotFoundException {
return new FileInputStream(_file);
}
public long lastUpdated(Set<Dependency> visitedDeps) {
return _file.lastModified();
}
public String getName() {
return _file.toString();
}
public File getFile() {
return _file;
}
public synchronized JSFunction getFunction() throws IOException {
final Node code = _getCode(); // Parsed Ruby code
return new ed.js.func.JSFunctionCalls0() {
public Object call(Scope s , Object unused[]) {
_setGlobals(s);
// See the second part of JRuby's Ruby.executeScript(String, String)
ThreadContext context = _runtime.getCurrentContext();
String oldFile = context.getFile();
int oldLine = context.getLine();
try {
context.setFile(code.getPosition().getFile());
context.setLine(code.getPosition().getStartLine());
return _runtime.runNormally(code, YARV_COMPILE);
} finally {
context.setFile(oldFile);
context.setLine(oldLine);
}
}
};
}
private Node _getCode() throws IOException {
final long lastModified = _file.lastModified();
if (_code == null || _lastCompile < lastModified) {
// See the first part of JRuby's Ruby.executeScript(String, String)
String script = getContent();
byte[] bytes;
try {
bytes = script.getBytes(KCode.NONE.getKCode());
} catch (UnsupportedEncodingException e) {
bytes = script.getBytes();
}
_code = _runtime.parseInline(new ByteArrayInputStream(bytes), _file.getPath(), null);
_lastCompile = lastModified;
}
return _code;
}
private void _setGlobals(Scope s) {
GlobalVariables g = _runtime.getGlobalVariables();
// Set stdout so that print/puts statements output to the right place
g.set("$stdout", new RubyIO(_runtime, _getOutputStream(s)));
// Turn all JSObject scope variables into Ruby global variables
while (s != null) {
for (String key : s.keySet()) {
Object val = s.get(key);
if (DEBUG)
System.err.println("about to set $" + key + "; class = " + (val == null ? "<null>" : val.getClass().getName()));
String name = "$" + key;
g.set(name, RubyObjectWrapper.create(s, _runtime, val, name));
}
s = s.getParent();
}
}
// Return an output stream that sends output to the HTTP response's output stream.
private OutputStream _getOutputStream(Scope s) {
HttpResponse response = (HttpResponse)s.get("response");
return new RubyJxpOutputStream(response.getWriter());
}
private final File _file;
private final JSFileLibrary _lib;
private final Ruby _runtime;
private Node _code;
private long _lastCompile;
}
| use most "local" version of each var in scope
| src/main/ed/lang/ruby/RubyJxpSource.java | use most "local" version of each var in scope |
|
Java | apache-2.0 | 2e38dd471b5b48fe9d08740a4ddc266cef412e8f | 0 | mvp/presto,mvp/presto,twitter-forks/presto,shixuan-fan/presto,shixuan-fan/presto,zzhao0/presto,arhimondr/presto,EvilMcJerkface/presto,arhimondr/presto,EvilMcJerkface/presto,EvilMcJerkface/presto,mvp/presto,shixuan-fan/presto,facebook/presto,zzhao0/presto,twitter-forks/presto,facebook/presto,twitter-forks/presto,EvilMcJerkface/presto,prestodb/presto,shixuan-fan/presto,mvp/presto,prestodb/presto,shixuan-fan/presto,EvilMcJerkface/presto,zzhao0/presto,arhimondr/presto,prestodb/presto,twitter-forks/presto,facebook/presto,prestodb/presto,twitter-forks/presto,arhimondr/presto,mvp/presto,prestodb/presto,arhimondr/presto,facebook/presto,zzhao0/presto,facebook/presto,prestodb/presto,zzhao0/presto | /*
* 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.facebook.presto.sql.gen;
import com.facebook.airlift.log.Logger;
import com.facebook.presto.bytecode.BytecodeBlock;
import com.facebook.presto.bytecode.BytecodeNode;
import com.facebook.presto.bytecode.ClassDefinition;
import com.facebook.presto.bytecode.FieldDefinition;
import com.facebook.presto.bytecode.MethodDefinition;
import com.facebook.presto.bytecode.Parameter;
import com.facebook.presto.bytecode.ParameterizedType;
import com.facebook.presto.bytecode.Scope;
import com.facebook.presto.bytecode.Variable;
import com.facebook.presto.bytecode.control.ForLoop;
import com.facebook.presto.bytecode.control.IfStatement;
import com.facebook.presto.common.Page;
import com.facebook.presto.common.block.Block;
import com.facebook.presto.common.block.BlockBuilder;
import com.facebook.presto.common.function.SqlFunctionProperties;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.operator.Work;
import com.facebook.presto.operator.project.ConstantPageProjection;
import com.facebook.presto.operator.project.GeneratedPageProjection;
import com.facebook.presto.operator.project.InputChannels;
import com.facebook.presto.operator.project.InputPageProjection;
import com.facebook.presto.operator.project.PageFieldsToInputParametersRewriter;
import com.facebook.presto.operator.project.PageFilter;
import com.facebook.presto.operator.project.PageProjection;
import com.facebook.presto.operator.project.PageProjectionWithOutputs;
import com.facebook.presto.operator.project.SelectedPositions;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.relation.CallExpression;
import com.facebook.presto.spi.relation.ConstantExpression;
import com.facebook.presto.spi.relation.DeterminismEvaluator;
import com.facebook.presto.spi.relation.InputReferenceExpression;
import com.facebook.presto.spi.relation.LambdaDefinitionExpression;
import com.facebook.presto.spi.relation.RowExpression;
import com.facebook.presto.spi.relation.RowExpressionVisitor;
import com.facebook.presto.spi.relation.SpecialFormExpression;
import com.facebook.presto.spi.relation.VariableReferenceExpression;
import com.facebook.presto.sql.gen.LambdaBytecodeGenerator.CompiledLambda;
import com.facebook.presto.sql.planner.CompilerConfig;
import com.facebook.presto.sql.relational.RowExpressionDeterminismEvaluator;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.Primitives;
import org.weakref.jmx.Managed;
import org.weakref.jmx.Nested;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.TreeSet;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import static com.facebook.presto.bytecode.Access.FINAL;
import static com.facebook.presto.bytecode.Access.PRIVATE;
import static com.facebook.presto.bytecode.Access.PUBLIC;
import static com.facebook.presto.bytecode.Access.a;
import static com.facebook.presto.bytecode.Parameter.arg;
import static com.facebook.presto.bytecode.ParameterizedType.type;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.add;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.and;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantBoolean;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantFalse;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantInt;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantNull;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.invokeStatic;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.lessThan;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.newArray;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.not;
import static com.facebook.presto.operator.project.PageFieldsToInputParametersRewriter.rewritePageFieldsToInputParameters;
import static com.facebook.presto.spi.StandardErrorCode.COMPILER_ERROR;
import static com.facebook.presto.sql.gen.BytecodeUtils.boxPrimitiveIfNecessary;
import static com.facebook.presto.sql.gen.BytecodeUtils.invoke;
import static com.facebook.presto.sql.gen.BytecodeUtils.unboxPrimitiveIfNecessary;
import static com.facebook.presto.sql.gen.CommonSubExpressionRewriter.collectCSEByLevel;
import static com.facebook.presto.sql.gen.CommonSubExpressionRewriter.getExpressionsPartitionedByCSE;
import static com.facebook.presto.sql.gen.CommonSubExpressionRewriter.rewriteExpressionWithCSE;
import static com.facebook.presto.sql.gen.LambdaBytecodeGenerator.generateMethodsForLambda;
import static com.facebook.presto.sql.relational.Expressions.subExpressions;
import static com.facebook.presto.util.CompilerUtils.defineClass;
import static com.facebook.presto.util.CompilerUtils.makeClassName;
import static com.facebook.presto.util.Reflection.constructorMethodHandle;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static java.util.Objects.requireNonNull;
public class PageFunctionCompiler
{
private static Logger log = Logger.get(PageFunctionCompiler.class);
private final Metadata metadata;
private final DeterminismEvaluator determinismEvaluator;
private final LoadingCache<CacheKey, Supplier<PageProjection>> projectionCache;
private final LoadingCache<CacheKey, Supplier<PageFilter>> filterCache;
private final CacheStatsMBean projectionCacheStats;
private final CacheStatsMBean filterCacheStats;
@Inject
public PageFunctionCompiler(Metadata metadata, CompilerConfig config)
{
this(metadata, requireNonNull(config, "config is null").getExpressionCacheSize());
}
public PageFunctionCompiler(Metadata metadata, int expressionCacheSize)
{
this.metadata = requireNonNull(metadata, "metadata is null");
this.determinismEvaluator = new RowExpressionDeterminismEvaluator(metadata.getFunctionManager());
if (expressionCacheSize > 0) {
projectionCache = CacheBuilder.newBuilder()
.recordStats()
.maximumSize(expressionCacheSize)
.build(CacheLoader.from(cacheKey -> compileProjectionInternal(cacheKey.sqlFunctionProperties, cacheKey.rowExpressions, cacheKey.isOptimizeCommonSubExpression, Optional.empty())));
projectionCacheStats = new CacheStatsMBean(projectionCache);
}
else {
projectionCache = null;
projectionCacheStats = null;
}
if (expressionCacheSize > 0) {
filterCache = CacheBuilder.newBuilder()
.recordStats()
.maximumSize(expressionCacheSize)
.build(CacheLoader.from(cacheKey -> compileFilterInternal(cacheKey.sqlFunctionProperties, cacheKey.rowExpressions.get(0), cacheKey.isOptimizeCommonSubExpression, Optional.empty())));
filterCacheStats = new CacheStatsMBean(filterCache);
}
else {
filterCache = null;
filterCacheStats = null;
}
}
@Nullable
@Managed
@Nested
public CacheStatsMBean getProjectionCache()
{
return projectionCacheStats;
}
@Nullable
@Managed
@Nested
public CacheStatsMBean getFilterCache()
{
return filterCacheStats;
}
public List<Supplier<PageProjectionWithOutputs>> compileProjections(SqlFunctionProperties sqlFunctionProperties, List<? extends RowExpression> projections, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
{
if (isOptimizeCommonSubExpression) {
ImmutableList.Builder<Supplier<PageProjectionWithOutputs>> pageProjections = ImmutableList.builder();
ImmutableMap.Builder<RowExpression, Integer> expressionsWithPositionBuilder = ImmutableMap.builder();
for (int i = 0; i < projections.size(); i++) {
RowExpression projection = projections.get(i);
if (projection instanceof ConstantExpression || projection instanceof InputReferenceExpression) {
pageProjections.add(toPageProjectionWithOutputs(compileProjection(sqlFunctionProperties, projection, classNameSuffix), new int[] {i}));
}
else {
expressionsWithPositionBuilder.put(projections.get(i), i);
}
}
Map<RowExpression, Integer> expressionsWithPosition = expressionsWithPositionBuilder.build();
Map<List<RowExpression>, Boolean> projectionsPartitionedByCSE = getExpressionsPartitionedByCSE(expressionsWithPosition.keySet());
for (Map.Entry<List<RowExpression>, Boolean> entry : projectionsPartitionedByCSE.entrySet()) {
if (entry.getValue()) {
pageProjections.add(toPageProjectionWithOutputs(compileProjectionCached(sqlFunctionProperties, entry.getKey(), true, classNameSuffix), toIntArray(entry.getKey().stream().map(expressionsWithPosition::get).collect(toImmutableList()))));
}
else {
verify(entry.getKey().size() == 1, "Expect non-cse expression list to only have one element");
RowExpression projection = entry.getKey().get(0);
pageProjections.add(toPageProjectionWithOutputs(compileProjection(sqlFunctionProperties, projection, classNameSuffix), new int[] {expressionsWithPosition.get(projection)}));
}
}
return pageProjections.build();
}
return IntStream.range(0, projections.size())
.mapToObj(outputChannel -> toPageProjectionWithOutputs(compileProjection(sqlFunctionProperties, projections.get(outputChannel), classNameSuffix), new int[] {outputChannel}))
.collect(toImmutableList());
}
@VisibleForTesting
public Supplier<PageProjection> compileProjection(SqlFunctionProperties sqlFunctionProperties, RowExpression projection, Optional<String> classNameSuffix)
{
if (projection instanceof InputReferenceExpression) {
InputReferenceExpression input = (InputReferenceExpression) projection;
InputPageProjection projectionFunction = new InputPageProjection(input.getField());
return () -> projectionFunction;
}
if (projection instanceof ConstantExpression) {
ConstantExpression constant = (ConstantExpression) projection;
ConstantPageProjection projectionFunction = new ConstantPageProjection(constant.getValue(), constant.getType());
return () -> projectionFunction;
}
return compileProjectionCached(sqlFunctionProperties, ImmutableList.of(projection), false, classNameSuffix);
}
private Supplier<PageProjection> compileProjectionCached(SqlFunctionProperties sqlFunctionProperties, List<RowExpression> projections, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
{
if (projectionCache == null) {
return compileProjectionInternal(sqlFunctionProperties, projections, isOptimizeCommonSubExpression, classNameSuffix);
}
return projectionCache.getUnchecked(new CacheKey(sqlFunctionProperties, projections, isOptimizeCommonSubExpression));
}
private Supplier<PageProjectionWithOutputs> toPageProjectionWithOutputs(Supplier<PageProjection> pageProjection, int[] outputChannels)
{
return () -> new PageProjectionWithOutputs(pageProjection.get(), outputChannels);
}
private Supplier<PageProjection> compileProjectionInternal(SqlFunctionProperties sqlFunctionProperties, List<RowExpression> projections, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
{
requireNonNull(projections, "projections is null");
checkArgument(!projections.isEmpty() && projections.stream().allMatch(projection -> projection instanceof CallExpression || projection instanceof SpecialFormExpression));
PageFieldsToInputParametersRewriter.Result result = rewritePageFieldsToInputParameters(projections);
List<RowExpression> rewrittenExpression = result.getRewrittenExpressions();
CallSiteBinder callSiteBinder = new CallSiteBinder();
// generate Work
ClassDefinition pageProjectionWorkDefinition = definePageProjectWorkClass(sqlFunctionProperties, rewrittenExpression, callSiteBinder, isOptimizeCommonSubExpression, classNameSuffix);
Class<? extends Work> pageProjectionWorkClass;
try {
pageProjectionWorkClass = defineClass(pageProjectionWorkDefinition, Work.class, callSiteBinder.getBindings(), getClass().getClassLoader());
}
catch (PrestoException prestoException) {
throw prestoException;
}
catch (Exception e) {
throw new PrestoException(COMPILER_ERROR, e);
}
return () -> new GeneratedPageProjection(
rewrittenExpression,
rewrittenExpression.stream().allMatch(determinismEvaluator::isDeterministic),
result.getInputChannels(),
constructorMethodHandle(pageProjectionWorkClass, List.class, SqlFunctionProperties.class, Page.class, SelectedPositions.class));
}
private static ParameterizedType generateProjectionWorkClassName(Optional<String> classNameSuffix)
{
return makeClassName("PageProjectionWork", classNameSuffix);
}
private ClassDefinition definePageProjectWorkClass(SqlFunctionProperties sqlFunctionProperties, List<RowExpression> projections, CallSiteBinder callSiteBinder, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
{
ClassDefinition classDefinition = new ClassDefinition(
a(PUBLIC, FINAL),
generateProjectionWorkClassName(classNameSuffix),
type(Object.class),
type(Work.class));
FieldDefinition blockBuilderFields = classDefinition.declareField(a(PRIVATE), "blockBuilders", type(List.class, BlockBuilder.class));
FieldDefinition propertiesField = classDefinition.declareField(a(PRIVATE), "properties", SqlFunctionProperties.class);
FieldDefinition pageField = classDefinition.declareField(a(PRIVATE), "page", Page.class);
FieldDefinition selectedPositionsField = classDefinition.declareField(a(PRIVATE), "selectedPositions", SelectedPositions.class);
FieldDefinition nextIndexOrPositionField = classDefinition.declareField(a(PRIVATE), "nextIndexOrPosition", int.class);
FieldDefinition resultField = classDefinition.declareField(a(PRIVATE), "result", List.class);
CachedInstanceBinder cachedInstanceBinder = new CachedInstanceBinder(classDefinition, callSiteBinder);
// process
generateProcessMethod(classDefinition, blockBuilderFields, projections.size(), propertiesField, pageField, selectedPositionsField, nextIndexOrPositionField, resultField);
// getResult
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "getResult", type(Object.class), ImmutableList.of());
method.getBody().append(method.getThis().getField(resultField)).ret(Object.class);
Map<LambdaDefinitionExpression, CompiledLambda> compiledLambdaMap = generateMethodsForLambda(classDefinition, callSiteBinder, cachedInstanceBinder, projections, metadata, sqlFunctionProperties, "");
// cse
Map<VariableReferenceExpression, CommonSubExpressionFields> cseFields = ImmutableMap.of();
if (isOptimizeCommonSubExpression) {
Map<Integer, Map<RowExpression, VariableReferenceExpression>> commonSubExpressionsByLevel = collectCSEByLevel(projections);
if (!commonSubExpressionsByLevel.isEmpty()) {
cseFields = declareCommonSubExpressionFields(classDefinition, commonSubExpressionsByLevel);
generateCommonSubExpressionMethods(sqlFunctionProperties, classDefinition, callSiteBinder, cachedInstanceBinder, compiledLambdaMap, commonSubExpressionsByLevel, cseFields);
Map<RowExpression, VariableReferenceExpression> commonSubExpressions = commonSubExpressionsByLevel.values().stream()
.flatMap(m -> m.entrySet().stream())
.collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
projections = projections.stream().map(projection -> rewriteExpressionWithCSE(projection, commonSubExpressions)).collect(toImmutableList());
if (log.isDebugEnabled()) {
log.debug("Extracted %d common sub-expressions", commonSubExpressions.size());
commonSubExpressions.entrySet().forEach(entry -> log.debug("\t%s = %s", entry.getValue(), entry.getKey()));
log.debug("Rewrote %d projections: %s", projections.size(), Joiner.on(", ").join(projections));
}
}
}
// evaluate
generateEvaluateMethod(sqlFunctionProperties, classDefinition, callSiteBinder, cachedInstanceBinder, compiledLambdaMap, projections, blockBuilderFields, cseFields);
// constructor
Parameter blockBuilders = arg("blockBuilders", type(List.class, BlockBuilder.class));
Parameter properties = arg("properties", SqlFunctionProperties.class);
Parameter page = arg("page", Page.class);
Parameter selectedPositions = arg("selectedPositions", SelectedPositions.class);
MethodDefinition constructorDefinition = classDefinition.declareConstructor(a(PUBLIC), blockBuilders, properties, page, selectedPositions);
BytecodeBlock body = constructorDefinition.getBody();
Variable thisVariable = constructorDefinition.getThis();
body.comment("super();")
.append(thisVariable)
.invokeConstructor(Object.class)
.append(thisVariable.setField(blockBuilderFields, invokeStatic(ImmutableList.class, "copyOf", ImmutableList.class, blockBuilders.cast(Collection.class))))
.append(thisVariable.setField(propertiesField, properties))
.append(thisVariable.setField(pageField, page))
.append(thisVariable.setField(selectedPositionsField, selectedPositions))
.append(thisVariable.setField(nextIndexOrPositionField, selectedPositions.invoke("getOffset", int.class)))
.append(thisVariable.setField(resultField, constantNull(Block.class)));
initializeCommonSubExpressionFields(cseFields.values(), thisVariable, body);
cachedInstanceBinder.generateInitializations(thisVariable, body);
body.ret();
return classDefinition;
}
private static MethodDefinition generateProcessMethod(
ClassDefinition classDefinition,
FieldDefinition blockBuilders,
int blockBuilderSize,
FieldDefinition properties,
FieldDefinition page,
FieldDefinition selectedPositions,
FieldDefinition nextIndexOrPosition,
FieldDefinition result)
{
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "process", type(boolean.class), ImmutableList.of());
Scope scope = method.getScope();
Variable thisVariable = method.getThis();
BytecodeBlock body = method.getBody();
Variable from = scope.declareVariable("from", body, thisVariable.getField(nextIndexOrPosition));
Variable to = scope.declareVariable("to", body, add(thisVariable.getField(selectedPositions).invoke("getOffset", int.class), thisVariable.getField(selectedPositions).invoke("size", int.class)));
Variable positions = scope.declareVariable(int[].class, "positions");
Variable index = scope.declareVariable(int.class, "index");
IfStatement ifStatement = new IfStatement()
.condition(thisVariable.getField(selectedPositions).invoke("isList", boolean.class));
body.append(ifStatement);
ifStatement.ifTrue(new BytecodeBlock()
.append(positions.set(thisVariable.getField(selectedPositions).invoke("getPositions", int[].class)))
.append(new ForLoop("positions loop")
.initialize(index.set(from))
.condition(lessThan(index, to))
.update(index.increment())
.body(new BytecodeBlock()
.append(thisVariable.invoke("evaluate", void.class, thisVariable.getField(properties), thisVariable.getField(page), positions.getElement(index))))));
ifStatement.ifFalse(new ForLoop("range based loop")
.initialize(index.set(from))
.condition(lessThan(index, to))
.update(index.increment())
.body(new BytecodeBlock()
.append(thisVariable.invoke("evaluate", void.class, thisVariable.getField(properties), thisVariable.getField(page), index))));
Variable blocksBuilder = scope.declareVariable("blocksBuilder", body, invokeStatic(ImmutableList.class, "builder", ImmutableList.Builder.class));
Variable iterator = scope.createTempVariable(int.class);
ForLoop forLoop = new ForLoop("for (iterator = 0; iterator < this.blockBuilders.size(); iterator ++) blockBuildersBuilder.add(this.blockBuilders.get(iterator).builder();")
.initialize(iterator.set(constantInt(0)))
.condition(lessThan(iterator, constantInt(blockBuilderSize)))
.update(iterator.increment())
.body(new BytecodeBlock()
.append(blocksBuilder.invoke(
"add",
ImmutableList.Builder.class,
thisVariable.getField(blockBuilders).invoke("get", Object.class, iterator).cast(BlockBuilder.class).invoke("build", Block.class).cast(Object.class)).pop()));
body.append(forLoop)
.comment("result = blockBuildersBuilder.build(); return true")
.append(thisVariable.setField(result, blocksBuilder.invoke("build", ImmutableList.class)))
.push(true)
.retBoolean();
return method;
}
private List<MethodDefinition> generateCommonSubExpressionMethods(
SqlFunctionProperties sqlFunctionProperties,
ClassDefinition classDefinition,
CallSiteBinder callSiteBinder,
CachedInstanceBinder cachedInstanceBinder,
Map<LambdaDefinitionExpression, CompiledLambda> compiledLambdaMap,
Map<Integer, Map<RowExpression, VariableReferenceExpression>> commonSubExpressionsByLevel,
Map<VariableReferenceExpression, CommonSubExpressionFields> commonSubExpressionFieldsMap)
{
ImmutableList.Builder<MethodDefinition> methods = ImmutableList.builder();
Parameter properties = arg("properties", SqlFunctionProperties.class);
Parameter page = arg("page", Page.class);
Parameter position = arg("position", int.class);
Map<VariableReferenceExpression, CommonSubExpressionFields> cseMap = new HashMap<>();
int startLevel = commonSubExpressionsByLevel.keySet().stream().reduce(Math::min).get();
int maxLevel = commonSubExpressionsByLevel.keySet().stream().reduce(Math::max).get();
for (int i = startLevel; i <= maxLevel; i++) {
if (commonSubExpressionsByLevel.containsKey(i)) {
for (Map.Entry<RowExpression, VariableReferenceExpression> entry : commonSubExpressionsByLevel.get(i).entrySet()) {
RowExpression cse = entry.getKey();
Class<?> type = Primitives.wrap(cse.getType().getJavaType());
VariableReferenceExpression cseVariable = entry.getValue();
CommonSubExpressionFields cseFields = commonSubExpressionFieldsMap.get(cseVariable);
MethodDefinition method = classDefinition.declareMethod(
a(PRIVATE),
"get" + cseVariable.getName(),
type(cseFields.resultType),
ImmutableList.<Parameter>builder()
.add(properties)
.add(page)
.add(position)
.build());
method.comment("cse: %s", cse);
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
declareBlockVariables(ImmutableList.of(cse), page, scope, body);
scope.declareVariable("wasNull", body, constantFalse());
RowExpressionCompiler cseCompiler = new RowExpressionCompiler(
classDefinition,
callSiteBinder,
cachedInstanceBinder,
new FieldAndVariableReferenceCompiler(callSiteBinder, cseMap, thisVariable),
metadata,
sqlFunctionProperties,
compiledLambdaMap);
IfStatement ifStatement = new IfStatement()
.condition(thisVariable.getField(cseFields.evaluatedField))
.ifFalse(new BytecodeBlock()
.append(thisVariable)
.append(cseCompiler.compile(cse, scope, Optional.empty()))
.append(boxPrimitiveIfNecessary(scope, type))
.putField(cseFields.resultField)
.append(thisVariable.setField(cseFields.evaluatedField, constantBoolean(true))));
body.append(ifStatement)
.append(thisVariable)
.getField(cseFields.resultField)
.retObject();
methods.add(method);
cseMap.put(cseVariable, cseFields);
}
}
}
return methods.build();
}
private MethodDefinition generateEvaluateMethod(
SqlFunctionProperties sqlFunctionProperties,
ClassDefinition classDefinition,
CallSiteBinder callSiteBinder,
CachedInstanceBinder cachedInstanceBinder,
Map<LambdaDefinitionExpression, CompiledLambda> compiledLambdaMap,
List<RowExpression> projections,
FieldDefinition blockBuilders,
Map<VariableReferenceExpression, CommonSubExpressionFields> cseFields)
{
Parameter properties = arg("properties", SqlFunctionProperties.class);
Parameter page = arg("page", Page.class);
Parameter position = arg("position", int.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"evaluate",
type(void.class),
ImmutableList.<Parameter>builder()
.add(properties)
.add(page)
.add(position)
.build());
method.comment("Projections: %s", Joiner.on(", ").join(projections));
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
declareBlockVariables(projections, page, scope, body);
Variable wasNull = scope.declareVariable("wasNull", body, constantFalse());
cseFields.values().forEach(fields -> body.append(thisVariable.setField(fields.evaluatedField, constantBoolean(false))));
RowExpressionCompiler compiler = new RowExpressionCompiler(
classDefinition,
callSiteBinder,
cachedInstanceBinder,
new FieldAndVariableReferenceCompiler(callSiteBinder, cseFields, thisVariable),
metadata,
sqlFunctionProperties,
compiledLambdaMap);
Variable outputBlockVariable = scope.createTempVariable(BlockBuilder.class);
for (int i = 0; i < projections.size(); i++) {
body.append(outputBlockVariable.set(thisVariable.getField(blockBuilders).invoke("get", Object.class, constantInt(i))))
.append(compiler.compile(projections.get(i), scope, Optional.of(outputBlockVariable)))
.append(constantBoolean(false))
.putVariable(wasNull);
}
body.ret();
return method;
}
public Supplier<PageFilter> compileFilter(SqlFunctionProperties sqlFunctionProperties, RowExpression filter, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
{
if (filterCache == null) {
return compileFilterInternal(sqlFunctionProperties, filter, isOptimizeCommonSubExpression, classNameSuffix);
}
return filterCache.getUnchecked(new CacheKey(sqlFunctionProperties, ImmutableList.of(filter), isOptimizeCommonSubExpression));
}
private Supplier<PageFilter> compileFilterInternal(SqlFunctionProperties sqlFunctionProperties, RowExpression filter, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
{
requireNonNull(filter, "filter is null");
PageFieldsToInputParametersRewriter.Result result = rewritePageFieldsToInputParameters(filter);
CallSiteBinder callSiteBinder = new CallSiteBinder();
ClassDefinition classDefinition = defineFilterClass(sqlFunctionProperties, result.getRewrittenExpression(), result.getInputChannels(), callSiteBinder, isOptimizeCommonSubExpression, classNameSuffix);
Class<? extends PageFilter> functionClass;
try {
functionClass = defineClass(classDefinition, PageFilter.class, callSiteBinder.getBindings(), getClass().getClassLoader());
}
catch (PrestoException prestoException) {
throw prestoException;
}
catch (Exception e) {
throw new PrestoException(COMPILER_ERROR, filter.toString(), e.getCause());
}
return () -> {
try {
return functionClass.getConstructor().newInstance();
}
catch (ReflectiveOperationException e) {
throw new PrestoException(COMPILER_ERROR, e);
}
};
}
private static ParameterizedType generateFilterClassName(Optional<String> classNameSuffix)
{
return makeClassName(PageFilter.class.getSimpleName(), classNameSuffix);
}
private ClassDefinition defineFilterClass(SqlFunctionProperties sqlFunctionProperties, RowExpression filter, InputChannels inputChannels, CallSiteBinder callSiteBinder, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
{
ClassDefinition classDefinition = new ClassDefinition(
a(PUBLIC, FINAL),
generateFilterClassName(classNameSuffix),
type(Object.class),
type(PageFilter.class));
CachedInstanceBinder cachedInstanceBinder = new CachedInstanceBinder(classDefinition, callSiteBinder);
Map<LambdaDefinitionExpression, CompiledLambda> compiledLambdaMap = generateMethodsForLambda(classDefinition, callSiteBinder, cachedInstanceBinder, filter, metadata, sqlFunctionProperties);
// cse
Map<VariableReferenceExpression, CommonSubExpressionFields> cseFields = ImmutableMap.of();
if (isOptimizeCommonSubExpression) {
Map<Integer, Map<RowExpression, VariableReferenceExpression>> commonSubExpressionsByLevel = collectCSEByLevel(filter);
if (!commonSubExpressionsByLevel.isEmpty()) {
cseFields = declareCommonSubExpressionFields(classDefinition, commonSubExpressionsByLevel);
generateCommonSubExpressionMethods(sqlFunctionProperties, classDefinition, callSiteBinder, cachedInstanceBinder, compiledLambdaMap, commonSubExpressionsByLevel, cseFields);
Map<RowExpression, VariableReferenceExpression> commonSubExpressions = commonSubExpressionsByLevel.values().stream()
.flatMap(m -> m.entrySet().stream())
.collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
filter = rewriteExpressionWithCSE(filter, commonSubExpressions);
if (log.isDebugEnabled()) {
log.debug("Extracted %d common sub-expressions", commonSubExpressions.size());
commonSubExpressions.entrySet().forEach(entry -> log.debug("\t%s = %s", entry.getValue(), entry.getKey()));
log.debug("Rewrote filter: %s", filter);
}
}
}
generateFilterMethod(sqlFunctionProperties, classDefinition, callSiteBinder, cachedInstanceBinder, compiledLambdaMap, filter, cseFields);
FieldDefinition selectedPositions = classDefinition.declareField(a(PRIVATE), "selectedPositions", boolean[].class);
generatePageFilterMethod(classDefinition, selectedPositions);
// isDeterministic
classDefinition.declareMethod(a(PUBLIC), "isDeterministic", type(boolean.class))
.getBody()
.append(constantBoolean(determinismEvaluator.isDeterministic(filter)))
.retBoolean();
// getInputChannels
classDefinition.declareMethod(a(PUBLIC), "getInputChannels", type(InputChannels.class))
.getBody()
.append(invoke(callSiteBinder.bind(inputChannels, InputChannels.class), "getInputChannels"))
.retObject();
// toString
String toStringResult = toStringHelper(classDefinition.getType()
.getJavaClassName())
.add("filter", filter)
.toString();
classDefinition.declareMethod(a(PUBLIC), "toString", type(String.class))
.getBody()
// bind constant via invokedynamic to avoid constant pool issues due to large strings
.append(invoke(callSiteBinder.bind(toStringResult, String.class), "toString"))
.retObject();
// constructor
MethodDefinition constructorDefinition = classDefinition.declareConstructor(a(PUBLIC));
BytecodeBlock body = constructorDefinition.getBody();
Variable thisVariable = constructorDefinition.getThis();
body.comment("super();")
.append(thisVariable)
.invokeConstructor(Object.class)
.append(thisVariable.setField(selectedPositions, newArray(type(boolean[].class), 0)));
initializeCommonSubExpressionFields(cseFields.values(), thisVariable, body);
cachedInstanceBinder.generateInitializations(thisVariable, body);
body.ret();
return classDefinition;
}
private static MethodDefinition generatePageFilterMethod(ClassDefinition classDefinition, FieldDefinition selectedPositionsField)
{
Parameter properties = arg("properties", SqlFunctionProperties.class);
Parameter page = arg("page", Page.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"filter",
type(SelectedPositions.class),
ImmutableList.<Parameter>builder()
.add(properties)
.add(page)
.build());
Scope scope = method.getScope();
Variable thisVariable = method.getThis();
BytecodeBlock body = method.getBody();
Variable positionCount = scope.declareVariable("positionCount", body, page.invoke("getPositionCount", int.class));
body.append(new IfStatement("grow selectedPositions if necessary")
.condition(lessThan(thisVariable.getField(selectedPositionsField).length(), positionCount))
.ifTrue(thisVariable.setField(selectedPositionsField, newArray(type(boolean[].class), positionCount))));
Variable selectedPositions = scope.declareVariable("selectedPositions", body, thisVariable.getField(selectedPositionsField));
Variable position = scope.declareVariable(int.class, "position");
body.append(new ForLoop()
.initialize(position.set(constantInt(0)))
.condition(lessThan(position, positionCount))
.update(position.increment())
.body(selectedPositions.setElement(position, thisVariable.invoke("filter", boolean.class, properties, page, position))));
body.append(invokeStatic(
PageFilter.class,
"positionsArrayToSelectedPositions",
SelectedPositions.class,
selectedPositions,
positionCount)
.ret());
return method;
}
private MethodDefinition generateFilterMethod(
SqlFunctionProperties sqlFunctionProperties,
ClassDefinition classDefinition,
CallSiteBinder callSiteBinder,
CachedInstanceBinder cachedInstanceBinder,
Map<LambdaDefinitionExpression, CompiledLambda> compiledLambdaMap,
RowExpression filter,
Map<VariableReferenceExpression, CommonSubExpressionFields> cseFields)
{
Parameter properties = arg("properties", SqlFunctionProperties.class);
Parameter page = arg("page", Page.class);
Parameter position = arg("position", int.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"filter",
type(boolean.class),
ImmutableList.<Parameter>builder()
.add(properties)
.add(page)
.add(position)
.build());
method.comment("Filter: %s", filter.toString());
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable thisVariable = scope.getThis();
declareBlockVariables(ImmutableList.of(filter), page, scope, body);
cseFields.values().forEach(fields -> body.append(thisVariable.setField(fields.evaluatedField, constantBoolean(false))));
Variable wasNullVariable = scope.declareVariable("wasNull", body, constantFalse());
RowExpressionCompiler compiler = new RowExpressionCompiler(
classDefinition,
callSiteBinder,
cachedInstanceBinder,
new FieldAndVariableReferenceCompiler(callSiteBinder, cseFields, thisVariable),
metadata,
sqlFunctionProperties,
compiledLambdaMap);
Variable result = scope.declareVariable(boolean.class, "result");
body.append(compiler.compile(filter, scope, Optional.empty()))
// store result so we can check for null
.putVariable(result)
.append(and(not(wasNullVariable), result).ret());
return method;
}
private static void initializeCommonSubExpressionFields(Collection<CommonSubExpressionFields> cseFields, Variable thisVariable, BytecodeBlock body)
{
cseFields.forEach(fields -> {
body.append(thisVariable.setField(fields.evaluatedField, constantBoolean(false)));
body.append(thisVariable.setField(fields.resultField, constantNull(fields.resultType)));
});
}
private static void declareBlockVariables(List<RowExpression> expressions, Parameter page, Scope scope, BytecodeBlock body)
{
for (int channel : getInputChannels(expressions)) {
scope.declareVariable("block_" + channel, body, page.invoke("getBlock", Block.class, constantInt(channel)));
}
}
private static Map<VariableReferenceExpression, CommonSubExpressionFields> declareCommonSubExpressionFields(ClassDefinition classDefinition, Map<Integer, Map<RowExpression, VariableReferenceExpression>> commonSubExpressionsByLevel)
{
ImmutableMap.Builder<VariableReferenceExpression, CommonSubExpressionFields> fields = ImmutableMap.builder();
commonSubExpressionsByLevel.values().stream().map(Map::values).flatMap(Collection::stream).forEach(variable -> {
Class<?> type = Primitives.wrap(variable.getType().getJavaType());
fields.put(variable, new CommonSubExpressionFields(
classDefinition.declareField(a(PRIVATE), variable.getName() + "Evaluated", boolean.class),
classDefinition.declareField(a(PRIVATE), variable.getName() + "Result", type),
type,
"get" + variable.getName()));
});
return fields.build();
}
private static List<Integer> getInputChannels(Iterable<RowExpression> expressions)
{
TreeSet<Integer> channels = new TreeSet<>();
for (RowExpression expression : subExpressions(expressions)) {
if (expression instanceof InputReferenceExpression) {
channels.add(((InputReferenceExpression) expression).getField());
}
}
return ImmutableList.copyOf(channels);
}
private static int[] toIntArray(List<Integer> list)
{
int[] array = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
return array;
}
private static class CommonSubExpressionFields
{
private final FieldDefinition evaluatedField;
private final FieldDefinition resultField;
private final Class<?> resultType;
private final String methodName;
public CommonSubExpressionFields(FieldDefinition evaluatedField, FieldDefinition resultField, Class<?> resultType, String methodName)
{
this.evaluatedField = evaluatedField;
this.resultField = resultField;
this.resultType = resultType;
this.methodName = methodName;
}
}
private static class FieldAndVariableReferenceCompiler
implements RowExpressionVisitor<BytecodeNode, Scope>
{
private final InputReferenceCompiler inputReferenceCompiler;
private final Map<VariableReferenceExpression, CommonSubExpressionFields> variableMap;
private final Variable thisVariable;
public FieldAndVariableReferenceCompiler(CallSiteBinder callSiteBinder, Map<VariableReferenceExpression, CommonSubExpressionFields> variableMap, Variable thisVariable)
{
this.inputReferenceCompiler = new InputReferenceCompiler(
(scope, field) -> scope.getVariable("block_" + field),
(scope, field) -> scope.getVariable("position"),
callSiteBinder);
this.variableMap = ImmutableMap.copyOf(variableMap);
this.thisVariable = thisVariable;
}
@Override
public BytecodeNode visitCall(CallExpression call, Scope context)
{
throw new UnsupportedOperationException();
}
@Override
public BytecodeNode visitInputReference(InputReferenceExpression reference, Scope context)
{
return inputReferenceCompiler.visitInputReference(reference, context);
}
@Override
public BytecodeNode visitConstant(ConstantExpression literal, Scope context)
{
throw new UnsupportedOperationException();
}
@Override
public BytecodeNode visitLambda(LambdaDefinitionExpression lambda, Scope context)
{
throw new UnsupportedOperationException();
}
@Override
public BytecodeNode visitVariableReference(VariableReferenceExpression reference, Scope context)
{
CommonSubExpressionFields fields = variableMap.get(reference);
return new BytecodeBlock()
.append(thisVariable.invoke(fields.methodName, fields.resultType, context.getVariable("properties"), context.getVariable("page"), context.getVariable("position")))
.append(unboxPrimitiveIfNecessary(context, Primitives.wrap(reference.getType().getJavaType())));
}
@Override
public BytecodeNode visitSpecialForm(SpecialFormExpression specialForm, Scope context)
{
throw new UnsupportedOperationException();
}
}
private static final class CacheKey
{
private final SqlFunctionProperties sqlFunctionProperties;
private final List<RowExpression> rowExpressions;
private final boolean isOptimizeCommonSubExpression;
private CacheKey(SqlFunctionProperties sqlFunctionProperties, List<RowExpression> rowExpressions, boolean isOptimizeCommonSubExpression)
{
requireNonNull(rowExpressions, "rowExpressions is null");
checkArgument(rowExpressions.size() >= 1, "Expect at least one RowExpression");
this.sqlFunctionProperties = requireNonNull(sqlFunctionProperties, "sqlFunctionProperties is null");
this.rowExpressions = ImmutableList.copyOf(rowExpressions);
this.isOptimizeCommonSubExpression = isOptimizeCommonSubExpression;
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (!(o instanceof CacheKey)) {
return false;
}
CacheKey that = (CacheKey) o;
return Objects.equals(sqlFunctionProperties, that.sqlFunctionProperties) &&
Objects.equals(rowExpressions, that.rowExpressions) &&
isOptimizeCommonSubExpression == that.isOptimizeCommonSubExpression;
}
@Override
public int hashCode()
{
return Objects.hash(sqlFunctionProperties, rowExpressions, isOptimizeCommonSubExpression);
}
}
}
| presto-main/src/main/java/com/facebook/presto/sql/gen/PageFunctionCompiler.java | /*
* 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.facebook.presto.sql.gen;
import com.facebook.airlift.log.Logger;
import com.facebook.presto.bytecode.BytecodeBlock;
import com.facebook.presto.bytecode.BytecodeNode;
import com.facebook.presto.bytecode.ClassDefinition;
import com.facebook.presto.bytecode.FieldDefinition;
import com.facebook.presto.bytecode.MethodDefinition;
import com.facebook.presto.bytecode.Parameter;
import com.facebook.presto.bytecode.ParameterizedType;
import com.facebook.presto.bytecode.Scope;
import com.facebook.presto.bytecode.Variable;
import com.facebook.presto.bytecode.control.ForLoop;
import com.facebook.presto.bytecode.control.IfStatement;
import com.facebook.presto.common.Page;
import com.facebook.presto.common.block.Block;
import com.facebook.presto.common.block.BlockBuilder;
import com.facebook.presto.common.function.SqlFunctionProperties;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.operator.Work;
import com.facebook.presto.operator.project.ConstantPageProjection;
import com.facebook.presto.operator.project.GeneratedPageProjection;
import com.facebook.presto.operator.project.InputChannels;
import com.facebook.presto.operator.project.InputPageProjection;
import com.facebook.presto.operator.project.PageFieldsToInputParametersRewriter;
import com.facebook.presto.operator.project.PageFilter;
import com.facebook.presto.operator.project.PageProjection;
import com.facebook.presto.operator.project.PageProjectionWithOutputs;
import com.facebook.presto.operator.project.SelectedPositions;
import com.facebook.presto.spi.PrestoException;
import com.facebook.presto.spi.relation.CallExpression;
import com.facebook.presto.spi.relation.ConstantExpression;
import com.facebook.presto.spi.relation.DeterminismEvaluator;
import com.facebook.presto.spi.relation.InputReferenceExpression;
import com.facebook.presto.spi.relation.LambdaDefinitionExpression;
import com.facebook.presto.spi.relation.RowExpression;
import com.facebook.presto.spi.relation.RowExpressionVisitor;
import com.facebook.presto.spi.relation.SpecialFormExpression;
import com.facebook.presto.spi.relation.VariableReferenceExpression;
import com.facebook.presto.sql.gen.LambdaBytecodeGenerator.CompiledLambda;
import com.facebook.presto.sql.planner.CompilerConfig;
import com.facebook.presto.sql.relational.RowExpressionDeterminismEvaluator;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.Primitives;
import org.weakref.jmx.Managed;
import org.weakref.jmx.Nested;
import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.TreeSet;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import static com.facebook.presto.bytecode.Access.FINAL;
import static com.facebook.presto.bytecode.Access.PRIVATE;
import static com.facebook.presto.bytecode.Access.PUBLIC;
import static com.facebook.presto.bytecode.Access.a;
import static com.facebook.presto.bytecode.Parameter.arg;
import static com.facebook.presto.bytecode.ParameterizedType.type;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.add;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.and;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantBoolean;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantFalse;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantInt;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.constantNull;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.invokeStatic;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.lessThan;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.newArray;
import static com.facebook.presto.bytecode.expression.BytecodeExpressions.not;
import static com.facebook.presto.operator.project.PageFieldsToInputParametersRewriter.rewritePageFieldsToInputParameters;
import static com.facebook.presto.spi.StandardErrorCode.COMPILER_ERROR;
import static com.facebook.presto.sql.gen.BytecodeUtils.boxPrimitiveIfNecessary;
import static com.facebook.presto.sql.gen.BytecodeUtils.invoke;
import static com.facebook.presto.sql.gen.BytecodeUtils.unboxPrimitiveIfNecessary;
import static com.facebook.presto.sql.gen.CommonSubExpressionRewriter.collectCSEByLevel;
import static com.facebook.presto.sql.gen.CommonSubExpressionRewriter.getExpressionsPartitionedByCSE;
import static com.facebook.presto.sql.gen.CommonSubExpressionRewriter.rewriteExpressionWithCSE;
import static com.facebook.presto.sql.gen.LambdaBytecodeGenerator.generateMethodsForLambda;
import static com.facebook.presto.sql.relational.Expressions.subExpressions;
import static com.facebook.presto.util.CompilerUtils.defineClass;
import static com.facebook.presto.util.CompilerUtils.makeClassName;
import static com.facebook.presto.util.Reflection.constructorMethodHandle;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Verify.verify;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableMap.toImmutableMap;
import static java.util.Objects.requireNonNull;
public class PageFunctionCompiler
{
private static Logger log = Logger.get(PageFunctionCompiler.class);
private final Metadata metadata;
private final DeterminismEvaluator determinismEvaluator;
private final LoadingCache<CacheKey, Supplier<PageProjection>> projectionCache;
private final LoadingCache<CacheKey, Supplier<PageFilter>> filterCache;
private final CacheStatsMBean projectionCacheStats;
private final CacheStatsMBean filterCacheStats;
@Inject
public PageFunctionCompiler(Metadata metadata, CompilerConfig config)
{
this(metadata, requireNonNull(config, "config is null").getExpressionCacheSize());
}
public PageFunctionCompiler(Metadata metadata, int expressionCacheSize)
{
this.metadata = requireNonNull(metadata, "metadata is null");
this.determinismEvaluator = new RowExpressionDeterminismEvaluator(metadata.getFunctionManager());
if (expressionCacheSize > 0) {
projectionCache = CacheBuilder.newBuilder()
.recordStats()
.maximumSize(expressionCacheSize)
.build(CacheLoader.from(cacheKey -> compileProjectionInternal(cacheKey.sqlFunctionProperties, cacheKey.rowExpressions, cacheKey.isOptimizeCommonSubExpression, Optional.empty())));
projectionCacheStats = new CacheStatsMBean(projectionCache);
}
else {
projectionCache = null;
projectionCacheStats = null;
}
if (expressionCacheSize > 0) {
filterCache = CacheBuilder.newBuilder()
.recordStats()
.maximumSize(expressionCacheSize)
.build(CacheLoader.from(cacheKey -> compileFilterInternal(cacheKey.sqlFunctionProperties, cacheKey.rowExpressions.get(0), cacheKey.isOptimizeCommonSubExpression, Optional.empty())));
filterCacheStats = new CacheStatsMBean(filterCache);
}
else {
filterCache = null;
filterCacheStats = null;
}
}
@Nullable
@Managed
@Nested
public CacheStatsMBean getProjectionCache()
{
return projectionCacheStats;
}
@Nullable
@Managed
@Nested
public CacheStatsMBean getFilterCache()
{
return filterCacheStats;
}
public List<Supplier<PageProjectionWithOutputs>> compileProjections(SqlFunctionProperties sqlFunctionProperties, List<? extends RowExpression> projections, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
{
if (isOptimizeCommonSubExpression) {
ImmutableList.Builder<Supplier<PageProjectionWithOutputs>> pageProjections = ImmutableList.builder();
ImmutableMap.Builder<RowExpression, Integer> expressionsWithPositionBuilder = ImmutableMap.builder();
for (int i = 0; i < projections.size(); i++) {
RowExpression projection = projections.get(i);
if (projection instanceof ConstantExpression || projection instanceof InputReferenceExpression) {
pageProjections.add(toPageProjectionWithOutputs(compileProjection(sqlFunctionProperties, projection, classNameSuffix), new int[] {i}));
}
else {
expressionsWithPositionBuilder.put(projections.get(i), i);
}
}
Map<RowExpression, Integer> expressionsWithPosition = expressionsWithPositionBuilder.build();
Map<List<RowExpression>, Boolean> projectionsPartitionedByCSE = getExpressionsPartitionedByCSE(expressionsWithPosition.keySet());
for (Map.Entry<List<RowExpression>, Boolean> entry : projectionsPartitionedByCSE.entrySet()) {
if (entry.getValue()) {
pageProjections.add(toPageProjectionWithOutputs(compileProjectionCached(sqlFunctionProperties, entry.getKey(), true, classNameSuffix), toIntArray(entry.getKey().stream().map(expressionsWithPosition::get).collect(toImmutableList()))));
}
else {
verify(entry.getKey().size() == 1, "Expect non-cse expression list to only have one element");
RowExpression projection = entry.getKey().get(0);
pageProjections.add(toPageProjectionWithOutputs(compileProjection(sqlFunctionProperties, projection, classNameSuffix), new int[] {expressionsWithPosition.get(projection)}));
}
}
return pageProjections.build();
}
return IntStream.range(0, projections.size())
.mapToObj(outputChannel -> toPageProjectionWithOutputs(compileProjection(sqlFunctionProperties, projections.get(outputChannel), classNameSuffix), new int[] {outputChannel}))
.collect(toImmutableList());
}
@VisibleForTesting
public Supplier<PageProjection> compileProjection(SqlFunctionProperties sqlFunctionProperties, RowExpression projection, Optional<String> classNameSuffix)
{
if (projection instanceof InputReferenceExpression) {
InputReferenceExpression input = (InputReferenceExpression) projection;
InputPageProjection projectionFunction = new InputPageProjection(input.getField());
return () -> projectionFunction;
}
if (projection instanceof ConstantExpression) {
ConstantExpression constant = (ConstantExpression) projection;
ConstantPageProjection projectionFunction = new ConstantPageProjection(constant.getValue(), constant.getType());
return () -> projectionFunction;
}
return compileProjectionCached(sqlFunctionProperties, ImmutableList.of(projection), false, classNameSuffix);
}
private Supplier<PageProjection> compileProjectionCached(SqlFunctionProperties sqlFunctionProperties, List<RowExpression> projections, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
{
if (projectionCache == null) {
return compileProjectionInternal(sqlFunctionProperties, projections, isOptimizeCommonSubExpression, classNameSuffix);
}
return projectionCache.getUnchecked(new CacheKey(sqlFunctionProperties, projections, isOptimizeCommonSubExpression));
}
private Supplier<PageProjectionWithOutputs> toPageProjectionWithOutputs(Supplier<PageProjection> pageProjection, int[] outputChannels)
{
return () -> new PageProjectionWithOutputs(pageProjection.get(), outputChannels);
}
private Supplier<PageProjection> compileProjectionInternal(SqlFunctionProperties sqlFunctionProperties, List<RowExpression> projections, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
{
requireNonNull(projections, "projections is null");
checkArgument(!projections.isEmpty() && projections.stream().allMatch(projection -> projection instanceof CallExpression || projection instanceof SpecialFormExpression));
PageFieldsToInputParametersRewriter.Result result = rewritePageFieldsToInputParameters(projections);
List<RowExpression> rewrittenExpression = result.getRewrittenExpressions();
CallSiteBinder callSiteBinder = new CallSiteBinder();
// generate Work
ClassDefinition pageProjectionWorkDefinition = definePageProjectWorkClass(sqlFunctionProperties, rewrittenExpression, callSiteBinder, isOptimizeCommonSubExpression, classNameSuffix);
Class<? extends Work> pageProjectionWorkClass;
try {
pageProjectionWorkClass = defineClass(pageProjectionWorkDefinition, Work.class, callSiteBinder.getBindings(), getClass().getClassLoader());
}
catch (PrestoException prestoException) {
throw prestoException;
}
catch (Exception e) {
throw new PrestoException(COMPILER_ERROR, e);
}
return () -> new GeneratedPageProjection(
rewrittenExpression,
rewrittenExpression.stream().allMatch(determinismEvaluator::isDeterministic),
result.getInputChannels(),
constructorMethodHandle(pageProjectionWorkClass, List.class, SqlFunctionProperties.class, Page.class, SelectedPositions.class));
}
private static ParameterizedType generateProjectionWorkClassName(Optional<String> classNameSuffix)
{
return makeClassName("PageProjectionWork", classNameSuffix);
}
private ClassDefinition definePageProjectWorkClass(SqlFunctionProperties sqlFunctionProperties, List<RowExpression> projections, CallSiteBinder callSiteBinder, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
{
ClassDefinition classDefinition = new ClassDefinition(
a(PUBLIC, FINAL),
generateProjectionWorkClassName(classNameSuffix),
type(Object.class),
type(Work.class));
FieldDefinition blockBuilderFields = classDefinition.declareField(a(PRIVATE), "blockBuilders", type(List.class, BlockBuilder.class));
FieldDefinition propertiesField = classDefinition.declareField(a(PRIVATE), "properties", SqlFunctionProperties.class);
FieldDefinition pageField = classDefinition.declareField(a(PRIVATE), "page", Page.class);
FieldDefinition selectedPositionsField = classDefinition.declareField(a(PRIVATE), "selectedPositions", SelectedPositions.class);
FieldDefinition nextIndexOrPositionField = classDefinition.declareField(a(PRIVATE), "nextIndexOrPosition", int.class);
FieldDefinition resultField = classDefinition.declareField(a(PRIVATE), "result", List.class);
CachedInstanceBinder cachedInstanceBinder = new CachedInstanceBinder(classDefinition, callSiteBinder);
// process
generateProcessMethod(classDefinition, blockBuilderFields, projections.size(), propertiesField, pageField, selectedPositionsField, nextIndexOrPositionField, resultField);
// getResult
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "getResult", type(Object.class), ImmutableList.of());
method.getBody().append(method.getThis().getField(resultField)).ret(Object.class);
Map<LambdaDefinitionExpression, CompiledLambda> compiledLambdaMap = generateMethodsForLambda(classDefinition, callSiteBinder, cachedInstanceBinder, projections, metadata, sqlFunctionProperties, "");
// cse
Map<VariableReferenceExpression, CommonSubExpressionFields> cseFields = ImmutableMap.of();
if (isOptimizeCommonSubExpression) {
Map<Integer, Map<RowExpression, VariableReferenceExpression>> commonSubExpressionsByLevel = collectCSEByLevel(projections);
if (!commonSubExpressionsByLevel.isEmpty()) {
cseFields = declareCommonSubExpressionFields(classDefinition, commonSubExpressionsByLevel);
generateCommonSubExpressionMethods(sqlFunctionProperties, classDefinition, callSiteBinder, cachedInstanceBinder, compiledLambdaMap, commonSubExpressionsByLevel, cseFields);
Map<RowExpression, VariableReferenceExpression> commonSubExpressions = commonSubExpressionsByLevel.values().stream()
.flatMap(m -> m.entrySet().stream())
.collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
projections = projections.stream().map(projection -> rewriteExpressionWithCSE(projection, commonSubExpressions)).collect(toImmutableList());
if (log.isDebugEnabled()) {
log.debug("Extracted %d common sub-expressions", commonSubExpressions.size());
commonSubExpressions.entrySet().forEach(entry -> log.debug("\t%s = %s", entry.getValue(), entry.getKey()));
log.debug("Rewrote %d projections: %s", projections.size(), Joiner.on(", ").join(projections));
}
}
}
// evaluate
generateEvaluateMethod(sqlFunctionProperties, classDefinition, callSiteBinder, cachedInstanceBinder, compiledLambdaMap, projections, blockBuilderFields, cseFields);
// constructor
Parameter blockBuilders = arg("blockBuilders", type(List.class, BlockBuilder.class));
Parameter properties = arg("properties", SqlFunctionProperties.class);
Parameter page = arg("page", Page.class);
Parameter selectedPositions = arg("selectedPositions", SelectedPositions.class);
MethodDefinition constructorDefinition = classDefinition.declareConstructor(a(PUBLIC), blockBuilders, properties, page, selectedPositions);
BytecodeBlock body = constructorDefinition.getBody();
Variable thisVariable = constructorDefinition.getThis();
body.comment("super();")
.append(thisVariable)
.invokeConstructor(Object.class)
.append(thisVariable.setField(blockBuilderFields, invokeStatic(ImmutableList.class, "copyOf", ImmutableList.class, blockBuilders.cast(Collection.class))))
.append(thisVariable.setField(propertiesField, properties))
.append(thisVariable.setField(pageField, page))
.append(thisVariable.setField(selectedPositionsField, selectedPositions))
.append(thisVariable.setField(nextIndexOrPositionField, selectedPositions.invoke("getOffset", int.class)))
.append(thisVariable.setField(resultField, constantNull(Block.class)));
initializeCommonSubExpressionFields(cseFields.values(), thisVariable, body);
cachedInstanceBinder.generateInitializations(thisVariable, body);
body.ret();
return classDefinition;
}
private static MethodDefinition generateProcessMethod(
ClassDefinition classDefinition,
FieldDefinition blockBuilders,
int blockBuilderSize,
FieldDefinition properties,
FieldDefinition page,
FieldDefinition selectedPositions,
FieldDefinition nextIndexOrPosition,
FieldDefinition result)
{
MethodDefinition method = classDefinition.declareMethod(a(PUBLIC), "process", type(boolean.class), ImmutableList.of());
Scope scope = method.getScope();
Variable thisVariable = method.getThis();
BytecodeBlock body = method.getBody();
Variable from = scope.declareVariable("from", body, thisVariable.getField(nextIndexOrPosition));
Variable to = scope.declareVariable("to", body, add(thisVariable.getField(selectedPositions).invoke("getOffset", int.class), thisVariable.getField(selectedPositions).invoke("size", int.class)));
Variable positions = scope.declareVariable(int[].class, "positions");
Variable index = scope.declareVariable(int.class, "index");
IfStatement ifStatement = new IfStatement()
.condition(thisVariable.getField(selectedPositions).invoke("isList", boolean.class));
body.append(ifStatement);
ifStatement.ifTrue(new BytecodeBlock()
.append(positions.set(thisVariable.getField(selectedPositions).invoke("getPositions", int[].class)))
.append(new ForLoop("positions loop")
.initialize(index.set(from))
.condition(lessThan(index, to))
.update(index.increment())
.body(new BytecodeBlock()
.append(thisVariable.invoke("evaluate", void.class, thisVariable.getField(properties), thisVariable.getField(page), positions.getElement(index))))));
ifStatement.ifFalse(new ForLoop("range based loop")
.initialize(index.set(from))
.condition(lessThan(index, to))
.update(index.increment())
.body(new BytecodeBlock()
.append(thisVariable.invoke("evaluate", void.class, thisVariable.getField(properties), thisVariable.getField(page), index))));
Variable blocksBuilder = scope.declareVariable("blocksBuilder", body, invokeStatic(ImmutableList.class, "builder", ImmutableList.Builder.class));
Variable iterator = scope.createTempVariable(int.class);
ForLoop forLoop = new ForLoop("for (iterator = 0; iterator < this.blockBuilders.size(); iterator ++) blockBuildersBuilder.add(this.blockBuilders.get(iterator).builder();")
.initialize(iterator.set(constantInt(0)))
.condition(lessThan(iterator, constantInt(blockBuilderSize)))
.update(iterator.increment())
.body(new BytecodeBlock()
.append(blocksBuilder.invoke(
"add",
ImmutableList.Builder.class,
thisVariable.getField(blockBuilders).invoke("get", Object.class, iterator).cast(BlockBuilder.class).invoke("build", Block.class).cast(Object.class)).pop()));
body.append(forLoop)
.comment("result = blockBuildersBuilder.build(); return true")
.append(thisVariable.setField(result, blocksBuilder.invoke("build", ImmutableList.class)))
.push(true)
.retBoolean();
return method;
}
private List<MethodDefinition> generateCommonSubExpressionMethods(
SqlFunctionProperties sqlFunctionProperties,
ClassDefinition classDefinition,
CallSiteBinder callSiteBinder,
CachedInstanceBinder cachedInstanceBinder,
Map<LambdaDefinitionExpression, CompiledLambda> compiledLambdaMap,
Map<Integer, Map<RowExpression, VariableReferenceExpression>> commonSubExpressionsByLevel,
Map<VariableReferenceExpression, CommonSubExpressionFields> commonSubExpressionFieldsMap)
{
ImmutableList.Builder<MethodDefinition> methods = ImmutableList.builder();
Parameter properties = arg("properties", SqlFunctionProperties.class);
Parameter page = arg("page", Page.class);
Parameter position = arg("position", int.class);
Map<VariableReferenceExpression, CommonSubExpressionFields> cseMap = new HashMap<>();
int startLevel = commonSubExpressionsByLevel.keySet().stream().reduce(Math::min).get();
int maxLevel = commonSubExpressionsByLevel.keySet().stream().reduce(Math::max).get();
for (int i = startLevel; i <= maxLevel; i++) {
if (commonSubExpressionsByLevel.containsKey(i)) {
for (Map.Entry<RowExpression, VariableReferenceExpression> entry : commonSubExpressionsByLevel.get(i).entrySet()) {
RowExpression cse = entry.getKey();
Class<?> type = Primitives.wrap(cse.getType().getJavaType());
VariableReferenceExpression cseVariable = entry.getValue();
CommonSubExpressionFields cseFields = commonSubExpressionFieldsMap.get(cseVariable);
MethodDefinition method = classDefinition.declareMethod(
a(PRIVATE),
"get" + cseVariable.getName(),
type(void.class),
ImmutableList.<Parameter>builder()
.add(properties)
.add(page)
.add(position)
.build());
method.comment("cse: %s", cse);
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
declareBlockVariables(ImmutableList.of(cse), page, scope, body);
scope.declareVariable("wasNull", body, constantFalse());
RowExpressionCompiler cseCompiler = new RowExpressionCompiler(
classDefinition,
callSiteBinder,
cachedInstanceBinder,
new FieldAndVariableReferenceCompiler(callSiteBinder, cseMap, thisVariable),
metadata,
sqlFunctionProperties,
compiledLambdaMap);
body.append(thisVariable)
.append(cseCompiler.compile(cse, scope, Optional.empty()))
.append(boxPrimitiveIfNecessary(scope, type))
.putField(cseFields.resultField)
.append(thisVariable.setField(cseFields.evaluatedField, constantBoolean(true)))
.ret();
methods.add(method);
cseMap.put(cseVariable, cseFields);
}
}
}
return methods.build();
}
private MethodDefinition generateEvaluateMethod(
SqlFunctionProperties sqlFunctionProperties,
ClassDefinition classDefinition,
CallSiteBinder callSiteBinder,
CachedInstanceBinder cachedInstanceBinder,
Map<LambdaDefinitionExpression, CompiledLambda> compiledLambdaMap,
List<RowExpression> projections,
FieldDefinition blockBuilders,
Map<VariableReferenceExpression, CommonSubExpressionFields> cseFields)
{
Parameter properties = arg("properties", SqlFunctionProperties.class);
Parameter page = arg("page", Page.class);
Parameter position = arg("position", int.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"evaluate",
type(void.class),
ImmutableList.<Parameter>builder()
.add(properties)
.add(page)
.add(position)
.build());
method.comment("Projections: %s", Joiner.on(", ").join(projections));
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable thisVariable = method.getThis();
declareBlockVariables(projections, page, scope, body);
Variable wasNull = scope.declareVariable("wasNull", body, constantFalse());
cseFields.values().forEach(fields -> body.append(thisVariable.setField(fields.evaluatedField, constantBoolean(false))));
RowExpressionCompiler compiler = new RowExpressionCompiler(
classDefinition,
callSiteBinder,
cachedInstanceBinder,
new FieldAndVariableReferenceCompiler(callSiteBinder, cseFields, thisVariable),
metadata,
sqlFunctionProperties,
compiledLambdaMap);
Variable outputBlockVariable = scope.createTempVariable(BlockBuilder.class);
for (int i = 0; i < projections.size(); i++) {
body.append(outputBlockVariable.set(thisVariable.getField(blockBuilders).invoke("get", Object.class, constantInt(i))))
.append(compiler.compile(projections.get(i), scope, Optional.of(outputBlockVariable)))
.append(constantBoolean(false))
.putVariable(wasNull);
}
body.ret();
return method;
}
public Supplier<PageFilter> compileFilter(SqlFunctionProperties sqlFunctionProperties, RowExpression filter, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
{
if (filterCache == null) {
return compileFilterInternal(sqlFunctionProperties, filter, isOptimizeCommonSubExpression, classNameSuffix);
}
return filterCache.getUnchecked(new CacheKey(sqlFunctionProperties, ImmutableList.of(filter), isOptimizeCommonSubExpression));
}
private Supplier<PageFilter> compileFilterInternal(SqlFunctionProperties sqlFunctionProperties, RowExpression filter, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
{
requireNonNull(filter, "filter is null");
PageFieldsToInputParametersRewriter.Result result = rewritePageFieldsToInputParameters(filter);
CallSiteBinder callSiteBinder = new CallSiteBinder();
ClassDefinition classDefinition = defineFilterClass(sqlFunctionProperties, result.getRewrittenExpression(), result.getInputChannels(), callSiteBinder, isOptimizeCommonSubExpression, classNameSuffix);
Class<? extends PageFilter> functionClass;
try {
functionClass = defineClass(classDefinition, PageFilter.class, callSiteBinder.getBindings(), getClass().getClassLoader());
}
catch (PrestoException prestoException) {
throw prestoException;
}
catch (Exception e) {
throw new PrestoException(COMPILER_ERROR, filter.toString(), e.getCause());
}
return () -> {
try {
return functionClass.getConstructor().newInstance();
}
catch (ReflectiveOperationException e) {
throw new PrestoException(COMPILER_ERROR, e);
}
};
}
private static ParameterizedType generateFilterClassName(Optional<String> classNameSuffix)
{
return makeClassName(PageFilter.class.getSimpleName(), classNameSuffix);
}
private ClassDefinition defineFilterClass(SqlFunctionProperties sqlFunctionProperties, RowExpression filter, InputChannels inputChannels, CallSiteBinder callSiteBinder, boolean isOptimizeCommonSubExpression, Optional<String> classNameSuffix)
{
ClassDefinition classDefinition = new ClassDefinition(
a(PUBLIC, FINAL),
generateFilterClassName(classNameSuffix),
type(Object.class),
type(PageFilter.class));
CachedInstanceBinder cachedInstanceBinder = new CachedInstanceBinder(classDefinition, callSiteBinder);
Map<LambdaDefinitionExpression, CompiledLambda> compiledLambdaMap = generateMethodsForLambda(classDefinition, callSiteBinder, cachedInstanceBinder, filter, metadata, sqlFunctionProperties);
// cse
Map<VariableReferenceExpression, CommonSubExpressionFields> cseFields = ImmutableMap.of();
if (isOptimizeCommonSubExpression) {
Map<Integer, Map<RowExpression, VariableReferenceExpression>> commonSubExpressionsByLevel = collectCSEByLevel(filter);
if (!commonSubExpressionsByLevel.isEmpty()) {
cseFields = declareCommonSubExpressionFields(classDefinition, commonSubExpressionsByLevel);
generateCommonSubExpressionMethods(sqlFunctionProperties, classDefinition, callSiteBinder, cachedInstanceBinder, compiledLambdaMap, commonSubExpressionsByLevel, cseFields);
Map<RowExpression, VariableReferenceExpression> commonSubExpressions = commonSubExpressionsByLevel.values().stream()
.flatMap(m -> m.entrySet().stream())
.collect(toImmutableMap(Map.Entry::getKey, Map.Entry::getValue));
filter = rewriteExpressionWithCSE(filter, commonSubExpressions);
if (log.isDebugEnabled()) {
log.debug("Extracted %d common sub-expressions", commonSubExpressions.size());
commonSubExpressions.entrySet().forEach(entry -> log.debug("\t%s = %s", entry.getValue(), entry.getKey()));
log.debug("Rewrote filter: %s", filter);
}
}
}
generateFilterMethod(sqlFunctionProperties, classDefinition, callSiteBinder, cachedInstanceBinder, compiledLambdaMap, filter, cseFields);
FieldDefinition selectedPositions = classDefinition.declareField(a(PRIVATE), "selectedPositions", boolean[].class);
generatePageFilterMethod(classDefinition, selectedPositions);
// isDeterministic
classDefinition.declareMethod(a(PUBLIC), "isDeterministic", type(boolean.class))
.getBody()
.append(constantBoolean(determinismEvaluator.isDeterministic(filter)))
.retBoolean();
// getInputChannels
classDefinition.declareMethod(a(PUBLIC), "getInputChannels", type(InputChannels.class))
.getBody()
.append(invoke(callSiteBinder.bind(inputChannels, InputChannels.class), "getInputChannels"))
.retObject();
// toString
String toStringResult = toStringHelper(classDefinition.getType()
.getJavaClassName())
.add("filter", filter)
.toString();
classDefinition.declareMethod(a(PUBLIC), "toString", type(String.class))
.getBody()
// bind constant via invokedynamic to avoid constant pool issues due to large strings
.append(invoke(callSiteBinder.bind(toStringResult, String.class), "toString"))
.retObject();
// constructor
MethodDefinition constructorDefinition = classDefinition.declareConstructor(a(PUBLIC));
BytecodeBlock body = constructorDefinition.getBody();
Variable thisVariable = constructorDefinition.getThis();
body.comment("super();")
.append(thisVariable)
.invokeConstructor(Object.class)
.append(thisVariable.setField(selectedPositions, newArray(type(boolean[].class), 0)));
initializeCommonSubExpressionFields(cseFields.values(), thisVariable, body);
cachedInstanceBinder.generateInitializations(thisVariable, body);
body.ret();
return classDefinition;
}
private static MethodDefinition generatePageFilterMethod(ClassDefinition classDefinition, FieldDefinition selectedPositionsField)
{
Parameter properties = arg("properties", SqlFunctionProperties.class);
Parameter page = arg("page", Page.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"filter",
type(SelectedPositions.class),
ImmutableList.<Parameter>builder()
.add(properties)
.add(page)
.build());
Scope scope = method.getScope();
Variable thisVariable = method.getThis();
BytecodeBlock body = method.getBody();
Variable positionCount = scope.declareVariable("positionCount", body, page.invoke("getPositionCount", int.class));
body.append(new IfStatement("grow selectedPositions if necessary")
.condition(lessThan(thisVariable.getField(selectedPositionsField).length(), positionCount))
.ifTrue(thisVariable.setField(selectedPositionsField, newArray(type(boolean[].class), positionCount))));
Variable selectedPositions = scope.declareVariable("selectedPositions", body, thisVariable.getField(selectedPositionsField));
Variable position = scope.declareVariable(int.class, "position");
body.append(new ForLoop()
.initialize(position.set(constantInt(0)))
.condition(lessThan(position, positionCount))
.update(position.increment())
.body(selectedPositions.setElement(position, thisVariable.invoke("filter", boolean.class, properties, page, position))));
body.append(invokeStatic(
PageFilter.class,
"positionsArrayToSelectedPositions",
SelectedPositions.class,
selectedPositions,
positionCount)
.ret());
return method;
}
private MethodDefinition generateFilterMethod(
SqlFunctionProperties sqlFunctionProperties,
ClassDefinition classDefinition,
CallSiteBinder callSiteBinder,
CachedInstanceBinder cachedInstanceBinder,
Map<LambdaDefinitionExpression, CompiledLambda> compiledLambdaMap,
RowExpression filter,
Map<VariableReferenceExpression, CommonSubExpressionFields> cseFields)
{
Parameter properties = arg("properties", SqlFunctionProperties.class);
Parameter page = arg("page", Page.class);
Parameter position = arg("position", int.class);
MethodDefinition method = classDefinition.declareMethod(
a(PUBLIC),
"filter",
type(boolean.class),
ImmutableList.<Parameter>builder()
.add(properties)
.add(page)
.add(position)
.build());
method.comment("Filter: %s", filter.toString());
Scope scope = method.getScope();
BytecodeBlock body = method.getBody();
Variable thisVariable = scope.getThis();
declareBlockVariables(ImmutableList.of(filter), page, scope, body);
cseFields.values().forEach(fields -> body.append(thisVariable.setField(fields.evaluatedField, constantBoolean(false))));
Variable wasNullVariable = scope.declareVariable("wasNull", body, constantFalse());
RowExpressionCompiler compiler = new RowExpressionCompiler(
classDefinition,
callSiteBinder,
cachedInstanceBinder,
new FieldAndVariableReferenceCompiler(callSiteBinder, cseFields, thisVariable),
metadata,
sqlFunctionProperties,
compiledLambdaMap);
Variable result = scope.declareVariable(boolean.class, "result");
body.append(compiler.compile(filter, scope, Optional.empty()))
// store result so we can check for null
.putVariable(result)
.append(and(not(wasNullVariable), result).ret());
return method;
}
private static void initializeCommonSubExpressionFields(Collection<CommonSubExpressionFields> cseFields, Variable thisVariable, BytecodeBlock body)
{
cseFields.forEach(fields -> {
body.append(thisVariable.setField(fields.evaluatedField, constantBoolean(false)));
body.append(thisVariable.setField(fields.resultField, constantNull(fields.resultType)));
});
}
private static void declareBlockVariables(List<RowExpression> expressions, Parameter page, Scope scope, BytecodeBlock body)
{
for (int channel : getInputChannels(expressions)) {
scope.declareVariable("block_" + channel, body, page.invoke("getBlock", Block.class, constantInt(channel)));
}
}
private static Map<VariableReferenceExpression, CommonSubExpressionFields> declareCommonSubExpressionFields(ClassDefinition classDefinition, Map<Integer, Map<RowExpression, VariableReferenceExpression>> commonSubExpressionsByLevel)
{
ImmutableMap.Builder<VariableReferenceExpression, CommonSubExpressionFields> fields = ImmutableMap.builder();
commonSubExpressionsByLevel.values().stream().map(Map::values).flatMap(Collection::stream).forEach(variable -> {
Class<?> type = Primitives.wrap(variable.getType().getJavaType());
fields.put(variable, new CommonSubExpressionFields(
classDefinition.declareField(a(PRIVATE), variable.getName() + "Evaluated", boolean.class),
classDefinition.declareField(a(PRIVATE), variable.getName() + "Result", type),
type,
"get" + variable.getName()));
});
return fields.build();
}
private static List<Integer> getInputChannels(Iterable<RowExpression> expressions)
{
TreeSet<Integer> channels = new TreeSet<>();
for (RowExpression expression : subExpressions(expressions)) {
if (expression instanceof InputReferenceExpression) {
channels.add(((InputReferenceExpression) expression).getField());
}
}
return ImmutableList.copyOf(channels);
}
private static int[] toIntArray(List<Integer> list)
{
int[] array = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
return array;
}
private static class CommonSubExpressionFields
{
private final FieldDefinition evaluatedField;
private final FieldDefinition resultField;
private final Class<?> resultType;
private final String methodName;
public CommonSubExpressionFields(FieldDefinition evaluatedField, FieldDefinition resultField, Class<?> resultType, String methodName)
{
this.evaluatedField = evaluatedField;
this.resultField = resultField;
this.resultType = resultType;
this.methodName = methodName;
}
}
private static class FieldAndVariableReferenceCompiler
implements RowExpressionVisitor<BytecodeNode, Scope>
{
private final InputReferenceCompiler inputReferenceCompiler;
private final Map<VariableReferenceExpression, CommonSubExpressionFields> variableMap;
private final Variable thisVariable;
public FieldAndVariableReferenceCompiler(CallSiteBinder callSiteBinder, Map<VariableReferenceExpression, CommonSubExpressionFields> variableMap, Variable thisVariable)
{
this.inputReferenceCompiler = new InputReferenceCompiler(
(scope, field) -> scope.getVariable("block_" + field),
(scope, field) -> scope.getVariable("position"),
callSiteBinder);
this.variableMap = ImmutableMap.copyOf(variableMap);
this.thisVariable = thisVariable;
}
@Override
public BytecodeNode visitCall(CallExpression call, Scope context)
{
throw new UnsupportedOperationException();
}
@Override
public BytecodeNode visitInputReference(InputReferenceExpression reference, Scope context)
{
return inputReferenceCompiler.visitInputReference(reference, context);
}
@Override
public BytecodeNode visitConstant(ConstantExpression literal, Scope context)
{
throw new UnsupportedOperationException();
}
@Override
public BytecodeNode visitLambda(LambdaDefinitionExpression lambda, Scope context)
{
throw new UnsupportedOperationException();
}
@Override
public BytecodeNode visitVariableReference(VariableReferenceExpression reference, Scope context)
{
CommonSubExpressionFields fields = variableMap.get(reference);
IfStatement ifStatement = new IfStatement()
.condition(thisVariable.getField(fields.evaluatedField))
.ifFalse(new BytecodeBlock()
.append(thisVariable.invoke(fields.methodName, void.class, context.getVariable("properties"), context.getVariable("page"), context.getVariable("position"))));
return new BytecodeBlock()
.append(ifStatement)
.append(thisVariable.getField(fields.resultField))
.append(unboxPrimitiveIfNecessary(context, Primitives.wrap(reference.getType().getJavaType())));
}
@Override
public BytecodeNode visitSpecialForm(SpecialFormExpression specialForm, Scope context)
{
throw new UnsupportedOperationException();
}
}
private static final class CacheKey
{
private final SqlFunctionProperties sqlFunctionProperties;
private final List<RowExpression> rowExpressions;
private final boolean isOptimizeCommonSubExpression;
private CacheKey(SqlFunctionProperties sqlFunctionProperties, List<RowExpression> rowExpressions, boolean isOptimizeCommonSubExpression)
{
requireNonNull(rowExpressions, "rowExpressions is null");
checkArgument(rowExpressions.size() >= 1, "Expect at least one RowExpression");
this.sqlFunctionProperties = requireNonNull(sqlFunctionProperties, "sqlFunctionProperties is null");
this.rowExpressions = ImmutableList.copyOf(rowExpressions);
this.isOptimizeCommonSubExpression = isOptimizeCommonSubExpression;
}
@Override
public boolean equals(Object o)
{
if (this == o) {
return true;
}
if (!(o instanceof CacheKey)) {
return false;
}
CacheKey that = (CacheKey) o;
return Objects.equals(sqlFunctionProperties, that.sqlFunctionProperties) &&
Objects.equals(rowExpressions, that.rowExpressions) &&
isOptimizeCommonSubExpression == that.isOptimizeCommonSubExpression;
}
@Override
public int hashCode()
{
return Objects.hash(sqlFunctionProperties, rowExpressions, isOptimizeCommonSubExpression);
}
}
}
| Change common sub-expression methods to return result
| presto-main/src/main/java/com/facebook/presto/sql/gen/PageFunctionCompiler.java | Change common sub-expression methods to return result |
|
Java | apache-2.0 | dc58c3fda91043c1be9c2c6c620b23c1315f7932 | 0 | irccloud/android,irccloud/android,irccloud/android,irccloud/android,irccloud/android | /*
* Copyright (c) 2013 IRCCloud, 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 com.irccloud.android;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.SQLException;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.WearableExtender;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.app.RemoteInput;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.RemoteViews;
import com.crashlytics.android.Crashlytics;
import com.irccloud.android.activity.QuickReplyActivity;
import com.sonyericsson.extras.liveware.extension.util.notification.NotificationUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Timer;
import java.util.TimerTask;
public class Notifications {
public class Notification {
public int cid;
public int bid;
public long eid;
public String nick;
public String message;
public String network;
public String chan;
public String buffer_type;
public String message_type;
public boolean shown = false;
public String toString() {
return "{cid: " + cid + ", bid: " + bid + ", eid: " + eid + ", nick: " + nick + ", message: " + message + ", network: " + network + " shown: " + shown + "}";
}
}
public class comparator implements Comparator<Notification> {
public int compare(Notification n1, Notification n2) {
if (n1.cid != n2.cid)
return Integer.valueOf(n1.cid).compareTo(n2.cid);
else if (n1.bid != n2.bid)
return Integer.valueOf(n1.bid).compareTo(n2.bid);
else
return Long.valueOf(n1.eid).compareTo(n2.eid);
}
}
private ArrayList<Notification> mNotifications = null;
private SparseArray<String> mNetworks = null;
private SparseArray<Long> mLastSeenEIDs = null;
private SparseArray<HashSet<Long>> mDismissedEIDs = null;
private static Notifications instance = null;
private int excludeBid = -1;
private static final Timer mNotificationTimer = new Timer("notification-timer");
private TimerTask mNotificationTimerTask = null;
public static Notifications getInstance() {
if (instance == null)
instance = new Notifications();
return instance;
}
public Notifications() {
try {
load();
} catch (Exception e) {
}
}
private void load() {
mNotifications = new ArrayList<Notification>();
mNetworks = new SparseArray<String>();
mLastSeenEIDs = new SparseArray<Long>();
mDismissedEIDs = new SparseArray<HashSet<Long>>();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
if (prefs.contains("notifications_json")) {
try {
JSONArray array = new JSONArray(prefs.getString("networks_json", "[]"));
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
mNetworks.put(o.getInt("cid"), o.getString("network"));
}
array = new JSONArray(prefs.getString("lastseeneids_json", "[]"));
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
mLastSeenEIDs.put(o.getInt("bid"), o.getLong("eid"));
}
array = new JSONArray(prefs.getString("dismissedeids_json", "[]"));
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
int bid = o.getInt("bid");
mDismissedEIDs.put(bid, new HashSet<Long>());
JSONArray eids = o.getJSONArray("eids");
for (int j = 0; j < eids.length(); j++) {
mDismissedEIDs.get(bid).add(eids.getLong(j));
}
}
synchronized (mNotifications) {
array = new JSONArray(prefs.getString("notifications_json", "[]"));
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
Notification n = new Notification();
n.bid = o.getInt("bid");
n.cid = o.getInt("cid");
n.eid = o.getLong("eid");
n.nick = o.getString("nick");
n.message = o.getString("message");
n.chan = o.getString("chan");
n.buffer_type = o.getString("buffer_type");
n.message_type = o.getString("message_type");
n.network = mNetworks.get(n.cid);
if (o.has("shown"))
n.shown = o.getBoolean("shown");
mNotifications.add(n);
}
Collections.sort(mNotifications, new comparator());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static final Timer mSaveTimer = new Timer("notifications-save-timer");
private TimerTask mSaveTimerTask = null;
@TargetApi(9)
private void save() {
if (mSaveTimerTask != null)
mSaveTimerTask.cancel();
mSaveTimerTask = new TimerTask() {
@Override
public void run() {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).edit();
try {
JSONArray array = new JSONArray();
synchronized (mNotifications) {
for (Notification n : mNotifications) {
if(n != null) {
JSONObject o = new JSONObject();
o.put("cid", n.cid);
o.put("bid", n.bid);
o.put("eid", n.eid);
o.put("nick", n.nick);
o.put("message", n.message);
o.put("chan", n.chan);
o.put("buffer_type", n.buffer_type);
o.put("message_type", n.message_type);
o.put("shown", n.shown);
array.put(o);
}
}
editor.putString("notifications_json", array.toString());
}
array = new JSONArray();
for (int i = 0; i < mNetworks.size(); i++) {
int cid = mNetworks.keyAt(i);
String network = mNetworks.get(cid);
JSONObject o = new JSONObject();
o.put("cid", cid);
o.put("network", network);
array.put(o);
}
editor.putString("networks_json", array.toString());
array = new JSONArray();
for (int i = 0; i < mLastSeenEIDs.size(); i++) {
int bid = mLastSeenEIDs.keyAt(i);
long eid = mLastSeenEIDs.get(bid);
JSONObject o = new JSONObject();
o.put("bid", bid);
o.put("eid", eid);
array.put(o);
}
editor.putString("lastseeneids_json", array.toString());
array = new JSONArray();
for (int i = 0; i < mDismissedEIDs.size(); i++) {
JSONArray a = new JSONArray();
int bid = mDismissedEIDs.keyAt(i);
HashSet<Long> eids = mDismissedEIDs.get(bid);
if(eids.size() > 0) {
for (long eid : eids) {
a.put(eid);
}
JSONObject o = new JSONObject();
o.put("bid", bid);
o.put("eids", a);
array.put(o);
}
}
editor.putString("dismissedeids_json", array.toString());
if (Build.VERSION.SDK_INT >= 9)
editor.apply();
else
editor.commit();
} catch (ConcurrentModificationException e) {
save();
} catch (OutOfMemoryError e) {
editor.remove("notifications_json");
editor.remove("networks_json");
editor.remove("lastseeneids_json");
editor.remove("dismissedeids_json");
editor.commit();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
try {
mSaveTimer.schedule(mSaveTimerTask, 100);
} catch (IllegalStateException e) {
//Timer is already cancelled
}
}
public void clearDismissed() {
mDismissedEIDs.clear();
save();
}
public void clear() {
try {
synchronized (mNotifications) {
if (mNotifications.size() > 0) {
for (Notification n : mNotifications) {
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel((int) (n.eid / 1000));
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel(n.bid);
}
}
}
IRCCloudApplication.getInstance().getApplicationContext().sendBroadcast(new Intent(DashClock.REFRESH_INTENT));
try {
if (PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).getBoolean("notify_sony", false))
NotificationUtil.deleteAllEvents(IRCCloudApplication.getInstance().getApplicationContext());
} catch (Exception e) {
//Sony LiveWare was probably removed
}
} catch (Exception e) {
e.printStackTrace();
}
if (mSaveTimerTask != null)
mSaveTimerTask.cancel();
mNotifications.clear();
mLastSeenEIDs.clear();
mDismissedEIDs.clear();
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).edit();
editor.remove("notifications_json");
editor.remove("lastseeneids_json");
editor.remove("dismissedeids_json");
editor.commit();
updateTeslaUnreadCount();
}
public void clearNetworks() {
mNetworks.clear();
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).edit();
editor.remove("networks_json");
editor.commit();
}
public void clearLastSeenEIDs() {
mLastSeenEIDs.clear();
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).edit();
editor.remove("lastseeneids_json");
editor.commit();
}
public long getLastSeenEid(int bid) {
if (mLastSeenEIDs.get(bid) != null)
return mLastSeenEIDs.get(bid);
else
return -1;
}
public synchronized void updateLastSeenEid(int bid, long eid) {
mLastSeenEIDs.put(bid, eid);
save();
}
public synchronized boolean isDismissed(int bid, long eid) {
if (mDismissedEIDs.get(bid) != null) {
for (Long e : mDismissedEIDs.get(bid)) {
if (e == eid)
return true;
}
}
return false;
}
public synchronized void dismiss(int bid, long eid) {
if (mDismissedEIDs.get(bid) == null)
mDismissedEIDs.put(bid, new HashSet<Long>());
mDismissedEIDs.get(bid).add(eid);
Notification n = getNotification(eid);
synchronized (mNotifications) {
if (n != null)
mNotifications.remove(n);
}
save();
if (IRCCloudApplication.getInstance() != null)
IRCCloudApplication.getInstance().getApplicationContext().sendBroadcast(new Intent(DashClock.REFRESH_INTENT));
updateTeslaUnreadCount();
}
public synchronized void addNetwork(int cid, String network) {
mNetworks.put(cid, network);
save();
}
public synchronized void deleteNetwork(int cid) {
mNetworks.remove(cid);
save();
}
public synchronized void addNotification(int cid, int bid, long eid, String from, String message, String chan, String buffer_type, String message_type) {
if (isDismissed(bid, eid)) {
Crashlytics.log("Refusing to add notification for dismissed eid: " + eid);
return;
}
long last_eid = getLastSeenEid(bid);
if (eid <= last_eid) {
Crashlytics.log("Refusing to add notification for seen eid: " + eid);
return;
}
String network = getNetwork(cid);
if (network == null)
addNetwork(cid, "Unknown Network");
Notification n = new Notification();
n.bid = bid;
n.cid = cid;
n.eid = eid;
n.nick = from;
n.message = TextUtils.htmlEncode(ColorFormatter.emojify(message));
n.chan = chan;
n.buffer_type = buffer_type;
n.message_type = message_type;
n.network = network;
synchronized (mNotifications) {
mNotifications.add(n);
Collections.sort(mNotifications, new comparator());
}
save();
}
public void deleteNotification(int cid, int bid, long eid) {
synchronized (mNotifications) {
for (Notification n : mNotifications) {
if (n.cid == cid && n.bid == bid && n.eid == eid) {
mNotifications.remove(n);
save();
return;
}
}
}
}
public void deleteOldNotifications(int bid, long last_seen_eid) {
boolean changed = false;
if (mNotificationTimerTask != null) {
mNotificationTimerTask.cancel();
}
ArrayList<Notification> notifications = getOtherNotifications();
if (notifications.size() > 0) {
for (Notification n : notifications) {
if (n.bid == bid && n.eid <= last_seen_eid) {
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel((int) (n.eid / 1000));
changed = true;
}
}
}
synchronized (mNotifications) {
for (int i = 0; i < mNotifications.size(); i++) {
Notification n = mNotifications.get(i);
if (n.bid == bid && n.eid <= last_seen_eid) {
mNotifications.remove(n);
i--;
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel(bid);
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel((int) (n.eid / 1000));
changed = true;
}
}
}
if (mDismissedEIDs.get(bid) != null) {
HashSet<Long> eids = mDismissedEIDs.get(bid);
Long[] eidsArray = eids.toArray(new Long[eids.size()]);
for (int i = 0; i < eidsArray.length; i++) {
if (eidsArray[i] <= last_seen_eid) {
eids.remove(eidsArray[i]);
}
}
}
save();
if (changed) {
IRCCloudApplication.getInstance().getApplicationContext().sendBroadcast(new Intent(DashClock.REFRESH_INTENT));
try {
if (PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).getBoolean("notify_sony", false))
NotificationUtil.deleteEvents(IRCCloudApplication.getInstance().getApplicationContext(), com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.FRIEND_KEY + " = ?", new String[]{String.valueOf(bid)});
} catch (Exception e) {
}
updateTeslaUnreadCount();
}
}
public void deleteNotificationsForBid(int bid) {
ArrayList<Notification> notifications = getOtherNotifications();
if (notifications.size() > 0) {
for (Notification n : notifications) {
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel((int) (n.eid / 1000));
}
}
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel(bid);
synchronized (mNotifications) {
for (int i = 0; i < mNotifications.size(); i++) {
Notification n = mNotifications.get(i);
if (n.bid == bid) {
mNotifications.remove(n);
i--;
}
}
}
mDismissedEIDs.remove(bid);
mLastSeenEIDs.remove(bid);
IRCCloudApplication.getInstance().getApplicationContext().sendBroadcast(new Intent(DashClock.REFRESH_INTENT));
try {
if (PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).getBoolean("notify_sony", false))
NotificationUtil.deleteEvents(IRCCloudApplication.getInstance().getApplicationContext(), com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.FRIEND_KEY + " = ?", new String[]{String.valueOf(bid)});
} catch (Exception e) {
//User has probably uninstalled Sony Liveware
}
updateTeslaUnreadCount();
}
private boolean isMessage(String type) {
return !(type.equalsIgnoreCase("channel_invite") || type.equalsIgnoreCase("callerid"));
}
public int count() {
return mNotifications.size();
}
public ArrayList<Notification> getMessageNotifications() {
ArrayList<Notification> notifications = new ArrayList<Notification>();
synchronized (mNotifications) {
for (int i = 0; i < mNotifications.size(); i++) {
Notification n = mNotifications.get(i);
if (n != null && n.bid != excludeBid && isMessage(n.message_type)) {
if (n.network == null)
n.network = getNetwork(n.cid);
notifications.add(n);
}
}
}
return notifications;
}
public ArrayList<Notification> getOtherNotifications() {
ArrayList<Notification> notifications = new ArrayList<Notification>();
synchronized (mNotifications) {
for (int i = 0; i < mNotifications.size(); i++) {
Notification n = mNotifications.get(i);
if (n != null && n.bid != excludeBid && !isMessage(n.message_type)) {
if (n.network == null)
n.network = getNetwork(n.cid);
notifications.add(n);
}
}
}
return notifications;
}
public String getNetwork(int cid) {
return mNetworks.get(cid);
}
public Notification getNotification(long eid) {
synchronized (mNotifications) {
for (int i = 0; i < mNotifications.size(); i++) {
Notification n = mNotifications.get(i);
if (n.bid != excludeBid && n.eid == eid && isMessage(n.message_type)) {
if (n.network == null)
n.network = getNetwork(n.cid);
return n;
}
}
}
return null;
}
public synchronized void excludeBid(int bid) {
excludeBid = -1;
ArrayList<Notification> notifications = getOtherNotifications();
if (notifications.size() > 0) {
for (Notification n : notifications) {
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel((int) (n.eid / 1000));
}
}
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel(bid);
excludeBid = bid;
}
private String mTicker = null;
public synchronized void showNotifications(String ticker) {
if (ticker != null)
mTicker = ColorFormatter.emojify(ticker);
ArrayList<Notification> notifications = getMessageNotifications();
for (Notification n : notifications) {
if (isDismissed(n.bid, n.eid)) {
deleteNotification(n.cid, n.bid, n.eid);
}
}
if (mNotificationTimerTask != null)
mNotificationTimerTask.cancel();
try {
mNotificationTimerTask = new TimerTask() {
@Override
public void run() {
showMessageNotifications(mTicker);
showOtherNotifications();
mTicker = null;
IRCCloudApplication.getInstance().getApplicationContext().sendBroadcast(new Intent(DashClock.REFRESH_INTENT));
updateTeslaUnreadCount();
}
};
mNotificationTimer.schedule(mNotificationTimerTask, 5000);
} catch (Exception e) {
e.printStackTrace();
Crashlytics.logException(e);
}
}
private void showOtherNotifications() {
String title = "";
String text = "";
String ticker = null;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
ArrayList<Notification> notifications = getOtherNotifications();
int notify_type = Integer.parseInt(prefs.getString("notify_type", "1"));
boolean notify = false;
if (notify_type == 1 || (notify_type == 2 && NetworkConnection.getInstance().isVisible()))
notify = true;
if (notifications.size() > 0 && notify) {
for (Notification n : notifications) {
if (!n.shown) {
if (n.message_type.equals("callerid")) {
title = "Callerid: " + n.nick + " (" + n.network + ")";
text = n.nick + " " + n.message;
ticker = n.nick + " " + n.message;
} else {
title = n.nick + " (" + n.network + ")";
text = n.message;
ticker = n.message;
}
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).notify((int) (n.eid / 1000), buildNotification(ticker, n.bid, new long[]{n.eid}, title, text, Html.fromHtml(text), 1, null, null, title, null));
n.shown = true;
}
}
}
}
@SuppressLint("NewApi")
private android.app.Notification buildNotification(String ticker, int bid, long[] eids, String title, String text, Spanned big_text, int count, Intent replyIntent, Spanned wear_text, String network, String auto_messages[]) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
NotificationCompat.Builder builder = new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext())
.setContentTitle(title + ((network != null) ? (" (" + network + ")") : ""))
.setContentText(Html.fromHtml(text))
.setAutoCancel(true)
.setTicker(ticker)
.setWhen(eids[0] / 1000)
.setSmallIcon(R.drawable.ic_stat_notify)
.setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources().getColor(R.color.dark_blue))
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOnlyAlertOnce(false);
if (ticker != null && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 10000) {
if (prefs.getBoolean("notify_vibrate", true))
builder.setDefaults(android.app.Notification.DEFAULT_VIBRATE);
String ringtone = prefs.getString("notify_ringtone", "content://settings/system/notification_sound");
if (ringtone != null && ringtone.length() > 0)
builder.setSound(Uri.parse(ringtone));
}
int led_color = Integer.parseInt(prefs.getString("notify_led_color", "1"));
if (led_color == 1) {
if (prefs.getBoolean("notify_vibrate", true))
builder.setDefaults(android.app.Notification.DEFAULT_LIGHTS | android.app.Notification.DEFAULT_VIBRATE);
else
builder.setDefaults(android.app.Notification.DEFAULT_LIGHTS);
} else if (led_color == 2) {
builder.setLights(0xFF0000FF, 500, 500);
}
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("lastNotificationTime", System.currentTimeMillis());
editor.commit();
Intent i = new Intent();
i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), "com.irccloud.android.MainActivity"));
i.putExtra("bid", bid);
i.setData(Uri.parse("bid://" + bid));
Intent dismiss = new Intent(IRCCloudApplication.getInstance().getApplicationContext().getResources().getString(R.string.DISMISS_NOTIFICATION));
dismiss.setData(Uri.parse("irccloud-dismiss://" + bid));
dismiss.putExtra("bid", bid);
dismiss.putExtra("eids", eids);
PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(IRCCloudApplication.getInstance().getApplicationContext(), 0, dismiss, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT));
builder.setDeleteIntent(dismissPendingIntent);
if (replyIntent != null) {
WearableExtender extender = new WearableExtender();
PendingIntent replyPendingIntent = PendingIntent.getService(IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT);
extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_reply,
"Reply", replyPendingIntent)
.addRemoteInput(new RemoteInput.Builder("extra_reply").setLabel("Reply").build()).build());
if (count > 1 && wear_text != null)
extender.addPage(new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext()).setContentText(wear_text).extend(new WearableExtender().setStartScrollBottom(true)).build());
NotificationCompat.CarExtender.UnreadConversation.Builder unreadConvBuilder =
new NotificationCompat.CarExtender.UnreadConversation.Builder(title + ((network != null) ? (" (" + network + ")") : ""))
.setReadPendingIntent(dismissPendingIntent)
.setReplyAction(replyPendingIntent, new RemoteInput.Builder("extra_reply").setLabel("Reply").build());
if (auto_messages != null) {
for (String m : auto_messages) {
if (m != null && m.length() > 0) {
unreadConvBuilder.addMessage(m);
}
}
} else {
unreadConvBuilder.addMessage(text);
}
unreadConvBuilder.setLatestTimestamp(eids[count - 1] / 1000);
builder.extend(extender).extend(new NotificationCompat.CarExtender().setUnreadConversation(unreadConvBuilder.build()));
}
if(replyIntent != null) {
i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
i.setData(Uri.parse("irccloud-bid://" + bid));
i.putExtras(replyIntent);
PendingIntent quickReplyIntent = PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(R.drawable.ic_action_reply, "Reply", quickReplyIntent);
}
android.app.Notification notification = builder.build();
RemoteViews contentView = new RemoteViews(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), R.layout.notification);
contentView.setTextViewText(R.id.title, title + " (" + network + ")");
contentView.setTextViewText(R.id.text, (count == 1) ? Html.fromHtml(text) : (count + " unread highlights."));
contentView.setLong(R.id.time, "setTime", eids[0] / 1000);
notification.contentView = contentView;
if (Build.VERSION.SDK_INT >= 16 && big_text != null) {
RemoteViews bigContentView = new RemoteViews(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), R.layout.notification_expanded);
bigContentView.setTextViewText(R.id.title, title + (!title.equals(network) ? (" (" + network + ")") : ""));
bigContentView.setTextViewText(R.id.text, big_text);
bigContentView.setLong(R.id.time, "setTime", eids[0] / 1000);
if (count > 3) {
bigContentView.setViewVisibility(R.id.more, View.VISIBLE);
bigContentView.setTextViewText(R.id.more, "+" + (count - 3) + " more");
} else {
bigContentView.setViewVisibility(R.id.more, View.GONE);
}
if(replyIntent != null) {
bigContentView.setViewVisibility(R.id.actions, View.VISIBLE);
bigContentView.setViewVisibility(R.id.action_divider, View.VISIBLE);
i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
i.setData(Uri.parse("irccloud-bid://" + bid));
i.putExtras(replyIntent);
PendingIntent quickReplyIntent = PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
bigContentView.setOnClickPendingIntent(R.id.action_reply, quickReplyIntent);
}
notification.bigContentView = bigContentView;
}
return notification;
}
private void notifyPebble(String title, String body) {
JSONObject jsonData = new JSONObject();
try {
final Intent i = new Intent("com.getpebble.action.SEND_NOTIFICATION");
jsonData.put("title", title);
jsonData.put("body", body);
final String notificationData = new JSONArray().put(jsonData).toString();
i.putExtra("messageType", "PEBBLE_ALERT");
i.putExtra("sender", "IRCCloud");
i.putExtra("notificationData", notificationData);
IRCCloudApplication.getInstance().getApplicationContext().sendBroadcast(i);
} catch (Exception e) {
e.printStackTrace();
}
}
private void showMessageNotifications(String ticker) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
String text = "";
String weartext = "";
ArrayList<Notification> notifications = getMessageNotifications();
int notify_type = Integer.parseInt(prefs.getString("notify_type", "1"));
boolean notify = false;
if (notify_type == 1 || (notify_type == 2 && NetworkConnection.getInstance().isVisible()))
notify = true;
if (notifications.size() > 0 && notify) {
int lastbid = notifications.get(0).bid;
int count = 0;
long[] eids = new long[notifications.size()];
String[] auto_messages = new String[notifications.size()];
Notification last = null;
count = 0;
boolean show = false;
for (Notification n : notifications) {
if (n.bid != lastbid) {
if (show) {
String title = last.chan;
if (title == null || title.length() == 0)
title = last.nick;
if (title == null || title.length() == 0)
title = last.network;
Intent replyIntent = new Intent(RemoteInputService.ACTION_REPLY);
replyIntent.putExtra("bid", last.bid);
replyIntent.putExtra("cid", last.cid);
replyIntent.putExtra("eids", eids);
replyIntent.putExtra("network", last.network);
if (last.buffer_type.equals("channel"))
replyIntent.putExtra("to", last.chan);
else
replyIntent.putExtra("to", last.nick);
String body = "";
if (last.buffer_type.equals("channel")) {
if (last.message_type.equals("buffer_me_msg"))
body = "<b>— " + last.nick + "</b> " + last.message;
else
body = "<b><" + last.nick + "></b> " + last.message;
} else {
if (last.message_type.equals("buffer_me_msg"))
body = "— " + last.nick + " " + last.message;
else
body = last.message;
}
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).notify(lastbid, buildNotification(ticker, lastbid, eids, title, body, Html.fromHtml(text), count, replyIntent, Html.fromHtml(weartext), last.network, auto_messages));
}
lastbid = n.bid;
text = "";
weartext = "";
count = 0;
eids = new long[notifications.size()];
show = false;
auto_messages = new String[notifications.size()];
}
if (count < 3) {
if (text.length() > 0)
text += "<br/>";
if (n.buffer_type.equals("conversation") && n.message_type.equals("buffer_me_msg"))
text += "— " + n.message;
else if (n.buffer_type.equals("conversation"))
text += n.message;
else if (n.message_type.equals("buffer_me_msg"))
text += "<b>— " + n.nick + "</b> " + n.message;
else
text += "<b>" + n.nick + "</b> " + n.message;
}
if (weartext.length() > 0)
weartext += "<br/><br/>";
if (n.message_type.equals("buffer_me_msg"))
weartext += "<b>— " + n.nick + "</b> " + n.message;
else
weartext += "<b><" + n.nick + "></b> " + n.message;
if (n.buffer_type.equals("conversation")) {
if (n.message_type.equals("buffer_me_msg"))
auto_messages[count] = "— " + n.nick + " " + Html.fromHtml(n.message).toString();
else
auto_messages[count] = Html.fromHtml(n.message).toString();
} else {
if (n.message_type.equals("buffer_me_msg"))
auto_messages[count] = "— " + n.nick + " " + Html.fromHtml(n.message).toString();
else
auto_messages[count] = n.nick + " said: " + Html.fromHtml(n.message).toString();
}
if (!n.shown) {
n.shown = true;
show = true;
if (prefs.getBoolean("notify_sony", false)) {
long time = System.currentTimeMillis();
long sourceId = NotificationUtil.getSourceId(IRCCloudApplication.getInstance().getApplicationContext(), SonyExtensionService.EXTENSION_SPECIFIC_ID);
if (sourceId == NotificationUtil.INVALID_ID) {
Crashlytics.log(Log.ERROR, "IRCCloud", "Sony LiveWare Manager not configured, disabling Sony notifications");
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("notify_sony", false);
editor.commit();
} else {
ContentValues eventValues = new ContentValues();
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.EVENT_READ_STATUS, false);
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.DISPLAY_NAME, n.nick);
if (n.buffer_type.equals("channel") && n.chan != null && n.chan.length() > 0)
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.TITLE, n.chan);
else
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.TITLE, n.network);
if (n.message_type.equals("buffer_me_msg"))
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.MESSAGE, "— " + Html.fromHtml(n.message).toString());
else
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.MESSAGE, Html.fromHtml(n.message).toString());
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.PERSONAL, 1);
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.PUBLISHED_TIME, time);
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.SOURCE_ID, sourceId);
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.FRIEND_KEY, String.valueOf(n.bid));
try {
IRCCloudApplication.getInstance().getApplicationContext().getContentResolver().insert(com.sonyericsson.extras.liveware.aef.notification.Notification.Event.URI, eventValues);
} catch (IllegalArgumentException e) {
Log.e("IRCCloud", "Failed to insert event", e);
} catch (SecurityException e) {
Log.e("IRCCloud", "Failed to insert event, is Live Ware Manager installed?", e);
} catch (SQLException e) {
Log.e("IRCCloud", "Failed to insert event", e);
}
}
}
if (prefs.getBoolean("notify_pebble", false)) {
String pebbleTitle = n.network + ":\n";
String pebbleBody = "";
if (n.buffer_type.equals("channel") && n.chan != null && n.chan.length() > 0)
pebbleTitle = n.chan + ":\n";
if (n.message_type.equals("buffer_me_msg"))
pebbleBody = "— " + n.message;
else
pebbleBody = n.message;
if (n.nick != null && n.nick.length() > 0)
notifyPebble(n.nick, pebbleTitle + Html.fromHtml(pebbleBody).toString());
else
notifyPebble(n.network, pebbleTitle + Html.fromHtml(pebbleBody).toString());
}
}
eids[count++] = n.eid;
last = n;
}
if (show) {
String title = last.chan;
if (title == null || title.length() == 0)
title = last.nick;
if (title == null || title.length() == 0)
title = last.network;
Intent replyIntent = new Intent(RemoteInputService.ACTION_REPLY);
replyIntent.putExtra("bid", last.bid);
replyIntent.putExtra("cid", last.cid);
replyIntent.putExtra("network", last.network);
replyIntent.putExtra("eids", eids);
if (last.buffer_type.equals("channel"))
replyIntent.putExtra("to", last.chan);
else
replyIntent.putExtra("to", last.nick);
String body = "";
if (last.buffer_type.equals("channel")) {
if (last.message_type.equals("buffer_me_msg"))
body = "<b>— " + last.nick + "</b> " + last.message;
else
body = "<b><" + last.nick + "></b> " + last.message;
} else {
if (last.message_type.equals("buffer_me_msg"))
body = "— " + last.nick + " " + last.message;
else
body = last.message;
}
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).notify(lastbid, buildNotification(ticker, lastbid, eids, title, body, Html.fromHtml(text), count, replyIntent, Html.fromHtml(weartext), last.network, auto_messages));
}
}
}
public NotificationCompat.Builder alert(int bid, String title, String body) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext())
.setContentTitle(title)
.setContentText(body)
.setTicker(body)
.setAutoCancel(true)
.setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources().getColor(R.color.dark_blue))
.setSmallIcon(R.drawable.ic_stat_notify);
Intent i = new Intent();
i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), "com.irccloud.android.MainActivity"));
i.putExtra("bid", bid);
i.setData(Uri.parse("bid://" + bid));
builder.setContentIntent(PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT));
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).notify(bid, builder.build());
return builder;
}
public void updateTeslaUnreadCount() {
try {
IRCCloudApplication.getInstance().getApplicationContext().getPackageManager().getPackageInfo("com.teslacoilsw.notifier", PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
return;
}
int count = 0;
synchronized (mNotifications) {
for (int i = 0; i < mNotifications.size(); i++) {
Notification n = mNotifications.get(i);
if (n.bid != excludeBid) {
count++;
}
}
}
try {
ContentValues cv = new ContentValues();
cv.put("tag", IRCCloudApplication.getInstance().getApplicationContext().getPackageManager().getLaunchIntentForPackage(IRCCloudApplication.getInstance().getApplicationContext().getPackageName()).getComponent().flattenToString());
cv.put("count", count);
IRCCloudApplication.getInstance().getApplicationContext().getContentResolver().insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), cv);
} catch (IllegalArgumentException ex) {
} catch (Exception ex) {
ex.printStackTrace();
}
}
} | src/com/irccloud/android/Notifications.java | /*
* Copyright (c) 2013 IRCCloud, 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 com.irccloud.android;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.SQLException;
import android.net.Uri;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.WearableExtender;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.app.RemoteInput;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.RemoteViews;
import com.crashlytics.android.Crashlytics;
import com.irccloud.android.activity.QuickReplyActivity;
import com.sonyericsson.extras.liveware.extension.util.notification.NotificationUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.ConcurrentModificationException;
import java.util.HashSet;
import java.util.Timer;
import java.util.TimerTask;
public class Notifications {
public class Notification {
public int cid;
public int bid;
public long eid;
public String nick;
public String message;
public String network;
public String chan;
public String buffer_type;
public String message_type;
public boolean shown = false;
public String toString() {
return "{cid: " + cid + ", bid: " + bid + ", eid: " + eid + ", nick: " + nick + ", message: " + message + ", network: " + network + " shown: " + shown + "}";
}
}
public class comparator implements Comparator<Notification> {
public int compare(Notification n1, Notification n2) {
if (n1.cid != n2.cid)
return Integer.valueOf(n1.cid).compareTo(n2.cid);
else if (n1.bid != n2.bid)
return Integer.valueOf(n1.bid).compareTo(n2.bid);
else
return Long.valueOf(n1.eid).compareTo(n2.eid);
}
}
private ArrayList<Notification> mNotifications = null;
private SparseArray<String> mNetworks = null;
private SparseArray<Long> mLastSeenEIDs = null;
private SparseArray<HashSet<Long>> mDismissedEIDs = null;
private static Notifications instance = null;
private int excludeBid = -1;
private static final Timer mNotificationTimer = new Timer("notification-timer");
private TimerTask mNotificationTimerTask = null;
public static Notifications getInstance() {
if (instance == null)
instance = new Notifications();
return instance;
}
public Notifications() {
try {
load();
} catch (Exception e) {
}
}
private void load() {
mNotifications = new ArrayList<Notification>();
mNetworks = new SparseArray<String>();
mLastSeenEIDs = new SparseArray<Long>();
mDismissedEIDs = new SparseArray<HashSet<Long>>();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
if (prefs.contains("notifications_json")) {
try {
JSONArray array = new JSONArray(prefs.getString("networks_json", "[]"));
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
mNetworks.put(o.getInt("cid"), o.getString("network"));
}
array = new JSONArray(prefs.getString("lastseeneids_json", "[]"));
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
mLastSeenEIDs.put(o.getInt("bid"), o.getLong("eid"));
}
array = new JSONArray(prefs.getString("dismissedeids_json", "[]"));
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
int bid = o.getInt("bid");
mDismissedEIDs.put(bid, new HashSet<Long>());
JSONArray eids = o.getJSONArray("eids");
for (int j = 0; j < eids.length(); j++) {
mDismissedEIDs.get(bid).add(eids.getLong(j));
}
}
synchronized (mNotifications) {
array = new JSONArray(prefs.getString("notifications_json", "[]"));
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
Notification n = new Notification();
n.bid = o.getInt("bid");
n.cid = o.getInt("cid");
n.eid = o.getLong("eid");
n.nick = o.getString("nick");
n.message = o.getString("message");
n.chan = o.getString("chan");
n.buffer_type = o.getString("buffer_type");
n.message_type = o.getString("message_type");
n.network = mNetworks.get(n.cid);
if (o.has("shown"))
n.shown = o.getBoolean("shown");
mNotifications.add(n);
}
Collections.sort(mNotifications, new comparator());
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private static final Timer mSaveTimer = new Timer("notifications-save-timer");
private TimerTask mSaveTimerTask = null;
@TargetApi(9)
private void save() {
if (mSaveTimerTask != null)
mSaveTimerTask.cancel();
mSaveTimerTask = new TimerTask() {
@Override
public void run() {
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).edit();
try {
JSONArray array = new JSONArray();
synchronized (mNotifications) {
for (Notification n : mNotifications) {
if(n != null) {
JSONObject o = new JSONObject();
o.put("cid", n.cid);
o.put("bid", n.bid);
o.put("eid", n.eid);
o.put("nick", n.nick);
o.put("message", n.message);
o.put("chan", n.chan);
o.put("buffer_type", n.buffer_type);
o.put("message_type", n.message_type);
o.put("shown", n.shown);
array.put(o);
}
}
editor.putString("notifications_json", array.toString());
}
array = new JSONArray();
for (int i = 0; i < mNetworks.size(); i++) {
int cid = mNetworks.keyAt(i);
String network = mNetworks.get(cid);
JSONObject o = new JSONObject();
o.put("cid", cid);
o.put("network", network);
array.put(o);
}
editor.putString("networks_json", array.toString());
array = new JSONArray();
for (int i = 0; i < mLastSeenEIDs.size(); i++) {
int bid = mLastSeenEIDs.keyAt(i);
long eid = mLastSeenEIDs.get(bid);
JSONObject o = new JSONObject();
o.put("bid", bid);
o.put("eid", eid);
array.put(o);
}
editor.putString("lastseeneids_json", array.toString());
array = new JSONArray();
for (int i = 0; i < mDismissedEIDs.size(); i++) {
JSONArray a = new JSONArray();
int bid = mDismissedEIDs.keyAt(i);
HashSet<Long> eids = mDismissedEIDs.get(bid);
if(eids.size() > 0) {
for (long eid : eids) {
a.put(eid);
}
JSONObject o = new JSONObject();
o.put("bid", bid);
o.put("eids", a);
array.put(o);
}
}
editor.putString("dismissedeids_json", array.toString());
if (Build.VERSION.SDK_INT >= 9)
editor.apply();
else
editor.commit();
} catch (ConcurrentModificationException e) {
save();
} catch (OutOfMemoryError e) {
editor.remove("notifications_json");
editor.remove("networks_json");
editor.remove("lastseeneids_json");
editor.remove("dismissedeids_json");
editor.commit();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
try {
mSaveTimer.schedule(mSaveTimerTask, 100);
} catch (IllegalStateException e) {
//Timer is already cancelled
}
}
public void clearDismissed() {
mDismissedEIDs.clear();
save();
}
public void clear() {
try {
synchronized (mNotifications) {
if (mNotifications.size() > 0) {
for (Notification n : mNotifications) {
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel((int) (n.eid / 1000));
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel(n.bid);
}
}
}
IRCCloudApplication.getInstance().getApplicationContext().sendBroadcast(new Intent(DashClock.REFRESH_INTENT));
try {
if (PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).getBoolean("notify_sony", false))
NotificationUtil.deleteAllEvents(IRCCloudApplication.getInstance().getApplicationContext());
} catch (Exception e) {
//Sony LiveWare was probably removed
}
} catch (Exception e) {
e.printStackTrace();
}
if (mSaveTimerTask != null)
mSaveTimerTask.cancel();
mNotifications.clear();
mLastSeenEIDs.clear();
mDismissedEIDs.clear();
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).edit();
editor.remove("notifications_json");
editor.remove("lastseeneids_json");
editor.remove("dismissedeids_json");
editor.commit();
updateTeslaUnreadCount();
}
public void clearNetworks() {
mNetworks.clear();
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).edit();
editor.remove("networks_json");
editor.commit();
}
public void clearLastSeenEIDs() {
mLastSeenEIDs.clear();
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).edit();
editor.remove("lastseeneids_json");
editor.commit();
}
public long getLastSeenEid(int bid) {
if (mLastSeenEIDs.get(bid) != null)
return mLastSeenEIDs.get(bid);
else
return -1;
}
public synchronized void updateLastSeenEid(int bid, long eid) {
mLastSeenEIDs.put(bid, eid);
save();
}
public synchronized boolean isDismissed(int bid, long eid) {
if (mDismissedEIDs.get(bid) != null) {
for (Long e : mDismissedEIDs.get(bid)) {
if (e == eid)
return true;
}
}
return false;
}
public synchronized void dismiss(int bid, long eid) {
if (mDismissedEIDs.get(bid) == null)
mDismissedEIDs.put(bid, new HashSet<Long>());
mDismissedEIDs.get(bid).add(eid);
Notification n = getNotification(eid);
synchronized (mNotifications) {
if (n != null)
mNotifications.remove(n);
}
save();
if (IRCCloudApplication.getInstance() != null)
IRCCloudApplication.getInstance().getApplicationContext().sendBroadcast(new Intent(DashClock.REFRESH_INTENT));
updateTeslaUnreadCount();
}
public synchronized void addNetwork(int cid, String network) {
mNetworks.put(cid, network);
save();
}
public synchronized void deleteNetwork(int cid) {
mNetworks.remove(cid);
save();
}
public synchronized void addNotification(int cid, int bid, long eid, String from, String message, String chan, String buffer_type, String message_type) {
if (isDismissed(bid, eid)) {
Crashlytics.log("Refusing to add notification for dismissed eid: " + eid);
return;
}
long last_eid = getLastSeenEid(bid);
if (eid <= last_eid) {
Crashlytics.log("Refusing to add notification for seen eid: " + eid);
return;
}
String network = getNetwork(cid);
if (network == null)
addNetwork(cid, "Unknown Network");
Notification n = new Notification();
n.bid = bid;
n.cid = cid;
n.eid = eid;
n.nick = from;
n.message = TextUtils.htmlEncode(ColorFormatter.emojify(message));
n.chan = chan;
n.buffer_type = buffer_type;
n.message_type = message_type;
n.network = network;
synchronized (mNotifications) {
mNotifications.add(n);
Collections.sort(mNotifications, new comparator());
}
save();
}
public void deleteNotification(int cid, int bid, long eid) {
synchronized (mNotifications) {
for (Notification n : mNotifications) {
if (n.cid == cid && n.bid == bid && n.eid == eid) {
mNotifications.remove(n);
save();
return;
}
}
}
}
public void deleteOldNotifications(int bid, long last_seen_eid) {
boolean changed = false;
if (mNotificationTimerTask != null) {
mNotificationTimerTask.cancel();
}
ArrayList<Notification> notifications = getOtherNotifications();
if (notifications.size() > 0) {
for (Notification n : notifications) {
if (n.bid == bid && n.eid <= last_seen_eid) {
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel((int) (n.eid / 1000));
changed = true;
}
}
}
synchronized (mNotifications) {
for (int i = 0; i < mNotifications.size(); i++) {
Notification n = mNotifications.get(i);
if (n.bid == bid && n.eid <= last_seen_eid) {
mNotifications.remove(n);
i--;
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel(bid);
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel((int) (n.eid / 1000));
changed = true;
}
}
}
if (mDismissedEIDs.get(bid) != null) {
HashSet<Long> eids = mDismissedEIDs.get(bid);
Long[] eidsArray = eids.toArray(new Long[eids.size()]);
for (int i = 0; i < eidsArray.length; i++) {
if (eidsArray[i] <= last_seen_eid) {
eids.remove(eidsArray[i]);
}
}
}
save();
if (changed) {
IRCCloudApplication.getInstance().getApplicationContext().sendBroadcast(new Intent(DashClock.REFRESH_INTENT));
try {
if (PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).getBoolean("notify_sony", false))
NotificationUtil.deleteEvents(IRCCloudApplication.getInstance().getApplicationContext(), com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.FRIEND_KEY + " = ?", new String[]{String.valueOf(bid)});
} catch (Exception e) {
}
updateTeslaUnreadCount();
}
}
public void deleteNotificationsForBid(int bid) {
ArrayList<Notification> notifications = getOtherNotifications();
if (notifications.size() > 0) {
for (Notification n : notifications) {
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel((int) (n.eid / 1000));
}
}
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel(bid);
synchronized (mNotifications) {
for (int i = 0; i < mNotifications.size(); i++) {
Notification n = mNotifications.get(i);
if (n.bid == bid) {
mNotifications.remove(n);
i--;
}
}
}
mDismissedEIDs.remove(bid);
mLastSeenEIDs.remove(bid);
IRCCloudApplication.getInstance().getApplicationContext().sendBroadcast(new Intent(DashClock.REFRESH_INTENT));
try {
if (PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext()).getBoolean("notify_sony", false))
NotificationUtil.deleteEvents(IRCCloudApplication.getInstance().getApplicationContext(), com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.FRIEND_KEY + " = ?", new String[]{String.valueOf(bid)});
} catch (Exception e) {
//User has probably uninstalled Sony Liveware
}
updateTeslaUnreadCount();
}
private boolean isMessage(String type) {
return !(type.equalsIgnoreCase("channel_invite") || type.equalsIgnoreCase("callerid"));
}
public int count() {
return mNotifications.size();
}
public ArrayList<Notification> getMessageNotifications() {
ArrayList<Notification> notifications = new ArrayList<Notification>();
synchronized (mNotifications) {
for (int i = 0; i < mNotifications.size(); i++) {
Notification n = mNotifications.get(i);
if (n != null && n.bid != excludeBid && isMessage(n.message_type)) {
if (n.network == null)
n.network = getNetwork(n.cid);
notifications.add(n);
}
}
}
return notifications;
}
public ArrayList<Notification> getOtherNotifications() {
ArrayList<Notification> notifications = new ArrayList<Notification>();
synchronized (mNotifications) {
for (int i = 0; i < mNotifications.size(); i++) {
Notification n = mNotifications.get(i);
if (n != null && n.bid != excludeBid && !isMessage(n.message_type)) {
if (n.network == null)
n.network = getNetwork(n.cid);
notifications.add(n);
}
}
}
return notifications;
}
public String getNetwork(int cid) {
return mNetworks.get(cid);
}
public Notification getNotification(long eid) {
synchronized (mNotifications) {
for (int i = 0; i < mNotifications.size(); i++) {
Notification n = mNotifications.get(i);
if (n.bid != excludeBid && n.eid == eid && isMessage(n.message_type)) {
if (n.network == null)
n.network = getNetwork(n.cid);
return n;
}
}
}
return null;
}
public synchronized void excludeBid(int bid) {
excludeBid = -1;
ArrayList<Notification> notifications = getOtherNotifications();
if (notifications.size() > 0) {
for (Notification n : notifications) {
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel((int) (n.eid / 1000));
}
}
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).cancel(bid);
excludeBid = bid;
}
private String mTicker = null;
public synchronized void showNotifications(String ticker) {
if (ticker != null)
mTicker = ColorFormatter.emojify(ticker);
ArrayList<Notification> notifications = getMessageNotifications();
for (Notification n : notifications) {
if (isDismissed(n.bid, n.eid)) {
deleteNotification(n.cid, n.bid, n.eid);
}
}
if (mNotificationTimerTask != null)
mNotificationTimerTask.cancel();
try {
mNotificationTimerTask = new TimerTask() {
@Override
public void run() {
showMessageNotifications(mTicker);
showOtherNotifications();
mTicker = null;
IRCCloudApplication.getInstance().getApplicationContext().sendBroadcast(new Intent(DashClock.REFRESH_INTENT));
updateTeslaUnreadCount();
}
};
mNotificationTimer.schedule(mNotificationTimerTask, 5000);
} catch (Exception e) {
e.printStackTrace();
Crashlytics.logException(e);
}
}
private void showOtherNotifications() {
String title = "";
String text = "";
String ticker = null;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
ArrayList<Notification> notifications = getOtherNotifications();
int notify_type = Integer.parseInt(prefs.getString("notify_type", "1"));
boolean notify = false;
if (notify_type == 1 || (notify_type == 2 && NetworkConnection.getInstance().isVisible()))
notify = true;
if (notifications.size() > 0 && notify) {
for (Notification n : notifications) {
if (!n.shown) {
if (n.message_type.equals("callerid")) {
title = "Callerid: " + n.nick + " (" + n.network + ")";
text = n.nick + " " + n.message;
ticker = n.nick + " " + n.message;
} else {
title = n.nick + " (" + n.network + ")";
text = n.message;
ticker = n.message;
}
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).notify((int) (n.eid / 1000), buildNotification(ticker, n.bid, new long[]{n.eid}, title, text, Html.fromHtml(text), 1, null, null, title, null));
n.shown = true;
}
}
}
}
@SuppressLint("NewApi")
private android.app.Notification buildNotification(String ticker, int bid, long[] eids, String title, String text, Spanned big_text, int count, Intent replyIntent, Spanned wear_text, String network, String auto_messages[]) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
NotificationCompat.Builder builder = new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext())
.setContentTitle(title + ((network != null) ? (" (" + network + ")") : ""))
.setContentText(Html.fromHtml(text))
.setAutoCancel(true)
.setTicker(ticker)
.setWhen(eids[0] / 1000)
.setSmallIcon(R.drawable.ic_stat_notify)
.setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources().getColor(R.color.dark_blue))
.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
.setCategory(NotificationCompat.CATEGORY_MESSAGE)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setOnlyAlertOnce(false);
if (ticker != null && (System.currentTimeMillis() - prefs.getLong("lastNotificationTime", 0)) > 10000) {
if (prefs.getBoolean("notify_vibrate", true))
builder.setDefaults(android.app.Notification.DEFAULT_VIBRATE);
String ringtone = prefs.getString("notify_ringtone", "content://settings/system/notification_sound");
if (ringtone != null && ringtone.length() > 0)
builder.setSound(Uri.parse(ringtone));
}
int led_color = Integer.parseInt(prefs.getString("notify_led_color", "1"));
if (led_color == 1) {
if (prefs.getBoolean("notify_vibrate", true))
builder.setDefaults(android.app.Notification.DEFAULT_LIGHTS | android.app.Notification.DEFAULT_VIBRATE);
else
builder.setDefaults(android.app.Notification.DEFAULT_LIGHTS);
} else if (led_color == 2) {
builder.setLights(0xFF0000FF, 500, 500);
}
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("lastNotificationTime", System.currentTimeMillis());
editor.commit();
Intent i = new Intent();
i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), "com.irccloud.android.MainActivity"));
i.putExtra("bid", bid);
i.setData(Uri.parse("bid://" + bid));
Intent dismiss = new Intent(IRCCloudApplication.getInstance().getApplicationContext().getResources().getString(R.string.DISMISS_NOTIFICATION));
dismiss.setData(Uri.parse("irccloud-dismiss://" + bid));
dismiss.putExtra("bid", bid);
dismiss.putExtra("eids", eids);
PendingIntent dismissPendingIntent = PendingIntent.getBroadcast(IRCCloudApplication.getInstance().getApplicationContext(), 0, dismiss, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT));
builder.setDeleteIntent(dismissPendingIntent);
if (replyIntent != null) {
WearableExtender extender = new WearableExtender();
PendingIntent replyPendingIntent = PendingIntent.getService(IRCCloudApplication.getInstance().getApplicationContext(), bid + 1, replyIntent, PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT);
extender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_reply,
"Reply", replyPendingIntent)
.addRemoteInput(new RemoteInput.Builder("extra_reply").setLabel("Reply").build()).build());
if (count > 1 && wear_text != null)
extender.addPage(new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext()).setContentText(wear_text).extend(new WearableExtender().setStartScrollBottom(true)).build());
NotificationCompat.CarExtender.UnreadConversation.Builder unreadConvBuilder =
new NotificationCompat.CarExtender.UnreadConversation.Builder(title + ((network != null) ? (" (" + network + ")") : ""))
.setReadPendingIntent(dismissPendingIntent)
.setReplyAction(replyPendingIntent, new RemoteInput.Builder("extra_reply").setLabel("Reply").build());
if (auto_messages != null) {
for (String m : auto_messages) {
if (m != null && m.length() > 0) {
unreadConvBuilder.addMessage(m);
}
}
} else {
unreadConvBuilder.addMessage(text);
}
unreadConvBuilder.setLatestTimestamp(eids[count - 1] / 1000);
builder.extend(extender).extend(new NotificationCompat.CarExtender().setUnreadConversation(unreadConvBuilder.build()));
}
if(replyIntent != null) {
i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
i.setData(Uri.parse("irccloud-bid://" + bid));
i.putExtras(replyIntent);
PendingIntent quickReplyIntent = PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(R.drawable.ic_action_reply, "Reply", quickReplyIntent);
}
RemoteViews contentView = new RemoteViews(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), R.layout.notification);
contentView.setTextViewText(R.id.title, title + " (" + network + ")");
contentView.setTextViewText(R.id.text, (count == 1) ? Html.fromHtml(text) : (count + " unread highlights."));
contentView.setLong(R.id.time, "setTime", eids[0] / 1000);
builder.setContent(contentView);
android.app.Notification notification = builder.build();
if (Build.VERSION.SDK_INT >= 16 && big_text != null) {
RemoteViews bigContentView = new RemoteViews(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), R.layout.notification_expanded);
bigContentView.setTextViewText(R.id.title, title + (!title.equals(network) ? (" (" + network + ")") : ""));
bigContentView.setTextViewText(R.id.text, big_text);
bigContentView.setLong(R.id.time, "setTime", eids[0] / 1000);
if (count > 3) {
bigContentView.setViewVisibility(R.id.more, View.VISIBLE);
bigContentView.setTextViewText(R.id.more, "+" + (count - 3) + " more");
} else {
bigContentView.setViewVisibility(R.id.more, View.GONE);
}
if(replyIntent != null) {
bigContentView.setViewVisibility(R.id.actions, View.VISIBLE);
bigContentView.setViewVisibility(R.id.action_divider, View.VISIBLE);
i = new Intent(IRCCloudApplication.getInstance().getApplicationContext(), QuickReplyActivity.class);
i.setData(Uri.parse("irccloud-bid://" + bid));
i.putExtras(replyIntent);
PendingIntent quickReplyIntent = PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
bigContentView.setOnClickPendingIntent(R.id.action_reply, quickReplyIntent);
}
notification.bigContentView = bigContentView;
}
return notification;
}
private void notifyPebble(String title, String body) {
JSONObject jsonData = new JSONObject();
try {
final Intent i = new Intent("com.getpebble.action.SEND_NOTIFICATION");
jsonData.put("title", title);
jsonData.put("body", body);
final String notificationData = new JSONArray().put(jsonData).toString();
i.putExtra("messageType", "PEBBLE_ALERT");
i.putExtra("sender", "IRCCloud");
i.putExtra("notificationData", notificationData);
IRCCloudApplication.getInstance().getApplicationContext().sendBroadcast(i);
} catch (Exception e) {
e.printStackTrace();
}
}
private void showMessageNotifications(String ticker) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(IRCCloudApplication.getInstance().getApplicationContext());
String text = "";
String weartext = "";
ArrayList<Notification> notifications = getMessageNotifications();
int notify_type = Integer.parseInt(prefs.getString("notify_type", "1"));
boolean notify = false;
if (notify_type == 1 || (notify_type == 2 && NetworkConnection.getInstance().isVisible()))
notify = true;
if (notifications.size() > 0 && notify) {
int lastbid = notifications.get(0).bid;
int count = 0;
long[] eids = new long[notifications.size()];
String[] auto_messages = new String[notifications.size()];
Notification last = null;
count = 0;
boolean show = false;
for (Notification n : notifications) {
if (n.bid != lastbid) {
if (show) {
String title = last.chan;
if (title == null || title.length() == 0)
title = last.nick;
if (title == null || title.length() == 0)
title = last.network;
Intent replyIntent = new Intent(RemoteInputService.ACTION_REPLY);
replyIntent.putExtra("bid", last.bid);
replyIntent.putExtra("cid", last.cid);
replyIntent.putExtra("eids", eids);
replyIntent.putExtra("network", last.network);
if (last.buffer_type.equals("channel"))
replyIntent.putExtra("to", last.chan);
else
replyIntent.putExtra("to", last.nick);
String body = "";
if (last.buffer_type.equals("channel")) {
if (last.message_type.equals("buffer_me_msg"))
body = "<b>— " + last.nick + "</b> " + last.message;
else
body = "<b><" + last.nick + "></b> " + last.message;
} else {
if (last.message_type.equals("buffer_me_msg"))
body = "— " + last.nick + " " + last.message;
else
body = last.message;
}
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).notify(lastbid, buildNotification(ticker, lastbid, eids, title, body, Html.fromHtml(text), count, replyIntent, Html.fromHtml(weartext), last.network, auto_messages));
}
lastbid = n.bid;
text = "";
weartext = "";
count = 0;
eids = new long[notifications.size()];
show = false;
auto_messages = new String[notifications.size()];
}
if (count < 3) {
if (text.length() > 0)
text += "<br/>";
if (n.buffer_type.equals("conversation") && n.message_type.equals("buffer_me_msg"))
text += "— " + n.message;
else if (n.buffer_type.equals("conversation"))
text += n.message;
else if (n.message_type.equals("buffer_me_msg"))
text += "<b>— " + n.nick + "</b> " + n.message;
else
text += "<b>" + n.nick + "</b> " + n.message;
}
if (weartext.length() > 0)
weartext += "<br/><br/>";
if (n.message_type.equals("buffer_me_msg"))
weartext += "<b>— " + n.nick + "</b> " + n.message;
else
weartext += "<b><" + n.nick + "></b> " + n.message;
if (n.buffer_type.equals("conversation")) {
if (n.message_type.equals("buffer_me_msg"))
auto_messages[count] = "— " + n.nick + " " + Html.fromHtml(n.message).toString();
else
auto_messages[count] = Html.fromHtml(n.message).toString();
} else {
if (n.message_type.equals("buffer_me_msg"))
auto_messages[count] = "— " + n.nick + " " + Html.fromHtml(n.message).toString();
else
auto_messages[count] = n.nick + " said: " + Html.fromHtml(n.message).toString();
}
if (!n.shown) {
n.shown = true;
show = true;
if (prefs.getBoolean("notify_sony", false)) {
long time = System.currentTimeMillis();
long sourceId = NotificationUtil.getSourceId(IRCCloudApplication.getInstance().getApplicationContext(), SonyExtensionService.EXTENSION_SPECIFIC_ID);
if (sourceId == NotificationUtil.INVALID_ID) {
Crashlytics.log(Log.ERROR, "IRCCloud", "Sony LiveWare Manager not configured, disabling Sony notifications");
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("notify_sony", false);
editor.commit();
} else {
ContentValues eventValues = new ContentValues();
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.EVENT_READ_STATUS, false);
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.DISPLAY_NAME, n.nick);
if (n.buffer_type.equals("channel") && n.chan != null && n.chan.length() > 0)
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.TITLE, n.chan);
else
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.TITLE, n.network);
if (n.message_type.equals("buffer_me_msg"))
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.MESSAGE, "— " + Html.fromHtml(n.message).toString());
else
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.MESSAGE, Html.fromHtml(n.message).toString());
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.PERSONAL, 1);
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.PUBLISHED_TIME, time);
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.SOURCE_ID, sourceId);
eventValues.put(com.sonyericsson.extras.liveware.aef.notification.Notification.EventColumns.FRIEND_KEY, String.valueOf(n.bid));
try {
IRCCloudApplication.getInstance().getApplicationContext().getContentResolver().insert(com.sonyericsson.extras.liveware.aef.notification.Notification.Event.URI, eventValues);
} catch (IllegalArgumentException e) {
Log.e("IRCCloud", "Failed to insert event", e);
} catch (SecurityException e) {
Log.e("IRCCloud", "Failed to insert event, is Live Ware Manager installed?", e);
} catch (SQLException e) {
Log.e("IRCCloud", "Failed to insert event", e);
}
}
}
if (prefs.getBoolean("notify_pebble", false)) {
String pebbleTitle = n.network + ":\n";
String pebbleBody = "";
if (n.buffer_type.equals("channel") && n.chan != null && n.chan.length() > 0)
pebbleTitle = n.chan + ":\n";
if (n.message_type.equals("buffer_me_msg"))
pebbleBody = "— " + n.message;
else
pebbleBody = n.message;
if (n.nick != null && n.nick.length() > 0)
notifyPebble(n.nick, pebbleTitle + Html.fromHtml(pebbleBody).toString());
else
notifyPebble(n.network, pebbleTitle + Html.fromHtml(pebbleBody).toString());
}
}
eids[count++] = n.eid;
last = n;
}
if (show) {
String title = last.chan;
if (title == null || title.length() == 0)
title = last.nick;
if (title == null || title.length() == 0)
title = last.network;
Intent replyIntent = new Intent(RemoteInputService.ACTION_REPLY);
replyIntent.putExtra("bid", last.bid);
replyIntent.putExtra("cid", last.cid);
replyIntent.putExtra("network", last.network);
replyIntent.putExtra("eids", eids);
if (last.buffer_type.equals("channel"))
replyIntent.putExtra("to", last.chan);
else
replyIntent.putExtra("to", last.nick);
String body = "";
if (last.buffer_type.equals("channel")) {
if (last.message_type.equals("buffer_me_msg"))
body = "<b>— " + last.nick + "</b> " + last.message;
else
body = "<b><" + last.nick + "></b> " + last.message;
} else {
if (last.message_type.equals("buffer_me_msg"))
body = "— " + last.nick + " " + last.message;
else
body = last.message;
}
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).notify(lastbid, buildNotification(ticker, lastbid, eids, title, body, Html.fromHtml(text), count, replyIntent, Html.fromHtml(weartext), last.network, auto_messages));
}
}
}
public NotificationCompat.Builder alert(int bid, String title, String body) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(IRCCloudApplication.getInstance().getApplicationContext())
.setContentTitle(title)
.setContentText(body)
.setTicker(body)
.setAutoCancel(true)
.setColor(IRCCloudApplication.getInstance().getApplicationContext().getResources().getColor(R.color.dark_blue))
.setSmallIcon(R.drawable.ic_stat_notify);
Intent i = new Intent();
i.setComponent(new ComponentName(IRCCloudApplication.getInstance().getApplicationContext().getPackageName(), "com.irccloud.android.MainActivity"));
i.putExtra("bid", bid);
i.setData(Uri.parse("bid://" + bid));
builder.setContentIntent(PendingIntent.getActivity(IRCCloudApplication.getInstance().getApplicationContext(), 0, i, PendingIntent.FLAG_UPDATE_CURRENT));
NotificationManagerCompat.from(IRCCloudApplication.getInstance().getApplicationContext()).notify(bid, builder.build());
return builder;
}
public void updateTeslaUnreadCount() {
try {
IRCCloudApplication.getInstance().getApplicationContext().getPackageManager().getPackageInfo("com.teslacoilsw.notifier", PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
return;
}
int count = 0;
synchronized (mNotifications) {
for (int i = 0; i < mNotifications.size(); i++) {
Notification n = mNotifications.get(i);
if (n.bid != excludeBid) {
count++;
}
}
}
try {
ContentValues cv = new ContentValues();
cv.put("tag", IRCCloudApplication.getInstance().getApplicationContext().getPackageManager().getLaunchIntentForPackage(IRCCloudApplication.getInstance().getApplicationContext().getPackageName()).getComponent().flattenToString());
cv.put("count", count);
IRCCloudApplication.getInstance().getApplicationContext().getContentResolver().insert(Uri.parse("content://com.teslacoilsw.notifier/unread_count"), cv);
} catch (IllegalArgumentException ex) {
} catch (Exception ex) {
ex.printStackTrace();
}
}
} | fix missing Gingerbread notification layout
| src/com/irccloud/android/Notifications.java | fix missing Gingerbread notification layout |
|
Java | bsd-2-clause | 145472d6ccd6e0f68fa0642533e6723f35cd0fd1 | 0 | cppchriscpp/TravelPortals | package net.cpprograms.minecraft.TravelPortals.storage;
import net.cpprograms.minecraft.TravelPortals.WarpLocation;
import org.bukkit.Location;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public abstract class PortalStorage {
private Map<String, WarpLocation> portals = new LinkedHashMap<>();
private Map<String, String> portalNames = new LinkedHashMap<>();
private Map<String, String> portalLocations = new LinkedHashMap<>();
/**
* Load the data from the storage
* @return true if it succeeded; false if it failed
*/
public abstract boolean load();
/**
* Save data of a portal to the storage
* @return true if it succeeded; false if it failed
*/
public abstract boolean save(WarpLocation portal);
/**
* Save data of a all portals in a world
* @return true if it succeeded; false if it failed
*/
public abstract boolean save(String worldName);
/**
* Save all data to the storage
* @return true if it succeeded; false if it failed
*/
public abstract boolean save();
/**
* Get the type of this storage
* @return The type of this storage
*/
public abstract StorageType getType();
/**
* This gets all portals
* @return A list with all portals
*/
public Map<String, WarpLocation> getPortals() {
return portals;
}
/**
* Add a new portal
* @param portal The info of the portal
*/
public void addPortal(WarpLocation portal) {
WarpLocation previous = portals.put(portal.getIdentifierString(), portal);
if (previous != null && !portal.hasName()) {
portal.setName(previous.getName());
}
if (portal.hasName()) {
portalNames.put(portal.getName(), portal.getIdentifierString());
}
portalLocations.put(portal.getWorld() + "," + portal.getX() + "," + portal.getY() + "," + portal.getZ(), portal.getIdentifierString());
portalLocations.put(portal.getWorld() + "," + portal.getX() + "," + portal.getY() + 1 + "," + portal.getZ(), portal.getIdentifierString());
}
/**
* Get portal by it's name
* @param name The name of the portal
* @return The portal info or null if none was found
*/
public WarpLocation getPortal(String name) {
String identifier = portalNames.get(name);
if (identifier == null) {
return null;
}
return portals.get(identifier);
}
/**
* Get a portal at that location
* @param location The location to get a portal at
* @return The Portal or null if none was found
*/
public WarpLocation getPortal(Location location) {
String portalIdentifier = portalLocations.get(location.getWorld().getName() + "," + location.getBlockX() + "," + location.getBlockY() + "," + location.getBlockZ());
if (portalIdentifier == null) {
portalIdentifier = portalLocations.get("," + location.getBlockX() + "," + location.getBlockY() + "," + location.getBlockZ());
}
if (portalIdentifier != null) {
if (portals.containsKey(portalIdentifier)) {
return portals.get(portalIdentifier);
} else {
portalLocations.remove(portalIdentifier);
}
}
return null;
}
/**
* Get the closest nearby portal
* @param location The location to get a portal at
* @param radius The radius in blocks to search in
* @return The Portal or null if none was found
*/
public WarpLocation getNearbyPortal(Location location, int radius) {
WarpLocation exact = getPortal(location);
if (exact != null) {
return exact;
}
Set<WarpLocation> nearbyPortals = new HashSet<>();
Location loopLocation = location.clone();
loopLocation.subtract(radius, radius, radius);
for (int x = -radius; x <= radius; x++) {
for (int z = -radius; z <= radius; z++) {
for (int y = -radius; y <= radius; y++) {
WarpLocation portal = getPortal(loopLocation);
if (portal != null && !nearbyPortals.contains(portal)) {
nearbyPortals.add(portal);
}
loopLocation.add(0, 1, 0);
}
loopLocation.add(0, 0, 1);
}
loopLocation.add(1, 0, 0);
}
if (nearbyPortals.size() == 1) {
return nearbyPortals.iterator().next();
} else if (!nearbyPortals.isEmpty()){
WarpLocation closest = null;
int closestDist = -1;
for (WarpLocation portal : nearbyPortals) {
int distance = Math.abs((location.getBlockX() - portal.getX()) * (location.getBlockY() - portal.getY()) * (location.getBlockZ() - portal.getZ()));
if (closest == null || closestDist > distance) {
closest = portal;
closestDist = distance;
}
}
return closest;
}
return null;
}
/**
* Remove a portal
* @param portal The portal to remove
*/
public void namePortal(WarpLocation portal, String name) {
removePortal(portal);
portal.setName(name);
addPortal(portal);
save(portal);
}
/**
* Remove a portal
* @param portal The portal to remove
*/
public void removePortal(WarpLocation portal) {
portals.remove(portal.getIdentifierString());
portalNames.remove(portal.getName().toLowerCase());
portalLocations.remove(portal.getWorld() + "," + portal.getX() + "," + portal.getY() + "," + portal.getZ());
portalLocations.remove(portal.getWorld() + "," + portal.getX() + "," + portal.getY() + 1 + "," + portal.getZ());
}
/**
* Rename a world for all existing portals.
* @param oldWorld The name of the old world.
* @param newWorld The name of the new world.
* @return true if it succeeded; false if it failed
*/
public boolean renameWorld(String oldWorld, String newWorld) {
for (WarpLocation portal : portals.values()) {
if (oldWorld.equalsIgnoreCase(portal.getWorld())) {
portal.setWorld(newWorld);
}
}
return save(newWorld);
}
/**
* Delete all portals linking to a world.
* @param world The world to delete all portals to.
* @return true if it succeeded; false if it failed
*/
public boolean deleteWorld(String world) {
for (WarpLocation portal : portals.values()) {
if (world.equalsIgnoreCase(portal.getWorld())) {
removePortal(portal);
}
}
return save(world);
}
/**
* This deletes all portals from the cache
*/
public void clearCache() {
portals.clear();
portalLocations.clear();
}
}
| src/main/java/net/cpprograms/minecraft/TravelPortals/storage/PortalStorage.java | package net.cpprograms.minecraft.TravelPortals.storage;
import net.cpprograms.minecraft.TravelPortals.WarpLocation;
import org.bukkit.Location;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public abstract class PortalStorage {
private Map<String, WarpLocation> portals = new LinkedHashMap<>();
private Map<String, String> portalNames = new LinkedHashMap<>();
private Map<String, String> portalLocations = new LinkedHashMap<>();
/**
* Load the data from the storage
* @return true if it succeeded; false if it failed
*/
public abstract boolean load();
/**
* Save data of a portal to the storage
* @return true if it succeeded; false if it failed
*/
public abstract boolean save(WarpLocation portal);
/**
* Save data of a all portals in a world
* @return true if it succeeded; false if it failed
*/
public abstract boolean save(String worldName);
/**
* Save all data to the storage
* @return true if it succeeded; false if it failed
*/
public abstract boolean save();
/**
* Get the type of this storage
* @return The type of this storage
*/
public abstract StorageType getType();
/**
* This gets all portals
* @return A list with all portals
*/
public Map<String, WarpLocation> getPortals() {
return portals;
}
/**
* Add a new portal
* @param portal The info of the portal
*/
public void addPortal(WarpLocation portal) {
portals.put(portal.getIdentifierString(), portal);
if (portal.hasName()) {
portalNames.put(portal.getName(), portal.getIdentifierString());
}
portalLocations.put(portal.getWorld() + "," + portal.getX() + "," + portal.getY() + "," + portal.getZ(), portal.getIdentifierString());
portalLocations.put(portal.getWorld() + "," + portal.getX() + "," + portal.getY() + 1 + "," + portal.getZ(), portal.getIdentifierString());
}
/**
* Get portal by it's name
* @param name The name of the portal
* @return The portal info or null if none was found
*/
public WarpLocation getPortal(String name) {
String identifier = portalNames.get(name);
if (identifier == null) {
return null;
}
return portals.get(identifier);
}
/**
* Get a portal at that location
* @param location The location to get a portal at
* @return The Portal or null if none was found
*/
public WarpLocation getPortal(Location location) {
String portalIdentifier = portalLocations.get(location.getWorld().getName() + "," + location.getBlockX() + "," + location.getBlockY() + "," + location.getBlockZ());
if (portalIdentifier == null) {
portalIdentifier = portalLocations.get("," + location.getBlockX() + "," + location.getBlockY() + "," + location.getBlockZ());
}
if (portalIdentifier != null) {
if (portals.containsKey(portalIdentifier)) {
return portals.get(portalIdentifier);
} else {
portalLocations.remove(portalIdentifier);
}
}
return null;
}
/**
* Get the closest nearby portal
* @param location The location to get a portal at
* @param radius The radius in blocks to search in
* @return The Portal or null if none was found
*/
public WarpLocation getNearbyPortal(Location location, int radius) {
WarpLocation exact = getPortal(location);
if (exact != null) {
return exact;
}
Set<WarpLocation> nearbyPortals = new HashSet<>();
Location loopLocation = location.clone();
loopLocation.subtract(radius, radius, radius);
for (int x = -radius; x <= radius; x++) {
for (int z = -radius; z <= radius; z++) {
for (int y = -radius; y <= radius; y++) {
WarpLocation portal = getPortal(loopLocation);
if (portal != null && !nearbyPortals.contains(portal)) {
nearbyPortals.add(portal);
}
loopLocation.add(0, 1, 0);
}
loopLocation.add(0, 0, 1);
}
loopLocation.add(1, 0, 0);
}
if (nearbyPortals.size() == 1) {
return nearbyPortals.iterator().next();
} else if (!nearbyPortals.isEmpty()){
WarpLocation closest = null;
int closestDist = -1;
for (WarpLocation portal : nearbyPortals) {
int distance = Math.abs((location.getBlockX() - portal.getX()) * (location.getBlockY() - portal.getY()) * (location.getBlockZ() - portal.getZ()));
if (closest == null || closestDist > distance) {
closest = portal;
closestDist = distance;
}
}
return closest;
}
return null;
}
/**
* Remove a portal
* @param portal The portal to remove
*/
public void namePortal(WarpLocation portal, String name) {
removePortal(portal);
portal.setName(name);
addPortal(portal);
save(portal);
}
/**
* Remove a portal
* @param portal The portal to remove
*/
public void removePortal(WarpLocation portal) {
portals.remove(portal.getIdentifierString());
portalNames.remove(portal.getName().toLowerCase());
portalLocations.remove(portal.getWorld() + "," + portal.getX() + "," + portal.getY() + "," + portal.getZ());
portalLocations.remove(portal.getWorld() + "," + portal.getX() + "," + portal.getY() + 1 + "," + portal.getZ());
}
/**
* Rename a world for all existing portals.
* @param oldWorld The name of the old world.
* @param newWorld The name of the new world.
* @return true if it succeeded; false if it failed
*/
public boolean renameWorld(String oldWorld, String newWorld) {
for (WarpLocation portal : portals.values()) {
if (oldWorld.equalsIgnoreCase(portal.getWorld())) {
portal.setWorld(newWorld);
}
}
return save(newWorld);
}
/**
* Delete all portals linking to a world.
* @param world The world to delete all portals to.
* @return true if it succeeded; false if it failed
*/
public boolean deleteWorld(String world) {
for (WarpLocation portal : portals.values()) {
if (world.equalsIgnoreCase(portal.getWorld())) {
removePortal(portal);
}
}
return save(world);
}
/**
* This deletes all portals from the cache
*/
public void clearCache() {
portals.clear();
portalLocations.clear();
}
}
| Use replaced portal's name if the new portal doesn't have one
| src/main/java/net/cpprograms/minecraft/TravelPortals/storage/PortalStorage.java | Use replaced portal's name if the new portal doesn't have one |
|
Java | bsd-3-clause | 2628351f1bde78036c1499a69b19f834592dba19 | 0 | dhis2/dhis2-core,msf-oca-his/dhis2-core,dhis2/dhis2-core,dhis2/dhis2-core,hispindia/dhis2-Core,hispindia/dhis2-Core,hispindia/dhis2-Core,msf-oca-his/dhis2-core,dhis2/dhis2-core,hispindia/dhis2-Core,hispindia/dhis2-Core,dhis2/dhis2-core,msf-oca-his/dhis2-core,msf-oca-his/dhis2-core,msf-oca-his/dhis2-core | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.util;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.hisp.dhis.calendar.DateTimeUnit;
import org.hisp.dhis.i18n.I18nFormat;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodType;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.IllegalInstantException;
import org.joda.time.LocalDate;
import org.joda.time.Months;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import org.joda.time.format.DateTimeParser;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.ObjectArrays;
/**
* @author Lars Helge Overland
*/
public class DateUtils
{
public static final String ISO8601_NO_TZ_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS";
private static DateTimeFormatter ISO8601_NO_TZ = DateTimeFormat.forPattern( ISO8601_NO_TZ_PATTERN );
public static final String ISO8601_PATTERN = ISO8601_NO_TZ_PATTERN + "Z";
private static DateTimeFormatter ISO8601 = DateTimeFormat.forPattern( ISO8601_PATTERN );
private static final String DEFAULT_DATE_REGEX = "\\b(?<year>\\d{4})-(?<month>0[1-9]|1[0-2])-(?<day>0[1-9]|[1-2][0-9]|3[0-2])(?<time>.*)\\b";
private static final Pattern DEFAULT_DATE_REGEX_PATTERN = Pattern.compile( DEFAULT_DATE_REGEX );
private static final DateTimeParser[] SUPPORTED_DATE_ONLY_PARSERS = {
DateTimeFormat.forPattern( "yyyy-MM-dd" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM" ).getParser(),
DateTimeFormat.forPattern( "yyyy" ).getParser()
};
private static final DateTimeParser[] SUPPORTED_DATE_TIME_FORMAT_PARSERS = {
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSZ" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSSSS" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSSZ" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSS" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSS" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ssZ" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mmZ" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HHZ" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd HH:mm:ssZ" ).getParser()
};
private static final DateTimeParser[] SUPPORTED_DATE_FORMAT_PARSERS = ObjectArrays
.concat( SUPPORTED_DATE_ONLY_PARSERS, SUPPORTED_DATE_TIME_FORMAT_PARSERS, DateTimeParser.class );
private static final DateTimeFormatter DATE_FORMATTER = new DateTimeFormatterBuilder()
.append( null, SUPPORTED_DATE_FORMAT_PARSERS ).toFormatter();
private static final DateTimeFormatter DATE_TIME_FORMAT = new DateTimeFormatterBuilder()
.append( null, SUPPORTED_DATE_TIME_FORMAT_PARSERS ).toFormatter();
public static final PeriodFormatter DAY_SECOND_FORMAT = new PeriodFormatterBuilder()
.appendDays().appendSuffix( " d" ).appendSeparator( ", " )
.appendHours().appendSuffix( " h" ).appendSeparator( ", " )
.appendMinutes().appendSuffix( " m" ).appendSeparator( ", " )
.appendSeconds().appendSuffix( " s" ).appendSeparator( ", " ).toFormatter();
private static final DateTimeFormatter MEDIUM_DATE_FORMAT = DateTimeFormat.forPattern( "yyyy-MM-dd" );
private static final DateTimeFormatter LONG_DATE_FORMAT = DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss" );
private static final DateTimeFormatter HTTP_DATE_FORMAT = DateTimeFormat
.forPattern( "EEE, dd MMM yyyy HH:mm:ss 'GMT'" ).withLocale( Locale.ENGLISH );
private static final DateTimeFormatter TIMESTAMP_UTC_TZ_FORMAT = DateTimeFormat
.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" ).withZoneUTC();
public static final double DAYS_IN_YEAR = 365.0;
private static final long MS_PER_DAY = 86400000;
private static final long MS_PER_S = 1000;
private static final Pattern DURATION_PATTERN = Pattern.compile( "^(\\d+)(d|h|m|s)$" );
private static final Map<String, ChronoUnit> TEMPORAL_MAP = ImmutableMap.of(
"d", ChronoUnit.DAYS, "h", ChronoUnit.HOURS, "m", ChronoUnit.MINUTES, "s", ChronoUnit.SECONDS );
/**
* Returns date formatted as ISO 8601
*/
public static String getIso8601( Date date )
{
return date != null ? ISO8601.print( new DateTime( date ) ) : null;
}
/**
* Returns date formatted as ISO 8601, without any TZ info
*/
public static String getIso8601NoTz( Date date )
{
return date != null ? ISO8601_NO_TZ.print( new DateTime( date ) ) : null;
}
/**
* Converts a Date to the GMT timezone and formats it to the format
* yyyy-MM-dd HH:mm:ssZ.
*
* @param date the Date to parse.
* @return A formatted date string.
*/
public static String getLongGmtDateString( Date date )
{
return date != null ? TIMESTAMP_UTC_TZ_FORMAT.print( new DateTime( date ) ) : null;
}
/**
* Formats a Date to the format yyyy-MM-dd HH:mm:ss.
*
* @param date the Date to parse.
* @return A formatted date string.
*/
public static String getLongDateString( Date date )
{
return date != null ? LONG_DATE_FORMAT.print( new DateTime( date ) ) : null;
}
/**
* Formats a Date to the format yyyy-MM-dd HH:mm:ss.
*
* @return A formatted date string.
*/
public static String getLongDateString()
{
return getLongDateString( Calendar.getInstance().getTime() );
}
/**
* Formats a Date to the format yyyy-MM-dd.
*
* @param date the Date to parse.
* @return A formatted date string. Null if argument is null.
*/
public static String getMediumDateString( Date date )
{
return date != null ? MEDIUM_DATE_FORMAT.print( new DateTime( date ) ) : null;
}
/**
* Formats the current Date to the format YYYY-MM-DD.
*
* @return A formatted date string.
*/
public static String getMediumDateString()
{
return getMediumDateString( Calendar.getInstance().getTime() );
}
/**
* Formats a Date according to the HTTP specification standard date format.
*
* @param date the Date to format.
* @return a formatted string.
*/
public static String getHttpDateString( Date date )
{
return date != null ? (HTTP_DATE_FORMAT.print( new DateTime( date ) )) : null;
}
/**
* Returns the latest of the two given dates.
*
* @param date1 the first date, can be null.
* @param date2 the second date, can be null.
* @return the latest of the two given dates.
*/
public static Date max( Date date1, Date date2 )
{
if ( date1 == null )
{
return date2;
}
return date2 != null ? (date1.after( date2 ) ? date1 : date2) : date1;
}
/**
* Returns the latest of the given dates.
*
* @param dates the collection of dates.
* @return the latest of the given dates.
*/
public static Date max( Collection<Date> dates )
{
Date latest = null;
for ( Date d : dates )
{
latest = max( d, latest );
}
return latest;
}
/**
* Returns the earliest of the two given dates.
*
* @param date1 the first date, can be null.
* @param date2 the second date, can be null.
* @return the latest of the two given dates.
*/
public static Date min( Date date1, Date date2 )
{
if ( date1 == null )
{
return date2;
}
return date2 != null ? (date1.before( date2 ) ? date1 : date2) : date1;
}
/**
* Returns the earliest of the given dates.
*
* @param dates the collection of dates.
* @return the earliest of the given dates.
*/
public static Date min( Collection<Date> dates )
{
Date earliest = null;
for ( Date d : dates )
{
earliest = min( d, earliest );
}
return earliest;
}
/**
* Parses a date from a String on the format YYYY-MM-DD. Returns null if the
* given string is null.
*
* @param string the String to parse.
* @return a Date based on the given String.
* @throws IllegalArgumentException if the given string is invalid.
*/
public static Date getMediumDate( String string )
{
return safeParseDateTime( string, MEDIUM_DATE_FORMAT );
}
/**
* Tests if the given base date is between the given start date and end
* date, including the dates themselves.
*
* @param baseDate the date used as base for the test.
* @param startDate the start date.
* @param endDate the end date.
* @return <code>true</code> if the base date is between the start date and
* end date, <code>false</code> otherwise.
*/
public static boolean between( Date baseDate, Date startDate, Date endDate )
{
if ( startDate.equals( endDate ) || endDate.before( startDate ) )
{
return false;
}
if ( (startDate.before( baseDate ) || startDate.equals( baseDate ))
&& (endDate.after( baseDate ) || endDate.equals( baseDate )) )
{
return true;
}
return false;
}
/**
* Tests if the given base date is strictly between the given start date and
* end date.
*
* @param baseDate the date used as base for the test.
* @param startDate the start date.
* @param endDate the end date.
* @return <code>true</code> if the base date is between the start date and
* end date, <code>false</code> otherwise.
*/
public static boolean strictlyBetween( Date baseDate, Date startDate, Date endDate )
{
if ( startDate.equals( endDate ) || endDate.before( startDate ) )
{
return false;
}
if ( startDate.before( baseDate ) && endDate.after( baseDate ) )
{
return true;
}
return false;
}
/**
* Returns the number of days since 01/01/1970. The value is rounded off to
* the floor value and does not take daylight saving time into account.
*
* @param date the date.
* @return number of days since Epoch.
*/
public static long getDays( Date date )
{
return date.getTime() / MS_PER_DAY;
}
/**
* Returns the number of days between the start date (inclusive) and end
* date (exclusive). The value is rounded off to the floor value and does
* not take daylight saving time into account.
*
* @param startDate the start-date.
* @param endDate the end-date.
* @return the number of days between the start and end-date.
*/
public static long getDays( Date startDate, Date endDate )
{
return (endDate.getTime() - startDate.getTime()) / MS_PER_DAY;
}
/**
* Returns the number of days between the start date (inclusive) and end
* date (inclusive). The value is rounded off to the floor value and does
* not take daylight saving time into account.
*
* @param startDate the start-date.
* @param endDate the end-date.
* @return the number of days between the start and end-date.
*/
public static long getDaysInclusive( Date startDate, Date endDate )
{
return getDays( startDate, endDate ) + 1;
}
/**
* Calculates the number of days between the start and end-date. Note this
* method is taking daylight saving time into account and has a performance
* overhead.
*
* @param startDate the start date.
* @param endDate the end date.
* @return the number of days between the start and end date.
*/
public static int daysBetween( Date startDate, Date endDate )
{
final Days days = Days.daysBetween( new DateTime( startDate ), new DateTime( endDate ) );
return days.getDays();
}
/**
* Checks if the date provided in argument is today's date.
*
* @param date to check
* @return <code>true</code> if date is representing today's date
* <code>false</code> otherwise
*/
public static boolean isToday( Date date )
{
int days = Days.daysBetween( new LocalDate( date ), new LocalDate() ).getDays();
return days == 0;
}
/**
* Calculates the number of months between the start and end-date. Note this
* method is taking daylight saving time into account and has a performance
* overhead.
*
* @param startDate the start date.
* @param endDate the end date.
* @return the number of months between the start and end date.
*/
public static int monthsBetween( Date startDate, Date endDate )
{
final Months days = Months.monthsBetween( new DateTime( startDate ), new DateTime( endDate ) );
return days.getMonths();
}
/**
* Calculates the number of days between Epoch and the given date.
*
* @param date the date.
* @return the number of days between Epoch and the given date.
*/
public static int daysSince1900( Date date )
{
final Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set( 1900, 0, 1 );
return daysBetween( calendar.getTime(), date );
}
/**
* Returns the nearest date forward in time with the given hour of day, with
* the minute, second and millisecond to zero. If the hour equals the
* current hour of day, the next following day is used.
*
* @param hourOfDay the hour of the day.
* @param now the date representing the current time, if null, the current
* time is used.
* @return the nearest date forward in time with the given hour of day.
*/
public static Date getNextDate( int hourOfDay, Date now )
{
now = now != null ? now : new Date();
DateTime date = new DateTime( now ).plusHours( 1 );
while ( date.getHourOfDay() != hourOfDay )
{
date = date.plusHours( 1 );
}
return date
.withMinuteOfHour( 0 )
.withSecondOfMinute( 0 )
.withMillisOfSecond( 0 )
.toDate();
}
/**
* Returns Epoch date, ie. 01/01/1970.
*
* @return Epoch date, ie. 01/01/1970.
*/
public static Date getEpoch()
{
final Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set( 1970, 0, 1 );
return calendar.getTime();
}
/**
* Returns a date formatted in ANSI SQL.
*
* @param date the Date.
* @return a date String.
*/
public static String getSqlDateString( Date date )
{
Calendar cal = Calendar.getInstance();
cal.setTime( date );
int year = cal.get( Calendar.YEAR );
int month = cal.get( Calendar.MONTH ) + 1;
int day = cal.get( Calendar.DAY_OF_MONTH );
String yearString = String.valueOf( year );
String monthString = month < 10 ? "0" + month : String.valueOf( month );
String dayString = day < 10 ? "0" + day : String.valueOf( day );
return yearString + "-" + monthString + "-" + dayString;
}
/**
* This method checks whether the String inDate is a valid date following
* the format "yyyy-MM-dd".
*
* @param dateString the string to be checked.
* @return true/false depending on whether the string is a date according to
* the format "yyyy-MM-dd".
*/
public static boolean dateIsValid( String dateString )
{
return dateIsValid( PeriodType.getCalendar(), dateString );
}
/**
* This method checks whether the String inDate is a valid date following
* the format "yyyy-MM-dd".
*
* @param calendar Calendar to be used
* @param dateString the string to be checked.
* @return true/false depending on whether the string is a date according to
* the format "yyyy-MM-dd".
*/
public static boolean dateIsValid( org.hisp.dhis.calendar.Calendar calendar, String dateString )
{
Matcher matcher = DEFAULT_DATE_REGEX_PATTERN.matcher( dateString );
if ( !matcher.matches() )
{
return false;
}
DateTimeUnit dateTime = new DateTimeUnit(
Integer.parseInt( matcher.group( "year" ) ),
Integer.parseInt( matcher.group( "month" ) ),
Integer.parseInt( matcher.group( "day" ) ) );
return calendar.isValid( dateTime );
}
/**
* This method checks whether the String dateTimeString is a valid datetime
* following the format "yyyy-MM-dd".
*
* @param dateTimeString the string to be checked.
* @return true/false depending on whether the string is a valid datetime
* according to the format "yyyy-MM-dd".
*/
public static boolean dateTimeIsValid( final String dateTimeString )
{
try
{
safeParseDateTime( dateTimeString, DATE_TIME_FORMAT );
return true;
}
catch ( IllegalArgumentException ex )
{
return false;
}
}
/**
* Returns the number of seconds until the next day at the given hour.
*
* @param hour the hour.
* @return number of seconds.
*/
public static long getSecondsUntilTomorrow( int hour )
{
Date date = getDateForTomorrow( hour );
return (date.getTime() - new Date().getTime()) / MS_PER_S;
}
/**
* Returns a date set to tomorrow at the given hour.
*
* @param hour the hour.
* @return a date.
*/
public static Date getDateForTomorrow( int hour )
{
Calendar cal = PeriodType.createCalendarInstance();
cal.add( Calendar.DAY_OF_YEAR, 1 );
cal.set( Calendar.HOUR_OF_DAY, hour );
return cal.getTime();
}
/**
* This method adds days to a date
*
* @param date the date.
* @param days the number of days to add.
*/
public static Date getDateAfterAddition( Date date, int days )
{
Calendar cal = Calendar.getInstance();
cal.setTime( date );
cal.add( Calendar.DATE, days );
return cal.getTime();
}
/**
* Method responsible for adding a positive or negative number based in a
* chronological unit.
*
* @param date the date to be modified. It's the input date for the
* calculation.
* @param addend a positive or negative integer to be added to the date.
* @param chronoUnit the unit of time to be used in the calculation. It's
* fully based in the Calendar API. Valid values could be:
* Calendar.DATE, Calendar.MILLISECOND, etc..
* @return the resultant date after the addition.
*/
public static Date calculateDateFrom( final Date date, final int addend, final int chronoUnit )
{
Calendar cal = Calendar.getInstance();
cal.setLenient( false );
cal.setTime( date );
cal.add( chronoUnit, addend );
return cal.getTime();
}
/**
* Sets the name property of each period based on the given I18nFormat.
*/
public static List<Period> setNames( List<Period> periods, I18nFormat format )
{
for ( Period period : periods )
{
if ( period != null )
{
period.setName( format.formatPeriod( period ) );
}
}
return periods;
}
/**
* Returns a pretty string representing the interval between the given start
* and end dates using a day, month, second format.
*
* @param start the start date.
* @param end the end date.
* @return a string, or null if the given start or end date is null.
*/
public static String getPrettyInterval( Date start, Date end )
{
if ( start == null || end == null )
{
return null;
}
long diff = end.getTime() - start.getTime();
return DAY_SECOND_FORMAT.print( new org.joda.time.Period( diff ) );
}
/**
* Parses the given string into a Date using the supported date formats.
* Returns null if the string cannot be parsed.
*
* @param dateString the date string.
* @return a date.
*/
public static Date parseDate( final String dateString )
{
return safeParseDateTime( dateString, DATE_FORMATTER );
}
/**
* Null safe instant to date conversion
*
* @param instant the instant
* @return a date.
*/
public static Date fromInstant( final Instant instant )
{
return convertOrNull( instant, Date::from );
}
/**
* Null safe date to instant conversion
*
* @param date the date
* @return an instant.
*/
public static Instant instantFromDate( final Date date )
{
return convertOrNull( date, Date::toInstant );
}
/**
* Null safe epoch to instant conversion
*
* @param epochMillis the date expressed as milliseconds from epoch
* @return an instant.
*/
public static Instant instantFromEpoch( final Long epochMillis )
{
return convertOrNull( new Date( epochMillis ), Date::toInstant );
}
public static Instant instantFromDateAsString( String dateAsString )
{
return convertOrNull( DateUtils.parseDate( dateAsString ), Date::toInstant );
}
private static <T, R> R convertOrNull( T from, Function<T, R> converter )
{
return Optional.ofNullable( from )
.map( converter )
.orElse( null );
}
/**
* Creates a {@link java.util.Date} from the given
* {@link java.time.LocalDateTime} based on the UTC time zone.
*
* @param time the LocalDateTime.
* @return a Date.
*/
public static Date getDate( LocalDateTime time )
{
Instant instant = time.toInstant( ZoneOffset.UTC );
return Date.from( instant );
}
/**
* Return the current date minus the duration specified by the given string.
*
* @param duration the duration string.
* @return a Date.
*/
public static Date nowMinusDuration( String duration )
{
Duration dr = DateUtils.getDuration( duration );
LocalDateTime time = LocalDateTime.now().minus( dr );
return DateUtils.getDate( time );
}
/**
* Parses the given string into a {@link java.time.Duration} object. The
* string syntax is [amount][unit]. The supported units are:
* <p>
* <ul>
* <li>"d": Days</li>
* <li>"h": Hours</li>
* <li>"m": Minutes</li>
* <li>"s": Seconds</li>
* </ul>
*
* @param duration the duration string, an example describing 12 days is
* "12d".
* @return a Duration object, or null if the duration string is invalid.
*/
public static Duration getDuration( String duration )
{
Matcher matcher = DURATION_PATTERN.matcher( duration );
if ( !matcher.find() )
{
return null;
}
long amount = Long.valueOf( matcher.group( 1 ) );
String unit = matcher.group( 2 );
ChronoUnit chronoUnit = TEMPORAL_MAP.get( unit );
if ( chronoUnit == null )
{
return null;
}
return Duration.of( amount, chronoUnit );
}
/**
* Converts the given {@link Date} to a {@link Timestamp}.
*
* @param date the date to convert.
* @return a time stamp.
*/
public static Timestamp asTimestamp( Date date )
{
return new Timestamp( date.getTime() );
}
/**
* Converts the given {@link Date} to a {@link java.sql.Date}.
*
* @param date the date to convert.
* @return a date.
*/
public static java.sql.Date asSqlDate( Date date )
{
return new java.sql.Date( date.getTime() );
}
/**
* Returns the latest, non-null date of the given dates. If all dates are
* null, then null is returned.
*
* @param dates the dates.
* @return the latest, non-null date.
*/
public static Date getLatest( Date... dates )
{
return Lists.newArrayList( dates ).stream()
.filter( Objects::nonNull )
.max( Date::compareTo ).orElse( null );
}
/**
* Returns only the date part after removing timestamp
*
* @param date the date to convert.
* @return a date
*/
public static Date removeTimeStamp( Date date )
{
return date == null ? null : getMediumDate( getMediumDateString( date ) );
}
/**
* Parses the given string into a Date object. In case the date parsed falls
* in a daylight savings transition, the date is parsed via a local date and
* converted to the first valid time after the DST gap. When the fallback is
* used, any timezone offset in the given format would be ignored.
*
* @param dateString The string to parse
* @param formatter The formatter to use for parsing
* @return Parsed Date object. Null if the supplied dateString is empty.
*/
private static Date safeParseDateTime( final String dateString, final DateTimeFormatter formatter )
{
if ( StringUtils.isEmpty( dateString ) )
{
return null;
}
try
{
return formatter.parseDateTime( dateString ).toDate();
}
catch ( IllegalInstantException e )
{
return formatter.parseLocalDateTime( dateString ).toDate();
}
}
}
| dhis-2/dhis-api/src/main/java/org/hisp/dhis/util/DateUtils.java | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.util;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.hisp.dhis.calendar.DateTimeUnit;
import org.hisp.dhis.i18n.I18nFormat;
import org.hisp.dhis.period.Period;
import org.hisp.dhis.period.PeriodType;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.IllegalInstantException;
import org.joda.time.LocalDate;
import org.joda.time.Months;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import org.joda.time.format.DateTimeParser;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.ObjectArrays;
/**
* @author Lars Helge Overland
*/
public class DateUtils
{
public static final String ISO8601_NO_TZ_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS";
private static DateTimeFormatter ISO8601_NO_TZ = DateTimeFormat.forPattern( ISO8601_NO_TZ_PATTERN );
public static final String ISO8601_PATTERN = ISO8601_NO_TZ_PATTERN + "Z";
private static DateTimeFormatter ISO8601 = DateTimeFormat.forPattern( ISO8601_PATTERN );
private static final String DEFAULT_DATE_REGEX = "\\b(?<year>\\d{4})-(?<month>0[1-9]|1[0-2])-(?<day>0[1-9]|[1-2][0-9]|3[0-2])(?<time>.*)\\b";
private static final Pattern DEFAULT_DATE_REGEX_PATTERN = Pattern.compile( DEFAULT_DATE_REGEX );
private static final DateTimeParser[] SUPPORTED_DATE_ONLY_PARSERS = {
DateTimeFormat.forPattern( "yyyy-MM-dd" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM" ).getParser(),
DateTimeFormat.forPattern( "yyyy" ).getParser()
};
private static final DateTimeParser[] SUPPORTED_DATE_TIME_FORMAT_PARSERS = {
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSSSS" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSSZ" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSS" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSS" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ssZ" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mmZ" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HHZ" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH" ).getParser(),
DateTimeFormat.forPattern( "yyyy-MM-dd HH:mm:ssZ" ).getParser()
};
private static final DateTimeParser[] SUPPORTED_DATE_FORMAT_PARSERS = ObjectArrays
.concat( SUPPORTED_DATE_ONLY_PARSERS, SUPPORTED_DATE_TIME_FORMAT_PARSERS, DateTimeParser.class );
private static final DateTimeFormatter DATE_FORMATTER = new DateTimeFormatterBuilder()
.append( null, SUPPORTED_DATE_FORMAT_PARSERS ).toFormatter();
private static final DateTimeFormatter DATE_TIME_FORMAT = new DateTimeFormatterBuilder()
.append( null, SUPPORTED_DATE_TIME_FORMAT_PARSERS ).toFormatter();
public static final PeriodFormatter DAY_SECOND_FORMAT = new PeriodFormatterBuilder()
.appendDays().appendSuffix( " d" ).appendSeparator( ", " )
.appendHours().appendSuffix( " h" ).appendSeparator( ", " )
.appendMinutes().appendSuffix( " m" ).appendSeparator( ", " )
.appendSeconds().appendSuffix( " s" ).appendSeparator( ", " ).toFormatter();
private static final DateTimeFormatter MEDIUM_DATE_FORMAT = DateTimeFormat.forPattern( "yyyy-MM-dd" );
private static final DateTimeFormatter LONG_DATE_FORMAT = DateTimeFormat.forPattern( "yyyy-MM-dd'T'HH:mm:ss" );
private static final DateTimeFormatter HTTP_DATE_FORMAT = DateTimeFormat
.forPattern( "EEE, dd MMM yyyy HH:mm:ss 'GMT'" ).withLocale( Locale.ENGLISH );
private static final DateTimeFormatter TIMESTAMP_UTC_TZ_FORMAT = DateTimeFormat
.forPattern( "yyyy-MM-dd'T'HH:mm:ss.SSSZ" ).withZoneUTC();
public static final double DAYS_IN_YEAR = 365.0;
private static final long MS_PER_DAY = 86400000;
private static final long MS_PER_S = 1000;
private static final Pattern DURATION_PATTERN = Pattern.compile( "^(\\d+)(d|h|m|s)$" );
private static final Map<String, ChronoUnit> TEMPORAL_MAP = ImmutableMap.of(
"d", ChronoUnit.DAYS, "h", ChronoUnit.HOURS, "m", ChronoUnit.MINUTES, "s", ChronoUnit.SECONDS );
/**
* Returns date formatted as ISO 8601
*/
public static String getIso8601( Date date )
{
return date != null ? ISO8601.print( new DateTime( date ) ) : null;
}
/**
* Returns date formatted as ISO 8601, without any TZ info
*/
public static String getIso8601NoTz( Date date )
{
return date != null ? ISO8601_NO_TZ.print( new DateTime( date ) ) : null;
}
/**
* Converts a Date to the GMT timezone and formats it to the format
* yyyy-MM-dd HH:mm:ssZ.
*
* @param date the Date to parse.
* @return A formatted date string.
*/
public static String getLongGmtDateString( Date date )
{
return date != null ? TIMESTAMP_UTC_TZ_FORMAT.print( new DateTime( date ) ) : null;
}
/**
* Formats a Date to the format yyyy-MM-dd HH:mm:ss.
*
* @param date the Date to parse.
* @return A formatted date string.
*/
public static String getLongDateString( Date date )
{
return date != null ? LONG_DATE_FORMAT.print( new DateTime( date ) ) : null;
}
/**
* Formats a Date to the format yyyy-MM-dd HH:mm:ss.
*
* @return A formatted date string.
*/
public static String getLongDateString()
{
return getLongDateString( Calendar.getInstance().getTime() );
}
/**
* Formats a Date to the format yyyy-MM-dd.
*
* @param date the Date to parse.
* @return A formatted date string. Null if argument is null.
*/
public static String getMediumDateString( Date date )
{
return date != null ? MEDIUM_DATE_FORMAT.print( new DateTime( date ) ) : null;
}
/**
* Formats the current Date to the format YYYY-MM-DD.
*
* @return A formatted date string.
*/
public static String getMediumDateString()
{
return getMediumDateString( Calendar.getInstance().getTime() );
}
/**
* Formats a Date according to the HTTP specification standard date format.
*
* @param date the Date to format.
* @return a formatted string.
*/
public static String getHttpDateString( Date date )
{
return date != null ? (HTTP_DATE_FORMAT.print( new DateTime( date ) )) : null;
}
/**
* Returns the latest of the two given dates.
*
* @param date1 the first date, can be null.
* @param date2 the second date, can be null.
* @return the latest of the two given dates.
*/
public static Date max( Date date1, Date date2 )
{
if ( date1 == null )
{
return date2;
}
return date2 != null ? (date1.after( date2 ) ? date1 : date2) : date1;
}
/**
* Returns the latest of the given dates.
*
* @param dates the collection of dates.
* @return the latest of the given dates.
*/
public static Date max( Collection<Date> dates )
{
Date latest = null;
for ( Date d : dates )
{
latest = max( d, latest );
}
return latest;
}
/**
* Returns the earliest of the two given dates.
*
* @param date1 the first date, can be null.
* @param date2 the second date, can be null.
* @return the latest of the two given dates.
*/
public static Date min( Date date1, Date date2 )
{
if ( date1 == null )
{
return date2;
}
return date2 != null ? (date1.before( date2 ) ? date1 : date2) : date1;
}
/**
* Returns the earliest of the given dates.
*
* @param dates the collection of dates.
* @return the earliest of the given dates.
*/
public static Date min( Collection<Date> dates )
{
Date earliest = null;
for ( Date d : dates )
{
earliest = min( d, earliest );
}
return earliest;
}
/**
* Parses a date from a String on the format YYYY-MM-DD. Returns null if the
* given string is null.
*
* @param string the String to parse.
* @return a Date based on the given String.
* @throws IllegalArgumentException if the given string is invalid.
*/
public static Date getMediumDate( String string )
{
return safeParseDateTime( string, MEDIUM_DATE_FORMAT );
}
/**
* Tests if the given base date is between the given start date and end
* date, including the dates themselves.
*
* @param baseDate the date used as base for the test.
* @param startDate the start date.
* @param endDate the end date.
* @return <code>true</code> if the base date is between the start date and
* end date, <code>false</code> otherwise.
*/
public static boolean between( Date baseDate, Date startDate, Date endDate )
{
if ( startDate.equals( endDate ) || endDate.before( startDate ) )
{
return false;
}
if ( (startDate.before( baseDate ) || startDate.equals( baseDate ))
&& (endDate.after( baseDate ) || endDate.equals( baseDate )) )
{
return true;
}
return false;
}
/**
* Tests if the given base date is strictly between the given start date and
* end date.
*
* @param baseDate the date used as base for the test.
* @param startDate the start date.
* @param endDate the end date.
* @return <code>true</code> if the base date is between the start date and
* end date, <code>false</code> otherwise.
*/
public static boolean strictlyBetween( Date baseDate, Date startDate, Date endDate )
{
if ( startDate.equals( endDate ) || endDate.before( startDate ) )
{
return false;
}
if ( startDate.before( baseDate ) && endDate.after( baseDate ) )
{
return true;
}
return false;
}
/**
* Returns the number of days since 01/01/1970. The value is rounded off to
* the floor value and does not take daylight saving time into account.
*
* @param date the date.
* @return number of days since Epoch.
*/
public static long getDays( Date date )
{
return date.getTime() / MS_PER_DAY;
}
/**
* Returns the number of days between the start date (inclusive) and end
* date (exclusive). The value is rounded off to the floor value and does
* not take daylight saving time into account.
*
* @param startDate the start-date.
* @param endDate the end-date.
* @return the number of days between the start and end-date.
*/
public static long getDays( Date startDate, Date endDate )
{
return (endDate.getTime() - startDate.getTime()) / MS_PER_DAY;
}
/**
* Returns the number of days between the start date (inclusive) and end
* date (inclusive). The value is rounded off to the floor value and does
* not take daylight saving time into account.
*
* @param startDate the start-date.
* @param endDate the end-date.
* @return the number of days between the start and end-date.
*/
public static long getDaysInclusive( Date startDate, Date endDate )
{
return getDays( startDate, endDate ) + 1;
}
/**
* Calculates the number of days between the start and end-date. Note this
* method is taking daylight saving time into account and has a performance
* overhead.
*
* @param startDate the start date.
* @param endDate the end date.
* @return the number of days between the start and end date.
*/
public static int daysBetween( Date startDate, Date endDate )
{
final Days days = Days.daysBetween( new DateTime( startDate ), new DateTime( endDate ) );
return days.getDays();
}
/**
* Checks if the date provided in argument is today's date.
*
* @param date to check
* @return <code>true</code> if date is representing today's date
* <code>false</code> otherwise
*/
public static boolean isToday( Date date )
{
int days = Days.daysBetween( new LocalDate( date ), new LocalDate() ).getDays();
return days == 0;
}
/**
* Calculates the number of months between the start and end-date. Note this
* method is taking daylight saving time into account and has a performance
* overhead.
*
* @param startDate the start date.
* @param endDate the end date.
* @return the number of months between the start and end date.
*/
public static int monthsBetween( Date startDate, Date endDate )
{
final Months days = Months.monthsBetween( new DateTime( startDate ), new DateTime( endDate ) );
return days.getMonths();
}
/**
* Calculates the number of days between Epoch and the given date.
*
* @param date the date.
* @return the number of days between Epoch and the given date.
*/
public static int daysSince1900( Date date )
{
final Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set( 1900, 0, 1 );
return daysBetween( calendar.getTime(), date );
}
/**
* Returns the nearest date forward in time with the given hour of day, with
* the minute, second and millisecond to zero. If the hour equals the
* current hour of day, the next following day is used.
*
* @param hourOfDay the hour of the day.
* @param now the date representing the current time, if null, the current
* time is used.
* @return the nearest date forward in time with the given hour of day.
*/
public static Date getNextDate( int hourOfDay, Date now )
{
now = now != null ? now : new Date();
DateTime date = new DateTime( now ).plusHours( 1 );
while ( date.getHourOfDay() != hourOfDay )
{
date = date.plusHours( 1 );
}
return date
.withMinuteOfHour( 0 )
.withSecondOfMinute( 0 )
.withMillisOfSecond( 0 )
.toDate();
}
/**
* Returns Epoch date, ie. 01/01/1970.
*
* @return Epoch date, ie. 01/01/1970.
*/
public static Date getEpoch()
{
final Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set( 1970, 0, 1 );
return calendar.getTime();
}
/**
* Returns a date formatted in ANSI SQL.
*
* @param date the Date.
* @return a date String.
*/
public static String getSqlDateString( Date date )
{
Calendar cal = Calendar.getInstance();
cal.setTime( date );
int year = cal.get( Calendar.YEAR );
int month = cal.get( Calendar.MONTH ) + 1;
int day = cal.get( Calendar.DAY_OF_MONTH );
String yearString = String.valueOf( year );
String monthString = month < 10 ? "0" + month : String.valueOf( month );
String dayString = day < 10 ? "0" + day : String.valueOf( day );
return yearString + "-" + monthString + "-" + dayString;
}
/**
* This method checks whether the String inDate is a valid date following
* the format "yyyy-MM-dd".
*
* @param dateString the string to be checked.
* @return true/false depending on whether the string is a date according to
* the format "yyyy-MM-dd".
*/
public static boolean dateIsValid( String dateString )
{
return dateIsValid( PeriodType.getCalendar(), dateString );
}
/**
* This method checks whether the String inDate is a valid date following
* the format "yyyy-MM-dd".
*
* @param calendar Calendar to be used
* @param dateString the string to be checked.
* @return true/false depending on whether the string is a date according to
* the format "yyyy-MM-dd".
*/
public static boolean dateIsValid( org.hisp.dhis.calendar.Calendar calendar, String dateString )
{
Matcher matcher = DEFAULT_DATE_REGEX_PATTERN.matcher( dateString );
if ( !matcher.matches() )
{
return false;
}
DateTimeUnit dateTime = new DateTimeUnit(
Integer.parseInt( matcher.group( "year" ) ),
Integer.parseInt( matcher.group( "month" ) ),
Integer.parseInt( matcher.group( "day" ) ) );
return calendar.isValid( dateTime );
}
/**
* This method checks whether the String dateTimeString is a valid datetime
* following the format "yyyy-MM-dd".
*
* @param dateTimeString the string to be checked.
* @return true/false depending on whether the string is a valid datetime
* according to the format "yyyy-MM-dd".
*/
public static boolean dateTimeIsValid( final String dateTimeString )
{
try
{
safeParseDateTime( dateTimeString, DATE_TIME_FORMAT );
return true;
}
catch ( IllegalArgumentException ex )
{
return false;
}
}
/**
* Returns the number of seconds until the next day at the given hour.
*
* @param hour the hour.
* @return number of seconds.
*/
public static long getSecondsUntilTomorrow( int hour )
{
Date date = getDateForTomorrow( hour );
return (date.getTime() - new Date().getTime()) / MS_PER_S;
}
/**
* Returns a date set to tomorrow at the given hour.
*
* @param hour the hour.
* @return a date.
*/
public static Date getDateForTomorrow( int hour )
{
Calendar cal = PeriodType.createCalendarInstance();
cal.add( Calendar.DAY_OF_YEAR, 1 );
cal.set( Calendar.HOUR_OF_DAY, hour );
return cal.getTime();
}
/**
* This method adds days to a date
*
* @param date the date.
* @param days the number of days to add.
*/
public static Date getDateAfterAddition( Date date, int days )
{
Calendar cal = Calendar.getInstance();
cal.setTime( date );
cal.add( Calendar.DATE, days );
return cal.getTime();
}
/**
* Method responsible for adding a positive or negative number based in a
* chronological unit.
*
* @param date the date to be modified. It's the input date for the
* calculation.
* @param addend a positive or negative integer to be added to the date.
* @param chronoUnit the unit of time to be used in the calculation. It's
* fully based in the Calendar API. Valid values could be:
* Calendar.DATE, Calendar.MILLISECOND, etc..
* @return the resultant date after the addition.
*/
public static Date calculateDateFrom( final Date date, final int addend, final int chronoUnit )
{
Calendar cal = Calendar.getInstance();
cal.setLenient( false );
cal.setTime( date );
cal.add( chronoUnit, addend );
return cal.getTime();
}
/**
* Sets the name property of each period based on the given I18nFormat.
*/
public static List<Period> setNames( List<Period> periods, I18nFormat format )
{
for ( Period period : periods )
{
if ( period != null )
{
period.setName( format.formatPeriod( period ) );
}
}
return periods;
}
/**
* Returns a pretty string representing the interval between the given start
* and end dates using a day, month, second format.
*
* @param start the start date.
* @param end the end date.
* @return a string, or null if the given start or end date is null.
*/
public static String getPrettyInterval( Date start, Date end )
{
if ( start == null || end == null )
{
return null;
}
long diff = end.getTime() - start.getTime();
return DAY_SECOND_FORMAT.print( new org.joda.time.Period( diff ) );
}
/**
* Parses the given string into a Date using the supported date formats.
* Returns null if the string cannot be parsed.
*
* @param dateString the date string.
* @return a date.
*/
public static Date parseDate( final String dateString )
{
return safeParseDateTime( dateString, DATE_FORMATTER );
}
/**
* Null safe instant to date conversion
*
* @param instant the instant
* @return a date.
*/
public static Date fromInstant( final Instant instant )
{
return convertOrNull( instant, Date::from );
}
/**
* Null safe date to instant conversion
*
* @param date the date
* @return an instant.
*/
public static Instant instantFromDate( final Date date )
{
return convertOrNull( date, Date::toInstant );
}
/**
* Null safe epoch to instant conversion
*
* @param epochMillis the date expressed as milliseconds from epoch
* @return an instant.
*/
public static Instant instantFromEpoch( final Long epochMillis )
{
return convertOrNull( new Date( epochMillis ), Date::toInstant );
}
public static Instant instantFromDateAsString( String dateAsString )
{
return convertOrNull( DateUtils.parseDate( dateAsString ), Date::toInstant );
}
private static <T, R> R convertOrNull( T from, Function<T, R> converter )
{
return Optional.ofNullable( from )
.map( converter )
.orElse( null );
}
/**
* Creates a {@link java.util.Date} from the given
* {@link java.time.LocalDateTime} based on the UTC time zone.
*
* @param time the LocalDateTime.
* @return a Date.
*/
public static Date getDate( LocalDateTime time )
{
Instant instant = time.toInstant( ZoneOffset.UTC );
return Date.from( instant );
}
/**
* Return the current date minus the duration specified by the given string.
*
* @param duration the duration string.
* @return a Date.
*/
public static Date nowMinusDuration( String duration )
{
Duration dr = DateUtils.getDuration( duration );
LocalDateTime time = LocalDateTime.now().minus( dr );
return DateUtils.getDate( time );
}
/**
* Parses the given string into a {@link java.time.Duration} object. The
* string syntax is [amount][unit]. The supported units are:
* <p>
* <ul>
* <li>"d": Days</li>
* <li>"h": Hours</li>
* <li>"m": Minutes</li>
* <li>"s": Seconds</li>
* </ul>
*
* @param duration the duration string, an example describing 12 days is
* "12d".
* @return a Duration object, or null if the duration string is invalid.
*/
public static Duration getDuration( String duration )
{
Matcher matcher = DURATION_PATTERN.matcher( duration );
if ( !matcher.find() )
{
return null;
}
long amount = Long.valueOf( matcher.group( 1 ) );
String unit = matcher.group( 2 );
ChronoUnit chronoUnit = TEMPORAL_MAP.get( unit );
if ( chronoUnit == null )
{
return null;
}
return Duration.of( amount, chronoUnit );
}
/**
* Converts the given {@link Date} to a {@link Timestamp}.
*
* @param date the date to convert.
* @return a time stamp.
*/
public static Timestamp asTimestamp( Date date )
{
return new Timestamp( date.getTime() );
}
/**
* Converts the given {@link Date} to a {@link java.sql.Date}.
*
* @param date the date to convert.
* @return a date.
*/
public static java.sql.Date asSqlDate( Date date )
{
return new java.sql.Date( date.getTime() );
}
/**
* Returns the latest, non-null date of the given dates. If all dates are
* null, then null is returned.
*
* @param dates the dates.
* @return the latest, non-null date.
*/
public static Date getLatest( Date... dates )
{
return Lists.newArrayList( dates ).stream()
.filter( Objects::nonNull )
.max( Date::compareTo ).orElse( null );
}
/**
* Returns only the date part after removing timestamp
*
* @param date the date to convert.
* @return a date
*/
public static Date removeTimeStamp( Date date )
{
return date == null ? null : getMediumDate( getMediumDateString( date ) );
}
/**
* Parses the given string into a Date object. In case the date parsed falls
* in a daylight savings transition, the date is parsed via a local date and
* converted to the first valid time after the DST gap. When the fallback is
* used, any timezone offset in the given format would be ignored.
*
* @param dateString The string to parse
* @param formatter The formatter to use for parsing
* @return Parsed Date object. Null if the supplied dateString is empty.
*/
private static Date safeParseDateTime( final String dateString, final DateTimeFormatter formatter )
{
if ( StringUtils.isEmpty( dateString ) )
{
return null;
}
try
{
return formatter.parseDateTime( dateString ).toDate();
}
catch ( IllegalInstantException e )
{
return formatter.parseLocalDateTime( dateString ).toDate();
}
}
}
| fix: Add new format with 9 fractions for parsing datetime
| dhis-2/dhis-api/src/main/java/org/hisp/dhis/util/DateUtils.java | fix: Add new format with 9 fractions for parsing datetime |
|
Java | bsd-3-clause | 9fea84bad1d5e0c59fe8defe8398ba96a353feb4 | 0 | sebastiangraf/treetank,sebastiangraf/treetank,sebastiangraf/treetank | package com.treetank.service.rest;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.junit.Test;
public final class TestResponseWrapper implements HttpServletResponse {
private final String contentType;
private final String encoding;
private final List<Byte> buffer;
private final byte[] content;
public TestResponseWrapper(final String paramContentType,
final String paramEncoding, final byte[] paramContent) {
this.contentType = paramContentType;
this.encoding = paramEncoding;
buffer = new ArrayList<Byte>();
content = paramContent;
}
public TestResponseWrapper() {
this("", "", null);
}
public void addCookie(Cookie arg0) {
}
public void addDateHeader(String arg0, long arg1) {
}
public void addHeader(String arg0, String arg1) {
}
public void addIntHeader(String arg0, int arg1) {
}
public boolean containsHeader(String arg0) {
return false;
}
public String encodeRedirectURL(String arg0) {
return null;
}
public String encodeRedirectUrl(String arg0) {
return null;
}
public String encodeURL(String arg0) {
return null;
}
public String encodeUrl(String arg0) {
return null;
}
public void sendError(int arg0) throws IOException {
}
public void sendError(int arg0, String arg1) throws IOException {
}
public void sendRedirect(String arg0) throws IOException {
}
public void setDateHeader(String arg0, long arg1) {
}
public void setHeader(String arg0, String arg1) {
}
public void setIntHeader(String arg0, int arg1) {
}
public void setStatus(int arg0) {
}
public void setStatus(int arg0, String arg1) {
}
public void flushBuffer() throws IOException {
}
public int getBufferSize() {
return 0;
}
public String getCharacterEncoding() {
return null;
}
public String getContentType() {
return null;
}
public Locale getLocale() {
return null;
}
public ServletOutputStream getOutputStream() throws IOException {
return new ServletOutputStream() {
public void write(int b) throws IOException {
buffer.add((byte) b);
}
};
}
public void checkWrittenBytes() {
final byte[] newByte = new byte[this.buffer.size()];
System.arraycopy(this.buffer.toArray(new Byte[this.buffer.size()]), 0,
newByte, 0, newByte.length);
assertEquals(newByte, content);
}
public PrintWriter getWriter() throws IOException {
return null;
}
public boolean isCommitted() {
return false;
}
public void reset() {
}
public void resetBuffer() {
}
public void setBufferSize(int arg0) {
}
public void setCharacterEncoding(String arg0) {
assertEquals(this.encoding, arg0);
}
public void setContentLength(int arg0) {
}
public void setContentType(String arg0) {
assertEquals(this.contentType, arg0);
}
public void setLocale(Locale arg0) {
}
@Test
public void testFake() {
// Just to fool maven
}
}
| src/test/java/com/treetank/service/rest/TestResponseWrapper.java | package com.treetank.service.rest;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.junit.Test;
public final class TestResponseWrapper implements HttpServletResponse {
private final String contentType;
private final String encoding;
private final List<Byte> buffer;
private final byte[] content;
public TestResponseWrapper(final String paramContentType,
final String paramEncoding, final byte[] paramContent) {
this.contentType = paramContentType;
this.encoding = paramEncoding;
buffer = new ArrayList<Byte>();
content = paramContent;
}
public TestResponseWrapper() {
this("", "", null);
}
@Override
public void addCookie(Cookie arg0) {
}
@Override
public void addDateHeader(String arg0, long arg1) {
}
@Override
public void addHeader(String arg0, String arg1) {
}
@Override
public void addIntHeader(String arg0, int arg1) {
}
@Override
public boolean containsHeader(String arg0) {
return false;
}
@Override
public String encodeRedirectURL(String arg0) {
return null;
}
@Override
public String encodeRedirectUrl(String arg0) {
return null;
}
@Override
public String encodeURL(String arg0) {
return null;
}
@Override
public String encodeUrl(String arg0) {
return null;
}
@Override
public void sendError(int arg0) throws IOException {
}
@Override
public void sendError(int arg0, String arg1) throws IOException {
}
@Override
public void sendRedirect(String arg0) throws IOException {
}
@Override
public void setDateHeader(String arg0, long arg1) {
}
@Override
public void setHeader(String arg0, String arg1) {
}
@Override
public void setIntHeader(String arg0, int arg1) {
}
@Override
public void setStatus(int arg0) {
}
@Override
public void setStatus(int arg0, String arg1) {
}
@Override
public void flushBuffer() throws IOException {
}
@Override
public int getBufferSize() {
return 0;
}
@Override
public String getCharacterEncoding() {
return null;
}
@Override
public String getContentType() {
return null;
}
@Override
public Locale getLocale() {
return null;
}
@Override
public ServletOutputStream getOutputStream() throws IOException {
return new ServletOutputStream() {
@Override
public void write(int b) throws IOException {
buffer.add((byte) b);
}
};
}
public void checkWrittenBytes() {
final byte[] newByte = new byte[this.buffer.size()];
System.arraycopy(this.buffer.toArray(new Byte[this.buffer.size()]), 0,
newByte, 0, newByte.length);
assertEquals(newByte, content);
}
@Override
public PrintWriter getWriter() throws IOException {
return null;
}
@Override
public boolean isCommitted() {
return false;
}
@Override
public void reset() {
}
@Override
public void resetBuffer() {
}
@Override
public void setBufferSize(int arg0) {
}
@Override
public void setCharacterEncoding(String arg0) {
assertEquals(this.encoding, arg0);
}
@Override
public void setContentLength(int arg0) {
}
@Override
public void setContentType(String arg0) {
assertEquals(this.contentType, arg0);
}
@Override
public void setLocale(Locale arg0) {
}
@Test
public void testFake() {
// Just to fool maven
}
}
| removed further @override-tags
git-svn-id: a5379eb5ca3beb2b6e029be3b1b7f6aa53f2352b@4915 e3ddb328-5bfe-0310-b762-aafcbcbd2528
| src/test/java/com/treetank/service/rest/TestResponseWrapper.java | removed further @override-tags |
|
Java | mit | a7e8268ab622100e4fd267dd9acc7bce0e558c61 | 0 | codehaus-plexus/modello | package org.codehaus.modello.plugin.java;
/*
* Copyright (c) 2004, Codehaus.org
*
* 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.
*/
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import org.codehaus.modello.ModelloException;
import org.codehaus.modello.ModelloParameterConstants;
import org.codehaus.modello.model.BaseElement;
import org.codehaus.modello.model.Model;
import org.codehaus.modello.model.ModelAssociation;
import org.codehaus.modello.model.ModelClass;
import org.codehaus.modello.model.ModelDefault;
import org.codehaus.modello.model.ModelField;
import org.codehaus.modello.model.ModelInterface;
import org.codehaus.modello.model.ModelType;
import org.codehaus.modello.plugin.AbstractModelloGenerator;
import org.codehaus.modello.plugin.java.javasource.JClass;
import org.codehaus.modello.plugin.java.javasource.JComment;
import org.codehaus.modello.plugin.java.javasource.JInterface;
import org.codehaus.modello.plugin.java.javasource.JSourceWriter;
import org.codehaus.modello.plugin.java.javasource.JStructure;
import org.codehaus.modello.plugin.java.metadata.JavaClassMetadata;
import org.codehaus.modello.plugin.java.metadata.JavaFieldMetadata;
import org.codehaus.modello.plugin.java.metadata.JavaModelMetadata;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.WriterFactory;
/**
* AbstractJavaModelloGenerator - similar in scope to {@link AbstractModelloGenerator} but with features that
* java generators can use.
*
* @author <a href="mailto:[email protected]">Joakim Erdfelt</a>
* @version $Id$
*/
public abstract class AbstractJavaModelloGenerator
extends AbstractModelloGenerator
{
protected boolean useJava5 = false;
protected void initialize( Model model, Properties parameters )
throws ModelloException
{
super.initialize( model, parameters );
useJava5 = Boolean.valueOf( getParameter( parameters,
ModelloParameterConstants.USE_JAVA5, "false" ) ).booleanValue();
}
/**
* Create a new java source file writer, with configured encoding.
*
* @param packageName the package of the source file to create
* @param className the class of the source file to create
* @return a JSourceWriter with configured encoding
* @throws IOException
*/
protected JSourceWriter newJSourceWriter( String packageName, String className )
throws IOException
{
String directory = packageName.replace( '.', File.separatorChar );
File f = new File( new File( getOutputDirectory(), directory ), className + ".java" );
if ( !f.getParentFile().exists() )
{
f.getParentFile().mkdirs();
}
OutputStream os = getBuildContext().newFileOutputStream( f );
Writer writer = ( getEncoding() == null ) ? WriterFactory.newPlatformWriter( os )
: WriterFactory.newWriter( os, getEncoding() );
return new JSourceWriter( writer );
}
private JComment getHeaderComment()
{
JComment comment = new JComment();
comment.setComment( getHeader() );
return comment;
}
protected void initHeader( JClass clazz )
{
clazz.setHeader( getHeaderComment() );
}
protected void initHeader( JInterface interfaze )
{
interfaze.setHeader( getHeaderComment() );
}
protected void suppressAllWarnings( Model objectModel, JStructure structure )
{
JavaModelMetadata javaModelMetadata = (JavaModelMetadata) objectModel.getMetadata( JavaModelMetadata.ID );
if ( useJava5 && javaModelMetadata.isSuppressAllWarnings() )
{
structure.appendAnnotation( "@SuppressWarnings( \"all\" )" );
}
}
protected void addModelImports( JClass jClass, BaseElement baseElem )
throws ModelloException
{
String basePackageName = null;
if ( baseElem instanceof ModelType )
{
basePackageName = ( (ModelType) baseElem ).getPackageName( isPackageWithVersion(), getGeneratedVersion() );
}
// import interfaces
for ( ModelInterface modelInterface : getModel().getInterfaces( getGeneratedVersion() ) )
{
addModelImport( jClass, modelInterface, basePackageName );
}
// import classes
for ( ModelClass modelClass : getClasses( getModel() ) )
{
addModelImport( jClass, modelClass, basePackageName );
}
}
private void addModelImport( JClass jClass, ModelType modelType, String basePackageName )
{
String packageName = modelType.getPackageName( isPackageWithVersion(), getGeneratedVersion() );
if ( !packageName.equals( basePackageName ) )
{
jClass.addImport( packageName + '.' + modelType.getName() );
}
}
protected String getPrefix( JavaFieldMetadata javaFieldMetadata )
{
return javaFieldMetadata.isBooleanGetter() ? "is" : "get";
}
protected String getDefaultValue( ModelAssociation association )
{
String value = association.getDefaultValue();
if ( useJava5 )
{
value = StringUtils.replaceOnce( StringUtils.replaceOnce( value, "/*", "" ), "*/", "" );
}
return value;
}
protected final static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS";
protected String getJavaDefaultValue( ModelField modelField )
throws ModelloException
{
if ( "String".equals( modelField.getType() ) )
{
return '"' + modelField.getDefaultValue() + '"';
}
else if ( "char".equals( modelField.getType() ) )
{
return '\'' + modelField.getDefaultValue() + '\'';
}
else if ( "long".equals( modelField.getType() ) )
{
return modelField.getDefaultValue() + 'L';
}
else if ( "float".equals( modelField.getType() ) )
{
return modelField.getDefaultValue() + 'f';
}
else if ( "Date".equals( modelField.getType() ) )
{
DateFormat format = new SimpleDateFormat( DEFAULT_DATE_FORMAT, Locale.US );
try
{
Date date = format.parse( modelField.getDefaultValue() );
return "new java.util.Date( " + date.getTime() + "L )";
}
catch ( ParseException pe )
{
throw new ModelloException( "Unparseable default date: " + modelField.getDefaultValue(), pe );
}
}
return modelField.getDefaultValue();
}
protected String getValueChecker( String type, String value, ModelField field )
throws ModelloException
{
String retVal;
if ( "boolean".equals( type ) || "double".equals( type ) || "float".equals( type ) || "int".equals( type )
|| "long".equals( type ) || "short".equals( type ) || "byte".equals( type ) || "char".equals( type ) )
{
retVal = "if ( " + value + " != " + getJavaDefaultValue( field ) + " )";
}
else if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type )
|| ModelDefault.MAP.equals( type ) || ModelDefault.PROPERTIES.equals( type ) )
{
retVal = "if ( ( " + value + " != null ) && ( " + value + ".size() > 0 ) )";
}
else if ( "String".equals( type ) && field.getDefaultValue() != null )
{
retVal = "if ( ( " + value + " != null ) && !" + value + ".equals( \"" + field.getDefaultValue() + "\" ) )";
}
else if ( "Date".equals( type ) && field.getDefaultValue() != null )
{
retVal = "if ( ( " + value + " != null ) && !" + value + ".equals( " + getJavaDefaultValue( field ) + " ) )";
}
else
{
retVal = "if ( " + value + " != null )";
}
return retVal;
}
protected List<ModelClass> getClasses( Model model )
{
List<ModelClass> modelClasses = new ArrayList<ModelClass>();
for ( ModelClass modelClass : model.getClasses( getGeneratedVersion() ) )
{
if ( isRelevant( modelClass ) )
{
modelClasses.add( modelClass );
}
}
return modelClasses;
}
protected boolean isRelevant( ModelClass modelClass )
{
return isJavaEnabled( modelClass );
}
protected boolean isJavaEnabled( ModelClass modelClass )
{
JavaClassMetadata javaClassMetadata = (JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.ID );
return javaClassMetadata.isEnabled();
}
}
| modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/AbstractJavaModelloGenerator.java | package org.codehaus.modello.plugin.java;
/*
* Copyright (c) 2004, Codehaus.org
*
* 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.
*/
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import org.codehaus.modello.ModelloException;
import org.codehaus.modello.ModelloParameterConstants;
import org.codehaus.modello.model.BaseElement;
import org.codehaus.modello.model.Model;
import org.codehaus.modello.model.ModelAssociation;
import org.codehaus.modello.model.ModelClass;
import org.codehaus.modello.model.ModelDefault;
import org.codehaus.modello.model.ModelField;
import org.codehaus.modello.model.ModelInterface;
import org.codehaus.modello.plugin.AbstractModelloGenerator;
import org.codehaus.modello.plugin.java.javasource.JClass;
import org.codehaus.modello.plugin.java.javasource.JComment;
import org.codehaus.modello.plugin.java.javasource.JInterface;
import org.codehaus.modello.plugin.java.javasource.JSourceWriter;
import org.codehaus.modello.plugin.java.javasource.JStructure;
import org.codehaus.modello.plugin.java.metadata.JavaClassMetadata;
import org.codehaus.modello.plugin.java.metadata.JavaFieldMetadata;
import org.codehaus.modello.plugin.java.metadata.JavaModelMetadata;
import org.codehaus.plexus.util.StringUtils;
import org.codehaus.plexus.util.WriterFactory;
/**
* AbstractJavaModelloGenerator - similar in scope to {@link AbstractModelloGenerator} but with features that
* java generators can use.
*
* @author <a href="mailto:[email protected]">Joakim Erdfelt</a>
* @version $Id$
*/
public abstract class AbstractJavaModelloGenerator
extends AbstractModelloGenerator
{
protected boolean useJava5 = false;
protected void initialize( Model model, Properties parameters )
throws ModelloException
{
super.initialize( model, parameters );
useJava5 = Boolean.valueOf( getParameter( parameters,
ModelloParameterConstants.USE_JAVA5, "false" ) ).booleanValue();
}
/**
* Create a new java source file writer, with configured encoding.
*
* @param packageName the package of the source file to create
* @param className the class of the source file to create
* @return a JSourceWriter with configured encoding
* @throws IOException
*/
protected JSourceWriter newJSourceWriter( String packageName, String className )
throws IOException
{
String directory = packageName.replace( '.', File.separatorChar );
File f = new File( new File( getOutputDirectory(), directory ), className + ".java" );
if ( !f.getParentFile().exists() )
{
f.getParentFile().mkdirs();
}
OutputStream os = getBuildContext().newFileOutputStream( f );
Writer writer = ( getEncoding() == null ) ? WriterFactory.newPlatformWriter( os )
: WriterFactory.newWriter( os, getEncoding() );
return new JSourceWriter( writer );
}
private JComment getHeaderComment()
{
JComment comment = new JComment();
comment.setComment( getHeader() );
return comment;
}
protected void initHeader( JClass clazz )
{
clazz.setHeader( getHeaderComment() );
}
protected void initHeader( JInterface interfaze )
{
interfaze.setHeader( getHeaderComment() );
}
protected void suppressAllWarnings( Model objectModel, JStructure structure )
{
JavaModelMetadata javaModelMetadata = (JavaModelMetadata) objectModel.getMetadata( JavaModelMetadata.ID );
if ( useJava5 && javaModelMetadata.isSuppressAllWarnings() )
{
structure.appendAnnotation( "@SuppressWarnings( \"all\" )" );
}
}
protected void addModelImports( JClass jClass, BaseElement baseElem )
throws ModelloException
{
String basePackageName = null;
if ( baseElem != null )
{
if ( baseElem instanceof ModelInterface )
{
basePackageName =
( (ModelInterface) baseElem ).getPackageName( isPackageWithVersion(), getGeneratedVersion() );
}
else if ( baseElem instanceof ModelClass )
{
basePackageName =
( (ModelClass) baseElem ).getPackageName( isPackageWithVersion(), getGeneratedVersion() );
}
}
// import interfaces
for ( ModelInterface modelInterface : getModel().getInterfaces( getGeneratedVersion() ) )
{
String packageName = modelInterface.getPackageName( isPackageWithVersion(), getGeneratedVersion() );
if ( packageName.equals( basePackageName ) )
{
continue;
}
jClass.addImport( packageName + '.' + modelInterface.getName() );
}
// import classes
for ( ModelClass modelClass : getClasses( getModel() ) )
{
String packageName = modelClass.getPackageName( isPackageWithVersion(), getGeneratedVersion() );
if ( packageName.equals( basePackageName ) )
{
continue;
}
jClass.addImport( packageName + '.' + modelClass.getName() );
}
}
protected String getPrefix( JavaFieldMetadata javaFieldMetadata )
{
return javaFieldMetadata.isBooleanGetter() ? "is" : "get";
}
protected String getDefaultValue( ModelAssociation association )
{
String value = association.getDefaultValue();
if ( useJava5 )
{
value = StringUtils.replaceOnce( StringUtils.replaceOnce( value, "/*", "" ), "*/", "" );
}
return value;
}
protected final static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS";
protected String getJavaDefaultValue( ModelField modelField )
throws ModelloException
{
if ( "String".equals( modelField.getType() ) )
{
return '"' + modelField.getDefaultValue() + '"';
}
else if ( "char".equals( modelField.getType() ) )
{
return '\'' + modelField.getDefaultValue() + '\'';
}
else if ( "long".equals( modelField.getType() ) )
{
return modelField.getDefaultValue() + 'L';
}
else if ( "float".equals( modelField.getType() ) )
{
return modelField.getDefaultValue() + 'f';
}
else if ( "Date".equals( modelField.getType() ) )
{
DateFormat format = new SimpleDateFormat( DEFAULT_DATE_FORMAT, Locale.US );
try
{
Date date = format.parse( modelField.getDefaultValue() );
return "new java.util.Date( " + date.getTime() + "L )";
}
catch ( ParseException pe )
{
throw new ModelloException( "Unparseable default date: " + modelField.getDefaultValue(), pe );
}
}
return modelField.getDefaultValue();
}
protected String getValueChecker( String type, String value, ModelField field )
throws ModelloException
{
String retVal;
if ( "boolean".equals( type ) || "double".equals( type ) || "float".equals( type ) || "int".equals( type )
|| "long".equals( type ) || "short".equals( type ) || "byte".equals( type ) || "char".equals( type ) )
{
retVal = "if ( " + value + " != " + getJavaDefaultValue( field ) + " )";
}
else if ( ModelDefault.LIST.equals( type ) || ModelDefault.SET.equals( type )
|| ModelDefault.MAP.equals( type ) || ModelDefault.PROPERTIES.equals( type ) )
{
retVal = "if ( ( " + value + " != null ) && ( " + value + ".size() > 0 ) )";
}
else if ( "String".equals( type ) && field.getDefaultValue() != null )
{
retVal = "if ( ( " + value + " != null ) && !" + value + ".equals( \"" + field.getDefaultValue() + "\" ) )";
}
else if ( "Date".equals( type ) && field.getDefaultValue() != null )
{
retVal = "if ( ( " + value + " != null ) && !" + value + ".equals( " + getJavaDefaultValue( field ) + " ) )";
}
else
{
retVal = "if ( " + value + " != null )";
}
return retVal;
}
protected List<ModelClass> getClasses( Model model )
{
List<ModelClass> modelClasses = new ArrayList<ModelClass>();
for ( ModelClass modelClass : model.getClasses( getGeneratedVersion() ) )
{
if ( isRelevant( modelClass ) )
{
modelClasses.add( modelClass );
}
}
return modelClasses;
}
protected boolean isRelevant( ModelClass modelClass )
{
JavaClassMetadata javaClassMetadata = (JavaClassMetadata) modelClass.getMetadata( JavaClassMetadata.ID );
return javaClassMetadata != null && javaClassMetadata.isEnabled();
}
}
| o Refactored code
| modello-plugins/modello-plugin-java/src/main/java/org/codehaus/modello/plugin/java/AbstractJavaModelloGenerator.java | o Refactored code |
|
Java | mit | f0921db10e70030a737da9196375491735087b4b | 0 | DovSnier/CSSTranslateMachine | /**
*
*/
package com.dovsnier.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* <pre>
* NodeBean
* </pre>
*
* @author dovsnier
* @version 1.0.0
* @since jdk 1.7
*/
public class NodeBean implements Serializable {
private static final long serialVersionUID = 5991461693066020378L;
private String annotation;
private String nodeName;
private ArrayList<Attribute> attribute = new ArrayList<Attribute>();
private LinkedList<NodeBean> itemNode = new LinkedList<NodeBean>();
/**
* @return the annotation
*/
public String getAnnotation() {
return annotation;
}
/**
* @param annotation
* the annotation to set
*/
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
/**
* @return the nodeName
*/
public String getNodeName() {
return nodeName;
}
/**
* @param nodeName
* the nodeName to set
*/
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
/**
* @return the attribute
*/
public ArrayList<Attribute> getAttribute() {
return attribute;
}
/**
* @param attribute
* the attribute to set
*/
public void setAttribute(ArrayList<Attribute> attribute) {
this.attribute = attribute;
}
/**
* @return the itemNode
*/
public LinkedList<NodeBean> getItemNode() {
return itemNode;
}
/**
* @param itemNode
* the itemNode to set
*/
public void setItemNode(LinkedList<NodeBean> itemNode) {
this.itemNode = itemNode;
}
}
| src/com/dovsnier/bean/NodeBean.java | /**
*
*/
package com.dovsnier.bean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* <pre>
* NodeBean
* </pre>
*
* @author dovsnier
* @version 1.0.0
* @since jdk 1.7
*/
public class NodeBean implements Serializable {
private static final long serialVersionUID = 5991461693066020378L;
private String nodeName;
private ArrayList<Attribute> attribute = new ArrayList<Attribute>();
private LinkedList<NodeBean> itemNode = new LinkedList<NodeBean>();
/**
* @return the nodeName
*/
public String getNodeName() {
return nodeName;
}
/**
* @param nodeName
* the nodeName to set
*/
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
/**
* @return the attribute
*/
public ArrayList<Attribute> getAttribute() {
return attribute;
}
/**
* @param attribute
* the attribute to set
*/
public void setAttribute(ArrayList<Attribute> attribute) {
this.attribute = attribute;
}
/**
* @return the itemNode
*/
public LinkedList<NodeBean> getItemNode() {
return itemNode;
}
/**
* @param itemNode
* the itemNode to set
*/
public void setItemNode(LinkedList<NodeBean> itemNode) {
this.itemNode = itemNode;
}
}
| the NodeBean class add annotation field | src/com/dovsnier/bean/NodeBean.java | the NodeBean class add annotation field |
|
Java | mit | 29d7593c32d54e88ab608f4f5e41cf7843020692 | 0 | CS2103JAN2017-W14-B4/main,CS2103JAN2017-W14-B4/main | package guitests;
import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import mockit.Mock;
import mockit.MockUp;
import mockit.integration.junit4.JMockit;
import seedu.ezdo.commons.util.FileUtil;
import seedu.ezdo.logic.commands.SaveCommand;
//@@author A0139248X
@RunWith(JMockit.class)
public class SaveCommandTest extends EzDoGuiTest {
private final String validDirectory = "./";
private final String inexistentDirectory = "data/COWABUNGA";
@Test
public void save_validDirectory_success() {
commandBox.runCommand("save " + validDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_SAVE_TASK_SUCCESS,
validDirectory + SaveCommand.DATA_FILE_NAME));
}
@Test
public void save_invalidFormat_failure() {
commandBox.runCommand("save");
assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveCommand.MESSAGE_USAGE));
}
@Test
public void save_inexistentDirectory_failure() {
commandBox.runCommand("save " + inexistentDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_DIRECTORY_PATH_DOES_NOT_EXIST));
}
@Test
public void save_validDirectory_noAdminPermissions_failure() throws Exception {
new MockUp<FileUtil>() {
@Mock
public void createIfMissing(File file) throws IOException {
throw new IOException();
}
};
commandBox.runCommand("save " + validDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_DIRECTORY_PATH_INVALID));
}
}
| src/test/java/guitests/SaveCommandTest.java | package guitests;
import static seedu.ezdo.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT;
import java.io.File;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import mockit.Mock;
import mockit.MockUp;
import mockit.integration.junit4.JMockit;
import seedu.ezdo.commons.util.FileUtil;
import seedu.ezdo.logic.commands.SaveCommand;
//@@author A0139248X
@RunWith(JMockit.class)
public class SaveCommandTest extends EzDoGuiTest {
private final String validDirectory = "./";
private final String inexistentDirectory = "data/COWABUNGA";
@Test
public void save_validDirectory_success() {
commandBox.runCommand("save " + validDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_SAVE_TASK_SUCCESS,
validDirectory + SaveCommand.DATA_FILE_NAME));
}
@Test
public void save_invalidFormat_failure() {
commandBox.runCommand("save");
assertResultMessage(String.format(MESSAGE_INVALID_COMMAND_FORMAT, SaveCommand.MESSAGE_USAGE));
}
@Test
public void save_inexistentDirectory_failure() {
commandBox.runCommand("save " + inexistentDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_DIRECTORY_PATH_DOES_NOT_EXIST));
}
@Test
public void save_validDirectory_noAdminPermissions_failure() throws Exception {
new MockUp<FileUtil>() {
@Mock
public void createIfMissing(File file) throws IOException {
throw new IOException();
}
};
commandBox.runCommand("save " + validDirectory);
assertResultMessage(String.format(SaveCommand.MESSAGE_DIRECTORY_PATH_INVALID));
}
}
| Remove whitespace
| src/test/java/guitests/SaveCommandTest.java | Remove whitespace |
|
Java | mit | 44df0ee55ee63605e5ac96aedd963d74d6c0315e | 0 | hazendaz/oshi,dbwiddis/oshi | /**
* MIT License
*
* Copyright (c) 2010 - 2020 The OSHI Project Contributors: https://github.com/oshi/oshi/graphs/contributors
*
* 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 oshi.hardware.common;
import static oshi.util.Memoizer.memoize;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import oshi.annotation.concurrent.ThreadSafe;
import oshi.hardware.NetworkIF;
import oshi.util.FileUtil;
import oshi.util.FormatUtil;
/**
* Network interfaces implementation.
*/
@ThreadSafe
public abstract class AbstractNetworkIF implements NetworkIF {
private static final Logger LOG = LoggerFactory.getLogger(AbstractNetworkIF.class);
private static final String OSHI_VM_MAC_ADDR_PROPERTIES = "oshi.vmmacaddr.properties";
private NetworkInterface networkInterface;
private int mtu;
private String mac;
private String[] ipv4;
private Short[] subnetMasks;
private String[] ipv6;
private Short[] prefixLengths;
private final Supplier<Properties> vmMacAddrProps = memoize(AbstractNetworkIF::queryVmMacAddrProps);
/**
* Construct a {@link NetworkIF} object backed by the specified
* {@link NetworkInterface}.
*
* @param netint
* The core java {@link NetworkInterface} backing this object.
*/
protected AbstractNetworkIF(NetworkInterface netint) {
this.networkInterface = netint;
try {
// Set MTU
this.mtu = networkInterface.getMTU();
// Set MAC
byte[] hwmac = networkInterface.getHardwareAddress();
if (hwmac != null) {
List<String> octets = new ArrayList<>(6);
for (byte b : hwmac) {
octets.add(String.format("%02x", b));
}
this.mac = String.join(":", octets);
} else {
this.mac = "Unknown";
}
// Set IP arrays
ArrayList<String> ipv4list = new ArrayList<>();
ArrayList<Short> subnetMaskList = new ArrayList<>();
ArrayList<String> ipv6list = new ArrayList<>();
ArrayList<Short> prefixLengthList = new ArrayList<>();
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
InetAddress address = interfaceAddress.getAddress();
if (address.getHostAddress().length() > 0) {
if (address.getHostAddress().contains(":")) {
ipv6list.add(address.getHostAddress().split("%")[0]);
prefixLengthList.add(interfaceAddress.getNetworkPrefixLength());
} else {
ipv4list.add(address.getHostAddress());
subnetMaskList.add(interfaceAddress.getNetworkPrefixLength());
}
}
}
this.ipv4 = ipv4list.toArray(new String[0]);
this.subnetMasks = subnetMaskList.toArray(new Short[0]);
this.ipv6 = ipv6list.toArray(new String[0]);
this.prefixLengths = prefixLengthList.toArray(new Short[0]);
} catch (SocketException e) {
LOG.error("Socket exception: {}", e.getMessage());
}
}
/**
* Returns network interfaces that are not Loopback, and have a hardware
* address.
*
* @return A list of network interfaces
*/
protected static List<NetworkInterface> getNetworkInterfaces() {
List<NetworkInterface> result = new ArrayList<>();
Enumeration<NetworkInterface> interfaces = null;
try {
interfaces = NetworkInterface.getNetworkInterfaces(); // can return null
} catch (SocketException ex) {
LOG.error("Socket exception when retrieving interfaces: {}", ex.getMessage());
}
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
NetworkInterface netint = interfaces.nextElement();
try {
if (!netint.isLoopback() && netint.getHardwareAddress() != null) {
result.add(netint);
}
} catch (SocketException ex) {
LOG.error("Socket exception when retrieving interface \"{}\": {}", netint.getName(),
ex.getMessage());
}
}
}
return result;
}
@Override
public NetworkInterface queryNetworkInterface() {
return this.networkInterface;
}
@Override
public String getName() {
return this.networkInterface.getName();
}
@Override
public String getDisplayName() {
return this.networkInterface.getDisplayName();
}
@Override
public int getMTU() {
return this.mtu;
}
@Override
public String getMacaddr() {
return this.mac;
}
@Override
public String[] getIPv4addr() {
return Arrays.copyOf(this.ipv4, this.ipv4.length);
}
@Override
public Short[] getSubnetMasks() {
return Arrays.copyOf(this.subnetMasks, this.subnetMasks.length);
}
@Override
public String[] getIPv6addr() {
return Arrays.copyOf(this.ipv6, this.ipv6.length);
}
@Override
public Short[] getPrefixLengths() {
return Arrays.copyOf(this.prefixLengths, this.prefixLengths.length);
}
@Override
public boolean isKnownVmMacAddr() {
String oui = getMacaddr().length() > 7 ? getMacaddr().substring(0, 8) : getMacaddr();
return this.vmMacAddrProps.get().containsKey(oui.toUpperCase());
}
@Override
public int getIfType() {
// default
return 0;
}
@Override
public int getNdisPhysicalMediumType() {
// default
return 0;
}
@Override
public boolean isConnectorPresent() {
// default
return false;
}
private static Properties queryVmMacAddrProps() {
return FileUtil.readPropertiesFromFilename(OSHI_VM_MAC_ADDR_PROPERTIES);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Name: ").append(getName()).append(" ").append("(").append(getDisplayName()).append(")").append("\n");
sb.append(" MAC Address: ").append(getMacaddr()).append("\n");
sb.append(" MTU: ").append(getMTU()).append(", ").append("Speed: ").append(getSpeed()).append("\n");
String[] ipv4withmask = getIPv4addr();
if (this.ipv4.length == this.subnetMasks.length) {
for (int i = 0; i < this.subnetMasks.length; i++) {
ipv4withmask[i] += "/" + this.subnetMasks[i];
}
}
sb.append(" IPv4: ").append(Arrays.toString(ipv4withmask)).append("\n");
String[] ipv6withprefixlength = getIPv6addr();
if (this.ipv6.length == this.prefixLengths.length) {
for (int j = 0; j < this.prefixLengths.length; j++) {
ipv6withprefixlength[j] += "/" + this.prefixLengths[j];
}
}
sb.append(" IPv6: ").append(Arrays.toString(ipv6withprefixlength)).append("\n");
sb.append(" Traffic: received ").append(getPacketsRecv()).append(" packets/")
.append(FormatUtil.formatBytes(getBytesRecv())).append(" (" + getInErrors() + " err, ")
.append(getInDrops() + " drop);");
sb.append(" transmitted ").append(getPacketsSent()).append(" packets/")
.append(FormatUtil.formatBytes(getBytesSent())).append(" (" + getOutErrors() + " err, ")
.append(getCollisions() + " coll);");
return sb.toString();
}
}
| oshi-core/src/main/java/oshi/hardware/common/AbstractNetworkIF.java | /**
* MIT License
*
* Copyright (c) 2010 - 2020 The OSHI Project Contributors: https://github.com/oshi/oshi/graphs/contributors
*
* 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 oshi.hardware.common;
import static oshi.util.Memoizer.memoize;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import oshi.annotation.concurrent.ThreadSafe;
import oshi.hardware.NetworkIF;
import oshi.util.FileUtil;
import oshi.util.FormatUtil;
/**
* Network interfaces implementation.
*/
@ThreadSafe
public abstract class AbstractNetworkIF implements NetworkIF {
private static final Logger LOG = LoggerFactory.getLogger(AbstractNetworkIF.class);
private static final String OSHI_VM_MAC_ADDR_PROPERTIES = "oshi.vmmacaddr.properties";
private NetworkInterface networkInterface;
private int mtu;
private String mac;
private String[] ipv4;
private Short[] subnetMasks;
private String[] ipv6;
private Short[] prefixLengths;
private final Supplier<Properties> vmMacAddrProps = memoize(AbstractNetworkIF::queryVmMacAddrProps);
/**
* Construct a {@link NetworkIF} object backed by the specified
* {@link NetworkInterface}.
*
* @param netint
* The core java {@link NetworkInterface} backing this object.
*/
protected AbstractNetworkIF(NetworkInterface netint) {
this.networkInterface = netint;
try {
// Set MTU
this.mtu = networkInterface.getMTU();
// Set MAC
byte[] hwmac = networkInterface.getHardwareAddress();
if (hwmac != null) {
List<String> octets = new ArrayList<>(6);
for (byte b : hwmac) {
octets.add(String.format("%02x", b));
}
this.mac = String.join(":", octets);
} else {
this.mac = "Unknown";
}
// Set IP arrays
ArrayList<String> ipv4list = new ArrayList<>();
ArrayList<Short> subnetMaskList = new ArrayList<>();
ArrayList<String> ipv6list = new ArrayList<>();
ArrayList<Short> prefixLengthList = new ArrayList<>();
for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
InetAddress address = interfaceAddress.getAddress();
if (address.getHostAddress().length() > 0) {
if (address.getHostAddress().contains(":")) {
ipv6list.add(address.getHostAddress().split("%")[0]);
prefixLengthList.add(interfaceAddress.getNetworkPrefixLength());
} else {
ipv4list.add(address.getHostAddress());
subnetMaskList.add(interfaceAddress.getNetworkPrefixLength());
}
}
}
this.ipv4 = ipv4list.toArray(new String[0]);
this.subnetMasks = subnetMaskList.toArray(new Short[0]);
this.ipv6 = ipv6list.toArray(new String[0]);
this.prefixLengths = prefixLengthList.toArray(new Short[0]);
} catch (SocketException e) {
LOG.error("Socket exception: {}", e.getMessage());
}
}
/**
* Returns network interfaces that are not Loopback, and have a hardware
* address.
*
* @return A list of network interfaces
*/
protected static List<NetworkInterface> getNetworkInterfaces() {
List<NetworkInterface> result = new ArrayList<>();
Enumeration<NetworkInterface> interfaces = null;
try {
interfaces = NetworkInterface.getNetworkInterfaces(); // can return null
} catch (SocketException ex) {
LOG.error("Socket exception when retrieving interfaces: {}", ex.getMessage());
}
if (interfaces != null) {
while (interfaces.hasMoreElements()) {
NetworkInterface netint = interfaces.nextElement();
try {
if (!netint.isLoopback() && netint.getHardwareAddress() != null) {
result.add(netint);
}
} catch (SocketException ex) {
LOG.error("Socket exception when retrieving interface \"{}\": {}", netint.getName(),
ex.getMessage());
}
}
}
return result;
}
@Override
public NetworkInterface queryNetworkInterface() {
return this.networkInterface;
}
@Override
public String getName() {
return this.networkInterface.getName();
}
@Override
public String getDisplayName() {
return this.networkInterface.getDisplayName();
}
@Override
public int getMTU() {
return this.mtu;
}
@Override
public String getMacaddr() {
return this.mac;
}
@Override
public String[] getIPv4addr() {
return Arrays.copyOf(this.ipv4, this.ipv4.length);
}
@Override
public Short[] getSubnetMasks() {
return Arrays.copyOf(this.subnetMasks, this.subnetMasks.length);
}
@Override
public String[] getIPv6addr() {
return Arrays.copyOf(this.ipv6, this.ipv6.length);
}
@Override
public Short[] getPrefixLengths() {
return Arrays.copyOf(this.prefixLengths, this.prefixLengths.length);
}
@Override
public boolean isKnownVmMacAddr() {
String oui = getMacaddr().length() > 7 ? getMacaddr().substring(0, 8) : getMacaddr();
return this.vmMacAddrProps.get().containsKey(oui.toUpperCase());
}
@Override
public int getIfType() {
// default
return 0;
}
@Override
public int getNdisPhysicalMediumType() {
// default
return 0;
}
@Override
public boolean isConnectorPresent() {
// default
return false;
}
private static Properties queryVmMacAddrProps() {
return FileUtil.readPropertiesFromFilename(OSHI_VM_MAC_ADDR_PROPERTIES);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Name: ").append(getName()).append(" ").append("(").append(getDisplayName()).append(")").append("\n");
sb.append(" MAC Address: ").append(getMacaddr()).append("\n");
sb.append(" MTU: ").append(getMTU()).append(", ").append("Speed: ").append(getSpeed()).append("\n");
sb.append(" IPv4: ").append(Arrays.toString(getIPv4addr())).append("\n");
sb.append(" Netmask: ").append(Arrays.toString(getSubnetMasks())).append("\n");
sb.append(" IPv6: ").append(Arrays.toString(getIPv6addr())).append("\n");
sb.append(" Prefix Lengths: ").append(Arrays.toString(getPrefixLengths())).append("\n");
sb.append(" Traffic: received ").append(getPacketsRecv()).append(" packets/")
.append(FormatUtil.formatBytes(getBytesRecv())).append(" (" + getInErrors() + " err, ")
.append(getInDrops() + " drop);");
sb.append(" transmitted ").append(getPacketsSent()).append(" packets/")
.append(FormatUtil.formatBytes(getBytesSent())).append(" (" + getOutErrors() + " err, ")
.append(getCollisions() + " coll);");
return sb.toString();
}
}
| Outputs for IPv4 & subnetMask and IPv6 & prefix lengths combined (#1261)
| oshi-core/src/main/java/oshi/hardware/common/AbstractNetworkIF.java | Outputs for IPv4 & subnetMask and IPv6 & prefix lengths combined (#1261) |
|
Java | mit | 47ab0a5d4f8da0c0be0f1b16581fd00bdb9eef2d | 0 | getsentry/react-native-sentry,getsentry/react-native-sentry,getsentry/react-native-sentry,getsentry/react-native-sentry,getsentry/react-native-sentry,getsentry/react-native-sentry | package io.sentry;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.ReadableType;
import com.getsentry.raven.Raven;
import com.getsentry.raven.android.AndroidRaven;
import com.getsentry.raven.android.event.helper.AndroidEventBuilderHelper;
import com.getsentry.raven.dsn.Dsn;
import com.getsentry.raven.event.Breadcrumb;
import com.getsentry.raven.event.BreadcrumbBuilder;
import com.getsentry.raven.event.Event;
import com.getsentry.raven.event.EventBuilder;
import com.getsentry.raven.event.UserBuilder;
import com.getsentry.raven.event.interfaces.UserInterface;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
public class RNSentryModule extends ReactContextBaseJavaModule {
private final ReactApplicationContext reactContext;
final static Logger logger = Logger.getLogger("react-native-sentry");
private ReadableMap extra;
private ReadableMap tags;
public RNSentryModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
}
@Override
public String getName() {
return "RNSentry";
}
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put("nativeClientAvailable", true);
return constants;
}
@ReactMethod
public void startWithDsnString(String dsnString) {
AndroidRaven.init(this.getReactApplicationContext(), new Dsn(dsnString));
logger.info(String.format("startWithDsnString '%s'", dsnString));
}
@ReactMethod
public void setLogLevel(int level) {
logger.setLevel(this.logLevel(level));
}
@ReactMethod
public void setExtra(ReadableMap extra) {
this.extra = extra;
}
@ReactMethod
public void setTags(ReadableMap tags) {
this.tags = tags;
}
@ReactMethod
public void setUser(ReadableMap user) {
Raven.getStoredInstance().getContext().setUser(
new UserBuilder()
.setEmail(user.getString("email"))
.setId(user.getString("userID"))
.setUsername(user.getString("username"))
.build()
);
}
@ReactMethod
public void crash() {
throw new RuntimeException("TEST - Sentry Client Crash");
}
@ReactMethod
public void captureBreadcrumb(ReadableMap breadcrumb) {
logger.info(String.format("captureEvent '%s'", breadcrumb));
if (breadcrumb.hasKey("message")) {
Raven.record(
new BreadcrumbBuilder()
.setMessage(breadcrumb.getString("message"))
.setCategory(breadcrumb.getString("category"))
.setLevel(breadcrumbLevel(breadcrumb.getString("level")))
.build()
);
}
}
@ReactMethod
public void captureEvent(ReadableMap event) {
if (event.hasKey("message")) {
AndroidEventBuilderHelper helper = new AndroidEventBuilderHelper(this.getReactApplicationContext());
EventBuilder eventBuilder = new EventBuilder()
.withMessage(event.getString("message"))
.withLogger(event.getString("logger"))
.withLevel(eventLevel(event.getString("level")));
eventBuilder.withSentryInterface(
new UserInterface(
event.getMap("user").getString("userID"),
event.getMap("user").getString("username"),
null,
event.getMap("user").getString("email")
)
);
helper.helpBuildingEvent(eventBuilder);
for (Map.Entry<String, Object> entry : recursivelyDeconstructReadableMap(event.getMap("extra")).entrySet()) {
eventBuilder.withExtra(entry.getKey(), entry.getValue());
}
if (this.extra != null) {
for (Map.Entry<String, Object> entry : recursivelyDeconstructReadableMap(this.extra).entrySet()) {
eventBuilder.withExtra(entry.getKey(), entry.getValue());
}
}
for (Map.Entry<String, Object> entry : recursivelyDeconstructReadableMap(event.getMap("tags")).entrySet()) {
eventBuilder.withTag(entry.getKey(), entry.getValue().toString());
}
if (this.tags != null) {
for (Map.Entry<String, Object> entry : recursivelyDeconstructReadableMap(this.tags).entrySet()) {
eventBuilder.withExtra(entry.getKey(), entry.getValue());
}
}
Raven.capture(eventBuilder.build());
} else {
logger.info("Event has no key message which means it is a js error");
}
}
@ReactMethod
public void clearContext() {
Raven.getStoredInstance().getContext().clear();
}
@ReactMethod
public void activateStacktraceMerging(Promise promise) {
logger.info("TODO: implement activateStacktraceMerging");
promise.resolve(true);
}
private Breadcrumb.Level breadcrumbLevel(String level) {
switch (level) {
case "critical":
return Breadcrumb.Level.CRITICAL;
case "warning":
return Breadcrumb.Level.WARNING;
case "info":
return Breadcrumb.Level.INFO;
case "debug":
return Breadcrumb.Level.DEBUG;
default:
return Breadcrumb.Level.ERROR;
}
}
private Event.Level eventLevel(String level) {
switch (level) {
case "fatal":
return Event.Level.FATAL;
case "warning":
return Event.Level.WARNING;
case "info":
return Event.Level.INFO;
case "debug":
return Event.Level.DEBUG;
default:
return Event.Level.ERROR;
}
}
private Level logLevel(int level) {
switch (level) {
case 1:
return Level.SEVERE;
case 2:
return Level.INFO;
case 3:
return Level.ALL;
default:
return Level.OFF;
}
}
private Map<String, Object> recursivelyDeconstructReadableMap(ReadableMap readableMap) {
ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
Map<String, Object> deconstructedMap = new HashMap<>();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableType type = readableMap.getType(key);
switch (type) {
case Null:
deconstructedMap.put(key, null);
break;
case Boolean:
deconstructedMap.put(key, readableMap.getBoolean(key));
break;
case Number:
deconstructedMap.put(key, readableMap.getDouble(key));
break;
case String:
deconstructedMap.put(key, readableMap.getString(key));
break;
case Map:
deconstructedMap.put(key, recursivelyDeconstructReadableMap(readableMap.getMap(key)));
break;
case Array:
deconstructedMap.put(key, recursivelyDeconstructReadableArray(readableMap.getArray(key)));
break;
default:
throw new IllegalArgumentException("Could not convert object with key: " + key + ".");
}
}
return deconstructedMap;
}
private List<Object> recursivelyDeconstructReadableArray(ReadableArray readableArray) {
List<Object> deconstructedList = new ArrayList<>(readableArray.size());
for (int i = 0; i < readableArray.size(); i++) {
ReadableType indexType = readableArray.getType(i);
switch (indexType) {
case Null:
deconstructedList.add(i, null);
break;
case Boolean:
deconstructedList.add(i, readableArray.getBoolean(i));
break;
case Number:
deconstructedList.add(i, readableArray.getDouble(i));
break;
case String:
deconstructedList.add(i, readableArray.getString(i));
break;
case Map:
deconstructedList.add(i, recursivelyDeconstructReadableMap(readableArray.getMap(i)));
break;
case Array:
deconstructedList.add(i, recursivelyDeconstructReadableArray(readableArray.getArray(i)));
break;
default:
throw new IllegalArgumentException("Could not convert object at index " + i + ".");
}
}
return deconstructedList;
}
}
| android/src/main/java/io/sentry/RNSentryModule.java | package io.sentry;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.ReadableType;
import com.getsentry.raven.RavenFactory;
import com.getsentry.raven.Raven;
import com.getsentry.raven.android.AndroidRaven;
import com.getsentry.raven.android.AndroidRavenFactory;
import com.getsentry.raven.android.event.helper.AndroidEventBuilderHelper;
import com.getsentry.raven.dsn.Dsn;
import com.getsentry.raven.event.Breadcrumb;
import com.getsentry.raven.event.Event;
import com.getsentry.raven.event.EventBuilder;
import com.getsentry.raven.context.Context;
import com.getsentry.raven.event.BreadcrumbBuilder;
import com.getsentry.raven.event.UserBuilder;
import com.getsentry.raven.event.interfaces.ExceptionInterface;
import com.getsentry.raven.event.interfaces.SentryException;
import com.getsentry.raven.event.interfaces.SentryStackTraceElement;
import com.getsentry.raven.event.interfaces.StackTraceInterface;
import com.getsentry.raven.event.interfaces.UserInterface;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
public class RNSentryModule extends ReactContextBaseJavaModule {
private final ReactApplicationContext reactContext;
final static Logger logger = Logger.getLogger("react-native-sentry");
public RNSentryModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
}
@Override
public String getName() {
return "RNSentry";
}
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put("nativeClientAvailable", true);
return constants;
}
@ReactMethod
public void startWithDsnString(String dsnString) {
AndroidRaven.init(this.getReactApplicationContext(), new Dsn(dsnString));
logger.info(String.format("startWithDsnString '%s'", dsnString));
}
@ReactMethod
public void setLogLevel(int level) {
logger.info("TODO: implement setLogLevel");
}
@ReactMethod
public void setExtra(ReadableMap extras) {
logger.info("TODO: implement setExtra");
}
@ReactMethod
public void setTags(ReadableMap tags) {
logger.info("TODO: implement setTags");
}
@ReactMethod
public void setUser(ReadableMap user) {
Raven.getStoredInstance().getContext().setUser(
new UserBuilder()
.setEmail(user.getString("email"))
.setId(user.getString("userID"))
.setUsername(user.getString("username"))
.build()
);
}
@ReactMethod
public void crash() {
throw new RuntimeException("Sentry TEST Crash");
}
@ReactMethod
public void captureBreadcrumb(ReadableMap breadcrumb) {
logger.info(String.format("captureEvent '%s'", breadcrumb));
if (breadcrumb.hasKey("message")) {
Raven.record(
new BreadcrumbBuilder()
.setMessage(breadcrumb.getString("message"))
.setCategory(breadcrumb.getString("category"))
.setLevel(breadcrumbLevel(breadcrumb.getString("level")))
.build()
);
}
}
@ReactMethod
public void captureEvent(ReadableMap event) {
if (event.hasKey("message")) {
AndroidEventBuilderHelper helper = new AndroidEventBuilderHelper(this.getReactApplicationContext());
EventBuilder eventBuilder = new EventBuilder()
.withMessage(event.getString("message"))
.withLogger(event.getString("logger"))
.withLevel(eventLevel(event.getString("level")));
eventBuilder.withSentryInterface(
new UserInterface(
event.getMap("user").getString("userID"),
event.getMap("user").getString("username"),
null,
event.getMap("user").getString("email")
)
);
helper.helpBuildingEvent(eventBuilder);
for (Map.Entry<String, Object> entry : recursivelyDeconstructReadableMap(event.getMap("extra")).entrySet()) {
eventBuilder.withExtra(entry.getKey(), entry.getValue());
}
for (Map.Entry<String, Object> entry : recursivelyDeconstructReadableMap(event.getMap("tags")).entrySet()) {
eventBuilder.withTag(entry.getKey(), entry.getValue().toString());
}
Raven.capture(eventBuilder.build());
} else {
logger.info("event has no key message that means it is a js error");
}
}
@ReactMethod
public void clearContext() {
Raven.getStoredInstance().getContext().clear();
}
@ReactMethod
public void activateStacktraceMerging(Promise promise) {
logger.info("TODO: implement activateStacktraceMerging");
// try {
promise.resolve(true);
// } catch (IllegalViewOperationException e) {
// promise.reject(E_LAYOUT_ERROR, e);
// }
}
private Breadcrumb.Level breadcrumbLevel(String level) {
switch (level) {
case "critical":
return Breadcrumb.Level.CRITICAL;
case "warning":
return Breadcrumb.Level.WARNING;
case "info":
return Breadcrumb.Level.INFO;
case "debug":
return Breadcrumb.Level.DEBUG;
default:
return Breadcrumb.Level.ERROR;
}
}
private Event.Level eventLevel(String level) {
switch (level) {
case "fatal":
return Event.Level.FATAL;
case "warning":
return Event.Level.WARNING;
case "info":
return Event.Level.INFO;
case "debug":
return Event.Level.DEBUG;
default:
return Event.Level.ERROR;
}
}
private Map<String, Object> recursivelyDeconstructReadableMap(ReadableMap readableMap) {
ReadableMapKeySetIterator iterator = readableMap.keySetIterator();
Map<String, Object> deconstructedMap = new HashMap<>();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableType type = readableMap.getType(key);
switch (type) {
case Null:
deconstructedMap.put(key, null);
break;
case Boolean:
deconstructedMap.put(key, readableMap.getBoolean(key));
break;
case Number:
deconstructedMap.put(key, readableMap.getDouble(key));
break;
case String:
deconstructedMap.put(key, readableMap.getString(key));
break;
case Map:
deconstructedMap.put(key, recursivelyDeconstructReadableMap(readableMap.getMap(key)));
break;
case Array:
deconstructedMap.put(key, recursivelyDeconstructReadableArray(readableMap.getArray(key)));
break;
default:
throw new IllegalArgumentException("Could not convert object with key: " + key + ".");
}
}
return deconstructedMap;
}
private List<Object> recursivelyDeconstructReadableArray(ReadableArray readableArray) {
List<Object> deconstructedList = new ArrayList<>(readableArray.size());
for (int i = 0; i < readableArray.size(); i++) {
ReadableType indexType = readableArray.getType(i);
switch (indexType) {
case Null:
deconstructedList.add(i, null);
break;
case Boolean:
deconstructedList.add(i, readableArray.getBoolean(i));
break;
case Number:
deconstructedList.add(i, readableArray.getDouble(i));
break;
case String:
deconstructedList.add(i, readableArray.getString(i));
break;
case Map:
deconstructedList.add(i, recursivelyDeconstructReadableMap(readableArray.getMap(i)));
break;
case Array:
deconstructedList.add(i, recursivelyDeconstructReadableArray(readableArray.getArray(i)));
break;
default:
throw new IllegalArgumentException("Could not convert object at index " + i + ".");
}
}
return deconstructedList;
}
}
| Implements setTags, setExtra, setLogLevel
| android/src/main/java/io/sentry/RNSentryModule.java | Implements setTags, setExtra, setLogLevel |
|
Java | mit | d491277fd7f2ae9516a41a96b8c8b9bb6befaebd | 0 | ijidan/kpush,yangkf1985/kpush,chengjunjian/kpush,ijidan/kpush,yangkf1985/kpush,ZhQYuan/kpush,ijidan/kpush,ZhQYuan/kpush,xiaokunLee/kpush,ijidan/kpush,yangkf1985/kpush,chengjunjian/kpush,chengjunjian/kpush,ijidan/kpush,xiaokunLee/kpush,ZhQYuan/kpush,xiaokunLee/kpush,chengjunjian/kpush,xiaokunLee/kpush,ZhQYuan/kpush,xiaokunLee/kpush,chengjunjian/kpush,yangkf1985/kpush,ZhQYuan/kpush,yangkf1985/kpush | package cn.vimer.kpush;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import cn.vimer.ferry.Ferry;
import cn.vimer.kpush_demo.Constants;
import cn.vimer.netkit.Box;
import cn.vimer.netkit.IBox;
/**
* Created by dantezhu on 15-4-13.
*/
public class PushService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(Constants.LOG_TAG, "onCreate");
regEventCallback();
Ferry.getInstance().init("192.168.1.77", 29000);
Ferry.getInstance().start();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 每次发intent都会进来,可以重复进入
Log.d(Constants.LOG_TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(Constants.LOG_TAG, "onDestory");
}
private void regEventCallback() {
Ferry.getInstance().addEventCallback(new Ferry.CallbackListener() {
@Override
public void onOpen() {
Log.d(Constants.LOG_TAG, "onOpen");
Box box = new Box();
box.version = 100;
box.flag = 99;
box.cmd = 1;
box.body = new String("I love you").getBytes();
Ferry.getInstance().send(box, new Ferry.CallbackListener() {
@Override
public void onSend(IBox ibox) {
Log.d(Constants.LOG_TAG, String.format("onSend, box: %s", ibox));
}
@Override
public void onRecv(IBox ibox) {
Log.d(Constants.LOG_TAG, String.format("onRecv, box: %s", ibox));
}
@Override
public void onError(int code, IBox ibox) {
Log.d(Constants.LOG_TAG, String.format("onError, code: %s, box: %s", code, ibox));
}
@Override
public void onTimeout() {
Log.d(Constants.LOG_TAG, "onTimeout");
}
}, 5, this);
}
@Override
public void onRecv(IBox ibox) {
Log.d(Constants.LOG_TAG, String.format("onRecv, box: %s", ibox));
}
@Override
public void onClose() {
Log.d(Constants.LOG_TAG, "onClose");
Ferry.getInstance().connect();
}
@Override
public void onError(int code, IBox ibox) {
Log.d(Constants.LOG_TAG, String.format("onError, code: %s, box: %s", code, ibox));
}
}, this, "ok");
}
}
| android/kpush_demo/src/cn/vimer/kpush/PushService.java | package cn.vimer.kpush;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import cn.vimer.kpush_demo.Constants;
/**
* Created by dantezhu on 15-4-13.
*/
public class PushService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(Constants.LOG_TAG, "onCreate");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 每次发intent都会进来,可以重复进入
Log.d(Constants.LOG_TAG, "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(Constants.LOG_TAG, "onDestory");
}
}
| 用protobuf
| android/kpush_demo/src/cn/vimer/kpush/PushService.java | 用protobuf |
|
Java | mpl-2.0 | 5e082988fdc6db6280e8379a21dabe4a93734d4b | 0 | PawelGutkowski/openmrs-sdk,AdamGrzybkowski/openmrs-sdk,AdamGrzybkowski/openmrs-sdk,AdamGrzybkowski/openmrs-sdk,PawelGutkowski/openmrs-sdk,PawelGutkowski/openmrs-sdk,PawelGutkowski/openmrs-sdk,AdamGrzybkowski/openmrs-sdk | package org.openmrs.maven.plugins;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.core.DockerClientBuilder;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.components.interactivity.Prompter;
import org.codehaus.plexus.components.interactivity.PrompterException;
import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
abstract class AbstractDockerMojo extends AbstractMojo {
protected static final String DEFAULT_MYSQL_CONTAINER = "openmrs-sdk-mysql";
protected static final String DEFAULT_MYSQL_PASSWORD = "Admin123";
protected static final String MYSQL_5_6 = "mysql:5.6";
protected static final String DEFAULT_MYSQL_EXPOSED_PORT = "3307";
protected static final String DEFAULT_MYSQL_DBURI = "jdbc:mysql://localhost:3307/";
private static final String DEFAULT_HOST_LINUX = "unix:///var/run/docker.sock";
/**
* Option to include demo data
*
* @parameter expression="${dockerHost}"
*/
protected String dockerHost;
/**
* @component
* @required
*/
protected Prompter prompter;
protected DockerClient docker;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
resolveDocker();
executeTask();
try {
docker.close();
} catch (IOException e) {
throw new MojoExecutionException("Failed to close Docker client");
}
}
public abstract void executeTask() throws MojoExecutionException, MojoFailureException;
protected void resolveDocker() {
if(dockerHost == null){
boolean isLinux = SystemUtils.IS_OS_LINUX;
if(isLinux){
dockerHost = prompt("Please specify your Docker host URL (either 'tcp://' or 'unix://')", DEFAULT_HOST_LINUX);
} else {
dockerHost = prompt("Please specify you Docker Machine host URL (format is: 'tcp://{docker-machine url}')","");
}
}
docker = DockerClientBuilder.getInstance(dockerHost).build();
}
protected Container findContainer(String id){
List<Container> containers = docker.listContainersCmd().withShowAll(true).exec();
for (Container container : containers) {
if (container.getId().equals(id)) {
return container;
}
}
String name = "/"+id;
for (Container container: containers) {
if (Arrays.asList(container.getNames()).contains(name)) {
return container;
}
}
for (Container container: containers) {
if (container.getLabels().containsKey(id)) {
return container;
}
}
return null;
}
protected String prompt(String message, String defaultValue) {
try {
if(StringUtils.isNotBlank(defaultValue)){
message = message+String.format(" (default: '%s')", defaultValue);
}
String answer = prompter.prompt("\n"+message);
if(StringUtils.isNotBlank(answer)){
return answer;
} else {
return defaultValue;
}
} catch (PrompterException e) {
throw new RuntimeException("Failed to prompt", e);
}
}
protected String prompt(String message) {
try {
String answer = prompter.prompt(message);
if(StringUtils.isBlank(answer)) return prompt(message);
else return answer;
} catch (PrompterException e) {
throw new RuntimeException("Failed to prompt", e);
}
}
protected void showMessage(String message) {
System.out.println("\n" + message);
}
}
| docker-maven-plugin/src/main/java/org/openmrs/maven/plugins/AbstractDockerMojo.java | package org.openmrs.maven.plugins;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.model.Container;
import com.github.dockerjava.api.model.Frame;
import com.github.dockerjava.core.DockerClientBuilder;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.codehaus.plexus.components.interactivity.Prompter;
import org.codehaus.plexus.components.interactivity.PrompterException;
import java.io.Closeable;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
abstract class AbstractDockerMojo extends AbstractMojo {
protected static final String DEFAULT_MYSQL_CONTAINER = "openmrs-sdk-mysql";
protected static final String DEFAULT_MYSQL_PASSWORD = "Admin123";
protected static final String MYSQL_5_6 = "mysql:5.6";
protected static final String DEFAULT_MYSQL_EXPOSED_PORT = "3307";
protected static final String DEFAULT_MYSQL_DBURI = "jdbc:mysql://localhost:3307/";
private static final String DEFAULT_HOST_LINUX = "unix:///var/run/docker.sock";
/**
* Option to include demo data
*
* @parameter expression="${dockerHost}"
*/
protected String dockerHost;
/**
* @component
* @required
*/
protected Prompter prompter;
protected DockerClient docker;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
resolveDocker();
executeTask();
try {
docker.close();
} catch (IOException e) {
throw new MojoExecutionException("Failed to close Docker client");
}
}
public abstract void executeTask() throws MojoExecutionException, MojoFailureException;
protected void resolveDocker() {
if(dockerHost == null){
boolean isLinux = SystemUtils.IS_OS_LINUX;
if(isLinux){
dockerHost = prompt("Please specify your Docker host URL (either 'tcp://' or 'unix://')", DEFAULT_HOST_LINUX);
} else {
dockerHost = prompt("Please specify you Docker Machine host URL (format is: 'tcp://{docker-machine url}')","");
}
}
docker = DockerClientBuilder.getInstance(dockerHost).build();
}
protected Container findContainer(String id){
List<Container> containers = docker.listContainersCmd().withShowAll(true).exec();
for (Container container : containers) {
if (container.getId().equals(id)) {
return container;
}
}
for (Container container: containers) {
if (Arrays.asList(container.getNames()).contains(id)) {
return container;
}
}
for (Container container: containers) {
if (container.getLabels().containsKey(id)) {
return container;
}
}
return null;
}
protected String prompt(String message, String defaultValue) {
try {
if(StringUtils.isNotBlank(defaultValue)){
message = message+String.format(" (default: '%s')", defaultValue);
}
String answer = prompter.prompt("\n"+message);
if(StringUtils.isNotBlank(answer)){
return answer;
} else {
return defaultValue;
}
} catch (PrompterException e) {
throw new RuntimeException("Failed to prompt", e);
}
}
protected String prompt(String message) {
try {
String answer = prompter.prompt(message);
if(StringUtils.isBlank(answer)) return prompt(message);
else return answer;
} catch (PrompterException e) {
throw new RuntimeException("Failed to prompt", e);
}
}
protected void showMessage(String message) {
System.out.println("\n" + message);
}
}
| SDK-130 fix query in searching container by name
| docker-maven-plugin/src/main/java/org/openmrs/maven/plugins/AbstractDockerMojo.java | SDK-130 fix query in searching container by name |
|
Java | agpl-3.0 | f34fb812812cc1bbb1bdcac88ce446d82d98bc08 | 0 | deerwalk/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,simonzhangsm/voltdb,VoltDB/voltdb,deerwalk/voltdb,VoltDB/voltdb,deerwalk/voltdb,VoltDB/voltdb,simonzhangsm/voltdb,simonzhangsm/voltdb,VoltDB/voltdb,VoltDB/voltdb,simonzhangsm/voltdb,VoltDB/voltdb,simonzhangsm/voltdb,deerwalk/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,VoltDB/voltdb,simonzhangsm/voltdb,deerwalk/voltdb,deerwalk/voltdb | /* This file is part of VoltDB.
* Copyright (C) 2008-2017 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.sysprocs;
import java.util.List;
import java.util.Map;
import org.apache.zookeeper_voltpatches.KeeperException.BadVersionException;
import org.apache.zookeeper_voltpatches.KeeperException.Code;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.apache.zookeeper_voltpatches.data.Stat;
import org.voltcore.logging.VoltLogger;
import org.voltdb.DependencyPair;
import org.voltdb.OperationMode;
import org.voltdb.ParameterSet;
import org.voltdb.ProcInfo;
import org.voltdb.SystemProcedureExecutionContext;
import org.voltdb.VoltDB;
import org.voltdb.VoltDBInterface;
import org.voltdb.VoltSystemProcedure;
import org.voltdb.VoltTable;
import org.voltdb.VoltZK;
import org.voltdb.snmp.SnmpTrapSender;
@ProcInfo(singlePartition = false)
public class Pause extends VoltSystemProcedure {
private final static VoltLogger LOG = new VoltLogger("HOST");
protected volatile Stat m_stat = null;
private final static OperationMode PAUSED = OperationMode.PAUSED;
@Override
public void init() {}
@Override
public DependencyPair executePlanFragment(
Map<Integer, List<VoltTable>> dependencies, long fragmentId,
ParameterSet params, SystemProcedureExecutionContext context)
{
throw new RuntimeException("Pause was given an " +
"invalid fragment id: " + String.valueOf(fragmentId));
}
protected static String ll(long l) {
return Long.toString(l, Character.MAX_RADIX);
}
/**
* Enter admin mode
* @param ctx Internal parameter. Not user-accessible.
* @return Standard STATUS table.
*/
public VoltTable[] run(SystemProcedureExecutionContext ctx) {
// Choose the lowest site ID on this host to actually flip the bit
if (ctx.isLowestSiteId()) {
VoltDBInterface voltdb = VoltDB.instance();
OperationMode opMode = voltdb.getMode();
if (LOG.isDebugEnabled()) {
LOG.debug("voltdb opmode is " + opMode);
}
ZooKeeper zk = voltdb.getHostMessenger().getZK();
try {
Stat stat;
OperationMode zkMode = null;
Code code;
do {
stat = new Stat();
code = Code.BADVERSION;
try {
byte [] data = zk.getData(VoltZK.operationMode, false, stat);
if (LOG.isDebugEnabled()) {
LOG.debug("zkMode is " + (zkMode == null ? "(null)" : OperationMode.valueOf(data)));
}
zkMode = data == null ? opMode : OperationMode.valueOf(data);
if (zkMode == PAUSED) {
if (LOG.isDebugEnabled()) {
LOG.debug("read node at version " + stat.getVersion() + ", txn " + ll(stat.getMzxid()));
}
break;
}
stat = zk.setData(VoltZK.operationMode, PAUSED.getBytes(), stat.getVersion());
code = Code.OK;
zkMode = PAUSED;
if (LOG.isDebugEnabled()) {
LOG.debug("!WROTE! node at version " + stat.getVersion() + ", txn " + ll(stat.getMzxid()));
}
break;
} catch (BadVersionException ex) {
code = ex.code();
}
} while (zkMode != PAUSED && code == Code.BADVERSION);
m_stat = stat;
voltdb.getHostMessenger().pause();
voltdb.setMode(PAUSED);
// for snmp
SnmpTrapSender snmp = voltdb.getSnmpTrapSender();
if (snmp != null) {
snmp.pause("Cluster paused.");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Force a tick so that stats will be updated.
// Primarily added to get latest table stats for DR pause and empty db check.
ctx.getSiteProcedureConnection().tick();
VoltTable t = new VoltTable(VoltSystemProcedure.STATUS_SCHEMA);
t.addRow(VoltSystemProcedure.STATUS_OK);
return (new VoltTable[] {t});
}
}
| src/frontend/org/voltdb/sysprocs/Pause.java | /* This file is part of VoltDB.
* Copyright (C) 2008-2017 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.sysprocs;
import java.util.List;
import java.util.Map;
import org.apache.zookeeper_voltpatches.KeeperException.BadVersionException;
import org.apache.zookeeper_voltpatches.KeeperException.Code;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.apache.zookeeper_voltpatches.data.Stat;
import org.voltcore.logging.VoltLogger;
import org.voltdb.DependencyPair;
import org.voltdb.OperationMode;
import org.voltdb.ParameterSet;
import org.voltdb.ProcInfo;
import org.voltdb.SystemProcedureExecutionContext;
import org.voltdb.VoltDB;
import org.voltdb.VoltDBInterface;
import org.voltdb.VoltSystemProcedure;
import org.voltdb.VoltTable;
import org.voltdb.VoltZK;
import org.voltdb.snmp.SnmpTrapSender;
@ProcInfo(singlePartition = false)
public class Pause extends VoltSystemProcedure {
private final static VoltLogger LOG = new VoltLogger("HOST");
protected volatile Stat m_stat = null;
private final static OperationMode PAUSED = OperationMode.PAUSED;
@Override
public void init() {}
@Override
public DependencyPair executePlanFragment(
Map<Integer, List<VoltTable>> dependencies, long fragmentId,
ParameterSet params, SystemProcedureExecutionContext context)
{
throw new RuntimeException("Pause was given an " +
"invalid fragment id: " + String.valueOf(fragmentId));
}
protected static String ll(long l) {
return Long.toString(l, Character.MAX_RADIX);
}
/**
* Enter admin mode
* @param ctx Internal parameter. Not user-accessible.
* @return Standard STATUS table.
*/
public VoltTable[] run(SystemProcedureExecutionContext ctx) {
// Choose the lowest site ID on this host to actually flip the bit
if (ctx.isLowestSiteId()) {
VoltDBInterface voltdb = VoltDB.instance();
OperationMode opMode = voltdb.getMode();
if (LOG.isDebugEnabled()) {
LOG.debug("voltdb opmode is " + opMode);
}
ZooKeeper zk = voltdb.getHostMessenger().getZK();
try {
Stat stat;
OperationMode zkMode = null;
Code code;
do {
stat = new Stat();
code = Code.BADVERSION;
try {
byte [] data = zk.getData(VoltZK.operationMode, false, stat);
if (LOG.isDebugEnabled()) {
LOG.debug("zkMode is " + (zkMode == null ? "(null)" : OperationMode.valueOf(data)));
}
zkMode = data == null ? opMode : OperationMode.valueOf(data);
if (zkMode == PAUSED) {
if (LOG.isDebugEnabled()) {
LOG.debug("read node at version " + stat.getVersion() + ", txn " + ll(stat.getMzxid()));
}
break;
}
stat = zk.setData(VoltZK.operationMode, PAUSED.getBytes(), stat.getVersion());
code = Code.OK;
zkMode = PAUSED;
if (LOG.isDebugEnabled()) {
LOG.debug("!WROTE! node at version " + stat.getVersion() + ", txn " + ll(stat.getMzxid()));
}
break;
} catch (BadVersionException ex) {
code = ex.code();
}
} while (zkMode != PAUSED && code == Code.BADVERSION);
m_stat = stat;
voltdb.getHostMessenger().pause();
voltdb.setMode(PAUSED);
// for snmp
SnmpTrapSender snmp = voltdb.getSnmpTrapSender();
if (snmp != null) {
snmp.pause("Cluster paused.");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
VoltTable t = new VoltTable(VoltSystemProcedure.STATUS_SCHEMA);
t.addRow(VoltSystemProcedure.STATUS_OK);
return (new VoltTable[] {t});
}
}
| ENG-11984: Force a stats collection at pause time, so that empty db check
from DR after that pause will give the latest.
Also in general it is not a bad idea to force stats collection at pause time.
| src/frontend/org/voltdb/sysprocs/Pause.java | ENG-11984: Force a stats collection at pause time, so that empty db check from DR after that pause will give the latest. Also in general it is not a bad idea to force stats collection at pause time. |
|
Java | agpl-3.0 | dae682e8167e0aa2859697555f812a64a811753d | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | d51a3822-2e5f-11e5-9284-b827eb9e62be | hello.java | d514be6a-2e5f-11e5-9284-b827eb9e62be | d51a3822-2e5f-11e5-9284-b827eb9e62be | hello.java | d51a3822-2e5f-11e5-9284-b827eb9e62be |
|
Java | lgpl-2.1 | a8ee70f8fa3b61c18c88c0c162c5cfb9adb46a3b | 0 | bstansberry/wildfly-core,yersan/wildfly-core,bstansberry/wildfly-core,aloubyansky/wildfly-core,luck3y/wildfly-core,JiriOndrusek/wildfly-core,darranl/wildfly-core,jamezp/wildfly-core,ivassile/wildfly-core,jfdenise/wildfly-core,luck3y/wildfly-core,ivassile/wildfly-core,jamezp/wildfly-core,soul2zimate/wildfly-core,JiriOndrusek/wildfly-core,darranl/wildfly-core,aloubyansky/wildfly-core,yersan/wildfly-core,bstansberry/wildfly-core,JiriOndrusek/wildfly-core,jamezp/wildfly-core,soul2zimate/wildfly-core,yersan/wildfly-core,jfdenise/wildfly-core,luck3y/wildfly-core,soul2zimate/wildfly-core,darranl/wildfly-core,ivassile/wildfly-core,jfdenise/wildfly-core,aloubyansky/wildfly-core | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.controller.audit;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.security.KeyStore;
import java.util.logging.ErrorManager;
import javax.net.SocketFactory;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.jboss.as.controller.interfaces.InetAddressUtil;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.services.path.PathManagerService;
import org.jboss.logmanager.ExtLogRecord;
import org.jboss.logmanager.Level;
import org.jboss.logmanager.handlers.SyslogHandler;
import org.jboss.logmanager.handlers.SyslogHandler.Protocol;
import org.jboss.logmanager.handlers.SyslogHandler.SyslogType;
import org.jboss.logmanager.handlers.TcpOutputStream;
import org.xnio.IoUtils;
/**
*
* @author <a href="[email protected]">Kabir Khan</a>
*/
public class SyslogAuditLogHandler extends AuditLogHandler {
private final PathManagerService pathManager;
private volatile SyslogHandler handler;
private volatile String appName;
private volatile String hostName;
private volatile SyslogType syslogType = SyslogType.RFC5424;
private volatile boolean truncate;
private volatile int maxLength;
private volatile InetAddress syslogServerAddress;
private volatile int port = 514;
private volatile Transport transport = Transport.UDP;
private volatile MessageTransfer messageTransfer = MessageTransfer.NON_TRANSPARENT_FRAMING;
private volatile Facility facility;
private volatile String tlsTrustStorePath;
private volatile String tlsTrustStoreRelativeTo;
private volatile String tlsTrustStorePassword;
private volatile String tlsClientCertStorePath;
private volatile String tlsClientCertStoreRelativeTo;
private volatile String tlsClientCertStorePassword;
private volatile String tlsClientCertStoreKeyPassword;
private volatile TransportErrorManager errorManager;
private volatile int reconnectTimeout = -1;
private volatile long lastErrorTime = -1;
public SyslogAuditLogHandler(String name, String formatterName, int maxFailureCount, PathManagerService pathManager) {
super(name, formatterName, maxFailureCount);
this.pathManager = pathManager;
}
public void setHostName(String hostName) {
assert hostName != null;
this.hostName = hostName;
}
public void setAppName(String appName) {
assert appName != null;
this.appName = appName;
//This gets updated immediately
if (handler != null) {
handler.setAppName(appName);
}
}
public void setFacility(Facility facility) {
assert facility != null;
this.facility = facility;
//This gets updated immediately
if (handler != null) {
handler.setFacility(facility.convert());
}
}
public void setSyslogType(SyslogType syslogType) {
assert syslogType != null;
this.syslogType = syslogType;
}
public void setTruncate(boolean truncate) {
this.truncate = truncate;
}
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
}
public void setMessageTransfer(MessageTransfer messageTransfer) {
assert messageTransfer != null;
this.messageTransfer = messageTransfer;
}
public void setSyslogServerAddress(InetAddress syslogServerAddress) {
assert syslogServerAddress != null;
this.syslogServerAddress = syslogServerAddress;
}
public void setPort(int port) {
this.port = port;
}
public void setTransport(Transport transport) {
assert transport != null;
this.transport = transport;
}
public void setTlsTrustStorePath(String tlsTrustStorePath) {
this.tlsTrustStorePath = tlsTrustStorePath;
}
public void setTlsTrustStoreRelativeTo(String tlsTrustStoreRelativeTo) {
this.tlsTrustStoreRelativeTo = tlsTrustStoreRelativeTo;
}
public void setTlsTruststorePassword(String tlsTrustStorePassword) {
this.tlsTrustStorePassword = tlsTrustStorePassword;
}
public void setTlsClientCertStorePath(String tlsClientCertStorePath) {
this.tlsClientCertStorePath = tlsClientCertStorePath;
}
public void setTlsClientCertStoreRelativeTo(String tlsClientCertStoreRelativeTo) {
this.tlsClientCertStoreRelativeTo = tlsClientCertStoreRelativeTo;
}
public void setTlsClientCertStorePassword(String tlsClientCertStorePassword) {
this.tlsClientCertStorePassword = tlsClientCertStorePassword;
}
public void setTlsClientCertStoreKeyPassword(String tlsClientCertStoreKeyPassword) {
this.tlsClientCertStoreKeyPassword = tlsClientCertStoreKeyPassword;
}
public void setReconnectTimeout(int reconnectTimeout) {
this.reconnectTimeout = reconnectTimeout;
}
@Override
boolean isActive() {
if (hasTooManyFailures()) {
if (reconnectTimeout >= 0) {
long end = lastErrorTime + reconnectTimeout * 1000;
return System.currentTimeMillis() > end;
}
return false;
}
return true;
}
@Override
void initialize() {
try {
if (handler != null) {
return;
}
final Protocol protocol;
switch (transport) {
case UDP:
protocol = Protocol.UDP;
break;
case TCP:
protocol = Protocol.TCP;
break;
case TLS:
protocol = Protocol.SSL_TCP;
break;
default:
//i18n not needed, user code will not end up here
throw new IllegalStateException("Unknown protocol");
}
handler = new SyslogHandler(syslogServerAddress, port, facility.convert(), syslogType, protocol, hostName == null ? InetAddressUtil.getLocalHostName() : hostName);
handler.setAppName(appName);
handler.setTruncate(truncate);
if (maxLength != 0) {
handler.setMaxLength(maxLength);
}
//Common for all protocols
handler.setSyslogType(syslogType);
errorManager = new TransportErrorManager();
handler.setErrorManager(errorManager);
if (transport != Transport.UDP){
if (messageTransfer == MessageTransfer.NON_TRANSPARENT_FRAMING) {
handler.setUseCountingFraming(false);
handler.setMessageDelimiter("\n");
handler.setUseMessageDelimiter(true);
} else {
handler.setUseCountingFraming(true);
handler.setMessageDelimiter(null);
handler.setUseMessageDelimiter(false);
}
if (transport == Transport.TLS && (tlsClientCertStorePath != null || tlsTrustStorePath != null)){
final SSLContext context = SSLContext.getInstance("TLS");
KeyManager[] keyManagers = null;
if (tlsClientCertStorePath != null){
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
final FileInputStream in = new FileInputStream(pathManager.resolveRelativePathEntry(tlsClientCertStorePath, tlsClientCertStoreRelativeTo));
try {
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(in, tlsClientCertStorePassword.toCharArray());
kmf.init(ks, tlsClientCertStoreKeyPassword != null ? tlsClientCertStoreKeyPassword.toCharArray() : tlsClientCertStorePassword.toCharArray());
keyManagers = kmf.getKeyManagers();
} finally {
IoUtils.safeClose(in);
}
}
TrustManager[] trustManagers = null;
if (tlsTrustStorePath != null){
final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
final FileInputStream in = new FileInputStream(pathManager.resolveRelativePathEntry(tlsTrustStorePath, tlsTrustStoreRelativeTo));
try {
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(in, tlsTrustStorePassword.toCharArray());
tmf.init(ks);
trustManagers = tmf.getTrustManagers();
} finally {
IoUtils.safeClose(in);
}
}
context.init(keyManagers, trustManagers, null);
handler.setOutputStream(new SSLContextOutputStream(context, syslogServerAddress, port));
} else {
handler.setOutputStream(new AuditLogTcpOutputStream(syslogServerAddress, port));
handler.setProtocol(transport == Transport.TCP ? Protocol.TCP : Protocol.SSL_TCP);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
void stop() {
SyslogHandler handler = this.handler;
this.handler = null;
if (handler != null) {
handler.close();
}
}
private boolean isReconnect() {
return hasTooManyFailures() && isActive();
}
FailureCountHandler getFailureCountHandler() {
return isReconnect() ? new ReconnectFailureCountHandler() : super.getFailureCountHandler();
}
@Override
void writeLogItem(String formattedItem) throws IOException {
boolean reconnect = isReconnect();
if (!reconnect) {
handler.publish(new ExtLogRecord(Level.WARN, formattedItem, SyslogAuditLogHandler.class.getName()));
errorManager.getAndThrowError();
} else {
ControllerLogger.MGMT_OP_LOGGER.attemptingReconnectToSyslog(name, reconnectTimeout);
try {
//Reinitialise the delegating syslog handler
stop();
initialize();
handler.publish(new ExtLogRecord(Level.WARN, formattedItem, SyslogAuditLogHandler.class.getName()));
errorManager.getAndThrowError();
lastErrorTime = -1;
} catch (Exception e) {
lastErrorTime = System.currentTimeMillis();
errorManager.throwAsIoOrRuntimeException(e);
}
}
}
@Override
boolean isDifferent(AuditLogHandler other){
if (other instanceof SyslogAuditLogHandler == false){
return true;
}
SyslogAuditLogHandler otherHandler = (SyslogAuditLogHandler)other;
if (!name.equals(otherHandler.name)){
return true;
}
if (!getFormatterName().equals(otherHandler.getFormatterName())) {
return true;
}
if (!hostName.equals(otherHandler.hostName)){
return true;
}
if (!syslogType.equals(otherHandler.syslogType)){
return true;
}
if (!truncate == otherHandler.truncate) {
return true;
}
if (maxLength != otherHandler.maxLength) {
return true;
}
if (!syslogServerAddress.equals(otherHandler.syslogServerAddress)){
return true;
}
if (port != otherHandler.port){
return true;
}
if (!transport.equals(otherHandler.transport)){
return true;
}
//These may or not be null depending on the transport
if (!compare(messageTransfer, otherHandler.messageTransfer)){
return true;
}
if (!compare(tlsTrustStorePath, otherHandler.tlsTrustStorePath)){
return true;
}
if (!compare(tlsTrustStoreRelativeTo, otherHandler.tlsTrustStoreRelativeTo)){
return true;
}
if (!compare(tlsTrustStorePassword, otherHandler.tlsTrustStorePassword)){
return true;
}
if (!compare(tlsClientCertStorePath, otherHandler.tlsClientCertStorePath)){
return true;
}
if (!compare(tlsClientCertStoreRelativeTo, otherHandler.tlsClientCertStoreRelativeTo)){
return true;
}
if (!compare(tlsClientCertStorePassword, otherHandler.tlsClientCertStorePassword)){
return true;
}
if (!compare(tlsClientCertStoreKeyPassword, otherHandler.tlsClientCertStoreKeyPassword)){
return true;
}
return false;
}
private boolean compare(Object one, Object two){
if (one == null && two == null){
return true;
}
if (one == null && two != null){
return false;
}
if (one != null && two == null){
return false;
}
return one.equals(two);
}
public enum Transport {
UDP,
TCP,
TLS
}
public enum MessageTransfer {
OCTET_COUNTING,
NON_TRANSPARENT_FRAMING;
}
/**
* Facility as defined by RFC-5424 (<a href="http://tools.ietf.org/html/rfc5424">http://tools.ietf.org/html/rfc5424</a>)
* and RFC-3164 (<a href="http://tools.ietf.org/html/rfc3164">http://tools.ietf.org/html/rfc3164</a>).
*/
public static enum Facility {
KERNEL(SyslogHandler.Facility.KERNEL),
USER_LEVEL(SyslogHandler.Facility.USER_LEVEL),
MAIL_SYSTEM(SyslogHandler.Facility.MAIL_SYSTEM),
SYSTEM_DAEMONS(SyslogHandler.Facility.SYSTEM_DAEMONS),
SECURITY(SyslogHandler.Facility.SECURITY),
SYSLOGD(SyslogHandler.Facility.SYSLOGD),
LINE_PRINTER(SyslogHandler.Facility.LINE_PRINTER),
NETWORK_NEWS(SyslogHandler.Facility.NETWORK_NEWS),
UUCP(SyslogHandler.Facility.UUCP),
CLOCK_DAEMON(SyslogHandler.Facility.CLOCK_DAEMON),
SECURITY2(SyslogHandler.Facility.SECURITY2),
FTP_DAEMON(SyslogHandler.Facility.FTP_DAEMON),
NTP(SyslogHandler.Facility.NTP),
LOG_AUDIT(SyslogHandler.Facility.LOG_AUDIT),
LOG_ALERT(SyslogHandler.Facility.LOG_ALERT),
CLOCK_DAEMON2(SyslogHandler.Facility.CLOCK_DAEMON2),
LOCAL_USE_0(SyslogHandler.Facility.LOCAL_USE_0),
LOCAL_USE_1(SyslogHandler.Facility.LOCAL_USE_1),
LOCAL_USE_2(SyslogHandler.Facility.LOCAL_USE_2),
LOCAL_USE_3(SyslogHandler.Facility.LOCAL_USE_3),
LOCAL_USE_4(SyslogHandler.Facility.LOCAL_USE_4),
LOCAL_USE_5(SyslogHandler.Facility.LOCAL_USE_5),
LOCAL_USE_6(SyslogHandler.Facility.LOCAL_USE_6),
LOCAL_USE_7(SyslogHandler.Facility.LOCAL_USE_7);
private final SyslogHandler.Facility realFacility;
private Facility(SyslogHandler.Facility realFacility) {
this.realFacility = realFacility;
}
public SyslogHandler.Facility convert(){
return realFacility;
}
}
// By default the TcpOutputStream attempts to reconnect on it's own, use our own to avoid the automatic reconnect
// See LOGMGR-113 for details on a better way to do this in the future
private static class AuditLogTcpOutputStream extends TcpOutputStream {
protected AuditLogTcpOutputStream(InetAddress host, int port) throws IOException {
super(SocketFactory.getDefault().createSocket(host, port));
}
}
private static class SSLContextOutputStream extends TcpOutputStream {
protected SSLContextOutputStream(SSLContext sslContext, InetAddress host, int port) throws IOException {
// Continue to use the deprecated constructor until LOGMGR-113 is resolved
super(sslContext.getSocketFactory().createSocket(host, port));
}
}
private class TransportErrorManager extends ErrorManager {
private volatile Exception error;
public TransportErrorManager() {
}
@Override
public synchronized void error(String msg, Exception ex, int code) {
error = ex;
lastErrorTime = System.currentTimeMillis();
}
void getAndThrowError() throws IOException {
Exception error = this.error;
this.error = null;
if (error != null) {
throwAsIoOrRuntimeException(error);
}
}
void throwAsIoOrRuntimeException(Throwable t) throws IOException {
if (t instanceof IOException) {
throw (IOException)error;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)error;
}
throw new RuntimeException(error);
}
}
}
| controller/src/main/java/org/jboss/as/controller/audit/SyslogAuditLogHandler.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2012, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.controller.audit;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.security.KeyStore;
import java.util.logging.ErrorManager;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.jboss.as.controller.interfaces.InetAddressUtil;
import org.jboss.as.controller.logging.ControllerLogger;
import org.jboss.as.controller.services.path.PathManagerService;
import org.jboss.logmanager.ExtLogRecord;
import org.jboss.logmanager.Level;
import org.jboss.logmanager.handlers.SyslogHandler;
import org.jboss.logmanager.handlers.SyslogHandler.Protocol;
import org.jboss.logmanager.handlers.SyslogHandler.SyslogType;
import org.jboss.logmanager.handlers.TcpOutputStream;
import org.xnio.IoUtils;
/**
*
* @author <a href="[email protected]">Kabir Khan</a>
*/
public class SyslogAuditLogHandler extends AuditLogHandler {
private final PathManagerService pathManager;
private volatile SyslogHandler handler;
private volatile String appName;
private volatile String hostName;
private volatile SyslogType syslogType = SyslogType.RFC5424;
private volatile boolean truncate;
private volatile int maxLength;
private volatile InetAddress syslogServerAddress;
private volatile int port = 514;
private volatile Transport transport = Transport.UDP;
private volatile MessageTransfer messageTransfer = MessageTransfer.NON_TRANSPARENT_FRAMING;
private volatile Facility facility;
private volatile String tlsTrustStorePath;
private volatile String tlsTrustStoreRelativeTo;
private volatile String tlsTrustStorePassword;
private volatile String tlsClientCertStorePath;
private volatile String tlsClientCertStoreRelativeTo;
private volatile String tlsClientCertStorePassword;
private volatile String tlsClientCertStoreKeyPassword;
private volatile TransportErrorManager errorManager;
private volatile int reconnectTimeout = -1;
private volatile long lastErrorTime = -1;
public SyslogAuditLogHandler(String name, String formatterName, int maxFailureCount, PathManagerService pathManager) {
super(name, formatterName, maxFailureCount);
this.pathManager = pathManager;
}
public void setHostName(String hostName) {
assert hostName != null;
this.hostName = hostName;
}
public void setAppName(String appName) {
assert appName != null;
this.appName = appName;
//This gets updated immediately
if (handler != null) {
handler.setAppName(appName);
}
}
public void setFacility(Facility facility) {
assert facility != null;
this.facility = facility;
//This gets updated immediately
if (handler != null) {
handler.setFacility(facility.convert());
}
}
public void setSyslogType(SyslogType syslogType) {
assert syslogType != null;
this.syslogType = syslogType;
}
public void setTruncate(boolean truncate) {
this.truncate = truncate;
}
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
}
public void setMessageTransfer(MessageTransfer messageTransfer) {
assert messageTransfer != null;
this.messageTransfer = messageTransfer;
}
public void setSyslogServerAddress(InetAddress syslogServerAddress) {
assert syslogServerAddress != null;
this.syslogServerAddress = syslogServerAddress;
}
public void setPort(int port) {
this.port = port;
}
public void setTransport(Transport transport) {
assert transport != null;
this.transport = transport;
}
public void setTlsTrustStorePath(String tlsTrustStorePath) {
this.tlsTrustStorePath = tlsTrustStorePath;
}
public void setTlsTrustStoreRelativeTo(String tlsTrustStoreRelativeTo) {
this.tlsTrustStoreRelativeTo = tlsTrustStoreRelativeTo;
}
public void setTlsTruststorePassword(String tlsTrustStorePassword) {
this.tlsTrustStorePassword = tlsTrustStorePassword;
}
public void setTlsClientCertStorePath(String tlsClientCertStorePath) {
this.tlsClientCertStorePath = tlsClientCertStorePath;
}
public void setTlsClientCertStoreRelativeTo(String tlsClientCertStoreRelativeTo) {
this.tlsClientCertStoreRelativeTo = tlsClientCertStoreRelativeTo;
}
public void setTlsClientCertStorePassword(String tlsClientCertStorePassword) {
this.tlsClientCertStorePassword = tlsClientCertStorePassword;
}
public void setTlsClientCertStoreKeyPassword(String tlsClientCertStoreKeyPassword) {
this.tlsClientCertStoreKeyPassword = tlsClientCertStoreKeyPassword;
}
public void setReconnectTimeout(int reconnectTimeout) {
this.reconnectTimeout = reconnectTimeout;
}
@Override
boolean isActive() {
if (hasTooManyFailures()) {
if (reconnectTimeout >= 0) {
long end = lastErrorTime + reconnectTimeout * 1000;
return System.currentTimeMillis() > end;
}
return false;
}
return true;
}
@Override
void initialize() {
try {
if (handler != null) {
return;
}
final Protocol protocol;
switch (transport) {
case UDP:
protocol = Protocol.UDP;
break;
case TCP:
protocol = Protocol.TCP;
break;
case TLS:
protocol = Protocol.SSL_TCP;
break;
default:
//i18n not needed, user code will not end up here
throw new IllegalStateException("Unknown protocol");
}
handler = new SyslogHandler(syslogServerAddress, port, facility.convert(), syslogType, protocol, hostName == null ? InetAddressUtil.getLocalHostName() : hostName);
handler.setEscapeEnabled(false); //Escaping is handled by the formatter
handler.setAppName(appName);
handler.setTruncate(truncate);
if (maxLength != 0) {
handler.setMaxLength(maxLength);
}
//Common for all protocols
handler.setSyslogType(syslogType);
errorManager = new TransportErrorManager();
handler.setErrorManager(errorManager);
if (transport != Transport.UDP){
if (messageTransfer == MessageTransfer.NON_TRANSPARENT_FRAMING) {
handler.setUseCountingFraming(false);
handler.setMessageDelimiter("\n");
handler.setUseMessageDelimiter(true);
} else {
handler.setUseCountingFraming(true);
handler.setMessageDelimiter(null);
handler.setUseMessageDelimiter(false);
}
if (transport == Transport.TLS && (tlsClientCertStorePath != null || tlsTrustStorePath != null)){
final SSLContext context = SSLContext.getInstance("TLS");
KeyManager[] keyManagers = null;
if (tlsClientCertStorePath != null){
final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
final FileInputStream in = new FileInputStream(pathManager.resolveRelativePathEntry(tlsClientCertStorePath, tlsClientCertStoreRelativeTo));
try {
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(in, tlsClientCertStorePassword.toCharArray());
kmf.init(ks, tlsClientCertStoreKeyPassword != null ? tlsClientCertStoreKeyPassword.toCharArray() : tlsClientCertStorePassword.toCharArray());
keyManagers = kmf.getKeyManagers();
} finally {
IoUtils.safeClose(in);
}
}
TrustManager[] trustManagers = null;
if (tlsTrustStorePath != null){
final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
final FileInputStream in = new FileInputStream(pathManager.resolveRelativePathEntry(tlsTrustStorePath, tlsTrustStoreRelativeTo));
try {
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(in, tlsTrustStorePassword.toCharArray());
tmf.init(ks);
trustManagers = tmf.getTrustManagers();
} finally {
IoUtils.safeClose(in);
}
}
context.init(keyManagers, trustManagers, null);
handler.setOutputStream(new SSLContextOutputStream(context, syslogServerAddress, port));
} else {
handler.setProtocol(transport == Transport.TCP ? Protocol.TCP : Protocol.SSL_TCP);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
void stop() {
SyslogHandler handler = this.handler;
this.handler = null;
if (handler != null) {
handler.close();
}
}
private boolean isReconnect() {
return hasTooManyFailures() && isActive();
}
FailureCountHandler getFailureCountHandler() {
return isReconnect() ? new ReconnectFailureCountHandler() : super.getFailureCountHandler();
}
@Override
void writeLogItem(String formattedItem) throws IOException {
boolean reconnect = isReconnect();
if (!reconnect) {
handler.publish(new ExtLogRecord(Level.WARN, formattedItem, SyslogAuditLogHandler.class.getName()));
errorManager.getAndThrowError();
} else {
ControllerLogger.MGMT_OP_LOGGER.attemptingReconnectToSyslog(name, reconnectTimeout);
try {
//Reinitialise the delegating syslog handler
stop();
initialize();
handler.publish(new ExtLogRecord(Level.WARN, formattedItem, SyslogAuditLogHandler.class.getName()));
errorManager.getAndThrowError();
lastErrorTime = -1;
} catch (Exception e) {
lastErrorTime = System.currentTimeMillis();
errorManager.throwAsIoOrRuntimeException(e);
}
}
}
@Override
boolean isDifferent(AuditLogHandler other){
if (other instanceof SyslogAuditLogHandler == false){
return true;
}
SyslogAuditLogHandler otherHandler = (SyslogAuditLogHandler)other;
if (!name.equals(otherHandler.name)){
return true;
}
if (!getFormatterName().equals(otherHandler.getFormatterName())) {
return true;
}
if (!hostName.equals(otherHandler.hostName)){
return true;
}
if (!syslogType.equals(otherHandler.syslogType)){
return true;
}
if (!truncate == otherHandler.truncate) {
return true;
}
if (maxLength != otherHandler.maxLength) {
return true;
}
if (!syslogServerAddress.equals(otherHandler.syslogServerAddress)){
return true;
}
if (port != otherHandler.port){
return true;
}
if (!transport.equals(otherHandler.transport)){
return true;
}
//These may or not be null depending on the transport
if (!compare(messageTransfer, otherHandler.messageTransfer)){
return true;
}
if (!compare(tlsTrustStorePath, otherHandler.tlsTrustStorePath)){
return true;
}
if (!compare(tlsTrustStoreRelativeTo, otherHandler.tlsTrustStoreRelativeTo)){
return true;
}
if (!compare(tlsTrustStorePassword, otherHandler.tlsTrustStorePassword)){
return true;
}
if (!compare(tlsClientCertStorePath, otherHandler.tlsClientCertStorePath)){
return true;
}
if (!compare(tlsClientCertStoreRelativeTo, otherHandler.tlsClientCertStoreRelativeTo)){
return true;
}
if (!compare(tlsClientCertStorePassword, otherHandler.tlsClientCertStorePassword)){
return true;
}
if (!compare(tlsClientCertStoreKeyPassword, otherHandler.tlsClientCertStoreKeyPassword)){
return true;
}
return false;
}
private boolean compare(Object one, Object two){
if (one == null && two == null){
return true;
}
if (one == null && two != null){
return false;
}
if (one != null && two == null){
return false;
}
return one.equals(two);
}
public enum Transport {
UDP,
TCP,
TLS
}
public enum MessageTransfer {
OCTET_COUNTING,
NON_TRANSPARENT_FRAMING;
}
/**
* Facility as defined by RFC-5424 (<a href="http://tools.ietf.org/html/rfc5424">http://tools.ietf.org/html/rfc5424</a>)
* and RFC-3164 (<a href="http://tools.ietf.org/html/rfc3164">http://tools.ietf.org/html/rfc3164</a>).
*/
public static enum Facility {
KERNEL(SyslogHandler.Facility.KERNEL),
USER_LEVEL(SyslogHandler.Facility.USER_LEVEL),
MAIL_SYSTEM(SyslogHandler.Facility.MAIL_SYSTEM),
SYSTEM_DAEMONS(SyslogHandler.Facility.SYSTEM_DAEMONS),
SECURITY(SyslogHandler.Facility.SECURITY),
SYSLOGD(SyslogHandler.Facility.SYSLOGD),
LINE_PRINTER(SyslogHandler.Facility.LINE_PRINTER),
NETWORK_NEWS(SyslogHandler.Facility.NETWORK_NEWS),
UUCP(SyslogHandler.Facility.UUCP),
CLOCK_DAEMON(SyslogHandler.Facility.CLOCK_DAEMON),
SECURITY2(SyslogHandler.Facility.SECURITY2),
FTP_DAEMON(SyslogHandler.Facility.FTP_DAEMON),
NTP(SyslogHandler.Facility.NTP),
LOG_AUDIT(SyslogHandler.Facility.LOG_AUDIT),
LOG_ALERT(SyslogHandler.Facility.LOG_ALERT),
CLOCK_DAEMON2(SyslogHandler.Facility.CLOCK_DAEMON2),
LOCAL_USE_0(SyslogHandler.Facility.LOCAL_USE_0),
LOCAL_USE_1(SyslogHandler.Facility.LOCAL_USE_1),
LOCAL_USE_2(SyslogHandler.Facility.LOCAL_USE_2),
LOCAL_USE_3(SyslogHandler.Facility.LOCAL_USE_3),
LOCAL_USE_4(SyslogHandler.Facility.LOCAL_USE_4),
LOCAL_USE_5(SyslogHandler.Facility.LOCAL_USE_5),
LOCAL_USE_6(SyslogHandler.Facility.LOCAL_USE_6),
LOCAL_USE_7(SyslogHandler.Facility.LOCAL_USE_7);
private final SyslogHandler.Facility realFacility;
private Facility(SyslogHandler.Facility realFacility) {
this.realFacility = realFacility;
}
public SyslogHandler.Facility convert(){
return realFacility;
}
}
private static class SSLContextOutputStream extends TcpOutputStream {
protected SSLContextOutputStream(SSLContext sslContext, InetAddress host, int port) throws IOException {
super(sslContext.getSocketFactory().createSocket(host, port));
}
}
private class TransportErrorManager extends ErrorManager {
private volatile Exception error;
public TransportErrorManager() {
}
@Override
public synchronized void error(String msg, Exception ex, int code) {
error = ex;
lastErrorTime = System.currentTimeMillis();
}
void getAndThrowError() throws IOException {
Exception error = this.error;
this.error = null;
if (error != null) {
throwAsIoOrRuntimeException(error);
}
}
void throwAsIoOrRuntimeException(Throwable t) throws IOException {
if (t instanceof IOException) {
throw (IOException)error;
}
if (t instanceof RuntimeException) {
throw (RuntimeException)error;
}
throw new RuntimeException(error);
}
}
}
| Change the SyslogAuditLogHandler to use it's own TcpOutputStream for the SyslogHandler. Required with the reconnection changes in the latest jboss-logmanager.
| controller/src/main/java/org/jboss/as/controller/audit/SyslogAuditLogHandler.java | Change the SyslogAuditLogHandler to use it's own TcpOutputStream for the SyslogHandler. Required with the reconnection changes in the latest jboss-logmanager. |
|
Java | lgpl-2.1 | d8a8044df16d5d773b0c52b6d96984cbe87f426c | 0 | netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration | /* File: $Id$
* Revision: $Revision$
* Date: $Date$
* Author: $Author$
*
* The Netarchive Suite - Software to harvest and preserve websites
* Copyright 2004-2009 Det Kongelige Bibliotek and Statsbiblioteket, Denmark
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package dk.netarkivet.archive.bitarchive;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import dk.netarkivet.archive.ArchiveSettings;
import dk.netarkivet.archive.Constants;
import dk.netarkivet.common.exceptions.ArgumentNotValid;
import dk.netarkivet.common.exceptions.IOFailure;
import dk.netarkivet.common.exceptions.PermissionDenied;
import dk.netarkivet.common.utils.ApplicationUtils;
import dk.netarkivet.common.utils.FileUtils;
import dk.netarkivet.common.utils.Settings;
/**
* This class handles file lookup and encapsulates the actual placement of
* files.
*/
public class BitarchiveAdmin {
/** The class logger. */
private final Log log = LogFactory.getLog(getClass().getName());
/**
* The list of valid archive directories.
*/
private List<File> archivePaths = new ArrayList<File>();
/**
* Singleton instance.
*/
private static BitarchiveAdmin instance;
/**
* How much space we must have available *in a single dir*
* before we will listen for new uploads.
*/
private final long minSpaceLeft;
/**
* How much space we require available *in every dir*
* after we have accepted an upload.
*/
private final long minSpaceRequired;
/**
* Creates a new BitarchiveAdmin object for an existing bit archive.
* Reads the directories to use from settings.
*
* @throws ArgumentNotValid If the settings for minSpaceLeft is non-positive
* or the setting for minSpaceRequired is negative.
* @throws PermissionDenied If any of the directories cannot be created or
* are not writeable.
*/
private BitarchiveAdmin() {
String[] filedirnames =
Settings.getAll(ArchiveSettings.BITARCHIVE_SERVER_FILEDIR);
minSpaceLeft = Settings.getLong(
ArchiveSettings.BITARCHIVE_MIN_SPACE_LEFT);
// Check, if value of minSpaceLeft is greater than zero
if (minSpaceLeft <= 0L) {
log.warn(
"Wrong setting of minSpaceLeft read from Settings: "
+ minSpaceLeft);
throw new ArgumentNotValid(
"Wrong setting of minSpaceLeft read from Settings: "
+ minSpaceLeft);
}
minSpaceRequired = Settings.getLong(
ArchiveSettings.BITARCHIVE_MIN_SPACE_REQUIRED);
// Check, if value of minSpaceRequired is at least zero
if (minSpaceLeft < 0L) {
log.warn(
"Wrong setting of minSpaceRequired read from Settings: "
+ minSpaceLeft);
throw new ArgumentNotValid(
"Wrong setting of minSpaceRequired read from Settings: "
+ minSpaceLeft);
}
log.info("Requiring at least " + minSpaceRequired + " bytes free.");
log.info("Listening if at least " + minSpaceLeft + " bytes free.");
for (String filedirname : filedirnames) {
File basedir = new File(filedirname);
File filedir = new File(basedir, Constants.FILE_DIRECTORY_NAME);
// Ensure that 'filedir' exists. If it doesn't, it is created
ApplicationUtils.dirMustExist(filedir);
File tempdir = new File(basedir,
Constants.TEMPORARY_DIRECTORY_NAME);
// Ensure that 'tempdir' exists. If it doesn't, it is created
ApplicationUtils.dirMustExist(tempdir);
File atticdir = new File(basedir, Constants.ATTIC_DIRECTORY_NAME);
// Ensure that 'atticdir' exists. If it doesn't, it is created
ApplicationUtils.dirMustExist(atticdir);
archivePaths.add(basedir);
final Long bytesUsedInDir = calculateBytesUsed(basedir);
log.info("Using bit archive directorys {'"
+ Constants.FILE_DIRECTORY_NAME + "', '"
+ Constants.TEMPORARY_DIRECTORY_NAME + "', '"
+ Constants.ATTIC_DIRECTORY_NAME
+ "'} under base directory: '" + basedir+ "' with "
+ bytesUsedInDir + " bytes of content and "
+ FileUtils.getBytesFree(basedir) + " bytes free");
}
}
/**
* Returns true if we have at least one dir with the required amount
* of space left.
*
* @return true if we have at least one dir with the required amount
* of space left, otherwise false.
*/
public boolean hasEnoughSpace() {
for (File dir : archivePaths) {
if (checkArchiveDir(dir)
&& FileUtils.getBytesFree(dir) > minSpaceLeft) {
return true;
}
}
return false;
}
/**
* Returns a temporary place for the the file to be stored.
*
* @param arcFileName The simple name (i.e. no dirs) of the ARC file.
* @param requestedSize How large the file is in bytes.
* @return The path where the arcFile should go.
*
* @throws ArgumentNotValid
* If arcFileName is null or empty, or requestedSize is negative.
* @throws IOFailure if there is no more room left to store this file of
* size=requestedSize
*/
public File getTemporaryPath(String arcFileName, long requestedSize)
throws ArgumentNotValid, IOFailure {
ArgumentNotValid.checkNotNullOrEmpty(arcFileName, "arcFile");
ArgumentNotValid.checkNotNegative(requestedSize, "requestedSize");
for (File dir : archivePaths) {
long bytesFreeInDir = FileUtils.getBytesFree(dir);
// TODO If it turns out that it has not enough space for
// this file, it should resend the Upload message
// This should probably be handled in the
// method BitarchiveServer.visit(UploadMessage msg)
// This is bug 1586.
if (checkArchiveDir(dir)
&& (bytesFreeInDir > minSpaceLeft)
&& (bytesFreeInDir - requestedSize > minSpaceRequired)) {
File filedir = new File(
dir, Constants.TEMPORARY_DIRECTORY_NAME);
return new File(filedir, arcFileName);
} else {
log.debug("Not enough space on dir '"
+ dir.getAbsolutePath() + "' for file '"
+ arcFileName + "' of size " + requestedSize
+ " bytes. Only " + bytesFreeInDir + " left");
}
}
String errMsg = "No space left in dirs: " + archivePaths
+ ", to store file '" + arcFileName
+ "' of size " + requestedSize;
log.warn(errMsg);
throw new IOFailure(errMsg);
}
/**
* Moves a file from temporary storage to file storage.
*
* Note: It is checked, if tempLocation resides in directory
* TEMPORARY_DIRECTORY_NAME and whether the parent of tempLocation
* is a Bitarchive directory.
*
* @param tempLocation The temporary location where the file was stored.
* This must be a path returned from getTemporaryPath
*
* @return The location where the file is now stored
* @throws IOFailure if tempLocation is not created from getTemporaryPath
* or file cannot be moved to Storage location.
*/
public File moveToStorage(File tempLocation) {
ArgumentNotValid.checkNotNull(tempLocation, "tempLocation");
tempLocation = tempLocation.getAbsoluteFile();
String arcFileName = tempLocation.getName();
/**
* Check, that File tempLocation resides in directory
* TEMPORARY_DIRECTORY_NAME.
*/
File arcFilePath = tempLocation.getParentFile();
if (arcFilePath == null
|| !arcFilePath.getName().equals(
Constants.TEMPORARY_DIRECTORY_NAME)) {
throw new IOFailure("Location '" + tempLocation + "' is not in "
+ "tempdir '"
+ Constants.TEMPORARY_DIRECTORY_NAME + "'");
}
/**
* Check, that arcFilePath (now known to be TEMPORARY_DIRECTORY_NAME)
* resides in a recognised Bitarchive Directory.
*/
File archivedir = arcFilePath.getParentFile();
if (archivedir == null || !isBitarchiveDirectory(archivedir)) {
throw new IOFailure("Location '" + tempLocation + "' is not in "
+ "recognised archive directory.");
}
/**
* Move File tempLocation to new location: storageFile
*/
File storagePath = new File(archivedir,
Constants.FILE_DIRECTORY_NAME);
File storageFile = new File(storagePath, arcFileName);
if (!tempLocation.renameTo(storageFile)) {
throw new IOFailure("Could not move '" + tempLocation.getPath()
+ "' to '" + storageFile.getPath() + "'");
}
return storageFile;
}
/**
* Checks whether a directory is one of the known bitarchive directories.
*
* @param theDir The dir to check
* @return true If it is a valid archive directory; otherwise returns false.
* @throws IOFailure if theDir or one of the valid archive directories
* does not exist
* @throws ArgumentNotValid if theDir is null
*/
protected boolean isBitarchiveDirectory(File theDir) {
ArgumentNotValid.checkNotNull(theDir, "File theDir");
try {
theDir = theDir.getCanonicalFile();
for (File knowndir : archivePaths) {
if (knowndir.getCanonicalFile().equals(theDir)) {
return true;
}
}
return false;
} catch (IOException e) {
final String errMsg = "File not known";
log.warn(errMsg, e);
throw new IOFailure(errMsg, e);
}
}
/**
* Check that the given file is a directory appropriate for use.
* A File is appropiate to use as archivedir, if the file is an
* existing directory, and is writable by this java process.
*
* @param file A file
* @return true, if 'file' is an existing directory and is writable.
* @throws ArgumentNotValid if 'file' is null.
*/
private boolean checkArchiveDir(File file) {
ArgumentNotValid.checkNotNull(file, "file");
if (!file.exists()) {
log.warn("Directory '" + file + "' does not exist");
return false;
}
if (!file.isDirectory()) {
log.warn("Directory '" + file
+ "' is not a directory after all");
return false;
}
if (!file.canWrite()) {
log.warn("Directory '" + file + "' is not writable");
return false;
}
return true;
}
/**
* Return array with references to all files in the archive.
*
* @return array with references to all files in the archive
*/
public File[] getFiles() {
List<File> files = new ArrayList<File>();
for (File archivePath : archivePaths) {
File archiveDir = new File(archivePath,
Constants.FILE_DIRECTORY_NAME);
if (checkArchiveDir(archiveDir)) {
File[] filesHere = archiveDir.listFiles();
for (File file : filesHere) {
if (!file.isFile()) {
log.warn("Non-file '" + file.getAbsolutePath()
+ "' found among archive files");
} else {
files.add(file);
}
}
}
}
return files.toArray(new File[files.size()]);
}
/** Return an array of all files in this archive that match a given
* regular expression on the filename.
*
* @param regexp A precompiled regular expression matching whole filenames.
* This will probably be given to a FilenameFilter
* @return An array of all the files in this bitarchive that exactly match
* the regular expression on the filename (sans paths).
*/
public File[] getFilesMatching(final Pattern regexp) {
ArgumentNotValid.checkNotNull(regexp, "Pattern regexp");
List<File> files = new ArrayList<File>();
for (File archivePath : archivePaths) {
File archiveDir = new File(archivePath,
Constants.FILE_DIRECTORY_NAME);
if (checkArchiveDir(archiveDir)) {
File[] filesHere = archiveDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
if (regexp.matcher(name).matches()) {
if (!new File(dir, name).isFile()) {
log.warn("Non regular file '"
+ new File(dir, name).getAbsolutePath()
+ "' found among archive files");
return false;
} else {
return true;
}
} else {
return false;
}
}
});
files.addAll(Arrays.asList(filesHere));
}
}
return files.toArray(new File[files.size()]);
}
/**
* Return the path that a given arc file can be found in.
*
* @param arcFileName Name of an arc file (with no path)
* @return A BitarchiveARCFile for the given file, or null if the
* file does not exist.
*/
public BitarchiveARCFile lookup(String arcFileName) {
ArgumentNotValid.checkNotNullOrEmpty(arcFileName, "arcFileName");
for (File archivePath : archivePaths) {
File archiveDir = new File(archivePath,
Constants.FILE_DIRECTORY_NAME);
if (checkArchiveDir(archiveDir)) {
File filename = new File(archiveDir, arcFileName);
if (filename.exists()) {
if (filename.isFile()) {
return new BitarchiveARCFile(arcFileName, filename);
}
log.fatal("Possibly corrupt bitarchive: Non-file '"
+ filename + "' found in"
+ " place of archive file");
}
}
}
// the arcfile named "arcFileName" does not exist in this bitarchive.
log.trace("The arcfile named '" + arcFileName
+ "' does not exist in this bitarchve");
return null;
}
/**
* Calculate how many bytes are used by all files in a directory.
*
* @param filedir An existing directory with a FILE_DIRECTORY_NAME subdir
* and a TEMPORARY_DIRECTORY_NAME subdir.
* @return Number of bytes used by all files in the directory (not including
* overhead from partially used blocks).
*/
private long calculateBytesUsed(File filedir) {
long used = 0;
File[] files = new File(filedir, Constants.FILE_DIRECTORY_NAME)
.listFiles();
// Check, that listFiles method returns valid information
if (files != null) {
for (File datafiles : files) {
if (datafiles.isFile()) {
// Add size of file f to amount of bytes used.
used += datafiles.length();
} else {
log.warn("Non-file '" + datafiles.getAbsolutePath()
+ "' found in archive");
}
}
} else {
log.warn("filedir does not contain a directory named: "
+ Constants.FILE_DIRECTORY_NAME);
}
File[] tempfiles = new File(filedir,
Constants.TEMPORARY_DIRECTORY_NAME).listFiles();
// Check, that listFiles() method returns valid information
if (tempfiles != null) {
for (File tempfile : tempfiles) {
if (tempfile.isFile()) {
// Add size of file f to amount of bytes used.
used += tempfile.length();
} else {
log.warn(
"Non-file '" + tempfile.getAbsolutePath()
+ "' found in archive");
}
}
} else {
log.warn("filedir does not contain a directory named: "
+ Constants.TEMPORARY_DIRECTORY_NAME);
}
File[] atticfiles = new File(filedir, Constants.ATTIC_DIRECTORY_NAME)
.listFiles();
// Check, that listFiles() method returns valid information
if (atticfiles != null) {
for (File atticfile : atticfiles) {
if (atticfile.isFile()) {
// Add size of file tempfiles[i] to amount of bytes used.
used += atticfile.length();
} else {
log.warn("Non-file '" + atticfile.getAbsolutePath()
+ "' found in archive");
}
}
} else {
log.warn("filedir does not contain a directory named: "
+ Constants.ATTIC_DIRECTORY_NAME);
}
return used;
}
/**
* Get the one and only instance of the bitarchive admin.
*
* @return A BitarchiveAdmin object
*/
public static BitarchiveAdmin getInstance() {
if (instance == null) {
instance = new BitarchiveAdmin();
}
return instance;
}
/**
* Close down the bitarchive admin.
* Currently has no data to store.
*/
public void close() {
instance = null;
}
/** Return the path used to store files that are removed by
* RemoveAndGetFileMessage.
*
* @param existingFile a File object for an existing file in the bitarchive
*
* @return The full path of the file in the attic dir
*/
public File getAtticPath(File existingFile) {
ArgumentNotValid.checkNotNull(existingFile, "File existingFile");
// Find where the file resides so we can use a dir in the same place.
existingFile = existingFile.getAbsoluteFile();
String arcFileName = existingFile.getName();
File parentDir = existingFile.getParentFile().getParentFile();
if (!isBitarchiveDirectory(parentDir)) {
log.warn("Attempt to get attic path for non-archived file '"
+ existingFile + "'");
throw new ArgumentNotValid("File should belong to a bitarchive dir,"
+ " but " + existingFile + " doesn't");
}
// Ensure that 'atticdir' exists. If it doesn't, it is created
File atticdir = new File(parentDir, Constants.ATTIC_DIRECTORY_NAME);
ApplicationUtils.dirMustExist(atticdir);
return new File(atticdir, arcFileName);
}
}
| src/dk/netarkivet/archive/bitarchive/BitarchiveAdmin.java | /* File: $Id$
* Revision: $Revision$
* Date: $Date$
* Author: $Author$
*
* The Netarchive Suite - Software to harvest and preserve websites
* Copyright 2004-2009 Det Kongelige Bibliotek and Statsbiblioteket, Denmark
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package dk.netarkivet.archive.bitarchive;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import dk.netarkivet.archive.ArchiveSettings;
import dk.netarkivet.archive.Constants;
import dk.netarkivet.common.exceptions.ArgumentNotValid;
import dk.netarkivet.common.exceptions.IOFailure;
import dk.netarkivet.common.exceptions.PermissionDenied;
import dk.netarkivet.common.utils.ApplicationUtils;
import dk.netarkivet.common.utils.FileUtils;
import dk.netarkivet.common.utils.Settings;
/**
* This class handles file lookup and encapsulates the actual placement of
* files.
*/
public class BitarchiveAdmin {
/** The class logger. */
private final Log log = LogFactory.getLog(getClass().getName());
/**
* The list of valid archive directories.
*/
private List<File> archivePaths = new ArrayList<File>();
/**
* Singleton instance.
*/
private static BitarchiveAdmin instance;
/**
* How much space we must have available *in a single dir*
* before we will listen for new uploads.
*/
private final long minSpaceLeft;
/**
* How much space we require available *in every dir*
* after we have accepted an upload.
*/
private final long minSpaceRequired;
/**
* Creates a new BitarchiveAdmin object for an existing bit archive.
* Reads the directories to use from settings.
*
* @throws ArgumentNotValid If the settings for minSpaceLeft is non-positive
* or the setting for minSpaceRequired is negative.
* @throws PermissionDenied If any of the directories cannot be created or
* are not writeable.
*/
private BitarchiveAdmin() {
String[] filedirnames =
Settings.getAll(ArchiveSettings.BITARCHIVE_SERVER_FILEDIR);
minSpaceLeft = Settings.getLong(
ArchiveSettings.BITARCHIVE_MIN_SPACE_LEFT);
// Check, if value of minSpaceLeft is greater than zero
if (minSpaceLeft <= 0L) {
log.warn(
"Wrong setting of minSpaceLeft read from Settings: "
+ minSpaceLeft);
throw new ArgumentNotValid(
"Wrong setting of minSpaceLeft read from Settings: "
+ minSpaceLeft);
}
minSpaceRequired = Settings.getLong(
ArchiveSettings.BITARCHIVE_MIN_SPACE_REQUIRED);
// Check, if value of minSpaceRequired is at least zero
if (minSpaceLeft < 0L) {
log.warn(
"Wrong setting of minSpaceRequired read from Settings: "
+ minSpaceLeft);
throw new ArgumentNotValid(
"Wrong setting of minSpaceRequired read from Settings: "
+ minSpaceLeft);
}
log.info("Requiring at least " + minSpaceRequired + " bytes free.");
log.info("Listening if at least " + minSpaceLeft + " bytes free.");
for (String filedirname : filedirnames) {
File basedir = new File(filedirname);
File filedir = new File(basedir, Constants.FILE_DIRECTORY_NAME);
// Ensure that 'filedir' exists. If it doesn't, it is created
ApplicationUtils.dirMustExist(filedir);
File tempdir = new File(basedir,
Constants.TEMPORARY_DIRECTORY_NAME);
// Ensure that 'tempdir' exists. If it doesn't, it is created
ApplicationUtils.dirMustExist(tempdir);
File atticdir = new File(basedir, Constants.ATTIC_DIRECTORY_NAME);
// Ensure that 'atticdir' exists. If it doesn't, it is created
ApplicationUtils.dirMustExist(atticdir);
archivePaths.add(basedir);
final Long bytesUsedInDir = calculateBytesUsed(basedir);
log.info("Using bit archive directorys {'"
+ Constants.FILE_DIRECTORY_NAME + "', '"
+ Constants.TEMPORARY_DIRECTORY_NAME + "', '"
+ Constants.ATTIC_DIRECTORY_NAME
+ "'} under base directory: '" + basedir+ "' with "
+ bytesUsedInDir + " bytes of content and "
+ FileUtils.getBytesFree(basedir) + " bytes free");
}
}
/**
* Returns true if we have at least one dir with the required amount
* of space left.
*
* @return true if we have at least one dir with the required amount
* of space left, otherwise false.
*/
public boolean hasEnoughSpace() {
for (File dir : archivePaths) {
if (checkArchiveDir(dir)
&& FileUtils.getBytesFree(dir) > minSpaceLeft) {
return true;
}
}
return false;
}
/**
* Returns a temporary place for the the file to be stored.
*
* @param arcFileName The simple name (i.e. no dirs) of the ARC file.
* @param requestedSize How large the file is in bytes.
* @return The path where the arcFile should go.
*
* @throws ArgumentNotValid
* If arcFileName is null or empty, or requestedSize is negative.
* @throws IOFailure if there is no more room left to store this file of
* size=requestedSize
*/
public File getTemporaryPath(String arcFileName, long requestedSize)
throws ArgumentNotValid, IOFailure {
ArgumentNotValid.checkNotNullOrEmpty(arcFileName, "arcFile");
ArgumentNotValid.checkNotNegative(requestedSize, "requestedSize");
for (File dir : archivePaths) {
long bytesFreeInDir = FileUtils.getBytesFree(dir);
// TODO If it turns out that it has not enough space for
// this file, it should resend the Upload message
// This should probably be handled in the
// method BitarchiveServer.visit(UploadMessage msg)
// This is bug 1586.
if (checkArchiveDir(dir)
&& (bytesFreeInDir > minSpaceLeft)
&& (bytesFreeInDir - requestedSize > minSpaceRequired)) {
File filedir = new File(
dir, Constants.TEMPORARY_DIRECTORY_NAME);
return new File(filedir, arcFileName);
} else {
log.debug("Not enough space on dir '"
+ dir.getAbsolutePath() + "' for file '"
+ arcFileName + "' of size " + requestedSize
+ " bytes. Only " + bytesFreeInDir + " left");
}
}
String errMsg = "No space left to store file '" + arcFileName
+ "' of size " + requestedSize;
log.warn(errMsg);
throw new IOFailure(errMsg);
}
/**
* Moves a file from temporary storage to file storage.
*
* Note: It is checked, if tempLocation resides in directory
* TEMPORARY_DIRECTORY_NAME and whether the parent of tempLocation
* is a Bitarchive directory.
*
* @param tempLocation The temporary location where the file was stored.
* This must be a path returned from getTemporaryPath
*
* @return The location where the file is now stored
* @throws IOFailure if tempLocation is not created from getTemporaryPath
* or file cannot be moved to Storage location.
*/
public File moveToStorage(File tempLocation) {
ArgumentNotValid.checkNotNull(tempLocation, "tempLocation");
tempLocation = tempLocation.getAbsoluteFile();
String arcFileName = tempLocation.getName();
/**
* Check, that File tempLocation resides in directory
* TEMPORARY_DIRECTORY_NAME.
*/
File arcFilePath = tempLocation.getParentFile();
if (arcFilePath == null
|| !arcFilePath.getName().equals(
Constants.TEMPORARY_DIRECTORY_NAME)) {
throw new IOFailure("Location '" + tempLocation + "' is not in "
+ "tempdir '"
+ Constants.TEMPORARY_DIRECTORY_NAME + "'");
}
/**
* Check, that arcFilePath (now known to be TEMPORARY_DIRECTORY_NAME)
* resides in a recognised Bitarchive Directory.
*/
File archivedir = arcFilePath.getParentFile();
if (archivedir == null || !isBitarchiveDirectory(archivedir)) {
throw new IOFailure("Location '" + tempLocation + "' is not in "
+ "recognised archive directory.");
}
/**
* Move File tempLocation to new location: storageFile
*/
File storagePath = new File(archivedir,
Constants.FILE_DIRECTORY_NAME);
File storageFile = new File(storagePath, arcFileName);
if (!tempLocation.renameTo(storageFile)) {
throw new IOFailure("Could not move '" + tempLocation.getPath()
+ "' to '" + storageFile.getPath() + "'");
}
return storageFile;
}
/**
* Checks whether a directory is one of the known bitarchive directories.
*
* @param theDir The dir to check
* @return true If it is a valid archive directory; otherwise returns false.
* @throws IOFailure if theDir or one of the valid archive directories
* does not exist
* @throws ArgumentNotValid if theDir is null
*/
protected boolean isBitarchiveDirectory(File theDir) {
ArgumentNotValid.checkNotNull(theDir, "File theDir");
try {
theDir = theDir.getCanonicalFile();
for (File knowndir : archivePaths) {
if (knowndir.getCanonicalFile().equals(theDir)) {
return true;
}
}
return false;
} catch (IOException e) {
final String errMsg = "File not known";
log.warn(errMsg, e);
throw new IOFailure(errMsg, e);
}
}
/**
* Check that the given file is a directory appropriate for use.
* A File is appropiate to use as archivedir, if the file is an
* existing directory, and is writable by this java process.
*
* @param file A file
* @return true, if 'file' is an existing directory and is writable.
* @throws ArgumentNotValid if 'file' is null.
*/
private boolean checkArchiveDir(File file) {
ArgumentNotValid.checkNotNull(file, "file");
if (!file.exists()) {
log.warn("Directory '" + file + "' does not exist");
return false;
}
if (!file.isDirectory()) {
log.warn("Directory '" + file
+ "' is not a directory after all");
return false;
}
if (!file.canWrite()) {
log.warn("Directory '" + file + "' is not writable");
return false;
}
return true;
}
/**
* Return array with references to all files in the archive.
*
* @return array with references to all files in the archive
*/
public File[] getFiles() {
List<File> files = new ArrayList<File>();
for (File archivePath : archivePaths) {
File archiveDir = new File(archivePath,
Constants.FILE_DIRECTORY_NAME);
if (checkArchiveDir(archiveDir)) {
File[] filesHere = archiveDir.listFiles();
for (File file : filesHere) {
if (!file.isFile()) {
log.warn("Non-file '" + file.getAbsolutePath()
+ "' found among archive files");
} else {
files.add(file);
}
}
}
}
return files.toArray(new File[files.size()]);
}
/** Return an array of all files in this archive that match a given
* regular expression on the filename.
*
* @param regexp A precompiled regular expression matching whole filenames.
* This will probably be given to a FilenameFilter
* @return An array of all the files in this bitarchive that exactly match
* the regular expression on the filename (sans paths).
*/
public File[] getFilesMatching(final Pattern regexp) {
ArgumentNotValid.checkNotNull(regexp, "Pattern regexp");
List<File> files = new ArrayList<File>();
for (File archivePath : archivePaths) {
File archiveDir = new File(archivePath,
Constants.FILE_DIRECTORY_NAME);
if (checkArchiveDir(archiveDir)) {
File[] filesHere = archiveDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
if (regexp.matcher(name).matches()) {
if (!new File(dir, name).isFile()) {
log.warn("Non regular file '"
+ new File(dir, name).getAbsolutePath()
+ "' found among archive files");
return false;
} else {
return true;
}
} else {
return false;
}
}
});
files.addAll(Arrays.asList(filesHere));
}
}
return files.toArray(new File[files.size()]);
}
/**
* Return the path that a given arc file can be found in.
*
* @param arcFileName Name of an arc file (with no path)
* @return A BitarchiveARCFile for the given file, or null if the
* file does not exist.
*/
public BitarchiveARCFile lookup(String arcFileName) {
ArgumentNotValid.checkNotNullOrEmpty(arcFileName, "arcFileName");
for (File archivePath : archivePaths) {
File archiveDir = new File(archivePath,
Constants.FILE_DIRECTORY_NAME);
if (checkArchiveDir(archiveDir)) {
File filename = new File(archiveDir, arcFileName);
if (filename.exists()) {
if (filename.isFile()) {
return new BitarchiveARCFile(arcFileName, filename);
}
log.fatal("Possibly corrupt bitarchive: Non-file '"
+ filename + "' found in"
+ " place of archive file");
}
}
}
// the arcfile named "arcFileName" does not exist in this bitarchive.
log.trace("The arcfile named '" + arcFileName
+ "' does not exist in this bitarchve");
return null;
}
/**
* Calculate how many bytes are used by all files in a directory.
*
* @param filedir An existing directory with a FILE_DIRECTORY_NAME subdir
* and a TEMPORARY_DIRECTORY_NAME subdir.
* @return Number of bytes used by all files in the directory (not including
* overhead from partially used blocks).
*/
private long calculateBytesUsed(File filedir) {
long used = 0;
File[] files = new File(filedir, Constants.FILE_DIRECTORY_NAME)
.listFiles();
// Check, that listFiles method returns valid information
if (files != null) {
for (File datafiles : files) {
if (datafiles.isFile()) {
// Add size of file f to amount of bytes used.
used += datafiles.length();
} else {
log.warn("Non-file '" + datafiles.getAbsolutePath()
+ "' found in archive");
}
}
} else {
log.warn("filedir does not contain a directory named: "
+ Constants.FILE_DIRECTORY_NAME);
}
File[] tempfiles = new File(filedir,
Constants.TEMPORARY_DIRECTORY_NAME).listFiles();
// Check, that listFiles() method returns valid information
if (tempfiles != null) {
for (File tempfile : tempfiles) {
if (tempfile.isFile()) {
// Add size of file f to amount of bytes used.
used += tempfile.length();
} else {
log.warn(
"Non-file '" + tempfile.getAbsolutePath()
+ "' found in archive");
}
}
} else {
log.warn("filedir does not contain a directory named: "
+ Constants.TEMPORARY_DIRECTORY_NAME);
}
File[] atticfiles = new File(filedir, Constants.ATTIC_DIRECTORY_NAME)
.listFiles();
// Check, that listFiles() method returns valid information
if (atticfiles != null) {
for (File atticfile : atticfiles) {
if (atticfile.isFile()) {
// Add size of file tempfiles[i] to amount of bytes used.
used += atticfile.length();
} else {
log.warn("Non-file '" + atticfile.getAbsolutePath()
+ "' found in archive");
}
}
} else {
log.warn("filedir does not contain a directory named: "
+ Constants.ATTIC_DIRECTORY_NAME);
}
return used;
}
/**
* Get the one and only instance of the bitarchive admin.
*
* @return A BitarchiveAdmin object
*/
public static BitarchiveAdmin getInstance() {
if (instance == null) {
instance = new BitarchiveAdmin();
}
return instance;
}
/**
* Close down the bitarchive admin.
* Currently has no data to store.
*/
public void close() {
instance = null;
}
/** Return the path used to store files that are removed by
* RemoveAndGetFileMessage.
*
* @param existingFile a File object for an existing file in the bitarchive
*
* @return The full path of the file in the attic dir
*/
public File getAtticPath(File existingFile) {
ArgumentNotValid.checkNotNull(existingFile, "File existingFile");
// Find where the file resides so we can use a dir in the same place.
existingFile = existingFile.getAbsoluteFile();
String arcFileName = existingFile.getName();
File parentDir = existingFile.getParentFile().getParentFile();
if (!isBitarchiveDirectory(parentDir)) {
log.warn("Attempt to get attic path for non-archived file '"
+ existingFile + "'");
throw new ArgumentNotValid("File should belong to a bitarchive dir,"
+ " but " + existingFile + " doesn't");
}
// Ensure that 'atticdir' exists. If it doesn't, it is created
File atticdir = new File(parentDir, Constants.ATTIC_DIRECTORY_NAME);
ApplicationUtils.dirMustExist(atticdir);
return new File(atticdir, arcFileName);
}
}
| Changed log message if all directories failed to store arc file.
| src/dk/netarkivet/archive/bitarchive/BitarchiveAdmin.java | Changed log message if all directories failed to store arc file. |
|
Java | apache-2.0 | 0b0b1a93a6335b7ed09eb06db65605dd7d411ca8 | 0 | BackupTheBerlios/gavrog,BackupTheBerlios/gavrog,BackupTheBerlios/gavrog,BackupTheBerlios/gavrog,BackupTheBerlios/gavrog | /*
Copyright 2006 Olaf Delgado-Friedrichs
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.gavrog.joss.experiments;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.gavrog.box.collections.Partition;
import org.gavrog.joss.geometry.Operator;
import org.gavrog.joss.geometry.Point;
import org.gavrog.joss.geometry.Vector;
import org.gavrog.joss.pgraphs.basic.INode;
import org.gavrog.joss.pgraphs.basic.Morphism;
import org.gavrog.joss.pgraphs.basic.PeriodicGraph;
import org.gavrog.joss.pgraphs.io.Net;
import org.gavrog.joss.pgraphs.io.NetParser;
import org.gavrog.joss.pgraphs.io.Output;
public class Ladder {
private final PeriodicGraph graph;
private final Partition rungPartition;
private final List stileMaps;
public Ladder(final PeriodicGraph G) {
// --- check prerequisites
if (!G.isConnected()) {
throw new UnsupportedOperationException("graph must be connected");
}
if (!G.isLocallyStable()) {
throw new UnsupportedOperationException("graph must be locally stable");
}
// --- remember the graph given
this.graph = G;
// --- find equivalence classes w.r.t. ladder translations
final Operator I = Operator.identity(G.getDimension());
final Partition P = new Partition();
final Iterator iter = G.nodes();
final INode start = (INode) iter.next();
final Map pos = G.barycentricPlacement();
final Point pos0 = (Point) pos.get(start);
while (iter.hasNext()) {
final INode v = (INode) iter.next();
final Point posv = (Point) pos.get(v);
if (!((Vector) posv.minus(pos0)).modZ().isZero()) {
continue;
}
if (P.areEquivalent(start, v)) {
continue;
}
final Morphism iso;
try {
iso = new Morphism(start, v, I);
} catch (Morphism.NoSuchMorphismException ex) {
continue;
}
boolean hasFixedPoints = false;
for (final Iterator it = G.nodes(); it.hasNext();) {
final INode w = (INode) it.next();
final INode u = (INode) iso.get(w);
if (w.equals(u)) {
hasFixedPoints = true;
break;
}
}
if (hasFixedPoints) {
continue;
}
for (final Iterator it = G.nodes(); it.hasNext();) {
final INode w = (INode) it.next();
P.unite(w, iso.get(w));
}
}
this.rungPartition = P;
// --- collect morphisms from the start node to each node in its rung
final List maps = new LinkedList();
for (final Iterator classes = P.classes(); classes.hasNext();) {
final Set A = (Set) classes.next();
if (A.contains(start)) {
for (final Iterator nodes = A.iterator(); nodes.hasNext();) {
final INode v = (INode) nodes.next();
maps.add(new Morphism(start, v, I));
}
break;
}
}
this.stileMaps = maps;
}
/**
* @return the graph
*/
public PeriodicGraph getGraph() {
return graph;
}
/**
* @return the stileMaps
*/
public List getStileMaps() {
return stileMaps;
}
/**
* @return the rungPartition
*/
public Partition getRungPartition() {
return rungPartition;
}
public static void main(final String args[]) {
try {
final Reader r;
final Writer w;
if (args.length > 0) {
r = new FileReader(args[0]);
} else {
r = new InputStreamReader(System.in);
}
if (args.length > 1) {
w = new FileWriter(args[1]);
} else {
w = new OutputStreamWriter(System.out);
}
final NetParser parser = new NetParser(r);
while (true) {
final Net net = parser.parseNet();
if (net == null) {
return;
} else {
final PeriodicGraph G = net.canonical();
final Ladder ladder = new Ladder(G);
Output.writePGR(w, G, net.getName());
w.write('\n');
w.write(String.valueOf(ladder.getRungPartition()));
w.write('\n');
w.write(String.valueOf(ladder.getStileMaps()));
w.write("\n\n");
w.flush();
}
}
} catch (final IOException ex) {
System.err.print(ex);
System.exit(1);
}
}
}
| src/org/gavrog/joss/experiments/Ladder.java | /*
Copyright 2006 Olaf Delgado-Friedrichs
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.gavrog.joss.experiments;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.gavrog.box.collections.Partition;
import org.gavrog.joss.geometry.Operator;
import org.gavrog.joss.geometry.Point;
import org.gavrog.joss.geometry.Vector;
import org.gavrog.joss.pgraphs.basic.INode;
import org.gavrog.joss.pgraphs.basic.Morphism;
import org.gavrog.joss.pgraphs.basic.PeriodicGraph;
import org.gavrog.joss.pgraphs.io.Net;
import org.gavrog.joss.pgraphs.io.NetParser;
import org.gavrog.joss.pgraphs.io.Output;
public class Ladder {
private final PeriodicGraph graph;
private final Partition rungPartition;
private final List stileMaps;
public Ladder(final PeriodicGraph G) {
// --- check prerequisites
if (!G.isConnected()) {
throw new UnsupportedOperationException("graph must be connected");
}
if (!G.isLocallyStable()) {
throw new UnsupportedOperationException("graph must be locally stable");
}
// --- find equivalence classes w.r.t. ladder translations
final Operator I = Operator.identity(G.getDimension());
final Partition P = new Partition();
final Iterator iter = G.nodes();
final INode start = (INode) iter.next();
final Map pos = G.barycentricPlacement();
final Point pos0 = (Point) pos.get(start);
final List maps = new LinkedList();
while (iter.hasNext()) {
final INode v = (INode) iter.next();
final Point posv = (Point) pos.get(v);
if (!((Vector) posv.minus(pos0)).modZ().isZero()) {
continue;
}
if (P.areEquivalent(start, v)) {
continue;
}
final Morphism iso;
try {
iso = new Morphism(start, v, I);
} catch (Morphism.NoSuchMorphismException ex) {
continue;
}
maps.add(iso);
boolean hasFixedPoints = false;
for (final Iterator it = G.nodes(); it.hasNext();) {
final INode w = (INode) it.next();
final INode u = (INode) iso.get(w);
if (w.equals(u)) {
hasFixedPoints = true;
break;
}
}
if (hasFixedPoints) {
continue;
}
for (final Iterator it = G.nodes(); it.hasNext();) {
final INode w = (INode) it.next();
P.unite(w, iso.get(w));
}
}
this.stileMaps = maps;
this.rungPartition = P;
this.graph = G;
}
/**
* @return the graph
*/
public PeriodicGraph getGraph() {
return graph;
}
/**
* @return the stileMaps
*/
public List getStileMaps() {
return stileMaps;
}
/**
* @return the rungPartition
*/
public Partition getRungPartition() {
return rungPartition;
}
public static void main(final String args[]) {
try {
final Reader r;
final Writer w;
if (args.length > 0) {
r = new FileReader(args[0]);
} else {
r = new InputStreamReader(System.in);
}
if (args.length > 1) {
w = new FileWriter(args[1]);
} else {
w = new OutputStreamWriter(System.out);
}
final NetParser parser = new NetParser(r);
while (true) {
final Net net = parser.parseNet();
if (net == null) {
return;
} else {
final PeriodicGraph G = net.canonical();
Output.writePGR(w, G, net.getName());
w.write('\n');
w.write(String.valueOf((new Ladder(G).getRungPartition())));
w.write("\n\n");
w.flush();
}
}
} catch (final IOException ex) {
System.err.print(ex);
System.exit(1);
}
}
}
| Generates a more usable list of stile maps and has main() print it.
| src/org/gavrog/joss/experiments/Ladder.java | Generates a more usable list of stile maps and has main() print it. |
|
Java | apache-2.0 | daa02870f050863d0e7dc66553f3ff8789159784 | 0 | subutai-io/base,subutai-io/base,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/base,subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai,subutai-io/Subutai | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.safehaus.subutai.core.communication.api;
import org.safehaus.subutai.common.protocol.Agent;
import org.safehaus.subutai.common.protocol.Request;
import org.safehaus.subutai.common.protocol.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* This is simple utility class for serializing/deserializing object to/from json.
*/
public class CommandJson
{
private static final Logger LOG = LoggerFactory.getLogger( CommandJson.class.getName() );
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().addDeserializationExclusionStrategy(
new SkipNullsExclusionStrategy() ).disableHtmlEscaping().create();
private CommandJson()
{
}
/**
* Escapes symbols in json string
*
* @param s - string to escape
*
* @return escaped json string
*/
private static String escape( String s )
{
StringBuilder sb = new StringBuilder();
for ( int i = 0; i < s.length(); i++ )
{
char ch = s.charAt( i );
switch ( ch )
{
case '"':
sb.append( "\"" );
break;
case '\\':
sb.append( "\\" );
break;
case '\b':
sb.append( "\b" );
break;
case '\f':
sb.append( "\f" );
break;
case '\n':
sb.append( "\n" );
break;
case '\r':
sb.append( "\r" );
break;
case '\t':
sb.append( "\t" );
break;
case '/':
sb.append( "\\/" );
break;
default:
sb.append( processDefaultCase( ch ) );
}
}
return sb.toString();
}
private static String processDefaultCase( char ch )
{
StringBuilder sb = new StringBuilder();
if ( ( ch >= '\u0000' && ch <= '\u001F' ) || ( ch >= '\u007F' && ch <= '\u009F' ) || ( ch >= '\u2000'
&& ch <= '\u20FF' ) )
{
String ss = Integer.toHexString( ch );
sb.append( "\\u" );
for ( int k = 0; k < 4 - ss.length(); k++ )
{
sb.append( '0' );
}
sb.append( ss.toUpperCase() );
}
else
{
sb.append( ch );
}
return sb.toString();
}
/**
* Returns deserialized request from json string
*
* @param json - request in json format
*
* @return request
*/
public static Request getRequest( String json )
{
try
{
Command cmd = getCommand( json );
if ( cmd.getRequest() != null )
{
return cmd.getRequest();
}
}
catch ( Exception ex )
{
LOG.error( "Error in getRequest", ex );
}
return null;
}
/**
* Returns deserialized response from json string
*
* @param json - response in json format
*
* @return response
*/
public static Response getResponse( String json )
{
try
{
Command cmd = getCommand( json );
if ( cmd.getResponse() != null )
{
return cmd.getResponse();
}
}
catch ( Exception ex )
{
LOG.error( "Error in getResponse", ex );
}
return null;
}
/**
* Returns deserialized command from json string
*
* @param json - command in json format
*
* @return command
*/
public static Command getCommand( String json )
{
try
{
return GSON.fromJson( escape( json ), CommandImpl.class );
}
catch ( Exception ex )
{
LOG.error( "Error in getCommand", ex );
}
return null;
}
/**
* Returns serialized request from Request POJO
*
* @param cmd - request in pojo format
*
* @return request in json format
*/
public static String getJson( Request cmd )
{
try
{
return GSON.toJson( new CommandImpl( cmd ) );
}
catch ( Exception ex )
{
LOG.error( "Error in getJson", ex );
}
return null;
}
/**
* Returns serialized response from Response POJO
*
* @param cmd - response in pojo format
*
* @return response in json format
*/
public static String getResponse( Response cmd )
{
try
{
return GSON.toJson( new CommandImpl( cmd ) );
}
catch ( Exception ex )
{
LOG.error( "Error in getResponse", ex );
}
return null;
}
/**
* Returns serialized command from Command POJO
*
* @param cmd - command in pojo format
*
* @return request in command format
*/
public static String getJson( Command cmd )
{
try
{
return GSON.toJson( cmd );
}
catch ( Exception ex )
{
LOG.error( "Error in getJson", ex );
}
return null;
}
/**
* Returns serialized agent from Agent POJO
*
* @param agent - agent in pojo format
*
* @return agent in json format
*/
public static String getAgentJson( Object agent )
{
try
{
return GSON.toJson( agent );
}
catch ( Exception ex )
{
LOG.error( "Error in getAgentJson", ex );
}
return null;
}
/**
* Returns deserialized agent from Agent json
*
* @param json - agent in json format
*
* @return agent in pojo format
*/
public static Agent getAgent( String json )
{
try
{
Agent agent = GSON.fromJson( escape( json ), Agent.class );
if ( agent != null )
{
return agent;
}
}
catch ( Exception ex )
{
LOG.error( "Error in getAgent", ex );
}
return null;
}
private static class CommandImpl implements Command
{
Request command;
Response response;
public CommandImpl( Object message )
{
if ( message instanceof Request )
{
this.command = ( Request ) message;
}
else if ( message instanceof Response )
{
this.response = ( Response ) message;
}
}
@Override
public Request getRequest()
{
return command;
}
@Override
public Response getResponse()
{
return response;
}
}
}
| management/server/core/communication-manager/communication-manager-api/src/main/java/org/safehaus/subutai/core/communication/api/CommandJson.java | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.safehaus.subutai.core.communication.api;
import org.safehaus.subutai.common.protocol.Agent;
import org.safehaus.subutai.common.protocol.Request;
import org.safehaus.subutai.common.protocol.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
/**
* This is simple utility class for serializing/deserializing object to/from json.
*/
public class CommandJson
{
private static final Logger LOG = LoggerFactory.getLogger( CommandJson.class.getName() );
private static final Gson GSON = new GsonBuilder().setPrettyPrinting().addDeserializationExclusionStrategy(
new SkipNullsExclusionStrategy() ).disableHtmlEscaping().create();
private CommandJson() {}
/**
* Escapes symbols in json string
*
* @param s - string to escape
*
* @return escaped json string
*/
private static String escape( String s )
{
StringBuilder sb = new StringBuilder();
for ( int i = 0; i < s.length(); i++ )
{
char ch = s.charAt( i );
switch ( ch )
{
case '"':
sb.append( "\"" );
break;
case '\\':
sb.append( "\\" );
break;
case '\b':
sb.append( "\b" );
break;
case '\f':
sb.append( "\f" );
break;
case '\n':
sb.append( "\n" );
break;
case '\r':
sb.append( "\r" );
break;
case '\t':
sb.append( "\t" );
break;
case '/':
sb.append( "\\/" );
break;
default:
sb.append( processDefaultCase( ch ) );
}
}
return sb.toString();
}
private static String processDefaultCase( char ch )
{
StringBuilder sb = new StringBuilder();
if ( ( ch >= '\u0000' && ch <= '\u001F' ) || ( ch >= '\u007F' && ch <= '\u009F' ) || ( ch >= '\u2000'
&& ch <= '\u20FF' ) )
{
String ss = Integer.toHexString( ch );
sb.append( "\\u" );
for ( int k = 0; k < 4 - ss.length(); k++ )
{
sb.append( '0' );
}
sb.append( ss.toUpperCase() );
}
else
{
sb.append( ch );
}
return sb.toString();
}
/**
* Returns deserialized request from json string
*
* @param json - request in json format
*
* @return request
*/
public static Request getRequest( String json )
{
try
{
Command cmd = getCommand( json );
if ( cmd.getRequest() != null )
{
return cmd.getRequest();
}
}
catch ( Exception ex )
{
LOG.error( "Error in getRequest", ex );
}
return null;
}
/**
* Returns deserialized response from json string
*
* @param json - response in json format
*
* @return response
*/
public static Response getResponse( String json )
{
try
{
Command cmd = getCommand( json );
if ( cmd.getResponse() != null )
{
return cmd.getResponse();
}
}
catch ( Exception ex )
{
LOG.error( "Error in getResponse", ex );
}
return null;
}
/**
* Returns deserialized command from json string
*
* @param json - command in json format
*
* @return command
*/
public static Command getCommand( String json )
{
try
{
return GSON.fromJson( escape( json ), CommandImpl.class );
}
catch ( Exception ex )
{
LOG.error( "Error in getCommand", ex );
}
return null;
}
/**
* Returns serialized request from Request POJO
*
* @param cmd - request in pojo format
*
* @return request in json format
*/
public static String getJson( Request cmd )
{
try
{
return GSON.toJson( new CommandImpl( cmd ) );
}
catch ( Exception ex )
{
LOG.error( "Error in getJson", ex );
}
return null;
}
/**
* Returns serialized response from Response POJO
*
* @param cmd - response in pojo format
*
* @return response in json format
*/
public static String getResponse( Response cmd )
{
try
{
return GSON.toJson( new CommandImpl( cmd ) );
}
catch ( Exception ex )
{
LOG.error( "Error in getResponse", ex );
}
return null;
}
/**
* Returns serialized command from Command POJO
*
* @param cmd - command in pojo format
*
* @return request in command format
*/
public static String getJson( Command cmd )
{
try
{
return GSON.toJson( cmd );
}
catch ( Exception ex )
{
LOG.error( "Error in getJson", ex );
}
return null;
}
/**
* Returns serialized agent from Agent POJO
*
* @param agent - agent in pojo format
*
* @return agent in json format
*/
public static String getAgentJson( Object agent )
{
try
{
return GSON.toJson( agent );
}
catch ( Exception ex )
{
LOG.error( "Error in getAgentJson", ex );
}
return null;
}
/**
* Returns deserialized agent from Agent json
*
* @param json - agent in json format
*
* @return agent in pojo format
*/
public static Agent getAgent( String json )
{
try
{
Agent agent = GSON.fromJson( escape( json ), Agent.class );
if ( agent != null )
{
return agent;
}
}
catch ( Exception ex )
{
LOG.error( "Error in getAgent", ex );
}
return null;
}
private static class CommandImpl implements Command
{
Request command;
Response response;
public CommandImpl( Object message )
{
if ( message instanceof Request )
{
this.command = ( Request ) message;
}
else if ( message instanceof Response )
{
this.response = ( Response ) message;
}
}
@Override
public Request getRequest()
{
return command;
}
@Override
public Response getResponse()
{
return response;
}
}
}
| sonar bugfix
| management/server/core/communication-manager/communication-manager-api/src/main/java/org/safehaus/subutai/core/communication/api/CommandJson.java | sonar bugfix |
|
Java | apache-2.0 | f35eb7166812904f03a98100b67a0db20a03e4fb | 0 | hazendaz/classloader-leak-prevention,mjiderhamn/classloader-leak-prevention | /*
Copyright 2012 Mattias Jiderhamn
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 se.jiderhamn.classloader.leak.prevention;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import se.jiderhamn.classloader.leak.prevention.cleanup.ShutdownHookCleanUp;
import se.jiderhamn.classloader.leak.prevention.cleanup.StopThreadsCleanUp;
import se.jiderhamn.classloader.leak.prevention.preinit.OracleJdbcThreadInitiator;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static se.jiderhamn.classloader.leak.prevention.cleanup.ShutdownHookCleanUp.SHUTDOWN_HOOK_WAIT_MS_DEFAULT;
/**
* This class helps prevent classloader leaks.
* <h1>Basic setup</h1>
* <p>Activate protection by adding this class as a context listener
* in your <code>web.xml</code>, like this:</p>
* <pre>
* <listener>
* <listener-class>se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor</listener-class>
* </listener>
* </pre>
*
* You should usually declare this <code>listener</code> before any other listeners, to make it "outermost".
*
* <h1>Configuration</h1>
* The context listener has a number of settings that can be configured with context parameters in <code>web.xml</code>,
* i.e.:
*
* <pre>
* <context-param>
* <param-name>ClassLoaderLeakPreventor.stopThreads</param-name>
* <param-value>false</param-value>
* </context-param>
* </pre>
*
* The available settings are
* <table border="1">
* <tr>
* <th>Parameter name</th>
* <th>Default value</th>
* <th>Description</th>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.stopThreads</code></td>
* <td><code>true</code></td>
* <td>Should threads tied to the web app classloader be forced to stop at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.stopTimerThreads</code></td>
* <td><code>true</code></td>
* <td>Should Timer threads tied to the web app classloader be forced to stop at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.executeShutdownHooks</td>
* <td><code>true</code></td>
* <td>Should shutdown hooks registered from the application be executed at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.threadWaitMs</td>
* <td><code>5000</code> (5 seconds)</td>
* <td>No of milliseconds to wait for threads to finish execution, before stopping them.</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.shutdownHookWaitMs</code></td>
* <td><code>10000</code> (10 seconds)</td>
* <td>
* No of milliseconds to wait for shutdown hooks to finish execution, before stopping them.
* If set to -1 there will be no waiting at all, but Thread is allowed to run until finished.
* </td>
* </tr>
* </table>
*
*
* <h1>License</h1>
* <p>This code is licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2</a> license,
* which allows you to include modified versions of the code in your distributed software, without having to release
* your source code.</p>
*
* <h1>More info</h1>
* <p>For more info, see
* <a href="http://java.jiderhamn.se/2012/03/04/classloader-leaks-vi-this-means-war-leak-prevention-library/">here</a>.
* </p>
*
* <h1>Design goals</h1>
* <p>If you want to help improve this component, you should be aware of the design goals</p>
* <p>
* Primary design goal: Zero dependencies. The component should build and run using nothing but the JDK and the
* Servlet API. Specifically we should <b>not</b> depend on any logging framework, since they are part of the problem.
* We also don't want to use any utility libraries, in order not to impose any further dependencies into any project
* that just wants to get rid of classloader leaks.
* Access to anything outside of the standard JDK (in order to prevent a known leak) should be managed
* with reflection.
* </p>
* <p>
* Secondary design goal: Keep the runtime component in a single <code>.java</code> file. It should be possible to
* just add this one <code>.java</code> file into your own source tree.
* </p>
*
* @author Mattias Jiderhamn, 2012-2016
*/
@SuppressWarnings("WeakerAccess")
public class ClassLoaderLeakPreventorListener implements ServletContextListener {
protected ClassLoaderLeakPreventor classLoaderLeakPreventor;
/** Other {@link javax.servlet.ServletContextListener}s to use also */
protected final List<ServletContextListener> otherListeners = new LinkedList<ServletContextListener>();
/**
* Get the default set of other {@link ServletContextListener} to be automatically invoked.
* NOTE! Anything added here should be idempotent, i.e. there should be no problem executing the listener twice.
*/
static List<ServletContextListener> getDefaultOtherListeners() {
try{
Class<ServletContextListener> introspectorCleanupListenerClass =
(Class<ServletContextListener>) Class.forName("org.springframework.web.util.IntrospectorCleanupListener");
return singletonList(introspectorCleanupListenerClass.newInstance());
}
catch (ClassNotFoundException e) {
// Ignore silently - Spring not present on classpath
}
catch(Exception e){
e.printStackTrace(System.err);
}
return emptyList();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Implement javax.servlet.ServletContextListener
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
otherListeners.addAll(getDefaultOtherListeners());
contextInitialized(servletContextEvent.getServletContext());
for(ServletContextListener listener : otherListeners) {
try {
listener.contextInitialized(servletContextEvent);
}
catch(Exception e){
classLoaderLeakPreventor.error(e);
}
}
}
void contextInitialized(final ServletContext servletContext) {
// Should threads tied to the web app classloader be forced to stop at application shutdown?
boolean stopThreads = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopThreads"));
// Should Timer threads tied to the web app classloader be forced to stop at application shutdown?
boolean stopTimerThreads = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopTimerThreads"));
// Should shutdown hooks registered from the application be executed at application shutdown?
boolean executeShutdownHooks = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.executeShutdownHooks"));
/*
* Should the {@code oracle.jdbc.driver.OracleTimeoutPollingThread} thread be forced to start with system classloader,
* in case Oracle JDBC driver is present? This is normally a good idea, but can be disabled in case the Oracle JDBC
* driver is not used even though it is on the classpath.
*/
boolean startOracleTimeoutThread = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.startOracleTimeoutThread"));
// No of milliseconds to wait for threads to finish execution, before stopping them.
int threadWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.threadWaitMs", ClassLoaderLeakPreventor.THREAD_WAIT_MS_DEFAULT);
/*
* No of milliseconds to wait for shutdown hooks to finish execution, before stopping them.
* If set to -1 there will be no waiting at all, but Thread is allowed to run until finished.
*/
int shutdownHookWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.shutdownHookWaitMs", SHUTDOWN_HOOK_WAIT_MS_DEFAULT);
final ClassLoader webAppClassLoader = Thread.currentThread().getContextClassLoader();
info("Settings for " + this.getClass().getName() + " (CL: 0x" +
Integer.toHexString(System.identityHashCode(webAppClassLoader)) + "):");
info(" stopThreads = " + stopThreads);
info(" stopTimerThreads = " + stopTimerThreads);
info(" executeShutdownHooks = " + executeShutdownHooks);
info(" threadWaitMs = " + threadWaitMs + " ms");
info(" shutdownHookWaitMs = " + shutdownHookWaitMs + " ms");
// Create factory with default PreClassLoaderInitiators and ClassLoaderPreMortemCleanUps
final ClassLoaderLeakPreventorFactory classLoaderLeakPreventorFactory = createClassLoaderLeakPreventorFactory();
// Configure default PreClassLoaderInitiators
if(! startOracleTimeoutThread)
classLoaderLeakPreventorFactory.removePreInitiator(OracleJdbcThreadInitiator.class);
// Configure default ClassLoaderPreMortemCleanUps
final ShutdownHookCleanUp shutdownHookCleanUp = classLoaderLeakPreventorFactory.getCleanUp(ShutdownHookCleanUp.class);
shutdownHookCleanUp.setExecuteShutdownHooks(executeShutdownHooks);
shutdownHookCleanUp.setShutdownHookWaitMs(shutdownHookWaitMs);
final StopThreadsCleanUp stopThreadsCleanUp = classLoaderLeakPreventorFactory.getCleanUp(StopThreadsCleanUp.class);
stopThreadsCleanUp.setStopThreads(stopThreads);
stopThreadsCleanUp.setStopTimerThreads(stopTimerThreads);
stopThreadsCleanUp.setThreadWaitMs(threadWaitMs);
classLoaderLeakPreventor = classLoaderLeakPreventorFactory.newLeakPreventor(webAppClassLoader);
classLoaderLeakPreventor.runPreClassLoaderInitiators();
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
info(getClass().getName() + " shutting down context by removing known leaks (CL: 0x" +
Integer.toHexString(System.identityHashCode(classLoaderLeakPreventor.getClassLoader())) + ")");
for(ServletContextListener listener : otherListeners) {
try {
listener.contextDestroyed(servletContextEvent);
}
catch(Exception e) {
classLoaderLeakPreventor.error(e);
}
}
classLoaderLeakPreventor.runCleanUps();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Utility methods
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Create {@link ClassLoaderLeakPreventorFactory} to use. Subclasses may opt to override this method. */
protected ClassLoaderLeakPreventorFactory createClassLoaderLeakPreventorFactory() {
return new ClassLoaderLeakPreventorFactory();
}
/** Parse init parameter for integer value, returning default if not found or invalid */
protected static int getIntInitParameter(ServletContext servletContext, String parameterName, int defaultValue) {
final String parameterString = servletContext.getInitParameter(parameterName);
if(parameterString != null && parameterString.trim().length() > 0) {
try {
return Integer.parseInt(parameterString);
}
catch (NumberFormatException e) {
// Do nothing, return default value
}
}
return defaultValue;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Log methods
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* Since logging frameworks are part of the problem, we don't want to depend on any of them here.
* Feel free however to subclass or fork and use a log framework, in case you think you know what you're doing.
*/
protected String getLogPrefix() {
return ClassLoaderLeakPreventorListener.class.getSimpleName() + ": ";
}
/**
* To "turn off" info logging override this method in a subclass and make that subclass method empty.
*/
protected void info(String s) {
System.out.println(getLogPrefix() + s);
}
}
| classloader-leak-prevention/classloader-leak-prevention-servlet/src/main/java/se/jiderhamn/classloader/leak/prevention/ClassLoaderLeakPreventorListener.java | /*
Copyright 2012 Mattias Jiderhamn
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 se.jiderhamn.classloader.leak.prevention;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import se.jiderhamn.classloader.leak.prevention.cleanup.ShutdownHookCleanUp;
import se.jiderhamn.classloader.leak.prevention.cleanup.StopThreadsCleanUp;
import se.jiderhamn.classloader.leak.prevention.preinit.OracleJdbcThreadInitiator;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static se.jiderhamn.classloader.leak.prevention.cleanup.ShutdownHookCleanUp.SHUTDOWN_HOOK_WAIT_MS_DEFAULT;
/**
* This class helps prevent classloader leaks.
* <h1>Basic setup</h1>
* <p>Activate protection by adding this class as a context listener
* in your <code>web.xml</code>, like this:</p>
* <pre>
* <listener>
* <listener-class>se.jiderhamn.classloader.leak.prevention.ClassLoaderLeakPreventor</listener-class>
* </listener>
* </pre>
*
* You should usually declare this <code>listener</code> before any other listeners, to make it "outermost".
*
* <h1>Configuration</h1>
* The context listener has a number of settings that can be configured with context parameters in <code>web.xml</code>,
* i.e.:
*
* <pre>
* <context-param>
* <param-name>ClassLoaderLeakPreventor.stopThreads</param-name>
* <param-value>false</param-value>
* </context-param>
* </pre>
*
* The available settings are
* <table border="1">
* <tr>
* <th>Parameter name</th>
* <th>Default value</th>
* <th>Description</th>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.stopThreads</code></td>
* <td><code>true</code></td>
* <td>Should threads tied to the web app classloader be forced to stop at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.stopTimerThreads</code></td>
* <td><code>true</code></td>
* <td>Should Timer threads tied to the web app classloader be forced to stop at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.executeShutdownHooks</td>
* <td><code>true</code></td>
* <td>Should shutdown hooks registered from the application be executed at application shutdown?</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.threadWaitMs</td>
* <td><code>5000</code> (5 seconds)</td>
* <td>No of milliseconds to wait for threads to finish execution, before stopping them.</td>
* </tr>
* <tr>
* <td><code>ClassLoaderLeakPreventor.shutdownHookWaitMs</code></td>
* <td><code>10000</code> (10 seconds)</td>
* <td>
* No of milliseconds to wait for shutdown hooks to finish execution, before stopping them.
* If set to -1 there will be no waiting at all, but Thread is allowed to run until finished.
* </td>
* </tr>
* </table>
*
*
* <h1>License</h1>
* <p>This code is licensed under the <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2</a> license,
* which allows you to include modified versions of the code in your distributed software, without having to release
* your source code.</p>
*
* <h1>More info</h1>
* <p>For more info, see
* <a href="http://java.jiderhamn.se/2012/03/04/classloader-leaks-vi-this-means-war-leak-prevention-library/">here</a>.
* </p>
*
* <h1>Design goals</h1>
* <p>If you want to help improve this component, you should be aware of the design goals</p>
* <p>
* Primary design goal: Zero dependencies. The component should build and run using nothing but the JDK and the
* Servlet API. Specifically we should <b>not</b> depend on any logging framework, since they are part of the problem.
* We also don't want to use any utility libraries, in order not to impose any further dependencies into any project
* that just wants to get rid of classloader leaks.
* Access to anything outside of the standard JDK (in order to prevent a known leak) should be managed
* with reflection.
* </p>
* <p>
* Secondary design goal: Keep the runtime component in a single <code>.java</code> file. It should be possible to
* just add this one <code>.java</code> file into your own source tree.
* </p>
*
* @author Mattias Jiderhamn, 2012-2016
*/
@SuppressWarnings("WeakerAccess")
public class ClassLoaderLeakPreventorListener implements ServletContextListener {
protected ClassLoaderLeakPreventor classLoaderLeakPreventor;
/** Other {@link javax.servlet.ServletContextListener}s to use also */
protected final List<ServletContextListener> otherListeners = new LinkedList<ServletContextListener>();
/**
* Get the default set of other {@link ServletContextListener} to be automatically invoked.
* NOTE! Anything added here should be idempotent, i.e. there should be no problem executing the listener twice.
*/
static List<ServletContextListener> getDefaultOtherListeners() {
try{
Class<ServletContextListener> introspectorCleanupListenerClass =
(Class<ServletContextListener>) Class.forName("org.springframework.web.util.IntrospectorCleanupListener");
return singletonList(introspectorCleanupListenerClass.newInstance());
}
catch (ClassNotFoundException e) {
// Ignore silently - Spring not present on classpath
}
catch(Exception e){
e.printStackTrace(System.err);
}
return emptyList();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Implement javax.servlet.ServletContextListener
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
otherListeners.addAll(getDefaultOtherListeners());
contextInitialized(servletContextEvent.getServletContext());
for(ServletContextListener listener : otherListeners) {
try {
listener.contextInitialized(servletContextEvent);
}
catch(Exception e){
classLoaderLeakPreventor.error(e);
}
}
}
void contextInitialized(final ServletContext servletContext) {
// Should threads tied to the web app classloader be forced to stop at application shutdown?
boolean stopThreads = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopThreads"));
// Should Timer threads tied to the web app classloader be forced to stop at application shutdown?
boolean stopTimerThreads = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopTimerThreads"));
// Should shutdown hooks registered from the application be executed at application shutdown?
boolean executeShutdownHooks = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.executeShutdownHooks"));
/*
* Should the {@code oracle.jdbc.driver.OracleTimeoutPollingThread} thread be forced to start with system classloader,
* in case Oracle JDBC driver is present? This is normally a good idea, but can be disabled in case the Oracle JDBC
* driver is not used even though it is on the classpath.
*/
boolean startOracleTimeoutThread = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.startOracleTimeoutThread"));
// No of milliseconds to wait for threads to finish execution, before stopping them.
int threadWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.threadWaitMs", ClassLoaderLeakPreventor.THREAD_WAIT_MS_DEFAULT);
/*
* No of milliseconds to wait for shutdown hooks to finish execution, before stopping them.
* If set to -1 there will be no waiting at all, but Thread is allowed to run until finished.
*/
int shutdownHookWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.shutdownHookWaitMs", SHUTDOWN_HOOK_WAIT_MS_DEFAULT);
final ClassLoader webAppClassLoader = Thread.currentThread().getContextClassLoader();
info("Settings for " + this.getClass().getName() + " (CL: 0x" +
Integer.toHexString(System.identityHashCode(webAppClassLoader)) + "):");
info(" stopThreads = " + stopThreads);
info(" stopTimerThreads = " + stopTimerThreads);
info(" executeShutdownHooks = " + executeShutdownHooks);
info(" threadWaitMs = " + threadWaitMs + " ms");
info(" shutdownHookWaitMs = " + shutdownHookWaitMs + " ms");
// Create factory with default PreClassLoaderInitiators and ClassLoaderPreMortemCleanUps
final ClassLoaderLeakPreventorFactory classLoaderLeakPreventorFactory = new ClassLoaderLeakPreventorFactory();
// Configure default PreClassLoaderInitiators
if(! startOracleTimeoutThread)
classLoaderLeakPreventorFactory.removePreInitiator(OracleJdbcThreadInitiator.class);
// Configure default ClassLoaderPreMortemCleanUps
final ShutdownHookCleanUp shutdownHookCleanUp = classLoaderLeakPreventorFactory.getCleanUp(ShutdownHookCleanUp.class);
shutdownHookCleanUp.setExecuteShutdownHooks(executeShutdownHooks);
shutdownHookCleanUp.setShutdownHookWaitMs(shutdownHookWaitMs);
final StopThreadsCleanUp stopThreadsCleanUp = classLoaderLeakPreventorFactory.getCleanUp(StopThreadsCleanUp.class);
stopThreadsCleanUp.setStopThreads(stopThreads);
stopThreadsCleanUp.setStopTimerThreads(stopTimerThreads);
stopThreadsCleanUp.setThreadWaitMs(threadWaitMs);
classLoaderLeakPreventor = classLoaderLeakPreventorFactory.newLeakPreventor(webAppClassLoader);
classLoaderLeakPreventor.runPreClassLoaderInitiators();
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
info(getClass().getName() + " shutting down context by removing known leaks (CL: 0x" +
Integer.toHexString(System.identityHashCode(classLoaderLeakPreventor.getClassLoader())) + ")");
for(ServletContextListener listener : otherListeners) {
try {
listener.contextDestroyed(servletContextEvent);
}
catch(Exception e) {
classLoaderLeakPreventor.error(e);
}
}
classLoaderLeakPreventor.runCleanUps();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Utility methods
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/** Parse init parameter for integer value, returning default if not found or invalid */
protected static int getIntInitParameter(ServletContext servletContext, String parameterName, int defaultValue) {
final String parameterString = servletContext.getInitParameter(parameterName);
if(parameterString != null && parameterString.trim().length() > 0) {
try {
return Integer.parseInt(parameterString);
}
catch (NumberFormatException e) {
// Do nothing, return default value
}
}
return defaultValue;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Log methods
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
* Since logging frameworks are part of the problem, we don't want to depend on any of them here.
* Feel free however to subclass or fork and use a log framework, in case you think you know what you're doing.
*/
protected String getLogPrefix() {
return ClassLoaderLeakPreventorListener.class.getSimpleName() + ": ";
}
/**
* To "turn off" info logging override this method in a subclass and make that subclass method empty.
*/
protected void info(String s) {
System.out.println(getLogPrefix() + s);
}
}
| Improve extendability of ClassLoaderLeakPreventorListener. Fixes #86
| classloader-leak-prevention/classloader-leak-prevention-servlet/src/main/java/se/jiderhamn/classloader/leak/prevention/ClassLoaderLeakPreventorListener.java | Improve extendability of ClassLoaderLeakPreventorListener. Fixes #86 |
|
Java | apache-2.0 | 131b59452cf38d90140aa02a53431eea9ff16901 | 0 | akosyakov/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,diorcety/intellij-community,ernestp/consulo,fitermay/intellij-community,caot/intellij-community,ol-loginov/intellij-community,dslomov/intellij-community,ernestp/consulo,jagguli/intellij-community,amith01994/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,robovm/robovm-studio,samthor/intellij-community,alphafoobar/intellij-community,MER-GROUP/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,suncycheng/intellij-community,consulo/consulo,adedayo/intellij-community,ryano144/intellij-community,youdonghai/intellij-community,Lekanich/intellij-community,holmes/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,signed/intellij-community,lucafavatella/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,supersven/intellij-community,samthor/intellij-community,apixandru/intellij-community,dslomov/intellij-community,Lekanich/intellij-community,holmes/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,fengbaicanhe/intellij-community,ibinti/intellij-community,da1z/intellij-community,supersven/intellij-community,fnouama/intellij-community,holmes/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,FHannes/intellij-community,lucafavatella/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,muntasirsyed/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,youdonghai/intellij-community,samthor/intellij-community,xfournet/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,allotria/intellij-community,nicolargo/intellij-community,allotria/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,fengbaicanhe/intellij-community,ernestp/consulo,wreckJ/intellij-community,kool79/intellij-community,da1z/intellij-community,ryano144/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,da1z/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,fnouama/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,signed/intellij-community,consulo/consulo,youdonghai/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,Lekanich/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,amith01994/intellij-community,clumsy/intellij-community,signed/intellij-community,semonte/intellij-community,xfournet/intellij-community,blademainer/intellij-community,fitermay/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,SerCeMan/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,jagguli/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,petteyg/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,ibinti/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,semonte/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,slisson/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,signed/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,amith01994/intellij-community,FHannes/intellij-community,holmes/intellij-community,ThiagoGarciaAlves/intellij-community,ernestp/consulo,caot/intellij-community,samthor/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,apixandru/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,vladmm/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,allotria/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,muntasirsyed/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,apixandru/intellij-community,semonte/intellij-community,caot/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,retomerz/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,ftomassetti/intellij-community,retomerz/intellij-community,supersven/intellij-community,akosyakov/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,idea4bsd/idea4bsd,Distrotech/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,supersven/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,slisson/intellij-community,robovm/robovm-studio,apixandru/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,ol-loginov/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,samthor/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,izonder/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,izonder/intellij-community,allotria/intellij-community,samthor/intellij-community,fnouama/intellij-community,allotria/intellij-community,dslomov/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,semonte/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,jagguli/intellij-community,da1z/intellij-community,clumsy/intellij-community,samthor/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,adedayo/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,adedayo/intellij-community,ryano144/intellij-community,FHannes/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,signed/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,fitermay/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,caot/intellij-community,izonder/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,fitermay/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,akosyakov/intellij-community,adedayo/intellij-community,jagguli/intellij-community,kool79/intellij-community,SerCeMan/intellij-community,MichaelNedzelsky/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,clumsy/intellij-community,allotria/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,xfournet/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,ivan-fedorov/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,ibinti/intellij-community,fitermay/intellij-community,adedayo/intellij-community,dslomov/intellij-community,asedunov/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,signed/intellij-community,kool79/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,samthor/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,xfournet/intellij-community,asedunov/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,supersven/intellij-community,orekyuu/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,ibinti/intellij-community,ernestp/consulo,pwoodworth/intellij-community,diorcety/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,hurricup/intellij-community,da1z/intellij-community,consulo/consulo,apixandru/intellij-community,ftomassetti/intellij-community,pwoodworth/intellij-community,ivan-fedorov/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,izonder/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,holmes/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,salguarnieri/intellij-community,akosyakov/intellij-community,kool79/intellij-community,clumsy/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,supersven/intellij-community,ryano144/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,vladmm/intellij-community,fitermay/intellij-community,petteyg/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,semonte/intellij-community,amith01994/intellij-community,ryano144/intellij-community,ibinti/intellij-community,suncycheng/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,dslomov/intellij-community,hurricup/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,consulo/consulo,SerCeMan/intellij-community,signed/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,supersven/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,MichaelNedzelsky/intellij-community,signed/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,apixandru/intellij-community,retomerz/intellij-community,consulo/consulo,lucafavatella/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,kdwink/intellij-community,izonder/intellij-community,hurricup/intellij-community,kdwink/intellij-community,signed/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,clumsy/intellij-community,caot/intellij-community,semonte/intellij-community,ibinti/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,kdwink/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,fnouama/intellij-community,asedunov/intellij-community,izonder/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,michaelgallacher/intellij-community,izonder/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,petteyg/intellij-community,amith01994/intellij-community,samthor/intellij-community,orekyuu/intellij-community,suncycheng/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,caot/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,jagguli/intellij-community,slisson/intellij-community,ryano144/intellij-community,allotria/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,adedayo/intellij-community,semonte/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,holmes/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,holmes/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,alphafoobar/intellij-community,slisson/intellij-community,asedunov/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,izonder/intellij-community,allotria/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,amith01994/intellij-community,xfournet/intellij-community,allotria/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,fnouama/intellij-community,apixandru/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,xfournet/intellij-community,kdwink/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,petteyg/intellij-community,adedayo/intellij-community,asedunov/intellij-community,vladmm/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,vladmm/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,kool79/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,semonte/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,amith01994/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,apixandru/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,slisson/intellij-community,ol-loginov/intellij-community,izonder/intellij-community,signed/intellij-community,semonte/intellij-community,petteyg/intellij-community,diorcety/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,fitermay/intellij-community,blademainer/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,fnouama/intellij-community,kool79/intellij-community,ernestp/consulo,kdwink/intellij-community,samthor/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,wreckJ/intellij-community,TangHao1987/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,adedayo/intellij-community,clumsy/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,hurricup/intellij-community,caot/intellij-community,signed/intellij-community,vvv1559/intellij-community,semonte/intellij-community,tmpgit/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,adedayo/intellij-community,adedayo/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,caot/intellij-community,lucafavatella/intellij-community,retomerz/intellij-community,orekyuu/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,robovm/robovm-studio,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,izonder/intellij-community,dslomov/intellij-community,jagguli/intellij-community,michaelgallacher/intellij-community,asedunov/intellij-community,amith01994/intellij-community,clumsy/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,diorcety/intellij-community,consulo/consulo,fnouama/intellij-community,robovm/robovm-studio,akosyakov/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,FHannes/intellij-community,slisson/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,jagguli/intellij-community,xfournet/intellij-community,diorcety/intellij-community | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.gradle.config;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.ide.util.projectWizard.NamePathComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Alarm;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.gradle.util.GradleBundle;
import org.jetbrains.plugins.gradle.util.GradleIcons;
import org.jetbrains.plugins.gradle.util.GradleLibraryManager;
import org.jetbrains.plugins.gradle.util.GradleUtil;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.io.File;
import java.util.concurrent.TimeUnit;
/**
* @author peter
*/
public class GradleConfigurable implements SearchableConfigurable {
@NonNls public static final String HELP_TOPIC = "reference.settingsdialog.project.gradle";
/**
* There is a possible case that end-user defines gradle home while particular project is open. We want to use that gradle
* home for the default project as well until that is manually changed for the default project.
* <p/>
* Current constant holds key of the value that defines if gradle home for default project should be tracked from
* the non-default one.
* <p/>
* This property has a form of 'not-propagate' in order to default to 'propagate'.
*/
@NonNls private static final String NOT_PROPAGATE_GRADLE_HOME_TO_DEFAULT_PROJECT = "gradle.not.propagate.home.to.default.project";
private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
private final GradleLibraryManager myLibraryManager;
private final Project myProject;
private GradleHomeSettingType myGradleHomeSettingType = GradleHomeSettingType.UNKNOWN;
private JComponent myComponent;
private NamePathComponent myGradleHomeComponent;
private boolean myPathManuallyModified;
private boolean myShowBalloonIfNecessary;
public GradleConfigurable(@Nullable Project project) {
this(project, ServiceManager.getService(GradleLibraryManager.class));
}
public GradleConfigurable(@Nullable Project project, @NotNull GradleLibraryManager gradleLibraryManager) {
myLibraryManager = gradleLibraryManager;
myProject = project;
doCreateComponent();
}
@NotNull
@Override
public String getId() {
return getHelpTopic();
}
@Override
public Runnable enableSearch(String option) {
return null;
}
@Nls
@Override
public String getDisplayName() {
return GradleBundle.message("gradle.name");
}
@Override
public JComponent createComponent() {
if (myComponent == null) {
doCreateComponent();
}
return myComponent;
}
private void doCreateComponent() {
myComponent = new JPanel(new GridBagLayout()) {
@Override
public void paint(Graphics g) {
super.paint(g);
if (!myShowBalloonIfNecessary) {
return;
}
myShowBalloonIfNecessary = false;
MessageType messageType = null;
switch (myGradleHomeSettingType) {
case DEDUCED: messageType = MessageType.WARNING; break;
case EXPLICIT_INCORRECT:
case UNKNOWN: messageType = MessageType.ERROR; break;
default:
}
if (messageType != null) {
new DelayedBalloonInfo(messageType, myGradleHomeSettingType).run();
}
}
};
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.weightx = 1;
constraints.weighty = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.anchor = GridBagConstraints.NORTH;
myGradleHomeComponent = new NamePathComponent(
"", GradleBundle.message("gradle.import.text.home.path"), GradleBundle.message("gradle.import.text.home.path"), "",
false,
false
);
myGradleHomeComponent.getPathComponent().getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
useNormalColorForPath();
myPathManuallyModified = true;
}
@Override
public void removeUpdate(DocumentEvent e) {
useNormalColorForPath();
myPathManuallyModified = true;
}
@Override
public void changedUpdate(DocumentEvent e) {
}
});
myGradleHomeComponent.setNameComponentVisible(false);
myComponent.add(myGradleHomeComponent, constraints);
myComponent.add(Box.createVerticalGlue());
}
@Override
public boolean isModified() {
myShowBalloonIfNecessary = true;
if (!myPathManuallyModified) {
return false;
}
String newPath = myGradleHomeComponent.getPath();
String oldPath = GradleSettings.getInstance(myProject).GRADLE_HOME;
boolean modified = newPath == null ? oldPath == null : !newPath.equals(oldPath);
if (modified) {
useNormalColorForPath();
}
return modified;
}
@Override
public void apply() {
useNormalColorForPath();
String path = myGradleHomeComponent.getPath();
GradleSettings.getInstance(myProject).GRADLE_HOME = path;
// There is a possible case that user defines gradle home for particular open project. We want to apply that value
// to the default project as well if it's still non-defined.
Project defaultProject = ProjectManager.getInstance().getDefaultProject();
if (defaultProject == myProject) {
PropertiesComponent.getInstance().setValue(NOT_PROPAGATE_GRADLE_HOME_TO_DEFAULT_PROJECT, Boolean.TRUE.toString());
return;
}
if (!StringUtil.isEmpty(path)
&& !Boolean.parseBoolean(PropertiesComponent.getInstance().getValue(NOT_PROPAGATE_GRADLE_HOME_TO_DEFAULT_PROJECT)))
{
GradleSettings.getInstance(defaultProject).GRADLE_HOME = path;
}
}
@Override
public void reset() {
useNormalColorForPath();
myPathManuallyModified = false;
String valueToUse = GradleSettings.getInstance(myProject).GRADLE_HOME;
if (StringUtil.isEmpty(valueToUse)) {
valueToUse = GradleSettings.getInstance(ProjectManager.getInstance().getDefaultProject()).GRADLE_HOME;
}
if (!StringUtil.isEmpty(valueToUse)) {
myGradleHomeSettingType = myLibraryManager.isGradleSdkHome(new File(valueToUse)) ?
GradleHomeSettingType.EXPLICIT_CORRECT :
GradleHomeSettingType.EXPLICIT_INCORRECT;
if (myGradleHomeSettingType == GradleHomeSettingType.EXPLICIT_INCORRECT) {
new DelayedBalloonInfo(MessageType.ERROR, myGradleHomeSettingType).run();
}
else {
myAlarm.cancelAllRequests();
}
myGradleHomeComponent.setPath(valueToUse);
return;
}
myGradleHomeSettingType = GradleHomeSettingType.UNKNOWN;
deduceGradleHomeIfPossible();
}
private void useNormalColorForPath() {
myGradleHomeComponent.getPathComponent().setForeground(UIManager.getColor("TextField.foreground"));
}
/**
* Updates GUI of the gradle configurable in order to show deduced path to gradle (if possible).
*/
private void deduceGradleHomeIfPossible() {
File gradleHome = myLibraryManager.getGradleHome(myProject);
if (gradleHome == null) {
new DelayedBalloonInfo(MessageType.WARNING, GradleHomeSettingType.UNKNOWN).run();
return;
}
myGradleHomeSettingType = GradleHomeSettingType.DEDUCED;
new DelayedBalloonInfo(MessageType.INFO, GradleHomeSettingType.DEDUCED).run();
if (myGradleHomeComponent != null) {
myGradleHomeComponent.setPath(gradleHome.getPath());
myGradleHomeComponent.getPathComponent().setForeground(UIManager.getColor("TextField.inactiveForeground"));
myPathManuallyModified = false;
}
}
@Override
public void disposeUIResources() {
myComponent = null;
myGradleHomeComponent = null;
myPathManuallyModified = false;
}
public Icon getIcon() {
return GradleIcons.GRADLE_ICON;
}
@NotNull
public String getHelpTopic() {
return HELP_TOPIC;
}
/**
* @return UI component that manages path to the local gradle distribution to use
*/
@NotNull
public NamePathComponent getGradleHomeComponent() {
if (myGradleHomeComponent == null) {
createComponent();
}
return myGradleHomeComponent;
}
@NotNull
public GradleHomeSettingType getCurrentGradleHomeSettingType() {
String path = myGradleHomeComponent.getPath();
if (path == null || StringUtil.isEmpty(path.trim())) {
return GradleHomeSettingType.UNKNOWN;
}
if (isModified()) {
return myLibraryManager.isGradleSdkHome(new File(path)) ? GradleHomeSettingType.EXPLICIT_CORRECT
: GradleHomeSettingType.EXPLICIT_INCORRECT;
}
return myGradleHomeSettingType;
}
private class DelayedBalloonInfo implements Runnable {
private final MessageType myMessageType;
private final String myText;
DelayedBalloonInfo(@NotNull MessageType messageType, @NotNull GradleHomeSettingType settingType) {
myMessageType = messageType;
myText = settingType.getDescription();
}
@Override
public void run() {
if (myGradleHomeComponent == null || !myGradleHomeComponent.getPathComponent().isShowing()) {
myAlarm.cancelAllRequests();
myAlarm.addRequest(this, (int)TimeUnit.MILLISECONDS.toMillis(200));
return;
}
GradleUtil.showBalloon(myGradleHomeComponent.getPathComponent(), myMessageType, myText);
}
}
} | plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleConfigurable.java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.gradle.config;
import com.intellij.ide.util.PropertiesComponent;
import com.intellij.ide.util.projectWizard.NamePathComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.options.SearchableConfigurable;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.Alarm;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.gradle.util.GradleBundle;
import org.jetbrains.plugins.gradle.util.GradleIcons;
import org.jetbrains.plugins.gradle.util.GradleLibraryManager;
import org.jetbrains.plugins.gradle.util.GradleUtil;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.io.File;
import java.util.concurrent.TimeUnit;
/**
* @author peter
*/
public class GradleConfigurable implements SearchableConfigurable {
@NonNls public static final String HELP_TOPIC = "reference.settingsdialog.project.gradle";
/**
* There is a possible case that end-user defines gradle home while particular project is open. We want to use that gradle
* home for the default project as well until that is manually changed for the default project.
* <p/>
* Current constant holds key of the value that defines if gradle home for default project should be tracked from
* the non-default one.
* <p/>
* This property has a form of 'not-propagate' in order to default to 'propagate'.
*/
@NonNls private static final String NOT_PROPAGATE_GRADLE_HOME_TO_DEFAULT_PROJECT = "gradle.not.propagate.home.to.default.project";
private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
private final GradleLibraryManager myLibraryManager;
private final Project myProject;
private GradleHomeSettingType myGradleHomeSettingType = GradleHomeSettingType.UNKNOWN;
private JComponent myComponent;
private NamePathComponent myGradleHomeComponent;
private boolean myPathManuallyModified;
public GradleConfigurable(@Nullable Project project) {
this(project, ServiceManager.getService(GradleLibraryManager.class));
}
public GradleConfigurable(@Nullable Project project, @NotNull GradleLibraryManager gradleLibraryManager) {
myLibraryManager = gradleLibraryManager;
myProject = project;
doCreateComponent();
}
@NotNull
@Override
public String getId() {
return getHelpTopic();
}
@Override
public Runnable enableSearch(String option) {
return null;
}
@Nls
@Override
public String getDisplayName() {
return GradleBundle.message("gradle.name");
}
@Override
public JComponent createComponent() {
if (myComponent == null) {
doCreateComponent();
}
return myComponent;
}
private void doCreateComponent() {
myComponent = new JPanel(new GridBagLayout());
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridwidth = GridBagConstraints.REMAINDER;
constraints.weightx = 1;
constraints.weighty = 1;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.anchor = GridBagConstraints.NORTH;
myGradleHomeComponent = new NamePathComponent(
"", GradleBundle.message("gradle.import.text.home.path"), GradleBundle.message("gradle.import.text.home.path"), "",
false,
false
);
myGradleHomeComponent.getPathComponent().getDocument().addDocumentListener(new DocumentListener() {
@Override
public void insertUpdate(DocumentEvent e) {
useNormalColorForPath();
myPathManuallyModified = true;
}
@Override
public void removeUpdate(DocumentEvent e) {
useNormalColorForPath();
myPathManuallyModified = true;
}
@Override
public void changedUpdate(DocumentEvent e) {
}
});
myGradleHomeComponent.setNameComponentVisible(false);
myComponent.add(myGradleHomeComponent, constraints);
myComponent.add(Box.createVerticalGlue());
}
@Override
public boolean isModified() {
if (!myPathManuallyModified) {
return false;
}
String newPath = myGradleHomeComponent.getPath();
String oldPath = GradleSettings.getInstance(myProject).GRADLE_HOME;
boolean modified = newPath == null ? oldPath == null : !newPath.equals(oldPath);
if (modified) {
useNormalColorForPath();
}
return modified;
}
@Override
public void apply() {
useNormalColorForPath();
String path = myGradleHomeComponent.getPath();
GradleSettings.getInstance(myProject).GRADLE_HOME = path;
// There is a possible case that user defines gradle home for particular open project. We want to apply that value
// to the default project as well if it's still non-defined.
Project defaultProject = ProjectManager.getInstance().getDefaultProject();
if (defaultProject == myProject) {
PropertiesComponent.getInstance().setValue(NOT_PROPAGATE_GRADLE_HOME_TO_DEFAULT_PROJECT, Boolean.TRUE.toString());
return;
}
if (!StringUtil.isEmpty(path)
&& !Boolean.parseBoolean(PropertiesComponent.getInstance().getValue(NOT_PROPAGATE_GRADLE_HOME_TO_DEFAULT_PROJECT)))
{
GradleSettings.getInstance(defaultProject).GRADLE_HOME = path;
}
}
@Override
public void reset() {
useNormalColorForPath();
myPathManuallyModified = false;
String valueToUse = GradleSettings.getInstance(myProject).GRADLE_HOME;
if (StringUtil.isEmpty(valueToUse)) {
valueToUse = GradleSettings.getInstance(ProjectManager.getInstance().getDefaultProject()).GRADLE_HOME;
}
if (!StringUtil.isEmpty(valueToUse)) {
myGradleHomeSettingType = myLibraryManager.isGradleSdkHome(new File(valueToUse)) ?
GradleHomeSettingType.EXPLICIT_CORRECT :
GradleHomeSettingType.EXPLICIT_INCORRECT;
if (myGradleHomeSettingType == GradleHomeSettingType.EXPLICIT_INCORRECT) {
new DelayedBalloonInfo(MessageType.ERROR, myGradleHomeSettingType).run();
}
else {
myAlarm.cancelAllRequests();
}
myGradleHomeComponent.setPath(valueToUse);
return;
}
myGradleHomeSettingType = GradleHomeSettingType.UNKNOWN;
deduceGradleHomeIfPossible();
}
private void useNormalColorForPath() {
myGradleHomeComponent.getPathComponent().setForeground(UIManager.getColor("TextField.foreground"));
}
/**
* Updates GUI of the gradle configurable in order to show deduced path to gradle (if possible).
*/
private void deduceGradleHomeIfPossible() {
File gradleHome = myLibraryManager.getGradleHome(myProject);
if (gradleHome == null) {
new DelayedBalloonInfo(MessageType.WARNING, GradleHomeSettingType.UNKNOWN).run();
return;
}
myGradleHomeSettingType = GradleHomeSettingType.DEDUCED;
new DelayedBalloonInfo(MessageType.INFO, GradleHomeSettingType.DEDUCED).run();
if (myGradleHomeComponent != null) {
myGradleHomeComponent.setPath(gradleHome.getPath());
myGradleHomeComponent.getPathComponent().setForeground(UIManager.getColor("TextField.inactiveForeground"));
myPathManuallyModified = false;
}
}
@Override
public void disposeUIResources() {
myComponent = null;
myGradleHomeComponent = null;
myPathManuallyModified = false;
}
public Icon getIcon() {
return GradleIcons.GRADLE_ICON;
}
@NotNull
public String getHelpTopic() {
return HELP_TOPIC;
}
/**
* @return UI component that manages path to the local gradle distribution to use
*/
@NotNull
public NamePathComponent getGradleHomeComponent() {
if (myGradleHomeComponent == null) {
createComponent();
}
return myGradleHomeComponent;
}
@NotNull
public GradleHomeSettingType getCurrentGradleHomeSettingType() {
String path = myGradleHomeComponent.getPath();
if (path == null || StringUtil.isEmpty(path.trim())) {
return GradleHomeSettingType.UNKNOWN;
}
if (isModified()) {
return myLibraryManager.isGradleSdkHome(new File(path)) ? GradleHomeSettingType.EXPLICIT_CORRECT
: GradleHomeSettingType.EXPLICIT_INCORRECT;
}
return myGradleHomeSettingType;
}
private class DelayedBalloonInfo implements Runnable {
private final MessageType myMessageType;
private final String myText;
DelayedBalloonInfo(@NotNull MessageType messageType, @NotNull GradleHomeSettingType settingType) {
myMessageType = messageType;
myText = settingType.getDescription();
}
@Override
public void run() {
if (myGradleHomeComponent == null || !myGradleHomeComponent.getPathComponent().isShowing()) {
myAlarm.cancelAllRequests();
myAlarm.addRequest(this, (int)TimeUnit.MILLISECONDS.toMillis(200));
return;
}
GradleUtil.showBalloon(myGradleHomeComponent.getPathComponent(), myMessageType, myText);
}
}
} | IDEA-53476 Gradle integration (Maven's level - dependencies, modules, repositories)
Balloon about gradle location is showed if necessary every time gradle configurable component is selected at the settings
| plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleConfigurable.java | IDEA-53476 Gradle integration (Maven's level - dependencies, modules, repositories) |
|
Java | apache-2.0 | af59ce82de3239295ae53e167bba080ccbec5f4b | 0 | powertac/powertac-server,powertac/powertac-server,powertac/powertac-server,powertac/powertac-server | /*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.powertac.visualizer.services;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.powertac.common.Competition;
import org.powertac.common.XMLMessageConverter;
import org.powertac.common.msg.BrokerAccept;
import org.powertac.common.msg.BrokerAuthentication;
import org.powertac.common.msg.VisualizerStatusRequest;
import org.powertac.common.repo.DomainRepo;
import org.powertac.visualizer.MessageDispatcher;
import org.powertac.visualizer.VisualizerApplicationContext;
import org.powertac.visualizer.beans.VisualizerBean;
import org.powertac.visualizer.interfaces.Initializable;
import org.powertac.visualizer.services.VisualizerState.Event;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.jms.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Main Visualizer service. Its main purpose is to register with Visualizer
* proxy and to receive messages from simulator.
*
* @author Jurica Babic, John Collins
*
*/
@Service
public class VisualizerServiceTournament
implements MessageListener, InitializingBean
{
static private Logger log =
Logger.getLogger(VisualizerServiceTournament.class.getName());
@Resource(name = "jmsFactory")
private ConnectionFactory connectionFactory;
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
@Autowired
XMLMessageConverter converter;
@Autowired
JmsTemplate template;
@Autowired
private VisualizerBean visualizerBean;
private String tournamentUrl = "";
private String visualizerLoginContext = "";
private String machineName = "";
private String serverUrl = "tcp://localhost:61616";
private String serverQueue = "serverInput";
private String queueName = "remote-visualizer";
// visualizer interaction
private LocalVisualizerProxy proxy;
private boolean initialized = false;
private boolean running = false;
// state parameters
private long tickPeriod = 30000l; // 30 sec
private long maxMsgInterval = 120000l; // 2 min
private long maxGameReadyInterval = 300000l; // 5 min
private long gameReadyAt = 0l;
private long lastMsgTime = 0l;
private boolean runningStates = true;
// States
private VisualizerState initial, loginWait, gameWait, gameReady, loggedIn;
private VisualizerState currentState;
// event queue
private BlockingQueue<Event> eventQueue = new LinkedBlockingQueue<Event>();
// message queue
private BlockingQueue<Object> messageQueue = new LinkedBlockingQueue<Object>();
// Timers, Threads and Runnables that may need to be killed
private Timer tickTimer = null;
private TimerTask stateTask = null;
private Thread messageFeeder = null;
private Thread stateRunner = null;
@Autowired
private MessageDispatcher dispatcher;
/**
* Called on initialization to start message feeder and state machine.
*/
public void init ()
{
// Start the logger
Logger root = Logger.getRootLogger();
root.removeAllAppenders();
try {
PatternLayout logLayout = new PatternLayout("%r %-5p %c{2}: %m%n");
String logPath = System.getProperty("catalina.base", "");
if (!logPath.isEmpty()) {
logPath += "/logs/" + machineName + "-viz.log";
} else {
logPath += "log/" + machineName + "-viz.log";
}
FileAppender logFile = new FileAppender(logLayout, logPath, false);
root.addAppender(logFile);
}
catch (IOException ioe) {
log.info("Can't open log file");
System.exit(0);
}
// Start the message feeder
messageFeeder = new Thread(messagePump);
messageFeeder.setDaemon(true);
messageFeeder.start();
// Start the state machine
tickTimer = new Timer(true);
stateTask = new TimerTask()
{
@Override
public void run ()
{
log.debug("message count = " + visualizerBean.getMessageCount() +
", queue size = " + messageQueue.size());
putEvent(Event.tick);
}
};
tickTimer.schedule(stateTask, 10, tickPeriod);
stateRunner = new Thread(runStates);
stateRunner.setDaemon(true);
stateRunner.start();
}
@PreDestroy
private void cleanUp () throws Exception
{
System.out.print("\nCleaning up VisualizerServiceTournament (8) : ");
// Shutdown the proxy if needed
if (proxy != null) {
proxy.shutDown();
}
System.out.print("1 ");
// Kill the tick timer
// I have no idea why this loop is needed
while (tickTimer == null) {
try { Thread.sleep(100); } catch (Exception ignored) {}
}
System.out.print("2 ");
tickTimer.cancel();
tickTimer.purge();
tickTimer = null;
System.out.print("3 ");
if (stateTask != null) {
stateTask.cancel();
}
System.out.print("4 ");
// Kill the message pump
try {
messageFeeder.interrupt();
messageFeeder.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("5 ");
// Kill the state machine from within
putEvent(Event.quit);
while (runningStates) {
try { Thread.sleep(100); } catch (Exception ignored) {}
if (currentState == loginWait && stateRunner != null &&
stateRunner.getState() == Thread.State.TIMED_WAITING) {
stateRunner.interrupt();
}
}
System.out.print("6 ");
try {
stateRunner.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("7 ");
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
for (Thread t: threadArray) {
if (t.getName().contains("Timer-") || t.getName().contains("ActiveMQ")) {
synchronized(t) {
t.stop();
}
}
}
System.out.println("8\n");
}
// convience functions for handling the event queue
private void putEvent (Event event)
{
try {
eventQueue.put(event);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
private Event getEvent ()
{
try {
return eventQueue.take();
}
catch (InterruptedException e) {
e.printStackTrace();
return Event.tick; // default event, harmless enough
}
}
private void setCurrentState (VisualizerState newState)
{
currentState = newState;
newState.entry();
}
// Run the viz state machine -- called from timer thread.
private Runnable runStates = new Runnable()
{
@Override
public void run ()
{
runningStates = true;
initial = new VisualizerState()
{
@Override
public void entry ()
{
log.info("state initial");
if (null != proxy) {
shutDown();
}
setCurrentState(loginWait);
}
@Override
public void handleEvent (Event event)
{
if (event == Event.tick) {
// safety valve
setCurrentState(loginWait);
}
}
};
loginWait = new VisualizerState()
{
@Override
public void entry ()
{
log.info("state loginWait");
tournamentLogin();
}
@Override
public void handleEvent (Event event)
{
if (event == Event.noTm) {
setCurrentState(gameWait);
} else if (event == Event.accept) {
setCurrentState(gameReady);
} else if (event == Event.tick) {
tournamentLogin();
}
}
};
gameWait = new VisualizerState()
{
@Override
public void entry ()
{
log.info("state gameWait");
gameLogin();
}
@Override
public void handleEvent (Event event)
{
if (event == Event.vsr) {
setCurrentState(loggedIn);
} else if (event == Event.tick) {
pingServer(); // try again
}
}
};
gameReady = new VisualizerState()
{
@Override
public void entry ()
{
log.info("state gameReady");
gameReadyAt = new Date().getTime();
gameLogin();
}
@Override
public void handleEvent (Event event)
{
if (event == Event.vsr) {
setCurrentState(loggedIn);
} else if (event == Event.tick) {
long now = new Date().getTime();
// limit harrassment of running game
if (now > (gameReadyAt + maxGameReadyInterval)) {
setCurrentState(initial);
} else {
pingServer(); // try again
}
}
}
};
loggedIn = new VisualizerState()
{
@Override
public void entry ()
{
log.info("state loggedIn");
}
@Override
public void handleEvent (Event event)
{
if (event == Event.simEnd) {
setCurrentState(initial);
} else if (event == Event.tick && isInactive()) {
setCurrentState(initial);
}
}
};
setCurrentState(initial);
while (runningStates) {
Event event = getEvent();
if (event == Event.quit) {
runningStates = false;
break;
}
currentState.handleEvent(event);
}
}
};
// Logs into the tournament manager to get the queue name for the
// upcoming session
private void tournamentLogin ()
{
//log.info("Tournament URL='" + tournamentUrl + "'");
if (tournamentUrl.isEmpty()) {
// No TM, just connect to server
putEvent(Event.noTm);
return;
}
String urlString = tournamentUrl + visualizerLoginContext +
"?machineName=" + machineName;
log.info("tourney url=" + urlString);
URL url;
try {
url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream input = conn.getInputStream();
log.info("Parsing message..");
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(input);
doc.getDocumentElement().normalize();
// Two different message types
Node retryNode = doc.getElementsByTagName("retry").item(0);
Node loginNode = doc.getElementsByTagName("login").item(0);
if (retryNode != null) {
String checkRetry = retryNode.getFirstChild()
.getNodeValue();
log.info("Retry in " + checkRetry + " seconds");
// Received retry message; spin and try again
try {
Thread.sleep(Integer.parseInt(checkRetry) * 1000);
} catch (InterruptedException e) {
//e.printStackTrace();
}
} else if (loginNode != null) {
log.info("Login response received! ");
queueName = doc.getElementsByTagName("queueName")
.item(0).getFirstChild().getNodeValue();
serverQueue = doc.getElementsByTagName("serverQueue")
.item(0).getFirstChild().getNodeValue();
log.info(String.format(
"Login message receieved: queueName=%s, serverQueue=%s",
queueName, serverQueue));
// Small delay, server sends 'game_ready' before it's actually ready
try { Thread.sleep(5000); } catch (Exception ignored) {}
putEvent(Event.accept);
} else {
// this is not working
log.info("Invalid response from TS");
}
} catch (Exception e) {
// should we have an event here?
e.printStackTrace();
}
}
// Attempt to log into a game.
private void gameLogin ()
{
if (null == proxy) {
// no proxy yet for this game
proxy = new LocalVisualizerProxy();
proxy.init(this);
}
pingServer();
}
private void pingServer ()
{
log.info("Ping sim server");
proxy.sendMessage(new VisualizerStatusRequest());
}
private boolean isInactive ()
{
long now = new Date().getTime();
long silence = now - lastMsgTime;
if (silence > maxMsgInterval) {
// declare inactivity
log.info("Inactivity declared");
return true;
}
return false;
}
// once-per-game initialization
public void initOnce ()
{
initialized = true;
log.info("initOnce()");
visualizerBean.newRun();
dispatcher.initialize();
// registrations for message listeners:
List<Initializable> initializers =
VisualizerApplicationContext.listBeansOfType(Initializable.class);
for (Initializable init : initializers) {
log.debug("initializing..." + init.getClass().getName());
init.initialize();
}
List<DomainRepo> repos =
VisualizerApplicationContext.listBeansOfType(DomainRepo.class);
for (DomainRepo repo : repos) {
log.debug("recycling..." + repos.getClass().getName());
repo.recycle();
}
}
// shut down the queue at end-of-game, wait a few seconds, go again.
public void shutDown ()
{
// no longer initialized
initialized = false;
log.info("shut down proxy");
proxy.shutDown();
proxy = null; // force re-creation
try {
Thread.sleep(5000); // wait for sim process to quit
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
// ---------------- Message handling ------------------
// Pumps messages from incoming JMS messages into the visualizer in
// a single thread. The queue avoids potential race conditions on
// input.
private Runnable messagePump = new Runnable()
{
@Override
public void run ()
{
while (true) {
Object msg = getMessage();
if (msg instanceof InterruptedException) {
if (tickTimer == null) {
break;
} else {
((InterruptedException) msg).printStackTrace();
}
} else {
receiveMessage(msg);
}
}
}
};
// convience functions for handling the event queue
private void putMessage (Object message)
{
try {
messageQueue.put(message);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
private Object getMessage ()
{
try {
return messageQueue.take();
}
catch (InterruptedException e) {
return e;
}
}
public void receiveMessage (Object msg)
{
// once-per-game initialization...
if (msg instanceof Competition) {
// Competition must be first message. If we see something else first,
// it's an error.
initOnce();
}
else if (!initialized) {
log.info("ERROR: msg of type " + msg.getClass().getName() +
", but not initialized. Ignoring.");
return;
}
visualizerBean.incrementMessageCounter();
if (msg != null) {
//log.debug("Counter: " + visualizerBean.getMessageCount()
// + ", Got message: " + msg.getClass().getName());
//log.info("Counter: " + visualizerBean.getMessageCount()
// + ", Got message: " + msg.getClass().getName());
dispatcher.routeMessage(msg);
}
else {
log.info("Counter:" + visualizerBean.getMessageCount()
+ " Received message is NULL!");
}
// end-of-game check
if (!running && visualizerBean.isRunning()) {
running = true;
}
if (running && visualizerBean.isFinished()) {
log.info("Game finished");
putEvent(Event.simEnd);
}
}
// JMS message input processing
@Override
public void onMessage (Message message)
{
lastMsgTime = new Date().getTime();
//log.info("onMessage");
if (message instanceof TextMessage) {
try {
//log.info("onMessage: text");
onMessage(((TextMessage) message).getText());
} catch (JMSException e) {
log.info("ERROR: viz failed to extract text from TextMessage: " + e.toString());
}
}
}
// runs in JMS thread
private void onMessage (String xml)
{
log.debug("onMessage(String) - received message:\n" + xml);
Object message = converter.fromXML(xml);
log.debug("onMessage(String) - received message of type " + message.getClass().getSimpleName());
if (message instanceof VisualizerStatusRequest) {
log.info("Received vsr");
putEvent(Event.vsr);
}
else if (message instanceof BrokerAccept ||
message instanceof BrokerAuthentication) {
// hack to ignore these
}
else {
putMessage(message);
}
}
@Override
public void afterPropertiesSet () throws Exception
{
Timer initTimer = new Timer(true);
// delay to let deployment complete
initTimer.schedule(new TimerTask () {
@Override
public void run () {
init();
}
}, 20000l);
}
// URL and queue name methods
public String getQueueName ()
{
return queueName;
}
public void setQueueName (String newName)
{
queueName = newName;
}
public String getServerUrl ()
{
return serverUrl;
}
public void setServerUrl (String newUrl)
{
serverUrl = newUrl;
}
public String getTournamentUrl ()
{
return tournamentUrl;
}
public void setTournamentUrl (String newUrl)
{
tournamentUrl = newUrl;
}
public String getVisualizerLoginContext ()
{
return visualizerLoginContext;
}
public void setVisualizerLoginContext (String newContext)
{
visualizerLoginContext = newContext;
}
public String getMachineName ()
{
return machineName;
}
public void setMachineName (String name)
{
machineName = name;
}
// ------------ Local proxy implementation -------------
class LocalVisualizerProxy
{
VisualizerServiceTournament host;
boolean connectionOpen = false;
DefaultMessageListenerContainer container;
// set up the jms queue
void init (VisualizerServiceTournament host)
{
log.info("Server URL: " + getServerUrl() + ", queue: " + getQueueName());
this.host = host;
ActiveMQConnectionFactory amqConnectionFactory = null;
if (connectionFactory instanceof PooledConnectionFactory) {
PooledConnectionFactory pooledConnectionFactory = (PooledConnectionFactory) connectionFactory;
if (pooledConnectionFactory.getConnectionFactory() instanceof ActiveMQConnectionFactory) {
amqConnectionFactory = (ActiveMQConnectionFactory) pooledConnectionFactory
.getConnectionFactory();
}
}
else if (connectionFactory instanceof CachingConnectionFactory) {
CachingConnectionFactory cachingConnectionFactory = (CachingConnectionFactory) connectionFactory;
if (cachingConnectionFactory.getTargetConnectionFactory() instanceof ActiveMQConnectionFactory) {
amqConnectionFactory = (ActiveMQConnectionFactory) cachingConnectionFactory
.getTargetConnectionFactory();
}
}
if (amqConnectionFactory != null) {
amqConnectionFactory.setBrokerURL(getServerUrl());
}
// register host as listener
container = new DefaultMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setDestinationName(getQueueName());
container.setMessageListener(host);
container.setTaskExecutor(taskExecutor);
container.afterPropertiesSet();
container.start();
connectionOpen = true;
}
public void sendMessage (Object msg)
{
try {
final String text = converter.toXML(msg);
template.send(serverQueue,
new MessageCreator()
{
@Override
public Message createMessage (Session session) throws JMSException
{
TextMessage message = session.createTextMessage(text);
return message;
}
});
} catch (Exception e) {
log.warn("Exception " + e.toString() +
" sending message - ignoring");
}
}
public synchronized void shutDown ()
{
final LocalVisualizerProxy proxy = this;
Runnable callback = new Runnable()
{
@Override
public void run ()
{
proxy.closeConnection();
}
};
container.stop(callback);
while (connectionOpen) {
try {
wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void closeConnection ()
{
connectionOpen = false;
notifyAll();
}
}
}
| src/main/java/org/powertac/visualizer/services/VisualizerServiceTournament.java | /*
* Copyright 2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.powertac.visualizer.services;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.pool.PooledConnectionFactory;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.powertac.common.Competition;
import org.powertac.common.XMLMessageConverter;
import org.powertac.common.msg.BrokerAccept;
import org.powertac.common.msg.BrokerAuthentication;
import org.powertac.common.msg.VisualizerStatusRequest;
import org.powertac.common.repo.DomainRepo;
import org.powertac.visualizer.MessageDispatcher;
import org.powertac.visualizer.VisualizerApplicationContext;
import org.powertac.visualizer.beans.VisualizerBean;
import org.powertac.visualizer.interfaces.Initializable;
import org.powertac.visualizer.services.VisualizerState.Event;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.connection.CachingConnectionFactory;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.jms.listener.DefaultMessageListenerContainer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.jms.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Main Visualizer service. Its main purpose is to register with Visualizer
* proxy and to receive messages from simulator.
*
* @author Jurica Babic, John Collins
*
*/
@Service
public class VisualizerServiceTournament
implements MessageListener, InitializingBean
{
static private Logger log =
Logger.getLogger(VisualizerServiceTournament.class.getName());
@Resource(name = "jmsFactory")
private ConnectionFactory connectionFactory;
@Autowired
private ThreadPoolTaskExecutor taskExecutor;
@Autowired
XMLMessageConverter converter;
@Autowired
JmsTemplate template;
@Autowired
private VisualizerBean visualizerBean;
private String tournamentUrl = "";
private String visualizerLoginContext = "";
private String machineName = "";
private String serverUrl = "tcp://localhost:61616";
private String serverQueue = "serverInput";
private String queueName = "remote-visualizer";
// visualizer interaction
private LocalVisualizerProxy proxy;
private boolean initialized = false;
private boolean running = false;
// state parameters
private long tickPeriod = 30000l; // 30 sec
private long maxMsgInterval = 120000l; // 2 min
private long maxGameReadyInterval = 300000l; // 5 min
private long gameReadyAt = 0l;
private long lastMsgTime = 0l;
private boolean runningStates = true;
// States
private VisualizerState initial, loginWait, gameWait, gameReady, loggedIn;
private VisualizerState currentState;
// event queue
private BlockingQueue<Event> eventQueue = new LinkedBlockingQueue<Event>();
// message queue
private BlockingQueue<Object> messageQueue = new LinkedBlockingQueue<Object>();
// Timers, Threads and Runnables that may need to be killed
private Timer tickTimer = null;
private TimerTask stateTask = null;
private Thread messageFeeder = null;
private Thread stateRunner = null;
@Autowired
private MessageDispatcher dispatcher;
/**
* Called on initialization to start message feeder and state machine.
*/
public void init ()
{
// Start the logger
Logger root = Logger.getRootLogger();
root.removeAllAppenders();
try {
PatternLayout logLayout = new PatternLayout("%r %-5p %c{2}: %m%n");
String logPath = System.getProperty("catalina.base", "");
if (!logPath.isEmpty()) {
logPath += "/logs/" + machineName + "-viz.log";
} else {
logPath += "log/" + machineName + "-viz.log";
}
FileAppender logFile = new FileAppender(logLayout, logPath, false);
root.addAppender(logFile);
}
catch (IOException ioe) {
log.info("Can't open log file");
System.exit(0);
}
// Start the message feeder
messageFeeder = new Thread(messagePump);
messageFeeder.setDaemon(true);
messageFeeder.start();
// Start the state machine
tickTimer = new Timer(true);
stateTask = new TimerTask()
{
@Override
public void run ()
{
log.debug("message count = " + visualizerBean.getMessageCount() +
", queue size = " + messageQueue.size());
putEvent(Event.tick);
}
};
tickTimer.schedule(stateTask, 10, tickPeriod);
stateRunner = new Thread(runStates);
stateRunner.setDaemon(true);
stateRunner.start();
}
@PreDestroy
private void cleanUp () throws Exception
{
System.out.print("\nCleaning up VisualizerServiceTournament (8) : ");
// Shutdown the proxy if needed
if (proxy != null) {
proxy.shutDown();
}
System.out.print("1 ");
// Kill the tick timer
// I have no idea why this loop is needed
while (tickTimer == null) {
try { Thread.sleep(100); } catch (Exception ignored) {}
}
System.out.print("2 ");
tickTimer.cancel();
tickTimer.purge();
tickTimer = null;
System.out.print("3 ");
if (stateTask != null) {
stateTask.cancel();
}
System.out.print("4 ");
// Kill the message pump
try {
messageFeeder.interrupt();
messageFeeder.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("5 ");
// Kill the state machine from within
putEvent(Event.quit);
while (runningStates) {
try { Thread.sleep(100); } catch (Exception ignored) {}
if (currentState == loginWait && stateRunner != null &&
stateRunner.getState() == Thread.State.TIMED_WAITING) {
stateRunner.interrupt();
}
}
System.out.print("6 ");
try {
stateRunner.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("7 ");
Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);
for (Thread t: threadArray) {
if (t.getName().contains("Timer-") || t.getName().contains("ActiveMQ")) {
synchronized(t) {
t.stop();
}
}
}
System.out.println("8\n");
}
// convience functions for handling the event queue
private void putEvent (Event event)
{
try {
eventQueue.put(event);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
private Event getEvent ()
{
try {
return eventQueue.take();
}
catch (InterruptedException e) {
e.printStackTrace();
return Event.tick; // default event, harmless enough
}
}
private void setCurrentState (VisualizerState newState)
{
currentState = newState;
newState.entry();
}
// Run the viz state machine -- called from timer thread.
private Runnable runStates = new Runnable()
{
@Override
public void run ()
{
runningStates = true;
initial = new VisualizerState()
{
@Override
public void entry ()
{
log.info("state initial");
if (null != proxy) {
shutDown();
}
setCurrentState(loginWait);
}
@Override
public void handleEvent (Event event)
{
if (event == Event.tick) {
// safety valve
setCurrentState(loginWait);
}
}
};
loginWait = new VisualizerState()
{
@Override
public void entry ()
{
log.info("state loginWait");
tournamentLogin();
}
@Override
public void handleEvent (Event event)
{
if (event == Event.noTm) {
setCurrentState(gameWait);
} else if (event == Event.accept) {
setCurrentState(gameReady);
} else if (event == Event.tick) {
tournamentLogin();
}
}
};
gameWait = new VisualizerState()
{
@Override
public void entry ()
{
log.info("state gameWait");
gameLogin();
}
@Override
public void handleEvent (Event event)
{
if (event == Event.vsr) {
setCurrentState(loggedIn);
} else if (event == Event.tick) {
pingServer(); // try again
}
}
};
gameReady = new VisualizerState()
{
@Override
public void entry ()
{
log.info("state gameReady");
gameReadyAt = new Date().getTime();
gameLogin();
}
@Override
public void handleEvent (Event event)
{
if (event == Event.vsr) {
setCurrentState(loggedIn);
} else if (event == Event.tick) {
long now = new Date().getTime();
// limit harrassment of running game
if (now > (gameReadyAt + maxGameReadyInterval)) {
setCurrentState(initial);
} else {
pingServer(); // try again
}
}
}
};
loggedIn = new VisualizerState()
{
@Override
public void entry ()
{
log.info("state loggedIn");
}
@Override
public void handleEvent (Event event)
{
if (event == Event.simEnd) {
setCurrentState(initial);
} else if (event == Event.tick && isInactive()) {
setCurrentState(initial);
}
}
};
setCurrentState(initial);
while (runningStates) {
Event event = getEvent();
if (event == Event.quit) {
runningStates = false;
break;
}
currentState.handleEvent(event);
}
}
};
// Logs into the tournament manager to get the queue name for the
// upcoming session
private void tournamentLogin ()
{
//log.info("Tournament URL='" + tournamentUrl + "'");
if (tournamentUrl.isEmpty()) {
// No TM, just connect to server
putEvent(Event.noTm);
return;
}
String urlString = tournamentUrl + visualizerLoginContext +
"?machineName=" + machineName;
log.info("tourney url=" + urlString);
URL url;
try {
url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream input = conn.getInputStream();
log.info("Parsing message..");
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
.newInstance();
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
Document doc = docBuilder.parse(input);
doc.getDocumentElement().normalize();
// Two different message types
Node retryNode = doc.getElementsByTagName("retry").item(0);
Node loginNode = doc.getElementsByTagName("login").item(0);
if (retryNode != null) {
String checkRetry = retryNode.getFirstChild()
.getNodeValue();
log.info("Retry in " + checkRetry + " seconds");
// Received retry message; spin and try again
try {
Thread.sleep(Integer.parseInt(checkRetry) * 1000);
} catch (InterruptedException e) {
//e.printStackTrace();
}
} else if (loginNode != null) {
log.info("Login response received! ");
queueName = doc.getElementsByTagName("queueName")
.item(0).getFirstChild().getNodeValue();
serverQueue = doc.getElementsByTagName("serverQueue")
.item(0).getFirstChild().getNodeValue();
log.info(String.format(
"Login message receieved: queueName=%s, serverQueue=%s",
queueName, serverQueue));
// TODO Better comment
// We have to wait, as the server sends out a 'game_ready' before it's actually ready
try { Thread.sleep(1000); } catch (Exception ignored) {}
putEvent(Event.accept);
} else {
// this is not working
log.info("Invalid response from TS");
}
} catch (Exception e) {
// should we have an event here?
e.printStackTrace();
}
}
// Attempt to log into a game.
private void gameLogin ()
{
if (null == proxy) {
// no proxy yet for this game
proxy = new LocalVisualizerProxy();
proxy.init(this);
}
pingServer();
}
private void pingServer ()
{
log.info("Ping sim server");
proxy.sendMessage(new VisualizerStatusRequest());
}
private boolean isInactive ()
{
long now = new Date().getTime();
long silence = now - lastMsgTime;
if (silence > maxMsgInterval) {
// declare inactivity
log.info("Inactivity declared");
return true;
}
return false;
}
// once-per-game initialization
public void initOnce ()
{
initialized = true;
log.info("initOnce()");
visualizerBean.newRun();
dispatcher.initialize();
// registrations for message listeners:
List<Initializable> initializers =
VisualizerApplicationContext.listBeansOfType(Initializable.class);
for (Initializable init : initializers) {
log.debug("initializing..." + init.getClass().getName());
init.initialize();
}
List<DomainRepo> repos =
VisualizerApplicationContext.listBeansOfType(DomainRepo.class);
for (DomainRepo repo : repos) {
log.debug("recycling..." + repos.getClass().getName());
repo.recycle();
}
}
// shut down the queue at end-of-game, wait a few seconds, go again.
public void shutDown ()
{
// no longer initialized
initialized = false;
log.info("shut down proxy");
proxy.shutDown();
proxy = null; // force re-creation
try {
Thread.sleep(5000); // wait for sim process to quit
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
// ---------------- Message handling ------------------
// Pumps messages from incoming JMS messages into the visualizer in
// a single thread. The queue avoids potential race conditions on
// input.
private Runnable messagePump = new Runnable()
{
@Override
public void run ()
{
while (true) {
Object msg = getMessage();
if (msg instanceof InterruptedException) {
if (tickTimer == null) {
break;
} else {
((InterruptedException) msg).printStackTrace();
}
} else {
receiveMessage(msg);
}
}
}
};
// convience functions for handling the event queue
private void putMessage (Object message)
{
try {
messageQueue.put(message);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
private Object getMessage ()
{
try {
return messageQueue.take();
}
catch (InterruptedException e) {
return e;
}
}
public void receiveMessage (Object msg)
{
// once-per-game initialization...
if (msg instanceof Competition) {
// Competition must be first message. If we see something else first,
// it's an error.
initOnce();
}
else if (!initialized) {
log.info("ERROR: msg of type " + msg.getClass().getName() +
", but not initialized. Ignoring.");
return;
}
visualizerBean.incrementMessageCounter();
if (msg != null) {
//log.debug("Counter: " + visualizerBean.getMessageCount()
// + ", Got message: " + msg.getClass().getName());
//log.info("Counter: " + visualizerBean.getMessageCount()
// + ", Got message: " + msg.getClass().getName());
dispatcher.routeMessage(msg);
}
else {
log.info("Counter:" + visualizerBean.getMessageCount()
+ " Received message is NULL!");
}
// end-of-game check
if (!running && visualizerBean.isRunning()) {
running = true;
}
if (running && visualizerBean.isFinished()) {
log.info("Game finished");
putEvent(Event.simEnd);
}
}
// JMS message input processing
@Override
public void onMessage (Message message)
{
lastMsgTime = new Date().getTime();
//log.info("onMessage");
if (message instanceof TextMessage) {
try {
//log.info("onMessage: text");
onMessage(((TextMessage) message).getText());
} catch (JMSException e) {
log.info("ERROR: viz failed to extract text from TextMessage: " + e.toString());
}
}
}
// runs in JMS thread
private void onMessage (String xml)
{
log.debug("onMessage(String) - received message:\n" + xml);
Object message = converter.fromXML(xml);
log.debug("onMessage(String) - received message of type " + message.getClass().getSimpleName());
if (message instanceof VisualizerStatusRequest) {
log.info("Received vsr");
putEvent(Event.vsr);
}
else if (message instanceof BrokerAccept ||
message instanceof BrokerAuthentication) {
// hack to ignore these
}
else {
putMessage(message);
}
}
@Override
public void afterPropertiesSet () throws Exception
{
Timer initTimer = new Timer(true);
// delay to let deployment complete
initTimer.schedule(new TimerTask () {
@Override
public void run () {
init();
}
}, 20000l);
}
// URL and queue name methods
public String getQueueName ()
{
return queueName;
}
public void setQueueName (String newName)
{
queueName = newName;
}
public String getServerUrl ()
{
return serverUrl;
}
public void setServerUrl (String newUrl)
{
serverUrl = newUrl;
}
public String getTournamentUrl ()
{
return tournamentUrl;
}
public void setTournamentUrl (String newUrl)
{
tournamentUrl = newUrl;
}
public String getVisualizerLoginContext ()
{
return visualizerLoginContext;
}
public void setVisualizerLoginContext (String newContext)
{
visualizerLoginContext = newContext;
}
public String getMachineName ()
{
return machineName;
}
public void setMachineName (String name)
{
machineName = name;
}
// ------------ Local proxy implementation -------------
class LocalVisualizerProxy
{
VisualizerServiceTournament host;
boolean connectionOpen = false;
DefaultMessageListenerContainer container;
// set up the jms queue
void init (VisualizerServiceTournament host)
{
log.info("Server URL: " + getServerUrl() + ", queue: " + getQueueName());
this.host = host;
ActiveMQConnectionFactory amqConnectionFactory = null;
if (connectionFactory instanceof PooledConnectionFactory) {
PooledConnectionFactory pooledConnectionFactory = (PooledConnectionFactory) connectionFactory;
if (pooledConnectionFactory.getConnectionFactory() instanceof ActiveMQConnectionFactory) {
amqConnectionFactory = (ActiveMQConnectionFactory) pooledConnectionFactory
.getConnectionFactory();
}
}
else if (connectionFactory instanceof CachingConnectionFactory) {
CachingConnectionFactory cachingConnectionFactory = (CachingConnectionFactory) connectionFactory;
if (cachingConnectionFactory.getTargetConnectionFactory() instanceof ActiveMQConnectionFactory) {
amqConnectionFactory = (ActiveMQConnectionFactory) cachingConnectionFactory
.getTargetConnectionFactory();
}
}
if (amqConnectionFactory != null) {
amqConnectionFactory.setBrokerURL(getServerUrl());
}
// register host as listener
container = new DefaultMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.setDestinationName(getQueueName());
container.setMessageListener(host);
container.setTaskExecutor(taskExecutor);
container.afterPropertiesSet();
container.start();
connectionOpen = true;
}
public void sendMessage (Object msg)
{
try {
final String text = converter.toXML(msg);
template.send(serverQueue,
new MessageCreator()
{
@Override
public Message createMessage (Session session) throws JMSException
{
TextMessage message = session.createTextMessage(text);
return message;
}
});
} catch (Exception e) {
log.warn("Exception " + e.toString() +
" sending message - ignoring");
}
}
public synchronized void shutDown ()
{
final LocalVisualizerProxy proxy = this;
Runnable callback = new Runnable()
{
@Override
public void run ()
{
proxy.closeConnection();
}
};
container.stop(callback);
while (connectionOpen) {
try {
wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private synchronized void closeConnection ()
{
connectionOpen = false;
notifyAll();
}
}
}
| Removed debug commment + increased delay
| src/main/java/org/powertac/visualizer/services/VisualizerServiceTournament.java | Removed debug commment + increased delay |
|
Java | apache-2.0 | 252a08bdf8148c65b74d86fda3e0fd7357756998 | 0 | ceylon/ceylon-js,ceylon/ceylon-js,ceylon/ceylon-js | package com.redhat.ceylon.compiler.js;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.eliminateParensAndWidening;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.antlr.runtime.CommonToken;
import com.redhat.ceylon.common.Backend;
import com.redhat.ceylon.compiler.js.util.JsIdentifierNames;
import com.redhat.ceylon.compiler.js.util.JsOutput;
import com.redhat.ceylon.compiler.js.util.JsUtils;
import com.redhat.ceylon.compiler.js.util.JsWriter;
import com.redhat.ceylon.compiler.js.util.Options;
import com.redhat.ceylon.compiler.js.util.RetainedVars;
import com.redhat.ceylon.compiler.js.util.TypeUtils;
import com.redhat.ceylon.compiler.js.util.TypeUtils.RuntimeMetamodelAnnotationGenerator;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassAlias;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.Setter;
import com.redhat.ceylon.compiler.typechecker.model.TypeAlias;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.Util;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.*;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.*;
public class GenerateJsVisitor extends Visitor
implements NaturalVisitor {
private final Stack<Continuation> continues = new Stack<>();
private final JsIdentifierNames names;
private final Set<Declaration> directAccess = new HashSet<>();
private final Set<Declaration> generatedAttributes = new HashSet<>();
private final RetainedVars retainedVars = new RetainedVars();
final ConditionGenerator conds;
private final InvocationGenerator invoker;
private final List<CommonToken> tokens;
private final ErrorVisitor errVisitor = new ErrorVisitor();
private int dynblock;
private int exitCode = 0;
static final class SuperVisitor extends Visitor {
private final List<Declaration> decs;
SuperVisitor(List<Declaration> decs) {
this.decs = decs;
}
@Override
public void visit(QualifiedMemberOrTypeExpression qe) {
Term primary = eliminateParensAndWidening(qe.getPrimary());
if (primary instanceof Super) {
decs.add(qe.getDeclaration());
}
super.visit(qe);
}
@Override
public void visit(QualifiedType that) {
if (that.getOuterType() instanceof SuperType) {
decs.add(that.getDeclarationModel());
}
super.visit(that);
}
public void visit(Tree.ClassOrInterface qe) {
//don't recurse
if (qe instanceof ClassDefinition) {
ExtendedType extType = ((ClassDefinition) qe).getExtendedType();
if (extType != null) { super.visit(extType); }
}
}
}
private final class OuterVisitor extends Visitor {
boolean found = false;
private Declaration dec;
private OuterVisitor(Declaration dec) {
this.dec = dec;
}
@Override
public void visit(QualifiedMemberOrTypeExpression qe) {
if (qe.getPrimary() instanceof Outer ||
qe.getPrimary() instanceof This) {
if ( qe.getDeclaration().equals(dec) ) {
found = true;
}
}
super.visit(qe);
}
}
private List<? extends Statement> currentStatements = null;
public final JsWriter out;
private final PrintWriter verboseOut;
public final Options opts;
private CompilationUnit root;
static final String function="function ";
public Package getCurrentPackage() {
return root.getUnit().getPackage();
}
/** Returns the module name for the language module. */
public String getClAlias() { return jsout.getLanguageModuleAlias(); }
@Override
public void handleException(Exception e, Node that) {
that.addUnexpectedError(that.getMessage(e, this));
}
private final JsOutput jsout;
public GenerateJsVisitor(JsOutput out, Options options, JsIdentifierNames names,
List<CommonToken> tokens) throws IOException {
this.jsout = out;
this.opts = options;
if (options.hasVerboseFlag("code")) {
Writer vw = options.getOutWriter();
verboseOut = vw instanceof PrintWriter ? (PrintWriter)vw :
new PrintWriter(vw == null ? new OutputStreamWriter(System.out) : vw);
} else {
verboseOut = null;
}
this.names = names;
conds = new ConditionGenerator(this, names, directAccess);
this.tokens = tokens;
invoker = new InvocationGenerator(this, names, retainedVars);
this.out = new JsWriter(out.getWriter(), verboseOut, opts.isMinify());
out.setJsWriter(this.out);
}
public InvocationGenerator getInvoker() { return invoker; }
/** Returns the helper component to handle naming. */
public JsIdentifierNames getNames() { return names; }
public static interface GenerateCallback {
public void generateValue();
}
/** Print generated code to the Writer specified at creation time.
* Automatically prints indentation first if necessary.
* @param code The main code
* @param codez Optional additional strings to print after the main code. */
public void out(String code, String... codez) {
out.write(code, codez);
}
/** Prints a newline. Indentation will automatically be printed by {@link #out(String, String...)}
* when the next line is started. */
void endLine() {
out.endLine(false);
}
/** Prints a newline. Indentation will automatically be printed by {@link #out(String, String...)}
* when the next line is started.
* @param semicolon if <code>true</code> then a semicolon is printed at the end
* of the previous line*/
public void endLine(boolean semicolon) {
out.endLine(semicolon);
}
/** Calls {@link #endLine()} if the current position is not already the beginning
* of a line. */
void beginNewLine() {
out.beginNewLine();
}
/** Increases indentation level, prints opening brace and newline. Indentation will
* automatically be printed by {@link #out(String, String...)} when the next line is started. */
void beginBlock() {
out.beginBlock();
}
/** Decreases indentation level, prints a closing brace in new line (using
* {@link #beginNewLine()}) and calls {@link #endLine()}. */
void endBlockNewLine() {
out.endBlock(false, true);
}
/** Decreases indentation level, prints a closing brace in new line (using
* {@link #beginNewLine()}) and calls {@link #endLine()}.
* @param semicolon if <code>true</code> then prints a semicolon after the brace*/
void endBlockNewLine(boolean semicolon) {
out.endBlock(semicolon, true);
}
/** Decreases indentation level and prints a closing brace in new line (using
* {@link #beginNewLine()}). */
void endBlock() {
out.endBlock(false, false);
}
/** Decreases indentation level and prints a closing brace in new line (using
* {@link #beginNewLine()}).
* @param semicolon if <code>true</code> then prints a semicolon after the brace
* @param newline if <code>true</code> then additionally calls {@link #endLine()} */
void endBlock(boolean semicolon, boolean newline) {
out.endBlock(semicolon, newline);
}
void spitOut(String s) {
out.spitOut(s);
}
/** Prints source code location in the form "at [filename] ([location])" */
public void location(Node node) {
out(" at ", node.getUnit().getFilename(), " (", node.getLocation(), ")");
}
private String generateToString(final GenerateCallback callback) {
return out.generateToString(callback);
}
@Override
public void visit(final Tree.CompilationUnit that) {
root = that;
if (!that.getModuleDescriptors().isEmpty()) {
ModuleDescriptor md = that.getModuleDescriptors().get(0);
out("ex$.$mod$ans$=");
TypeUtils.outputAnnotationsFunction(md.getAnnotationList(), null, this);
endLine(true);
if (md.getImportModuleList() != null && !md.getImportModuleList().getImportModules().isEmpty()) {
out("ex$.$mod$imps=function(){return{");
if (!opts.isMinify())endLine();
boolean first=true;
for (ImportModule im : md.getImportModuleList().getImportModules()) {
final StringBuilder path=new StringBuilder("'");
if (im.getImportPath()==null) {
if (im.getQuotedLiteral()==null) {
throw new CompilerErrorException("Invalid imported module");
} else {
final String ql = im.getQuotedLiteral().getText();
path.append(ql.substring(1, ql.length()-1));
}
} else {
for (Identifier id : im.getImportPath().getIdentifiers()) {
if (path.length()>1)path.append('.');
path.append(id.getText());
}
}
final String qv = im.getVersion().getText();
path.append('/').append(qv.substring(1, qv.length()-1)).append("'");
if (first)first=false;else{out(",");endLine();}
out(path.toString(), ":");
TypeUtils.outputAnnotationsFunction(im.getAnnotationList(), null, this);
}
if (!opts.isMinify())endLine();
out("};};");
if (!opts.isMinify())endLine();
}
}
if (!that.getPackageDescriptors().isEmpty()) {
final String pknm = that.getUnit().getPackage().getNameAsString().replaceAll("\\.", "\\$");
out("ex$.$pkg$ans$", pknm, "=");
TypeUtils.outputAnnotationsFunction(that.getPackageDescriptors().get(0).getAnnotationList(), null, this);
endLine(true);
}
for (CompilerAnnotation ca: that.getCompilerAnnotations()) {
ca.visit(this);
}
if (that.getImportList() != null) {
that.getImportList().visit(this);
}
visitStatements(that.getDeclarations());
}
public void visit(final Tree.Import that) {
}
@Override
public void visit(final Tree.Parameter that) {
out(names.name(that.getParameterModel()));
}
@Override
public void visit(final Tree.ParameterList that) {
out("(");
boolean first=true;
boolean ptypes = false;
//Check if this is the first parameter list
if (that.getScope() instanceof Method && that.getModel().isFirst()) {
ptypes = ((Method)that.getScope()).getTypeParameters() != null &&
!((Method)that.getScope()).getTypeParameters().isEmpty();
}
for (Parameter param: that.getParameters()) {
if (!first) out(",");
out(names.name(param.getParameterModel()));
first = false;
}
if (ptypes) {
if (!first) out(",");
out("$$$mptypes");
}
out(")");
}
void visitStatements(List<? extends Statement> statements) {
List<String> oldRetainedVars = retainedVars.reset(null);
final List<? extends Statement> prevStatements = currentStatements;
currentStatements = statements;
for (int i=0; i<statements.size(); i++) {
Statement s = statements.get(i);
s.visit(this);
if (!opts.isMinify())beginNewLine();
retainedVars.emitRetainedVars(this);
}
retainedVars.reset(oldRetainedVars);
currentStatements = prevStatements;
}
@Override
public void visit(final Tree.Body that) {
visitStatements(that.getStatements());
}
@Override
public void visit(final Tree.Block that) {
List<Statement> stmnts = that.getStatements();
if (stmnts.isEmpty()) {
out("{}");
}
else {
beginBlock();
visitStatements(stmnts);
endBlock();
}
}
void initSelf(Node node) {
final NeedsThisVisitor ntv = new NeedsThisVisitor(node);
if (ntv.needsThisReference()) {
final String me=names.self(prototypeOwner);
out("var ", me, "=this");
//Code inside anonymous inner types sometimes gens direct refs to the outer instance
//We can detect if that's going to happen and declare the ref right here
if (ntv.needsOuterReference()) {
final Declaration od = Util.getContainingDeclaration(prototypeOwner);
if (od instanceof TypeDeclaration) {
out(",", names.self((TypeDeclaration)od), "=", me, ".outer$");
}
}
endLine(true);
}
}
/** Visitor that determines if a method definition will need the "this" reference. */
class NeedsThisVisitor extends Visitor {
private boolean refs=false;
private boolean outerRefs=false;
NeedsThisVisitor(Node n) {
if (prototypeOwner != null) {
n.visit(this);
}
}
@Override public void visit(Tree.This that) {
refs = true;
}
@Override public void visit(Tree.Outer that) {
refs = true;
}
@Override public void visit(Tree.Super that) {
refs = true;
}
private boolean check(final Scope origScope) {
Scope s = origScope;
while (s != null) {
if (s == prototypeOwner || (s instanceof TypeDeclaration && prototypeOwner.inherits((TypeDeclaration)s))) {
refs = true;
if (prototypeOwner.isAnonymous() && prototypeOwner.isMember()) {
outerRefs=true;
}
return true;
}
s = s.getContainer();
}
//Check the other way around as well
s = prototypeOwner;
while (s != null) {
if (s == origScope ||
(s instanceof TypeDeclaration && origScope instanceof TypeDeclaration
&& ((TypeDeclaration)s).inherits((TypeDeclaration)origScope))) {
refs = true;
return true;
}
s = s.getContainer();
}
return false;
}
public void visit(Tree.MemberOrTypeExpression that) {
if (refs)return;
if (that.getDeclaration() == null) {
//Some expressions in dynamic blocks can have null declarations
super.visit(that);
return;
}
if (!check(that.getDeclaration().getContainer())) {
super.visit(that);
}
}
public void visit(Tree.Type that) {
if (!check(that.getTypeModel().getDeclaration())) {
super.visit(that);
}
}
public void visit(Tree.ParameterList plist) {
for (Tree.Parameter param : plist.getParameters()) {
if (param.getParameterModel().isDefaulted()) {
refs = true;
return;
}
}
super.visit(plist);
}
boolean needsThisReference() {
return refs;
}
boolean needsOuterReference() {
return outerRefs;
}
}
void comment(Tree.Declaration that) {
if (!opts.isComment() || opts.isMinify()) return;
endLine();
String dname = that.getNodeType();
if (dname.endsWith("Declaration") || dname.endsWith("Definition")) {
dname = dname.substring(0, dname.length()-7);
}
if (that instanceof Tree.Constructor) {
String cname = ((com.redhat.ceylon.compiler.typechecker.model.Class)((Tree.Constructor)that)
.getDeclarationModel().getContainer()).getName();
out("//Constructor ", cname, ".",
that.getDeclarationModel().getName() == null ? cname : that.getDeclarationModel().getName());
} else {
out("//", dname, " ", that.getDeclarationModel().getName());
}
location(that);
endLine();
}
boolean share(Declaration d) {
return share(d, true);
}
private boolean share(Declaration d, boolean excludeProtoMembers) {
boolean shared = false;
if (!(excludeProtoMembers && opts.isOptimize() && d.isClassOrInterfaceMember())
&& isCaptured(d)) {
beginNewLine();
outerSelf(d);
String dname=names.name(d);
if (dname.endsWith("()")){
dname = dname.substring(0, dname.length()-2);
}
out(".", dname, "=", dname);
endLine(true);
shared = true;
}
return shared;
}
@Override
public void visit(final Tree.ClassDeclaration that) {
if (opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember()) return;
classDeclaration(that);
}
private void addClassDeclarationToPrototype(TypeDeclaration outer, final Tree.ClassDeclaration that) {
classDeclaration(that);
final String tname = names.name(that.getDeclarationModel());
out(names.self(outer), ".", tname, "=", tname);
endLine(true);
}
private void addAliasDeclarationToPrototype(TypeDeclaration outer, Tree.TypeAliasDeclaration that) {
comment(that);
final TypeAlias d = that.getDeclarationModel();
String path = qualifiedPath(that, d, true);
if (path.length() > 0) {
path += '.';
}
String tname = names.name(d);
tname = tname.substring(0, tname.length()-2);
String _tmp=names.createTempVariable();
out(names.self(outer), ".", tname, "=function(){var ");
ProducedType pt = that.getTypeSpecifier().getType().getTypeModel();
boolean skip=true;
if (pt.containsTypeParameters() && outerSelf(d)) {
out("=this,");
skip=false;
}
out(_tmp, "=");
TypeUtils.typeNameOrList(that, pt, this, skip);
out(";", _tmp, ".$crtmm$=");
TypeUtils.encodeForRuntime(that,d,this);
out(";return ", _tmp, ";}");
endLine(true);
}
@Override
public void visit(final Tree.InterfaceDeclaration that) {
if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) {
interfaceDeclaration(that);
}
}
private void addInterfaceDeclarationToPrototype(TypeDeclaration outer, final Tree.InterfaceDeclaration that) {
interfaceDeclaration(that);
final String tname = names.name(that.getDeclarationModel());
out(names.self(outer), ".", tname, "=", tname);
endLine(true);
}
private void addInterfaceToPrototype(ClassOrInterface type, final Tree.InterfaceDefinition interfaceDef) {
if (type.isDynamic())return;
TypeGenerator.interfaceDefinition(interfaceDef, this);
Interface d = interfaceDef.getDeclarationModel();
out(names.self(type), ".", names.name(d), "=", names.name(d));
endLine(true);
}
@Override
public void visit(final Tree.InterfaceDefinition that) {
if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) {
TypeGenerator.interfaceDefinition(that, this);
}
}
private void addClassToPrototype(ClassOrInterface type, final Tree.ClassDefinition classDef) {
if (type.isDynamic())return;
TypeGenerator.classDefinition(classDef, this);
final String tname = names.name(classDef.getDeclarationModel());
out(names.self(type), ".", tname, "=", tname);
endLine(true);
}
@Override
public void visit(final Tree.ClassDefinition that) {
if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember()) && isForBackend(that)) {
TypeGenerator.classDefinition(that, this);
}
}
private void interfaceDeclaration(final Tree.InterfaceDeclaration that) {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(that))return;
comment(that);
final Interface d = that.getDeclarationModel();
final String aname = names.name(d);
Tree.StaticType ext = that.getTypeSpecifier().getType();
out(function, aname, "(");
if (d.getTypeParameters() != null && !d.getTypeParameters().isEmpty()) {
out("$$targs$$,");
}
out(names.self(d), "){");
final ProducedType pt = ext.getTypeModel();
final TypeDeclaration aliased = pt.getDeclaration();
qualify(that,aliased);
out(names.name(aliased), "(");
if (!pt.getTypeArguments().isEmpty()) {
TypeUtils.printTypeArguments(that, pt.getTypeArguments(), this, true,
pt.getVarianceOverrides());
out(",");
}
out(names.self(d), ");}");
endLine();
out(aname,".$crtmm$=");
TypeUtils.encodeForRuntime(that, d, this);
endLine(true);
share(d);
}
private void classDeclaration(final Tree.ClassDeclaration that) {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(that))return;
comment(that);
final Class d = that.getDeclarationModel();
final String aname = names.name(d);
final Tree.ClassSpecifier ext = that.getClassSpecifier();
out(function, aname, "(");
//Generate each parameter because we need to append one at the end
for (Parameter p: that.getParameterList().getParameters()) {
p.visit(this);
out(", ");
}
if (d.getTypeParameters() != null && !d.getTypeParameters().isEmpty()) {
out("$$targs$$,");
}
out(names.self(d), "){return ");
TypeDeclaration aliased = ext.getType().getDeclarationModel();
qualify(that, aliased);
out(names.name(aliased), "(");
if (ext.getInvocationExpression().getPositionalArgumentList() != null) {
ext.getInvocationExpression().getPositionalArgumentList().visit(this);
if (!ext.getInvocationExpression().getPositionalArgumentList().getPositionalArguments().isEmpty()) {
out(",");
}
} else {
out("/*PENDIENTE NAMED ARG CLASS DECL */");
}
Map<TypeParameter, ProducedType> invargs = ext.getType().getTypeModel().getTypeArguments();
if (invargs != null && !invargs.isEmpty()) {
TypeUtils.printTypeArguments(that, invargs, this, true,
ext.getType().getTypeModel().getVarianceOverrides());
out(",");
}
out(names.self(d), ");}");
endLine();
out(aname, ".$$=");
qualify(that, aliased);
out(names.name(aliased), ".$$");
endLine(true);
out(aname,".$crtmm$=");
TypeUtils.encodeForRuntime(that, d, this);
endLine(true);
share(d);
}
@Override
public void visit(final Tree.TypeAliasDeclaration that) {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(that))return;
final TypeAlias d = that.getDeclarationModel();
if (opts.isOptimize() && d.isClassOrInterfaceMember()) return;
comment(that);
final String tname=names.createTempVariable();
out(function, names.name(d), "{var ", tname, "=");
TypeUtils.typeNameOrList(that, that.getTypeSpecifier().getType().getTypeModel(), this, false);
out(";", tname, ".$crtmm$=");
TypeUtils.encodeForRuntime(that, d, this, new RuntimeMetamodelAnnotationGenerator() {
@Override public void generateAnnotations() {
TypeUtils.outputAnnotationsFunction(that.getAnnotationList(), d, GenerateJsVisitor.this);
}
});
out(";return ", tname, ";}");
endLine();
share(d);
}
void referenceOuter(TypeDeclaration d) {
if (!d.isToplevel()) {
final ClassOrInterface coi = Util.getContainingClassOrInterface(d.getContainer());
if (coi != null) {
out(names.self(d), ".outer$");
if (d.isClassOrInterfaceMember()) {
out("=this");
} else {
out("=", names.self(coi));
}
endLine(true);
}
}
}
/** Returns the name of the type or its $init$ function if it's local. */
String typeFunctionName(final Tree.StaticType type, boolean removeAlias) {
TypeDeclaration d = type.getTypeModel().getDeclaration();
if ((removeAlias && d.isAlias()) || d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) {
d = d.getExtendedTypeDeclaration();
}
boolean inProto = opts.isOptimize()
&& (type.getScope().getContainer() instanceof TypeDeclaration);
String tfn = memberAccessBase(type, d, false, qualifiedPath(type, d, inProto));
if (removeAlias && !isImported(type.getUnit().getPackage(), d)) {
int idx = tfn.lastIndexOf('.');
if (idx > 0) {
tfn = tfn.substring(0, idx+1) + "$init$" + tfn.substring(idx+1) + "()";
} else {
tfn = "$init$" + tfn + "()";
}
}
return tfn;
}
void addToPrototype(Node node, ClassOrInterface d, List<Tree.Statement> statements) {
final boolean isSerial = d instanceof com.redhat.ceylon.compiler.typechecker.model.Class
&& ((com.redhat.ceylon.compiler.typechecker.model.Class)d).isSerializable();
boolean enter = opts.isOptimize();
ArrayList<com.redhat.ceylon.compiler.typechecker.model.Parameter> plist = null;
if (enter) {
enter = !statements.isEmpty();
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
com.redhat.ceylon.compiler.typechecker.model.ParameterList _pl =
((com.redhat.ceylon.compiler.typechecker.model.Class)d).getParameterList();
if (_pl != null) {
plist = new ArrayList<>(_pl.getParameters().size());
plist.addAll(_pl.getParameters());
enter |= !plist.isEmpty();
}
}
}
if (enter || isSerial) {
final List<? extends Statement> prevStatements = currentStatements;
currentStatements = statements;
out("(function(", names.self(d), ")");
beginBlock();
if (enter) {
//Generated attributes with corresponding parameters will remove them from the list
if (plist != null) {
for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : plist) {
generateAttributeForParameter(node, (com.redhat.ceylon.compiler.typechecker.model.Class)d, p);
}
}
for (Statement s: statements) {
if (s instanceof Tree.ClassOrInterface == false && !(s instanceof Tree.AttributeDeclaration &&
((Tree.AttributeDeclaration)s).getDeclarationModel().isParameter())) {
addToPrototype(d, s, plist);
}
}
for (Statement s: statements) {
if (s instanceof Tree.ClassOrInterface) {
addToPrototype(d, s, plist);
}
}
if (d.isMember()) {
ClassOrInterface coi = Util.getContainingClassOrInterface(d.getContainer());
if (coi != null && d.inherits(coi)) {
out(names.self(d), ".", names.name(d),"=", names.name(d), ";");
}
}
}
if (isSerial) {
SerializationHelper.addSerializer(node, (com.redhat.ceylon.compiler.typechecker.model.Class)d, this);
}
endBlock();
out(")(", names.name(d), ".$$.prototype)");
endLine(true);
currentStatements = prevStatements;
}
}
void generateAttributeForParameter(Node node, com.redhat.ceylon.compiler.typechecker.model.Class d,
com.redhat.ceylon.compiler.typechecker.model.Parameter p) {
final String privname = names.name(p) + "_";
final MethodOrValue pdec = p.getModel();
defineAttribute(names.self(d), names.name(pdec));
out("{");
if (pdec.isLate()) {
generateUnitializedAttributeReadCheck("this."+privname, names.name(p));
}
out("return this.", privname, ";}");
if (pdec.isVariable() || pdec.isLate()) {
final String param = names.createTempVariable();
out(",function(", param, "){");
//Because of this one case, we need to pass 3 args to this method
generateImmutableAttributeReassignmentCheck(pdec, "this."+privname, names.name(p));
out("return this.", privname,
"=", param, ";}");
} else {
out(",undefined");
}
out(",");
TypeUtils.encodeForRuntime(node, pdec, this);
out(")");
endLine(true);
}
private ClassOrInterface prototypeOwner;
private void addToPrototype(ClassOrInterface d, final Tree.Statement s,
List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params) {
ClassOrInterface oldPrototypeOwner = prototypeOwner;
prototypeOwner = d;
if (s instanceof MethodDefinition) {
addMethodToPrototype(d, (MethodDefinition)s);
} else if (s instanceof MethodDeclaration) {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(s))return;
FunctionHelper.methodDeclaration(d, (MethodDeclaration) s, this);
} else if (s instanceof AttributeGetterDefinition) {
addGetterToPrototype(d, (AttributeGetterDefinition)s);
} else if (s instanceof AttributeDeclaration) {
AttributeGenerator.addGetterAndSetterToPrototype(d, (AttributeDeclaration) s, this);
} else if (s instanceof ClassDefinition) {
addClassToPrototype(d, (ClassDefinition) s);
} else if (s instanceof InterfaceDefinition) {
addInterfaceToPrototype(d, (InterfaceDefinition) s);
} else if (s instanceof ObjectDefinition) {
addObjectToPrototype(d, (ObjectDefinition) s);
} else if (s instanceof ClassDeclaration) {
addClassDeclarationToPrototype(d, (ClassDeclaration) s);
} else if (s instanceof InterfaceDeclaration) {
addInterfaceDeclarationToPrototype(d, (InterfaceDeclaration) s);
} else if (s instanceof SpecifierStatement) {
addSpecifierToPrototype(d, (SpecifierStatement) s);
} else if (s instanceof TypeAliasDeclaration) {
addAliasDeclarationToPrototype(d, (TypeAliasDeclaration)s);
}
//This fixes #231 for prototype style
if (params != null && s instanceof Tree.Declaration) {
Declaration m = ((Tree.Declaration)s).getDeclarationModel();
for (Iterator<com.redhat.ceylon.compiler.typechecker.model.Parameter> iter = params.iterator();
iter.hasNext();) {
com.redhat.ceylon.compiler.typechecker.model.Parameter _p = iter.next();
if (m.getName() != null && m.getName().equals(_p.getName())) {
iter.remove();
break;
}
}
}
prototypeOwner = oldPrototypeOwner;
}
void declareSelf(ClassOrInterface d) {
out("if(", names.self(d), "===undefined)");
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class && d.isAbstract()) {
out(getClAlias(), "throwexc(", getClAlias(), "InvocationException$meta$model(");
out("\"Cannot instantiate abstract class ", d.getQualifiedNameString(), "\"),'?','?')");
} else {
out(names.self(d), "=new ");
if (opts.isOptimize() && d.isClassOrInterfaceMember()) {
out("this.");
}
out(names.name(d), ".$$;");
}
endLine();
}
void instantiateSelf(ClassOrInterface d) {
out("var ", names.self(d), "=new ");
if (opts.isOptimize() && d.isClassOrInterfaceMember()) {
out("this.");
}
out(names.name(d), ".$$;");
}
private void addObjectToPrototype(ClassOrInterface type, final Tree.ObjectDefinition objDef) {
TypeGenerator.objectDefinition(objDef, this);
Value d = objDef.getDeclarationModel();
Class c = (Class) d.getTypeDeclaration();
out(names.self(type), ".", names.name(c), "=", names.name(c), ";",
names.self(type), ".", names.name(c), ".$crtmm$=");
TypeUtils.encodeForRuntime(objDef, d, this);
endLine(true);
}
@Override
public void visit(final Tree.ObjectDefinition that) {
if (errVisitor.hasErrors(that))return;
Value d = that.getDeclarationModel();
if (!(opts.isOptimize() && d.isClassOrInterfaceMember())) {
TypeGenerator.objectDefinition(that, this);
} else {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(that))return;
Class c = (Class) d.getTypeDeclaration();
comment(that);
outerSelf(d);
out(".", names.privateName(d), "=");
outerSelf(d);
out(".", names.name(c), "()");
endLine(true);
}
}
@Override
public void visit(final Tree.ObjectExpression that) {
if (errVisitor.hasErrors(that))return;
out("function(){");
try {
TypeGenerator.defineObject(that, null, that.getSatisfiedTypes(),
that.getExtendedType(), that.getClassBody(), null, this);
} catch (Exception e) {
e.printStackTrace();
}
out("}()");
}
@Override
public void visit(final Tree.MethodDeclaration that) {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(that))return;
FunctionHelper.methodDeclaration(null, that, this);
}
boolean shouldStitch(Declaration d) {
return JsCompiler.isCompilingLanguageModule() && d.isNative();
}
private File getStitchedFilename(final Declaration d, final String suffix) {
String fqn = d.getQualifiedNameString();
if (d.getName() == null && d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) {
String cname = ((com.redhat.ceylon.compiler.typechecker.model.Constructor)d).getExtendedTypeDeclaration().getName();
fqn = fqn.substring(0, fqn.length()-4) + cname;
}
if (fqn.startsWith("ceylon.language"))fqn = fqn.substring(15);
if (fqn.startsWith("::"))fqn=fqn.substring(2);
fqn = fqn.replace('.', '/').replace("::", "/");
return new File(Stitcher.LANGMOD_JS_SRC, fqn + suffix);
}
/** Reads a file with hand-written snippet and outputs it to the current writer. */
boolean stitchNative(final Declaration d, final Tree.Declaration n) {
final File f = getStitchedFilename(d, ".js");
if (f.exists() && f.canRead()) {
jsout.outputFile(f);
if (d.isClassOrInterfaceMember()) {
if (d instanceof Value || n instanceof Tree.Constructor) {
//Native values are defined as attributes
//Constructor metamodel is done in TypeGenerator.classConstructor
return true;
}
out(names.self((TypeDeclaration)d.getContainer()), ".");
}
out(names.name(d), ".$crtmm$=");
TypeUtils.encodeForRuntime(d, n.getAnnotationList(), this);
endLine(true);
return true;
} else {
if (!(d instanceof ClassOrInterface || n instanceof Tree.MethodDefinition)) {
final String err = "REQUIRED NATIVE FILE MISSING FOR "
+ d.getQualifiedNameString() + " => " + f + ", containing " + names.name(d) + ": " + f;
spitOut(err);
out("/*", err, "*/");
}
return false;
}
}
/** Stitch a snippet of code to initialize type (usually a call to initTypeProto). */
boolean stitchInitializer(TypeDeclaration d) {
final File f = getStitchedFilename(d, "$init.js");
if (f.exists() && f.canRead()) {
jsout.outputFile(f);
return true;
}
return false;
}
boolean stitchConstructorHelper(final Tree.ClassOrInterface coi, final String partName) {
final File f;
if (JsCompiler.isCompilingLanguageModule()) {
f = getStitchedFilename(coi.getDeclarationModel(), partName + ".js");
} else {
f = new File(new File(coi.getUnit().getFullPath()).getParentFile(),
String.format("%s%s.js", names.name(coi.getDeclarationModel()), partName));
}
if (f.exists() && f.isFile() && f.canRead()) {
if (verboseOut != null || JsCompiler.isCompilingLanguageModule()) {
spitOut("Stitching in " + f + ". It must contain an anonymous function "
+ "which will be invoked with the same arguments as the "
+ names.name(coi.getDeclarationModel()) + " constructor.");
}
out("(");
jsout.outputFile(f);
out(")");
TypeGenerator.generateParameters(coi.getTypeParameterList(), coi instanceof Tree.ClassDefinition ?
((Tree.ClassDefinition)coi).getParameterList() : null, coi.getDeclarationModel(), this);
endLine(true);
}
return false;
}
@Override
public void visit(final Tree.MethodDefinition that) {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(that) || !isForBackend(that))return;
final Method d = that.getDeclarationModel();
if (!((opts.isOptimize() && d.isClassOrInterfaceMember()) || isNative(d))) {
comment(that);
initDefaultedParameters(that.getParameterLists().get(0), d);
FunctionHelper.methodDefinition(that, this, true);
//Add reference to metamodel
out(names.name(d), ".$crtmm$=");
TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this);
endLine(true);
}
}
/** Get the specifier expression for a Parameter, if one is available. */
private SpecifierOrInitializerExpression getDefaultExpression(final Tree.Parameter param) {
final SpecifierOrInitializerExpression expr;
if (param instanceof ParameterDeclaration || param instanceof InitializerParameter) {
MethodDeclaration md = null;
if (param instanceof ParameterDeclaration) {
TypedDeclaration td = ((ParameterDeclaration) param).getTypedDeclaration();
if (td instanceof AttributeDeclaration) {
expr = ((AttributeDeclaration) td).getSpecifierOrInitializerExpression();
} else if (td instanceof MethodDeclaration) {
md = (MethodDeclaration)td;
expr = md.getSpecifierExpression();
} else {
param.addUnexpectedError("Don't know what to do with TypedDeclaration " + td.getClass().getName());
expr = null;
}
} else {
expr = ((InitializerParameter) param).getSpecifierExpression();
}
} else {
param.addUnexpectedError("Don't know what to do with defaulted/sequenced param " + param);
expr = null;
}
return expr;
}
/** Create special functions with the expressions for defaulted parameters in a parameter list. */
void initDefaultedParameters(final Tree.ParameterList params, Method container) {
if (!container.isMember())return;
for (final Parameter param : params.getParameters()) {
com.redhat.ceylon.compiler.typechecker.model.Parameter pd = param.getParameterModel();
if (pd.isDefaulted()) {
final SpecifierOrInitializerExpression expr = getDefaultExpression(param);
if (expr == null) {
continue;
}
qualify(params, container);
out(names.name(container), "$defs$", pd.getName(), "=function");
params.visit(this);
out("{");
initSelf(expr);
out("return ");
if (param instanceof ParameterDeclaration &&
((ParameterDeclaration)param).getTypedDeclaration() instanceof MethodDeclaration) {
// function parameter defaulted using "=>"
FunctionHelper.singleExprFunction(
((MethodDeclaration)((ParameterDeclaration)param).getTypedDeclaration()).getParameterLists(),
expr.getExpression(), null, true, true, this);
} else if (!isNaturalLiteral(expr.getExpression().getTerm())) {
expr.visit(this);
}
out(";}");
endLine(true);
}
}
}
/** Initialize the sequenced, defaulted and captured parameters in a type declaration. */
void initParameters(final Tree.ParameterList params, TypeDeclaration typeDecl, Method m) {
for (final Parameter param : params.getParameters()) {
com.redhat.ceylon.compiler.typechecker.model.Parameter pd = param.getParameterModel();
final String paramName = names.name(pd);
if (pd.isDefaulted() || pd.isSequenced()) {
out("if(", paramName, "===undefined){", paramName, "=");
if (pd.isDefaulted()) {
if (m !=null && m.isMember()) {
qualify(params, m);
out(names.name(m), "$defs$", pd.getName(), "(");
boolean firstParam=true;
for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : m.getParameterLists().get(0).getParameters()) {
if (firstParam){firstParam=false;}else out(",");
out(names.name(p));
}
out(")");
} else {
final SpecifierOrInitializerExpression expr = getDefaultExpression(param);
if (expr == null) {
param.addUnexpectedError("Default expression missing for " + pd.getName());
out("null");
} else if (param instanceof ParameterDeclaration &&
((ParameterDeclaration)param).getTypedDeclaration() instanceof MethodDeclaration) {
// function parameter defaulted using "=>"
FunctionHelper.singleExprFunction(
((MethodDeclaration)((ParameterDeclaration)param).getTypedDeclaration()).getParameterLists(),
expr.getExpression(), m, true, true, this);
} else {
expr.visit(this);
}
}
} else {
out(getClAlias(), "empty()");
}
out(";}");
endLine();
}
if ((typeDecl != null) && (pd.getModel().isCaptured() ||
pd.getDeclaration() instanceof com.redhat.ceylon.compiler.typechecker.model.Class)) {
out(names.self(typeDecl), ".", paramName, "_=", paramName);
if (!opts.isOptimize() && pd.isHidden()) { //belt and suspenders...
out(";", names.self(typeDecl), ".", paramName, "=", paramName);
}
endLine(true);
}
}
}
private void addMethodToPrototype(TypeDeclaration outer,
final Tree.MethodDefinition that) {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(that))return;
Method d = that.getDeclarationModel();
if (!opts.isOptimize()||!d.isClassOrInterfaceMember()) return;
comment(that);
initDefaultedParameters(that.getParameterLists().get(0), d);
out(names.self(outer), ".", names.name(d), "=");
FunctionHelper.methodDefinition(that, this, false);
//Add reference to metamodel
out(names.self(outer), ".", names.name(d), ".$crtmm$=");
TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this);
endLine(true);
}
@Override
public void visit(final Tree.AttributeGetterDefinition that) {
if (errVisitor.hasErrors(that))return;
Value d = that.getDeclarationModel();
if (opts.isOptimize()&&d.isClassOrInterfaceMember()) return;
comment(that);
if (defineAsProperty(d)) {
defineAttribute(names.self((TypeDeclaration)d.getContainer()), names.name(d));
AttributeGenerator.getter(that, this);
final AttributeSetterDefinition setterDef = associatedSetterDefinition(d);
if (setterDef == null) {
out(",undefined");
} else {
out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")");
AttributeGenerator.setter(setterDef, this);
}
out(",");
TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this);
if (setterDef != null) {
out(",");
TypeUtils.encodeForRuntime(setterDef.getDeclarationModel(), setterDef.getAnnotationList(), this);
}
out(");");
}
else {
out(function, names.getter(d, false), "()");
AttributeGenerator.getter(that, this);
endLine();
out(names.getter(d, false), ".$crtmm$=");
TypeUtils.encodeForRuntime(that, d, this);
if (!shareGetter(d)) { out(";"); }
generateAttributeMetamodel(that, true, false);
}
}
private void addGetterToPrototype(TypeDeclaration outer,
final Tree.AttributeGetterDefinition that) {
Value d = that.getDeclarationModel();
if (!opts.isOptimize()||!d.isClassOrInterfaceMember()) return;
comment(that);
defineAttribute(names.self(outer), names.name(d));
AttributeGenerator.getter(that, this);
final AttributeSetterDefinition setterDef = associatedSetterDefinition(d);
if (setterDef == null) {
out(",undefined");
} else {
out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")");
AttributeGenerator.setter(setterDef, this);
}
out(",");
TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this);
if (setterDef != null) {
out(",");
TypeUtils.encodeForRuntime(setterDef.getDeclarationModel(), setterDef.getAnnotationList(), this);
}
out(");");
}
Tree.AttributeSetterDefinition associatedSetterDefinition(
final Value valueDecl) {
final Setter setter = valueDecl.getSetter();
if ((setter != null) && (currentStatements != null)) {
for (Statement stmt : currentStatements) {
if (stmt instanceof AttributeSetterDefinition) {
final AttributeSetterDefinition setterDef =
(AttributeSetterDefinition) stmt;
if (setterDef.getDeclarationModel() == setter) {
return setterDef;
}
}
}
}
return null;
}
/** Exports a getter function; useful in non-prototype style. */
boolean shareGetter(final MethodOrValue d) {
boolean shared = false;
if (isCaptured(d)) {
beginNewLine();
outerSelf(d);
out(".", names.getter(d, false), "=", names.getter(d, false));
endLine(true);
shared = true;
}
return shared;
}
@Override
public void visit(final Tree.AttributeSetterDefinition that) {
if (errVisitor.hasErrors(that))return;
Setter d = that.getDeclarationModel();
if ((opts.isOptimize()&&d.isClassOrInterfaceMember()) || defineAsProperty(d)) return;
comment(that);
out("function ", names.setter(d.getGetter()), "(", names.name(d.getParameter()), ")");
AttributeGenerator.setter(that, this);
if (!shareSetter(d)) { out(";"); }
if (!d.isToplevel())outerSelf(d);
out(names.setter(d.getGetter()), ".$crtmm$=");
TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this);
endLine(true);
generateAttributeMetamodel(that, false, true);
}
boolean isCaptured(Declaration d) {
if (d.isToplevel()||d.isClassOrInterfaceMember()) {
if (d.isShared() || d.isCaptured()) {
return true;
}
else {
OuterVisitor ov = new OuterVisitor(d);
ov.visit(root);
return ov.found;
}
}
else {
return false;
}
}
boolean shareSetter(final MethodOrValue d) {
boolean shared = false;
if (isCaptured(d)) {
beginNewLine();
outerSelf(d);
out(".", names.setter(d), "=", names.setter(d));
endLine(true);
shared = true;
}
return shared;
}
@Override
public void visit(final Tree.AttributeDeclaration that) {
if (errVisitor.hasErrors(that))return;
final Value d = that.getDeclarationModel();
//Check if the attribute corresponds to a class parameter
//This is because of the new initializer syntax
final com.redhat.ceylon.compiler.typechecker.model.Parameter param = d.isParameter() ?
((Functional)d.getContainer()).getParameter(d.getName()) : null;
final boolean asprop = defineAsProperty(d);
if (d.isFormal()) {
if (!opts.isOptimize()) {
generateAttributeMetamodel(that, false, false);
}
} else {
comment(that);
SpecifierOrInitializerExpression specInitExpr =
that.getSpecifierOrInitializerExpression();
final boolean addGetter = (specInitExpr != null) || (param != null) || !d.isMember()
|| d.isVariable() || d.isLate();
final boolean addSetter = (d.isVariable() || d.isLate()) && !asprop;
if (opts.isOptimize() && d.isClassOrInterfaceMember()) {
if (specInitExpr != null
&& !(specInitExpr instanceof LazySpecifierExpression)) {
outerSelf(d);
out(".", names.privateName(d), "=");
if (d.isLate()) {
out("undefined");
} else {
super.visit(specInitExpr);
}
endLine(true);
}
}
else if (specInitExpr instanceof LazySpecifierExpression) {
if (asprop) {
defineAttribute(names.self((TypeDeclaration)d.getContainer()), names.name(d));
out("{");
} else {
out(function, names.getter(d, false), "(){");
}
initSelf(that);
out("return ");
if (!isNaturalLiteral(specInitExpr.getExpression().getTerm())) {
int boxType = boxStart(specInitExpr.getExpression().getTerm());
specInitExpr.getExpression().visit(this);
if (boxType == 4) out("/*TODO: callable targs 1*/");
boxUnboxEnd(boxType);
}
out(";}");
if (asprop) {
Tree.AttributeSetterDefinition setterDef = null;
if (d.isVariable()) {
setterDef = associatedSetterDefinition(d);
if (setterDef != null) {
out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")");
AttributeGenerator.setter(setterDef, this);
}
}
if (setterDef == null) {
out(",undefined");
}
out(",");
TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this);
if (setterDef != null) {
out(",");
TypeUtils.encodeForRuntime(setterDef.getDeclarationModel(), setterDef.getAnnotationList(), this);
}
out(")");
endLine(true);
} else {
endLine(true);
shareGetter(d);
}
}
else if (!(d.isParameter() && d.getContainer() instanceof Method)) {
if (addGetter) {
AttributeGenerator.generateAttributeGetter(that, d, specInitExpr,
names.name(param), this, directAccess);
}
if (addSetter) {
AttributeGenerator.generateAttributeSetter(that, d, this);
}
}
boolean addMeta=!opts.isOptimize() || d.isToplevel();
if (!d.isToplevel()) {
addMeta |= Util.getContainingDeclaration(d).isAnonymous();
}
if (addMeta) {
generateAttributeMetamodel(that, addGetter, addSetter);
}
}
}
/** Generate runtime metamodel info for an attribute declaration or definition. */
void generateAttributeMetamodel(final Tree.TypedDeclaration that, final boolean addGetter, final boolean addSetter) {
//No need to define all this for local values
Scope _scope = that.getScope();
while (_scope != null) {
//TODO this is bound to change for local decl metamodel
if (_scope instanceof Declaration) {
if (_scope instanceof Method)return;
else break;
}
_scope = _scope.getContainer();
}
Declaration d = that.getDeclarationModel();
if (d instanceof Setter) d = ((Setter)d).getGetter();
final String pname = names.getter(d, false);
final String pnameMeta = names.getter(d, true);
if (!generatedAttributes.contains(d)) {
if (d.isToplevel()) {
out("var ");
} else if (outerSelf(d)) {
out(".");
}
//issue 297 this is only needed in some cases
out(pnameMeta, "={$crtmm$:");
TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this);
out("}"); endLine(true);
if (d.isToplevel()) {
out("ex$.", pnameMeta, "=", pnameMeta);
endLine(true);
}
generatedAttributes.add(d);
}
if (addGetter) {
if (!d.isToplevel()) {
if (outerSelf(d))out(".");
}
out(pnameMeta, ".get=");
if (isCaptured(d) && !defineAsProperty(d)) {
out(pname);
endLine(true);
out(pname, ".$crtmm$=", pnameMeta, ".$crtmm$");
} else {
if (d.isToplevel()) {
out(pname);
} else {
out("function(){return ", names.name(d), "}");
}
}
endLine(true);
}
if (addSetter) {
final String pset = names.setter(d instanceof Setter ? ((Setter)d).getGetter() : d);
if (!d.isToplevel()) {
if (outerSelf(d))out(".");
}
out(pnameMeta, ".set=", pset);
endLine(true);
out("if(", pset, ".$crtmm$===undefined)", pset, ".$crtmm$=", pnameMeta, ".$crtmm$");
endLine(true);
}
}
void generateUnitializedAttributeReadCheck(String privname, String pubname) {
//TODO we can later optimize this, to replace this getter with the plain one
//once the value has been defined
out("if(", privname, "===undefined)throw ", getClAlias(),
"InitializationError('Attempt to read unitialized attribute «", pubname, "»');");
}
void generateImmutableAttributeReassignmentCheck(MethodOrValue decl, String privname, String pubname) {
if (decl.isLate() && !decl.isVariable()) {
out("if(", privname, "!==undefined)throw ", getClAlias(),
"InitializationError('Attempt to reassign immutable attribute «", pubname, "»');");
}
}
@Override
public void visit(final Tree.CharLiteral that) {
out(getClAlias(), "Character(");
out(String.valueOf(that.getText().codePointAt(1)));
out(",true)");
}
@Override
public void visit(final Tree.StringLiteral that) {
out("\"", JsUtils.escapeStringLiteral(that.getText()), "\"");
}
@Override
public void visit(final Tree.StringTemplate that) {
if (errVisitor.hasErrors(that))return;
//TODO optimize to avoid generating initial "" and final .plus("")
List<StringLiteral> literals = that.getStringLiterals();
List<Expression> exprs = that.getExpressions();
for (int i = 0; i < literals.size(); i++) {
StringLiteral literal = literals.get(i);
literal.visit(this);
if (i>0)out(")");
if (i < exprs.size()) {
out(".plus(");
final Expression expr = exprs.get(i);
expr.visit(this);
if (expr.getTypeModel() == null || !"ceylon.language::String".equals(expr.getTypeModel().getProducedTypeQualifiedName())) {
out(".string");
}
out(").plus(");
}
}
}
@Override
public void visit(final Tree.FloatLiteral that) {
out(getClAlias(), "Float(", that.getText(), ")");
}
public long parseNaturalLiteral(Tree.NaturalLiteral that) throws NumberFormatException {
char prefix = that.getText().charAt(0);
int radix = 10;
String nt = that.getText();
if (prefix == '$' || prefix == '#') {
radix = prefix == '$' ? 2 : 16;
nt = nt.substring(1);
}
return new java.math.BigInteger(nt, radix).longValue();
}
@Override
public void visit(final Tree.NaturalLiteral that) {
try {
out("(", Long.toString(parseNaturalLiteral(that)), ")");
} catch (NumberFormatException ex) {
that.addError("Invalid numeric literal " + that.getText());
}
}
@Override
public void visit(final Tree.This that) {
out(names.self(Util.getContainingClassOrInterface(that.getScope())));
}
@Override
public void visit(final Tree.Super that) {
out(names.self(Util.getContainingClassOrInterface(that.getScope())));
}
@Override
public void visit(final Tree.Outer that) {
boolean outer = false;
if (opts.isOptimize()) {
Scope scope = that.getScope();
while ((scope != null) && !(scope instanceof TypeDeclaration)) {
scope = scope.getContainer();
}
if (scope != null && ((TypeDeclaration)scope).isClassOrInterfaceMember()) {
out(names.self((TypeDeclaration) scope), ".");
outer = true;
}
}
if (outer) {
out("outer$");
} else {
out(names.self(that.getTypeModel().getDeclaration()));
}
}
@Override
public void visit(final Tree.BaseMemberExpression that) {
BmeGenerator.generateBme(that, this, false);
}
/** Tells whether a declaration can be accessed directly (using its name) or
* through its getter. */
boolean accessDirectly(Declaration d) {
return !accessThroughGetter(d) || directAccess.contains(d) || d.isParameter();
}
private boolean accessThroughGetter(Declaration d) {
return (d instanceof MethodOrValue) && !(d instanceof Method)
&& !defineAsProperty(d);
}
private boolean defineAsProperty(Declaration d) {
return AttributeGenerator.defineAsProperty(d);
}
/** Returns true if the top-level declaration for the term is annotated "nativejs" */
static boolean isNative(final Tree.Term t) {
if (t instanceof MemberOrTypeExpression) {
return isNative(((MemberOrTypeExpression)t).getDeclaration());
}
return false;
}
/** Returns true if the declaration is annotated "nativejs" */
static boolean isNative(Declaration d) {
return hasAnnotationByName(getToplevel(d), "nativejs") || TypeUtils.isUnknown(d);
}
private static Declaration getToplevel(Declaration d) {
while (d != null && !d.isToplevel()) {
Scope s = d.getContainer();
// Skip any non-declaration elements
while (s != null && !(s instanceof Declaration)) {
s = s.getContainer();
}
d = (Declaration) s;
}
return d;
}
private static boolean hasAnnotationByName(Declaration d, String name){
if (d != null) {
for(com.redhat.ceylon.compiler.typechecker.model.Annotation annotation : d.getAnnotations()){
if(annotation.getName().equals(name))
return true;
}
}
return false;
}
private void generateSafeOp(final Tree.QualifiedMemberOrTypeExpression that) {
boolean isMethod = that.getDeclaration() instanceof Method;
String lhsVar = createRetainedTempVar();
out("(", lhsVar, "=");
super.visit(that);
out(",");
if (isMethod) {
out(getClAlias(), "JsCallable(", lhsVar, ",");
}
out(getClAlias(),"nn$(", lhsVar, ")?");
if (isMethod && !((Method)that.getDeclaration()).getTypeParameters().isEmpty()) {
//Method ref with type parameters
BmeGenerator.printGenericMethodReference(this, that, lhsVar, memberAccess(that, lhsVar));
} else {
out(memberAccess(that, lhsVar));
}
out(":null)");
if (isMethod) {
out(")");
}
}
void supervisit(final Tree.QualifiedMemberOrTypeExpression that) {
super.visit(that);
}
@Override
public void visit(final Tree.QualifiedMemberExpression that) {
if (errVisitor.hasErrors(that))return;
//Big TODO: make sure the member is actually
// refined by the current class!
if (that.getMemberOperator() instanceof SafeMemberOp) {
generateSafeOp(that);
} else if (that.getMemberOperator() instanceof SpreadOp) {
SequenceGenerator.generateSpread(that, this);
} else if (that.getDeclaration() instanceof Method && that.getSignature() == null) {
//TODO right now this causes that all method invocations are done this way
//we need to filter somehow to only use this pattern when the result is supposed to be a callable
//looks like checking for signature is a good way (not THE way though; named arg calls don't have signature)
generateCallable(that, null);
} else if (that.getStaticMethodReference() && that.getDeclaration()!=null) {
out("function($O$){return ");
if (that.getDeclaration() instanceof Method) {
if (BmeGenerator.hasTypeParameters(that)) {
BmeGenerator.printGenericMethodReference(this, that, "$O$", "$O$."+names.name(that.getDeclaration()));
} else {
out(getClAlias(), "JsCallable($O$,$O$.", names.name(that.getDeclaration()), ")");
}
out(";}");
} else {
out("$O$.", names.name(that.getDeclaration()), ";}");
}
} else {
final String lhs = generateToString(new GenerateCallback() {
@Override public void generateValue() {
GenerateJsVisitor.super.visit(that);
}
});
out(memberAccess(that, lhs));
}
}
void generateCallable(final Tree.QualifiedMemberOrTypeExpression that, String name) {
if (that.getPrimary() instanceof Tree.BaseTypeExpression) {
//it's a static method ref
if (name == null) {
name = memberAccess(that, "");
}
out("function(x){return ");
if (BmeGenerator.hasTypeParameters(that)) {
BmeGenerator.printGenericMethodReference(this, that, "x", "x."+name);
} else {
out(getClAlias(), "JsCallable(x,x.", name, ")");
}
out(";}");
return;
}
final Declaration d = that.getDeclaration();
if (d.isToplevel() && d instanceof Method) {
//Just output the name
out(names.name(d));
return;
}
String primaryVar = createRetainedTempVar();
out("(", primaryVar, "=");
that.getPrimary().visit(this);
out(",");
final String member = (name == null) ? memberAccess(that, primaryVar) : (primaryVar+"."+name);
if (that.getDeclaration() instanceof Method
&& !((Method)that.getDeclaration()).getTypeParameters().isEmpty()) {
//Method ref with type parameters
BmeGenerator.printGenericMethodReference(this, that, primaryVar, member);
} else {
out(getClAlias(), "JsCallable(", primaryVar, ",", getClAlias(), "nn$(", primaryVar, ")?", member, ":null)");
}
out(")");
}
/**
* Checks if the given node is a MemberOrTypeExpression or QualifiedType which
* represents an access to a supertype member and returns the scope of that
* member or null.
*/
Scope getSuperMemberScope(Node node) {
Scope scope = null;
if (node instanceof QualifiedMemberOrTypeExpression) {
// Check for "super.member"
QualifiedMemberOrTypeExpression qmte = (QualifiedMemberOrTypeExpression) node;
final Term primary = eliminateParensAndWidening(qmte.getPrimary());
if (primary instanceof Super) {
scope = qmte.getDeclaration().getContainer();
}
}
else if (node instanceof QualifiedType) {
// Check for super.Membertype
QualifiedType qtype = (QualifiedType) node;
if (qtype.getOuterType() instanceof SuperType) {
scope = qtype.getDeclarationModel().getContainer();
}
}
return scope;
}
String getMember(Node node, Declaration decl, String lhs) {
final StringBuilder sb = new StringBuilder();
if (lhs != null) {
if (lhs.length() > 0) {
sb.append(lhs);
}
}
else if (node instanceof BaseMemberOrTypeExpression) {
BaseMemberOrTypeExpression bmte = (BaseMemberOrTypeExpression) node;
Declaration bmd = bmte.getDeclaration();
if (bmd.isParameter() && bmd.getContainer() instanceof ClassAlias) {
return names.name(bmd);
}
String path = qualifiedPath(node, bmd);
if (path.length() > 0) {
sb.append(path);
}
}
return sb.toString();
}
String memberAccessBase(Node node, Declaration decl, boolean setter,
String lhs) {
final StringBuilder sb = new StringBuilder(getMember(node, decl, lhs));
if (sb.length() > 0) {
if (node instanceof BaseMemberOrTypeExpression) {
Declaration bmd = ((BaseMemberOrTypeExpression)node).getDeclaration();
if (bmd.isParameter() && bmd.getContainer() instanceof ClassAlias) {
return sb.toString();
}
}
sb.append(decl instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor ? '_':'.');
}
Scope scope = getSuperMemberScope(node);
boolean metaGetter = false;
if (opts.isOptimize() && (scope != null) &&
decl instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor == false) {
sb.append("getT$all()['");
sb.append(scope.getQualifiedNameString());
sb.append("']");
if (defineAsProperty(decl)) {
return getClAlias() + (setter ? "attrSetter(" : "attrGetter(")
+ sb.toString() + ",'" + names.name(decl) + "')";
}
sb.append(".$$.prototype.");
metaGetter = true;
}
final String member = (accessThroughGetter(decl) && !accessDirectly(decl))
? (setter ? names.setter(decl) : names.getter(decl, metaGetter)) : names.name(decl);
sb.append(member);
if (!opts.isOptimize() && (scope != null)) {
sb.append(names.scopeSuffix(scope));
}
return sb.toString();
}
/**
* Returns a string representing a read access to a member, as represented by
* the given expression. If lhs==null and the expression is a BaseMemberExpression
* then the qualified path is prepended.
*/
String memberAccess(final Tree.StaticMemberOrTypeExpression expr, String lhs) {
Declaration decl = expr.getDeclaration();
String plainName = null;
if (decl == null && dynblock > 0) {
plainName = expr.getIdentifier().getText();
}
else if (isNative(decl)) {
// direct access to a native element
plainName = decl.getName();
}
if (plainName != null) {
return ((lhs != null) && (lhs.length() > 0))
? (lhs + "." + plainName) : plainName;
}
boolean protoCall = opts.isOptimize() && (getSuperMemberScope(expr) != null);
if (accessDirectly(decl) && !(protoCall && defineAsProperty(decl))) {
// direct access, without getter
return memberAccessBase(expr, decl, false, lhs);
}
// access through getter
return memberAccessBase(expr, decl, false, lhs)
+ (protoCall ? ".call(this)" : "()");
}
@Override
public void visit(final Tree.BaseTypeExpression that) {
Declaration d = that.getDeclaration();
if (d == null && isInDynamicBlock()) {
//It's a native js type but will be wrapped in dyntype() call
String id = that.getIdentifier().getText();
out("(typeof ", id, "==='undefined'?");
generateThrow(null, "Undefined type " + id, that);
out(":", id, ")");
} else {
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) {
//This is an ugly-ass hack for when the typechecker incorrectly reports
//the declaration as the constructor instead of the class;
//this happens with classes that have a default constructor with the same name as the type
if (names.name(d).equals(names.name((TypeDeclaration)d.getContainer()))) {
qualify(that, (TypeDeclaration)d.getContainer());
} else {
qualify(that, d);
}
} else {
qualify(that, d);
}
out(names.name(d));
}
}
@Override
public void visit(final Tree.QualifiedTypeExpression that) {
BmeGenerator.generateQte(that, this, false);
}
public void visit(final Tree.Dynamic that) {
invoker.nativeObject(that.getNamedArgumentList());
}
@Override
public void visit(final Tree.InvocationExpression that) {
invoker.generateInvocation(that);
}
@Override
public void visit(final Tree.PositionalArgumentList that) {
invoker.generatePositionalArguments(null, that, that.getPositionalArguments(), false, false);
}
/** Box a term, visit it, unbox it. */
void box(final Tree.Term term) {
final int t = boxStart(term);
term.visit(this);
if (t == 4) {
final ProducedType ct = term.getTypeModel();
out(",");
TypeUtils.encodeCallableArgumentsAsParameterListForRuntime(term, ct, this);
out(",");
TypeUtils.printTypeArguments(term, ct.getTypeArguments(), this, true, null);
}
boxUnboxEnd(t);
}
// Make sure fromTerm is compatible with toTerm by boxing it when necessary
int boxStart(final Tree.Term fromTerm) {
return boxUnboxStart(fromTerm, false);
}
// Make sure fromTerm is compatible with toTerm by boxing or unboxing it when necessary
int boxUnboxStart(final Tree.Term fromTerm, final Tree.Term toTerm) {
return boxUnboxStart(fromTerm, isNative(toTerm));
}
// Make sure fromTerm is compatible with toDecl by boxing or unboxing it when necessary
int boxUnboxStart(final Tree.Term fromTerm, com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration toDecl) {
return boxUnboxStart(fromTerm, isNative(toDecl));
}
int boxUnboxStart(final Tree.Term fromTerm, boolean toNative) {
// Box the value
final boolean fromNative = isNative(fromTerm);
final ProducedType fromType = fromTerm.getTypeModel();
final String fromTypeName = Util.isTypeUnknown(fromType) ? "UNKNOWN" : fromType.getProducedTypeQualifiedName();
if (fromNative != toNative || fromTypeName.startsWith("ceylon.language::Callable<")) {
if (fromNative) {
// conversion from native value to Ceylon value
if (fromTypeName.equals("ceylon.language::Integer")) {
out("(");
} else if (fromTypeName.equals("ceylon.language::Float")) {
out(getClAlias(), "Float(");
} else if (fromTypeName.equals("ceylon.language::Boolean")) {
out("(");
} else if (fromTypeName.equals("ceylon.language::Character")) {
out(getClAlias(), "Character(");
} else if (fromTypeName.startsWith("ceylon.language::Callable<")) {
out(getClAlias(), "$JsCallable(");
return 4;
} else {
return 0;
}
return 1;
} else if ("ceylon.language::Float".equals(fromTypeName)) {
// conversion from Ceylon Float to native value
return 2;
} else if (fromTypeName.startsWith("ceylon.language::Callable<")) {
Term _t = fromTerm;
if (_t instanceof Tree.InvocationExpression) {
_t = ((Tree.InvocationExpression)_t).getPrimary();
}
//Don't box callables if they're not members or anonymous
if (_t instanceof Tree.MemberOrTypeExpression) {
final Declaration d = ((Tree.MemberOrTypeExpression)_t).getDeclaration();
if (d != null && !(d.isClassOrInterfaceMember() || d.isAnonymous())) {
return 0;
}
}
out(getClAlias(), "$JsCallable(");
return 4;
} else {
return 3;
}
}
return 0;
}
void boxUnboxEnd(int boxType) {
switch (boxType) {
case 1: out(")"); break;
case 2: out(".valueOf()"); break;
case 4: out(")"); break;
default: //nothing
}
}
@Override
public void visit(final Tree.ObjectArgument that) {
if (errVisitor.hasErrors(that))return;
FunctionHelper.objectArgument(that, this);
}
@Override
public void visit(final Tree.AttributeArgument that) {
if (errVisitor.hasErrors(that))return;
FunctionHelper.attributeArgument(that, this);
}
@Override
public void visit(final Tree.SequencedArgument that) {
if (errVisitor.hasErrors(that))return;
SequenceGenerator.sequencedArgument(that, this);
}
@Override
public void visit(final Tree.SequenceEnumeration that) {
if (errVisitor.hasErrors(that))return;
SequenceGenerator.sequenceEnumeration(that, this);
}
@Override
public void visit(final Tree.Comprehension that) {
new ComprehensionGenerator(this, names, directAccess).generateComprehension(that);
}
@Override
public void visit(final Tree.SpecifierStatement that) {
// A lazy specifier expression in a class/interface should go into the
// prototype in prototype style, so don't generate them here.
if (!(opts.isOptimize() && (that.getSpecifierExpression() instanceof LazySpecifierExpression)
&& (that.getScope().getContainer() instanceof TypeDeclaration))) {
specifierStatement(null, that);
}
}
private void specifierStatement(final TypeDeclaration outer,
final Tree.SpecifierStatement specStmt) {
final Tree.Expression expr = specStmt.getSpecifierExpression().getExpression();
final Tree.Term term = specStmt.getBaseMemberExpression();
final Tree.StaticMemberOrTypeExpression smte = term instanceof Tree.StaticMemberOrTypeExpression
? (Tree.StaticMemberOrTypeExpression)term : null;
if (dynblock > 0 && Util.isTypeUnknown(term.getTypeModel())) {
if (smte != null && smte.getDeclaration() == null) {
out(smte.getIdentifier().getText());
} else {
term.visit(this);
}
out("=");
int box = boxUnboxStart(expr, term);
expr.visit(this);
if (box == 4) out("/*TODO: callable targs 6*/");
boxUnboxEnd(box);
out(";");
return;
}
if (smte != null) {
Declaration bmeDecl = smte.getDeclaration();
if (specStmt.getSpecifierExpression() instanceof LazySpecifierExpression) {
// attr => expr;
final boolean property = defineAsProperty(bmeDecl);
if (property) {
defineAttribute(qualifiedPath(specStmt, bmeDecl), names.name(bmeDecl));
} else {
if (bmeDecl.isMember()) {
qualify(specStmt, bmeDecl);
} else {
out ("var ");
}
out(names.getter(bmeDecl, false), "=function()");
}
beginBlock();
if (outer != null) { initSelf(specStmt); }
out ("return ");
if (!isNaturalLiteral(specStmt.getSpecifierExpression().getExpression().getTerm())) {
specStmt.getSpecifierExpression().visit(this);
}
out(";");
endBlock();
if (property) {
out(",undefined,");
TypeUtils.encodeForRuntime(specStmt, bmeDecl, this);
out(")");
}
endLine(true);
directAccess.remove(bmeDecl);
}
else if (outer != null) {
// "attr = expr;" in a prototype definition
//since #451 we now generate an attribute here
if (bmeDecl.isMember() && (bmeDecl instanceof Value) && bmeDecl.isActual()) {
Value vdec = (Value)bmeDecl;
final String atname = vdec.isShared() ? names.name(vdec)+"_" : names.privateName(vdec);
defineAttribute(names.self(outer), names.name(vdec));
out("{");
if (vdec.isLate()) {
generateUnitializedAttributeReadCheck("this."+atname, names.name(vdec));
}
out("return this.", atname, ";}");
if (vdec.isVariable() || vdec.isLate()) {
final String par = getNames().createTempVariable();
out(",function(", par, "){");
generateImmutableAttributeReassignmentCheck(vdec, "this."+atname, names.name(vdec));
out("return this.", atname, "=", par, ";}");
} else {
out(",undefined");
}
out(",");
TypeUtils.encodeForRuntime(expr, vdec, this);
out(")");
endLine(true);
}
}
else if (bmeDecl instanceof MethodOrValue) {
// "attr = expr;" in an initializer or method
final MethodOrValue moval = (MethodOrValue)bmeDecl;
if (moval.isVariable()) {
// simple assignment to a variable attribute
BmeGenerator.generateMemberAccess(smte, new GenerateCallback() {
@Override public void generateValue() {
int boxType = boxUnboxStart(expr.getTerm(), moval);
if (dynblock > 0 && !Util.isTypeUnknown(moval.getType())
&& Util.isTypeUnknown(expr.getTypeModel())) {
TypeUtils.generateDynamicCheck(expr, moval.getType(), GenerateJsVisitor.this, false,
expr.getTypeModel().getTypeArguments());
} else {
expr.visit(GenerateJsVisitor.this);
}
if (boxType == 4) {
out(",");
if (moval instanceof Method) {
//Add parameters
TypeUtils.encodeParameterListForRuntime(specStmt,
((Method)moval).getParameterLists().get(0), GenerateJsVisitor.this);
out(",");
} else {
//TODO extract parameters from Value
out("[/*VALUE Callable params", moval.getClass().getName(), "*/],");
}
TypeUtils.printTypeArguments(expr, expr.getTypeModel().getTypeArguments(),
GenerateJsVisitor.this, false, expr.getTypeModel().getVarianceOverrides());
}
boxUnboxEnd(boxType);
}
}, qualifiedPath(smte, moval), this);
out(";");
} else if (moval.isMember()) {
if (moval instanceof Method) {
//same as fat arrow
qualify(specStmt, bmeDecl);
out(names.name(moval), "=function ", names.name(moval), "(");
//Build the parameter list, we'll use it several times
final StringBuilder paramNames = new StringBuilder();
final List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params =
((Method) moval).getParameterLists().get(0).getParameters();
for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : params) {
if (paramNames.length() > 0) paramNames.append(",");
paramNames.append(names.name(p));
}
out(paramNames.toString());
out("){");
for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : params) {
if (p.isDefaulted()) {
out("if(", names.name(p), "===undefined)", names.name(p),"=");
qualify(specStmt, moval);
out(names.name(moval), "$defs$", p.getName(), "(", paramNames.toString(), ")");
endLine(true);
}
}
out("return ");
if (!isNaturalLiteral(specStmt.getSpecifierExpression().getExpression().getTerm())) {
specStmt.getSpecifierExpression().visit(this);
}
out("(", paramNames.toString(), ");}");
endLine(true);
} else {
// Specifier for a member attribute. This actually defines the
// member (e.g. in shortcut refinement syntax the attribute
// declaration itself can be omitted), so generate the attribute.
if (opts.isOptimize()) {
//#451
out(names.self(Util.getContainingClassOrInterface(moval.getScope())), ".",
names.name(moval));
if (!(moval.isVariable() || moval.isLate())) {
out("_");
}
out("=");
specStmt.getSpecifierExpression().visit(this);
endLine(true);
} else {
AttributeGenerator.generateAttributeGetter(null, moval,
specStmt.getSpecifierExpression(), null, this, directAccess);
}
}
} else {
// Specifier for some other attribute, or for a method.
if (opts.isOptimize()
|| (bmeDecl.isMember() && (bmeDecl instanceof Method))) {
qualify(specStmt, bmeDecl);
}
out(names.name(bmeDecl), "=");
if (dynblock > 0 && Util.isTypeUnknown(expr.getTypeModel())
&& !Util.isTypeUnknown(((MethodOrValue) bmeDecl).getType())) {
TypeUtils.generateDynamicCheck(expr, ((MethodOrValue) bmeDecl).getType(), this, false,
expr.getTypeModel().getTypeArguments());
} else {
specStmt.getSpecifierExpression().visit(this);
}
out(";");
}
}
}
else if ((term instanceof ParameterizedExpression)
&& (specStmt.getSpecifierExpression() != null)) {
final ParameterizedExpression paramExpr = (ParameterizedExpression)term;
if (paramExpr.getPrimary() instanceof BaseMemberExpression) {
// func(params) => expr;
final BaseMemberExpression bme2 = (BaseMemberExpression) paramExpr.getPrimary();
final Declaration bmeDecl = bme2.getDeclaration();
if (bmeDecl.isMember()) {
qualify(specStmt, bmeDecl);
} else {
out("var ");
}
out(names.name(bmeDecl), "=");
FunctionHelper.singleExprFunction(paramExpr.getParameterLists(), expr,
bmeDecl instanceof Scope ? (Scope)bmeDecl : null, true, true, this);
out(";");
}
}
}
private void addSpecifierToPrototype(final TypeDeclaration outer,
final Tree.SpecifierStatement specStmt) {
specifierStatement(outer, specStmt);
}
@Override
public void visit(final AssignOp that) {
String returnValue = null;
StaticMemberOrTypeExpression lhsExpr = null;
if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) {
that.getLeftTerm().visit(this);
out("=");
int box = boxUnboxStart(that.getRightTerm(), that.getLeftTerm());
that.getRightTerm().visit(this);
if (box == 4) out("/*TODO: callable targs 6*/");
boxUnboxEnd(box);
return;
}
out("(");
if (that.getLeftTerm() instanceof BaseMemberExpression) {
BaseMemberExpression bme = (BaseMemberExpression) that.getLeftTerm();
lhsExpr = bme;
Declaration bmeDecl = bme.getDeclaration();
boolean simpleSetter = hasSimpleGetterSetter(bmeDecl);
if (!simpleSetter) {
returnValue = memberAccess(bme, null);
}
} else if (that.getLeftTerm() instanceof QualifiedMemberExpression) {
QualifiedMemberExpression qme = (QualifiedMemberExpression)that.getLeftTerm();
lhsExpr = qme;
boolean simpleSetter = hasSimpleGetterSetter(qme.getDeclaration());
String lhsVar = null;
if (!simpleSetter) {
lhsVar = createRetainedTempVar();
out(lhsVar, "=");
super.visit(qme);
out(",", lhsVar, ".");
returnValue = memberAccess(qme, lhsVar);
} else {
super.visit(qme);
out(".");
}
}
BmeGenerator.generateMemberAccess(lhsExpr, new GenerateCallback() {
@Override public void generateValue() {
if (!isNaturalLiteral(that.getRightTerm())) {
int boxType = boxUnboxStart(that.getRightTerm(), that.getLeftTerm());
that.getRightTerm().visit(GenerateJsVisitor.this);
if (boxType == 4) out("/*TODO: callable targs 7*/");
boxUnboxEnd(boxType);
}
}
}, null, this);
if (returnValue != null) { out(",", returnValue); }
out(")");
}
/** Outputs the module name for the specified declaration. Returns true if something was output. */
public boolean qualify(final Node that, final Declaration d) {
String path = qualifiedPath(that, d);
if (path.length() > 0) {
out(path, d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor ? "_" : ".");
}
return path.length() > 0;
}
private String qualifiedPath(final Node that, final Declaration d) {
return qualifiedPath(that, d, false);
}
public String qualifiedPath(final Node that, final Declaration d, final boolean inProto) {
final boolean isMember = d.isClassOrInterfaceMember();
final boolean imported = isImported(that == null ? null : that.getUnit().getPackage(), d);
if (!isMember && imported) {
return names.moduleAlias(d.getUnit().getPackage().getModule());
}
else if (opts.isOptimize() && !inProto) {
if (isMember && !(d.isParameter() && !d.isCaptured())) {
TypeDeclaration id = that.getScope().getInheritingDeclaration(d);
if (id == null) {
//a local declaration of some kind,
//perhaps in an outer scope
id = (TypeDeclaration) d.getContainer();
}
Scope scope = that.getScope();
if ((scope != null) && (that instanceof Tree.ClassDeclaration
|| that instanceof Tree.InterfaceDeclaration || that instanceof Tree.Constructor)) {
// class/interface aliases have no own "this"
scope = scope.getContainer();
}
final StringBuilder path = new StringBuilder();
final Declaration innermostDeclaration = Util.getContainingDeclarationOfScope(scope);
while (scope != null) {
if (scope instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor
&& scope == innermostDeclaration) {
if (that instanceof BaseTypeExpression) {
path.append(names.name((TypeDeclaration)scope.getContainer()));
} else {
path.append(names.self((TypeDeclaration)scope.getContainer()));
}
if (scope == id) {
break;
}
scope = scope.getContainer();
} else if (scope instanceof TypeDeclaration) {
if (path.length() > 0) {
path.append(".outer$");
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor
&& Util.getContainingDeclaration(d) == scope) {
if (!d.getName().equals(((TypeDeclaration)scope).getName())) {
path.append(names.name((TypeDeclaration) scope));
}
} else {
path.append(names.self((TypeDeclaration) scope));
}
} else {
path.setLength(0);
}
if (scope == id) {
break;
}
scope = scope.getContainer();
}
if (id != null && path.length() == 0 && id.isToplevel() && !Util.contains(id, that.getScope())) {
//Import of toplevel object or constructor
if (imported) {
path.append(names.moduleAlias(id.getUnit().getPackage().getModule())).append('.');
}
path.append(id.isAnonymous() ? names.objectName(id) : names.name(id));
}
return path.toString();
}
}
else if (d != null) {
if (isMember && (d.isShared() || inProto || (!d.isParameter() && defineAsProperty(d)))) {
TypeDeclaration id = d instanceof TypeAlias ? (TypeDeclaration)d : that.getScope().getInheritingDeclaration(d);
if (id==null) {
//a local declaration of some kind,
//perhaps in an outer scope
id = (TypeDeclaration) d.getContainer();
if (id.isToplevel() && !Util.contains(id, that.getScope())) {
//Import of toplevel object or constructor
final StringBuilder sb = new StringBuilder();
if (imported) {
sb.append(names.moduleAlias(id.getUnit().getPackage().getModule())).append('.');
}
sb.append(id.isAnonymous() ? names.objectName(id) : names.name(id));
return sb.toString();
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) {
return names.name(id);
} else {
//a shared local declaration
return names.self(id);
}
} else {
//an inherited declaration that might be
//inherited by an outer scope
return names.self(id);
}
}
}
return "";
}
/** Tells whether a declaration is in the specified package. */
public boolean isImported(final Package p2, final Declaration d) {
if (d == null) {
return false;
}
Package p1 = d.getUnit().getPackage();
if (p2 == null)return p1 != null;
if (p1.getModule()== null)return p2.getModule()!=null;
return !p1.getModule().equals(p2.getModule());
}
@Override
public void visit(final Tree.ExecutableStatement that) {
super.visit(that);
endLine(true);
}
/** Creates a new temporary variable which can be used immediately, even
* inside an expression. The declaration for that temporary variable will be
* emitted after the current Ceylon statement has been completely processed.
* The resulting code is valid because JavaScript variables may be used before
* they are declared. */
String createRetainedTempVar() {
String varName = names.createTempVariable();
retainedVars.add(varName);
return varName;
}
@Override
public void visit(final Tree.Return that) {
out("return");
if (that.getExpression() == null) {
endLine(true);
return;
}
out(" ");
if (dynblock > 0 && Util.isTypeUnknown(that.getExpression().getTypeModel())) {
Scope cont = Util.getRealScope(that.getScope()).getScope();
if (cont instanceof Declaration) {
final ProducedType dectype = ((Declaration)cont).getReference().getType();
if (!Util.isTypeUnknown(dectype)) {
TypeUtils.generateDynamicCheck(that.getExpression(), dectype, this, false,
that.getExpression().getTypeModel().getTypeArguments());
endLine(true);
return;
}
}
}
if (isNaturalLiteral(that.getExpression().getTerm())) {
out(";");
} else {
super.visit(that);
}
}
@Override
public void visit(final Tree.AnnotationList that) {}
boolean outerSelf(Declaration d) {
if (d.isToplevel()) {
out("ex$");
return true;
}
else if (d.isClassOrInterfaceMember()) {
out(names.self((TypeDeclaration)d.getContainer()));
return true;
}
return false;
}
@Override
public void visit(final Tree.SumOp that) {
Operators.simpleBinaryOp(that, null, ".plus(", ")", this);
}
@Override
public void visit(final Tree.ScaleOp that) {
final String lhs = names.createTempVariable();
Operators.simpleBinaryOp(that, "function(){var "+lhs+"=", ";return ", ".scale("+lhs+");}()", this);
}
@Override
public void visit(final Tree.DifferenceOp that) {
Operators.simpleBinaryOp(that, null, ".minus(", ")", this);
}
@Override
public void visit(final Tree.ProductOp that) {
Operators.simpleBinaryOp(that, null, ".times(", ")", this);
}
@Override
public void visit(final Tree.QuotientOp that) {
Operators.simpleBinaryOp(that, null, ".divided(", ")", this);
}
@Override public void visit(final Tree.RemainderOp that) {
Operators.simpleBinaryOp(that, null, ".remainder(", ")", this);
}
@Override public void visit(final Tree.PowerOp that) {
Operators.simpleBinaryOp(that, null, ".power(", ")", this);
}
@Override public void visit(final Tree.AddAssignOp that) {
assignOp(that, "plus", null);
}
@Override public void visit(final Tree.SubtractAssignOp that) {
assignOp(that, "minus", null);
}
@Override public void visit(final Tree.MultiplyAssignOp that) {
assignOp(that, "times", null);
}
@Override public void visit(final Tree.DivideAssignOp that) {
assignOp(that, "divided", null);
}
@Override public void visit(final Tree.RemainderAssignOp that) {
assignOp(that, "remainder", null);
}
public void visit(Tree.ComplementAssignOp that) {
assignOp(that, "complement", TypeUtils.mapTypeArgument(that, "complement", "Element", "Other"));
}
public void visit(Tree.UnionAssignOp that) {
assignOp(that, "union", TypeUtils.mapTypeArgument(that, "union", "Element", "Other"));
}
public void visit(Tree.IntersectAssignOp that) {
assignOp(that, "intersection", TypeUtils.mapTypeArgument(that, "intersection", "Element", "Other"));
}
public void visit(Tree.AndAssignOp that) {
assignOp(that, "&&", null);
}
public void visit(Tree.OrAssignOp that) {
assignOp(that, "||", null);
}
private void assignOp(final Tree.AssignmentOp that, final String functionName, final Map<TypeParameter, ProducedType> targs) {
Term lhs = that.getLeftTerm();
final boolean isNative="||".equals(functionName)||"&&".equals(functionName);
if (lhs instanceof BaseMemberExpression) {
BaseMemberExpression lhsBME = (BaseMemberExpression) lhs;
Declaration lhsDecl = lhsBME.getDeclaration();
final String getLHS = memberAccess(lhsBME, null);
out("(");
BmeGenerator.generateMemberAccess(lhsBME, new GenerateCallback() {
@Override public void generateValue() {
if (isNative) {
out(getLHS, functionName);
} else {
out(getLHS, ".", functionName, "(");
}
if (!isNaturalLiteral(that.getRightTerm())) {
that.getRightTerm().visit(GenerateJsVisitor.this);
}
if (!isNative) {
if (targs != null) {
out(",");
TypeUtils.printTypeArguments(that, targs, GenerateJsVisitor.this, false, null);
}
out(")");
}
}
}, null, this);
if (!hasSimpleGetterSetter(lhsDecl)) { out(",", getLHS); }
out(")");
} else if (lhs instanceof QualifiedMemberExpression) {
QualifiedMemberExpression lhsQME = (QualifiedMemberExpression) lhs;
if (isNative(lhsQME)) {
// ($1.foo = Box($1.foo).operator($2))
final String tmp = names.createTempVariable();
final String dec = isInDynamicBlock() && lhsQME.getDeclaration() == null ?
lhsQME.getIdentifier().getText() : lhsQME.getDeclaration().getName();
out("(", tmp, "=");
lhsQME.getPrimary().visit(this);
out(",", tmp, ".", dec, "=");
int boxType = boxStart(lhsQME);
out(tmp, ".", dec);
if (boxType == 4) out("/*TODO: callable targs 8*/");
boxUnboxEnd(boxType);
out(".", functionName, "(");
if (!isNaturalLiteral(that.getRightTerm())) {
that.getRightTerm().visit(this);
}
out("))");
} else {
final String lhsPrimaryVar = createRetainedTempVar();
final String getLHS = memberAccess(lhsQME, lhsPrimaryVar);
out("(", lhsPrimaryVar, "=");
lhsQME.getPrimary().visit(this);
out(",");
BmeGenerator.generateMemberAccess(lhsQME, new GenerateCallback() {
@Override public void generateValue() {
out(getLHS, ".", functionName, "(");
if (!isNaturalLiteral(that.getRightTerm())) {
that.getRightTerm().visit(GenerateJsVisitor.this);
}
out(")");
}
}, lhsPrimaryVar, this);
if (!hasSimpleGetterSetter(lhsQME.getDeclaration())) {
out(",", getLHS);
}
out(")");
}
}
}
@Override public void visit(final Tree.NegativeOp that) {
if (that.getTerm() instanceof Tree.NaturalLiteral) {
long t = parseNaturalLiteral((Tree.NaturalLiteral)that.getTerm());
out("(");
if (t > 0) {
out("-");
}
out(Long.toString(t));
out(")");
if (t == 0) {
//Force -0
out(".negated");
}
return;
}
final TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration();
final boolean isint = d.inherits(that.getUnit().getIntegerDeclaration());
Operators.unaryOp(that, isint?"(-":null, isint?")":".negated", this);
}
@Override public void visit(final Tree.PositiveOp that) {
final TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration();
final boolean nat = d.inherits(that.getUnit().getIntegerDeclaration());
//TODO if it's positive we leave it as is?
Operators.unaryOp(that, nat?"(+":null, nat?")":null, this);
}
@Override public void visit(final Tree.EqualOp that) {
if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) {
//Try to use equals() if it exists
String ltmp = names.createTempVariable();
String rtmp = names.createTempVariable();
out("(", ltmp, "=");
box(that.getLeftTerm());
out(",", rtmp, "=");
box(that.getRightTerm());
out(",(", ltmp, ".equals&&", ltmp, ".equals(", rtmp, "))||", ltmp, "===", rtmp, ")");
} else {
final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm());
Operators.simpleBinaryOp(that, usenat?"((":null, usenat?").valueOf()==(":".equals(",
usenat?").valueOf())":")", this);
}
}
@Override public void visit(final Tree.NotEqualOp that) {
if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) {
//Try to use equals() if it exists
String ltmp = names.createTempVariable();
String rtmp = names.createTempVariable();
out("(", ltmp, "=");
box(that.getLeftTerm());
out(",", rtmp, "=");
box(that.getRightTerm());
out(",(", ltmp, ".equals&&!", ltmp, ".equals(", rtmp, "))||", ltmp, "!==", rtmp, ")");
} else {
final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm());
Operators.simpleBinaryOp(that, usenat?"!(":"(!", usenat?"==":".equals(", usenat?")":"))", this);
}
}
@Override public void visit(final Tree.NotOp that) {
final Term t = that.getTerm();
final boolean omitParens = t instanceof BaseMemberExpression
|| t instanceof QualifiedMemberExpression
|| t instanceof IsOp || t instanceof Exists || t instanceof IdenticalOp
|| t instanceof InOp || t instanceof Nonempty
|| (t instanceof InvocationExpression && ((InvocationExpression)t).getNamedArgumentList() == null);
if (omitParens) {
Operators.unaryOp(that, "!", null, this);
} else {
Operators.unaryOp(that, "(!", ")", this);
}
}
@Override public void visit(final Tree.IdenticalOp that) {
Operators.simpleBinaryOp(that, "(", "===", ")", this);
}
@Override public void visit(final Tree.CompareOp that) {
Operators.simpleBinaryOp(that, null, ".compare(", ")", this);
}
/** Returns true if both Terms' types is either Integer or Boolean. */
private boolean canUseNativeComparator(final Tree.Term left, final Tree.Term right) {
if (left == null || right == null || left.getTypeModel() == null || right.getTypeModel() == null) {
return false;
}
final ProducedType lt = left.getTypeModel();
final ProducedType rt = right.getTypeModel();
final TypeDeclaration intdecl = left.getUnit().getIntegerDeclaration();
final TypeDeclaration booldecl = left.getUnit().getBooleanDeclaration();
return (intdecl.equals(lt.getDeclaration()) && intdecl.equals(rt.getDeclaration()))
|| (booldecl.equals(lt.getDeclaration()) && booldecl.equals(rt.getDeclaration()));
}
@Override public void visit(final Tree.SmallerOp that) {
if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) {
//Try to use compare() if it exists
String ltmp = names.createTempVariable();
String rtmp = names.createTempVariable();
out("(", ltmp, "=");
box(that.getLeftTerm());
out(",", rtmp, "=");
box(that.getRightTerm());
out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(",
getClAlias(), "smaller()))||", ltmp, "<", rtmp, ")");
} else {
final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm());
if (usenat) {
Operators.simpleBinaryOp(that, "(", "<", ")", this);
} else {
Operators.simpleBinaryOp(that, null, ".compare(", ")", this);
out(".equals(", getClAlias(), "smaller())");
}
}
}
@Override public void visit(final Tree.LargerOp that) {
if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) {
//Try to use compare() if it exists
String ltmp = names.createTempVariable();
String rtmp = names.createTempVariable();
out("(", ltmp, "=");
box(that.getLeftTerm());
out(",", rtmp, "=");
box(that.getRightTerm());
out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(",
getClAlias(), "larger()))||", ltmp, ">", rtmp, ")");
} else {
final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm());
if (usenat) {
Operators.simpleBinaryOp(that, "(", ">", ")", this);
} else {
Operators.simpleBinaryOp(that, null, ".compare(", ")", this);
out(".equals(", getClAlias(), "larger())");
}
}
}
@Override public void visit(final Tree.SmallAsOp that) {
if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) {
//Try to use compare() if it exists
String ltmp = names.createTempVariable();
String rtmp = names.createTempVariable();
out("(", ltmp, "=");
box(that.getLeftTerm());
out(",", rtmp, "=");
box(that.getRightTerm());
out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==",
getClAlias(), "larger())||", ltmp, "<=", rtmp, ")");
} else {
final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm());
if (usenat) {
Operators.simpleBinaryOp(that, "(", "<=", ")", this);
} else {
out("(");
Operators.simpleBinaryOp(that, null, ".compare(", ")", this);
out("!==", getClAlias(), "larger()");
out(")");
}
}
}
@Override public void visit(final Tree.LargeAsOp that) {
if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) {
//Try to use compare() if it exists
String ltmp = names.createTempVariable();
String rtmp = names.createTempVariable();
out("(", ltmp, "=");
box(that.getLeftTerm());
out(",", rtmp, "=");
box(that.getRightTerm());
out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==",
getClAlias(), "smaller())||", ltmp, ">=", rtmp, ")");
} else {
final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm());
if (usenat) {
Operators.simpleBinaryOp(that, "(", ">=", ")", this);
} else {
out("(");
Operators.simpleBinaryOp(that, null, ".compare(", ")", this);
out("!==", getClAlias(), "smaller()");
out(")");
}
}
}
public void visit(final Tree.WithinOp that) {
final String ttmp = names.createTempVariable();
out("(", ttmp, "=");
box(that.getTerm());
out(",");
if (dynblock > 0 && Util.isTypeUnknown(that.getTerm().getTypeModel())) {
final String tmpl = names.createTempVariable();
final String tmpu = names.createTempVariable();
out(tmpl, "=");
box(that.getLowerBound().getTerm());
out(",", tmpu, "=");
box(that.getUpperBound().getTerm());
out(",((", ttmp, ".compare&&",ttmp,".compare(", tmpl);
if (that.getLowerBound() instanceof Tree.OpenBound) {
out(")===", getClAlias(), "larger())||", ttmp, ">", tmpl, ")");
} else {
out(")!==", getClAlias(), "smaller())||", ttmp, ">=", tmpl, ")");
}
out("&&((", ttmp, ".compare&&",ttmp,".compare(", tmpu);
if (that.getUpperBound() instanceof Tree.OpenBound) {
out(")===", getClAlias(), "smaller())||", ttmp, "<", tmpu, ")");
} else {
out(")!==", getClAlias(), "larger())||", ttmp, "<=", tmpu, ")");
}
} else {
out(ttmp, ".compare(");
box(that.getLowerBound().getTerm());
if (that.getLowerBound() instanceof Tree.OpenBound) {
out(")===", getClAlias(), "larger()");
} else {
out(")!==", getClAlias(), "smaller()");
}
out("&&");
out(ttmp, ".compare(");
box(that.getUpperBound().getTerm());
if (that.getUpperBound() instanceof Tree.OpenBound) {
out(")===", getClAlias(), "smaller()");
} else {
out(")!==", getClAlias(), "larger()");
}
}
out(")");
}
@Override public void visit(final Tree.AndOp that) {
Operators.simpleBinaryOp(that, "(", "&&", ")", this);
}
@Override public void visit(final Tree.OrOp that) {
Operators.simpleBinaryOp(that, "(", "||", ")", this);
}
@Override public void visit(final Tree.EntryOp that) {
out(getClAlias(), "Entry(");
Operators.genericBinaryOp(that, ",", that.getTypeModel().getTypeArguments(),
that.getTypeModel().getVarianceOverrides(), this);
}
@Override public void visit(final Tree.RangeOp that) {
out(getClAlias(), "span(");
that.getLeftTerm().visit(this);
out(",");
that.getRightTerm().visit(this);
out(",{Element$span:");
TypeUtils.typeNameOrList(that,
Util.unionType(that.getLeftTerm().getTypeModel(), that.getRightTerm().getTypeModel(), that.getUnit()),
this, false);
out("})");
}
@Override
public void visit(final Tree.SegmentOp that) {
final Tree.Term left = that.getLeftTerm();
final Tree.Term right = that.getRightTerm();
out(getClAlias(), "measure(");
left.visit(this);
out(",");
right.visit(this);
out(",{Element$measure:");
TypeUtils.typeNameOrList(that,
Util.unionType(left.getTypeModel(), right.getTypeModel(), that.getUnit()),
this, false);
out("})");
}
@Override public void visit(final Tree.ThenOp that) {
Operators.simpleBinaryOp(that, "(", "?", ":null)", this);
}
@Override public void visit(final Tree.Element that) {
out(".$_get(");
if (!isNaturalLiteral(that.getExpression().getTerm())) {
that.getExpression().visit(this);
}
out(")");
}
@Override public void visit(final Tree.DefaultOp that) {
String lhsVar = createRetainedTempVar();
out("(", lhsVar, "=");
box(that.getLeftTerm());
out(",", getClAlias(), "nn$(", lhsVar, ")?", lhsVar, ":");
box(that.getRightTerm());
out(")");
}
@Override public void visit(final Tree.IncrementOp that) {
Operators.prefixIncrementOrDecrement(that.getTerm(), "successor", this);
}
@Override public void visit(final Tree.DecrementOp that) {
Operators.prefixIncrementOrDecrement(that.getTerm(), "predecessor", this);
}
boolean hasSimpleGetterSetter(Declaration decl) {
return (dynblock > 0 && TypeUtils.isUnknown(decl)) ||
!((decl instanceof Value && ((Value)decl).isTransient()) || (decl instanceof Setter) || decl.isFormal());
}
@Override public void visit(final Tree.PostfixIncrementOp that) {
Operators.postfixIncrementOrDecrement(that.getTerm(), "successor", this);
}
@Override public void visit(final Tree.PostfixDecrementOp that) {
Operators.postfixIncrementOrDecrement(that.getTerm(), "predecessor", this);
}
@Override
public void visit(final Tree.UnionOp that) {
Operators.genericBinaryOp(that, ".union(",
TypeUtils.mapTypeArgument(that, "union", "Element", "Other"),
that.getTypeModel().getVarianceOverrides(), this);
}
@Override
public void visit(final Tree.IntersectionOp that) {
Operators.genericBinaryOp(that, ".intersection(",
TypeUtils.mapTypeArgument(that, "intersection", "Element", "Other"),
that.getTypeModel().getVarianceOverrides(), this);
}
@Override
public void visit(final Tree.ComplementOp that) {
Operators.genericBinaryOp(that, ".complement(",
TypeUtils.mapTypeArgument(that, "complement", "Element", "Other"),
that.getTypeModel().getVarianceOverrides(), this);
}
@Override public void visit(final Tree.Exists that) {
Operators.unaryOp(that, getClAlias()+"nn$(", ")", this);
}
@Override public void visit(final Tree.Nonempty that) {
Operators.unaryOp(that, getClAlias()+"ne$(", ")", this);
}
//Don't know if we'll ever see this...
@Override public void visit(final Tree.ConditionList that) {
spitOut("ZOMG condition list in the wild! " + that.getLocation()
+ " of " + that.getUnit().getFilename());
super.visit(that);
}
@Override public void visit(final Tree.BooleanCondition that) {
int boxType = boxStart(that.getExpression().getTerm());
super.visit(that);
if (boxType == 4) out("/*TODO: callable targs 10*/");
boxUnboxEnd(boxType);
}
@Override public void visit(final Tree.IfStatement that) {
if (errVisitor.hasErrors(that))return;
conds.generateIf(that);
}
@Override public void visit(final Tree.IfExpression that) {
if (errVisitor.hasErrors(that))return;
conds.generateIfExpression(that, false);
}
@Override public void visit(final Tree.WhileStatement that) {
conds.generateWhile(that);
}
/** Generates js code to check if a term is of a certain type. We solve this in JS by
* checking against all types that Type satisfies (in the case of union types, matching any
* type will do, and in case of intersection types, all types must be matched).
* @param term The term that is to be checked against a type
* @param termString (optional) a string to be used as the term to be checked
* @param type The type to check against
* @param tmpvar (optional) a variable to which the term is assigned
* @param negate If true, negates the generated condition
*/
void generateIsOfType(Node term, String termString, final ProducedType type, String tmpvar, final boolean negate) {
if (negate) {
out("!");
}
out(getClAlias(), "is$(");
if (term instanceof Term) {
conds.specialConditionRHS((Term)term, tmpvar);
} else {
conds.specialConditionRHS(termString, tmpvar);
}
out(",");
TypeUtils.typeNameOrList(term, type, this, false);
if (type.getQualifyingType() != null) {
out(",[");
ProducedType outer = type.getQualifyingType();
boolean first=true;
while (outer != null) {
if (first) {
first=false;
} else{
out(",");
}
TypeUtils.typeNameOrList(term, outer, this, false);
outer = outer.getQualifyingType();
}
out("]");
} else if (type.getDeclaration() != null && type.getDeclaration().getContainer() != null) {
Declaration d = Util.getContainingDeclarationOfScope(type.getDeclaration().getContainer());
if (d != null && d instanceof Method && !((Method)d).getTypeParameters().isEmpty()) {
out(",$$$mptypes");
}
}
out(")");
}
@Override
public void visit(final Tree.IsOp that) {
generateIsOfType(that.getTerm(), null, that.getType().getTypeModel(), null, false);
}
@Override public void visit(final Tree.Break that) {
if (continues.isEmpty()) {
out("break;");
} else {
Continuation top=continues.peek();
if (that.getScope()==top.getScope()) {
top.useBreak();
out(top.getBreakName(), "=true; return;");
} else {
out("break;");
}
}
}
@Override public void visit(final Tree.Continue that) {
if (continues.isEmpty()) {
out("continue;");
} else {
Continuation top=continues.peek();
if (that.getScope()==top.getScope()) {
top.useContinue();
out(top.getContinueName(), "=true; return;");
} else {
out("continue;");
}
}
}
@Override public void visit(final Tree.ForStatement that) {
if (errVisitor.hasErrors(that))return;
new ForGenerator(this, directAccess).generate(that);
}
public void visit(final Tree.InOp that) {
box(that.getRightTerm());
out(".contains(");
if (!isNaturalLiteral(that.getLeftTerm())) {
box(that.getLeftTerm());
}
out(")");
}
@Override public void visit(final Tree.TryCatchStatement that) {
if (errVisitor.hasErrors(that))return;
new TryCatchGenerator(this, directAccess).generate(that);
}
@Override public void visit(final Tree.Throw that) {
out("throw ", getClAlias(), "wrapexc(");
if (that.getExpression() == null) {
out(getClAlias(), "Exception()");
} else {
that.getExpression().visit(this);
}
that.getUnit().getFullPath();
out(",'", that.getLocation(), "','", that.getUnit().getRelativePath(), "');");
}
private void visitIndex(final Tree.IndexExpression that) {
that.getPrimary().visit(this);
ElementOrRange eor = that.getElementOrRange();
if (eor instanceof Element) {
final Tree.Expression _elemexpr = ((Tree.Element)eor).getExpression();
final String _end;
if (Util.isTypeUnknown(that.getPrimary().getTypeModel()) && dynblock > 0) {
out("[");
_end = "]";
} else {
out(".$_get(");
_end = ")";
}
if (!isNaturalLiteral(_elemexpr.getTerm())) {
_elemexpr.visit(this);
}
out(_end);
} else {//range, or spread?
ElementRange er = (ElementRange)eor;
Expression sexpr = er.getLength();
if (sexpr == null) {
if (er.getLowerBound() == null) {
out(".spanTo(");
} else if (er.getUpperBound() == null) {
out(".spanFrom(");
} else {
out(".span(");
}
} else {
out(".measure(");
}
if (er.getLowerBound() != null) {
if (!isNaturalLiteral(er.getLowerBound().getTerm())) {
er.getLowerBound().visit(this);
}
if (er.getUpperBound() != null || sexpr != null) {
out(",");
}
}
if (er.getUpperBound() != null) {
if (!isNaturalLiteral(er.getUpperBound().getTerm())) {
er.getUpperBound().visit(this);
}
} else if (sexpr != null) {
sexpr.visit(this);
}
out(")");
}
}
public void visit(final Tree.IndexExpression that) {
visitIndex(that);
}
@Override
public void visit(final Tree.SwitchStatement that) {
if (errVisitor.hasErrors(that))return;
if (opts.isComment() && !opts.isMinify()) {
out("//Switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")");
endLine();
}
conds.switchStatement(that);
if (opts.isComment() && !opts.isMinify()) {
out("//End switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")");
endLine();
}
}
@Override public void visit(final Tree.SwitchExpression that) {
conds.switchExpression(that);
}
/** Generates the code for an anonymous function defined inside an argument list. */
@Override
public void visit(final Tree.FunctionArgument that) {
if (errVisitor.hasErrors(that))return;
FunctionHelper.functionArgument(that, this);
}
public void visit(final Tree.SpecifiedArgument that) {
if (errVisitor.hasErrors(that))return;
int _box=0;
final Tree.SpecifierExpression expr = that.getSpecifierExpression();
if (that.getParameter() != null && expr != null) {
_box = boxUnboxStart(expr.getExpression().getTerm(), that.getParameter().getModel());
}
expr.visit(this);
if (_box == 4) {
out(",");
//Add parameters
invoker.describeMethodParameters(expr.getExpression().getTerm());
out(",");
TypeUtils.printTypeArguments(that, expr.getExpression().getTypeModel().getTypeArguments(), this, false,
expr.getExpression().getTypeModel().getVarianceOverrides());
}
boxUnboxEnd(_box);
}
/** Generates the code for a function in a named argument list. */
@Override
public void visit(final Tree.MethodArgument that) {
if (errVisitor.hasErrors(that))return;
FunctionHelper.methodArgument(that, this);
}
/** Determines whether the specified block should be enclosed in a function. */
public boolean shouldEncloseBlock(Block block) {
// just check if the block contains a captured declaration
for (Tree.Statement statement : block.getStatements()) {
if (statement instanceof Tree.Declaration) {
if (((Tree.Declaration) statement).getDeclarationModel().isCaptured()) {
return true;
}
}
}
return false;
}
/** Encloses the block in a function, IF NEEDED. */
void encloseBlockInFunction(final Tree.Block block, final boolean markBlock) {
final boolean wrap=shouldEncloseBlock(block);
if (wrap) {
if (markBlock)beginBlock();
Continuation c = new Continuation(block.getScope(), names);
continues.push(c);
out("var ", c.getContinueName(), "=false"); endLine(true);
out("var ", c.getBreakName(), "=false"); endLine(true);
out("var ", c.getReturnName(), "=(function()");
if (!markBlock)beginBlock();
}
if (markBlock) {
block.visit(this);
} else {
visitStatements(block.getStatements());
}
if (wrap) {
Continuation c = continues.pop();
if (!markBlock)endBlock();
out("());if(", c.getReturnName(), "!==undefined){return ", c.getReturnName(), ";}");
if (c.isContinued()) {
out("else if(", c.getContinueName(),"===true){continue;}");
}
if (c.isBreaked()) {
out("else if(", c.getBreakName(),"===true){break;}");
}
if (markBlock)endBlockNewLine();
}
}
private static class Continuation {
private final String cvar;
private final String rvar;
private final String bvar;
private final Scope scope;
private boolean cused, bused;
public Continuation(Scope scope, JsIdentifierNames names) {
this.scope=scope;
cvar = names.createTempVariable();
rvar = names.createTempVariable();
bvar = names.createTempVariable();
}
public Scope getScope() { return scope; }
public String getContinueName() { return cvar; }
public String getBreakName() { return bvar; }
public String getReturnName() { return rvar; }
public void useContinue() { cused = true; }
public void useBreak() { bused=true; }
public boolean isContinued() { return cused; }
public boolean isBreaked() { return bused; } //"isBroken" sounds really really bad in this case
}
/** This interface is used inside type initialization method. */
static interface PrototypeInitCallback {
/** Generates a function that adds members to a prototype, then calls it. */
void addToPrototypeCallback();
}
@Override
public void visit(final Tree.Tuple that) {
SequenceGenerator.tuple(that, this);
}
@Override
public void visit(final Tree.Assertion that) {
if (opts.isComment() && !opts.isMinify()) {
out("//assert");
location(that);
endLine();
}
String custom = "Assertion failed";
//Scan for a "doc" annotation with custom message
if (that.getAnnotationList() != null && that.getAnnotationList().getAnonymousAnnotation() != null) {
custom = that.getAnnotationList().getAnonymousAnnotation().getStringLiteral().getText();
} else {
for (Annotation ann : that.getAnnotationList().getAnnotations()) {
BaseMemberExpression bme = (BaseMemberExpression)ann.getPrimary();
if ("doc".equals(bme.getDeclaration().getName())) {
custom = ((Tree.ListedArgument)ann.getPositionalArgumentList().getPositionalArguments().get(0))
.getExpression().getTerm().getText();
}
}
}
StringBuilder sb = new StringBuilder(custom).append(": '");
for (int i = that.getConditionList().getToken().getTokenIndex()+1;
i < that.getConditionList().getEndToken().getTokenIndex(); i++) {
sb.append(tokens.get(i).getText());
}
sb.append("' at ").append(that.getUnit().getFilename()).append(" (").append(
that.getConditionList().getLocation()).append(")");
conds.specialConditionsAndBlock(that.getConditionList(), null, getClAlias()+"asrt$(");
//escape
out(",\"", JsUtils.escapeStringLiteral(sb.toString()), "\",'",that.getLocation(), "','",
that.getUnit().getFilename(), "');");
endLine();
}
@Override
public void visit(Tree.DynamicStatement that) {
dynblock++;
if (dynblock == 1 && !opts.isMinify()) {
if (opts.isComment()) {
out("/*BEG dynblock*/");
}
endLine();
}
for (Tree.Statement stmt : that.getDynamicClause().getBlock().getStatements()) {
stmt.visit(this);
}
if (dynblock == 1 && !opts.isMinify()) {
if (opts.isComment()) {
out("/*END dynblock*/");
}
endLine();
}
dynblock--;
}
public boolean isInDynamicBlock() {
return dynblock > 0;
}
@Override
public void visit(final Tree.TypeLiteral that) {
//Can be an alias, class, interface or type parameter
if (that.getWantsDeclaration()) {
MetamodelHelper.generateOpenType(that, that.getDeclaration(), this);
} else {
MetamodelHelper.generateClosedTypeLiteral(that, this);
}
}
@Override
public void visit(final Tree.MemberLiteral that) {
if (that.getWantsDeclaration()) {
MetamodelHelper.generateOpenType(that, that.getDeclaration(), this);
} else {
MetamodelHelper.generateMemberLiteral(that, this);
}
}
@Override
public void visit(final Tree.PackageLiteral that) {
com.redhat.ceylon.compiler.typechecker.model.Package pkg =
(com.redhat.ceylon.compiler.typechecker.model.Package)that.getImportPath().getModel();
MetamodelHelper.findModule(pkg.getModule(), this);
out(".findPackage('", pkg.getNameAsString(), "')");
}
@Override
public void visit(Tree.ModuleLiteral that) {
Module m = (Module)that.getImportPath().getModel();
MetamodelHelper.findModule(m, this);
}
/** Call internal function "throwexc" with the specified message and source location. */
void generateThrow(String exceptionClass, String msg, Node node) {
out(getClAlias(), "throwexc(", exceptionClass==null ? getClAlias() + "Exception":exceptionClass, "(");
out("\"", JsUtils.escapeStringLiteral(msg), "\"),'", node.getLocation(), "','",
node.getUnit().getFilename(), "')");
}
@Override public void visit(Tree.CompilerAnnotation that) {
//just ignore this
}
/** Outputs the initial part of an attribute definition. */
void defineAttribute(final String owner, final String name) {
out(getClAlias(), "atr$(", owner, ",'", name, "',function()");
}
public int getExitCode() {
return exitCode;
}
@Override public void visit(Tree.ListedArgument that) {
if (!isNaturalLiteral(that.getExpression().getTerm())) {
super.visit(that);
}
}
@Override public void visit(Tree.LetExpression that) {
if (errVisitor.hasErrors(that))return;
FunctionHelper.generateLet(that, directAccess, this);
}
@Override public void visit(final Tree.Destructure that) {
if (errVisitor.hasErrors(that))return;
final String expvar = names.createTempVariable();
out("var ", expvar, "=");
that.getSpecifierExpression().visit(this);
new Destructurer(that.getPattern(), this, directAccess, expvar, false);
endLine(true);
}
boolean isNaturalLiteral(Tree.Term that) {
if (that instanceof Tree.NaturalLiteral) {
out(Long.toString(parseNaturalLiteral((Tree.NaturalLiteral)that)));
return true;
}
return false;
}
static boolean isForBackend(Tree.Declaration decl) {
return isForBackend(decl.getDeclarationModel());
}
static boolean isForBackend(Declaration decl) {
String backend = decl.getNative();
return backend == null || backend.equals(Backend.JavaScript.nativeAnnotation);
}
}
| src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java | package com.redhat.ceylon.compiler.js;
import static com.redhat.ceylon.compiler.typechecker.analyzer.Util.eliminateParensAndWidening;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import org.antlr.runtime.CommonToken;
import com.redhat.ceylon.compiler.js.util.JsIdentifierNames;
import com.redhat.ceylon.compiler.js.util.JsOutput;
import com.redhat.ceylon.compiler.js.util.JsUtils;
import com.redhat.ceylon.compiler.js.util.JsWriter;
import com.redhat.ceylon.compiler.js.util.Options;
import com.redhat.ceylon.compiler.js.util.RetainedVars;
import com.redhat.ceylon.compiler.js.util.TypeUtils;
import com.redhat.ceylon.compiler.js.util.TypeUtils.RuntimeMetamodelAnnotationGenerator;
import com.redhat.ceylon.compiler.typechecker.model.Class;
import com.redhat.ceylon.compiler.typechecker.model.ClassAlias;
import com.redhat.ceylon.compiler.typechecker.model.ClassOrInterface;
import com.redhat.ceylon.compiler.typechecker.model.Declaration;
import com.redhat.ceylon.compiler.typechecker.model.Functional;
import com.redhat.ceylon.compiler.typechecker.model.Interface;
import com.redhat.ceylon.compiler.typechecker.model.Method;
import com.redhat.ceylon.compiler.typechecker.model.MethodOrValue;
import com.redhat.ceylon.compiler.typechecker.model.Module;
import com.redhat.ceylon.compiler.typechecker.model.Package;
import com.redhat.ceylon.compiler.typechecker.model.ProducedType;
import com.redhat.ceylon.compiler.typechecker.model.Scope;
import com.redhat.ceylon.compiler.typechecker.model.Setter;
import com.redhat.ceylon.compiler.typechecker.model.TypeAlias;
import com.redhat.ceylon.compiler.typechecker.model.TypeDeclaration;
import com.redhat.ceylon.compiler.typechecker.model.TypeParameter;
import com.redhat.ceylon.compiler.typechecker.model.Util;
import com.redhat.ceylon.compiler.typechecker.model.Value;
import com.redhat.ceylon.compiler.typechecker.tree.*;
import com.redhat.ceylon.compiler.typechecker.tree.Tree.*;
public class GenerateJsVisitor extends Visitor
implements NaturalVisitor {
private final Stack<Continuation> continues = new Stack<>();
private final JsIdentifierNames names;
private final Set<Declaration> directAccess = new HashSet<>();
private final Set<Declaration> generatedAttributes = new HashSet<>();
private final RetainedVars retainedVars = new RetainedVars();
final ConditionGenerator conds;
private final InvocationGenerator invoker;
private final List<CommonToken> tokens;
private final ErrorVisitor errVisitor = new ErrorVisitor();
private int dynblock;
private int exitCode = 0;
static final class SuperVisitor extends Visitor {
private final List<Declaration> decs;
SuperVisitor(List<Declaration> decs) {
this.decs = decs;
}
@Override
public void visit(QualifiedMemberOrTypeExpression qe) {
Term primary = eliminateParensAndWidening(qe.getPrimary());
if (primary instanceof Super) {
decs.add(qe.getDeclaration());
}
super.visit(qe);
}
@Override
public void visit(QualifiedType that) {
if (that.getOuterType() instanceof SuperType) {
decs.add(that.getDeclarationModel());
}
super.visit(that);
}
public void visit(Tree.ClassOrInterface qe) {
//don't recurse
if (qe instanceof ClassDefinition) {
ExtendedType extType = ((ClassDefinition) qe).getExtendedType();
if (extType != null) { super.visit(extType); }
}
}
}
private final class OuterVisitor extends Visitor {
boolean found = false;
private Declaration dec;
private OuterVisitor(Declaration dec) {
this.dec = dec;
}
@Override
public void visit(QualifiedMemberOrTypeExpression qe) {
if (qe.getPrimary() instanceof Outer ||
qe.getPrimary() instanceof This) {
if ( qe.getDeclaration().equals(dec) ) {
found = true;
}
}
super.visit(qe);
}
}
private List<? extends Statement> currentStatements = null;
public final JsWriter out;
private final PrintWriter verboseOut;
public final Options opts;
private CompilationUnit root;
static final String function="function ";
public Package getCurrentPackage() {
return root.getUnit().getPackage();
}
/** Returns the module name for the language module. */
public String getClAlias() { return jsout.getLanguageModuleAlias(); }
@Override
public void handleException(Exception e, Node that) {
that.addUnexpectedError(that.getMessage(e, this));
}
private final JsOutput jsout;
public GenerateJsVisitor(JsOutput out, Options options, JsIdentifierNames names,
List<CommonToken> tokens) throws IOException {
this.jsout = out;
this.opts = options;
if (options.hasVerboseFlag("code")) {
Writer vw = options.getOutWriter();
verboseOut = vw instanceof PrintWriter ? (PrintWriter)vw :
new PrintWriter(vw == null ? new OutputStreamWriter(System.out) : vw);
} else {
verboseOut = null;
}
this.names = names;
conds = new ConditionGenerator(this, names, directAccess);
this.tokens = tokens;
invoker = new InvocationGenerator(this, names, retainedVars);
this.out = new JsWriter(out.getWriter(), verboseOut, opts.isMinify());
out.setJsWriter(this.out);
}
public InvocationGenerator getInvoker() { return invoker; }
/** Returns the helper component to handle naming. */
public JsIdentifierNames getNames() { return names; }
public static interface GenerateCallback {
public void generateValue();
}
/** Print generated code to the Writer specified at creation time.
* Automatically prints indentation first if necessary.
* @param code The main code
* @param codez Optional additional strings to print after the main code. */
public void out(String code, String... codez) {
out.write(code, codez);
}
/** Prints a newline. Indentation will automatically be printed by {@link #out(String, String...)}
* when the next line is started. */
void endLine() {
out.endLine(false);
}
/** Prints a newline. Indentation will automatically be printed by {@link #out(String, String...)}
* when the next line is started.
* @param semicolon if <code>true</code> then a semicolon is printed at the end
* of the previous line*/
public void endLine(boolean semicolon) {
out.endLine(semicolon);
}
/** Calls {@link #endLine()} if the current position is not already the beginning
* of a line. */
void beginNewLine() {
out.beginNewLine();
}
/** Increases indentation level, prints opening brace and newline. Indentation will
* automatically be printed by {@link #out(String, String...)} when the next line is started. */
void beginBlock() {
out.beginBlock();
}
/** Decreases indentation level, prints a closing brace in new line (using
* {@link #beginNewLine()}) and calls {@link #endLine()}. */
void endBlockNewLine() {
out.endBlock(false, true);
}
/** Decreases indentation level, prints a closing brace in new line (using
* {@link #beginNewLine()}) and calls {@link #endLine()}.
* @param semicolon if <code>true</code> then prints a semicolon after the brace*/
void endBlockNewLine(boolean semicolon) {
out.endBlock(semicolon, true);
}
/** Decreases indentation level and prints a closing brace in new line (using
* {@link #beginNewLine()}). */
void endBlock() {
out.endBlock(false, false);
}
/** Decreases indentation level and prints a closing brace in new line (using
* {@link #beginNewLine()}).
* @param semicolon if <code>true</code> then prints a semicolon after the brace
* @param newline if <code>true</code> then additionally calls {@link #endLine()} */
void endBlock(boolean semicolon, boolean newline) {
out.endBlock(semicolon, newline);
}
void spitOut(String s) {
out.spitOut(s);
}
/** Prints source code location in the form "at [filename] ([location])" */
public void location(Node node) {
out(" at ", node.getUnit().getFilename(), " (", node.getLocation(), ")");
}
private String generateToString(final GenerateCallback callback) {
return out.generateToString(callback);
}
@Override
public void visit(final Tree.CompilationUnit that) {
root = that;
if (!that.getModuleDescriptors().isEmpty()) {
ModuleDescriptor md = that.getModuleDescriptors().get(0);
out("ex$.$mod$ans$=");
TypeUtils.outputAnnotationsFunction(md.getAnnotationList(), null, this);
endLine(true);
if (md.getImportModuleList() != null && !md.getImportModuleList().getImportModules().isEmpty()) {
out("ex$.$mod$imps=function(){return{");
if (!opts.isMinify())endLine();
boolean first=true;
for (ImportModule im : md.getImportModuleList().getImportModules()) {
final StringBuilder path=new StringBuilder("'");
if (im.getImportPath()==null) {
if (im.getQuotedLiteral()==null) {
throw new CompilerErrorException("Invalid imported module");
} else {
final String ql = im.getQuotedLiteral().getText();
path.append(ql.substring(1, ql.length()-1));
}
} else {
for (Identifier id : im.getImportPath().getIdentifiers()) {
if (path.length()>1)path.append('.');
path.append(id.getText());
}
}
final String qv = im.getVersion().getText();
path.append('/').append(qv.substring(1, qv.length()-1)).append("'");
if (first)first=false;else{out(",");endLine();}
out(path.toString(), ":");
TypeUtils.outputAnnotationsFunction(im.getAnnotationList(), null, this);
}
if (!opts.isMinify())endLine();
out("};};");
if (!opts.isMinify())endLine();
}
}
if (!that.getPackageDescriptors().isEmpty()) {
final String pknm = that.getUnit().getPackage().getNameAsString().replaceAll("\\.", "\\$");
out("ex$.$pkg$ans$", pknm, "=");
TypeUtils.outputAnnotationsFunction(that.getPackageDescriptors().get(0).getAnnotationList(), null, this);
endLine(true);
}
for (CompilerAnnotation ca: that.getCompilerAnnotations()) {
ca.visit(this);
}
if (that.getImportList() != null) {
that.getImportList().visit(this);
}
visitStatements(that.getDeclarations());
}
public void visit(final Tree.Import that) {
}
@Override
public void visit(final Tree.Parameter that) {
out(names.name(that.getParameterModel()));
}
@Override
public void visit(final Tree.ParameterList that) {
out("(");
boolean first=true;
boolean ptypes = false;
//Check if this is the first parameter list
if (that.getScope() instanceof Method && that.getModel().isFirst()) {
ptypes = ((Method)that.getScope()).getTypeParameters() != null &&
!((Method)that.getScope()).getTypeParameters().isEmpty();
}
for (Parameter param: that.getParameters()) {
if (!first) out(",");
out(names.name(param.getParameterModel()));
first = false;
}
if (ptypes) {
if (!first) out(",");
out("$$$mptypes");
}
out(")");
}
void visitStatements(List<? extends Statement> statements) {
List<String> oldRetainedVars = retainedVars.reset(null);
final List<? extends Statement> prevStatements = currentStatements;
currentStatements = statements;
for (int i=0; i<statements.size(); i++) {
Statement s = statements.get(i);
s.visit(this);
if (!opts.isMinify())beginNewLine();
retainedVars.emitRetainedVars(this);
}
retainedVars.reset(oldRetainedVars);
currentStatements = prevStatements;
}
@Override
public void visit(final Tree.Body that) {
visitStatements(that.getStatements());
}
@Override
public void visit(final Tree.Block that) {
List<Statement> stmnts = that.getStatements();
if (stmnts.isEmpty()) {
out("{}");
}
else {
beginBlock();
visitStatements(stmnts);
endBlock();
}
}
void initSelf(Node node) {
final NeedsThisVisitor ntv = new NeedsThisVisitor(node);
if (ntv.needsThisReference()) {
final String me=names.self(prototypeOwner);
out("var ", me, "=this");
//Code inside anonymous inner types sometimes gens direct refs to the outer instance
//We can detect if that's going to happen and declare the ref right here
if (ntv.needsOuterReference()) {
final Declaration od = Util.getContainingDeclaration(prototypeOwner);
if (od instanceof TypeDeclaration) {
out(",", names.self((TypeDeclaration)od), "=", me, ".outer$");
}
}
endLine(true);
}
}
/** Visitor that determines if a method definition will need the "this" reference. */
class NeedsThisVisitor extends Visitor {
private boolean refs=false;
private boolean outerRefs=false;
NeedsThisVisitor(Node n) {
if (prototypeOwner != null) {
n.visit(this);
}
}
@Override public void visit(Tree.This that) {
refs = true;
}
@Override public void visit(Tree.Outer that) {
refs = true;
}
@Override public void visit(Tree.Super that) {
refs = true;
}
private boolean check(final Scope origScope) {
Scope s = origScope;
while (s != null) {
if (s == prototypeOwner || (s instanceof TypeDeclaration && prototypeOwner.inherits((TypeDeclaration)s))) {
refs = true;
if (prototypeOwner.isAnonymous() && prototypeOwner.isMember()) {
outerRefs=true;
}
return true;
}
s = s.getContainer();
}
//Check the other way around as well
s = prototypeOwner;
while (s != null) {
if (s == origScope ||
(s instanceof TypeDeclaration && origScope instanceof TypeDeclaration
&& ((TypeDeclaration)s).inherits((TypeDeclaration)origScope))) {
refs = true;
return true;
}
s = s.getContainer();
}
return false;
}
public void visit(Tree.MemberOrTypeExpression that) {
if (refs)return;
if (that.getDeclaration() == null) {
//Some expressions in dynamic blocks can have null declarations
super.visit(that);
return;
}
if (!check(that.getDeclaration().getContainer())) {
super.visit(that);
}
}
public void visit(Tree.Type that) {
if (!check(that.getTypeModel().getDeclaration())) {
super.visit(that);
}
}
public void visit(Tree.ParameterList plist) {
for (Tree.Parameter param : plist.getParameters()) {
if (param.getParameterModel().isDefaulted()) {
refs = true;
return;
}
}
super.visit(plist);
}
boolean needsThisReference() {
return refs;
}
boolean needsOuterReference() {
return outerRefs;
}
}
void comment(Tree.Declaration that) {
if (!opts.isComment() || opts.isMinify()) return;
endLine();
String dname = that.getNodeType();
if (dname.endsWith("Declaration") || dname.endsWith("Definition")) {
dname = dname.substring(0, dname.length()-7);
}
if (that instanceof Tree.Constructor) {
String cname = ((com.redhat.ceylon.compiler.typechecker.model.Class)((Tree.Constructor)that)
.getDeclarationModel().getContainer()).getName();
out("//Constructor ", cname, ".",
that.getDeclarationModel().getName() == null ? cname : that.getDeclarationModel().getName());
} else {
out("//", dname, " ", that.getDeclarationModel().getName());
}
location(that);
endLine();
}
boolean share(Declaration d) {
return share(d, true);
}
private boolean share(Declaration d, boolean excludeProtoMembers) {
boolean shared = false;
if (!(excludeProtoMembers && opts.isOptimize() && d.isClassOrInterfaceMember())
&& isCaptured(d)) {
beginNewLine();
outerSelf(d);
String dname=names.name(d);
if (dname.endsWith("()")){
dname = dname.substring(0, dname.length()-2);
}
out(".", dname, "=", dname);
endLine(true);
shared = true;
}
return shared;
}
@Override
public void visit(final Tree.ClassDeclaration that) {
if (opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember()) return;
classDeclaration(that);
}
private void addClassDeclarationToPrototype(TypeDeclaration outer, final Tree.ClassDeclaration that) {
classDeclaration(that);
final String tname = names.name(that.getDeclarationModel());
out(names.self(outer), ".", tname, "=", tname);
endLine(true);
}
private void addAliasDeclarationToPrototype(TypeDeclaration outer, Tree.TypeAliasDeclaration that) {
comment(that);
final TypeAlias d = that.getDeclarationModel();
String path = qualifiedPath(that, d, true);
if (path.length() > 0) {
path += '.';
}
String tname = names.name(d);
tname = tname.substring(0, tname.length()-2);
String _tmp=names.createTempVariable();
out(names.self(outer), ".", tname, "=function(){var ");
ProducedType pt = that.getTypeSpecifier().getType().getTypeModel();
boolean skip=true;
if (pt.containsTypeParameters() && outerSelf(d)) {
out("=this,");
skip=false;
}
out(_tmp, "=");
TypeUtils.typeNameOrList(that, pt, this, skip);
out(";", _tmp, ".$crtmm$=");
TypeUtils.encodeForRuntime(that,d,this);
out(";return ", _tmp, ";}");
endLine(true);
}
@Override
public void visit(final Tree.InterfaceDeclaration that) {
if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) {
interfaceDeclaration(that);
}
}
private void addInterfaceDeclarationToPrototype(TypeDeclaration outer, final Tree.InterfaceDeclaration that) {
interfaceDeclaration(that);
final String tname = names.name(that.getDeclarationModel());
out(names.self(outer), ".", tname, "=", tname);
endLine(true);
}
private void addInterfaceToPrototype(ClassOrInterface type, final Tree.InterfaceDefinition interfaceDef) {
if (type.isDynamic())return;
TypeGenerator.interfaceDefinition(interfaceDef, this);
Interface d = interfaceDef.getDeclarationModel();
out(names.self(type), ".", names.name(d), "=", names.name(d));
endLine(true);
}
@Override
public void visit(final Tree.InterfaceDefinition that) {
if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) {
TypeGenerator.interfaceDefinition(that, this);
}
}
private void addClassToPrototype(ClassOrInterface type, final Tree.ClassDefinition classDef) {
if (type.isDynamic())return;
TypeGenerator.classDefinition(classDef, this);
final String tname = names.name(classDef.getDeclarationModel());
out(names.self(type), ".", tname, "=", tname);
endLine(true);
}
@Override
public void visit(final Tree.ClassDefinition that) {
if (!(opts.isOptimize() && that.getDeclarationModel().isClassOrInterfaceMember())) {
TypeGenerator.classDefinition(that, this);
}
}
private void interfaceDeclaration(final Tree.InterfaceDeclaration that) {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(that))return;
comment(that);
final Interface d = that.getDeclarationModel();
final String aname = names.name(d);
Tree.StaticType ext = that.getTypeSpecifier().getType();
out(function, aname, "(");
if (d.getTypeParameters() != null && !d.getTypeParameters().isEmpty()) {
out("$$targs$$,");
}
out(names.self(d), "){");
final ProducedType pt = ext.getTypeModel();
final TypeDeclaration aliased = pt.getDeclaration();
qualify(that,aliased);
out(names.name(aliased), "(");
if (!pt.getTypeArguments().isEmpty()) {
TypeUtils.printTypeArguments(that, pt.getTypeArguments(), this, true,
pt.getVarianceOverrides());
out(",");
}
out(names.self(d), ");}");
endLine();
out(aname,".$crtmm$=");
TypeUtils.encodeForRuntime(that, d, this);
endLine(true);
share(d);
}
private void classDeclaration(final Tree.ClassDeclaration that) {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(that))return;
comment(that);
final Class d = that.getDeclarationModel();
final String aname = names.name(d);
final Tree.ClassSpecifier ext = that.getClassSpecifier();
out(function, aname, "(");
//Generate each parameter because we need to append one at the end
for (Parameter p: that.getParameterList().getParameters()) {
p.visit(this);
out(", ");
}
if (d.getTypeParameters() != null && !d.getTypeParameters().isEmpty()) {
out("$$targs$$,");
}
out(names.self(d), "){return ");
TypeDeclaration aliased = ext.getType().getDeclarationModel();
qualify(that, aliased);
out(names.name(aliased), "(");
if (ext.getInvocationExpression().getPositionalArgumentList() != null) {
ext.getInvocationExpression().getPositionalArgumentList().visit(this);
if (!ext.getInvocationExpression().getPositionalArgumentList().getPositionalArguments().isEmpty()) {
out(",");
}
} else {
out("/*PENDIENTE NAMED ARG CLASS DECL */");
}
Map<TypeParameter, ProducedType> invargs = ext.getType().getTypeModel().getTypeArguments();
if (invargs != null && !invargs.isEmpty()) {
TypeUtils.printTypeArguments(that, invargs, this, true,
ext.getType().getTypeModel().getVarianceOverrides());
out(",");
}
out(names.self(d), ");}");
endLine();
out(aname, ".$$=");
qualify(that, aliased);
out(names.name(aliased), ".$$");
endLine(true);
out(aname,".$crtmm$=");
TypeUtils.encodeForRuntime(that, d, this);
endLine(true);
share(d);
}
@Override
public void visit(final Tree.TypeAliasDeclaration that) {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(that))return;
final TypeAlias d = that.getDeclarationModel();
if (opts.isOptimize() && d.isClassOrInterfaceMember()) return;
comment(that);
final String tname=names.createTempVariable();
out(function, names.name(d), "{var ", tname, "=");
TypeUtils.typeNameOrList(that, that.getTypeSpecifier().getType().getTypeModel(), this, false);
out(";", tname, ".$crtmm$=");
TypeUtils.encodeForRuntime(that, d, this, new RuntimeMetamodelAnnotationGenerator() {
@Override public void generateAnnotations() {
TypeUtils.outputAnnotationsFunction(that.getAnnotationList(), d, GenerateJsVisitor.this);
}
});
out(";return ", tname, ";}");
endLine();
share(d);
}
void referenceOuter(TypeDeclaration d) {
if (!d.isToplevel()) {
final ClassOrInterface coi = Util.getContainingClassOrInterface(d.getContainer());
if (coi != null) {
out(names.self(d), ".outer$");
if (d.isClassOrInterfaceMember()) {
out("=this");
} else {
out("=", names.self(coi));
}
endLine(true);
}
}
}
/** Returns the name of the type or its $init$ function if it's local. */
String typeFunctionName(final Tree.StaticType type, boolean removeAlias) {
TypeDeclaration d = type.getTypeModel().getDeclaration();
if ((removeAlias && d.isAlias()) || d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) {
d = d.getExtendedTypeDeclaration();
}
boolean inProto = opts.isOptimize()
&& (type.getScope().getContainer() instanceof TypeDeclaration);
String tfn = memberAccessBase(type, d, false, qualifiedPath(type, d, inProto));
if (removeAlias && !isImported(type.getUnit().getPackage(), d)) {
int idx = tfn.lastIndexOf('.');
if (idx > 0) {
tfn = tfn.substring(0, idx+1) + "$init$" + tfn.substring(idx+1) + "()";
} else {
tfn = "$init$" + tfn + "()";
}
}
return tfn;
}
void addToPrototype(Node node, ClassOrInterface d, List<Tree.Statement> statements) {
final boolean isSerial = d instanceof com.redhat.ceylon.compiler.typechecker.model.Class
&& ((com.redhat.ceylon.compiler.typechecker.model.Class)d).isSerializable();
boolean enter = opts.isOptimize();
ArrayList<com.redhat.ceylon.compiler.typechecker.model.Parameter> plist = null;
if (enter) {
enter = !statements.isEmpty();
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class) {
com.redhat.ceylon.compiler.typechecker.model.ParameterList _pl =
((com.redhat.ceylon.compiler.typechecker.model.Class)d).getParameterList();
if (_pl != null) {
plist = new ArrayList<>(_pl.getParameters().size());
plist.addAll(_pl.getParameters());
enter |= !plist.isEmpty();
}
}
}
if (enter || isSerial) {
final List<? extends Statement> prevStatements = currentStatements;
currentStatements = statements;
out("(function(", names.self(d), ")");
beginBlock();
if (enter) {
//Generated attributes with corresponding parameters will remove them from the list
if (plist != null) {
for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : plist) {
generateAttributeForParameter(node, (com.redhat.ceylon.compiler.typechecker.model.Class)d, p);
}
}
for (Statement s: statements) {
if (s instanceof Tree.ClassOrInterface == false && !(s instanceof Tree.AttributeDeclaration &&
((Tree.AttributeDeclaration)s).getDeclarationModel().isParameter())) {
addToPrototype(d, s, plist);
}
}
for (Statement s: statements) {
if (s instanceof Tree.ClassOrInterface) {
addToPrototype(d, s, plist);
}
}
if (d.isMember()) {
ClassOrInterface coi = Util.getContainingClassOrInterface(d.getContainer());
if (coi != null && d.inherits(coi)) {
out(names.self(d), ".", names.name(d),"=", names.name(d), ";");
}
}
}
if (isSerial) {
SerializationHelper.addSerializer(node, (com.redhat.ceylon.compiler.typechecker.model.Class)d, this);
}
endBlock();
out(")(", names.name(d), ".$$.prototype)");
endLine(true);
currentStatements = prevStatements;
}
}
void generateAttributeForParameter(Node node, com.redhat.ceylon.compiler.typechecker.model.Class d,
com.redhat.ceylon.compiler.typechecker.model.Parameter p) {
final String privname = names.name(p) + "_";
final MethodOrValue pdec = p.getModel();
defineAttribute(names.self(d), names.name(pdec));
out("{");
if (pdec.isLate()) {
generateUnitializedAttributeReadCheck("this."+privname, names.name(p));
}
out("return this.", privname, ";}");
if (pdec.isVariable() || pdec.isLate()) {
final String param = names.createTempVariable();
out(",function(", param, "){");
//Because of this one case, we need to pass 3 args to this method
generateImmutableAttributeReassignmentCheck(pdec, "this."+privname, names.name(p));
out("return this.", privname,
"=", param, ";}");
} else {
out(",undefined");
}
out(",");
TypeUtils.encodeForRuntime(node, pdec, this);
out(")");
endLine(true);
}
private ClassOrInterface prototypeOwner;
private void addToPrototype(ClassOrInterface d, final Tree.Statement s,
List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params) {
ClassOrInterface oldPrototypeOwner = prototypeOwner;
prototypeOwner = d;
if (s instanceof MethodDefinition) {
addMethodToPrototype(d, (MethodDefinition)s);
} else if (s instanceof MethodDeclaration) {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(s))return;
FunctionHelper.methodDeclaration(d, (MethodDeclaration) s, this);
} else if (s instanceof AttributeGetterDefinition) {
addGetterToPrototype(d, (AttributeGetterDefinition)s);
} else if (s instanceof AttributeDeclaration) {
AttributeGenerator.addGetterAndSetterToPrototype(d, (AttributeDeclaration) s, this);
} else if (s instanceof ClassDefinition) {
addClassToPrototype(d, (ClassDefinition) s);
} else if (s instanceof InterfaceDefinition) {
addInterfaceToPrototype(d, (InterfaceDefinition) s);
} else if (s instanceof ObjectDefinition) {
addObjectToPrototype(d, (ObjectDefinition) s);
} else if (s instanceof ClassDeclaration) {
addClassDeclarationToPrototype(d, (ClassDeclaration) s);
} else if (s instanceof InterfaceDeclaration) {
addInterfaceDeclarationToPrototype(d, (InterfaceDeclaration) s);
} else if (s instanceof SpecifierStatement) {
addSpecifierToPrototype(d, (SpecifierStatement) s);
} else if (s instanceof TypeAliasDeclaration) {
addAliasDeclarationToPrototype(d, (TypeAliasDeclaration)s);
}
//This fixes #231 for prototype style
if (params != null && s instanceof Tree.Declaration) {
Declaration m = ((Tree.Declaration)s).getDeclarationModel();
for (Iterator<com.redhat.ceylon.compiler.typechecker.model.Parameter> iter = params.iterator();
iter.hasNext();) {
com.redhat.ceylon.compiler.typechecker.model.Parameter _p = iter.next();
if (m.getName() != null && m.getName().equals(_p.getName())) {
iter.remove();
break;
}
}
}
prototypeOwner = oldPrototypeOwner;
}
void declareSelf(ClassOrInterface d) {
out("if(", names.self(d), "===undefined)");
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Class && d.isAbstract()) {
out(getClAlias(), "throwexc(", getClAlias(), "InvocationException$meta$model(");
out("\"Cannot instantiate abstract class ", d.getQualifiedNameString(), "\"),'?','?')");
} else {
out(names.self(d), "=new ");
if (opts.isOptimize() && d.isClassOrInterfaceMember()) {
out("this.");
}
out(names.name(d), ".$$;");
}
endLine();
}
void instantiateSelf(ClassOrInterface d) {
out("var ", names.self(d), "=new ");
if (opts.isOptimize() && d.isClassOrInterfaceMember()) {
out("this.");
}
out(names.name(d), ".$$;");
}
private void addObjectToPrototype(ClassOrInterface type, final Tree.ObjectDefinition objDef) {
TypeGenerator.objectDefinition(objDef, this);
Value d = objDef.getDeclarationModel();
Class c = (Class) d.getTypeDeclaration();
out(names.self(type), ".", names.name(c), "=", names.name(c), ";",
names.self(type), ".", names.name(c), ".$crtmm$=");
TypeUtils.encodeForRuntime(objDef, d, this);
endLine(true);
}
@Override
public void visit(final Tree.ObjectDefinition that) {
if (errVisitor.hasErrors(that))return;
Value d = that.getDeclarationModel();
if (!(opts.isOptimize() && d.isClassOrInterfaceMember())) {
TypeGenerator.objectDefinition(that, this);
} else {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(that))return;
Class c = (Class) d.getTypeDeclaration();
comment(that);
outerSelf(d);
out(".", names.privateName(d), "=");
outerSelf(d);
out(".", names.name(c), "()");
endLine(true);
}
}
@Override
public void visit(final Tree.ObjectExpression that) {
if (errVisitor.hasErrors(that))return;
out("function(){");
try {
TypeGenerator.defineObject(that, null, that.getSatisfiedTypes(),
that.getExtendedType(), that.getClassBody(), null, this);
} catch (Exception e) {
e.printStackTrace();
}
out("}()");
}
@Override
public void visit(final Tree.MethodDeclaration that) {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(that))return;
FunctionHelper.methodDeclaration(null, that, this);
}
boolean shouldStitch(Declaration d) {
return JsCompiler.isCompilingLanguageModule() && d.isNative();
}
private File getStitchedFilename(final Declaration d, final String suffix) {
String fqn = d.getQualifiedNameString();
if (d.getName() == null && d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) {
String cname = ((com.redhat.ceylon.compiler.typechecker.model.Constructor)d).getExtendedTypeDeclaration().getName();
fqn = fqn.substring(0, fqn.length()-4) + cname;
}
if (fqn.startsWith("ceylon.language"))fqn = fqn.substring(15);
if (fqn.startsWith("::"))fqn=fqn.substring(2);
fqn = fqn.replace('.', '/').replace("::", "/");
return new File(Stitcher.LANGMOD_JS_SRC, fqn + suffix);
}
/** Reads a file with hand-written snippet and outputs it to the current writer. */
boolean stitchNative(final Declaration d, final Tree.Declaration n) {
final File f = getStitchedFilename(d, ".js");
if (f.exists() && f.canRead()) {
jsout.outputFile(f);
if (d.isClassOrInterfaceMember()) {
if (d instanceof Value || n instanceof Tree.Constructor) {
//Native values are defined as attributes
//Constructor metamodel is done in TypeGenerator.classConstructor
return true;
}
out(names.self((TypeDeclaration)d.getContainer()), ".");
}
out(names.name(d), ".$crtmm$=");
TypeUtils.encodeForRuntime(d, n.getAnnotationList(), this);
endLine(true);
return true;
} else {
if (!(d instanceof ClassOrInterface || n instanceof Tree.MethodDefinition)) {
final String err = "REQUIRED NATIVE FILE MISSING FOR "
+ d.getQualifiedNameString() + " => " + f + ", containing " + names.name(d) + ": " + f;
spitOut(err);
out("/*", err, "*/");
}
return false;
}
}
/** Stitch a snippet of code to initialize type (usually a call to initTypeProto). */
boolean stitchInitializer(TypeDeclaration d) {
final File f = getStitchedFilename(d, "$init.js");
if (f.exists() && f.canRead()) {
jsout.outputFile(f);
return true;
}
return false;
}
boolean stitchConstructorHelper(final Tree.ClassOrInterface coi, final String partName) {
final File f;
if (JsCompiler.isCompilingLanguageModule()) {
f = getStitchedFilename(coi.getDeclarationModel(), partName + ".js");
} else {
f = new File(new File(coi.getUnit().getFullPath()).getParentFile(),
String.format("%s%s.js", names.name(coi.getDeclarationModel()), partName));
}
if (f.exists() && f.isFile() && f.canRead()) {
if (verboseOut != null || JsCompiler.isCompilingLanguageModule()) {
spitOut("Stitching in " + f + ". It must contain an anonymous function "
+ "which will be invoked with the same arguments as the "
+ names.name(coi.getDeclarationModel()) + " constructor.");
}
out("(");
jsout.outputFile(f);
out(")");
TypeGenerator.generateParameters(coi.getTypeParameterList(), coi instanceof Tree.ClassDefinition ?
((Tree.ClassDefinition)coi).getParameterList() : null, coi.getDeclarationModel(), this);
endLine(true);
}
return false;
}
@Override
public void visit(final Tree.MethodDefinition that) {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(that))return;
final Method d = that.getDeclarationModel();
if (!((opts.isOptimize() && d.isClassOrInterfaceMember()) || isNative(d))) {
comment(that);
initDefaultedParameters(that.getParameterLists().get(0), d);
FunctionHelper.methodDefinition(that, this, true);
//Add reference to metamodel
out(names.name(d), ".$crtmm$=");
TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this);
endLine(true);
}
}
/** Get the specifier expression for a Parameter, if one is available. */
private SpecifierOrInitializerExpression getDefaultExpression(final Tree.Parameter param) {
final SpecifierOrInitializerExpression expr;
if (param instanceof ParameterDeclaration || param instanceof InitializerParameter) {
MethodDeclaration md = null;
if (param instanceof ParameterDeclaration) {
TypedDeclaration td = ((ParameterDeclaration) param).getTypedDeclaration();
if (td instanceof AttributeDeclaration) {
expr = ((AttributeDeclaration) td).getSpecifierOrInitializerExpression();
} else if (td instanceof MethodDeclaration) {
md = (MethodDeclaration)td;
expr = md.getSpecifierExpression();
} else {
param.addUnexpectedError("Don't know what to do with TypedDeclaration " + td.getClass().getName());
expr = null;
}
} else {
expr = ((InitializerParameter) param).getSpecifierExpression();
}
} else {
param.addUnexpectedError("Don't know what to do with defaulted/sequenced param " + param);
expr = null;
}
return expr;
}
/** Create special functions with the expressions for defaulted parameters in a parameter list. */
void initDefaultedParameters(final Tree.ParameterList params, Method container) {
if (!container.isMember())return;
for (final Parameter param : params.getParameters()) {
com.redhat.ceylon.compiler.typechecker.model.Parameter pd = param.getParameterModel();
if (pd.isDefaulted()) {
final SpecifierOrInitializerExpression expr = getDefaultExpression(param);
if (expr == null) {
continue;
}
qualify(params, container);
out(names.name(container), "$defs$", pd.getName(), "=function");
params.visit(this);
out("{");
initSelf(expr);
out("return ");
if (param instanceof ParameterDeclaration &&
((ParameterDeclaration)param).getTypedDeclaration() instanceof MethodDeclaration) {
// function parameter defaulted using "=>"
FunctionHelper.singleExprFunction(
((MethodDeclaration)((ParameterDeclaration)param).getTypedDeclaration()).getParameterLists(),
expr.getExpression(), null, true, true, this);
} else if (!isNaturalLiteral(expr.getExpression().getTerm())) {
expr.visit(this);
}
out(";}");
endLine(true);
}
}
}
/** Initialize the sequenced, defaulted and captured parameters in a type declaration. */
void initParameters(final Tree.ParameterList params, TypeDeclaration typeDecl, Method m) {
for (final Parameter param : params.getParameters()) {
com.redhat.ceylon.compiler.typechecker.model.Parameter pd = param.getParameterModel();
final String paramName = names.name(pd);
if (pd.isDefaulted() || pd.isSequenced()) {
out("if(", paramName, "===undefined){", paramName, "=");
if (pd.isDefaulted()) {
if (m !=null && m.isMember()) {
qualify(params, m);
out(names.name(m), "$defs$", pd.getName(), "(");
boolean firstParam=true;
for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : m.getParameterLists().get(0).getParameters()) {
if (firstParam){firstParam=false;}else out(",");
out(names.name(p));
}
out(")");
} else {
final SpecifierOrInitializerExpression expr = getDefaultExpression(param);
if (expr == null) {
param.addUnexpectedError("Default expression missing for " + pd.getName());
out("null");
} else if (param instanceof ParameterDeclaration &&
((ParameterDeclaration)param).getTypedDeclaration() instanceof MethodDeclaration) {
// function parameter defaulted using "=>"
FunctionHelper.singleExprFunction(
((MethodDeclaration)((ParameterDeclaration)param).getTypedDeclaration()).getParameterLists(),
expr.getExpression(), m, true, true, this);
} else {
expr.visit(this);
}
}
} else {
out(getClAlias(), "empty()");
}
out(";}");
endLine();
}
if ((typeDecl != null) && (pd.getModel().isCaptured() ||
pd.getDeclaration() instanceof com.redhat.ceylon.compiler.typechecker.model.Class)) {
out(names.self(typeDecl), ".", paramName, "_=", paramName);
if (!opts.isOptimize() && pd.isHidden()) { //belt and suspenders...
out(";", names.self(typeDecl), ".", paramName, "=", paramName);
}
endLine(true);
}
}
}
private void addMethodToPrototype(TypeDeclaration outer,
final Tree.MethodDefinition that) {
//Don't even bother with nodes that have errors
if (errVisitor.hasErrors(that))return;
Method d = that.getDeclarationModel();
if (!opts.isOptimize()||!d.isClassOrInterfaceMember()) return;
comment(that);
initDefaultedParameters(that.getParameterLists().get(0), d);
out(names.self(outer), ".", names.name(d), "=");
FunctionHelper.methodDefinition(that, this, false);
//Add reference to metamodel
out(names.self(outer), ".", names.name(d), ".$crtmm$=");
TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this);
endLine(true);
}
@Override
public void visit(final Tree.AttributeGetterDefinition that) {
if (errVisitor.hasErrors(that))return;
Value d = that.getDeclarationModel();
if (opts.isOptimize()&&d.isClassOrInterfaceMember()) return;
comment(that);
if (defineAsProperty(d)) {
defineAttribute(names.self((TypeDeclaration)d.getContainer()), names.name(d));
AttributeGenerator.getter(that, this);
final AttributeSetterDefinition setterDef = associatedSetterDefinition(d);
if (setterDef == null) {
out(",undefined");
} else {
out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")");
AttributeGenerator.setter(setterDef, this);
}
out(",");
TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this);
if (setterDef != null) {
out(",");
TypeUtils.encodeForRuntime(setterDef.getDeclarationModel(), setterDef.getAnnotationList(), this);
}
out(");");
}
else {
out(function, names.getter(d, false), "()");
AttributeGenerator.getter(that, this);
endLine();
out(names.getter(d, false), ".$crtmm$=");
TypeUtils.encodeForRuntime(that, d, this);
if (!shareGetter(d)) { out(";"); }
generateAttributeMetamodel(that, true, false);
}
}
private void addGetterToPrototype(TypeDeclaration outer,
final Tree.AttributeGetterDefinition that) {
Value d = that.getDeclarationModel();
if (!opts.isOptimize()||!d.isClassOrInterfaceMember()) return;
comment(that);
defineAttribute(names.self(outer), names.name(d));
AttributeGenerator.getter(that, this);
final AttributeSetterDefinition setterDef = associatedSetterDefinition(d);
if (setterDef == null) {
out(",undefined");
} else {
out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")");
AttributeGenerator.setter(setterDef, this);
}
out(",");
TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this);
if (setterDef != null) {
out(",");
TypeUtils.encodeForRuntime(setterDef.getDeclarationModel(), setterDef.getAnnotationList(), this);
}
out(");");
}
Tree.AttributeSetterDefinition associatedSetterDefinition(
final Value valueDecl) {
final Setter setter = valueDecl.getSetter();
if ((setter != null) && (currentStatements != null)) {
for (Statement stmt : currentStatements) {
if (stmt instanceof AttributeSetterDefinition) {
final AttributeSetterDefinition setterDef =
(AttributeSetterDefinition) stmt;
if (setterDef.getDeclarationModel() == setter) {
return setterDef;
}
}
}
}
return null;
}
/** Exports a getter function; useful in non-prototype style. */
boolean shareGetter(final MethodOrValue d) {
boolean shared = false;
if (isCaptured(d)) {
beginNewLine();
outerSelf(d);
out(".", names.getter(d, false), "=", names.getter(d, false));
endLine(true);
shared = true;
}
return shared;
}
@Override
public void visit(final Tree.AttributeSetterDefinition that) {
if (errVisitor.hasErrors(that))return;
Setter d = that.getDeclarationModel();
if ((opts.isOptimize()&&d.isClassOrInterfaceMember()) || defineAsProperty(d)) return;
comment(that);
out("function ", names.setter(d.getGetter()), "(", names.name(d.getParameter()), ")");
AttributeGenerator.setter(that, this);
if (!shareSetter(d)) { out(";"); }
if (!d.isToplevel())outerSelf(d);
out(names.setter(d.getGetter()), ".$crtmm$=");
TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this);
endLine(true);
generateAttributeMetamodel(that, false, true);
}
boolean isCaptured(Declaration d) {
if (d.isToplevel()||d.isClassOrInterfaceMember()) {
if (d.isShared() || d.isCaptured()) {
return true;
}
else {
OuterVisitor ov = new OuterVisitor(d);
ov.visit(root);
return ov.found;
}
}
else {
return false;
}
}
boolean shareSetter(final MethodOrValue d) {
boolean shared = false;
if (isCaptured(d)) {
beginNewLine();
outerSelf(d);
out(".", names.setter(d), "=", names.setter(d));
endLine(true);
shared = true;
}
return shared;
}
@Override
public void visit(final Tree.AttributeDeclaration that) {
if (errVisitor.hasErrors(that))return;
final Value d = that.getDeclarationModel();
//Check if the attribute corresponds to a class parameter
//This is because of the new initializer syntax
final com.redhat.ceylon.compiler.typechecker.model.Parameter param = d.isParameter() ?
((Functional)d.getContainer()).getParameter(d.getName()) : null;
final boolean asprop = defineAsProperty(d);
if (d.isFormal()) {
if (!opts.isOptimize()) {
generateAttributeMetamodel(that, false, false);
}
} else {
comment(that);
SpecifierOrInitializerExpression specInitExpr =
that.getSpecifierOrInitializerExpression();
final boolean addGetter = (specInitExpr != null) || (param != null) || !d.isMember()
|| d.isVariable() || d.isLate();
final boolean addSetter = (d.isVariable() || d.isLate()) && !asprop;
if (opts.isOptimize() && d.isClassOrInterfaceMember()) {
if (specInitExpr != null
&& !(specInitExpr instanceof LazySpecifierExpression)) {
outerSelf(d);
out(".", names.privateName(d), "=");
if (d.isLate()) {
out("undefined");
} else {
super.visit(specInitExpr);
}
endLine(true);
}
}
else if (specInitExpr instanceof LazySpecifierExpression) {
if (asprop) {
defineAttribute(names.self((TypeDeclaration)d.getContainer()), names.name(d));
out("{");
} else {
out(function, names.getter(d, false), "(){");
}
initSelf(that);
out("return ");
if (!isNaturalLiteral(specInitExpr.getExpression().getTerm())) {
int boxType = boxStart(specInitExpr.getExpression().getTerm());
specInitExpr.getExpression().visit(this);
if (boxType == 4) out("/*TODO: callable targs 1*/");
boxUnboxEnd(boxType);
}
out(";}");
if (asprop) {
Tree.AttributeSetterDefinition setterDef = null;
if (d.isVariable()) {
setterDef = associatedSetterDefinition(d);
if (setterDef != null) {
out(",function(", names.name(setterDef.getDeclarationModel().getParameter()), ")");
AttributeGenerator.setter(setterDef, this);
}
}
if (setterDef == null) {
out(",undefined");
}
out(",");
TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this);
if (setterDef != null) {
out(",");
TypeUtils.encodeForRuntime(setterDef.getDeclarationModel(), setterDef.getAnnotationList(), this);
}
out(")");
endLine(true);
} else {
endLine(true);
shareGetter(d);
}
}
else if (!(d.isParameter() && d.getContainer() instanceof Method)) {
if (addGetter) {
AttributeGenerator.generateAttributeGetter(that, d, specInitExpr,
names.name(param), this, directAccess);
}
if (addSetter) {
AttributeGenerator.generateAttributeSetter(that, d, this);
}
}
boolean addMeta=!opts.isOptimize() || d.isToplevel();
if (!d.isToplevel()) {
addMeta |= Util.getContainingDeclaration(d).isAnonymous();
}
if (addMeta) {
generateAttributeMetamodel(that, addGetter, addSetter);
}
}
}
/** Generate runtime metamodel info for an attribute declaration or definition. */
void generateAttributeMetamodel(final Tree.TypedDeclaration that, final boolean addGetter, final boolean addSetter) {
//No need to define all this for local values
Scope _scope = that.getScope();
while (_scope != null) {
//TODO this is bound to change for local decl metamodel
if (_scope instanceof Declaration) {
if (_scope instanceof Method)return;
else break;
}
_scope = _scope.getContainer();
}
Declaration d = that.getDeclarationModel();
if (d instanceof Setter) d = ((Setter)d).getGetter();
final String pname = names.getter(d, false);
final String pnameMeta = names.getter(d, true);
if (!generatedAttributes.contains(d)) {
if (d.isToplevel()) {
out("var ");
} else if (outerSelf(d)) {
out(".");
}
//issue 297 this is only needed in some cases
out(pnameMeta, "={$crtmm$:");
TypeUtils.encodeForRuntime(d, that.getAnnotationList(), this);
out("}"); endLine(true);
if (d.isToplevel()) {
out("ex$.", pnameMeta, "=", pnameMeta);
endLine(true);
}
generatedAttributes.add(d);
}
if (addGetter) {
if (!d.isToplevel()) {
if (outerSelf(d))out(".");
}
out(pnameMeta, ".get=");
if (isCaptured(d) && !defineAsProperty(d)) {
out(pname);
endLine(true);
out(pname, ".$crtmm$=", pnameMeta, ".$crtmm$");
} else {
if (d.isToplevel()) {
out(pname);
} else {
out("function(){return ", names.name(d), "}");
}
}
endLine(true);
}
if (addSetter) {
final String pset = names.setter(d instanceof Setter ? ((Setter)d).getGetter() : d);
if (!d.isToplevel()) {
if (outerSelf(d))out(".");
}
out(pnameMeta, ".set=", pset);
endLine(true);
out("if(", pset, ".$crtmm$===undefined)", pset, ".$crtmm$=", pnameMeta, ".$crtmm$");
endLine(true);
}
}
void generateUnitializedAttributeReadCheck(String privname, String pubname) {
//TODO we can later optimize this, to replace this getter with the plain one
//once the value has been defined
out("if(", privname, "===undefined)throw ", getClAlias(),
"InitializationError('Attempt to read unitialized attribute «", pubname, "»');");
}
void generateImmutableAttributeReassignmentCheck(MethodOrValue decl, String privname, String pubname) {
if (decl.isLate() && !decl.isVariable()) {
out("if(", privname, "!==undefined)throw ", getClAlias(),
"InitializationError('Attempt to reassign immutable attribute «", pubname, "»');");
}
}
@Override
public void visit(final Tree.CharLiteral that) {
out(getClAlias(), "Character(");
out(String.valueOf(that.getText().codePointAt(1)));
out(",true)");
}
@Override
public void visit(final Tree.StringLiteral that) {
out("\"", JsUtils.escapeStringLiteral(that.getText()), "\"");
}
@Override
public void visit(final Tree.StringTemplate that) {
if (errVisitor.hasErrors(that))return;
//TODO optimize to avoid generating initial "" and final .plus("")
List<StringLiteral> literals = that.getStringLiterals();
List<Expression> exprs = that.getExpressions();
for (int i = 0; i < literals.size(); i++) {
StringLiteral literal = literals.get(i);
literal.visit(this);
if (i>0)out(")");
if (i < exprs.size()) {
out(".plus(");
final Expression expr = exprs.get(i);
expr.visit(this);
if (expr.getTypeModel() == null || !"ceylon.language::String".equals(expr.getTypeModel().getProducedTypeQualifiedName())) {
out(".string");
}
out(").plus(");
}
}
}
@Override
public void visit(final Tree.FloatLiteral that) {
out(getClAlias(), "Float(", that.getText(), ")");
}
public long parseNaturalLiteral(Tree.NaturalLiteral that) throws NumberFormatException {
char prefix = that.getText().charAt(0);
int radix = 10;
String nt = that.getText();
if (prefix == '$' || prefix == '#') {
radix = prefix == '$' ? 2 : 16;
nt = nt.substring(1);
}
return new java.math.BigInteger(nt, radix).longValue();
}
@Override
public void visit(final Tree.NaturalLiteral that) {
try {
out("(", Long.toString(parseNaturalLiteral(that)), ")");
} catch (NumberFormatException ex) {
that.addError("Invalid numeric literal " + that.getText());
}
}
@Override
public void visit(final Tree.This that) {
out(names.self(Util.getContainingClassOrInterface(that.getScope())));
}
@Override
public void visit(final Tree.Super that) {
out(names.self(Util.getContainingClassOrInterface(that.getScope())));
}
@Override
public void visit(final Tree.Outer that) {
boolean outer = false;
if (opts.isOptimize()) {
Scope scope = that.getScope();
while ((scope != null) && !(scope instanceof TypeDeclaration)) {
scope = scope.getContainer();
}
if (scope != null && ((TypeDeclaration)scope).isClassOrInterfaceMember()) {
out(names.self((TypeDeclaration) scope), ".");
outer = true;
}
}
if (outer) {
out("outer$");
} else {
out(names.self(that.getTypeModel().getDeclaration()));
}
}
@Override
public void visit(final Tree.BaseMemberExpression that) {
BmeGenerator.generateBme(that, this, false);
}
/** Tells whether a declaration can be accessed directly (using its name) or
* through its getter. */
boolean accessDirectly(Declaration d) {
return !accessThroughGetter(d) || directAccess.contains(d) || d.isParameter();
}
private boolean accessThroughGetter(Declaration d) {
return (d instanceof MethodOrValue) && !(d instanceof Method)
&& !defineAsProperty(d);
}
private boolean defineAsProperty(Declaration d) {
return AttributeGenerator.defineAsProperty(d);
}
/** Returns true if the top-level declaration for the term is annotated "nativejs" */
static boolean isNative(final Tree.Term t) {
if (t instanceof MemberOrTypeExpression) {
return isNative(((MemberOrTypeExpression)t).getDeclaration());
}
return false;
}
/** Returns true if the declaration is annotated "nativejs" */
static boolean isNative(Declaration d) {
return hasAnnotationByName(getToplevel(d), "nativejs") || TypeUtils.isUnknown(d);
}
private static Declaration getToplevel(Declaration d) {
while (d != null && !d.isToplevel()) {
Scope s = d.getContainer();
// Skip any non-declaration elements
while (s != null && !(s instanceof Declaration)) {
s = s.getContainer();
}
d = (Declaration) s;
}
return d;
}
private static boolean hasAnnotationByName(Declaration d, String name){
if (d != null) {
for(com.redhat.ceylon.compiler.typechecker.model.Annotation annotation : d.getAnnotations()){
if(annotation.getName().equals(name))
return true;
}
}
return false;
}
private void generateSafeOp(final Tree.QualifiedMemberOrTypeExpression that) {
boolean isMethod = that.getDeclaration() instanceof Method;
String lhsVar = createRetainedTempVar();
out("(", lhsVar, "=");
super.visit(that);
out(",");
if (isMethod) {
out(getClAlias(), "JsCallable(", lhsVar, ",");
}
out(getClAlias(),"nn$(", lhsVar, ")?");
if (isMethod && !((Method)that.getDeclaration()).getTypeParameters().isEmpty()) {
//Method ref with type parameters
BmeGenerator.printGenericMethodReference(this, that, lhsVar, memberAccess(that, lhsVar));
} else {
out(memberAccess(that, lhsVar));
}
out(":null)");
if (isMethod) {
out(")");
}
}
void supervisit(final Tree.QualifiedMemberOrTypeExpression that) {
super.visit(that);
}
@Override
public void visit(final Tree.QualifiedMemberExpression that) {
if (errVisitor.hasErrors(that))return;
//Big TODO: make sure the member is actually
// refined by the current class!
if (that.getMemberOperator() instanceof SafeMemberOp) {
generateSafeOp(that);
} else if (that.getMemberOperator() instanceof SpreadOp) {
SequenceGenerator.generateSpread(that, this);
} else if (that.getDeclaration() instanceof Method && that.getSignature() == null) {
//TODO right now this causes that all method invocations are done this way
//we need to filter somehow to only use this pattern when the result is supposed to be a callable
//looks like checking for signature is a good way (not THE way though; named arg calls don't have signature)
generateCallable(that, null);
} else if (that.getStaticMethodReference() && that.getDeclaration()!=null) {
out("function($O$){return ");
if (that.getDeclaration() instanceof Method) {
if (BmeGenerator.hasTypeParameters(that)) {
BmeGenerator.printGenericMethodReference(this, that, "$O$", "$O$."+names.name(that.getDeclaration()));
} else {
out(getClAlias(), "JsCallable($O$,$O$.", names.name(that.getDeclaration()), ")");
}
out(";}");
} else {
out("$O$.", names.name(that.getDeclaration()), ";}");
}
} else {
final String lhs = generateToString(new GenerateCallback() {
@Override public void generateValue() {
GenerateJsVisitor.super.visit(that);
}
});
out(memberAccess(that, lhs));
}
}
void generateCallable(final Tree.QualifiedMemberOrTypeExpression that, String name) {
if (that.getPrimary() instanceof Tree.BaseTypeExpression) {
//it's a static method ref
if (name == null) {
name = memberAccess(that, "");
}
out("function(x){return ");
if (BmeGenerator.hasTypeParameters(that)) {
BmeGenerator.printGenericMethodReference(this, that, "x", "x."+name);
} else {
out(getClAlias(), "JsCallable(x,x.", name, ")");
}
out(";}");
return;
}
final Declaration d = that.getDeclaration();
if (d.isToplevel() && d instanceof Method) {
//Just output the name
out(names.name(d));
return;
}
String primaryVar = createRetainedTempVar();
out("(", primaryVar, "=");
that.getPrimary().visit(this);
out(",");
final String member = (name == null) ? memberAccess(that, primaryVar) : (primaryVar+"."+name);
if (that.getDeclaration() instanceof Method
&& !((Method)that.getDeclaration()).getTypeParameters().isEmpty()) {
//Method ref with type parameters
BmeGenerator.printGenericMethodReference(this, that, primaryVar, member);
} else {
out(getClAlias(), "JsCallable(", primaryVar, ",", getClAlias(), "nn$(", primaryVar, ")?", member, ":null)");
}
out(")");
}
/**
* Checks if the given node is a MemberOrTypeExpression or QualifiedType which
* represents an access to a supertype member and returns the scope of that
* member or null.
*/
Scope getSuperMemberScope(Node node) {
Scope scope = null;
if (node instanceof QualifiedMemberOrTypeExpression) {
// Check for "super.member"
QualifiedMemberOrTypeExpression qmte = (QualifiedMemberOrTypeExpression) node;
final Term primary = eliminateParensAndWidening(qmte.getPrimary());
if (primary instanceof Super) {
scope = qmte.getDeclaration().getContainer();
}
}
else if (node instanceof QualifiedType) {
// Check for super.Membertype
QualifiedType qtype = (QualifiedType) node;
if (qtype.getOuterType() instanceof SuperType) {
scope = qtype.getDeclarationModel().getContainer();
}
}
return scope;
}
String getMember(Node node, Declaration decl, String lhs) {
final StringBuilder sb = new StringBuilder();
if (lhs != null) {
if (lhs.length() > 0) {
sb.append(lhs);
}
}
else if (node instanceof BaseMemberOrTypeExpression) {
BaseMemberOrTypeExpression bmte = (BaseMemberOrTypeExpression) node;
Declaration bmd = bmte.getDeclaration();
if (bmd.isParameter() && bmd.getContainer() instanceof ClassAlias) {
return names.name(bmd);
}
String path = qualifiedPath(node, bmd);
if (path.length() > 0) {
sb.append(path);
}
}
return sb.toString();
}
String memberAccessBase(Node node, Declaration decl, boolean setter,
String lhs) {
final StringBuilder sb = new StringBuilder(getMember(node, decl, lhs));
if (sb.length() > 0) {
if (node instanceof BaseMemberOrTypeExpression) {
Declaration bmd = ((BaseMemberOrTypeExpression)node).getDeclaration();
if (bmd.isParameter() && bmd.getContainer() instanceof ClassAlias) {
return sb.toString();
}
}
sb.append(decl instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor ? '_':'.');
}
Scope scope = getSuperMemberScope(node);
boolean metaGetter = false;
if (opts.isOptimize() && (scope != null) &&
decl instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor == false) {
sb.append("getT$all()['");
sb.append(scope.getQualifiedNameString());
sb.append("']");
if (defineAsProperty(decl)) {
return getClAlias() + (setter ? "attrSetter(" : "attrGetter(")
+ sb.toString() + ",'" + names.name(decl) + "')";
}
sb.append(".$$.prototype.");
metaGetter = true;
}
final String member = (accessThroughGetter(decl) && !accessDirectly(decl))
? (setter ? names.setter(decl) : names.getter(decl, metaGetter)) : names.name(decl);
sb.append(member);
if (!opts.isOptimize() && (scope != null)) {
sb.append(names.scopeSuffix(scope));
}
return sb.toString();
}
/**
* Returns a string representing a read access to a member, as represented by
* the given expression. If lhs==null and the expression is a BaseMemberExpression
* then the qualified path is prepended.
*/
String memberAccess(final Tree.StaticMemberOrTypeExpression expr, String lhs) {
Declaration decl = expr.getDeclaration();
String plainName = null;
if (decl == null && dynblock > 0) {
plainName = expr.getIdentifier().getText();
}
else if (isNative(decl)) {
// direct access to a native element
plainName = decl.getName();
}
if (plainName != null) {
return ((lhs != null) && (lhs.length() > 0))
? (lhs + "." + plainName) : plainName;
}
boolean protoCall = opts.isOptimize() && (getSuperMemberScope(expr) != null);
if (accessDirectly(decl) && !(protoCall && defineAsProperty(decl))) {
// direct access, without getter
return memberAccessBase(expr, decl, false, lhs);
}
// access through getter
return memberAccessBase(expr, decl, false, lhs)
+ (protoCall ? ".call(this)" : "()");
}
@Override
public void visit(final Tree.BaseTypeExpression that) {
Declaration d = that.getDeclaration();
if (d == null && isInDynamicBlock()) {
//It's a native js type but will be wrapped in dyntype() call
String id = that.getIdentifier().getText();
out("(typeof ", id, "==='undefined'?");
generateThrow(null, "Undefined type " + id, that);
out(":", id, ")");
} else {
if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) {
//This is an ugly-ass hack for when the typechecker incorrectly reports
//the declaration as the constructor instead of the class;
//this happens with classes that have a default constructor with the same name as the type
if (names.name(d).equals(names.name((TypeDeclaration)d.getContainer()))) {
qualify(that, (TypeDeclaration)d.getContainer());
} else {
qualify(that, d);
}
} else {
qualify(that, d);
}
out(names.name(d));
}
}
@Override
public void visit(final Tree.QualifiedTypeExpression that) {
BmeGenerator.generateQte(that, this, false);
}
public void visit(final Tree.Dynamic that) {
invoker.nativeObject(that.getNamedArgumentList());
}
@Override
public void visit(final Tree.InvocationExpression that) {
invoker.generateInvocation(that);
}
@Override
public void visit(final Tree.PositionalArgumentList that) {
invoker.generatePositionalArguments(null, that, that.getPositionalArguments(), false, false);
}
/** Box a term, visit it, unbox it. */
void box(final Tree.Term term) {
final int t = boxStart(term);
term.visit(this);
if (t == 4) {
final ProducedType ct = term.getTypeModel();
out(",");
TypeUtils.encodeCallableArgumentsAsParameterListForRuntime(term, ct, this);
out(",");
TypeUtils.printTypeArguments(term, ct.getTypeArguments(), this, true, null);
}
boxUnboxEnd(t);
}
// Make sure fromTerm is compatible with toTerm by boxing it when necessary
int boxStart(final Tree.Term fromTerm) {
return boxUnboxStart(fromTerm, false);
}
// Make sure fromTerm is compatible with toTerm by boxing or unboxing it when necessary
int boxUnboxStart(final Tree.Term fromTerm, final Tree.Term toTerm) {
return boxUnboxStart(fromTerm, isNative(toTerm));
}
// Make sure fromTerm is compatible with toDecl by boxing or unboxing it when necessary
int boxUnboxStart(final Tree.Term fromTerm, com.redhat.ceylon.compiler.typechecker.model.TypedDeclaration toDecl) {
return boxUnboxStart(fromTerm, isNative(toDecl));
}
int boxUnboxStart(final Tree.Term fromTerm, boolean toNative) {
// Box the value
final boolean fromNative = isNative(fromTerm);
final ProducedType fromType = fromTerm.getTypeModel();
final String fromTypeName = Util.isTypeUnknown(fromType) ? "UNKNOWN" : fromType.getProducedTypeQualifiedName();
if (fromNative != toNative || fromTypeName.startsWith("ceylon.language::Callable<")) {
if (fromNative) {
// conversion from native value to Ceylon value
if (fromTypeName.equals("ceylon.language::Integer")) {
out("(");
} else if (fromTypeName.equals("ceylon.language::Float")) {
out(getClAlias(), "Float(");
} else if (fromTypeName.equals("ceylon.language::Boolean")) {
out("(");
} else if (fromTypeName.equals("ceylon.language::Character")) {
out(getClAlias(), "Character(");
} else if (fromTypeName.startsWith("ceylon.language::Callable<")) {
out(getClAlias(), "$JsCallable(");
return 4;
} else {
return 0;
}
return 1;
} else if ("ceylon.language::Float".equals(fromTypeName)) {
// conversion from Ceylon Float to native value
return 2;
} else if (fromTypeName.startsWith("ceylon.language::Callable<")) {
Term _t = fromTerm;
if (_t instanceof Tree.InvocationExpression) {
_t = ((Tree.InvocationExpression)_t).getPrimary();
}
//Don't box callables if they're not members or anonymous
if (_t instanceof Tree.MemberOrTypeExpression) {
final Declaration d = ((Tree.MemberOrTypeExpression)_t).getDeclaration();
if (d != null && !(d.isClassOrInterfaceMember() || d.isAnonymous())) {
return 0;
}
}
out(getClAlias(), "$JsCallable(");
return 4;
} else {
return 3;
}
}
return 0;
}
void boxUnboxEnd(int boxType) {
switch (boxType) {
case 1: out(")"); break;
case 2: out(".valueOf()"); break;
case 4: out(")"); break;
default: //nothing
}
}
@Override
public void visit(final Tree.ObjectArgument that) {
if (errVisitor.hasErrors(that))return;
FunctionHelper.objectArgument(that, this);
}
@Override
public void visit(final Tree.AttributeArgument that) {
if (errVisitor.hasErrors(that))return;
FunctionHelper.attributeArgument(that, this);
}
@Override
public void visit(final Tree.SequencedArgument that) {
if (errVisitor.hasErrors(that))return;
SequenceGenerator.sequencedArgument(that, this);
}
@Override
public void visit(final Tree.SequenceEnumeration that) {
if (errVisitor.hasErrors(that))return;
SequenceGenerator.sequenceEnumeration(that, this);
}
@Override
public void visit(final Tree.Comprehension that) {
new ComprehensionGenerator(this, names, directAccess).generateComprehension(that);
}
@Override
public void visit(final Tree.SpecifierStatement that) {
// A lazy specifier expression in a class/interface should go into the
// prototype in prototype style, so don't generate them here.
if (!(opts.isOptimize() && (that.getSpecifierExpression() instanceof LazySpecifierExpression)
&& (that.getScope().getContainer() instanceof TypeDeclaration))) {
specifierStatement(null, that);
}
}
private void specifierStatement(final TypeDeclaration outer,
final Tree.SpecifierStatement specStmt) {
final Tree.Expression expr = specStmt.getSpecifierExpression().getExpression();
final Tree.Term term = specStmt.getBaseMemberExpression();
final Tree.StaticMemberOrTypeExpression smte = term instanceof Tree.StaticMemberOrTypeExpression
? (Tree.StaticMemberOrTypeExpression)term : null;
if (dynblock > 0 && Util.isTypeUnknown(term.getTypeModel())) {
if (smte != null && smte.getDeclaration() == null) {
out(smte.getIdentifier().getText());
} else {
term.visit(this);
}
out("=");
int box = boxUnboxStart(expr, term);
expr.visit(this);
if (box == 4) out("/*TODO: callable targs 6*/");
boxUnboxEnd(box);
out(";");
return;
}
if (smte != null) {
Declaration bmeDecl = smte.getDeclaration();
if (specStmt.getSpecifierExpression() instanceof LazySpecifierExpression) {
// attr => expr;
final boolean property = defineAsProperty(bmeDecl);
if (property) {
defineAttribute(qualifiedPath(specStmt, bmeDecl), names.name(bmeDecl));
} else {
if (bmeDecl.isMember()) {
qualify(specStmt, bmeDecl);
} else {
out ("var ");
}
out(names.getter(bmeDecl, false), "=function()");
}
beginBlock();
if (outer != null) { initSelf(specStmt); }
out ("return ");
if (!isNaturalLiteral(specStmt.getSpecifierExpression().getExpression().getTerm())) {
specStmt.getSpecifierExpression().visit(this);
}
out(";");
endBlock();
if (property) {
out(",undefined,");
TypeUtils.encodeForRuntime(specStmt, bmeDecl, this);
out(")");
}
endLine(true);
directAccess.remove(bmeDecl);
}
else if (outer != null) {
// "attr = expr;" in a prototype definition
//since #451 we now generate an attribute here
if (bmeDecl.isMember() && (bmeDecl instanceof Value) && bmeDecl.isActual()) {
Value vdec = (Value)bmeDecl;
final String atname = vdec.isShared() ? names.name(vdec)+"_" : names.privateName(vdec);
defineAttribute(names.self(outer), names.name(vdec));
out("{");
if (vdec.isLate()) {
generateUnitializedAttributeReadCheck("this."+atname, names.name(vdec));
}
out("return this.", atname, ";}");
if (vdec.isVariable() || vdec.isLate()) {
final String par = getNames().createTempVariable();
out(",function(", par, "){");
generateImmutableAttributeReassignmentCheck(vdec, "this."+atname, names.name(vdec));
out("return this.", atname, "=", par, ";}");
} else {
out(",undefined");
}
out(",");
TypeUtils.encodeForRuntime(expr, vdec, this);
out(")");
endLine(true);
}
}
else if (bmeDecl instanceof MethodOrValue) {
// "attr = expr;" in an initializer or method
final MethodOrValue moval = (MethodOrValue)bmeDecl;
if (moval.isVariable()) {
// simple assignment to a variable attribute
BmeGenerator.generateMemberAccess(smte, new GenerateCallback() {
@Override public void generateValue() {
int boxType = boxUnboxStart(expr.getTerm(), moval);
if (dynblock > 0 && !Util.isTypeUnknown(moval.getType())
&& Util.isTypeUnknown(expr.getTypeModel())) {
TypeUtils.generateDynamicCheck(expr, moval.getType(), GenerateJsVisitor.this, false,
expr.getTypeModel().getTypeArguments());
} else {
expr.visit(GenerateJsVisitor.this);
}
if (boxType == 4) {
out(",");
if (moval instanceof Method) {
//Add parameters
TypeUtils.encodeParameterListForRuntime(specStmt,
((Method)moval).getParameterLists().get(0), GenerateJsVisitor.this);
out(",");
} else {
//TODO extract parameters from Value
out("[/*VALUE Callable params", moval.getClass().getName(), "*/],");
}
TypeUtils.printTypeArguments(expr, expr.getTypeModel().getTypeArguments(),
GenerateJsVisitor.this, false, expr.getTypeModel().getVarianceOverrides());
}
boxUnboxEnd(boxType);
}
}, qualifiedPath(smte, moval), this);
out(";");
} else if (moval.isMember()) {
if (moval instanceof Method) {
//same as fat arrow
qualify(specStmt, bmeDecl);
out(names.name(moval), "=function ", names.name(moval), "(");
//Build the parameter list, we'll use it several times
final StringBuilder paramNames = new StringBuilder();
final List<com.redhat.ceylon.compiler.typechecker.model.Parameter> params =
((Method) moval).getParameterLists().get(0).getParameters();
for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : params) {
if (paramNames.length() > 0) paramNames.append(",");
paramNames.append(names.name(p));
}
out(paramNames.toString());
out("){");
for (com.redhat.ceylon.compiler.typechecker.model.Parameter p : params) {
if (p.isDefaulted()) {
out("if(", names.name(p), "===undefined)", names.name(p),"=");
qualify(specStmt, moval);
out(names.name(moval), "$defs$", p.getName(), "(", paramNames.toString(), ")");
endLine(true);
}
}
out("return ");
if (!isNaturalLiteral(specStmt.getSpecifierExpression().getExpression().getTerm())) {
specStmt.getSpecifierExpression().visit(this);
}
out("(", paramNames.toString(), ");}");
endLine(true);
} else {
// Specifier for a member attribute. This actually defines the
// member (e.g. in shortcut refinement syntax the attribute
// declaration itself can be omitted), so generate the attribute.
if (opts.isOptimize()) {
//#451
out(names.self(Util.getContainingClassOrInterface(moval.getScope())), ".",
names.name(moval));
if (!(moval.isVariable() || moval.isLate())) {
out("_");
}
out("=");
specStmt.getSpecifierExpression().visit(this);
endLine(true);
} else {
AttributeGenerator.generateAttributeGetter(null, moval,
specStmt.getSpecifierExpression(), null, this, directAccess);
}
}
} else {
// Specifier for some other attribute, or for a method.
if (opts.isOptimize()
|| (bmeDecl.isMember() && (bmeDecl instanceof Method))) {
qualify(specStmt, bmeDecl);
}
out(names.name(bmeDecl), "=");
if (dynblock > 0 && Util.isTypeUnknown(expr.getTypeModel())
&& !Util.isTypeUnknown(((MethodOrValue) bmeDecl).getType())) {
TypeUtils.generateDynamicCheck(expr, ((MethodOrValue) bmeDecl).getType(), this, false,
expr.getTypeModel().getTypeArguments());
} else {
specStmt.getSpecifierExpression().visit(this);
}
out(";");
}
}
}
else if ((term instanceof ParameterizedExpression)
&& (specStmt.getSpecifierExpression() != null)) {
final ParameterizedExpression paramExpr = (ParameterizedExpression)term;
if (paramExpr.getPrimary() instanceof BaseMemberExpression) {
// func(params) => expr;
final BaseMemberExpression bme2 = (BaseMemberExpression) paramExpr.getPrimary();
final Declaration bmeDecl = bme2.getDeclaration();
if (bmeDecl.isMember()) {
qualify(specStmt, bmeDecl);
} else {
out("var ");
}
out(names.name(bmeDecl), "=");
FunctionHelper.singleExprFunction(paramExpr.getParameterLists(), expr,
bmeDecl instanceof Scope ? (Scope)bmeDecl : null, true, true, this);
out(";");
}
}
}
private void addSpecifierToPrototype(final TypeDeclaration outer,
final Tree.SpecifierStatement specStmt) {
specifierStatement(outer, specStmt);
}
@Override
public void visit(final AssignOp that) {
String returnValue = null;
StaticMemberOrTypeExpression lhsExpr = null;
if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) {
that.getLeftTerm().visit(this);
out("=");
int box = boxUnboxStart(that.getRightTerm(), that.getLeftTerm());
that.getRightTerm().visit(this);
if (box == 4) out("/*TODO: callable targs 6*/");
boxUnboxEnd(box);
return;
}
out("(");
if (that.getLeftTerm() instanceof BaseMemberExpression) {
BaseMemberExpression bme = (BaseMemberExpression) that.getLeftTerm();
lhsExpr = bme;
Declaration bmeDecl = bme.getDeclaration();
boolean simpleSetter = hasSimpleGetterSetter(bmeDecl);
if (!simpleSetter) {
returnValue = memberAccess(bme, null);
}
} else if (that.getLeftTerm() instanceof QualifiedMemberExpression) {
QualifiedMemberExpression qme = (QualifiedMemberExpression)that.getLeftTerm();
lhsExpr = qme;
boolean simpleSetter = hasSimpleGetterSetter(qme.getDeclaration());
String lhsVar = null;
if (!simpleSetter) {
lhsVar = createRetainedTempVar();
out(lhsVar, "=");
super.visit(qme);
out(",", lhsVar, ".");
returnValue = memberAccess(qme, lhsVar);
} else {
super.visit(qme);
out(".");
}
}
BmeGenerator.generateMemberAccess(lhsExpr, new GenerateCallback() {
@Override public void generateValue() {
if (!isNaturalLiteral(that.getRightTerm())) {
int boxType = boxUnboxStart(that.getRightTerm(), that.getLeftTerm());
that.getRightTerm().visit(GenerateJsVisitor.this);
if (boxType == 4) out("/*TODO: callable targs 7*/");
boxUnboxEnd(boxType);
}
}
}, null, this);
if (returnValue != null) { out(",", returnValue); }
out(")");
}
/** Outputs the module name for the specified declaration. Returns true if something was output. */
public boolean qualify(final Node that, final Declaration d) {
String path = qualifiedPath(that, d);
if (path.length() > 0) {
out(path, d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor ? "_" : ".");
}
return path.length() > 0;
}
private String qualifiedPath(final Node that, final Declaration d) {
return qualifiedPath(that, d, false);
}
public String qualifiedPath(final Node that, final Declaration d, final boolean inProto) {
final boolean isMember = d.isClassOrInterfaceMember();
final boolean imported = isImported(that == null ? null : that.getUnit().getPackage(), d);
if (!isMember && imported) {
return names.moduleAlias(d.getUnit().getPackage().getModule());
}
else if (opts.isOptimize() && !inProto) {
if (isMember && !(d.isParameter() && !d.isCaptured())) {
TypeDeclaration id = that.getScope().getInheritingDeclaration(d);
if (id == null) {
//a local declaration of some kind,
//perhaps in an outer scope
id = (TypeDeclaration) d.getContainer();
}
Scope scope = that.getScope();
if ((scope != null) && (that instanceof Tree.ClassDeclaration
|| that instanceof Tree.InterfaceDeclaration || that instanceof Tree.Constructor)) {
// class/interface aliases have no own "this"
scope = scope.getContainer();
}
final StringBuilder path = new StringBuilder();
final Declaration innermostDeclaration = Util.getContainingDeclarationOfScope(scope);
while (scope != null) {
if (scope instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor
&& scope == innermostDeclaration) {
if (that instanceof BaseTypeExpression) {
path.append(names.name((TypeDeclaration)scope.getContainer()));
} else {
path.append(names.self((TypeDeclaration)scope.getContainer()));
}
if (scope == id) {
break;
}
scope = scope.getContainer();
} else if (scope instanceof TypeDeclaration) {
if (path.length() > 0) {
path.append(".outer$");
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor
&& Util.getContainingDeclaration(d) == scope) {
if (!d.getName().equals(((TypeDeclaration)scope).getName())) {
path.append(names.name((TypeDeclaration) scope));
}
} else {
path.append(names.self((TypeDeclaration) scope));
}
} else {
path.setLength(0);
}
if (scope == id) {
break;
}
scope = scope.getContainer();
}
if (id != null && path.length() == 0 && id.isToplevel() && !Util.contains(id, that.getScope())) {
//Import of toplevel object or constructor
if (imported) {
path.append(names.moduleAlias(id.getUnit().getPackage().getModule())).append('.');
}
path.append(id.isAnonymous() ? names.objectName(id) : names.name(id));
}
return path.toString();
}
}
else if (d != null) {
if (isMember && (d.isShared() || inProto || (!d.isParameter() && defineAsProperty(d)))) {
TypeDeclaration id = d instanceof TypeAlias ? (TypeDeclaration)d : that.getScope().getInheritingDeclaration(d);
if (id==null) {
//a local declaration of some kind,
//perhaps in an outer scope
id = (TypeDeclaration) d.getContainer();
if (id.isToplevel() && !Util.contains(id, that.getScope())) {
//Import of toplevel object or constructor
final StringBuilder sb = new StringBuilder();
if (imported) {
sb.append(names.moduleAlias(id.getUnit().getPackage().getModule())).append('.');
}
sb.append(id.isAnonymous() ? names.objectName(id) : names.name(id));
return sb.toString();
} else if (d instanceof com.redhat.ceylon.compiler.typechecker.model.Constructor) {
return names.name(id);
} else {
//a shared local declaration
return names.self(id);
}
} else {
//an inherited declaration that might be
//inherited by an outer scope
return names.self(id);
}
}
}
return "";
}
/** Tells whether a declaration is in the specified package. */
public boolean isImported(final Package p2, final Declaration d) {
if (d == null) {
return false;
}
Package p1 = d.getUnit().getPackage();
if (p2 == null)return p1 != null;
if (p1.getModule()== null)return p2.getModule()!=null;
return !p1.getModule().equals(p2.getModule());
}
@Override
public void visit(final Tree.ExecutableStatement that) {
super.visit(that);
endLine(true);
}
/** Creates a new temporary variable which can be used immediately, even
* inside an expression. The declaration for that temporary variable will be
* emitted after the current Ceylon statement has been completely processed.
* The resulting code is valid because JavaScript variables may be used before
* they are declared. */
String createRetainedTempVar() {
String varName = names.createTempVariable();
retainedVars.add(varName);
return varName;
}
@Override
public void visit(final Tree.Return that) {
out("return");
if (that.getExpression() == null) {
endLine(true);
return;
}
out(" ");
if (dynblock > 0 && Util.isTypeUnknown(that.getExpression().getTypeModel())) {
Scope cont = Util.getRealScope(that.getScope()).getScope();
if (cont instanceof Declaration) {
final ProducedType dectype = ((Declaration)cont).getReference().getType();
if (!Util.isTypeUnknown(dectype)) {
TypeUtils.generateDynamicCheck(that.getExpression(), dectype, this, false,
that.getExpression().getTypeModel().getTypeArguments());
endLine(true);
return;
}
}
}
if (isNaturalLiteral(that.getExpression().getTerm())) {
out(";");
} else {
super.visit(that);
}
}
@Override
public void visit(final Tree.AnnotationList that) {}
boolean outerSelf(Declaration d) {
if (d.isToplevel()) {
out("ex$");
return true;
}
else if (d.isClassOrInterfaceMember()) {
out(names.self((TypeDeclaration)d.getContainer()));
return true;
}
return false;
}
@Override
public void visit(final Tree.SumOp that) {
Operators.simpleBinaryOp(that, null, ".plus(", ")", this);
}
@Override
public void visit(final Tree.ScaleOp that) {
final String lhs = names.createTempVariable();
Operators.simpleBinaryOp(that, "function(){var "+lhs+"=", ";return ", ".scale("+lhs+");}()", this);
}
@Override
public void visit(final Tree.DifferenceOp that) {
Operators.simpleBinaryOp(that, null, ".minus(", ")", this);
}
@Override
public void visit(final Tree.ProductOp that) {
Operators.simpleBinaryOp(that, null, ".times(", ")", this);
}
@Override
public void visit(final Tree.QuotientOp that) {
Operators.simpleBinaryOp(that, null, ".divided(", ")", this);
}
@Override public void visit(final Tree.RemainderOp that) {
Operators.simpleBinaryOp(that, null, ".remainder(", ")", this);
}
@Override public void visit(final Tree.PowerOp that) {
Operators.simpleBinaryOp(that, null, ".power(", ")", this);
}
@Override public void visit(final Tree.AddAssignOp that) {
assignOp(that, "plus", null);
}
@Override public void visit(final Tree.SubtractAssignOp that) {
assignOp(that, "minus", null);
}
@Override public void visit(final Tree.MultiplyAssignOp that) {
assignOp(that, "times", null);
}
@Override public void visit(final Tree.DivideAssignOp that) {
assignOp(that, "divided", null);
}
@Override public void visit(final Tree.RemainderAssignOp that) {
assignOp(that, "remainder", null);
}
public void visit(Tree.ComplementAssignOp that) {
assignOp(that, "complement", TypeUtils.mapTypeArgument(that, "complement", "Element", "Other"));
}
public void visit(Tree.UnionAssignOp that) {
assignOp(that, "union", TypeUtils.mapTypeArgument(that, "union", "Element", "Other"));
}
public void visit(Tree.IntersectAssignOp that) {
assignOp(that, "intersection", TypeUtils.mapTypeArgument(that, "intersection", "Element", "Other"));
}
public void visit(Tree.AndAssignOp that) {
assignOp(that, "&&", null);
}
public void visit(Tree.OrAssignOp that) {
assignOp(that, "||", null);
}
private void assignOp(final Tree.AssignmentOp that, final String functionName, final Map<TypeParameter, ProducedType> targs) {
Term lhs = that.getLeftTerm();
final boolean isNative="||".equals(functionName)||"&&".equals(functionName);
if (lhs instanceof BaseMemberExpression) {
BaseMemberExpression lhsBME = (BaseMemberExpression) lhs;
Declaration lhsDecl = lhsBME.getDeclaration();
final String getLHS = memberAccess(lhsBME, null);
out("(");
BmeGenerator.generateMemberAccess(lhsBME, new GenerateCallback() {
@Override public void generateValue() {
if (isNative) {
out(getLHS, functionName);
} else {
out(getLHS, ".", functionName, "(");
}
if (!isNaturalLiteral(that.getRightTerm())) {
that.getRightTerm().visit(GenerateJsVisitor.this);
}
if (!isNative) {
if (targs != null) {
out(",");
TypeUtils.printTypeArguments(that, targs, GenerateJsVisitor.this, false, null);
}
out(")");
}
}
}, null, this);
if (!hasSimpleGetterSetter(lhsDecl)) { out(",", getLHS); }
out(")");
} else if (lhs instanceof QualifiedMemberExpression) {
QualifiedMemberExpression lhsQME = (QualifiedMemberExpression) lhs;
if (isNative(lhsQME)) {
// ($1.foo = Box($1.foo).operator($2))
final String tmp = names.createTempVariable();
final String dec = isInDynamicBlock() && lhsQME.getDeclaration() == null ?
lhsQME.getIdentifier().getText() : lhsQME.getDeclaration().getName();
out("(", tmp, "=");
lhsQME.getPrimary().visit(this);
out(",", tmp, ".", dec, "=");
int boxType = boxStart(lhsQME);
out(tmp, ".", dec);
if (boxType == 4) out("/*TODO: callable targs 8*/");
boxUnboxEnd(boxType);
out(".", functionName, "(");
if (!isNaturalLiteral(that.getRightTerm())) {
that.getRightTerm().visit(this);
}
out("))");
} else {
final String lhsPrimaryVar = createRetainedTempVar();
final String getLHS = memberAccess(lhsQME, lhsPrimaryVar);
out("(", lhsPrimaryVar, "=");
lhsQME.getPrimary().visit(this);
out(",");
BmeGenerator.generateMemberAccess(lhsQME, new GenerateCallback() {
@Override public void generateValue() {
out(getLHS, ".", functionName, "(");
if (!isNaturalLiteral(that.getRightTerm())) {
that.getRightTerm().visit(GenerateJsVisitor.this);
}
out(")");
}
}, lhsPrimaryVar, this);
if (!hasSimpleGetterSetter(lhsQME.getDeclaration())) {
out(",", getLHS);
}
out(")");
}
}
}
@Override public void visit(final Tree.NegativeOp that) {
if (that.getTerm() instanceof Tree.NaturalLiteral) {
long t = parseNaturalLiteral((Tree.NaturalLiteral)that.getTerm());
out("(");
if (t > 0) {
out("-");
}
out(Long.toString(t));
out(")");
if (t == 0) {
//Force -0
out(".negated");
}
return;
}
final TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration();
final boolean isint = d.inherits(that.getUnit().getIntegerDeclaration());
Operators.unaryOp(that, isint?"(-":null, isint?")":".negated", this);
}
@Override public void visit(final Tree.PositiveOp that) {
final TypeDeclaration d = that.getTerm().getTypeModel().getDeclaration();
final boolean nat = d.inherits(that.getUnit().getIntegerDeclaration());
//TODO if it's positive we leave it as is?
Operators.unaryOp(that, nat?"(+":null, nat?")":null, this);
}
@Override public void visit(final Tree.EqualOp that) {
if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) {
//Try to use equals() if it exists
String ltmp = names.createTempVariable();
String rtmp = names.createTempVariable();
out("(", ltmp, "=");
box(that.getLeftTerm());
out(",", rtmp, "=");
box(that.getRightTerm());
out(",(", ltmp, ".equals&&", ltmp, ".equals(", rtmp, "))||", ltmp, "===", rtmp, ")");
} else {
final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm());
Operators.simpleBinaryOp(that, usenat?"((":null, usenat?").valueOf()==(":".equals(",
usenat?").valueOf())":")", this);
}
}
@Override public void visit(final Tree.NotEqualOp that) {
if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) {
//Try to use equals() if it exists
String ltmp = names.createTempVariable();
String rtmp = names.createTempVariable();
out("(", ltmp, "=");
box(that.getLeftTerm());
out(",", rtmp, "=");
box(that.getRightTerm());
out(",(", ltmp, ".equals&&!", ltmp, ".equals(", rtmp, "))||", ltmp, "!==", rtmp, ")");
} else {
final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm());
Operators.simpleBinaryOp(that, usenat?"!(":"(!", usenat?"==":".equals(", usenat?")":"))", this);
}
}
@Override public void visit(final Tree.NotOp that) {
final Term t = that.getTerm();
final boolean omitParens = t instanceof BaseMemberExpression
|| t instanceof QualifiedMemberExpression
|| t instanceof IsOp || t instanceof Exists || t instanceof IdenticalOp
|| t instanceof InOp || t instanceof Nonempty
|| (t instanceof InvocationExpression && ((InvocationExpression)t).getNamedArgumentList() == null);
if (omitParens) {
Operators.unaryOp(that, "!", null, this);
} else {
Operators.unaryOp(that, "(!", ")", this);
}
}
@Override public void visit(final Tree.IdenticalOp that) {
Operators.simpleBinaryOp(that, "(", "===", ")", this);
}
@Override public void visit(final Tree.CompareOp that) {
Operators.simpleBinaryOp(that, null, ".compare(", ")", this);
}
/** Returns true if both Terms' types is either Integer or Boolean. */
private boolean canUseNativeComparator(final Tree.Term left, final Tree.Term right) {
if (left == null || right == null || left.getTypeModel() == null || right.getTypeModel() == null) {
return false;
}
final ProducedType lt = left.getTypeModel();
final ProducedType rt = right.getTypeModel();
final TypeDeclaration intdecl = left.getUnit().getIntegerDeclaration();
final TypeDeclaration booldecl = left.getUnit().getBooleanDeclaration();
return (intdecl.equals(lt.getDeclaration()) && intdecl.equals(rt.getDeclaration()))
|| (booldecl.equals(lt.getDeclaration()) && booldecl.equals(rt.getDeclaration()));
}
@Override public void visit(final Tree.SmallerOp that) {
if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) {
//Try to use compare() if it exists
String ltmp = names.createTempVariable();
String rtmp = names.createTempVariable();
out("(", ltmp, "=");
box(that.getLeftTerm());
out(",", rtmp, "=");
box(that.getRightTerm());
out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(",
getClAlias(), "smaller()))||", ltmp, "<", rtmp, ")");
} else {
final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm());
if (usenat) {
Operators.simpleBinaryOp(that, "(", "<", ")", this);
} else {
Operators.simpleBinaryOp(that, null, ".compare(", ")", this);
out(".equals(", getClAlias(), "smaller())");
}
}
}
@Override public void visit(final Tree.LargerOp that) {
if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) {
//Try to use compare() if it exists
String ltmp = names.createTempVariable();
String rtmp = names.createTempVariable();
out("(", ltmp, "=");
box(that.getLeftTerm());
out(",", rtmp, "=");
box(that.getRightTerm());
out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ").equals(",
getClAlias(), "larger()))||", ltmp, ">", rtmp, ")");
} else {
final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm());
if (usenat) {
Operators.simpleBinaryOp(that, "(", ">", ")", this);
} else {
Operators.simpleBinaryOp(that, null, ".compare(", ")", this);
out(".equals(", getClAlias(), "larger())");
}
}
}
@Override public void visit(final Tree.SmallAsOp that) {
if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) {
//Try to use compare() if it exists
String ltmp = names.createTempVariable();
String rtmp = names.createTempVariable();
out("(", ltmp, "=");
box(that.getLeftTerm());
out(",", rtmp, "=");
box(that.getRightTerm());
out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==",
getClAlias(), "larger())||", ltmp, "<=", rtmp, ")");
} else {
final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm());
if (usenat) {
Operators.simpleBinaryOp(that, "(", "<=", ")", this);
} else {
out("(");
Operators.simpleBinaryOp(that, null, ".compare(", ")", this);
out("!==", getClAlias(), "larger()");
out(")");
}
}
}
@Override public void visit(final Tree.LargeAsOp that) {
if (dynblock > 0 && Util.isTypeUnknown(that.getLeftTerm().getTypeModel())) {
//Try to use compare() if it exists
String ltmp = names.createTempVariable();
String rtmp = names.createTempVariable();
out("(", ltmp, "=");
box(that.getLeftTerm());
out(",", rtmp, "=");
box(that.getRightTerm());
out(",(", ltmp, ".compare&&", ltmp, ".compare(", rtmp, ")!==",
getClAlias(), "smaller())||", ltmp, ">=", rtmp, ")");
} else {
final boolean usenat = canUseNativeComparator(that.getLeftTerm(), that.getRightTerm());
if (usenat) {
Operators.simpleBinaryOp(that, "(", ">=", ")", this);
} else {
out("(");
Operators.simpleBinaryOp(that, null, ".compare(", ")", this);
out("!==", getClAlias(), "smaller()");
out(")");
}
}
}
public void visit(final Tree.WithinOp that) {
final String ttmp = names.createTempVariable();
out("(", ttmp, "=");
box(that.getTerm());
out(",");
if (dynblock > 0 && Util.isTypeUnknown(that.getTerm().getTypeModel())) {
final String tmpl = names.createTempVariable();
final String tmpu = names.createTempVariable();
out(tmpl, "=");
box(that.getLowerBound().getTerm());
out(",", tmpu, "=");
box(that.getUpperBound().getTerm());
out(",((", ttmp, ".compare&&",ttmp,".compare(", tmpl);
if (that.getLowerBound() instanceof Tree.OpenBound) {
out(")===", getClAlias(), "larger())||", ttmp, ">", tmpl, ")");
} else {
out(")!==", getClAlias(), "smaller())||", ttmp, ">=", tmpl, ")");
}
out("&&((", ttmp, ".compare&&",ttmp,".compare(", tmpu);
if (that.getUpperBound() instanceof Tree.OpenBound) {
out(")===", getClAlias(), "smaller())||", ttmp, "<", tmpu, ")");
} else {
out(")!==", getClAlias(), "larger())||", ttmp, "<=", tmpu, ")");
}
} else {
out(ttmp, ".compare(");
box(that.getLowerBound().getTerm());
if (that.getLowerBound() instanceof Tree.OpenBound) {
out(")===", getClAlias(), "larger()");
} else {
out(")!==", getClAlias(), "smaller()");
}
out("&&");
out(ttmp, ".compare(");
box(that.getUpperBound().getTerm());
if (that.getUpperBound() instanceof Tree.OpenBound) {
out(")===", getClAlias(), "smaller()");
} else {
out(")!==", getClAlias(), "larger()");
}
}
out(")");
}
@Override public void visit(final Tree.AndOp that) {
Operators.simpleBinaryOp(that, "(", "&&", ")", this);
}
@Override public void visit(final Tree.OrOp that) {
Operators.simpleBinaryOp(that, "(", "||", ")", this);
}
@Override public void visit(final Tree.EntryOp that) {
out(getClAlias(), "Entry(");
Operators.genericBinaryOp(that, ",", that.getTypeModel().getTypeArguments(),
that.getTypeModel().getVarianceOverrides(), this);
}
@Override public void visit(final Tree.RangeOp that) {
out(getClAlias(), "span(");
that.getLeftTerm().visit(this);
out(",");
that.getRightTerm().visit(this);
out(",{Element$span:");
TypeUtils.typeNameOrList(that,
Util.unionType(that.getLeftTerm().getTypeModel(), that.getRightTerm().getTypeModel(), that.getUnit()),
this, false);
out("})");
}
@Override
public void visit(final Tree.SegmentOp that) {
final Tree.Term left = that.getLeftTerm();
final Tree.Term right = that.getRightTerm();
out(getClAlias(), "measure(");
left.visit(this);
out(",");
right.visit(this);
out(",{Element$measure:");
TypeUtils.typeNameOrList(that,
Util.unionType(left.getTypeModel(), right.getTypeModel(), that.getUnit()),
this, false);
out("})");
}
@Override public void visit(final Tree.ThenOp that) {
Operators.simpleBinaryOp(that, "(", "?", ":null)", this);
}
@Override public void visit(final Tree.Element that) {
out(".$_get(");
if (!isNaturalLiteral(that.getExpression().getTerm())) {
that.getExpression().visit(this);
}
out(")");
}
@Override public void visit(final Tree.DefaultOp that) {
String lhsVar = createRetainedTempVar();
out("(", lhsVar, "=");
box(that.getLeftTerm());
out(",", getClAlias(), "nn$(", lhsVar, ")?", lhsVar, ":");
box(that.getRightTerm());
out(")");
}
@Override public void visit(final Tree.IncrementOp that) {
Operators.prefixIncrementOrDecrement(that.getTerm(), "successor", this);
}
@Override public void visit(final Tree.DecrementOp that) {
Operators.prefixIncrementOrDecrement(that.getTerm(), "predecessor", this);
}
boolean hasSimpleGetterSetter(Declaration decl) {
return (dynblock > 0 && TypeUtils.isUnknown(decl)) ||
!((decl instanceof Value && ((Value)decl).isTransient()) || (decl instanceof Setter) || decl.isFormal());
}
@Override public void visit(final Tree.PostfixIncrementOp that) {
Operators.postfixIncrementOrDecrement(that.getTerm(), "successor", this);
}
@Override public void visit(final Tree.PostfixDecrementOp that) {
Operators.postfixIncrementOrDecrement(that.getTerm(), "predecessor", this);
}
@Override
public void visit(final Tree.UnionOp that) {
Operators.genericBinaryOp(that, ".union(",
TypeUtils.mapTypeArgument(that, "union", "Element", "Other"),
that.getTypeModel().getVarianceOverrides(), this);
}
@Override
public void visit(final Tree.IntersectionOp that) {
Operators.genericBinaryOp(that, ".intersection(",
TypeUtils.mapTypeArgument(that, "intersection", "Element", "Other"),
that.getTypeModel().getVarianceOverrides(), this);
}
@Override
public void visit(final Tree.ComplementOp that) {
Operators.genericBinaryOp(that, ".complement(",
TypeUtils.mapTypeArgument(that, "complement", "Element", "Other"),
that.getTypeModel().getVarianceOverrides(), this);
}
@Override public void visit(final Tree.Exists that) {
Operators.unaryOp(that, getClAlias()+"nn$(", ")", this);
}
@Override public void visit(final Tree.Nonempty that) {
Operators.unaryOp(that, getClAlias()+"ne$(", ")", this);
}
//Don't know if we'll ever see this...
@Override public void visit(final Tree.ConditionList that) {
spitOut("ZOMG condition list in the wild! " + that.getLocation()
+ " of " + that.getUnit().getFilename());
super.visit(that);
}
@Override public void visit(final Tree.BooleanCondition that) {
int boxType = boxStart(that.getExpression().getTerm());
super.visit(that);
if (boxType == 4) out("/*TODO: callable targs 10*/");
boxUnboxEnd(boxType);
}
@Override public void visit(final Tree.IfStatement that) {
if (errVisitor.hasErrors(that))return;
conds.generateIf(that);
}
@Override public void visit(final Tree.IfExpression that) {
if (errVisitor.hasErrors(that))return;
conds.generateIfExpression(that, false);
}
@Override public void visit(final Tree.WhileStatement that) {
conds.generateWhile(that);
}
/** Generates js code to check if a term is of a certain type. We solve this in JS by
* checking against all types that Type satisfies (in the case of union types, matching any
* type will do, and in case of intersection types, all types must be matched).
* @param term The term that is to be checked against a type
* @param termString (optional) a string to be used as the term to be checked
* @param type The type to check against
* @param tmpvar (optional) a variable to which the term is assigned
* @param negate If true, negates the generated condition
*/
void generateIsOfType(Node term, String termString, final ProducedType type, String tmpvar, final boolean negate) {
if (negate) {
out("!");
}
out(getClAlias(), "is$(");
if (term instanceof Term) {
conds.specialConditionRHS((Term)term, tmpvar);
} else {
conds.specialConditionRHS(termString, tmpvar);
}
out(",");
TypeUtils.typeNameOrList(term, type, this, false);
if (type.getQualifyingType() != null) {
out(",[");
ProducedType outer = type.getQualifyingType();
boolean first=true;
while (outer != null) {
if (first) {
first=false;
} else{
out(",");
}
TypeUtils.typeNameOrList(term, outer, this, false);
outer = outer.getQualifyingType();
}
out("]");
} else if (type.getDeclaration() != null && type.getDeclaration().getContainer() != null) {
Declaration d = Util.getContainingDeclarationOfScope(type.getDeclaration().getContainer());
if (d != null && d instanceof Method && !((Method)d).getTypeParameters().isEmpty()) {
out(",$$$mptypes");
}
}
out(")");
}
@Override
public void visit(final Tree.IsOp that) {
generateIsOfType(that.getTerm(), null, that.getType().getTypeModel(), null, false);
}
@Override public void visit(final Tree.Break that) {
if (continues.isEmpty()) {
out("break;");
} else {
Continuation top=continues.peek();
if (that.getScope()==top.getScope()) {
top.useBreak();
out(top.getBreakName(), "=true; return;");
} else {
out("break;");
}
}
}
@Override public void visit(final Tree.Continue that) {
if (continues.isEmpty()) {
out("continue;");
} else {
Continuation top=continues.peek();
if (that.getScope()==top.getScope()) {
top.useContinue();
out(top.getContinueName(), "=true; return;");
} else {
out("continue;");
}
}
}
@Override public void visit(final Tree.ForStatement that) {
if (errVisitor.hasErrors(that))return;
new ForGenerator(this, directAccess).generate(that);
}
public void visit(final Tree.InOp that) {
box(that.getRightTerm());
out(".contains(");
if (!isNaturalLiteral(that.getLeftTerm())) {
box(that.getLeftTerm());
}
out(")");
}
@Override public void visit(final Tree.TryCatchStatement that) {
if (errVisitor.hasErrors(that))return;
new TryCatchGenerator(this, directAccess).generate(that);
}
@Override public void visit(final Tree.Throw that) {
out("throw ", getClAlias(), "wrapexc(");
if (that.getExpression() == null) {
out(getClAlias(), "Exception()");
} else {
that.getExpression().visit(this);
}
that.getUnit().getFullPath();
out(",'", that.getLocation(), "','", that.getUnit().getRelativePath(), "');");
}
private void visitIndex(final Tree.IndexExpression that) {
that.getPrimary().visit(this);
ElementOrRange eor = that.getElementOrRange();
if (eor instanceof Element) {
final Tree.Expression _elemexpr = ((Tree.Element)eor).getExpression();
final String _end;
if (Util.isTypeUnknown(that.getPrimary().getTypeModel()) && dynblock > 0) {
out("[");
_end = "]";
} else {
out(".$_get(");
_end = ")";
}
if (!isNaturalLiteral(_elemexpr.getTerm())) {
_elemexpr.visit(this);
}
out(_end);
} else {//range, or spread?
ElementRange er = (ElementRange)eor;
Expression sexpr = er.getLength();
if (sexpr == null) {
if (er.getLowerBound() == null) {
out(".spanTo(");
} else if (er.getUpperBound() == null) {
out(".spanFrom(");
} else {
out(".span(");
}
} else {
out(".measure(");
}
if (er.getLowerBound() != null) {
if (!isNaturalLiteral(er.getLowerBound().getTerm())) {
er.getLowerBound().visit(this);
}
if (er.getUpperBound() != null || sexpr != null) {
out(",");
}
}
if (er.getUpperBound() != null) {
if (!isNaturalLiteral(er.getUpperBound().getTerm())) {
er.getUpperBound().visit(this);
}
} else if (sexpr != null) {
sexpr.visit(this);
}
out(")");
}
}
public void visit(final Tree.IndexExpression that) {
visitIndex(that);
}
@Override
public void visit(final Tree.SwitchStatement that) {
if (errVisitor.hasErrors(that))return;
if (opts.isComment() && !opts.isMinify()) {
out("//Switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")");
endLine();
}
conds.switchStatement(that);
if (opts.isComment() && !opts.isMinify()) {
out("//End switch statement at ", that.getUnit().getFilename(), " (", that.getLocation(), ")");
endLine();
}
}
@Override public void visit(final Tree.SwitchExpression that) {
conds.switchExpression(that);
}
/** Generates the code for an anonymous function defined inside an argument list. */
@Override
public void visit(final Tree.FunctionArgument that) {
if (errVisitor.hasErrors(that))return;
FunctionHelper.functionArgument(that, this);
}
public void visit(final Tree.SpecifiedArgument that) {
if (errVisitor.hasErrors(that))return;
int _box=0;
final Tree.SpecifierExpression expr = that.getSpecifierExpression();
if (that.getParameter() != null && expr != null) {
_box = boxUnboxStart(expr.getExpression().getTerm(), that.getParameter().getModel());
}
expr.visit(this);
if (_box == 4) {
out(",");
//Add parameters
invoker.describeMethodParameters(expr.getExpression().getTerm());
out(",");
TypeUtils.printTypeArguments(that, expr.getExpression().getTypeModel().getTypeArguments(), this, false,
expr.getExpression().getTypeModel().getVarianceOverrides());
}
boxUnboxEnd(_box);
}
/** Generates the code for a function in a named argument list. */
@Override
public void visit(final Tree.MethodArgument that) {
if (errVisitor.hasErrors(that))return;
FunctionHelper.methodArgument(that, this);
}
/** Determines whether the specified block should be enclosed in a function. */
public boolean shouldEncloseBlock(Block block) {
// just check if the block contains a captured declaration
for (Tree.Statement statement : block.getStatements()) {
if (statement instanceof Tree.Declaration) {
if (((Tree.Declaration) statement).getDeclarationModel().isCaptured()) {
return true;
}
}
}
return false;
}
/** Encloses the block in a function, IF NEEDED. */
void encloseBlockInFunction(final Tree.Block block, final boolean markBlock) {
final boolean wrap=shouldEncloseBlock(block);
if (wrap) {
if (markBlock)beginBlock();
Continuation c = new Continuation(block.getScope(), names);
continues.push(c);
out("var ", c.getContinueName(), "=false"); endLine(true);
out("var ", c.getBreakName(), "=false"); endLine(true);
out("var ", c.getReturnName(), "=(function()");
if (!markBlock)beginBlock();
}
if (markBlock) {
block.visit(this);
} else {
visitStatements(block.getStatements());
}
if (wrap) {
Continuation c = continues.pop();
if (!markBlock)endBlock();
out("());if(", c.getReturnName(), "!==undefined){return ", c.getReturnName(), ";}");
if (c.isContinued()) {
out("else if(", c.getContinueName(),"===true){continue;}");
}
if (c.isBreaked()) {
out("else if(", c.getBreakName(),"===true){break;}");
}
if (markBlock)endBlockNewLine();
}
}
private static class Continuation {
private final String cvar;
private final String rvar;
private final String bvar;
private final Scope scope;
private boolean cused, bused;
public Continuation(Scope scope, JsIdentifierNames names) {
this.scope=scope;
cvar = names.createTempVariable();
rvar = names.createTempVariable();
bvar = names.createTempVariable();
}
public Scope getScope() { return scope; }
public String getContinueName() { return cvar; }
public String getBreakName() { return bvar; }
public String getReturnName() { return rvar; }
public void useContinue() { cused = true; }
public void useBreak() { bused=true; }
public boolean isContinued() { return cused; }
public boolean isBreaked() { return bused; } //"isBroken" sounds really really bad in this case
}
/** This interface is used inside type initialization method. */
static interface PrototypeInitCallback {
/** Generates a function that adds members to a prototype, then calls it. */
void addToPrototypeCallback();
}
@Override
public void visit(final Tree.Tuple that) {
SequenceGenerator.tuple(that, this);
}
@Override
public void visit(final Tree.Assertion that) {
if (opts.isComment() && !opts.isMinify()) {
out("//assert");
location(that);
endLine();
}
String custom = "Assertion failed";
//Scan for a "doc" annotation with custom message
if (that.getAnnotationList() != null && that.getAnnotationList().getAnonymousAnnotation() != null) {
custom = that.getAnnotationList().getAnonymousAnnotation().getStringLiteral().getText();
} else {
for (Annotation ann : that.getAnnotationList().getAnnotations()) {
BaseMemberExpression bme = (BaseMemberExpression)ann.getPrimary();
if ("doc".equals(bme.getDeclaration().getName())) {
custom = ((Tree.ListedArgument)ann.getPositionalArgumentList().getPositionalArguments().get(0))
.getExpression().getTerm().getText();
}
}
}
StringBuilder sb = new StringBuilder(custom).append(": '");
for (int i = that.getConditionList().getToken().getTokenIndex()+1;
i < that.getConditionList().getEndToken().getTokenIndex(); i++) {
sb.append(tokens.get(i).getText());
}
sb.append("' at ").append(that.getUnit().getFilename()).append(" (").append(
that.getConditionList().getLocation()).append(")");
conds.specialConditionsAndBlock(that.getConditionList(), null, getClAlias()+"asrt$(");
//escape
out(",\"", JsUtils.escapeStringLiteral(sb.toString()), "\",'",that.getLocation(), "','",
that.getUnit().getFilename(), "');");
endLine();
}
@Override
public void visit(Tree.DynamicStatement that) {
dynblock++;
if (dynblock == 1 && !opts.isMinify()) {
if (opts.isComment()) {
out("/*BEG dynblock*/");
}
endLine();
}
for (Tree.Statement stmt : that.getDynamicClause().getBlock().getStatements()) {
stmt.visit(this);
}
if (dynblock == 1 && !opts.isMinify()) {
if (opts.isComment()) {
out("/*END dynblock*/");
}
endLine();
}
dynblock--;
}
public boolean isInDynamicBlock() {
return dynblock > 0;
}
@Override
public void visit(final Tree.TypeLiteral that) {
//Can be an alias, class, interface or type parameter
if (that.getWantsDeclaration()) {
MetamodelHelper.generateOpenType(that, that.getDeclaration(), this);
} else {
MetamodelHelper.generateClosedTypeLiteral(that, this);
}
}
@Override
public void visit(final Tree.MemberLiteral that) {
if (that.getWantsDeclaration()) {
MetamodelHelper.generateOpenType(that, that.getDeclaration(), this);
} else {
MetamodelHelper.generateMemberLiteral(that, this);
}
}
@Override
public void visit(final Tree.PackageLiteral that) {
com.redhat.ceylon.compiler.typechecker.model.Package pkg =
(com.redhat.ceylon.compiler.typechecker.model.Package)that.getImportPath().getModel();
MetamodelHelper.findModule(pkg.getModule(), this);
out(".findPackage('", pkg.getNameAsString(), "')");
}
@Override
public void visit(Tree.ModuleLiteral that) {
Module m = (Module)that.getImportPath().getModel();
MetamodelHelper.findModule(m, this);
}
/** Call internal function "throwexc" with the specified message and source location. */
void generateThrow(String exceptionClass, String msg, Node node) {
out(getClAlias(), "throwexc(", exceptionClass==null ? getClAlias() + "Exception":exceptionClass, "(");
out("\"", JsUtils.escapeStringLiteral(msg), "\"),'", node.getLocation(), "','",
node.getUnit().getFilename(), "')");
}
@Override public void visit(Tree.CompilerAnnotation that) {
//just ignore this
}
/** Outputs the initial part of an attribute definition. */
void defineAttribute(final String owner, final String name) {
out(getClAlias(), "atr$(", owner, ",'", name, "',function()");
}
public int getExitCode() {
return exitCode;
}
@Override public void visit(Tree.ListedArgument that) {
if (!isNaturalLiteral(that.getExpression().getTerm())) {
super.visit(that);
}
}
@Override public void visit(Tree.LetExpression that) {
if (errVisitor.hasErrors(that))return;
FunctionHelper.generateLet(that, directAccess, this);
}
@Override public void visit(final Tree.Destructure that) {
if (errVisitor.hasErrors(that))return;
final String expvar = names.createTempVariable();
out("var ", expvar, "=");
that.getSpecifierExpression().visit(this);
new Destructurer(that.getPattern(), this, directAccess, expvar, false);
endLine(true);
}
boolean isNaturalLiteral(Tree.Term that) {
if (that instanceof Tree.NaturalLiteral) {
out(Long.toString(parseNaturalLiteral((Tree.NaturalLiteral)that)));
return true;
}
return false;
}
}
| Makes ure we ignore native methods and classes that are not for our backend (ceylon/ceylon-spec#500)
| src/main/java/com/redhat/ceylon/compiler/js/GenerateJsVisitor.java | Makes ure we ignore native methods and classes that are not for our backend (ceylon/ceylon-spec#500) |
|
Java | apache-2.0 | b60987cfe15f89ad8207a8cc4c5ac7e63c111a69 | 0 | jmmut/eva-pipeline,EBIvariation/eva-pipeline,cyenyxe/eva-pipeline,jmmut/eva-pipeline,jmmut/eva-pipeline,EBIvariation/eva-pipeline,cyenyxe/eva-pipeline,cyenyxe/eva-pipeline | /*
* Copyright 2016 EMBL - European Bioinformatics Institute
*
* 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 uk.ac.ebi.eva.pipeline.io.mappers;
import org.opencb.biodata.models.variant.VariantSource;
import org.springframework.batch.item.file.LineMapper;
import uk.ac.ebi.eva.commons.models.data.Variant;
import java.util.List;
import static org.junit.Assert.assertNotNull;
/**
* Maps a String (in VCF format) to a list of variants.
* <p>
* The actual implementation is reused from {@link VariantVcfFactory}.
*/
public class VcfLineMapper implements LineMapper<List<Variant>> {
private final String fileId;
private final String studyId;
private final VariantVcfFactory factory;
public VcfLineMapper(String fileId, String studyId) {
this.fileId = fileId;
this.studyId = studyId;
this.factory = new VariantVcfFactory();
}
@Override
public List<Variant> mapLine(String line, int lineNumber) {
return factory.create(fileId, studyId, line);
}
}
| src/main/java/uk/ac/ebi/eva/pipeline/io/mappers/VcfLineMapper.java | /*
* Copyright 2016 EMBL - European Bioinformatics Institute
*
* 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 uk.ac.ebi.eva.pipeline.io.mappers;
import org.opencb.biodata.models.variant.VariantSource;
import org.springframework.batch.item.file.LineMapper;
import uk.ac.ebi.eva.commons.models.data.Variant;
import java.util.List;
import static org.junit.Assert.assertNotNull;
/**
* Maps a String (in VCF format) to a list of variants.
* <p>
* The actual implementation is reused from {@link VariantVcfFactory}.
*/
public class VcfLineMapper implements LineMapper<List<Variant>> {
private final String fileId;
private final String studyId;
private final VariantVcfFactory factory;
public VcfLineMapper(String fileId, String studyId) {
this.fileId = fileId;
this.studyId = studyId;
this.factory = new VariantVcfFactory();
}
@Override
public List<Variant> mapLine(String line, int lineNumber) {
assertNotNull(this.getClass().getSimpleName() + " should be used to read genotyped VCFs only " +
"(hint: set VariantSource.Aggregation to NONE)", factory);
return factory.create(fileId, studyId, line);
}
}
| Removed unused asertion.
| src/main/java/uk/ac/ebi/eva/pipeline/io/mappers/VcfLineMapper.java | Removed unused asertion. |
|
Java | apache-2.0 | 557c59607fa9eb2014a7905cfc0eb3dbcd043cab | 0 | iamaleksey/cassandra,clohfink/cassandra,Instagram/cassandra,exoscale/cassandra,jasonstack/cassandra,beobal/cassandra,apache/cassandra,cooldoger/cassandra,sharvanath/cassandra,mike-tr-adamson/cassandra,Jollyplum/cassandra,ifesdjeen/cassandra,mambocab/cassandra,Instagram/cassandra,aboudreault/cassandra,thelastpickle/cassandra,ifesdjeen/cassandra,snazy/cassandra,scylladb/scylla-tools-java,blerer/cassandra,joesiewert/cassandra,sedulam/CASSANDRA-12201,pauloricardomg/cassandra,kgreav/cassandra,driftx/cassandra,josh-mckenzie/cassandra,tommystendahl/cassandra,bdeggleston/cassandra,sharvanath/cassandra,bmel/cassandra,joesiewert/cassandra,aboudreault/cassandra,scylladb/scylla-tools-java,aureagle/cassandra,mike-tr-adamson/cassandra,jasonwee/cassandra,Jaumo/cassandra,yhnishi/cassandra,tommystendahl/cassandra,Jollyplum/cassandra,krummas/cassandra,exoscale/cassandra,ptnapoleon/cassandra,thelastpickle/cassandra,bcoverston/cassandra,mambocab/cassandra,ifesdjeen/cassandra,hengxin/cassandra,stef1927/cassandra,jeffjirsa/cassandra,adejanovski/cassandra,blambov/cassandra,jeromatron/cassandra,iamaleksey/cassandra,jasobrown/cassandra,yukim/cassandra,mkjellman/cassandra,spodkowinski/cassandra,exoscale/cassandra,tjake/cassandra,jrwest/cassandra,thelastpickle/cassandra,ollie314/cassandra,michaelsembwever/cassandra,josh-mckenzie/cassandra,aweisberg/cassandra,jbellis/cassandra,mshuler/cassandra,spodkowinski/cassandra,jrwest/cassandra,carlyeks/cassandra,clohfink/cassandra,jasobrown/cassandra,strapdata/cassandra,thobbs/cassandra,mike-tr-adamson/cassandra,krummas/cassandra,szhou1234/cassandra,DikangGu/cassandra,driftx/cassandra,instaclustr/cassandra,bcoverston/cassandra,carlyeks/cassandra,apache/cassandra,hengxin/cassandra,driftx/cassandra,pauloricardomg/cassandra,Jaumo/cassandra,thelastpickle/cassandra,hengxin/cassandra,jrwest/cassandra,kgreav/cassandra,kgreav/cassandra,christian-esken/cassandra,jasobrown/cassandra,adelapena/cassandra,sedulam/CASSANDRA-12201,aureagle/cassandra,jasobrown/cassandra,modempachev4/kassandra,mshuler/cassandra,mike-tr-adamson/cassandra,jeromatron/cassandra,mkjellman/cassandra,spodkowinski/cassandra,jeffjirsa/cassandra,yukim/cassandra,kgreav/cassandra,modempachev4/kassandra,beobal/cassandra,iamaleksey/cassandra,WorksApplications/cassandra,instaclustr/cassandra,szhou1234/cassandra,jasonstack/cassandra,jeffjirsa/cassandra,belliottsmith/cassandra,clohfink/cassandra,bdeggleston/cassandra,Jaumo/cassandra,blerer/cassandra,scaledata/cassandra,pauloricardomg/cassandra,cooldoger/cassandra,tjake/cassandra,strapdata/cassandra,juiceblender/cassandra,joesiewert/cassandra,aweisberg/cassandra,modempachev4/kassandra,stef1927/cassandra,josh-mckenzie/cassandra,Instagram/cassandra,szhou1234/cassandra,cooldoger/cassandra,juiceblender/cassandra,aweisberg/cassandra,mkjellman/cassandra,michaelsembwever/cassandra,weideng1/cassandra,christian-esken/cassandra,strapdata/cassandra,weideng1/cassandra,ifesdjeen/cassandra,sharvanath/cassandra,christian-esken/cassandra,aureagle/cassandra,blerer/cassandra,vaibhi9/cassandra,apache/cassandra,ollie314/cassandra,juiceblender/cassandra,juiceblender/cassandra,cooldoger/cassandra,DikangGu/cassandra,belliottsmith/cassandra,belliottsmith/cassandra,hhorii/cassandra,chbatey/cassandra-1,blerer/cassandra,ptnapoleon/cassandra,tommystendahl/cassandra,tommystendahl/cassandra,ptnapoleon/cassandra,stef1927/cassandra,thobbs/cassandra,WorksApplications/cassandra,snazy/cassandra,scylladb/scylla-tools-java,blambov/cassandra,yukim/cassandra,hhorii/cassandra,adelapena/cassandra,mshuler/cassandra,adelapena/cassandra,sedulam/CASSANDRA-12201,apache/cassandra,bdeggleston/cassandra,jeromatron/cassandra,DikangGu/cassandra,jasonstack/cassandra,bmel/cassandra,bmel/cassandra,adejanovski/cassandra,jasonwee/cassandra,yukim/cassandra,krummas/cassandra,carlyeks/cassandra,tjake/cassandra,blambov/cassandra,mkjellman/cassandra,belliottsmith/cassandra,WorksApplications/cassandra,aweisberg/cassandra,bdeggleston/cassandra,krummas/cassandra,aboudreault/cassandra,iamaleksey/cassandra,strapdata/cassandra,jasonwee/cassandra,josh-mckenzie/cassandra,michaelsembwever/cassandra,beobal/cassandra,yhnishi/cassandra,scaledata/cassandra,WorksApplications/cassandra,adelapena/cassandra,hhorii/cassandra,jrwest/cassandra,snazy/cassandra,jeffjirsa/cassandra,driftx/cassandra,instaclustr/cassandra,spodkowinski/cassandra,adejanovski/cassandra,blambov/cassandra,bcoverston/cassandra,scaledata/cassandra,jbellis/cassandra,instaclustr/cassandra,thobbs/cassandra,scylladb/scylla-tools-java,snazy/cassandra,Jollyplum/cassandra,mshuler/cassandra,pauloricardomg/cassandra,michaelsembwever/cassandra,tjake/cassandra,bcoverston/cassandra,beobal/cassandra,ollie314/cassandra,szhou1234/cassandra,Instagram/cassandra,chbatey/cassandra-1,vaibhi9/cassandra,yhnishi/cassandra,vaibhi9/cassandra,mambocab/cassandra,chbatey/cassandra-1,stef1927/cassandra,clohfink/cassandra,jbellis/cassandra,weideng1/cassandra | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.db;
import java.io.*;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.common.annotations.VisibleForTesting;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.db.filter.ClusteringIndexFilter;
import org.apache.cassandra.db.filter.ColumnFilter;
import org.apache.cassandra.db.rows.*;
import org.apache.cassandra.db.partitions.*;
import org.apache.cassandra.dht.*;
import org.apache.cassandra.io.ForwardingVersionedSerializer;
import org.apache.cassandra.io.IVersionedSerializer;
import org.apache.cassandra.io.util.DataInputBuffer;
import org.apache.cassandra.io.util.DataInputPlus;
import org.apache.cassandra.io.util.DataOutputPlus;
import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.thrift.ThriftResultsMerger;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
public abstract class ReadResponse
{
// Serializer for single partition read response
public static final IVersionedSerializer<ReadResponse> serializer = new Serializer();
// Serializer for the pre-3.0 rang slice responses.
public static final IVersionedSerializer<ReadResponse> legacyRangeSliceReplySerializer = new LegacyRangeSliceReplySerializer();
// Serializer for partition range read response (this actually delegate to 'serializer' in 3.0 and to
// 'legacyRangeSliceReplySerializer' in older version.
public static final IVersionedSerializer<ReadResponse> rangeSliceSerializer = new ForwardingVersionedSerializer<ReadResponse>()
{
@Override
protected IVersionedSerializer<ReadResponse> delegate(int version)
{
return version < MessagingService.VERSION_30
? legacyRangeSliceReplySerializer
: serializer;
}
};
// This is used only when serializing data responses and we can't it easily in other cases. So this can be null, which is slighly
// hacky, but as this hack doesn't escape this class, and it's easy enough to validate that it's not null when we need, it's "good enough".
private final ReadCommand command;
protected ReadResponse(ReadCommand command)
{
this.command = command;
}
public static ReadResponse createDataResponse(UnfilteredPartitionIterator data, ReadCommand command)
{
return new LocalDataResponse(data, command);
}
@VisibleForTesting
public static ReadResponse createRemoteDataResponse(UnfilteredPartitionIterator data, ReadCommand command)
{
return new RemoteDataResponse(LocalDataResponse.build(data, command.columnFilter()));
}
public static ReadResponse createDigestResponse(UnfilteredPartitionIterator data, ReadCommand command)
{
return new DigestResponse(makeDigest(data, command));
}
public abstract UnfilteredPartitionIterator makeIterator(ReadCommand command);
public abstract ByteBuffer digest(ReadCommand command);
public abstract boolean isDigestResponse();
protected static ByteBuffer makeDigest(UnfilteredPartitionIterator iterator, ReadCommand command)
{
MessageDigest digest = FBUtilities.threadLocalMD5Digest();
UnfilteredPartitionIterators.digest(command, iterator, digest, command.digestVersion());
return ByteBuffer.wrap(digest.digest());
}
private static class DigestResponse extends ReadResponse
{
private final ByteBuffer digest;
private DigestResponse(ByteBuffer digest)
{
super(null);
assert digest.hasRemaining();
this.digest = digest;
}
public UnfilteredPartitionIterator makeIterator(ReadCommand command)
{
throw new UnsupportedOperationException();
}
public ByteBuffer digest(ReadCommand command)
{
// We assume that the digest is in the proper version, which bug excluded should be true since this is called with
// ReadCommand.digestVersion() as argument and that's also what we use to produce the digest in the first place.
// Validating it's the proper digest in this method would require sending back the digest version along with the
// digest which would waste bandwith for little gain.
return digest;
}
public boolean isDigestResponse()
{
return true;
}
}
// built on the owning node responding to a query
private static class LocalDataResponse extends DataResponse
{
private LocalDataResponse(UnfilteredPartitionIterator iter, ReadCommand command)
{
super(command, build(iter, command.columnFilter()), SerializationHelper.Flag.LOCAL);
}
private static ByteBuffer build(UnfilteredPartitionIterator iter, ColumnFilter selection)
{
try (DataOutputBuffer buffer = new DataOutputBuffer())
{
UnfilteredPartitionIterators.serializerForIntraNode().serialize(iter, selection, buffer, MessagingService.current_version);
return buffer.buffer();
}
catch (IOException e)
{
// We're serializing in memory so this shouldn't happen
throw new RuntimeException(e);
}
}
}
// built on the coordinator node receiving a response
private static class RemoteDataResponse extends DataResponse
{
protected RemoteDataResponse(ByteBuffer data)
{
super(null, data, SerializationHelper.Flag.FROM_REMOTE);
}
}
static abstract class DataResponse extends ReadResponse
{
// TODO: can the digest be calculated over the raw bytes now?
// The response, serialized in the current messaging version
private final ByteBuffer data;
private final SerializationHelper.Flag flag;
protected DataResponse(ReadCommand command, ByteBuffer data, SerializationHelper.Flag flag)
{
super(command);
this.data = data;
this.flag = flag;
}
public UnfilteredPartitionIterator makeIterator(ReadCommand command)
{
try (DataInputBuffer in = new DataInputBuffer(data, true))
{
// Note that the command parameter shadows the 'command' field and this is intended because
// the later can be null (for RemoteDataResponse as those are created in the serializers and
// those don't have easy access to the command). This is also why we need the command as parameter here.
return UnfilteredPartitionIterators.serializerForIntraNode().deserialize(in,
MessagingService.current_version,
command.metadata(),
command.columnFilter(),
flag);
}
catch (IOException e)
{
// We're deserializing in memory so this shouldn't happen
throw new RuntimeException(e);
}
}
public ByteBuffer digest(ReadCommand command)
{
try (UnfilteredPartitionIterator iterator = makeIterator(command))
{
return makeDigest(iterator, command);
}
}
public boolean isDigestResponse()
{
return false;
}
}
/**
* A remote response from a pre-3.0 node. This needs a separate class in order to cleanly handle trimming and
* reversal of results when the read command calls for it. Pre-3.0 nodes always return results in the normal
* sorted order, even if the query asks for reversed results. Additionally, pre-3.0 nodes do not have a notion of
* exclusive slices on non-composite tables, so extra rows may need to be trimmed.
*/
@VisibleForTesting
static class LegacyRemoteDataResponse extends ReadResponse
{
private final List<ImmutableBTreePartition> partitions;
@VisibleForTesting
LegacyRemoteDataResponse(List<ImmutableBTreePartition> partitions)
{
super(null); // we never serialize LegacyRemoteDataResponses, so we don't care about the command
this.partitions = partitions;
}
public UnfilteredPartitionIterator makeIterator(final ReadCommand command)
{
// Due to a bug in the serialization of AbstractBounds, anything that isn't a Range is understood by pre-3.0 nodes
// as a Bound, which means IncludingExcludingBounds and ExcludingBounds responses may include keys they shouldn't.
// So filter partitions that shouldn't be included here.
boolean skipFirst = false;
boolean skipLast = false;
if (!partitions.isEmpty() && command instanceof PartitionRangeReadCommand)
{
AbstractBounds<PartitionPosition> keyRange = ((PartitionRangeReadCommand)command).dataRange().keyRange();
boolean isExcludingBounds = keyRange instanceof ExcludingBounds;
skipFirst = isExcludingBounds && !keyRange.contains(partitions.get(0).partitionKey());
skipLast = (isExcludingBounds || keyRange instanceof IncludingExcludingBounds) && !keyRange.contains(partitions.get(partitions.size() - 1).partitionKey());
}
final List<ImmutableBTreePartition> toReturn;
if (skipFirst || skipLast)
{
toReturn = partitions.size() == 1
? Collections.emptyList()
: partitions.subList(skipFirst ? 1 : 0, skipLast ? partitions.size() - 1 : partitions.size());
}
else
{
toReturn = partitions;
}
return new AbstractUnfilteredPartitionIterator()
{
private int idx;
public boolean isForThrift()
{
return true;
}
public CFMetaData metadata()
{
return command.metadata();
}
public boolean hasNext()
{
return idx < toReturn.size();
}
public UnfilteredRowIterator next()
{
ImmutableBTreePartition partition = toReturn.get(idx++);
ClusteringIndexFilter filter = command.clusteringIndexFilter(partition.partitionKey());
// Pre-3.0, we didn't have a way to express exclusivity for non-composite comparators, so all slices were
// inclusive on both ends. If we have exclusive slice ends, we need to filter the results here.
UnfilteredRowIterator iterator;
if (!command.metadata().isCompound())
iterator = filter.filter(partition.sliceableUnfilteredIterator(command.columnFilter(), filter.isReversed()));
else
iterator = partition.unfilteredIterator(command.columnFilter(), Slices.ALL, filter.isReversed());
// Wrap results with a ThriftResultMerger only if they're intended for the thrift command.
if (command.isForThrift())
return ThriftResultsMerger.maybeWrap(iterator, command.nowInSec());
else
return iterator;
}
};
}
public ByteBuffer digest(ReadCommand command)
{
try (UnfilteredPartitionIterator iterator = makeIterator(command))
{
return makeDigest(iterator, command);
}
}
public boolean isDigestResponse()
{
return false;
}
}
private static class Serializer implements IVersionedSerializer<ReadResponse>
{
public void serialize(ReadResponse response, DataOutputPlus out, int version) throws IOException
{
boolean isDigest = response instanceof DigestResponse;
ByteBuffer digest = isDigest ? ((DigestResponse)response).digest : ByteBufferUtil.EMPTY_BYTE_BUFFER;
if (version < MessagingService.VERSION_30)
{
out.writeInt(digest.remaining());
out.write(digest);
out.writeBoolean(isDigest);
if (!isDigest)
{
assert response.command != null; // we only serialize LocalDataResponse, which always has the command set
try (UnfilteredPartitionIterator iter = response.makeIterator(response.command))
{
assert iter.hasNext();
try (UnfilteredRowIterator partition = iter.next())
{
ByteBufferUtil.writeWithShortLength(partition.partitionKey().getKey(), out);
LegacyLayout.serializeAsLegacyPartition(response.command, partition, out, version);
}
assert !iter.hasNext();
}
}
return;
}
ByteBufferUtil.writeWithVIntLength(digest, out);
if (!isDigest)
{
ByteBuffer data = ((DataResponse)response).data;
ByteBufferUtil.writeWithVIntLength(data, out);
}
}
public ReadResponse deserialize(DataInputPlus in, int version) throws IOException
{
if (version < MessagingService.VERSION_30)
{
byte[] digest = null;
int digestSize = in.readInt();
if (digestSize > 0)
{
digest = new byte[digestSize];
in.readFully(digest, 0, digestSize);
}
boolean isDigest = in.readBoolean();
assert isDigest == digestSize > 0;
if (isDigest)
{
assert digest != null;
return new DigestResponse(ByteBuffer.wrap(digest));
}
// ReadResponses from older versions are always single-partition (ranges are handled by RangeSliceReply)
ByteBuffer key = ByteBufferUtil.readWithShortLength(in);
try (UnfilteredRowIterator rowIterator = LegacyLayout.deserializeLegacyPartition(in, version, SerializationHelper.Flag.FROM_REMOTE, key))
{
if (rowIterator == null)
return new LegacyRemoteDataResponse(Collections.emptyList());
return new LegacyRemoteDataResponse(Collections.singletonList(ImmutableBTreePartition.create(rowIterator)));
}
}
ByteBuffer digest = ByteBufferUtil.readWithVIntLength(in);
if (digest.hasRemaining())
return new DigestResponse(digest);
assert version == MessagingService.VERSION_30;
ByteBuffer data = ByteBufferUtil.readWithVIntLength(in);
return new RemoteDataResponse(data);
}
public long serializedSize(ReadResponse response, int version)
{
boolean isDigest = response instanceof DigestResponse;
ByteBuffer digest = isDigest ? ((DigestResponse)response).digest : ByteBufferUtil.EMPTY_BYTE_BUFFER;
if (version < MessagingService.VERSION_30)
{
long size = TypeSizes.sizeof(digest.remaining())
+ digest.remaining()
+ TypeSizes.sizeof(isDigest);
if (!isDigest)
{
assert response.command != null; // we only serialize LocalDataResponse, which always has the command set
try (UnfilteredPartitionIterator iter = response.makeIterator(response.command))
{
assert iter.hasNext();
try (UnfilteredRowIterator partition = iter.next())
{
size += ByteBufferUtil.serializedSizeWithShortLength(partition.partitionKey().getKey());
size += LegacyLayout.serializedSizeAsLegacyPartition(response.command, partition, version);
}
assert !iter.hasNext();
}
}
return size;
}
long size = ByteBufferUtil.serializedSizeWithVIntLength(digest);
if (!isDigest)
{
// Note that we can only get there if version == 3.0, which is the current_version. When we'll change the
// version, we'll have to deserialize/re-serialize the data to be in the proper version.
assert version == MessagingService.VERSION_30;
ByteBuffer data = ((DataResponse)response).data;
size += ByteBufferUtil.serializedSizeWithVIntLength(data);
}
return size;
}
}
private static class LegacyRangeSliceReplySerializer implements IVersionedSerializer<ReadResponse>
{
public void serialize(ReadResponse response, DataOutputPlus out, int version) throws IOException
{
assert version < MessagingService.VERSION_30;
// determine the number of partitions upfront for serialization
int numPartitions = 0;
assert response.command != null; // we only serialize LocalDataResponse, which always has the command set
try (UnfilteredPartitionIterator iterator = response.makeIterator(response.command))
{
while (iterator.hasNext())
{
try (UnfilteredRowIterator atomIterator = iterator.next())
{
numPartitions++;
// we have to fully exhaust the subiterator
while (atomIterator.hasNext())
atomIterator.next();
}
}
}
out.writeInt(numPartitions);
try (UnfilteredPartitionIterator iterator = response.makeIterator(response.command))
{
while (iterator.hasNext())
{
try (UnfilteredRowIterator partition = iterator.next())
{
ByteBufferUtil.writeWithShortLength(partition.partitionKey().getKey(), out);
LegacyLayout.serializeAsLegacyPartition(response.command, partition, out, version);
}
}
}
}
public ReadResponse deserialize(DataInputPlus in, int version) throws IOException
{
assert version < MessagingService.VERSION_30;
int partitionCount = in.readInt();
ArrayList<ImmutableBTreePartition> partitions = new ArrayList<>(partitionCount);
for (int i = 0; i < partitionCount; i++)
{
ByteBuffer key = ByteBufferUtil.readWithShortLength(in);
try (UnfilteredRowIterator partition = LegacyLayout.deserializeLegacyPartition(in, version, SerializationHelper.Flag.FROM_REMOTE, key))
{
partitions.add(ImmutableBTreePartition.create(partition));
}
}
return new LegacyRemoteDataResponse(partitions);
}
public long serializedSize(ReadResponse response, int version)
{
assert version < MessagingService.VERSION_30;
long size = TypeSizes.sizeof(0); // number of partitions
assert response.command != null; // we only serialize LocalDataResponse, which always has the command set
try (UnfilteredPartitionIterator iterator = response.makeIterator(response.command))
{
while (iterator.hasNext())
{
try (UnfilteredRowIterator partition = iterator.next())
{
size += ByteBufferUtil.serializedSizeWithShortLength(partition.partitionKey().getKey());
size += LegacyLayout.serializedSizeAsLegacyPartition(response.command, partition, version);
}
}
}
return size;
}
}
}
| src/java/org/apache/cassandra/db/ReadResponse.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.cassandra.db;
import java.io.*;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.google.common.annotations.VisibleForTesting;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.db.filter.ClusteringIndexFilter;
import org.apache.cassandra.db.filter.ColumnFilter;
import org.apache.cassandra.db.rows.*;
import org.apache.cassandra.db.partitions.*;
import org.apache.cassandra.dht.*;
import org.apache.cassandra.io.ForwardingVersionedSerializer;
import org.apache.cassandra.io.IVersionedSerializer;
import org.apache.cassandra.io.util.DataInputBuffer;
import org.apache.cassandra.io.util.DataInputPlus;
import org.apache.cassandra.io.util.DataOutputPlus;
import org.apache.cassandra.io.util.DataOutputBuffer;
import org.apache.cassandra.net.MessagingService;
import org.apache.cassandra.thrift.ThriftResultsMerger;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
public abstract class ReadResponse
{
// Serializer for single partition read response
public static final IVersionedSerializer<ReadResponse> serializer = new Serializer();
// Serializer for the pre-3.0 rang slice responses.
public static final IVersionedSerializer<ReadResponse> legacyRangeSliceReplySerializer = new LegacyRangeSliceReplySerializer();
// Serializer for partition range read response (this actually delegate to 'serializer' in 3.0 and to
// 'legacyRangeSliceReplySerializer' in older version.
public static final IVersionedSerializer<ReadResponse> rangeSliceSerializer = new ForwardingVersionedSerializer<ReadResponse>()
{
@Override
protected IVersionedSerializer<ReadResponse> delegate(int version)
{
return version < MessagingService.VERSION_30
? legacyRangeSliceReplySerializer
: serializer;
}
};
// This is used only when serializing data responses and we can't it easily in other cases. So this can be null, which is slighly
// hacky, but as this hack doesn't escape this class, and it's easy enough to validate that it's not null when we need, it's "good enough".
private final ReadCommand command;
protected ReadResponse(ReadCommand command)
{
this.command = command;
}
public static ReadResponse createDataResponse(UnfilteredPartitionIterator data, ReadCommand command)
{
return new LocalDataResponse(data, command);
}
@VisibleForTesting
public static ReadResponse createRemoteDataResponse(UnfilteredPartitionIterator data, ReadCommand command)
{
return new RemoteDataResponse(LocalDataResponse.build(data, command.columnFilter()));
}
public static ReadResponse createDigestResponse(UnfilteredPartitionIterator data, ReadCommand command)
{
return new DigestResponse(makeDigest(data, command));
}
public abstract UnfilteredPartitionIterator makeIterator(ReadCommand command);
public abstract ByteBuffer digest(ReadCommand command);
public abstract boolean isDigestResponse();
protected static ByteBuffer makeDigest(UnfilteredPartitionIterator iterator, ReadCommand command)
{
MessageDigest digest = FBUtilities.threadLocalMD5Digest();
UnfilteredPartitionIterators.digest(command, iterator, digest, command.digestVersion());
return ByteBuffer.wrap(digest.digest());
}
private static class DigestResponse extends ReadResponse
{
private final ByteBuffer digest;
private DigestResponse(ByteBuffer digest)
{
super(null);
assert digest.hasRemaining();
this.digest = digest;
}
public UnfilteredPartitionIterator makeIterator(ReadCommand command)
{
throw new UnsupportedOperationException();
}
public ByteBuffer digest(ReadCommand command)
{
// We assume that the digest is in the proper version, which bug excluded should be true since this is called with
// ReadCommand.digestVersion() as argument and that's also what we use to produce the digest in the first place.
// Validating it's the proper digest in this method would require sending back the digest version along with the
// digest which would waste bandwith for little gain.
return digest;
}
public boolean isDigestResponse()
{
return true;
}
}
// built on the owning node responding to a query
private static class LocalDataResponse extends DataResponse
{
private LocalDataResponse(UnfilteredPartitionIterator iter, ReadCommand command)
{
super(command, build(iter, command.columnFilter()), SerializationHelper.Flag.LOCAL);
}
private static ByteBuffer build(UnfilteredPartitionIterator iter, ColumnFilter selection)
{
try (DataOutputBuffer buffer = new DataOutputBuffer())
{
UnfilteredPartitionIterators.serializerForIntraNode().serialize(iter, selection, buffer, MessagingService.current_version);
return buffer.buffer();
}
catch (IOException e)
{
// We're serializing in memory so this shouldn't happen
throw new RuntimeException(e);
}
}
}
// built on the coordinator node receiving a response
private static class RemoteDataResponse extends DataResponse
{
protected RemoteDataResponse(ByteBuffer data)
{
super(null, data, SerializationHelper.Flag.FROM_REMOTE);
}
}
static abstract class DataResponse extends ReadResponse
{
// TODO: can the digest be calculated over the raw bytes now?
// The response, serialized in the current messaging version
private final ByteBuffer data;
private final SerializationHelper.Flag flag;
protected DataResponse(ReadCommand command, ByteBuffer data, SerializationHelper.Flag flag)
{
super(command);
this.data = data;
this.flag = flag;
}
public UnfilteredPartitionIterator makeIterator(ReadCommand command)
{
try (DataInputBuffer in = new DataInputBuffer(data, true))
{
// Note that the command parameter shadows the 'command' field and this is intended because
// the later can be null (for RemoteDataResponse as those are created in the serializers and
// those don't have easy access to the command). This is also why we need the command as parameter here.
return UnfilteredPartitionIterators.serializerForIntraNode().deserialize(in,
MessagingService.current_version,
command.metadata(),
command.columnFilter(),
flag);
}
catch (IOException e)
{
// We're deserializing in memory so this shouldn't happen
throw new RuntimeException(e);
}
}
public ByteBuffer digest(ReadCommand command)
{
try (UnfilteredPartitionIterator iterator = makeIterator(command))
{
return makeDigest(iterator, command);
}
}
public boolean isDigestResponse()
{
return false;
}
}
/**
* A remote response from a pre-3.0 node. This needs a separate class in order to cleanly handle trimming and
* reversal of results when the read command calls for it. Pre-3.0 nodes always return results in the normal
* sorted order, even if the query asks for reversed results. Additionally, pre-3.0 nodes do not have a notion of
* exclusive slices on non-composite tables, so extra rows may need to be trimmed.
*/
@VisibleForTesting
static class LegacyRemoteDataResponse extends ReadResponse
{
private final List<ImmutableBTreePartition> partitions;
@VisibleForTesting
LegacyRemoteDataResponse(List<ImmutableBTreePartition> partitions)
{
super(null); // we never serialize LegacyRemoteDataResponses, so we don't care about the command
this.partitions = partitions;
}
public UnfilteredPartitionIterator makeIterator(final ReadCommand command)
{
// Due to a bug in the serialization of AbstractBounds, anything that isn't a Range is understood by pre-3.0 nodes
// as a Bound, which means IncludingExcludingBounds and ExcludingBounds responses may include keys they shouldn't.
// So filter partitions that shouldn't be included here.
boolean skipFirst = false;
boolean skipLast = false;
if (!partitions.isEmpty() && command instanceof PartitionRangeReadCommand)
{
AbstractBounds<PartitionPosition> keyRange = ((PartitionRangeReadCommand)command).dataRange().keyRange();
boolean isExcludingBounds = keyRange instanceof ExcludingBounds;
skipFirst = isExcludingBounds && !keyRange.contains(partitions.get(0).partitionKey());
skipLast = (isExcludingBounds || keyRange instanceof IncludingExcludingBounds) && !keyRange.contains(partitions.get(partitions.size() - 1).partitionKey());
}
final List<ImmutableBTreePartition> toReturn;
if (skipFirst || skipLast)
{
toReturn = partitions.size() == 1
? Collections.emptyList()
: partitions.subList(skipFirst ? 1 : 0, skipLast ? partitions.size() - 1 : partitions.size());
}
else
{
toReturn = partitions;
}
return new AbstractUnfilteredPartitionIterator()
{
private int idx;
public boolean isForThrift()
{
return true;
}
public CFMetaData metadata()
{
return command.metadata();
}
public boolean hasNext()
{
return idx < toReturn.size();
}
public UnfilteredRowIterator next()
{
ImmutableBTreePartition partition = toReturn.get(idx++);
ClusteringIndexFilter filter = command.clusteringIndexFilter(partition.partitionKey());
// Pre-3.0, we didn't have a way to express exclusivity for non-composite comparators, so all slices were
// inclusive on both ends. If we have exclusive slice ends, we need to filter the results here.
if (!command.metadata().isCompound())
return ThriftResultsMerger.maybeWrap(
filter.filter(partition.sliceableUnfilteredIterator(command.columnFilter(), filter.isReversed())), command.nowInSec());
return ThriftResultsMerger.maybeWrap(
partition.unfilteredIterator(command.columnFilter(), Slices.ALL, filter.isReversed()), command.nowInSec());
}
};
}
public ByteBuffer digest(ReadCommand command)
{
try (UnfilteredPartitionIterator iterator = makeIterator(command))
{
return makeDigest(iterator, command);
}
}
public boolean isDigestResponse()
{
return false;
}
}
private static class Serializer implements IVersionedSerializer<ReadResponse>
{
public void serialize(ReadResponse response, DataOutputPlus out, int version) throws IOException
{
boolean isDigest = response instanceof DigestResponse;
ByteBuffer digest = isDigest ? ((DigestResponse)response).digest : ByteBufferUtil.EMPTY_BYTE_BUFFER;
if (version < MessagingService.VERSION_30)
{
out.writeInt(digest.remaining());
out.write(digest);
out.writeBoolean(isDigest);
if (!isDigest)
{
assert response.command != null; // we only serialize LocalDataResponse, which always has the command set
try (UnfilteredPartitionIterator iter = response.makeIterator(response.command))
{
assert iter.hasNext();
try (UnfilteredRowIterator partition = iter.next())
{
ByteBufferUtil.writeWithShortLength(partition.partitionKey().getKey(), out);
LegacyLayout.serializeAsLegacyPartition(response.command, partition, out, version);
}
assert !iter.hasNext();
}
}
return;
}
ByteBufferUtil.writeWithVIntLength(digest, out);
if (!isDigest)
{
ByteBuffer data = ((DataResponse)response).data;
ByteBufferUtil.writeWithVIntLength(data, out);
}
}
public ReadResponse deserialize(DataInputPlus in, int version) throws IOException
{
if (version < MessagingService.VERSION_30)
{
byte[] digest = null;
int digestSize = in.readInt();
if (digestSize > 0)
{
digest = new byte[digestSize];
in.readFully(digest, 0, digestSize);
}
boolean isDigest = in.readBoolean();
assert isDigest == digestSize > 0;
if (isDigest)
{
assert digest != null;
return new DigestResponse(ByteBuffer.wrap(digest));
}
// ReadResponses from older versions are always single-partition (ranges are handled by RangeSliceReply)
ByteBuffer key = ByteBufferUtil.readWithShortLength(in);
try (UnfilteredRowIterator rowIterator = LegacyLayout.deserializeLegacyPartition(in, version, SerializationHelper.Flag.FROM_REMOTE, key))
{
if (rowIterator == null)
return new LegacyRemoteDataResponse(Collections.emptyList());
return new LegacyRemoteDataResponse(Collections.singletonList(ImmutableBTreePartition.create(rowIterator)));
}
}
ByteBuffer digest = ByteBufferUtil.readWithVIntLength(in);
if (digest.hasRemaining())
return new DigestResponse(digest);
assert version == MessagingService.VERSION_30;
ByteBuffer data = ByteBufferUtil.readWithVIntLength(in);
return new RemoteDataResponse(data);
}
public long serializedSize(ReadResponse response, int version)
{
boolean isDigest = response instanceof DigestResponse;
ByteBuffer digest = isDigest ? ((DigestResponse)response).digest : ByteBufferUtil.EMPTY_BYTE_BUFFER;
if (version < MessagingService.VERSION_30)
{
long size = TypeSizes.sizeof(digest.remaining())
+ digest.remaining()
+ TypeSizes.sizeof(isDigest);
if (!isDigest)
{
assert response.command != null; // we only serialize LocalDataResponse, which always has the command set
try (UnfilteredPartitionIterator iter = response.makeIterator(response.command))
{
assert iter.hasNext();
try (UnfilteredRowIterator partition = iter.next())
{
size += ByteBufferUtil.serializedSizeWithShortLength(partition.partitionKey().getKey());
size += LegacyLayout.serializedSizeAsLegacyPartition(response.command, partition, version);
}
assert !iter.hasNext();
}
}
return size;
}
long size = ByteBufferUtil.serializedSizeWithVIntLength(digest);
if (!isDigest)
{
// Note that we can only get there if version == 3.0, which is the current_version. When we'll change the
// version, we'll have to deserialize/re-serialize the data to be in the proper version.
assert version == MessagingService.VERSION_30;
ByteBuffer data = ((DataResponse)response).data;
size += ByteBufferUtil.serializedSizeWithVIntLength(data);
}
return size;
}
}
private static class LegacyRangeSliceReplySerializer implements IVersionedSerializer<ReadResponse>
{
public void serialize(ReadResponse response, DataOutputPlus out, int version) throws IOException
{
assert version < MessagingService.VERSION_30;
// determine the number of partitions upfront for serialization
int numPartitions = 0;
assert response.command != null; // we only serialize LocalDataResponse, which always has the command set
try (UnfilteredPartitionIterator iterator = response.makeIterator(response.command))
{
while (iterator.hasNext())
{
try (UnfilteredRowIterator atomIterator = iterator.next())
{
numPartitions++;
// we have to fully exhaust the subiterator
while (atomIterator.hasNext())
atomIterator.next();
}
}
}
out.writeInt(numPartitions);
try (UnfilteredPartitionIterator iterator = response.makeIterator(response.command))
{
while (iterator.hasNext())
{
try (UnfilteredRowIterator partition = iterator.next())
{
ByteBufferUtil.writeWithShortLength(partition.partitionKey().getKey(), out);
LegacyLayout.serializeAsLegacyPartition(response.command, partition, out, version);
}
}
}
}
public ReadResponse deserialize(DataInputPlus in, int version) throws IOException
{
assert version < MessagingService.VERSION_30;
int partitionCount = in.readInt();
ArrayList<ImmutableBTreePartition> partitions = new ArrayList<>(partitionCount);
for (int i = 0; i < partitionCount; i++)
{
ByteBuffer key = ByteBufferUtil.readWithShortLength(in);
try (UnfilteredRowIterator partition = LegacyLayout.deserializeLegacyPartition(in, version, SerializationHelper.Flag.FROM_REMOTE, key))
{
partitions.add(ImmutableBTreePartition.create(partition));
}
}
return new LegacyRemoteDataResponse(partitions);
}
public long serializedSize(ReadResponse response, int version)
{
assert version < MessagingService.VERSION_30;
long size = TypeSizes.sizeof(0); // number of partitions
assert response.command != null; // we only serialize LocalDataResponse, which always has the command set
try (UnfilteredPartitionIterator iterator = response.makeIterator(response.command))
{
while (iterator.hasNext())
{
try (UnfilteredRowIterator partition = iterator.next())
{
size += ByteBufferUtil.serializedSizeWithShortLength(partition.partitionKey().getKey());
size += LegacyLayout.serializedSizeAsLegacyPartition(response.command, partition, version);
}
}
}
return size;
}
}
}
| Avoid wrapping results with ThriftResultsMerger if command is not for thrift
Patch by Alex Petrov; reviewed by Tyler Hobbs for CASSANDRA-12193.
| src/java/org/apache/cassandra/db/ReadResponse.java | Avoid wrapping results with ThriftResultsMerger if command is not for thrift |
|
Java | apache-2.0 | bf4688d143b323e6d87ae94f493f6df122b95362 | 0 | jenmalloy/enmasse,jenmalloy/enmasse,EnMasseProject/enmasse,jenmalloy/enmasse,jenmalloy/enmasse,EnMasseProject/enmasse,EnMasseProject/enmasse,EnMasseProject/enmasse,jenmalloy/enmasse,EnMasseProject/enmasse,jenmalloy/enmasse,EnMasseProject/enmasse,EnMasseProject/enmasse,jenmalloy/enmasse | package io.enmasse.systemtest.authz;
import io.enmasse.systemtest.*;
import io.enmasse.systemtest.amqp.AmqpClient;
import org.apache.qpid.proton.message.Message;
import org.junit.Before;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public abstract class AuthorizationTestBase extends TestBaseWithDefault {
private static final Destination queue = Destination.queue("authz-queue");
private static final Destination topic = Destination.topic("authz-topic");
private static final Destination anycast = Destination.anycast("authz-anycast");
private static final Destination multicast = Destination.multicast("authz-multicast");
@Before
public void initAddresses() throws Exception {
List<Destination> addresses = new ArrayList<>();
addresses.add(queue);
addresses.add(topic);
if(getAddressSpaceType() == AddressSpaceType.STANDARD){
addresses.add(anycast);
addresses.add(multicast);
}
setAddresses(defaultAddressSpace, addresses.toArray(new Destination[0]));
}
protected void doTestSendAuthz() throws Exception {
KeycloakCredentials allowedUser = new KeycloakCredentials("sender", "senderPa55");
getKeycloakClient().createUser(defaultAddressSpace.getName(), allowedUser.getUsername(), allowedUser.getPassword(), Group.SEND_ALL.toString());
assertSend(allowedUser.getUsername(), allowedUser.getPassword());
getKeycloakClient().deleteUser(defaultAddressSpace.getName(), allowedUser.getUsername());
KeycloakCredentials noAllowedUser = new KeycloakCredentials("nobody", "nobodyPa55");
getKeycloakClient().createUser(defaultAddressSpace.getName(), noAllowedUser.getUsername(), noAllowedUser.getPassword(), "null");
assertCannotSend(noAllowedUser.getUsername(), noAllowedUser.getPassword());
getKeycloakClient().deleteUser(defaultAddressSpace.getName(), noAllowedUser.getUsername());
getKeycloakClient().createUser(defaultAddressSpace.getName(), noAllowedUser.getUsername(), noAllowedUser.getPassword(), Group.RECV_ALL.toString());
assertCannotSend(noAllowedUser.getUsername(), noAllowedUser.getPassword());
getKeycloakClient().deleteUser(defaultAddressSpace.getName(), noAllowedUser.getUsername());
}
protected void doTestReceiveAuthz() throws Exception {
KeycloakCredentials allowedUser = new KeycloakCredentials("receiver", "receiverPa55");
getKeycloakClient().createUser(defaultAddressSpace.getName(), allowedUser.getUsername(), allowedUser.getPassword(), Group.RECV_ALL.toString());
assertReceive(allowedUser.getUsername(), allowedUser.getPassword());
getKeycloakClient().deleteUser(defaultAddressSpace.getName(), allowedUser.getUsername());
KeycloakCredentials noAllowedUser = new KeycloakCredentials("nobody", "nobodyPa55");
getKeycloakClient().createUser(defaultAddressSpace.getName(), noAllowedUser.getUsername(), noAllowedUser.getPassword(), Group.SEND_ALL.toString());
assertCannotReceive(noAllowedUser.getUsername(), noAllowedUser.getPassword());
getKeycloakClient().deleteUser(defaultAddressSpace.getName(), noAllowedUser.getUsername());
}
private void assertSend(String username, String password) throws Exception {
Logging.log.info("Testing if client is authorized to send messages");
assertTrue(canSend(queue, username, password));
assertTrue(canSend(topic, username, password));
if (getAddressSpaceType() == AddressSpaceType.STANDARD) {
assertTrue(canSend(multicast, username, password));
assertTrue(canSend(anycast, username, password));
}
}
private void assertCannotSend(String username, String password) throws Exception {
Logging.log.info("Testing if client is NOT authorized to send messages");
assertFalse(canSend(queue, username, password));
assertFalse(canSend(topic, username, password));
if (getAddressSpaceType() == AddressSpaceType.STANDARD) {
assertFalse(canSend(multicast, username, password));
assertFalse(canSend(anycast, username, password));
}
}
private void assertReceive(String username, String password) throws Exception {
Logging.log.info("Testing if client is authorized to receive messages");
assertTrue(canReceive(queue, username, password));
assertTrue(canReceive(topic, username, password));
if (getAddressSpaceType() == AddressSpaceType.STANDARD) {
assertTrue(canReceive(multicast, username, password));
assertTrue(canReceive(anycast, username, password));
}
}
private void assertCannotReceive(String username, String password) throws Exception {
Logging.log.info("Testing if client is NOT authorized to receive messages");
assertFalse(canReceive(queue, username, password));
assertFalse(canReceive(topic, username, password));
if (getAddressSpaceType() == AddressSpaceType.STANDARD) {
assertFalse(canReceive(multicast, username, password));
assertFalse(canReceive(anycast, username, password));
}
}
private boolean canSend(Destination destination, String username, String password) throws Exception {
AmqpClient adminClient = createClient(destination, this.username, this.password);
AmqpClient client = createClient(destination, username, password);
try {
Future<List<Message>> received = adminClient.recvMessages(destination.getAddress(), 1, 10, TimeUnit.SECONDS);
Future<Integer> sent = client.sendMessages(destination.getAddress(), Collections.singletonList("msg1"), 10, TimeUnit.SECONDS);
return received.get(1, TimeUnit.MINUTES).size() == sent.get(10, TimeUnit.SECONDS);
}catch (Exception ex){
return false;
}
}
private boolean canReceive(Destination destination, String username, String password) throws Exception {
AmqpClient adminClient = createClient(destination, this.username, this.password);
AmqpClient client = createClient(destination, username, password);
try {
Future<List<Message>> received = client.recvMessages(destination.getAddress(), 1, 10, TimeUnit.SECONDS);
Future<Integer> sent = adminClient.sendMessages(destination.getAddress(), Collections.singletonList("msg1"), 10, TimeUnit.SECONDS);
return received.get(1, TimeUnit.MINUTES).size() == sent.get(1, TimeUnit.MINUTES);
}catch (Exception ex){
return false;
}
}
private AmqpClient createClient(Destination dest, String username, String password) throws Exception {
AmqpClient client = null;
switch (dest.getType()) {
case "queue":
client = amqpClientFactory.createQueueClient(defaultAddressSpace);
break;
case "topic":
client = amqpClientFactory.createTopicClient(defaultAddressSpace);
break;
case "anycast":
client = amqpClientFactory.createQueueClient(defaultAddressSpace);
break;
case "multicast":
client = amqpClientFactory.createBroadcastClient(defaultAddressSpace);
break;
}
client.getConnectOptions().setUsername(username).setPassword(password);
return client;
}
}
| systemtests/src/test/java/io/enmasse/systemtest/authz/AuthorizationTestBase.java | package io.enmasse.systemtest.authz;
import io.enmasse.systemtest.*;
import io.enmasse.systemtest.amqp.AmqpClient;
import org.apache.qpid.proton.message.Message;
import org.junit.Before;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public abstract class AuthorizationTestBase extends TestBaseWithDefault {
private static final Destination queue = Destination.queue("authz-queue");
private static final Destination topic = Destination.topic("authz-topic");
private static final Destination anycast = Destination.anycast("authz-anycast");
private static final Destination multicast = Destination.multicast("authz-multicast");
@Before
public void initAddresses() throws Exception {
List<Destination> addresses = new ArrayList<>();
addresses.add(queue);
addresses.add(topic);
if(getAddressSpaceType() == AddressSpaceType.STANDARD){
addresses.add(anycast);
addresses.add(multicast);
}
setAddresses(defaultAddressSpace, addresses.toArray(new Destination[0]));
}
protected void doTestSendAuthz() throws Exception {
KeycloakCredentials allowedUser = new KeycloakCredentials("sender", "senderPa55");
getKeycloakClient().createUser(defaultAddressSpace.getName(), allowedUser.getUsername(), allowedUser.getPassword(), Group.SEND_ALL.toString());
assertSend(allowedUser.getUsername(), allowedUser.getPassword());
getKeycloakClient().deleteUser(defaultAddressSpace.getName(), allowedUser.getUsername());
KeycloakCredentials noAllowedUser = new KeycloakCredentials("nobody", "nobodyPa55");
getKeycloakClient().createUser(defaultAddressSpace.getName(), noAllowedUser.getUsername(), noAllowedUser.getPassword(), "null");
assertCannotSend(noAllowedUser.getUsername(), noAllowedUser.getPassword());
getKeycloakClient().deleteUser(defaultAddressSpace.getName(), noAllowedUser.getUsername());
getKeycloakClient().createUser(defaultAddressSpace.getName(), noAllowedUser.getUsername(), noAllowedUser.getPassword(), Group.RECV_ALL.toString());
assertCannotSend(noAllowedUser.getUsername(), noAllowedUser.getPassword());
getKeycloakClient().deleteUser(defaultAddressSpace.getName(), noAllowedUser.getUsername());
}
protected void doTestReceiveAuthz() throws Exception {
KeycloakCredentials allowedUser = new KeycloakCredentials("receiver", "receiverPa55");
getKeycloakClient().createUser(defaultAddressSpace.getName(), allowedUser.getUsername(), allowedUser.getPassword(), Group.RECV_ALL.toString());
assertReceive(allowedUser.getUsername(), allowedUser.getPassword());
getKeycloakClient().deleteUser(defaultAddressSpace.getName(), allowedUser.getUsername());
KeycloakCredentials noAllowedUser = new KeycloakCredentials("nobody", "nobodyPa55");
getKeycloakClient().createUser(defaultAddressSpace.getName(), noAllowedUser.getUsername(), noAllowedUser.getPassword(), Group.SEND_ALL.toString());
assertCannotReceive(noAllowedUser.getUsername(), noAllowedUser.getPassword());
getKeycloakClient().deleteUser(defaultAddressSpace.getName(), noAllowedUser.getUsername());
}
private void assertSend(String username, String password) throws Exception {
Logging.log.info("Testing if client is authorized to send messages");
assertTrue(canSend(queue, username, password));
assertTrue(canSend(topic, username, password));
if (getAddressSpaceType() == AddressSpaceType.STANDARD) {
assertTrue(canSend(multicast, username, password));
assertTrue(canSend(anycast, username, password));
}
}
private void assertCannotSend(String username, String password) throws Exception {
Logging.log.info("Testing if client is NOT authorized to send messages");
assertFalse(canSend(queue, username, password));
assertFalse(canSend(topic, username, password));
if (getAddressSpaceType() == AddressSpaceType.STANDARD) {
assertFalse(canSend(multicast, username, password));
assertFalse(canSend(anycast, username, password));
}
}
private void assertReceive(String username, String password) throws Exception {
Logging.log.info("Testing if client is authorized to receive messages");
assertTrue(canReceive(queue, username, password));
assertTrue(canReceive(topic, username, password));
if (getAddressSpaceType() == AddressSpaceType.STANDARD) {
assertTrue(canReceive(multicast, username, password));
assertTrue(canReceive(anycast, username, password));
}
}
private void assertCannotReceive(String username, String password) throws Exception {
Logging.log.info("Testing if client is NOT authorized to receive messages");
assertFalse(canReceive(queue, username, password));
assertFalse(canReceive(topic, username, password));
if (getAddressSpaceType() == AddressSpaceType.STANDARD) {
assertFalse(canReceive(multicast, username, password));
assertFalse(canReceive(anycast, username, password));
}
}
private boolean canSend(Destination destination, String username, String password) throws Exception {
AmqpClient adminClient = createClient(destination, this.username, this.password);
AmqpClient client = createClient(destination, username, password);
try {
Future<List<Message>> received = adminClient.recvMessages(destination.getAddress(), 1, 10, TimeUnit.SECONDS);
Future<Integer> sent = client.sendMessages(destination.getAddress(), Collections.singletonList("msg1"), 10, TimeUnit.SECONDS);
return received.get(1, TimeUnit.MINUTES).size() == sent.get(1, TimeUnit.MINUTES);
}catch (Exception ex){
Logging.log.info(ex.getMessage());
return false;
}
}
private boolean canReceive(Destination destination, String username, String password) throws Exception {
AmqpClient adminClient = createClient(destination, this.username, this.password);
AmqpClient client = createClient(destination, username, password);
try {
Future<List<Message>> received = client.recvMessages(destination.getAddress(), 1, 10, TimeUnit.SECONDS);
Future<Integer> sent = adminClient.sendMessages(destination.getAddress(), Collections.singletonList("msg1"), 10, TimeUnit.SECONDS);
return received.get(1, TimeUnit.MINUTES).size() == sent.get(1, TimeUnit.MINUTES);
}catch (Exception ex){
Logging.log.info(ex.getMessage());
return false;
}
}
private AmqpClient createClient(Destination dest, String username, String password) throws Exception {
AmqpClient client = null;
switch (dest.getType()) {
case "queue":
client = amqpClientFactory.createQueueClient(defaultAddressSpace);
break;
case "topic":
client = amqpClientFactory.createTopicClient(defaultAddressSpace);
break;
case "anycast":
client = amqpClientFactory.createQueueClient(defaultAddressSpace);
break;
case "multicast":
client = amqpClientFactory.createBroadcastClient(defaultAddressSpace);
break;
}
client.getConnectOptions().setUsername(username).setPassword(password);
return client;
}
}
| FIX decrease timeouts
| systemtests/src/test/java/io/enmasse/systemtest/authz/AuthorizationTestBase.java | FIX decrease timeouts |
|
Java | apache-2.0 | d9a38c3c56bd86b273bb195485e1b38999885937 | 0 | MovingBlocks/gestalt | /*
* Copyright 2019 MovingBlocks
*
* 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.terasology.gestalt.naming;
import com.google.common.base.Preconditions;
import java.util.Locale;
import javax.annotation.concurrent.Immutable;
/**
* A name is a normalised string used as an identifier. Primarily this means it is case insensitive.
* <p>
* The original case-sensitive name is retained and available for display purposes, since it may use camel casing for readability.
* </p><p>
* This class is immutable.
* </p>
*
* @author Immortius
*/
@Immutable
public final class Name implements Comparable<Name> {
/**
* The Name equivalent of an empty String
*/
public static final Name EMPTY = new Name("");
private final String normalizedName;
private final String originalName;
public Name(String name) {
Preconditions.checkNotNull(name);
this.originalName = name;
this.normalizedName = name.toLowerCase(Locale.ENGLISH);
}
/**
* @return The original <b>case-sensitive</b> name when string is passed into name
*/
public String displayName() {
return originalName;
}
/**
* @return Whether this name is empty (equivalent to an empty string)
*/
public boolean isEmpty() {
return normalizedName.isEmpty();
}
/**
* @return The Name in lowercase consistent with Name equality (so two names that are equal will have the same lowercase)
* @deprecated This is scheduled for removal in upcoming versions.
* Use {@code toString} or {@code displayName} instead.
* Note that a Name should not be transformed to a String for further processing.
*/
@Deprecated
public String toLowerCase() {
return normalizedName;
}
/**
* @return The Name in uppercase consistent with Name equality (so two names that are equal will have the same uppercase)
* @deprecated
*/
public String toUpperCase() {
return originalName.toUpperCase(Locale.ENGLISH);
}
@Override
public int compareTo(Name o) {
return normalizedName.compareTo(o.normalizedName);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Name) {
Name other = (Name) obj;
return normalizedName.equals(other.normalizedName);
}
return false;
}
@Override
public int hashCode() {
return normalizedName.hashCode();
}
/**
* @return The Name as string consistent with Name equality (so two names that are equal will have the same {@code toString})
*/
@Override
public String toString() {
return normalizedName;
}
}
| gestalt-module/src/main/java/org/terasology/gestalt/naming/Name.java | /*
* Copyright 2019 MovingBlocks
*
* 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.terasology.gestalt.naming;
import com.google.common.base.Preconditions;
import java.util.Locale;
import javax.annotation.concurrent.Immutable;
/**
* A name is a normalised string used as an identifier. Primarily this means it is case insensitive.
* <p>
* The original case-sensitive name is retained and available for display purposes, since it may use camel casing for readability.
* </p><p>
* This class is immutable.
* </p>
*
* @author Immortius
*/
@Immutable
public final class Name implements Comparable<Name> {
/**
* The Name equivalent of an empty String
*/
public static final Name EMPTY = new Name("");
private final String normalizedName;
private final String originalName;
public Name(String name) {
Preconditions.checkNotNull(name);
this.originalName = name;
this.normalizedName = name.toLowerCase(Locale.ENGLISH);
}
/**
* @return The original <b>case-sensitive</b> name when string is passed into name
*/
public String displayName() {
return originalName;
}
/**
* @return Whether this name is empty (equivalent to an empty string)
*/
public boolean isEmpty() {
return normalizedName.isEmpty();
}
/**
* @return The Name in lowercase consistent with Name equality (so two names that are equal will have the same lowercase)
* @deprecated This is scheduled for removal in upcoming versions.
* Use {@code toString} or {@code displayName} instead.
* Note that a Name should not be transformed to a String for further processing.
*/
@Deprecated
public String toLowerCase() {
return normalizedName;
}
/**
* @return The Name in uppercase consistent with Name equality (so two names that are equal will have the same uppercase)
* @deprecated
*/
public String toUpperCase() {
return originalName.toUpperCase(Locale.ENGLISH);
}
@Override
public int compareTo(Name o) {
return normalizedName.compareTo(o.normalizedName);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Name) {
Name other = (Name) obj;
return normalizedName.equals(other.normalizedName);
}
return false;
}
@Override
public int hashCode() {
return normalizedName.hashCode();
}
@Override
public String toString() {
return normalizedName;
}
}
| Update gestalt-module/src/main/java/org/terasology/gestalt/naming/Name.java
Co-Authored-By: Tobias Nett <[email protected]> | gestalt-module/src/main/java/org/terasology/gestalt/naming/Name.java | Update gestalt-module/src/main/java/org/terasology/gestalt/naming/Name.java |
|
Java | apache-2.0 | 4bc5c0acc22ed9d27c959736428db5ecdc28c08a | 0 | minnal/minnal,minnal/minnal,minnal/minnal | /**
*
*/
package org.minnal.core.server;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.minnal.core.Response;
import org.minnal.core.serializer.Serializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.FluentIterable;
import com.google.common.net.MediaType;
/**
* @author ganeshs
*
*/
public class ServerResponse extends ServerMessage implements Response {
private HttpResponse response;
private ServerRequest request;
private boolean contentSet;
private ResponseWriter writer;
private static Logger logger = LoggerFactory.getLogger(ServerResponse.class);
public ServerResponse(ServerRequest request, HttpResponse response) {
super(response);
this.request = request;
this.response = response;
this.writer = new DefaultResponseWriter(this);
init();
}
protected void init() {
// TODO: Allowing CORS for all domains. Take the value from configuration
addHeader(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
addHeader(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_METHODS, "*");
addHeader(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_HEADERS, "*");
}
/**
* @param writer
*/
public void setResponseWriter(ResponseWriter writer) {
this.writer = writer;
}
public void setStatus(HttpResponseStatus status) {
response.setStatus(status);
}
public void setContent(Object content) {
if (! contentSet) {
writer.write(content);
}
}
@Override
public void setContent(ChannelBuffer content) {
super.setContent(content);
contentSet = true;
}
public ChannelFuture write(Channel channel) {
return channel.write(response);
}
public HttpResponseStatus getStatus() {
return response.getStatus();
}
public void setContentType(MediaType type) {
response.addHeader(HttpHeaders.Names.CONTENT_TYPE, type.toString());
}
public boolean isContentSet() {
return contentSet;
}
@Override
protected String getCookieHeaderName() {
return HttpHeaders.Names.SET_COOKIE;
}
/**
* Returns the request associated with this response
* @return
*/
protected ServerRequest getRequest() {
return request;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ServerResponse [response=").append(response)
.append(", request=").append(request).append(", contentSet=")
.append(contentSet).append("]");
return builder.toString();
}
}
| minnal-core/src/main/java/org/minnal/core/server/ServerResponse.java | /**
*
*/
package org.minnal.core.server;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.handler.codec.http.HttpHeaders;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
import org.minnal.core.Response;
import org.minnal.core.serializer.Serializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.FluentIterable;
import com.google.common.net.MediaType;
/**
* @author ganeshs
*
*/
public class ServerResponse extends ServerMessage implements Response {
private HttpResponse response;
private ServerRequest request;
private boolean contentSet;
private static Logger logger = LoggerFactory.getLogger(ServerResponse.class);
public ServerResponse(ServerRequest request, HttpResponse response) {
super(response);
this.request = request;
this.response = response;
init();
}
protected void init() {
// TODO: Allowing CORS for all domains. Take the value from configuration
addHeader(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
addHeader(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_METHODS, "*");
addHeader(HttpHeaders.Names.ACCESS_CONTROL_ALLOW_HEADERS, "*");
}
public void setStatus(HttpResponseStatus status) {
response.setStatus(status);
}
public void setContent(Object content) {
if (! contentSet) {
MediaType type = null;
Serializer serializer = null;
if (request.getSupportedAccepts() != null) {
type = FluentIterable.from(request.getSupportedAccepts()).first().or(getResolvedRoute().getConfiguration().getDefaultMediaType());
serializer = getSerializer(type);
} else {
type = MediaType.PLAIN_TEXT_UTF_8;
serializer = Serializer.DEFAULT_TEXT_SERIALIZER;
}
setContentType(type);
setContent(serializer.serialize(content));
}
}
@Override
public void setContent(ChannelBuffer content) {
super.setContent(content);
contentSet = true;
}
public ChannelFuture write(Channel channel) {
return channel.write(response);
}
public HttpResponseStatus getStatus() {
return response.getStatus();
}
public void setContentType(MediaType type) {
response.addHeader(HttpHeaders.Names.CONTENT_TYPE, type.toString());
}
public boolean isContentSet() {
return contentSet;
}
@Override
protected String getCookieHeaderName() {
return HttpHeaders.Names.SET_COOKIE;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ServerResponse [response=").append(response)
.append(", request=").append(request).append(", contentSet=")
.append(contentSet).append("]");
return builder.toString();
}
}
| moving content serialization from server response to response writer
| minnal-core/src/main/java/org/minnal/core/server/ServerResponse.java | moving content serialization from server response to response writer |
|
Java | apache-2.0 | 2dbb919ce4ae735777afaa061001f71f322a7a2f | 0 | gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas,gxa/atlas | /*
* Copyright 2008-2013 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* 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.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.atlas.web.controllers.page;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.springframework.context.annotation.Scope;
import uk.ac.ebi.atlas.geneindex.SolrClient;
import uk.ac.ebi.atlas.utils.UniProtClient;
import uk.ac.ebi.atlas.web.BioEntityCardProperties;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.List;
@Named("bioEntityPropertyService")
@Scope("request")
public class BioentityPropertyService {
public static final String PROPERTY_TYPE_DESCRIPTION = "description";
private SolrClient solrClient;
private UniProtClient uniProtClient;
private BioEntityCardProperties bioEntityCardProperties;
private Multimap<String, String> propertyValuesByType;
private String species;
@Inject
public BioEntityPropertyService(SolrClient solrClient, UniProtClient uniProtClient, BioEntityCardProperties bioEntityCardProperties) {
this.solrClient = solrClient;
this.uniProtClient = uniProtClient;
this.bioEntityCardProperties = bioEntityCardProperties;
}
public void init(String identifier, String[] queryPropertyTypes) {
species = solrClient.findSpeciesForGeneId(identifier);
propertyValuesByType = solrClient.fetchGenePageProperties(identifier, queryPropertyTypes);
}
public String getSpecies(){
return species;
}
//used in bioEntity.jsp
public List<PropertyLink> getPropertyLinks(String propertyType) {
if ("reactome".equals(propertyType)){
addReactomePropertyValues();
}
List<PropertyLink> propertyLinks = Lists.newArrayList();
for(String propertyValue: propertyValuesByType.get(propertyType) ){
propertyLinks.add(createLink(propertyType, propertyValue, species));
}
return propertyLinks;
}
public String getBioEntityDescription() {
String description = getFirstValueOfProperty(PROPERTY_TYPE_DESCRIPTION);
return StringUtils.substringBefore(description, "[");
}
String getFirstValueOfProperty(String propertyType) {
Collection<String> properties = propertyValuesByType.get(propertyType);
return CollectionUtils.isNotEmpty(properties) ? properties.iterator().next() : "";
}
void addReactomePropertyValues() {
Collection<String> uniprotIds = propertyValuesByType.get("uniprot");
if (CollectionUtils.isNotEmpty(uniprotIds)) {
for (String uniprotId : uniprotIds) {
Collection<String> reactomeIds = uniProtClient.fetchReactomeIds(uniprotId);
propertyValuesByType.putAll("reactome", reactomeIds);
}
}
}
String transformOrthologToSymbol(String identifier) {
String species = solrClient.findSpeciesForGeneId(identifier);
species = WordUtils.capitalize(species);
List<String> valuesForGeneId = solrClient.findPropertyValuesForGeneId(identifier, "symbol");
if (!valuesForGeneId.isEmpty()) {
String symbol = valuesForGeneId.get(0);
return symbol + " (" + species + ")";
}
return identifier;
}
PropertyLink createLink(String propertyType, String propertyValue, String species) {
final String linkSpecies = species.replaceAll(" ", "_");
String linkText = getLinkText(propertyType, propertyValue);
String link = bioEntityCardProperties.getLinkTemplate(propertyType);
if (link != null) {
if (propertyType.equals("ensprotein") || propertyType.equals("enstranscript")) {
link = MessageFormat.format(link, linkSpecies, getEncodedString(getFirstValueOfProperty("ensgene"))
, getEncodedString(getFirstValueOfProperty("enstranscript")));
} else {
link = MessageFormat.format(link, getEncodedString(propertyValue), linkSpecies);
}
return new PropertyLink(linkText, link);
}
return new PropertyLink(linkText);
}
String getLinkText(String propertyType, String propertyValue) {
String displayName = propertyValue;
if (propertyType.equals("ortholog")) {
displayName = transformOrthologToSymbol(displayName);
}
return displayName;
}
String getEncodedString(String value) {
try {
return URLEncoder.encode(value, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Cannot create URL from " + value, e);
}
}
}
| web/src/main/java/uk/ac/ebi/atlas/web/controllers/page/BioentityPropertyService.java | /*
* Copyright 2008-2013 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* 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.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.atlas.web.controllers.page;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.springframework.context.annotation.Scope;
import uk.ac.ebi.atlas.geneindex.SolrClient;
import uk.ac.ebi.atlas.utils.UniProtClient;
import uk.ac.ebi.atlas.web.BioEntityCardProperties;
import javax.inject.Inject;
import javax.inject.Named;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.List;
@Named("bioEntityPropertyService")
@Scope("request")
public class BioEntityPropertyService {
public static final String PROPERTY_TYPE_DESCRIPTION = "description";
private SolrClient solrClient;
private UniProtClient uniProtClient;
private BioEntityCardProperties bioEntityCardProperties;
private Multimap<String, String> propertyValuesByType;
private String species;
@Inject
public BioEntityPropertyService(SolrClient solrClient, UniProtClient uniProtClient, BioEntityCardProperties bioEntityCardProperties) {
this.solrClient = solrClient;
this.uniProtClient = uniProtClient;
this.bioEntityCardProperties = bioEntityCardProperties;
}
public void init(String identifier, String[] queryPropertyTypes) {
species = solrClient.findSpeciesForGeneId(identifier);
propertyValuesByType = solrClient.fetchGenePageProperties(identifier, queryPropertyTypes);
}
public String getSpecies(){
return species;
}
//used in bioEntity.jsp
public List<PropertyLink> getPropertyLinks(String propertyType) {
if ("reactome".equals(propertyType)){
addReactomePropertyValues();
}
List<PropertyLink> propertyLinks = Lists.newArrayList();
for(String propertyValue: propertyValuesByType.get(propertyType) ){
propertyLinks.add(createLink(propertyType, propertyValue, species));
}
return propertyLinks;
}
public String getBioEntityDescription() {
String description = getFirstValueOfProperty(PROPERTY_TYPE_DESCRIPTION);
return StringUtils.substringBefore(description, "[");
}
String getFirstValueOfProperty(String propertyType) {
Collection<String> properties = propertyValuesByType.get(propertyType);
return CollectionUtils.isNotEmpty(properties) ? properties.iterator().next() : "";
}
void addReactomePropertyValues() {
Collection<String> uniprotIds = propertyValuesByType.get("uniprot");
if (CollectionUtils.isNotEmpty(uniprotIds)) {
for (String uniprotId : uniprotIds) {
Collection<String> reactomeIds = uniProtClient.fetchReactomeIds(uniprotId);
propertyValuesByType.putAll("reactome", reactomeIds);
}
}
}
String transformOrthologToSymbol(String identifier) {
String species = solrClient.findSpeciesForGeneId(identifier);
species = WordUtils.capitalize(species);
List<String> valuesForGeneId = solrClient.findPropertyValuesForGeneId(identifier, "symbol");
if (!valuesForGeneId.isEmpty()) {
String symbol = valuesForGeneId.get(0);
return symbol + " (" + species + ")";
}
return identifier;
}
PropertyLink createLink(String propertyType, String propertyValue, String species) {
final String linkSpecies = species.replaceAll(" ", "_");
String linkText = getLinkText(propertyType, propertyValue);
String link = bioEntityCardProperties.getLinkTemplate(propertyType);
if (link != null) {
if (propertyType.equals("ensprotein") || propertyType.equals("enstranscript")) {
link = MessageFormat.format(link, linkSpecies, getEncodedString(getFirstValueOfProperty("ensgene"))
, getEncodedString(getFirstValueOfProperty("enstranscript")));
} else {
link = MessageFormat.format(link, getEncodedString(propertyValue), linkSpecies);
}
return new PropertyLink(linkText, link);
}
return new PropertyLink(linkText);
}
String getLinkText(String propertyType, String propertyValue) {
String displayName = propertyValue;
if (propertyType.equals("ortholog")) {
displayName = transformOrthologToSymbol(displayName);
}
return displayName;
}
String getEncodedString(String value) {
try {
return URLEncoder.encode(value, "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
throw new IllegalStateException("Cannot create URL from " + value, e);
}
}
}
| Update BioentityPropertyService.java | web/src/main/java/uk/ac/ebi/atlas/web/controllers/page/BioentityPropertyService.java | Update BioentityPropertyService.java |
|
Java | apache-2.0 | 0d6cbb2f5477f869c9d8afc8d02229d1d313b887 | 0 | satishgummadelli/camel,pplatek/camel,askannon/camel,lasombra/camel,apache/camel,duro1/camel,lasombra/camel,gilfernandes/camel,Thopap/camel,royopa/camel,veithen/camel,manuelh9r/camel,erwelch/camel,oalles/camel,woj-i/camel,mcollovati/camel,josefkarasek/camel,manuelh9r/camel,manuelh9r/camel,jamesnetherton/camel,JYBESSON/camel,oalles/camel,YMartsynkevych/camel,logzio/camel,dsimansk/camel,apache/camel,qst-jdc-labs/camel,NickCis/camel,rmarting/camel,lburgazzoli/apache-camel,davidwilliams1978/camel,dsimansk/camel,mnki/camel,mgyongyosi/camel,noelo/camel,gnodet/camel,snadakuduru/camel,isavin/camel,igarashitm/camel,dpocock/camel,dvankleef/camel,mike-kukla/camel,pplatek/camel,jkorab/camel,mohanaraosv/camel,bdecoste/camel,edigrid/camel,zregvart/camel,stravag/camel,oscerd/camel,tdiesler/camel,anoordover/camel,Fabryprog/camel,lburgazzoli/apache-camel,mzapletal/camel,alvinkwekel/camel,nikvaessen/camel,chanakaudaya/camel,grgrzybek/camel,oalles/camel,ekprayas/camel,veithen/camel,jmandawg/camel,iweiss/camel,rparree/camel,gyc567/camel,pplatek/camel,johnpoth/camel,bfitzpat/camel,yuruki/camel,chirino/camel,skinzer/camel,noelo/camel,chirino/camel,pmoerenhout/camel,sebi-hgdata/camel,tarilabs/camel,davidkarlsen/camel,duro1/camel,tarilabs/camel,trohovsky/camel,logzio/camel,engagepoint/camel,allancth/camel,adessaigne/camel,gautric/camel,mcollovati/camel,atoulme/camel,tlehoux/camel,lburgazzoli/camel,skinzer/camel,atoulme/camel,grange74/camel,yuruki/camel,lowwool/camel,NetNow/camel,curso007/camel,FingolfinTEK/camel,davidwilliams1978/camel,MohammedHammam/camel,w4tson/camel,gilfernandes/camel,nikhilvibhav/camel,hqstevenson/camel,DariusX/camel,stalet/camel,jamesnetherton/camel,grange74/camel,ssharma/camel,davidwilliams1978/camel,oalles/camel,snadakuduru/camel,zregvart/camel,gilfernandes/camel,nikvaessen/camel,yury-vashchyla/camel,akhettar/camel,yuruki/camel,royopa/camel,snadakuduru/camel,pax95/camel,jameszkw/camel,stravag/camel,stalet/camel,logzio/camel,maschmid/camel,pax95/camel,satishgummadelli/camel,sverkera/camel,brreitme/camel,YoshikiHigo/camel,mike-kukla/camel,rparree/camel,jpav/camel,haku/camel,brreitme/camel,christophd/camel,duro1/camel,dmvolod/camel,sebi-hgdata/camel,oscerd/camel,chirino/camel,jamesnetherton/camel,nboukhed/camel,pmoerenhout/camel,yury-vashchyla/camel,DariusX/camel,jmandawg/camel,gautric/camel,igarashitm/camel,askannon/camel,dpocock/camel,neoramon/camel,bfitzpat/camel,sverkera/camel,gyc567/camel,lburgazzoli/camel,dkhanolkar/camel,jkorab/camel,oalles/camel,arnaud-deprez/camel,ullgren/camel,prashant2402/camel,FingolfinTEK/camel,partis/camel,chirino/camel,RohanHart/camel,snurmine/camel,anoordover/camel,engagepoint/camel,johnpoth/camel,tadayosi/camel,arnaud-deprez/camel,igarashitm/camel,lburgazzoli/camel,mohanaraosv/camel,cunningt/camel,mike-kukla/camel,christophd/camel,nikvaessen/camel,isavin/camel,johnpoth/camel,duro1/camel,aaronwalker/camel,tdiesler/camel,allancth/camel,ramonmaruko/camel,jpav/camel,bhaveshdt/camel,ssharma/camel,stravag/camel,nicolaferraro/camel,mzapletal/camel,manuelh9r/camel,rmarting/camel,dsimansk/camel,jarst/camel,sabre1041/camel,Thopap/camel,RohanHart/camel,trohovsky/camel,rmarting/camel,gautric/camel,chanakaudaya/camel,jpav/camel,atoulme/camel,qst-jdc-labs/camel,YoshikiHigo/camel,satishgummadelli/camel,NetNow/camel,driseley/camel,rparree/camel,bgaudaen/camel,yury-vashchyla/camel,ge0ffrey/camel,bdecoste/camel,NetNow/camel,anton-k11/camel,josefkarasek/camel,acartapanis/camel,MrCoder/camel,objectiser/camel,ullgren/camel,haku/camel,mgyongyosi/camel,nikvaessen/camel,arnaud-deprez/camel,mzapletal/camel,borcsokj/camel,dmvolod/camel,partis/camel,woj-i/camel,eformat/camel,neoramon/camel,CandleCandle/camel,NetNow/camel,haku/camel,oalles/camel,royopa/camel,atoulme/camel,tkopczynski/camel,jlpedrosa/camel,lburgazzoli/apache-camel,bgaudaen/camel,veithen/camel,pax95/camel,allancth/camel,coderczp/camel,apache/camel,FingolfinTEK/camel,mnki/camel,kevinearls/camel,onders86/camel,jkorab/camel,coderczp/camel,lburgazzoli/camel,prashant2402/camel,yury-vashchyla/camel,nikhilvibhav/camel,bhaveshdt/camel,salikjan/camel,gautric/camel,coderczp/camel,gnodet/camel,jkorab/camel,akhettar/camel,pax95/camel,ramonmaruko/camel,aaronwalker/camel,ramonmaruko/camel,jlpedrosa/camel,isavin/camel,maschmid/camel,grange74/camel,josefkarasek/camel,duro1/camel,erwelch/camel,curso007/camel,nboukhed/camel,driseley/camel,ramonmaruko/camel,bhaveshdt/camel,punkhorn/camel-upstream,YMartsynkevych/camel,aaronwalker/camel,salikjan/camel,RohanHart/camel,pax95/camel,ullgren/camel,bdecoste/camel,stravag/camel,tadayosi/camel,tarilabs/camel,bdecoste/camel,mnki/camel,prashant2402/camel,MrCoder/camel,isururanawaka/camel,YMartsynkevych/camel,adessaigne/camel,onders86/camel,pkletsko/camel,koscejev/camel,JYBESSON/camel,skinzer/camel,hqstevenson/camel,grgrzybek/camel,w4tson/camel,curso007/camel,nikvaessen/camel,erwelch/camel,tadayosi/camel,objectiser/camel,bgaudaen/camel,nikhilvibhav/camel,borcsokj/camel,oscerd/camel,mzapletal/camel,CandleCandle/camel,logzio/camel,ssharma/camel,nicolaferraro/camel,scranton/camel,haku/camel,lowwool/camel,YoshikiHigo/camel,Thopap/camel,dvankleef/camel,koscejev/camel,snurmine/camel,nboukhed/camel,dvankleef/camel,maschmid/camel,nicolaferraro/camel,nboukhed/camel,tarilabs/camel,ullgren/camel,christophd/camel,tkopczynski/camel,drsquidop/camel,grgrzybek/camel,eformat/camel,mike-kukla/camel,akhettar/camel,neoramon/camel,ekprayas/camel,NetNow/camel,mgyongyosi/camel,dpocock/camel,anton-k11/camel,pkletsko/camel,jarst/camel,CodeSmell/camel,manuelh9r/camel,iweiss/camel,mohanaraosv/camel,qst-jdc-labs/camel,MrCoder/camel,snurmine/camel,engagepoint/camel,CodeSmell/camel,scranton/camel,royopa/camel,neoramon/camel,gilfernandes/camel,dmvolod/camel,ramonmaruko/camel,acartapanis/camel,drsquidop/camel,sirlatrom/camel,mohanaraosv/camel,jonmcewen/camel,haku/camel,gilfernandes/camel,bfitzpat/camel,mgyongyosi/camel,sebi-hgdata/camel,atoulme/camel,woj-i/camel,christophd/camel,bgaudaen/camel,jlpedrosa/camel,manuelh9r/camel,stalet/camel,jollygeorge/camel,jarst/camel,jkorab/camel,acartapanis/camel,pax95/camel,yury-vashchyla/camel,NickCis/camel,sverkera/camel,oscerd/camel,askannon/camel,sirlatrom/camel,MohammedHammam/camel,zregvart/camel,nicolaferraro/camel,skinzer/camel,apache/camel,johnpoth/camel,kevinearls/camel,anton-k11/camel,sabre1041/camel,aaronwalker/camel,lburgazzoli/camel,Thopap/camel,tadayosi/camel,snurmine/camel,anton-k11/camel,oscerd/camel,isururanawaka/camel,royopa/camel,nikhilvibhav/camel,davidkarlsen/camel,MrCoder/camel,acartapanis/camel,RohanHart/camel,lburgazzoli/apache-camel,igarashitm/camel,Fabryprog/camel,mnki/camel,bfitzpat/camel,isururanawaka/camel,lburgazzoli/camel,jmandawg/camel,stalet/camel,zregvart/camel,lasombra/camel,MohammedHammam/camel,satishgummadelli/camel,DariusX/camel,driseley/camel,davidwilliams1978/camel,lburgazzoli/apache-camel,sirlatrom/camel,jarst/camel,dkhanolkar/camel,dkhanolkar/camel,grange74/camel,dmvolod/camel,isavin/camel,jollygeorge/camel,aaronwalker/camel,NickCis/camel,jlpedrosa/camel,yogamaha/camel,chirino/camel,johnpoth/camel,tlehoux/camel,pmoerenhout/camel,jameszkw/camel,bhaveshdt/camel,yuruki/camel,kevinearls/camel,cunningt/camel,joakibj/camel,pmoerenhout/camel,gautric/camel,adessaigne/camel,ekprayas/camel,akhettar/camel,logzio/camel,jpav/camel,cunningt/camel,brreitme/camel,dvankleef/camel,FingolfinTEK/camel,jamesnetherton/camel,snadakuduru/camel,nboukhed/camel,johnpoth/camel,qst-jdc-labs/camel,tdiesler/camel,drsquidop/camel,dkhanolkar/camel,jlpedrosa/camel,CandleCandle/camel,isururanawaka/camel,NickCis/camel,FingolfinTEK/camel,koscejev/camel,mgyongyosi/camel,mzapletal/camel,sirlatrom/camel,iweiss/camel,bdecoste/camel,JYBESSON/camel,chanakaudaya/camel,joakibj/camel,sabre1041/camel,ge0ffrey/camel,stalet/camel,yogamaha/camel,kevinearls/camel,pplatek/camel,dsimansk/camel,allancth/camel,josefkarasek/camel,scranton/camel,jameszkw/camel,pkletsko/camel,snurmine/camel,noelo/camel,dmvolod/camel,jonmcewen/camel,cunningt/camel,dpocock/camel,stravag/camel,arnaud-deprez/camel,logzio/camel,joakibj/camel,jollygeorge/camel,tkopczynski/camel,adessaigne/camel,mohanaraosv/camel,adessaigne/camel,jameszkw/camel,grgrzybek/camel,driseley/camel,MohammedHammam/camel,skinzer/camel,edigrid/camel,Thopap/camel,yuruki/camel,RohanHart/camel,RohanHart/camel,yogamaha/camel,MohammedHammam/camel,FingolfinTEK/camel,coderczp/camel,prashant2402/camel,JYBESSON/camel,dkhanolkar/camel,mcollovati/camel,iweiss/camel,bfitzpat/camel,tdiesler/camel,Fabryprog/camel,josefkarasek/camel,kevinearls/camel,chanakaudaya/camel,grange74/camel,pkletsko/camel,mike-kukla/camel,sirlatrom/camel,sverkera/camel,gyc567/camel,sebi-hgdata/camel,CandleCandle/camel,royopa/camel,scranton/camel,satishgummadelli/camel,pplatek/camel,yogamaha/camel,satishgummadelli/camel,rmarting/camel,partis/camel,MrCoder/camel,NickCis/camel,erwelch/camel,pplatek/camel,isururanawaka/camel,borcsokj/camel,driseley/camel,jollygeorge/camel,mzapletal/camel,scranton/camel,grgrzybek/camel,anoordover/camel,lasombra/camel,dpocock/camel,grgrzybek/camel,stravag/camel,gilfernandes/camel,koscejev/camel,jameszkw/camel,gyc567/camel,CandleCandle/camel,gyc567/camel,jlpedrosa/camel,veithen/camel,mike-kukla/camel,ge0ffrey/camel,allancth/camel,igarashitm/camel,atoulme/camel,rmarting/camel,bhaveshdt/camel,drsquidop/camel,ge0ffrey/camel,apache/camel,noelo/camel,Thopap/camel,askannon/camel,koscejev/camel,askannon/camel,tlehoux/camel,alvinkwekel/camel,dmvolod/camel,sabre1041/camel,mgyongyosi/camel,anoordover/camel,dpocock/camel,partis/camel,lowwool/camel,YMartsynkevych/camel,punkhorn/camel-upstream,joakibj/camel,rparree/camel,tkopczynski/camel,bgaudaen/camel,anoordover/camel,curso007/camel,jmandawg/camel,woj-i/camel,arnaud-deprez/camel,onders86/camel,joakibj/camel,aaronwalker/camel,chanakaudaya/camel,lowwool/camel,dsimansk/camel,sebi-hgdata/camel,edigrid/camel,prashant2402/camel,eformat/camel,borcsokj/camel,pkletsko/camel,trohovsky/camel,w4tson/camel,igarashitm/camel,cunningt/camel,isavin/camel,pplatek/camel,jmandawg/camel,tarilabs/camel,akhettar/camel,rmarting/camel,anton-k11/camel,tarilabs/camel,drsquidop/camel,MrCoder/camel,noelo/camel,tadayosi/camel,logzio/camel,jarst/camel,davidkarlsen/camel,jollygeorge/camel,maschmid/camel,dvankleef/camel,bfitzpat/camel,christophd/camel,brreitme/camel,veithen/camel,woj-i/camel,CodeSmell/camel,tkopczynski/camel,hqstevenson/camel,nikvaessen/camel,bdecoste/camel,chanakaudaya/camel,w4tson/camel,joakibj/camel,davidwilliams1978/camel,neoramon/camel,eformat/camel,mnki/camel,lasombra/camel,YMartsynkevych/camel,eformat/camel,DariusX/camel,cunningt/camel,duro1/camel,ge0ffrey/camel,sabre1041/camel,oscerd/camel,ge0ffrey/camel,noelo/camel,allancth/camel,koscejev/camel,pmoerenhout/camel,coderczp/camel,sebi-hgdata/camel,davidwilliams1978/camel,scranton/camel,neoramon/camel,haku/camel,pmoerenhout/camel,nboukhed/camel,NickCis/camel,YoshikiHigo/camel,woj-i/camel,jonmcewen/camel,davidkarlsen/camel,CodeSmell/camel,drsquidop/camel,CandleCandle/camel,gyc567/camel,curso007/camel,mnki/camel,jamesnetherton/camel,alvinkwekel/camel,snadakuduru/camel,jonmcewen/camel,acartapanis/camel,hqstevenson/camel,edigrid/camel,objectiser/camel,yuruki/camel,iweiss/camel,w4tson/camel,jpav/camel,askannon/camel,rparree/camel,onders86/camel,gautric/camel,brreitme/camel,dvankleef/camel,objectiser/camel,yury-vashchyla/camel,arnaud-deprez/camel,veithen/camel,mohanaraosv/camel,dkhanolkar/camel,dsimansk/camel,edigrid/camel,kevinearls/camel,partis/camel,acartapanis/camel,ekprayas/camel,sabre1041/camel,isururanawaka/camel,prashant2402/camel,ekprayas/camel,sirlatrom/camel,ssharma/camel,rparree/camel,skinzer/camel,jonmcewen/camel,gnodet/camel,jkorab/camel,pkletsko/camel,ssharma/camel,erwelch/camel,engagepoint/camel,jollygeorge/camel,grange74/camel,ramonmaruko/camel,maschmid/camel,adessaigne/camel,lasombra/camel,brreitme/camel,snadakuduru/camel,coderczp/camel,jonmcewen/camel,ekprayas/camel,erwelch/camel,trohovsky/camel,mcollovati/camel,engagepoint/camel,eformat/camel,lowwool/camel,trohovsky/camel,hqstevenson/camel,tkopczynski/camel,maschmid/camel,gnodet/camel,lburgazzoli/apache-camel,iweiss/camel,qst-jdc-labs/camel,Fabryprog/camel,christophd/camel,tdiesler/camel,JYBESSON/camel,stalet/camel,anoordover/camel,jameszkw/camel,jamesnetherton/camel,onders86/camel,bhaveshdt/camel,snurmine/camel,bgaudaen/camel,lowwool/camel,alvinkwekel/camel,w4tson/camel,yogamaha/camel,YMartsynkevych/camel,tlehoux/camel,borcsokj/camel,trohovsky/camel,tdiesler/camel,josefkarasek/camel,NetNow/camel,hqstevenson/camel,anton-k11/camel,jpav/camel,YoshikiHigo/camel,curso007/camel,onders86/camel,yogamaha/camel,apache/camel,edigrid/camel,JYBESSON/camel,tlehoux/camel,akhettar/camel,isavin/camel,partis/camel,jarst/camel,MohammedHammam/camel,qst-jdc-labs/camel,YoshikiHigo/camel,sverkera/camel,tlehoux/camel,ssharma/camel,punkhorn/camel-upstream,driseley/camel,chirino/camel,borcsokj/camel,sverkera/camel,jmandawg/camel,gnodet/camel,punkhorn/camel-upstream,tadayosi/camel | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.file;
import java.io.File;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Route;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.RoutePolicySupport;
/**
* @version $Revision$
*/
public class FileConsumerSuspendTest extends ContextTestSupport {
public void testConsumeSuspendFile() throws Exception {
deleteDirectory("target/suspended");
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
template.sendBodyAndHeader("file://target/suspended", "Bye World", Exchange.FILE_NAME, "bye.txt");
template.sendBodyAndHeader("file://target/suspended", "Hello World", Exchange.FILE_NAME, "hello.txt");
assertMockEndpointsSatisfied();
Thread.sleep(1000);
// the route is suspended by the policy so we should only receive one
File file = new File("target/suspended/hello.txt").getAbsoluteFile();
assertEquals("The file should exists", true, file.exists());
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
MyPolicy myPolicy = new MyPolicy();
from("file://target/suspended?maxMessagesPerPoll=1&sortBy=file:name")
.routePolicy(myPolicy).id("myRoute")
.to("mock:result");
}
};
}
private class MyPolicy extends RoutePolicySupport {
private int counter;
public void onExchangeDone(Route route, Exchange exchange) {
// only stop it at first run
if (counter++ == 0) {
try {
super.stopConsumer(route.getConsumer());
} catch (Exception e) {
handleException(e);
}
}
}
}
}
| camel-core/src/test/java/org/apache/camel/component/file/FileConsumerSuspendTest.java | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.file;
import java.io.File;
import org.apache.camel.ContextTestSupport;
import org.apache.camel.Exchange;
import org.apache.camel.Route;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.impl.RoutePolicySupport;
/**
* @version $Revision$
*/
public class FileConsumerSuspendTest extends ContextTestSupport {
public void testConsumeSuspendFile() throws Exception {
deleteDirectory("target/suspended");
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Bye World");
template.sendBodyAndHeader("file://target/suspended", "Bye World", Exchange.FILE_NAME, "bye.txt");
template.sendBodyAndHeader("file://target/suspended", "Hello World", Exchange.FILE_NAME, "hello.txt");
assertMockEndpointsSatisfied();
Thread.sleep(1000);
// the route is suspended by the policy so we should only receive one
File file = new File("target/suspended/hello.txt").getAbsoluteFile();
assertEquals("The file should exists", true, file.exists());
}
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
MyPolicy myPolicy = new MyPolicy();
from("file://target/suspended?maxMessagesPerPoll=1&sortBy=file:name")
.routePolicy(myPolicy).id("myRoute")
.to("mock:result");
}
};
}
private class MyPolicy extends RoutePolicySupport {
private int counter;
public void onExchangeDone(Route route, Exchange exchange) {
// only stop it at first run
if (counter++ == 0) {
try {
super.stopConsumer(route.getConsumer());
} catch (Exception e) {
handleException(e);
}
}
}
}
}
| Fixed unit test
git-svn-id: 11f3c9e1d08a13a4be44fe98a6d63a9c00f6ab23@889120 13f79535-47bb-0310-9956-ffa450edef68
| camel-core/src/test/java/org/apache/camel/component/file/FileConsumerSuspendTest.java | Fixed unit test |
|
Java | apache-2.0 | 83cb7798f475b55a66d9a77c6a837aefcbf0fde1 | 0 | gurbuzali/hazelcast-jet,gurbuzali/hazelcast-jet | /*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.aggregate;
import com.hazelcast.jet.accumulator.DoubleAccumulator;
import com.hazelcast.jet.accumulator.LinTrendAccumulator;
import com.hazelcast.jet.accumulator.LongAccumulator;
import com.hazelcast.jet.accumulator.LongDoubleAccumulator;
import com.hazelcast.jet.accumulator.LongLongAccumulator;
import com.hazelcast.jet.accumulator.MutableReference;
import com.hazelcast.jet.function.DistributedBiConsumer;
import com.hazelcast.jet.function.DistributedBinaryOperator;
import com.hazelcast.jet.function.DistributedComparator;
import com.hazelcast.jet.function.DistributedFunction;
import com.hazelcast.jet.function.DistributedSupplier;
import com.hazelcast.jet.function.DistributedToDoubleFunction;
import com.hazelcast.jet.function.DistributedToLongFunction;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
/**
* Utility class with factory methods for several useful aggregate
* operations.
*/
public final class AggregateOperations {
private AggregateOperations() {
}
/**
* Returns an aggregate operation that computes the number of items.
*/
@Nonnull
public static <T> AggregateOperation1<T, LongAccumulator, Long> counting() {
return AggregateOperation
.withCreate(LongAccumulator::new)
.andAccumulate((LongAccumulator a, T item) -> a.addExact(1))
.andCombine(LongAccumulator::addExact)
.andDeduct(LongAccumulator::subtract)
.andFinish(LongAccumulator::get);
}
/**
* Returns an aggregate operation that computes the sum of the {@code long}
* values it obtains by applying {@code getLongValueFn} to each item.
*
* @param <T> input item type
*/
@Nonnull
public static <T> AggregateOperation1<T, LongAccumulator, Long> summingLong(
@Nonnull DistributedToLongFunction<T> getLongValueFn
) {
return AggregateOperation
.withCreate(LongAccumulator::new)
.andAccumulate((LongAccumulator a, T item) -> a.addExact(getLongValueFn.applyAsLong(item)))
.andCombine(LongAccumulator::addExact)
.andDeduct(LongAccumulator::subtractExact)
.andFinish(LongAccumulator::get);
}
/**
* Returns an aggregate operation that computes the sum of the {@code double}
* values it obtains by applying {@code getDoubleValueFn} to each item.
*
* @param <T> input item type
*/
@Nonnull
public static <T> AggregateOperation1<T, DoubleAccumulator, Double> summingDouble(
@Nonnull DistributedToDoubleFunction<T> getDoubleValueFn
) {
return AggregateOperation
.withCreate(DoubleAccumulator::new)
.andAccumulate((DoubleAccumulator a, T item) -> a.add(getDoubleValueFn.applyAsDouble(item)))
.andCombine(DoubleAccumulator::add)
.andDeduct(DoubleAccumulator::subtract)
.andFinish(DoubleAccumulator::get);
}
/**
* Returns an aggregate operation that computes the minimal item according
* to the given {@code comparator}.
* <p>
* This aggregate operation does not implement the {@link
* AggregateOperation1#deductFn() deduct} primitive.
*
* @param <T> input item type
*/
@Nonnull
public static <T> AggregateOperation1<T, MutableReference<T>, T> minBy(
@Nonnull DistributedComparator<? super T> comparator
) {
return maxBy(comparator.reversed());
}
/**
* Returns an aggregate operation that computes the maximal item according
* to the given {@code comparator}.
* <p>
* This aggregate operation does not implement the {@link
* AggregateOperation1#deductFn() deduct} primitive.
*
* @param <T> input item type
*/
@Nonnull
public static <T> AggregateOperation1<T, MutableReference<T>, T> maxBy(
@Nonnull DistributedComparator<? super T> comparator
) {
return AggregateOperation
.withCreate(MutableReference<T>::new)
.andAccumulate((MutableReference<T> a, T i) -> {
if (a.get() == null || comparator.compare(i, a.get()) > 0) {
a.set(i);
}
})
.andCombine((a1, a2) -> {
if (a1.get() == null || comparator.compare(a1.get(), a2.get()) < 0) {
a1.set(a2.get());
}
})
.andFinish(MutableReference::get);
}
/**
* Returns an aggregate operation that computes the arithmetic mean of the
* {@code long} values it obtains by applying {@code getLongValueFn} to
* each item.
*
* @param <T> input item type
*/
@Nonnull
public static <T> AggregateOperation1<T, LongLongAccumulator, Double> averagingLong(
@Nonnull DistributedToLongFunction<T> getLongValueFn
) {
// accumulator.value1 is count
// accumulator.value2 is sum
return AggregateOperation
.withCreate(LongLongAccumulator::new)
.andAccumulate((LongLongAccumulator a, T i) -> {
// a bit faster check than in addExact, specialized for increment
if (a.getValue1() == Long.MAX_VALUE) {
throw new ArithmeticException("Counter overflow");
}
a.setValue1(a.getValue1() + 1);
a.setValue2(Math.addExact(a.getValue2(), getLongValueFn.applyAsLong(i)));
})
.andCombine((a1, a2) -> {
a1.setValue1(Math.addExact(a1.getValue1(), a2.getValue1()));
a1.setValue2(Math.addExact(a1.getValue2(), a2.getValue2()));
})
.andDeduct((a1, a2) -> {
a1.setValue1(Math.subtractExact(a1.getValue1(), a2.getValue1()));
a1.setValue2(Math.subtractExact(a1.getValue2(), a2.getValue2()));
})
.andFinish(a -> (double) a.getValue2() / a.getValue1());
}
/**
* Returns an aggregate operation that computes the arithmetic mean of the
* {@code double} values it obtains by applying {@code getDoubleValueFn} to
* each item.
*
* @param <T> input item type
*/
@Nonnull
public static <T> AggregateOperation1<T, LongDoubleAccumulator, Double> averagingDouble(
@Nonnull DistributedToDoubleFunction<T> getDoubleValueFn
) {
// accumulator.value1 is count
// accumulator.value2 is sum
return AggregateOperation
.withCreate(LongDoubleAccumulator::new)
.andAccumulate((LongDoubleAccumulator a, T item) -> {
// a bit faster check than in addExact, specialized for increment
if (a.getValue1() == Long.MAX_VALUE) {
throw new ArithmeticException("Counter overflow");
}
a.setValue1(a.getValue1() + 1);
a.setValue2(a.getValue2() + getDoubleValueFn.applyAsDouble(item));
})
.andCombine((a1, a2) -> {
a1.setValue1(Math.addExact(a1.getValue1(), a2.getValue1()));
a1.setValue2(a1.getValue2() + a2.getValue2());
})
.andDeduct((a1, a2) -> {
a1.setValue1(Math.subtractExact(a1.getValue1(), a2.getValue1()));
a1.setValue2(a1.getValue2() - a2.getValue2());
})
.andFinish(a -> a.getValue2() / a.getValue1());
}
/**
* Returns an aggregate operation that computes a linear trend on the items.
* The operation will produce a {@code double}-valued coefficient that
* approximates the rate of change of {@code y} as a function of {@code x},
* where {@code x} and {@code y} are {@code long} quantities obtained
* by applying the two provided functions to each item.
*/
@Nonnull
public static <T> AggregateOperation1<T, LinTrendAccumulator, Double> linearTrend(
@Nonnull DistributedToLongFunction<T> getXFn,
@Nonnull DistributedToLongFunction<T> getYFn
) {
return AggregateOperation
.withCreate(LinTrendAccumulator::new)
.andAccumulate((LinTrendAccumulator a, T item) ->
a.accumulate(getXFn.applyAsLong(item), getYFn.applyAsLong(item)))
.andCombine(LinTrendAccumulator::combine)
.andDeduct(LinTrendAccumulator::deduct)
.andFinish(LinTrendAccumulator::finish);
}
/**
* Returns a composite operation that computes multiple aggregate
* operations and returns their results in a {@code List<Object>}.
*
* @param operations aggregate operations to apply
*/
@SafeVarargs @Nonnull
public static <T> AggregateOperation1<T, List<Object>, List<Object>> allOf(
@Nonnull AggregateOperation1<? super T, ?, ?>... operations
) {
AggregateOperation1[] untypedOps = operations;
return AggregateOperation
.withCreate(() -> {
List<Object> res = new ArrayList<>(untypedOps.length);
for (AggregateOperation untypedOp : untypedOps) {
res.add(untypedOp.createFn().get());
}
return res;
})
.andAccumulate((List<Object> accs, T item) -> {
for (int i = 0; i < untypedOps.length; i++) {
untypedOps[i].accumulateFn().accept(accs.get(i), item);
}
})
.andCombine(
// we can support combine only if all operations do
Stream.of(untypedOps).allMatch(o -> o.combineFn() != null)
? (accs1, accs2) -> {
for (int i = 0; i < untypedOps.length; i++) {
untypedOps[i].combineFn().accept(accs1.get(i), accs2.get(i));
}
} : null)
.andDeduct(
// we can support deduct only if all operations do
Stream.of(untypedOps).allMatch(o -> o.deductFn() != null)
? (accs1, accs2) -> {
for (int i = 0; i < untypedOps.length; i++) {
untypedOps[i].deductFn().accept(accs1.get(i), accs2.get(i));
}
}
: null)
.andFinish(accs -> {
List<Object> res = new ArrayList<>(untypedOps.length);
for (int i = 0; i < untypedOps.length; i++) {
res.add(untypedOps[i].finishFn().apply(accs.get(i)));
}
return res;
});
}
/**
* Adapts an aggregate operation accepting items of type {@code
* U} to one accepting items of type {@code T} by applying a mapping
* function to each item before accumulation.
* <p>
* If the {@code mapFn} returns {@code null}, the item won't be aggregated
* at all. This allows applying a filter at the same time.
*
* @param <T> input item type
* @param <U> input type of the downstream aggregate operation
* @param <A> downstream operation's accumulator type
* @param <R> downstream operation's result type
* @param mapFn the function to apply to input items
* @param downstream the downstream aggregate operation
*/
public static <T, U, A, R>
AggregateOperation1<T, ?, R> mapping(
@Nonnull DistributedFunction<? super T, ? extends U> mapFn,
@Nonnull AggregateOperation1<? super U, A, R> downstream
) {
DistributedBiConsumer<? super A, ? super U> downstreamAccumulateFn = downstream.accumulateFn();
return AggregateOperation
.withCreate(downstream.createFn())
.andAccumulate((A a, T t) -> {
U mapped = mapFn.apply(t);
if (mapped != null) {
downstreamAccumulateFn.accept(a, mapped);
}
})
.andCombine(downstream.combineFn())
.andDeduct(downstream.deductFn())
.andFinish(downstream.finishFn());
}
/**
* Returns an aggregate operation that accumulates the items into a {@code
* Collection}. It creates the collections as needed by calling the
* provided {@code createCollectionFn}.
* <p>
* If you use a collection that preserves the insertion order, keep in mind
* that there is no specified order in which the items are aggregated.
*
* @param <T> input item type
* @param <C> the type of the collection
* @param createCollectionFn a {@code Supplier} which returns a new, empty {@code Collection} of the
* appropriate type
*/
public static <T, C extends Collection<T>> AggregateOperation1<T, C, C> toCollection(
DistributedSupplier<C> createCollectionFn
) {
return AggregateOperation
.withCreate(createCollectionFn)
.<T>andAccumulate(Collection::add)
.andCombine(Collection::addAll)
.andIdentityFinish();
}
/**
* Returns an aggregate operation that accumulates the items into an {@code
* ArrayList}.
*
* @param <T> input item type
*/
public static <T> AggregateOperation1<T, List<T>, List<T>> toList() {
return toCollection(ArrayList::new);
}
/**
* Returns an aggregate operation that accumulates the items into a {@code
* HashSet}.
*
* @param <T> input item type
*/
public static <T>
AggregateOperation1<T, ?, Set<T>> toSet() {
return toCollection(HashSet::new);
}
/**
* Returns an aggregate operation that accumulates the items into a
* {@code HashMap} whose keys and values are the result of applying
* the provided mapping functions.
* <p>
* This aggregate operation does not tolerate duplicate keys and will
* throw {@code IllegalStateException} if it detects them. If your
* data contains duplicates, use the {@link #toMap(DistributedFunction,
* DistributedFunction, DistributedBinaryOperator) toMap()} overload
* that can resolve them.
*
* @param <T> input item type
* @param <K> type of the key
* @param <U> type of the value
* @param getKeyFn a function to extract the key from the input item
* @param getValueFn a function to extract the value from the input item
*
* @see #toMap(DistributedFunction, DistributedFunction, DistributedBinaryOperator)
* @see #toMap(DistributedFunction, DistributedFunction, DistributedBinaryOperator, DistributedSupplier)
*/
public static <T, K, U> AggregateOperation1<T, Map<K, U>, Map<K, U>> toMap(
DistributedFunction<? super T, ? extends K> getKeyFn,
DistributedFunction<? super T, ? extends U> getValueFn
) {
return toMap(getKeyFn, getValueFn, throwingMerger(), HashMap::new);
}
/**
* Returns an aggregate operation that accumulates the items into a
* {@code HashMap} whose keys and values are the result of applying
* the provided mapping functions.
* <p>
* This aggregate operation resolves duplicate keys by applying {@code
* mergeFn} to the conflicting values. {@code mergeFn} will act upon the
* values after {@code getValueFn} has already been applied.
*
* @param <T> input item type
* @param <K> the type of key
* @param <U> the output type of the value mapping function
* @param getKeyFn a function to extract the key from input item
* @param getValueFn a function to extract value from input item
* @param mergeFn a merge function, used to resolve collisions between
* values associated with the same key, as supplied
* to {@link Map#merge(Object, Object,
* java.util.function.BiFunction)}
*
* @see #toMap(DistributedFunction, DistributedFunction)
* @see #toMap(DistributedFunction, DistributedFunction, DistributedBinaryOperator, DistributedSupplier)
*/
public static <T, K, U> AggregateOperation1<T, Map<K, U>, Map<K, U>> toMap(
DistributedFunction<? super T, ? extends K> getKeyFn,
DistributedFunction<? super T, ? extends U> getValueFn,
DistributedBinaryOperator<U> mergeFn
) {
return toMap(getKeyFn, getValueFn, mergeFn, HashMap::new);
}
/**
* Returns an {@code AggregateOperation1} that accumulates elements
* into a {@code Map} whose keys and values are the result of applying the
* provided mapping functions to the input elements.
* <p>
* If the mapped keys contain duplicates (according to {@link
* Object#equals(Object)}), the value mapping function is applied to each
* equal element, and the results are merged using the provided merging
* function. The {@code Map} is created by a provided {@code createMapFn}
* function.
*
* @param <T> input item type
* @param <K> the output type of the key mapping function
* @param <U> the output type of the value mapping function
* @param <M> the type of the resulting {@code Map}
* @param getKeyFn a function to extract the key from input item
* @param getValueFn a function to extract value from input item
* @param mergeFn a merge function, used to resolve collisions between
* values associated with the same key, as supplied
* to {@link Map#merge(Object, Object,
* java.util.function.BiFunction)}
* @param createMapFn a function which returns a new, empty {@code Map} into
* which the results will be inserted
*
* @see #toMap(DistributedFunction, DistributedFunction)
* @see #toMap(DistributedFunction, DistributedFunction, DistributedBinaryOperator)
*/
public static <T, K, U, M extends Map<K, U>> AggregateOperation1<T, M, M> toMap(
DistributedFunction<? super T, ? extends K> getKeyFn,
DistributedFunction<? super T, ? extends U> getValueFn,
DistributedBinaryOperator<U> mergeFn,
DistributedSupplier<M> createMapFn
) {
DistributedBiConsumer<M, T> accumulateFn =
(map, element) -> map.merge(getKeyFn.apply(element), getValueFn.apply(element), mergeFn);
return AggregateOperation
.withCreate(createMapFn)
.andAccumulate(accumulateFn)
.andCombine(mapMerger(mergeFn))
.andIdentityFinish();
}
private static <T> DistributedBinaryOperator<T> throwingMerger() {
return (u, v) -> {
throw new IllegalStateException("Duplicate key: " + u);
};
}
private static <K, V, M extends Map<K, V>> DistributedBiConsumer<M, M> mapMerger(
DistributedBinaryOperator<V> mergeFunction
) {
return (m1, m2) -> {
for (Map.Entry<K, V> e : m2.entrySet()) {
m1.merge(e.getKey(), e.getValue(), mergeFunction);
}
};
}
/**
* A reducing operation maintains an accumulated value that starts out as
* {@code emptyAccValue} and is iteratively transformed by applying
* {@code combineAccValuesFn} to it and each stream item's accumulated
* value, as returned from {@code toAccValueFn}. {@code combineAccValuesFn}
* must be <em>associative</em> because it will also be used to combine
* partial results, as well as <em>commutative</em> because the encounter
* order of items is unspecified.
* <p>
* The optional {@code deductAccValueFn} allows Jet to compute the sliding
* window in O(1) time. It must undo the effects of a previous {@code
* combineAccValuesFn} call:
* <pre>
* A accVal; (has some pre-existing value)
* A itemAccVal = toAccValueFn.apply(item);
* A combined = combineAccValuesFn.apply(accVal, itemAccVal);
* A deducted = deductAccValueFn.apply(combined, itemAccVal);
* assert deducted.equals(accVal);
* </pre>
*
* @param emptyAccValue the reducing operation's emptyAccValue element
* @param toAccValueFn transforms the stream item into its accumulated value
* @param combineAccValuesFn combines two accumulated values into one
* @param deductAccValueFn deducts the right-hand accumulated value from the left-hand one
* (optional)
* @param <T> input item type
* @param <A> type of the accumulated value
*/
@Nonnull
public static <T, A> AggregateOperation1<T, MutableReference<A>, A> reducing(
@Nonnull A emptyAccValue,
@Nonnull DistributedFunction<? super T, ? extends A> toAccValueFn,
@Nonnull DistributedBinaryOperator<A> combineAccValuesFn,
@Nullable DistributedBinaryOperator<A> deductAccValueFn
) {
return AggregateOperation
.withCreate(() -> new MutableReference<>(emptyAccValue))
.andAccumulate((MutableReference<A> a, T t) ->
a.set(combineAccValuesFn.apply(a.get(), toAccValueFn.apply(t))))
.andCombine((a, b) -> a.set(combineAccValuesFn.apply(a.get(), b.get())))
.andDeduct(deductAccValueFn != null
? (a, b) -> a.set(deductAccValueFn.apply(a.get(), b.get()))
: null)
.andFinish(MutableReference::get);
}
}
| hazelcast-jet-core/src/main/java/com/hazelcast/jet/aggregate/AggregateOperations.java | /*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.jet.aggregate;
import com.hazelcast.jet.accumulator.DoubleAccumulator;
import com.hazelcast.jet.accumulator.LinTrendAccumulator;
import com.hazelcast.jet.accumulator.LongAccumulator;
import com.hazelcast.jet.accumulator.LongDoubleAccumulator;
import com.hazelcast.jet.accumulator.LongLongAccumulator;
import com.hazelcast.jet.accumulator.MutableReference;
import com.hazelcast.jet.function.DistributedBiConsumer;
import com.hazelcast.jet.function.DistributedBinaryOperator;
import com.hazelcast.jet.function.DistributedComparator;
import com.hazelcast.jet.function.DistributedFunction;
import com.hazelcast.jet.function.DistributedSupplier;
import com.hazelcast.jet.function.DistributedToDoubleFunction;
import com.hazelcast.jet.function.DistributedToLongFunction;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;
/**
* Utility class with factory methods for several useful windowing
* operations.
*/
public final class AggregateOperations {
private AggregateOperations() {
}
/**
* Returns an operation that tracks the count of items in the window.
*/
@Nonnull
public static <T> AggregateOperation1<T, LongAccumulator, Long> counting() {
return AggregateOperation
.withCreate(LongAccumulator::new)
.andAccumulate((LongAccumulator a, T item) -> a.addExact(1))
.andCombine(LongAccumulator::addExact)
.andDeduct(LongAccumulator::subtract)
.andFinish(LongAccumulator::get);
}
/**
* Returns an operation that tracks the sum of the quantity returned by
* {@code getLongValueFn} applied to each item in the window.
*
* @param <T> Input item type
*/
@Nonnull
public static <T> AggregateOperation1<T, LongAccumulator, Long> summingLong(
@Nonnull DistributedToLongFunction<T> getLongValueFn
) {
return AggregateOperation
.withCreate(LongAccumulator::new)
.andAccumulate((LongAccumulator a, T item) -> a.addExact(getLongValueFn.applyAsLong(item)))
.andCombine(LongAccumulator::addExact)
.andDeduct(LongAccumulator::subtractExact)
.andFinish(LongAccumulator::get);
}
/**
* Returns an operation that tracks the sum of the quantity returned by
* {@code getDoubleValueFn} applied to each item in the window.
*
* @param <T> Input item type
*/
@Nonnull
public static <T> AggregateOperation1<T, DoubleAccumulator, Double> summingDouble(
@Nonnull DistributedToDoubleFunction<T> getDoubleValueFn
) {
return AggregateOperation
.withCreate(DoubleAccumulator::new)
.andAccumulate((DoubleAccumulator a, T item) -> a.add(getDoubleValueFn.applyAsDouble(item)))
.andCombine(DoubleAccumulator::add)
.andDeduct(DoubleAccumulator::subtract)
.andFinish(DoubleAccumulator::get);
}
/**
* Returns an operation that returns the minimum item, according the given
* {@code comparator}.
* <p>
* The implementation doesn't have the <i>deduction function </i>. {@link
* AggregateOperation1#deductFn() See note here}.
*
* @param <T> Input item type
*/
@Nonnull
public static <T> AggregateOperation1<T, MutableReference<T>, T> minBy(
@Nonnull DistributedComparator<? super T> comparator
) {
return maxBy(comparator.reversed());
}
/**
* Returns an operation that returns the maximum item, according the given
* {@code comparator}.
* <p>
* The implementation doesn't have the <i>deduction function </i>. {@link
* AggregateOperation1#deductFn() See note here}.
*
* @param <T> Input item type
*/
@Nonnull
public static <T> AggregateOperation1<T, MutableReference<T>, T> maxBy(
@Nonnull DistributedComparator<? super T> comparator
) {
return AggregateOperation
.withCreate(MutableReference<T>::new)
.andAccumulate((MutableReference<T> a, T i) -> {
if (a.get() == null || comparator.compare(i, a.get()) > 0) {
a.set(i);
}
})
.andCombine((a1, a2) -> {
if (a1.get() == null || comparator.compare(a1.get(), a2.get()) < 0) {
a1.set(a2.get());
}
})
.andFinish(MutableReference::get);
}
/**
* Returns an operation that calculates the arithmetic mean of {@code long}
* values returned by the {@code getLongValueFn} function.
*
* @param <T> Input item type
*/
@Nonnull
public static <T> AggregateOperation1<T, LongLongAccumulator, Double> averagingLong(
@Nonnull DistributedToLongFunction<T> getLongValueFn
) {
// accumulator.value1 is count
// accumulator.value2 is sum
return AggregateOperation
.withCreate(LongLongAccumulator::new)
.andAccumulate((LongLongAccumulator a, T i) -> {
// a bit faster check than in addExact, specialized for increment
if (a.getValue1() == Long.MAX_VALUE) {
throw new ArithmeticException("Counter overflow");
}
a.setValue1(a.getValue1() + 1);
a.setValue2(Math.addExact(a.getValue2(), getLongValueFn.applyAsLong(i)));
})
.andCombine((a1, a2) -> {
a1.setValue1(Math.addExact(a1.getValue1(), a2.getValue1()));
a1.setValue2(Math.addExact(a1.getValue2(), a2.getValue2()));
})
.andDeduct((a1, a2) -> {
a1.setValue1(Math.subtractExact(a1.getValue1(), a2.getValue1()));
a1.setValue2(Math.subtractExact(a1.getValue2(), a2.getValue2()));
})
.andFinish(a -> (double) a.getValue2() / a.getValue1());
}
/**
* Returns an operation that calculates the arithmetic mean of {@code double}
* values returned by the {@code getDoubleValueFn} function.
*
* @param <T> Input item type
*/
@Nonnull
public static <T> AggregateOperation1<T, LongDoubleAccumulator, Double> averagingDouble(
@Nonnull DistributedToDoubleFunction<T> getDoubleValueFn
) {
// accumulator.value1 is count
// accumulator.value2 is sum
return AggregateOperation
.withCreate(LongDoubleAccumulator::new)
.andAccumulate((LongDoubleAccumulator a, T item) -> {
// a bit faster check than in addExact, specialized for increment
if (a.getValue1() == Long.MAX_VALUE) {
throw new ArithmeticException("Counter overflow");
}
a.setValue1(a.getValue1() + 1);
a.setValue2(a.getValue2() + getDoubleValueFn.applyAsDouble(item));
})
.andCombine((a1, a2) -> {
a1.setValue1(Math.addExact(a1.getValue1(), a2.getValue1()));
a1.setValue2(a1.getValue2() + a2.getValue2());
})
.andDeduct((a1, a2) -> {
a1.setValue1(Math.subtractExact(a1.getValue1(), a2.getValue1()));
a1.setValue2(a1.getValue2() - a2.getValue2());
})
.andFinish(a -> a.getValue2() / a.getValue1());
}
/**
* Returns an operation that computes a linear trend on the items in the
* window. The operation will produce a {@code double}-valued coefficient
* that approximates the rate of change of {@code y} as a function of
* {@code x}, where {@code x} and {@code y} are {@code long} quantities
* extracted from each item by the two provided functions.
*/
@Nonnull
public static <T> AggregateOperation1<T, LinTrendAccumulator, Double> linearTrend(
@Nonnull DistributedToLongFunction<T> getXFn,
@Nonnull DistributedToLongFunction<T> getYFn
) {
return AggregateOperation
.withCreate(LinTrendAccumulator::new)
.andAccumulate((LinTrendAccumulator a, T item) ->
a.accumulate(getXFn.applyAsLong(item), getYFn.applyAsLong(item)))
.andCombine(LinTrendAccumulator::combine)
.andDeduct(LinTrendAccumulator::deduct)
.andFinish(LinTrendAccumulator::finish);
}
/**
* Returns an operation, that calculates multiple aggregations and returns their value in
* {@code List<Object>}.
* <p>
* Useful, if you want to calculate multiple values for the same window.
*
* @param operations Operations to calculate.
*/
@SafeVarargs @Nonnull
public static <T> AggregateOperation1<T, List<Object>, List<Object>> allOf(
@Nonnull AggregateOperation1<? super T, ?, ?>... operations
) {
AggregateOperation1[] untypedOps = operations;
return AggregateOperation
.withCreate(() -> {
List<Object> res = new ArrayList<>(untypedOps.length);
for (AggregateOperation untypedOp : untypedOps) {
res.add(untypedOp.createFn().get());
}
return res;
})
.andAccumulate((List<Object> accs, T item) -> {
for (int i = 0; i < untypedOps.length; i++) {
untypedOps[i].accumulateFn().accept(accs.get(i), item);
}
})
.andCombine(
// we can support combine only if all operations do
Stream.of(untypedOps).allMatch(o -> o.combineFn() != null)
? (accs1, accs2) -> {
for (int i = 0; i < untypedOps.length; i++) {
untypedOps[i].combineFn().accept(accs1.get(i), accs2.get(i));
}
} : null)
.andDeduct(
// we can support deduct only if all operations do
Stream.of(untypedOps).allMatch(o -> o.deductFn() != null)
? (accs1, accs2) -> {
for (int i = 0; i < untypedOps.length; i++) {
untypedOps[i].deductFn().accept(accs1.get(i), accs2.get(i));
}
}
: null)
.andFinish(accs -> {
List<Object> res = new ArrayList<>(untypedOps.length);
for (int i = 0; i < untypedOps.length; i++) {
res.add(untypedOps[i].finishFn().apply(accs.get(i)));
}
return res;
});
}
/**
* Adapts an {@code AggregateOperation1} accepting elements of type {@code
* U} to one accepting elements of type {@code T} by applying a mapping
* function to each input element before accumulation.
* <p>
* If the {@code mapFn} maps to {@code null}, the item won't be aggregated
* at all. This allows the mapping to be used as a filter at the same time.
* <p>
* This operation is useful if we cannot precede the aggregating vertex
* with a {@link
* com.hazelcast.jet.core.processor.Processors#mapP(DistributedFunction) map()}
* processors, which is useful
*
* @param <T> the type of the input elements
* @param <U> type of elements accepted by downstream operation
* @param <A> intermediate accumulation type of the downstream operation
* @param <R> result type of operation
* @param mapFn a function to be applied to the input elements
* @param downstream an operation which will accept mapped values
*/
public static <T, U, A, R>
AggregateOperation1<T, ?, R> mapping(
@Nonnull DistributedFunction<? super T, ? extends U> mapFn,
@Nonnull AggregateOperation1<? super U, A, R> downstream
) {
DistributedBiConsumer<? super A, ? super U> downstreamAccumulateFn = downstream.accumulateFn();
return AggregateOperation
.withCreate(downstream.createFn())
.andAccumulate((A a, T t) -> {
U mapped = mapFn.apply(t);
if (mapped != null) {
downstreamAccumulateFn.accept(a, mapped);
}
})
.andCombine(downstream.combineFn())
.andDeduct(downstream.deductFn())
.andFinish(downstream.finishFn());
}
/**
* Returns an {@code AggregateOperation1} that accumulates the input
* elements into a new {@code Collection}. The {@code Collection} is
* created by the provided factory.
* <p>
* Note: due to the distributed nature of processing the order might be
* unspecified.
*
* @param <T> the type of the input elements
* @param <C> the type of the resulting {@code Collection}
* @param createCollectionFn a {@code Supplier} which returns a new, empty
* {@code Collection} of the appropriate type
*/
public static <T, C extends Collection<T>> AggregateOperation1<T, C, C> toCollection(
DistributedSupplier<C> createCollectionFn
) {
return AggregateOperation
.withCreate(createCollectionFn)
.andAccumulate(Collection<T>::add)
.andCombine(Collection::addAll)
.andIdentityFinish();
}
/**
* Returns an {@code AggregateOperation1} that accumulates the input
* elements into a new {@code ArrayList}.
*
* @param <T> the type of the input elements
*/
public static <T> AggregateOperation1<T, List<T>, List<T>> toList() {
return toCollection(ArrayList::new);
}
/**
* Returns an {@code AggregateOperation1} that accumulates the input
* elements into a new {@code HashSet}.
*
* @param <T> the type of the input elements
*/
public static <T>
AggregateOperation1<T, ?, Set<T>> toSet() {
return toCollection(HashSet::new);
}
/**
* Returns an {@code AggregateOperation1} that accumulates elements
* into a {@code HashMap} whose keys and values are the result of applying
* the provided mapping functions to the input elements.
* <p>
* If the mapped keys contain duplicates (according to {@link
* Object#equals(Object)}), an {@code IllegalStateException} is thrown when
* the collection operation is performed. If the mapped keys may have
* duplicates, use {@link #toMap(DistributedFunction, DistributedFunction,
* DistributedBinaryOperator)} instead.
*
* @param <T> the type of the input elements
* @param <K> the output type of the key mapping function
* @param <U> the output type of the value mapping function
* @param getKeyFn a function to extract the key from input item
* @param getValueFn a function to extract value from input item
*
* @see #toMap(DistributedFunction, DistributedFunction,
* DistributedBinaryOperator)
* @see #toMap(DistributedFunction, DistributedFunction,
* DistributedBinaryOperator, DistributedSupplier)
*/
public static <T, K, U> AggregateOperation1<T, Map<K, U>, Map<K, U>> toMap(
DistributedFunction<? super T, ? extends K> getKeyFn,
DistributedFunction<? super T, ? extends U> getValueFn
) {
return toMap(getKeyFn, getValueFn, throwingMerger(), HashMap::new);
}
/**
* Returns an {@code AggregateOperation1} that accumulates elements
* into a {@code HashMap} whose keys and values are the result of applying
* the provided mapping functions to the input elements.
*
* <p>If the mapped keys contains duplicates (according to {@link
* Object#equals(Object)}), the value mapping function is applied to each
* equal element, and the results are merged using the provided merging
* function.
*
* @param <T> the type of the input elements
* @param <K> the output type of the key mapping function
* @param <U> the output type of the value mapping function
* @param getKeyFn a function to extract the key from input item
* @param getValueFn a function to extract value from input item
* @param mergeFn a merge function, used to resolve collisions between
* values associated with the same key, as supplied
* to {@link Map#merge(Object, Object,
* java.util.function.BiFunction)}
*
* @see #toMap(DistributedFunction, DistributedFunction)
* @see #toMap(DistributedFunction, DistributedFunction,
* DistributedBinaryOperator, DistributedSupplier)
*/
public static <T, K, U> AggregateOperation1<T, Map<K, U>, Map<K, U>> toMap(
DistributedFunction<? super T, ? extends K> getKeyFn,
DistributedFunction<? super T, ? extends U> getValueFn,
DistributedBinaryOperator<U> mergeFn
) {
return toMap(getKeyFn, getValueFn, mergeFn, HashMap::new);
}
/**
* Returns an {@code AggregateOperation1} that accumulates elements
* into a {@code Map} whose keys and values are the result of applying the
* provided mapping functions to the input elements.
* <p>
* If the mapped keys contain duplicates (according to {@link
* Object#equals(Object)}), the value mapping function is applied to each
* equal element, and the results are merged using the provided merging
* function. The {@code Map} is created by a provided {@code createMapFn}
* function.
*
* @param <T> the type of the input elements
* @param <K> the output type of the key mapping function
* @param <U> the output type of the value mapping function
* @param <M> the type of the resulting {@code Map}
* @param getKeyFn a function to extract the key from input item
* @param getValueFn a function to extract value from input item
* @param mergeFn a merge function, used to resolve collisions between
* values associated with the same key, as supplied
* to {@link Map#merge(Object, Object,
* java.util.function.BiFunction)}
* @param createMapFn a function which returns a new, empty {@code Map} into
* which the results will be inserted
*
* @see #toMap(DistributedFunction, DistributedFunction)
* @see #toMap(DistributedFunction, DistributedFunction, DistributedBinaryOperator)
*/
public static <T, K, U, M extends Map<K, U>> AggregateOperation1<T, M, M> toMap(
DistributedFunction<? super T, ? extends K> getKeyFn,
DistributedFunction<? super T, ? extends U> getValueFn,
DistributedBinaryOperator<U> mergeFn,
DistributedSupplier<M> createMapFn
) {
DistributedBiConsumer<M, T> accumulateFn =
(map, element) -> map.merge(getKeyFn.apply(element), getValueFn.apply(element), mergeFn);
return AggregateOperation
.withCreate(createMapFn)
.andAccumulate(accumulateFn)
.andCombine(mapMerger(mergeFn))
.andIdentityFinish();
}
private static <T> DistributedBinaryOperator<T> throwingMerger() {
return (u, v) -> {
throw new IllegalStateException("Duplicate key: " + u);
};
}
private static <K, V, M extends Map<K, V>> DistributedBiConsumer<M, M> mapMerger(
DistributedBinaryOperator<V> mergeFunction
) {
return (m1, m2) -> {
for (Map.Entry<K, V> e : m2.entrySet()) {
m1.merge(e.getKey(), e.getValue(), mergeFunction);
}
};
}
/**
* A reducing operation maintains an accumulated value that starts out as
* {@code emptyAccValue} and is being iteratively transformed by applying
* the {@code combine} primitive to it and each stream item's accumulated
* value, as returned from {@code toAccValueFn}. The {@code combine} must
* be <em>associative</em> because it will also be used to combine partial
* results, and <em>commutative</em> because the encounter order of items
* is unspecified.
* <p>
* The optional {@code deduct} primitive allows Jet to compute the sliding
* window in O(1) time. It must undo the effects of a previous
* {@code combine}:
* <pre>
* A accVal; (has some pre-existing value)
* A itemAccVal = toAccValueFn.apply(item);
* A combined = combineAccValuesFn.apply(accVal, itemAccVal);
* A deducted = deductAccValueFn.apply(combined, itemAccVal);
* assert deducted.equals(accVal);
* </pre>
*
* @param emptyAccValue the reducing operation's emptyAccValue element
* @param toAccValueFn transforms the stream item into its accumulated value
* @param combineAccValuesFn combines two accumulated values into one
* @param deductAccValueFn deducts the right-hand accumulated value from the left-hand one
* (optional)
* @param <T> type of the stream item
* @param <A> type of the accumulated value
*/
@Nonnull
public static <T, A> AggregateOperation1<T, MutableReference<A>, A> reducing(
@Nonnull A emptyAccValue,
@Nonnull DistributedFunction<? super T, ? extends A> toAccValueFn,
@Nonnull DistributedBinaryOperator<A> combineAccValuesFn,
@Nullable DistributedBinaryOperator<A> deductAccValueFn
) {
return AggregateOperation
.withCreate(() -> new MutableReference<>(emptyAccValue))
.andAccumulate((MutableReference<A> a, T t) ->
a.set(combineAccValuesFn.apply(a.get(), toAccValueFn.apply(t))))
.andCombine((a, b) -> a.set(combineAccValuesFn.apply(a.get(), b.get())))
.andDeduct(deductAccValueFn != null
? (a, b) -> a.set(deductAccValueFn.apply(a.get(), b.get()))
: null)
.andFinish(MutableReference::get);
}
}
| Fix and improve AggregateOperations Javadoc
Fixes #598 | hazelcast-jet-core/src/main/java/com/hazelcast/jet/aggregate/AggregateOperations.java | Fix and improve AggregateOperations Javadoc |
|
Java | apache-2.0 | ee6e445cf552d5756000231a5cd939aa041b43f5 | 0 | zstackio/zstack,MatheMatrix/zstack,MatheMatrix/zstack,zstackio/zstack,AlanJager/zstack,zstackorg/zstack,MatheMatrix/zstack,AlanJager/zstack,AlanJager/zstack,zstackorg/zstack,zstackio/zstack | package org.zstack.storage.ceph.primary;
import org.springframework.beans.factory.annotation.Autowired;
import org.zstack.core.Platform;
import org.zstack.core.asyncbatch.While;
import org.zstack.core.cloudbus.CloudBusCallBack;
import org.zstack.core.cloudbus.CloudBusListCallBack;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.db.Q;
import org.zstack.core.db.SQL;
import org.zstack.core.db.SQLBatch;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.thread.AsyncThread;
import org.zstack.core.thread.ChainTask;
import org.zstack.core.thread.SyncTaskChain;
import org.zstack.core.thread.ThreadFacade;
import org.zstack.core.timeout.ApiTimeoutManager;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.core.workflow.ShareFlow;
import org.zstack.header.HasThreadContext;
import org.zstack.header.agent.ReloadableCommand;
import org.zstack.header.cluster.ClusterVO;
import org.zstack.header.cluster.ClusterVO_;
import org.zstack.header.core.*;
import org.zstack.header.core.progress.TaskProgressRange;
import org.zstack.header.core.trash.CleanTrashResult;
import org.zstack.header.core.validation.Validation;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.ErrorCodeList;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.host.HostConstant;
import org.zstack.header.host.HostStatus;
import org.zstack.header.host.HostVO;
import org.zstack.header.host.HostVO_;
import org.zstack.header.image.*;
import org.zstack.header.image.ImageConstant.ImageMediaType;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.MessageReply;
import org.zstack.header.rest.RESTFacade;
import org.zstack.header.storage.backup.*;
import org.zstack.header.storage.primary.*;
import org.zstack.header.storage.primary.VolumeSnapshotCapability.VolumeSnapshotArrangementType;
import org.zstack.header.storage.snapshot.*;
import org.zstack.header.vm.VmInstanceSpec.ImageSpec;
import org.zstack.header.volume.*;
import org.zstack.identity.AccountManager;
import org.zstack.kvm.*;
import org.zstack.kvm.KvmSetupSelfFencerExtensionPoint.KvmCancelSelfFencerParam;
import org.zstack.kvm.KvmSetupSelfFencerExtensionPoint.KvmSetupSelfFencerParam;
import org.zstack.storage.backup.sftp.GetSftpBackupStorageDownloadCredentialMsg;
import org.zstack.storage.backup.sftp.GetSftpBackupStorageDownloadCredentialReply;
import org.zstack.storage.backup.sftp.SftpBackupStorageConstant;
import org.zstack.storage.ceph.*;
import org.zstack.storage.ceph.CephMonBase.PingResult;
import org.zstack.storage.ceph.backup.CephBackupStorageVO;
import org.zstack.storage.ceph.backup.CephBackupStorageVO_;
import org.zstack.storage.ceph.primary.CephPrimaryStorageMonBase.PingOperationFailure;
import org.zstack.storage.primary.PrimaryStorageBase;
import org.zstack.storage.primary.PrimaryStorageSystemTags;
import org.zstack.utils.*;
import org.zstack.utils.function.Function;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static org.zstack.core.Platform.i18n;
import static org.zstack.core.Platform.operr;
import static org.zstack.core.progress.ProgressReportService.*;
import static org.zstack.utils.CollectionDSL.list;
/**
* Created by frank on 7/28/2015.
*/
public class CephPrimaryStorageBase extends PrimaryStorageBase {
private static final CLogger logger = Utils.getLogger(CephPrimaryStorageBase.class);
@Autowired
private RESTFacade restf;
@Autowired
private ThreadFacade thdf;
@Autowired
private ApiTimeoutManager timeoutMgr;
@Autowired
private CephImageCacheCleaner imageCacheCleaner;
@Autowired
private AccountManager acntMgr;
@Autowired
private PluginRegistry pluginRgty;
public CephPrimaryStorageBase() {
}
class ReconnectMonLock {
AtomicBoolean hold = new AtomicBoolean(false);
boolean lock() {
return hold.compareAndSet(false, true);
}
void unlock() {
hold.set(false);
}
}
ReconnectMonLock reconnectMonLock = new ReconnectMonLock();
public static class AgentCommand {
String fsId;
String uuid;
public String monUuid;
public String getFsId() {
return fsId;
}
public void setFsId(String fsId) {
this.fsId = fsId;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
public static class AgentResponse {
String error;
boolean success = true;
Long totalCapacity;
Long availableCapacity;
List<CephPoolCapacity> poolCapacities;
boolean xsky = false;
public String getError() {
return error;
}
public void setError(String error) {
this.success = false;
this.error = error;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public Long getTotalCapacity() {
return totalCapacity;
}
public void setTotalCapacity(Long totalCapacity) {
this.totalCapacity = totalCapacity;
}
public Long getAvailableCapacity() {
return availableCapacity;
}
public void setAvailableCapacity(Long availableCapacity) {
this.availableCapacity = availableCapacity;
}
public List<CephPoolCapacity> getPoolCapacities() {
return poolCapacities;
}
public void setPoolCapacities(List<CephPoolCapacity> poolCapacities) {
this.poolCapacities = poolCapacities;
}
public boolean isXsky() {
return xsky;
}
public void setXsky(boolean xsky) {
this.xsky = xsky;
}
}
public static class AddPoolCmd extends AgentCommand {
public String poolName;
public boolean isCreate;
}
public static class AddPoolRsp extends AgentResponse {
}
public static class DeletePoolRsp extends AgentResponse {
}
public static class GetVolumeSizeCmd extends AgentCommand {
public String volumeUuid;
public String installPath;
}
public static class GetVolumeSnapshotSizeCmd extends AgentCommand {
public String volumeSnapshotUuid;
public String installPath;
}
public static class GetVolumeSizeRsp extends AgentResponse {
public Long size;
public Long actualSize;
}
public static class GetVolumeSnapshotSizeRsp extends AgentResponse {
public Long size;
public Long actualSize;
}
public static class Pool {
String name;
boolean predefined;
}
public static class InitCmd extends AgentCommand {
List<Pool> pools;
Boolean nocephx = false;
public List<Pool> getPools() {
return pools;
}
public void setPools(List<Pool> pools) {
this.pools = pools;
}
public Boolean getNocephx() {
return nocephx;
}
public void setNocephx(Boolean nocephx) {
this.nocephx = nocephx;
}
}
public static class InitRsp extends AgentResponse {
String fsid;
String userKey;
public String getUserKey() {
return userKey;
}
public void setUserKey(String userKey) {
this.userKey = userKey;
}
public String getFsid() {
return fsid;
}
public void setFsid(String fsid) {
this.fsid = fsid;
}
}
public static class CheckCmd extends AgentCommand {
List<Pool> pools;
public List<Pool> getPools() {
return pools;
}
public void setPools(List<Pool> pools) {
this.pools = pools;
}
}
public static class CheckRsp extends AgentResponse{
}
public static class CreateEmptyVolumeCmd extends AgentCommand {
String installPath;
long size;
boolean shareable;
boolean skipIfExisting;
public boolean isShareable() {
return shareable;
}
public void setShareable(boolean shareable) {
this.shareable = shareable;
}
public String getInstallPath() {
return installPath;
}
public void setInstallPath(String installPath) {
this.installPath = installPath;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public void setSkipIfExisting(boolean skipIfExisting) {
this.skipIfExisting = skipIfExisting;
}
public boolean isSkipIfExisting() {
return skipIfExisting;
}
}
public static class CreateEmptyVolumeRsp extends AgentResponse {
}
public static class DeleteCmd extends AgentCommand {
String installPath;
public String getInstallPath() {
return installPath;
}
public void setInstallPath(String installPath) {
this.installPath = installPath;
}
}
public static class DeleteRsp extends AgentResponse {
}
public static class CloneCmd extends AgentCommand {
String srcPath;
String dstPath;
public String getSrcPath() {
return srcPath;
}
public void setSrcPath(String srcPath) {
this.srcPath = srcPath;
}
public String getDstPath() {
return dstPath;
}
public void setDstPath(String dstPath) {
this.dstPath = dstPath;
}
}
public static class CloneRsp extends AgentResponse {
}
public static class FlattenCmd extends AgentCommand {
String path;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
public static class FlattenRsp extends AgentResponse {
}
public static class SftpDownloadCmd extends AgentCommand {
String sshKey;
String hostname;
String username;
int sshPort;
String backupStorageInstallPath;
String primaryStorageInstallPath;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getSshPort() {
return sshPort;
}
public void setSshPort(int sshPort) {
this.sshPort = sshPort;
}
public String getSshKey() {
return sshKey;
}
public void setSshKey(String sshKey) {
this.sshKey = sshKey;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getBackupStorageInstallPath() {
return backupStorageInstallPath;
}
public void setBackupStorageInstallPath(String backupStorageInstallPath) {
this.backupStorageInstallPath = backupStorageInstallPath;
}
public String getPrimaryStorageInstallPath() {
return primaryStorageInstallPath;
}
public void setPrimaryStorageInstallPath(String primaryStorageInstallPath) {
this.primaryStorageInstallPath = primaryStorageInstallPath;
}
}
public static class SftpDownloadRsp extends AgentResponse {
}
public static class SftpUpLoadCmd extends AgentCommand implements HasThreadContext{
String sendCommandUrl;
String primaryStorageInstallPath;
String backupStorageInstallPath;
String hostname;
String username;
String sshKey;
int sshPort;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getSshPort() {
return sshPort;
}
public void setSshPort(int sshPort) {
this.sshPort = sshPort;
}
public String getPrimaryStorageInstallPath() {
return primaryStorageInstallPath;
}
public void setPrimaryStorageInstallPath(String primaryStorageInstallPath) {
this.primaryStorageInstallPath = primaryStorageInstallPath;
}
public String getBackupStorageInstallPath() {
return backupStorageInstallPath;
}
public void setBackupStorageInstallPath(String backupStorageInstallPath) {
this.backupStorageInstallPath = backupStorageInstallPath;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getSshKey() {
return sshKey;
}
public void setSshKey(String sshKey) {
this.sshKey = sshKey;
}
public void setSendCommandUrl(String sendCommandUrl) {
this.sendCommandUrl = sendCommandUrl;
}
public String getSendCommandUrl() {
return sendCommandUrl;
}
}
public static class SftpUploadRsp extends AgentResponse {
}
public static class CreateSnapshotCmd extends AgentCommand {
boolean skipOnExisting;
String snapshotPath;
String volumeUuid;
public String getVolumeUuid() {
return volumeUuid;
}
public void setVolumeUuid(String volumeUuid) {
this.volumeUuid = volumeUuid;
}
public boolean isSkipOnExisting() {
return skipOnExisting;
}
public void setSkipOnExisting(boolean skipOnExisting) {
this.skipOnExisting = skipOnExisting;
}
public String getSnapshotPath() {
return snapshotPath;
}
public void setSnapshotPath(String snapshotPath) {
this.snapshotPath = snapshotPath;
}
}
public static class CreateSnapshotRsp extends AgentResponse {
Long size;
Long actualSize;
public Long getActualSize() {
return actualSize;
}
public void setActualSize(Long actualSize) {
this.actualSize = actualSize;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
}
public static class DeleteSnapshotCmd extends AgentCommand {
String snapshotPath;
public String getSnapshotPath() {
return snapshotPath;
}
public void setSnapshotPath(String snapshotPath) {
this.snapshotPath = snapshotPath;
}
}
public static class DeleteSnapshotRsp extends AgentResponse {
}
public static class ProtectSnapshotCmd extends AgentCommand {
String snapshotPath;
boolean ignoreError;
public boolean isIgnoreError() {
return ignoreError;
}
public void setIgnoreError(boolean ignoreError) {
this.ignoreError = ignoreError;
}
public String getSnapshotPath() {
return snapshotPath;
}
public void setSnapshotPath(String snapshotPath) {
this.snapshotPath = snapshotPath;
}
}
public static class ProtectSnapshotRsp extends AgentResponse {
}
public static class UnprotectedSnapshotCmd extends AgentCommand {
String snapshotPath;
public String getSnapshotPath() {
return snapshotPath;
}
public void setSnapshotPath(String snapshotPath) {
this.snapshotPath = snapshotPath;
}
}
public static class UnprotectedSnapshotRsp extends AgentResponse {
}
public static class CpCmd extends AgentCommand implements HasThreadContext{
String sendCommandUrl;
String resourceUuid;
String srcPath;
String dstPath;
}
public static class UploadCmd extends AgentCommand implements HasThreadContext{
public String sendCommandUrl;
public String imageUuid;
public String hostname;
public String srcPath;
public String dstPath;
public String description;
}
public static class CpRsp extends AgentResponse {
public Long size;
public Long actualSize;
public String installPath;
}
public static class RollbackSnapshotCmd extends AgentCommand implements HasThreadContext {
String snapshotPath;
public String getSnapshotPath() {
return snapshotPath;
}
public void setSnapshotPath(String snapshotPath) {
this.snapshotPath = snapshotPath;
}
}
public static class RollbackSnapshotRsp extends AgentResponse {
@Validation
long size;
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
}
public static class CheckIsBitsExistingCmd extends AgentCommand {
String installPath;
public void setInstallPath(String installPath) {
this.installPath = installPath;
}
public String getInstallPath() {
return installPath;
}
}
public static class CreateKvmSecretCmd extends KVMAgentCommands.AgentCommand {
String userKey;
String uuid;
public String getUserKey() {
return userKey;
}
public void setUserKey(String userKey) {
this.userKey = userKey;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
public static class CreateKvmSecretRsp extends AgentResponse {
}
public static class DeletePoolCmd extends AgentCommand {
List<String> poolNames;
public List<String> getPoolNames() {
return poolNames;
}
public void setPoolNames(List<String> poolNames) {
this.poolNames = poolNames;
}
}
public static class KvmSetupSelfFencerCmd extends AgentCommand {
public String heartbeatImagePath;
public String hostUuid;
public long interval;
public int maxAttempts;
public int storageCheckerTimeout;
public String userKey;
public List<String> monUrls;
}
public static class KvmCancelSelfFencerCmd extends AgentCommand {
public String hostUuid;
}
public static class GetFactsCmd extends AgentCommand {
}
public static class GetFactsRsp extends AgentResponse {
public String fsid;
public String monAddr;
}
public static class DeleteImageCacheCmd extends AgentCommand {
public String imagePath;
public String snapshotPath;
}
public static class PurgeSnapshotCmd extends AgentCommand {
public String volumePath;
}
public static class PurgeSnapshotRsp extends AgentResponse {
}
public static class CephToCephMigrateVolumeSegmentCmd extends AgentCommand {
String parentUuid;
String resourceUuid;
String srcInstallPath;
String dstInstallPath;
String dstMonHostname;
String dstMonSshUsername;
String dstMonSshPassword;
int dstMonSshPort;
public String getParentUuid() {
return parentUuid;
}
public void setParentUuid(String parentUuid) {
this.parentUuid = parentUuid;
}
public String getResourceUuid() {
return resourceUuid;
}
public void setResourceUuid(String resourceUuid) {
this.resourceUuid = resourceUuid;
}
public String getSrcInstallPath() {
return srcInstallPath;
}
public void setSrcInstallPath(String srcInstallPath) {
this.srcInstallPath = srcInstallPath;
}
public String getDstInstallPath() {
return dstInstallPath;
}
public void setDstInstallPath(String dstInstallPath) {
this.dstInstallPath = dstInstallPath;
}
public String getDstMonHostname() {
return dstMonHostname;
}
public void setDstMonHostname(String dstMonHostname) {
this.dstMonHostname = dstMonHostname;
}
public String getDstMonSshUsername() {
return dstMonSshUsername;
}
public void setDstMonSshUsername(String dstMonSshUsername) {
this.dstMonSshUsername = dstMonSshUsername;
}
public String getDstMonSshPassword() {
return dstMonSshPassword;
}
public void setDstMonSshPassword(String dstMonSshPassword) {
this.dstMonSshPassword = dstMonSshPassword;
}
public int getDstMonSshPort() {
return dstMonSshPort;
}
public void setDstMonSshPort(int dstMonSshPort) {
this.dstMonSshPort = dstMonSshPort;
}
}
// common response of storage migration
public static class StorageMigrationRsp extends AgentResponse {
}
public static class GetVolumeSnapInfosCmd extends AgentCommand {
private String volumePath;
public String getVolumePath() {
return volumePath;
}
public void setVolumePath(String volumePath) {
this.volumePath = volumePath;
}
}
public static class GetVolumeSnapInfosRsp extends AgentResponse {
private List<SnapInfo> snapInfos;
public List<SnapInfo> getSnapInfos() {
return snapInfos;
}
public void setSnapInfos(List<SnapInfo> snapInfos) {
this.snapInfos = snapInfos;
}
}
public static class CheckSnapshotCompletedCmd extends AgentCommand {
private String volumePath;
private List<String> snapshots; // uuids
public String getVolumePath() {
return volumePath;
}
public void setVolumePath(String volumePath) {
this.volumePath = volumePath;
}
public List<String> getSnapshots() {
return snapshots;
}
public void setSnapshots(List<String> snapshots) {
this.snapshots = snapshots;
}
}
public static class CheckSnapshotCompletedRsp extends AgentResponse {
public String snapshotUuid;
public boolean completed; // whether the snapshot create completed
public long size;
}
public static class DownloadBitsFromKVMHostCmd extends AgentCommand implements ReloadableCommand {
private String hostname;
private String username;
private String sshKey;
private int sshPort;
// it's file path on kvm host actually
private String backupStorageInstallPath;
private String primaryStorageInstallPath;
private Long bandWidth;
private String identificationCode;
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSshKey() {
return sshKey;
}
public void setSshKey(String sshKey) {
this.sshKey = sshKey;
}
public int getSshPort() {
return sshPort;
}
public void setSshPort(int sshPort) {
this.sshPort = sshPort;
}
public String getBackupStorageInstallPath() {
return backupStorageInstallPath;
}
public void setBackupStorageInstallPath(String backupStorageInstallPath) {
this.backupStorageInstallPath = backupStorageInstallPath;
}
public String getPrimaryStorageInstallPath() {
return primaryStorageInstallPath;
}
public void setPrimaryStorageInstallPath(String primaryStorageInstallPath) {
this.primaryStorageInstallPath = primaryStorageInstallPath;
}
public Long getBandWidth() {
return bandWidth;
}
public void setBandWidth(Long bandWidth) {
this.bandWidth = bandWidth;
}
@Override
public void setIdentificationCode(String identificationCode) {
this.identificationCode = identificationCode;
}
}
public static class CancelDownloadBitsFromKVMHostCmd extends AgentCommand {
private String primaryStorageInstallPath;
public String getPrimaryStorageInstallPath() {
return primaryStorageInstallPath;
}
public void setPrimaryStorageInstallPath(String primaryStorageInstallPath) {
this.primaryStorageInstallPath = primaryStorageInstallPath;
}
}
public static class SnapInfo implements Comparable<SnapInfo> {
long id;
String name;
long size;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
@Override
public int compareTo(SnapInfo snapInfo) {
return Long.compare(this.getId(), snapInfo.getId());
}
}
public static final String INIT_PATH = "/ceph/primarystorage/init";
public static final String CREATE_VOLUME_PATH = "/ceph/primarystorage/volume/createempty";
public static final String DELETE_PATH = "/ceph/primarystorage/delete";
public static final String CLONE_PATH = "/ceph/primarystorage/volume/clone";
public static final String FLATTEN_PATH = "/ceph/primarystorage/volume/flatten";
public static final String SFTP_DOWNLOAD_PATH = "/ceph/primarystorage/sftpbackupstorage/download";
public static final String SFTP_UPLOAD_PATH = "/ceph/primarystorage/sftpbackupstorage/upload";
public static final String CREATE_SNAPSHOT_PATH = "/ceph/primarystorage/snapshot/create";
public static final String DELETE_SNAPSHOT_PATH = "/ceph/primarystorage/snapshot/delete";
public static final String PURGE_SNAPSHOT_PATH = "/ceph/primarystorage/volume/purgesnapshots";
public static final String PROTECT_SNAPSHOT_PATH = "/ceph/primarystorage/snapshot/protect";
public static final String ROLLBACK_SNAPSHOT_PATH = "/ceph/primarystorage/snapshot/rollback";
public static final String UNPROTECT_SNAPSHOT_PATH = "/ceph/primarystorage/snapshot/unprotect";
public static final String CP_PATH = "/ceph/primarystorage/volume/cp";
public static final String KVM_CREATE_SECRET_PATH = "/vm/createcephsecret";
public static final String DELETE_POOL_PATH = "/ceph/primarystorage/deletepool";
public static final String GET_VOLUME_SIZE_PATH = "/ceph/primarystorage/getvolumesize";
public static final String GET_VOLUME_SNAPSHOT_SIZE_PATH = "/ceph/primarystorage/getvolumesnapshotsize";
public static final String KVM_HA_SETUP_SELF_FENCER = "/ha/ceph/setupselffencer";
public static final String KVM_HA_CANCEL_SELF_FENCER = "/ha/ceph/cancelselffencer";
public static final String GET_FACTS = "/ceph/primarystorage/facts";
public static final String DELETE_IMAGE_CACHE = "/ceph/primarystorage/deleteimagecache";
public static final String ADD_POOL_PATH = "/ceph/primarystorage/addpool";
public static final String CHECK_POOL_PATH = "/ceph/primarystorage/checkpool";
public static final String CHECK_BITS_PATH = "/ceph/primarystorage/snapshot/checkbits";
public static final String CEPH_TO_CEPH_MIGRATE_VOLUME_SEGMENT_PATH = "/ceph/primarystorage/volume/migratesegment";
public static final String GET_VOLUME_SNAPINFOS_PATH = "/ceph/primarystorage/volume/getsnapinfos";
public static final String DOWNLOAD_BITS_FROM_KVM_HOST_PATH = "/ceph/primarystorage/kvmhost/download";
public static final String CANCEL_DOWNLOAD_BITS_FROM_KVM_HOST_PATH = "/ceph/primarystorage/kvmhost/download/cancel";
public static final String CHECK_SNAPSHOT_COMPLETED = "/ceph/primarystorage/check/snapshot";
private final Map<String, BackupStorageMediator> backupStorageMediators = new HashMap<String, BackupStorageMediator>();
{
backupStorageMediators.put(SftpBackupStorageConstant.SFTP_BACKUP_STORAGE_TYPE, new SftpBackupStorageMediator());
backupStorageMediators.put(CephConstants.CEPH_BACKUP_STORAGE_TYPE, new CephBackupStorageMediator());
List<PrimaryStorageToBackupStorageMediatorExtensionPoint> exts = pluginRgty.getExtensionList(PrimaryStorageToBackupStorageMediatorExtensionPoint.class);
exts.forEach(ext -> backupStorageMediators.putAll(ext.getBackupStorageMediators()));
}
class UploadParam implements MediatorParam {
ImageInventory image;
String primaryStorageInstallPath;
String backupStorageInstallPath;
}
class SftpBackupStorageMediator extends BackupStorageMediator {
private void getSftpCredentials(final ReturnValueCompletion<GetSftpBackupStorageDownloadCredentialReply> completion) {
GetSftpBackupStorageDownloadCredentialMsg gmsg = new GetSftpBackupStorageDownloadCredentialMsg();
gmsg.setBackupStorageUuid(backupStorage.getUuid());
bus.makeTargetServiceIdByResourceUuid(gmsg, BackupStorageConstant.SERVICE_ID, backupStorage.getUuid());
bus.send(gmsg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
completion.fail(reply.getError());
} else {
completion.success((GetSftpBackupStorageDownloadCredentialReply) reply);
}
}
});
}
@Override
public void download(final ReturnValueCompletion<String> completion) {
checkParam();
final MediatorDowloadParam dparam = (MediatorDowloadParam) param;
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("download-image-from-sftp-%s-to-ceph-%s", backupStorage.getUuid(), dparam.getPrimaryStorageUuid()));
chain.then(new ShareFlow() {
String sshkey;
int sshport;
String sftpHostname;
String username;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "get-sftp-credentials";
@Override
public void run(final FlowTrigger trigger, Map data) {
getSftpCredentials(new ReturnValueCompletion<GetSftpBackupStorageDownloadCredentialReply>(trigger) {
@Override
public void success(GetSftpBackupStorageDownloadCredentialReply greply) {
sshkey = greply.getSshKey();
sshport = greply.getSshPort();
sftpHostname = greply.getHostname();
username = greply.getUsername();
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "download-image";
@Override
public void run(final FlowTrigger trigger, Map data) {
SftpDownloadCmd cmd = new SftpDownloadCmd();
cmd.backupStorageInstallPath = dparam.getImage().getSelectedBackupStorage().getInstallPath();
cmd.hostname = sftpHostname;
cmd.username = username;
cmd.sshKey = sshkey;
cmd.sshPort = sshport;
cmd.primaryStorageInstallPath = dparam.getInstallPath();
httpCall(SFTP_DOWNLOAD_PATH, cmd, SftpDownloadRsp.class, new ReturnValueCompletion<SftpDownloadRsp>(trigger) {
@Override
public void success(SftpDownloadRsp returnValue) {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
completion.success(dparam.getInstallPath());
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
@Override
public void upload(final ReturnValueCompletion<String> completion) {
checkParam();
final UploadParam uparam = (UploadParam) param;
final TaskProgressRange parentStage = getTaskStage();
final TaskProgressRange PREPARATION_STAGE = new TaskProgressRange(0, 10);
final TaskProgressRange UPLOAD_STAGE = new TaskProgressRange(10, 100);
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("upload-image-ceph-%s-to-sftp-%s", self.getUuid(), backupStorage.getUuid()));
chain.then(new ShareFlow() {
String sshKey;
String hostname;
String username;
int sshPort;
String backupStorageInstallPath;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "get-sftp-credentials";
@Override
public void run(final FlowTrigger trigger, Map data) {
getSftpCredentials(new ReturnValueCompletion<GetSftpBackupStorageDownloadCredentialReply>(trigger) {
@Override
public void success(GetSftpBackupStorageDownloadCredentialReply returnValue) {
sshKey = returnValue.getSshKey();
hostname = returnValue.getHostname();
username = returnValue.getUsername();
sshPort = returnValue.getSshPort();
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "get-backup-storage-install-path";
@Override
public void run(final FlowTrigger trigger, Map data) {
TaskProgressRange stage = markTaskStage(parentStage, PREPARATION_STAGE);
BackupStorageAskInstallPathMsg msg = new BackupStorageAskInstallPathMsg();
msg.setBackupStorageUuid(backupStorage.getUuid());
msg.setImageUuid(uparam.image.getUuid());
msg.setImageMediaType(uparam.image.getMediaType());
bus.makeTargetServiceIdByResourceUuid(msg, BackupStorageConstant.SERVICE_ID, backupStorage.getUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
} else {
backupStorageInstallPath = ((BackupStorageAskInstallPathReply) reply).getInstallPath();
reportProgress(stage.getEnd().toString());
trigger.next();
}
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "upload-to-backup-storage";
@Override
public void run(final FlowTrigger trigger, Map data) {
TaskProgressRange stage = markTaskStage(parentStage, UPLOAD_STAGE);
SftpUpLoadCmd cmd = new SftpUpLoadCmd();
cmd.setSendCommandUrl(restf.getSendCommandUrl());
cmd.setBackupStorageInstallPath(backupStorageInstallPath);
cmd.setHostname(hostname);
cmd.setUsername(username);
cmd.setSshKey(sshKey);
cmd.setSshPort(sshPort);
cmd.setPrimaryStorageInstallPath(uparam.primaryStorageInstallPath);
httpCall(SFTP_UPLOAD_PATH, cmd, SftpUploadRsp.class, new ReturnValueCompletion<SftpUploadRsp>(trigger) {
@Override
public void success(SftpUploadRsp returnValue) {
reportProgress(stage.getEnd().toString());
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
reportProgress(parentStage.getEnd().toString());
completion.success(backupStorageInstallPath);
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
@Override
public boolean deleteWhenRollbackDownload() {
return true;
}
}
class CephBackupStorageMediator extends BackupStorageMediator {
public void checkParam() {
super.checkParam();
SimpleQuery<CephBackupStorageVO> q = dbf.createQuery(CephBackupStorageVO.class);
q.select(CephBackupStorageVO_.fsid);
q.add(CephBackupStorageVO_.uuid, Op.EQ, backupStorage.getUuid());
String bsFsid = q.findValue();
if (!getSelf().getFsid().equals(bsFsid)) {
throw new OperationFailureException(operr(
"the backup storage[uuid:%s, name:%s, fsid:%s] is not in the same ceph cluster" +
" with the primary storage[uuid:%s, name:%s, fsid:%s]", backupStorage.getUuid(),
backupStorage.getName(), bsFsid, self.getUuid(), self.getName(), getSelf().getFsid())
);
}
}
@Override
public void download(final ReturnValueCompletion<String> completion) {
checkParam();
final MediatorDowloadParam dparam = (MediatorDowloadParam) param;
if (ImageMediaType.DataVolumeTemplate.toString().equals(dparam.getImage().getInventory().getMediaType())) {
CpCmd cmd = new CpCmd();
cmd.srcPath = dparam.getImage().getSelectedBackupStorage().getInstallPath();
cmd.dstPath = dparam.getInstallPath();
httpCall(CP_PATH, cmd, CpRsp.class, new ReturnValueCompletion<CpRsp>(completion) {
@Override
public void success(CpRsp returnValue) {
completion.success(dparam.getInstallPath());
}
@Override
public void fail(ErrorCode errorCode) {
completion.fail(errorCode);
}
});
} else {
completion.success(dparam.getImage().getSelectedBackupStorage().getInstallPath());
}
}
@Override
public void upload(final ReturnValueCompletion<String> completion) {
checkParam();
final UploadParam uparam = (UploadParam) param;
final TaskProgressRange parentStage = getTaskStage();
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("upload-image-ceph-%s-to-ceph-%s", self.getUuid(), backupStorage.getUuid()));
chain.then(new ShareFlow() {
String backupStorageInstallPath;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "get-backup-storage-install-path";
@Override
public void run(final FlowTrigger trigger, Map data) {
BackupStorageAskInstallPathMsg msg = new BackupStorageAskInstallPathMsg();
msg.setBackupStorageUuid(backupStorage.getUuid());
msg.setImageUuid(uparam.image.getUuid());
msg.setImageMediaType(uparam.image.getMediaType());
bus.makeTargetServiceIdByResourceUuid(msg, BackupStorageConstant.SERVICE_ID, backupStorage.getUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
} else {
backupStorageInstallPath = ((BackupStorageAskInstallPathReply) reply).getInstallPath();
trigger.next();
}
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "cp-to-the-image";
@Override
public void run(final FlowTrigger trigger, Map data) {
CpCmd cmd = new CpCmd();
cmd.sendCommandUrl = restf.getSendCommandUrl();
cmd.srcPath = uparam.primaryStorageInstallPath;
cmd.dstPath = backupStorageInstallPath;
httpCall(CP_PATH, cmd, CpRsp.class, new ReturnValueCompletion<CpRsp>(trigger) {
@Override
public void success(CpRsp returnValue) {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
reportProgress(parentStage.getEnd().toString());
completion.success(backupStorageInstallPath);
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
@Override
public boolean deleteWhenRollbackDownload() {
return false;
}
}
private BackupStorageMediator getBackupStorageMediator(String bsUuid) {
BackupStorageVO bsvo = dbf.findByUuid(bsUuid, BackupStorageVO.class);
BackupStorageMediator mediator = backupStorageMediators.get(bsvo.getType());
if (mediator == null) {
throw new CloudRuntimeException(String.format("cannot find BackupStorageMediator for type[%s]", bsvo.getType()));
}
mediator.backupStorage = BackupStorageInventory.valueOf(bsvo);
return mediator;
}
private String makeRootVolumeInstallPath(String volUuid) {
String poolName = CephSystemTags.USE_CEPH_ROOT_POOL.getTokenByResourceUuid(volUuid, CephSystemTags.USE_CEPH_ROOT_POOL_TOKEN);
return String.format("ceph://%s/%s",getPoolName(poolName, getDefaultRootVolumePoolName()), volUuid);
}
private String makeResetImageRootVolumeInstallPath(String volUuid) {
return String.format("ceph://%s/reset-image-%s-%s",
getDefaultRootVolumePoolName(),
volUuid,
System.currentTimeMillis());
}
private String makeDataVolumeInstallPath(String volUuid) {
String poolName = CephSystemTags.USE_CEPH_PRIMARY_STORAGE_POOL.getTokenByResourceUuid(volUuid, CephSystemTags.USE_CEPH_PRIMARY_STORAGE_POOL_TOKEN);
return String.format("ceph://%s/%s",getPoolName(poolName, getDefaultDataVolumePoolName()), volUuid);
}
private String getPoolName(String customPoolName, String defaultPoolName){
return customPoolName != null ? customPoolName : defaultPoolName;
}
private String makeCacheInstallPath(String uuid) {
return String.format("ceph://%s/%s",
getDefaultImageCachePoolName(),
uuid);
}
public CephPrimaryStorageBase(PrimaryStorageVO self) {
super(self);
}
protected CephPrimaryStorageVO getSelf() {
return (CephPrimaryStorageVO) self;
}
private String getDefaultImageCachePoolName() {
return CephSystemTags.DEFAULT_CEPH_PRIMARY_STORAGE_IMAGE_CACHE_POOL.getTokenByResourceUuid(self.getUuid(), CephSystemTags.DEFAULT_CEPH_PRIMARY_STORAGE_IMAGE_CACHE_POOL_TOKEN);
}
private String getDefaultDataVolumePoolName() {
return CephSystemTags.DEFAULT_CEPH_PRIMARY_STORAGE_DATA_VOLUME_POOL.getTokenByResourceUuid(self.getUuid(), CephSystemTags.DEFAULT_CEPH_PRIMARY_STORAGE_DATA_VOLUME_POOL_TOKEN);
}
private String getDefaultRootVolumePoolName() {
return CephSystemTags.DEFAULT_CEPH_PRIMARY_STORAGE_ROOT_VOLUME_POOL.getTokenByResourceUuid(self.getUuid(), CephSystemTags.DEFAULT_CEPH_PRIMARY_STORAGE_ROOT_VOLUME_POOL_TOKEN);
}
protected CephPrimaryStorageInventory getSelfInventory() {
return CephPrimaryStorageInventory.valueOf(getSelf());
}
private void createEmptyVolume(final InstantiateVolumeOnPrimaryStorageMsg msg) {
final CreateEmptyVolumeCmd cmd = new CreateEmptyVolumeCmd();
if (VolumeType.Root.toString().equals(msg.getVolume().getType())) {
cmd.installPath = makeRootVolumeInstallPath(msg.getVolume().getUuid());
} else {
cmd.installPath = makeDataVolumeInstallPath(msg.getVolume().getUuid());
}
cmd.size = msg.getVolume().getSize();
cmd.setShareable(msg.getVolume().isShareable());
cmd.skipIfExisting = msg.isSkipIfExisting();
final InstantiateVolumeOnPrimaryStorageReply reply = new InstantiateVolumeOnPrimaryStorageReply();
httpCall(CREATE_VOLUME_PATH, cmd, CreateEmptyVolumeRsp.class, new ReturnValueCompletion<CreateEmptyVolumeRsp>(msg) {
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
}
@Override
public void success(CreateEmptyVolumeRsp ret) {
VolumeInventory vol = msg.getVolume();
vol.setInstallPath(cmd.getInstallPath());
vol.setFormat(VolumeConstant.VOLUME_FORMAT_RAW);
reply.setVolume(vol);
bus.reply(msg, reply);
}
});
}
private void cleanTrash(Long trashId, final ReturnValueCompletion<CleanTrashResult> completion) {
CleanTrashResult result = new CleanTrashResult();
StorageTrashSpec spec = trash.getTrash(self.getUuid(), trashId);
if (spec == null) {
completion.success(result);
return;
}
if (!trash.makeSureInstallPathNotUsed(spec)) {
logger.warn(String.format("%s is still in using by %s, only remove it from trash...", spec.getInstallPath(), spec.getResourceType()));
trash.removeFromDb(spec.getTrashId());
completion.success(result);
return;
}
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("clean-trash-on-volume-%s", spec.getInstallPath()));
chain.then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
PurgeSnapshotOnPrimaryStorageMsg msg = new PurgeSnapshotOnPrimaryStorageMsg();
msg.setPrimaryStorageUuid(self.getUuid());
msg.setVolumePath(spec.getInstallPath());
bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, self.getUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
logger.info(String.format("Purged all snapshots of volume %s.", spec.getInstallPath()));
} else {
logger.warn(String.format("Failed to purge snapshots of volume %s.", spec.getInstallPath()));
}
trigger.next();
}
});
}
}).then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
DeleteVolumeBitsOnPrimaryStorageMsg msg = new DeleteVolumeBitsOnPrimaryStorageMsg();
msg.setPrimaryStorageUuid(self.getUuid());
msg.setInstallPath(spec.getInstallPath());
bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, self.getUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
logger.info(String.format("Deleted volume %s in Trash.", spec.getInstallPath()));
} else {
logger.warn(String.format("Failed to delete volume %s in Trash.", spec.getInstallPath()));
}
trigger.next();
}
});
}
});
chain.done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
IncreasePrimaryStorageCapacityMsg imsg = new IncreasePrimaryStorageCapacityMsg();
imsg.setPrimaryStorageUuid(self.getUuid());
imsg.setDiskSize(spec.getSize());
bus.makeTargetServiceIdByResourceUuid(imsg, PrimaryStorageConstant.SERVICE_ID, self.getUuid());
bus.send(imsg);
logger.info(String.format("Returned space[size:%s] to PS %s after volume migration", spec.getSize(), self.getUuid()));
trash.removeFromDb(trashId);
result.setSize(spec.getSize());
result.setResourceUuids(CollectionDSL.list(spec.getResourceUuid()));
completion.success(result);
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
}).start();
}
private void cleanUpTrash(Long trashId, final ReturnValueCompletion<CleanTrashResult> completion) {
if (trashId != null) {
cleanTrash(trashId, completion);
return;
}
CleanTrashResult result = new CleanTrashResult();
Map<String, StorageTrashSpec> trashs = trash.getTrashList(self.getUuid(), trashLists);
if (trashs.isEmpty()) {
completion.success(result);
return;
}
ErrorCodeList errorCodeList = new ErrorCodeList();
new While<>(trashs.entrySet()).all((t, coml) -> {
StorageTrashSpec spec = t.getValue();
if (!trash.makeSureInstallPathNotUsed(spec)) {
logger.warn(String.format("%s is still in using by %s, only remove it from trash...", spec.getInstallPath(), spec.getResourceType()));
trash.removeFromDb(spec.getTrashId());
coml.done();
return;
}
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("clean-trash-on-volume-%s", spec.getInstallPath()));
chain.then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
PurgeSnapshotOnPrimaryStorageMsg msg = new PurgeSnapshotOnPrimaryStorageMsg();
msg.setPrimaryStorageUuid(self.getUuid());
msg.setVolumePath(spec.getInstallPath());
bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, self.getUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
logger.info(String.format("Purged all snapshots of volume %s.", spec.getInstallPath()));
} else {
logger.warn(String.format("Failed to purge snapshots of volume %s.", spec.getInstallPath()));
}
trigger.next();
}
});
}
}).then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
DeleteVolumeBitsOnPrimaryStorageMsg msg = new DeleteVolumeBitsOnPrimaryStorageMsg();
msg.setPrimaryStorageUuid(self.getUuid());
msg.setInstallPath(spec.getInstallPath());
bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, self.getUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
logger.info(String.format("Deleted volume %s in Trash.", spec.getInstallPath()));
} else {
logger.warn(String.format("Failed to delete volume %s in Trash.", spec.getInstallPath()));
}
trigger.next();
}
});
}
});
chain.done(new FlowDoneHandler(coml) {
@Override
public void handle(Map data) {
IncreasePrimaryStorageCapacityMsg imsg = new IncreasePrimaryStorageCapacityMsg();
imsg.setPrimaryStorageUuid(self.getUuid());
imsg.setDiskSize(spec.getSize());
bus.makeTargetServiceIdByResourceUuid(imsg, PrimaryStorageConstant.SERVICE_ID, self.getUuid());
bus.send(imsg);
logger.info(String.format("Returned space[size:%s] to PS %s after volume migration", spec.getSize(), self.getUuid()));
result.getResourceUuids().add(spec.getResourceUuid());
updateTrashSize(result, spec.getSize());
trash.removeFromDb(t.getKey(), self.getUuid());
coml.done();
}
}).error(new FlowErrorHandler(coml) {
@Override
public void handle(ErrorCode errCode, Map data) {
errorCodeList.getCauses().add(errCode);
coml.done();
}
}).start();
}).run(new NoErrorCompletion() {
@Override
public void done() {
if (errorCodeList.getCauses().isEmpty()) {
completion.success(result);
} else {
completion.fail(errorCodeList.getCauses().get(0));
}
}
});
}
protected void handle(final CleanUpTrashOnPrimaryStroageMsg msg) {
MessageReply reply = new MessageReply();
thdf.chainSubmit(new ChainTask(msg) {
private String name = String.format("cleanup-trash-on-%s", self.getUuid());
@Override
public String getSyncSignature() {
return name;
}
@Override
public void run(SyncTaskChain chain) {
cleanUpTrash(msg.getTrashId(), new ReturnValueCompletion<CleanTrashResult>(msg) {
@Override
public void success(CleanTrashResult returnValue) {
bus.reply(msg, reply);
chain.next();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
chain.next();
}
});
}
@Override
public String getName() {
return name;
}
});
}
@Override
protected void handle(final APICleanUpTrashOnPrimaryStorageMsg msg) {
APICleanUpTrashOnPrimaryStorageEvent evt = new APICleanUpTrashOnPrimaryStorageEvent(msg.getId());
thdf.chainSubmit(new ChainTask(msg) {
private String name = String.format("cleanup-trash-on-%s", self.getUuid());
@Override
public String getSyncSignature() {
return name;
}
@Override
public void run(SyncTaskChain chain) {
cleanUpTrash(msg.getTrashId(), new ReturnValueCompletion<CleanTrashResult>(chain) {
@Override
public void success(CleanTrashResult result) {
evt.setResult(result);
bus.publish(evt);
chain.next();
}
@Override
public void fail(ErrorCode errorCode) {
evt.setError(errorCode);
bus.publish(evt);
chain.next();
}
});
}
@Override
public String getName() {
return name;
}
});
}
@Override
protected void handle(APICleanUpImageCacheOnPrimaryStorageMsg msg) {
APICleanUpImageCacheOnPrimaryStorageEvent evt = new APICleanUpImageCacheOnPrimaryStorageEvent(msg.getId());
imageCacheCleaner.cleanup(msg.getUuid());
bus.publish(evt);
}
@Override
protected void handle(final InstantiateVolumeOnPrimaryStorageMsg msg) {
if (msg instanceof InstantiateRootVolumeFromTemplateOnPrimaryStorageMsg) {
createVolumeFromTemplate((InstantiateRootVolumeFromTemplateOnPrimaryStorageMsg) msg);
} else {
createEmptyVolume(msg);
}
}
class DownloadToCache {
ImageSpec image;
private void doDownload(final ReturnValueCompletion<ImageCacheVO> completion) {
ImageCacheVO cache = Q.New(ImageCacheVO.class)
.eq(ImageCacheVO_.primaryStorageUuid, self.getUuid())
.eq(ImageCacheVO_.imageUuid, image.getInventory().getUuid())
.find();
if (cache != null) {
completion.success(cache);
return;
}
final FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("prepare-image-cache-ceph-%s", self.getUuid()));
chain.then(new ShareFlow() {
String cachePath;
String snapshotPath;
@Override
public void setup() {
flow(new Flow() {
String __name__ = "allocate-primary-storage-capacity-for-image-cache";
boolean s = false;
@Override
public void run(final FlowTrigger trigger, Map data) {
AllocatePrimaryStorageMsg amsg = new AllocatePrimaryStorageMsg();
amsg.setRequiredPrimaryStorageUuid(self.getUuid());
amsg.setSize(image.getInventory().getActualSize());
amsg.setPurpose(PrimaryStorageAllocationPurpose.DownloadImage.toString());
amsg.setImageUuid(image.getInventory().getUuid());
amsg.setNoOverProvisioning(true);
bus.makeLocalServiceId(amsg, PrimaryStorageConstant.SERVICE_ID);
bus.send(amsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
} else {
s = true;
trigger.next();
}
}
});
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (s) {
IncreasePrimaryStorageCapacityMsg imsg = new IncreasePrimaryStorageCapacityMsg();
imsg.setNoOverProvisioning(true);
imsg.setPrimaryStorageUuid(self.getUuid());
imsg.setDiskSize(image.getInventory().getActualSize());
bus.makeLocalServiceId(imsg, PrimaryStorageConstant.SERVICE_ID);
bus.send(imsg);
}
trigger.rollback();
}
});
flow(new Flow() {
String __name__ = "download-from-backup-storage";
boolean deleteOnRollback;
@Override
public void run(final FlowTrigger trigger, Map data) {
MediatorDowloadParam param = new MediatorDowloadParam();
param.setImage(image);
param.setInstallPath(makeCacheInstallPath(image.getInventory().getUuid()));
param.setPrimaryStorageUuid(self.getUuid());
BackupStorageMediator mediator = getBackupStorageMediator(image.getSelectedBackupStorage().getBackupStorageUuid());
mediator.param = param;
deleteOnRollback = mediator.deleteWhenRollbackDownload();
mediator.download(new ReturnValueCompletion<String>(trigger) {
@Override
public void success(String path) {
cachePath = path;
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (deleteOnRollback && cachePath != null) {
DeleteCmd cmd = new DeleteCmd();
cmd.installPath = cachePath;
httpCall(DELETE_PATH, cmd, DeleteRsp.class, new ReturnValueCompletion<DeleteRsp>(null) {
@Override
public void success(DeleteRsp returnValue) {
logger.debug(String.format("successfully deleted %s", cachePath));
}
@Override
public void fail(ErrorCode errorCode) {
//TODO GC
logger.warn(String.format("unable to delete %s, %s. Need a cleanup", cachePath, errorCode));
}
});
}
trigger.rollback();
}
});
flow(new Flow() {
String __name__ = "create-snapshot";
boolean needCleanup = false;
@Override
public void run(final FlowTrigger trigger, Map data) {
snapshotPath = String.format("%s@%s", cachePath, image.getInventory().getUuid());
CreateSnapshotCmd cmd = new CreateSnapshotCmd();
cmd.skipOnExisting = true;
cmd.snapshotPath = snapshotPath;
httpCall(CREATE_SNAPSHOT_PATH, cmd, CreateSnapshotRsp.class, new ReturnValueCompletion<CreateSnapshotRsp>(trigger) {
@Override
public void success(CreateSnapshotRsp returnValue) {
needCleanup = true;
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (needCleanup) {
DeleteSnapshotCmd cmd = new DeleteSnapshotCmd();
cmd.snapshotPath = snapshotPath;
httpCall(DELETE_SNAPSHOT_PATH, cmd, DeleteSnapshotRsp.class, new ReturnValueCompletion<DeleteSnapshotRsp>(null) {
@Override
public void success(DeleteSnapshotRsp returnValue) {
logger.debug(String.format("successfully deleted the snapshot %s", snapshotPath));
}
@Override
public void fail(ErrorCode errorCode) {
//TODO
logger.warn(String.format("unable to delete the snapshot %s, %s. Need a cleanup", snapshotPath, errorCode));
}
});
}
trigger.rollback();
}
});
flow(new NoRollbackFlow() {
String __name__ = "protect-snapshot";
@Override
public void run(final FlowTrigger trigger, Map data) {
ProtectSnapshotCmd cmd = new ProtectSnapshotCmd();
cmd.snapshotPath = snapshotPath;
cmd.ignoreError = true;
httpCall(PROTECT_SNAPSHOT_PATH, cmd, ProtectSnapshotRsp.class, new ReturnValueCompletion<ProtectSnapshotRsp>(trigger) {
@Override
public void success(ProtectSnapshotRsp returnValue) {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
ImageCacheVO cvo = new ImageCacheVO();
cvo.setMd5sum("not calculated");
cvo.setSize(image.getInventory().getActualSize());
cvo.setInstallUrl(snapshotPath);
cvo.setImageUuid(image.getInventory().getUuid());
cvo.setPrimaryStorageUuid(self.getUuid());
cvo.setMediaType(ImageMediaType.valueOf(image.getInventory().getMediaType()));
cvo.setState(ImageCacheState.ready);
cvo = dbf.persistAndRefresh(cvo);
completion.success(cvo);
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
void download(final ReturnValueCompletion<ImageCacheVO> completion) {
thdf.chainSubmit(new ChainTask(completion) {
@Override
public String getSyncSignature() {
return String.format("ceph-p-%s-download-image-%s", self.getUuid(), image.getInventory().getUuid());
}
@Override
public void run(final SyncTaskChain chain) {
ImageCacheVO cache = Q.New(ImageCacheVO.class)
.eq(ImageCacheVO_.primaryStorageUuid, self.getUuid())
.eq(ImageCacheVO_.imageUuid, image.getInventory().getUuid())
.find();
if (cache != null ){
final CheckIsBitsExistingCmd cmd = new CheckIsBitsExistingCmd();
cmd.setInstallPath(cache.getInstallUrl());
httpCall(CHECK_BITS_PATH, cmd, CheckIsBitsExistingRsp.class, new ReturnValueCompletion<CheckIsBitsExistingRsp>(chain) {
@Override
public void success(CheckIsBitsExistingRsp returnValue) {
if(returnValue.isExisting()) {
logger.debug("image has been existing");
completion.success(cache);
chain.next();
}else{
logger.debug("image not found, remove vo and re-download");
SimpleQuery<ImageCacheVO> q = dbf.createQuery(ImageCacheVO.class);
q.add(ImageCacheVO_.primaryStorageUuid, Op.EQ, self.getUuid());
q.add(ImageCacheVO_.imageUuid, Op.EQ, image.getInventory().getUuid());
ImageCacheVO cvo = q.find();
IncreasePrimaryStorageCapacityMsg imsg = new IncreasePrimaryStorageCapacityMsg();
imsg.setDiskSize(cvo.getSize());
imsg.setPrimaryStorageUuid(cvo.getPrimaryStorageUuid());
bus.makeTargetServiceIdByResourceUuid(imsg, PrimaryStorageConstant.SERVICE_ID, cvo.getPrimaryStorageUuid());
bus.send(imsg);
dbf.remove(cvo);
doDownload(new ReturnValueCompletion<ImageCacheVO>(chain) {
@Override
public void success(ImageCacheVO returnValue) {
completion.success(returnValue);
chain.next();
}
@Override
public void fail(ErrorCode errorCode) {
completion.fail(errorCode);
chain.next();
}
});
}
}
@Override
public void fail(ErrorCode errorCode) {
completion.fail(errorCode);
chain.next();
}
});
}else{
doDownload(new ReturnValueCompletion<ImageCacheVO>(chain) {
@Override
public void success(ImageCacheVO returnValue) {
completion.success(returnValue);
chain.next();
}
@Override
public void fail(ErrorCode errorCode) {
completion.fail(errorCode);
chain.next();
}
});
}
}
@Override
public String getName() {
return getSyncSignature();
}
});
}
}
private void createVolumeFromTemplate(final InstantiateRootVolumeFromTemplateOnPrimaryStorageMsg msg) {
final InstantiateVolumeOnPrimaryStorageReply reply = new InstantiateVolumeOnPrimaryStorageReply();
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("create-root-volume-%s", msg.getVolume().getUuid()));
chain.then(new ShareFlow() {
String cloneInstallPath;
String volumePath = makeRootVolumeInstallPath(msg.getVolume().getUuid());
ImageCacheInventory cache;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "download-image-to-cache";
@Override
public void run(final FlowTrigger trigger, Map data) {
DownloadVolumeTemplateToPrimaryStorageMsg dmsg = new DownloadVolumeTemplateToPrimaryStorageMsg();
dmsg.setPrimaryStorageUuid(msg.getPrimaryStorageUuid());
dmsg.setHostUuid(msg.getDestHost().getUuid());
dmsg.setTemplateSpec(msg.getTemplateSpec());
bus.makeTargetServiceIdByResourceUuid(dmsg, PrimaryStorageConstant.SERVICE_ID, dmsg.getPrimaryStorageUuid());
bus.send(dmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
return;
}
cache = ((DownloadVolumeTemplateToPrimaryStorageReply) reply).getImageCache();
cloneInstallPath = cache.getInstallUrl();
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "clone-image";
@Override
public void run(final FlowTrigger trigger, Map data) {
CloneCmd cmd = new CloneCmd();
cmd.srcPath = cloneInstallPath;
cmd.dstPath = volumePath;
httpCall(CLONE_PATH, cmd, CloneRsp.class, new ReturnValueCompletion<CloneRsp>(trigger) {
@Override
public void fail(ErrorCode err) {
trigger.fail(err);
}
@Override
public void success(CloneRsp ret) {
trigger.next();
}
});
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
VolumeInventory vol = msg.getVolume();
vol.setInstallPath(volumePath);
vol.setFormat(VolumeConstant.VOLUME_FORMAT_RAW);
reply.setVolume(vol);
ImageCacheVolumeRefVO ref = new ImageCacheVolumeRefVO();
ref.setImageCacheId(cache.getId());
ref.setPrimaryStorageUuid(self.getUuid());
ref.setVolumeUuid(vol.getUuid());
dbf.persist(ref);
bus.reply(msg, reply);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
reply.setError(errCode);
bus.reply(msg, reply);
}
});
}
}).start();
}
@Override
protected void handle(final DeleteVolumeOnPrimaryStorageMsg msg) {
DeleteCmd cmd = new DeleteCmd();
cmd.installPath = msg.getVolume().getInstallPath();
final DeleteVolumeOnPrimaryStorageReply reply = new DeleteVolumeOnPrimaryStorageReply();
httpCall(DELETE_PATH, cmd, DeleteRsp.class, new ReturnValueCompletion<DeleteRsp>(msg) {
@Override
public void fail(ErrorCode err) {
CephDeleteVolumeGC gc = new CephDeleteVolumeGC();
gc.NAME = String.format("gc-ceph-%s-volume-%s", self.getUuid(), msg.getVolume());
gc.primaryStorageUuid = self.getUuid();
gc.volume = msg.getVolume();
gc.submit(CephGlobalConfig.GC_INTERVAL.value(Long.class), TimeUnit.SECONDS);
bus.reply(msg, reply);
}
@Override
public void success(DeleteRsp ret) {
bus.reply(msg, reply);
}
});
}
@Override
protected void handle(final GetPrimaryStorageFolderListMsg msg) {
GetPrimaryStorageFolderListReply reply = new GetPrimaryStorageFolderListReply();
bus.reply(msg, reply);
}
@Override
protected void handle(DownloadVolumeTemplateToPrimaryStorageMsg msg) {
final DownloadVolumeTemplateToPrimaryStorageReply reply = new DownloadVolumeTemplateToPrimaryStorageReply();
DownloadToCache downloadToCache = new DownloadToCache();
downloadToCache.image = msg.getTemplateSpec();
downloadToCache.download(new ReturnValueCompletion<ImageCacheVO>(msg) {
@Override
public void success(ImageCacheVO cache) {
reply.setImageCache(ImageCacheInventory.valueOf(cache));
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
@Override
protected void handle(final DeleteBitsOnPrimaryStorageMsg msg) {
DeleteCmd cmd = new DeleteCmd();
cmd.installPath = msg.getInstallPath();
final DeleteBitsOnPrimaryStorageReply reply = new DeleteBitsOnPrimaryStorageReply();
httpCall(DELETE_PATH, cmd, DeleteRsp.class, new ReturnValueCompletion<DeleteRsp>(msg) {
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
}
@Override
public void success(DeleteRsp ret) {
bus.reply(msg, reply);
}
});
}
private void checkCephFsId(String psUuid, String bsUuid) {
CephPrimaryStorageVO cephPS = dbf.findByUuid(psUuid, CephPrimaryStorageVO.class);
DebugUtils.Assert(cephPS != null && cephPS.getFsid() != null, String.format("ceph ps: [%s] and its fsid cannot be null", psUuid));
CephBackupStorageVO cephBS = dbf.findByUuid(bsUuid, CephBackupStorageVO.class);
if (cephBS != null) {
DebugUtils.Assert(cephBS.getFsid() != null, String.format("fsid cannot be null in ceph bs:[%s]", bsUuid));
if (!cephPS.getFsid().equals(cephBS.getFsid())) {
throw new OperationFailureException(operr(
"fsid is not same between ps[%s] and bs[%s], create template is forbidden.", psUuid, bsUuid));
}
}
}
@Override
protected void handle(final CreateTemplateFromVolumeOnPrimaryStorageMsg msg) {
final CreateTemplateFromVolumeOnPrimaryStorageReply reply = new CreateTemplateFromVolumeOnPrimaryStorageReply();
final TaskProgressRange parentStage = getTaskStage();
final TaskProgressRange CREATE_SNAPSHOT_STAGE = new TaskProgressRange(0, 10);
final TaskProgressRange CREATE_IMAGE_STAGE = new TaskProgressRange(10, 100);
checkCephFsId(msg.getPrimaryStorageUuid(), msg.getBackupStorageUuid());
String volumeUuid = msg.getVolumeInventory().getUuid();
String imageUuid = msg.getImageInventory().getUuid();
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("create-snapshot-and-image-from-volume-%s", volumeUuid));
chain.then(new ShareFlow() {
VolumeSnapshotInventory snapshot;
CreateTemplateFromVolumeSnapshotReply imageReply;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "create-volume-snapshot";
@Override
public void run(final FlowTrigger trigger, Map data) {
String volumeAccountUuid = acntMgr.getOwnerAccountUuidOfResource(volumeUuid);
TaskProgressRange stage = markTaskStage(parentStage, CREATE_SNAPSHOT_STAGE);
// 1. create snapshot
CreateVolumeSnapshotMsg cmsg = new CreateVolumeSnapshotMsg();
cmsg.setName("Snapshot-" + volumeUuid);
cmsg.setDescription("Take snapshot for " + volumeUuid);
cmsg.setVolumeUuid(volumeUuid);
cmsg.setAccountUuid(volumeAccountUuid);
bus.makeLocalServiceId(cmsg, VolumeSnapshotConstant.SERVICE_ID);
bus.send(cmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply r) {
if (!r.isSuccess()) {
trigger.fail(r.getError());
return;
}
CreateVolumeSnapshotReply createVolumeSnapshotReply = (CreateVolumeSnapshotReply)r;
snapshot = createVolumeSnapshotReply.getInventory();
reportProgress(stage.getEnd().toString());
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "create-template-from-volume-snapshot";
@Override
public void run(final FlowTrigger trigger, Map data) {
// 2.create image
TaskProgressRange stage = markTaskStage(parentStage, CREATE_IMAGE_STAGE);
VolumeSnapshotVO vo = dbf.findByUuid(snapshot.getUuid(), VolumeSnapshotVO.class);
String treeUuid = vo.getTreeUuid();
CreateTemplateFromVolumeSnapshotMsg cmsg = new CreateTemplateFromVolumeSnapshotMsg();
cmsg.setSnapshotUuid(snapshot.getUuid());
cmsg.setImageUuid(imageUuid);
cmsg.setVolumeUuid(snapshot.getVolumeUuid());
cmsg.setTreeUuid(treeUuid);
cmsg.setBackupStorageUuid(msg.getBackupStorageUuid());
String resourceUuid = volumeUuid != null ? volumeUuid : treeUuid;
bus.makeTargetServiceIdByResourceUuid(cmsg, VolumeSnapshotConstant.SERVICE_ID, resourceUuid);
bus.send(cmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply r) {
if (!r.isSuccess()) {
trigger.fail(r.getError());
return;
}
imageReply = (CreateTemplateFromVolumeSnapshotReply)r;
reportProgress(stage.getEnd().toString());
trigger.next();
}
});
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
logger.warn(String.format("successfully create template[uuid:%s] from volume[uuid:%s]", imageUuid, volumeUuid));
reply.setTemplateBackupStorageInstallPath(imageReply.getBackupStorageInstallPath());
reply.setFormat(snapshot.getFormat());
bus.reply(msg, reply);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
logger.warn(String.format("failed to create template from volume[uuid:%s], because %s", volumeUuid, errCode));
reply.setError(errCode);
bus.reply(msg, reply);
}
});
}
}).start();
}
@Override
protected void handle(final DownloadDataVolumeToPrimaryStorageMsg msg) {
final DownloadDataVolumeToPrimaryStorageReply reply = new DownloadDataVolumeToPrimaryStorageReply();
BackupStorageMediator mediator = getBackupStorageMediator(msg.getBackupStorageRef().getBackupStorageUuid());
ImageSpec spec = new ImageSpec();
spec.setInventory(msg.getImage());
spec.setSelectedBackupStorage(msg.getBackupStorageRef());
MediatorDowloadParam param = new MediatorDowloadParam();
param.setImage(spec);
param.setInstallPath(makeDataVolumeInstallPath(msg.getVolumeUuid()));
param.setPrimaryStorageUuid(self.getUuid());
mediator.param = param;
mediator.download(new ReturnValueCompletion<String>(msg) {
@Override
public void success(String returnValue) {
reply.setInstallPath(returnValue);
reply.setFormat(VolumeConstant.VOLUME_FORMAT_RAW);
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
@Override
protected void handle(GetInstallPathForDataVolumeDownloadMsg msg) {
GetInstallPathForDataVolumeDownloadReply reply = new GetInstallPathForDataVolumeDownloadReply();
reply.setInstallPath(makeDataVolumeInstallPath(msg.getVolumeUuid()));
bus.reply(msg, reply);
}
@Override
protected void handle(final DeleteVolumeBitsOnPrimaryStorageMsg msg) {
DeleteCmd cmd = new DeleteCmd();
cmd.installPath = msg.getInstallPath();
final DeleteVolumeBitsOnPrimaryStorageReply reply = new DeleteVolumeBitsOnPrimaryStorageReply();
httpCall(DELETE_PATH, cmd, DeleteRsp.class, new ReturnValueCompletion<DeleteRsp>(msg) {
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
}
@Override
public void success(DeleteRsp ret) {
bus.reply(msg, reply);
}
});
}
@Override
protected void handle(final DownloadIsoToPrimaryStorageMsg msg) {
final DownloadIsoToPrimaryStorageReply reply = new DownloadIsoToPrimaryStorageReply();
DownloadToCache downloadToCache = new DownloadToCache();
downloadToCache.image = msg.getIsoSpec();
downloadToCache.download(new ReturnValueCompletion<ImageCacheVO>(msg) {
@Override
public void success(ImageCacheVO returnValue) {
reply.setInstallPath(returnValue.getInstallUrl());
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
@Override
protected void handle(DeleteIsoFromPrimaryStorageMsg msg) {
DeleteIsoFromPrimaryStorageReply reply = new DeleteIsoFromPrimaryStorageReply();
bus.reply(msg, reply);
}
@Override
protected void handle(AskVolumeSnapshotCapabilityMsg msg) {
AskVolumeSnapshotCapabilityReply reply = new AskVolumeSnapshotCapabilityReply();
VolumeSnapshotCapability cap = new VolumeSnapshotCapability();
cap.setSupport(true);
cap.setArrangementType(VolumeSnapshotArrangementType.INDIVIDUAL);
reply.setCapability(cap);
bus.reply(msg, reply);
}
@Override
protected void handle(final SyncVolumeSizeOnPrimaryStorageMsg msg) {
final SyncVolumeSizeOnPrimaryStorageReply reply = new SyncVolumeSizeOnPrimaryStorageReply();
final VolumeVO vol = dbf.findByUuid(msg.getVolumeUuid(), VolumeVO.class);
String installPath = vol.getInstallPath();
GetVolumeSizeCmd cmd = new GetVolumeSizeCmd();
cmd.fsId = getSelf().getFsid();
cmd.uuid = self.getUuid();
cmd.volumeUuid = msg.getVolumeUuid();
cmd.installPath = installPath;
httpCall(GET_VOLUME_SIZE_PATH, cmd, GetVolumeSizeRsp.class, new ReturnValueCompletion<GetVolumeSizeRsp>(msg) {
@Override
public void success(GetVolumeSizeRsp rsp) {
// current ceph has no way to get actual size
long asize = rsp.actualSize == null ? vol.getActualSize() : rsp.actualSize;
reply.setActualSize(asize);
reply.setSize(rsp.size);
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
protected <T extends AgentResponse> void httpCall(final String path, final AgentCommand cmd, final Class<T> retClass, final ReturnValueCompletion<T> callback) {
httpCall(path, cmd, retClass, callback, null, 0);
}
protected <T extends AgentResponse> void httpCall(final String path, final AgentCommand cmd, final Class<T> retClass, final ReturnValueCompletion<T> callback, TimeUnit unit, long timeout) {
new HttpCaller<>(path, cmd, retClass, callback, unit, timeout).call();
}
protected class HttpCaller<T extends AgentResponse> {
private Iterator<CephPrimaryStorageMonBase> it;
private List<ErrorCode> errorCodes = new ArrayList<ErrorCode>();
private final String path;
private final AgentCommand cmd;
private final Class<T> retClass;
private final ReturnValueCompletion<T> callback;
private final TimeUnit unit;
private final long timeout;
private String randomFactor = null;
private boolean tryNext = false;
HttpCaller(String path, AgentCommand cmd, Class<T> retClass, ReturnValueCompletion<T> callback) {
this(path, cmd, retClass, callback, null, 0);
}
HttpCaller(String path, AgentCommand cmd, Class<T> retClass, ReturnValueCompletion<T> callback, TimeUnit unit, long timeout) {
this.path = path;
this.cmd = cmd;
this.retClass = retClass;
this.callback = callback;
this.unit = unit;
this.timeout = timeout;
}
void call() {
it = prepareMons().iterator();
prepareCmd();
doCall();
}
// specify mons order by randomFactor to ensure that the same mon receive cmd every time.
HttpCaller<T> specifyOrder(String randomFactor) {
this.randomFactor = randomFactor;
return this;
}
HttpCaller<T> tryNext() {
this.tryNext = true;
return this;
}
private void prepareCmd() {
cmd.setUuid(self.getUuid());
cmd.setFsId(getSelf().getFsid());
}
private List<CephPrimaryStorageMonBase> prepareMons() {
final List<CephPrimaryStorageMonBase> mons = new ArrayList<CephPrimaryStorageMonBase>();
for (CephPrimaryStorageMonVO monvo : getSelf().getMons()) {
mons.add(new CephPrimaryStorageMonBase(monvo));
}
if (randomFactor != null) {
CollectionUtils.shuffleByKeySeed(mons, randomFactor, it -> it.getSelf().getUuid());
} else {
Collections.shuffle(mons);
}
mons.removeIf(it -> it.getSelf().getStatus() != MonStatus.Connected);
if (mons.isEmpty()) {
throw new OperationFailureException(operr(
"all ceph mons of primary storage[uuid:%s] are not in Connected state", self.getUuid())
);
}
return mons;
}
private void doCall() {
if (!it.hasNext()) {
callback.fail(operr(
"all mons failed to execute http call[%s], errors are %s", path, JSONObjectUtil.toJsonString(errorCodes))
);
return;
}
CephPrimaryStorageMonBase base = it.next();
cmd.monUuid = base.getSelf().getUuid();
ReturnValueCompletion<T> completion = new ReturnValueCompletion<T>(callback) {
@Override
public void success(T ret) {
if (!ret.success) {
if (tryNext) {
doCall();
} else {
callback.fail(operr("operation error, because:%s", ret.error));
}
return;
}
if (!(cmd instanceof InitCmd)) {
updateCapacityIfNeeded(ret);
}
callback.success(ret);
}
@Override
public void fail(ErrorCode errorCode) {
logger.warn(String.format("mon[%s] failed to execute http call[%s], error is: %s",
base.getSelf().getHostname(), path, JSONObjectUtil.toJsonString(errorCode)));
errorCodes.add(errorCode);
doCall();
}
};
if (unit == null) {
base.httpCall(path, cmd, retClass, completion);
} else {
base.httpCall(path, cmd, retClass, completion, unit, timeout);
}
}
}
private void updateCapacityIfNeeded(AgentResponse rsp) {
if (rsp.totalCapacity != null && rsp.availableCapacity != null) {
CephCapacity cephCapacity = new CephCapacity();
cephCapacity.setFsid(getSelf().getFsid());
cephCapacity.setAvailableCapacity(rsp.availableCapacity);
cephCapacity.setTotalCapacity(rsp.totalCapacity);
cephCapacity.setPoolCapacities(rsp.poolCapacities);
cephCapacity.setXsky(rsp.isXsky());
new CephCapacityUpdater().update(cephCapacity);
}
}
private void connect(final boolean newAdded, final Completion completion) {
final List<CephPrimaryStorageMonBase> mons = CollectionUtils.transformToList(getSelf().getMons(),
CephPrimaryStorageMonBase::new);
class Connector {
private List<ErrorCode> errorCodes = new ArrayList<>();
private Iterator<CephPrimaryStorageMonBase> it = mons.iterator();
void connect(final FlowTrigger trigger) {
if (!it.hasNext()) {
if (errorCodes.size() == mons.size()) {
if (errorCodes.isEmpty()) {
trigger.fail(operr("unable to connect to the ceph primary storage[uuid:%s]." +
" Failed to connect all ceph mons.", self.getUuid()));
} else {
trigger.fail(operr("unable to connect to the ceph primary storage[uuid:%s]." +
" Failed to connect all ceph mons. Errors are %s",
self.getUuid(), JSONObjectUtil.toJsonString(errorCodes)));
}
} else {
// reload because mon status changed
PrimaryStorageVO vo = dbf.reload(self);
if (vo == null) {
if (newAdded) {
if (!getSelf().getMons().isEmpty()) {
dbf.removeCollection(getSelf().getMons(), CephPrimaryStorageMonVO.class);
}
}
trigger.fail(operr("ceph primary storage[uuid:%s] may have been deleted.", self.getUuid()));
} else {
self = vo;
trigger.next();
}
}
return;
}
final CephPrimaryStorageMonBase base = it.next();
base.connect(new Completion(trigger) {
@Override
public void success() {
connect(trigger);
}
@Override
public void fail(ErrorCode errorCode) {
errorCodes.add(errorCode);
if (newAdded) {
// the mon fails to connect, remove it
dbf.remove(base.getSelf());
}
connect(trigger);
}
});
}
}
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("connect-ceph-primary-storage-%s", self.getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "connect-monitor";
@Override
public void run(FlowTrigger trigger, Map data) {
new Connector().connect(trigger);
}
});
flow(new NoRollbackFlow() {
String __name__ = "check-mon-integrity";
@Override
public void run(final FlowTrigger trigger, Map data) {
final Map<String, String> fsids = new HashMap<String, String>();
final List<CephPrimaryStorageMonBase> mons = CollectionUtils.transformToList(getSelf().getMons(), new Function<CephPrimaryStorageMonBase, CephPrimaryStorageMonVO>() {
@Override
public CephPrimaryStorageMonBase call(CephPrimaryStorageMonVO arg) {
return arg.getStatus() == MonStatus.Connected ? new CephPrimaryStorageMonBase(arg) : null;
}
});
DebugUtils.Assert(!mons.isEmpty(), "how can be no connected MON !!!???");
List<ErrorCode> errors = new ArrayList<>();
new While<>(mons).each((mon, compl) -> {
GetFactsCmd cmd = new GetFactsCmd();
cmd.uuid = self.getUuid();
cmd.monUuid = mon.getSelf().getUuid();
mon.httpCall(GET_FACTS, cmd, GetFactsRsp.class, new ReturnValueCompletion<GetFactsRsp>(compl) {
@Override
public void success(GetFactsRsp rsp) {
if (!rsp.success) {
// one mon cannot get the facts, directly error out
errors.add(Platform.operr("%s", rsp.getError()));
compl.allDone();
return;
}
CephPrimaryStorageMonVO monVO = dbf.reload(mon.getSelf());
if (monVO != null) {
fsids.put(monVO.getUuid(), rsp.fsid);
monVO.setMonAddr(rsp.monAddr == null ? monVO.getHostname() : rsp.monAddr);
dbf.update(monVO);
}
compl.done();
}
@Override
public void fail(ErrorCode errorCode) {
// one mon cannot get the facts, directly error out
errors.add(errorCode);
compl.allDone();
}
});
}).run(new NoErrorCompletion(trigger) {
@Override
public void done() {
if (!errors.isEmpty()) {
trigger.fail(errors.get(0));
return;
}
Set<String> set = new HashSet<>(fsids.values());
if (set.size() != 1) {
StringBuilder sb = new StringBuilder(i18n("the fsid returned by mons are mismatching, it seems the mons belong to different ceph clusters:\n"));
for (CephPrimaryStorageMonBase mon : mons) {
String fsid = fsids.get(mon.getSelf().getUuid());
sb.append(String.format("%s (mon ip) --> %s (fsid)\n", mon.getSelf().getHostname(), fsid));
}
throw new OperationFailureException(operr(sb.toString()));
}
// check if there is another ceph setup having the same fsid
String fsId = set.iterator().next();
SimpleQuery<CephPrimaryStorageVO> q = dbf.createQuery(CephPrimaryStorageVO.class);
q.add(CephPrimaryStorageVO_.fsid, Op.EQ, fsId);
q.add(CephPrimaryStorageVO_.uuid, Op.NOT_EQ, self.getUuid());
CephPrimaryStorageVO otherCeph = q.find();
if (otherCeph != null) {
throw new OperationFailureException(
operr("there is another CEPH primary storage[name:%s, uuid:%s] with the same" +
" FSID[%s], you cannot add the same CEPH setup as two different primary storage",
otherCeph.getName(), otherCeph.getUuid(), fsId)
);
}
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "check_pool";
@Override
public void run(FlowTrigger trigger, Map data) {
List<Pool> pools = new ArrayList<Pool>();
String primaryStorageUuid = self.getUuid();
Pool p = new Pool();
p.name = getDefaultImageCachePoolName();
p.predefined = CephSystemTags.PREDEFINED_PRIMARY_STORAGE_IMAGE_CACHE_POOL.hasTag(primaryStorageUuid);
pools.add(p);
p = new Pool();
p.name = getDefaultRootVolumePoolName();
p.predefined = CephSystemTags.PREDEFINED_PRIMARY_STORAGE_ROOT_VOLUME_POOL.hasTag(primaryStorageUuid);
pools.add(p);
p = new Pool();
p.name = getDefaultDataVolumePoolName();
p.predefined = CephSystemTags.PREDEFINED_PRIMARY_STORAGE_DATA_VOLUME_POOL.hasTag(primaryStorageUuid);
pools.add(p);
if(!newAdded){
CheckCmd check = new CheckCmd();
check.setPools(pools);
httpCall(CHECK_POOL_PATH, check, CheckRsp.class, new ReturnValueCompletion<CheckRsp>(trigger) {
@Override
public void fail(ErrorCode err) {
trigger.fail(err);
}
@Override
public void success(CheckRsp ret) {
trigger.next();
}
});
}else {
trigger.next();
}
}
});
flow(new NoRollbackFlow() {
String __name__ = "init";
@Override
public void run(final FlowTrigger trigger, Map data) {
List<Pool> pools = new ArrayList<Pool>();
String primaryStorageUuid = self.getUuid();
Pool p = new Pool();
p.name = getDefaultImageCachePoolName();
p.predefined = CephSystemTags.PREDEFINED_PRIMARY_STORAGE_IMAGE_CACHE_POOL.hasTag(primaryStorageUuid);
pools.add(p);
p = new Pool();
p.name = getDefaultRootVolumePoolName();
p.predefined = CephSystemTags.PREDEFINED_PRIMARY_STORAGE_ROOT_VOLUME_POOL.hasTag(primaryStorageUuid);
pools.add(p);
p = new Pool();
p.name = getDefaultDataVolumePoolName();
p.predefined = CephSystemTags.PREDEFINED_PRIMARY_STORAGE_DATA_VOLUME_POOL.hasTag(primaryStorageUuid);
pools.add(p);
InitCmd cmd = new InitCmd();
if (CephSystemTags.NO_CEPHX.hasTag(primaryStorageUuid)) {
cmd.nocephx = true;
}
cmd.pools = pools;
httpCall(INIT_PATH, cmd, InitRsp.class, new ReturnValueCompletion<InitRsp>(trigger) {
@Override
public void fail(ErrorCode err) {
trigger.fail(err);
}
@Override
public void success(InitRsp ret) {
if (getSelf().getFsid() == null) {
getSelf().setFsid(ret.fsid);
}
getSelf().setUserKey(ret.userKey);
self = dbf.updateAndRefresh(self);
CephCapacityUpdater updater = new CephCapacityUpdater();
CephCapacity cephCapacity = new CephCapacity();
cephCapacity.setFsid(ret.fsid);
cephCapacity.setAvailableCapacity(ret.availableCapacity);
cephCapacity.setTotalCapacity(ret.totalCapacity);
cephCapacity.setPoolCapacities(ret.poolCapacities);
cephCapacity.setXsky(ret.isXsky());
updater.update(cephCapacity, true);
trigger.next();
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
if (newAdded) {
PrimaryStorageVO vo = dbf.reload(self);
if (vo != null) {
self = vo;
}
if (!getSelf().getMons().isEmpty()) {
dbf.removeCollection(getSelf().getMons(), CephPrimaryStorageMonVO.class);
}
if (!getSelf().getPools().isEmpty()) {
dbf.removeCollection(getSelf().getPools(), CephPrimaryStoragePoolVO.class);
}
}
completion.fail(errCode);
}
});
}
}).start();
}
@Override
protected void connectHook(ConnectParam param, final Completion completion) {
connect(param.isNewAdded(), completion);
}
@Override
protected void pingHook(final Completion completion) {
final List<CephPrimaryStorageMonBase> mons = getSelf().getMons().stream()
.filter(mon -> !mon.getStatus().equals(MonStatus.Connecting)).map(CephPrimaryStorageMonBase::new).collect(Collectors.toList());
final List<ErrorCode> errors = new ArrayList<ErrorCode>();
class Ping {
private AtomicBoolean replied = new AtomicBoolean(false);
@AsyncThread
private void reconnectMon(final CephPrimaryStorageMonBase mon, boolean delay) {
if (!CephGlobalConfig.PRIMARY_STORAGE_MON_AUTO_RECONNECT.value(Boolean.class)) {
logger.debug(String.format("do not reconnect the ceph primary storage mon[uuid:%s] as the global config[%s] is set to false",
self.getUuid(), CephGlobalConfig.PRIMARY_STORAGE_MON_AUTO_RECONNECT.getCanonicalName()));
return;
}
// there has been a reconnect in process
if (!reconnectMonLock.lock()) {
logger.debug(String.format("ignore this call, reconnect ceph primary storage mon[uuid:%s] is in process", self.getUuid()));
return;
}
final NoErrorCompletion releaseLock = new NoErrorCompletion() {
@Override
public void done() {
reconnectMonLock.unlock();
}
};
try {
if (delay) {
try {
TimeUnit.SECONDS.sleep(CephGlobalConfig.PRIMARY_STORAGE_MON_RECONNECT_DELAY.value(Long.class));
} catch (InterruptedException ignored) {
}
}
mon.connect(new Completion(releaseLock) {
@Override
public void success() {
logger.debug(String.format("successfully reconnected the mon[uuid:%s] of the ceph primary" +
" storage[uuid:%s, name:%s]", mon.getSelf().getUuid(), self.getUuid(), self.getName()));
releaseLock.done();
}
@Override
public void fail(ErrorCode errorCode) {
logger.warn(String.format("failed to reconnect the mon[uuid:%s] server of the ceph primary" +
" storage[uuid:%s, name:%s], %s", mon.getSelf().getUuid(), self.getUuid(), self.getName(), errorCode));
releaseLock.done();
}
});
} catch (Throwable t) {
releaseLock.done();
logger.warn(t.getMessage(), t);
}
}
private void ping() {
final List<String> monUuids = mons.stream()
.map(m -> m.getSelf().getMonAddr())
.collect(Collectors.toList());
logger.info(String.format("ceph-ps-ping-mon: %s", String.join(",", monUuids)));
// this is only called when all mons are disconnected
final AsyncLatch latch = new AsyncLatch(mons.size(), new NoErrorCompletion() {
@Override
public void done() {
if (!replied.compareAndSet(false, true)) {
return;
}
ErrorCode err = errf.stringToOperationError(String.format("failed to ping the ceph primary storage[uuid:%s, name:%s]",
self.getUuid(), self.getName()), errors);
completion.fail(err);
}
});
for (final CephPrimaryStorageMonBase mon : mons) {
mon.ping(new ReturnValueCompletion<PingResult>(latch) {
private void thisMonIsDown(ErrorCode err) {
//TODO
logger.warn(String.format("cannot ping mon[uuid:%s] of the ceph primary storage[uuid:%s, name:%s], %s",
mon.getSelf().getUuid(), self.getUuid(), self.getName(), err));
errors.add(err);
mon.changeStatus(MonStatus.Disconnected);
reconnectMon(mon, true);
latch.ack();
}
@Override
public void success(PingResult res) {
if (res.success) {
// as long as there is one mon working, the primary storage works
pingSuccess();
if (mon.getSelf().getStatus() == MonStatus.Disconnected) {
reconnectMon(mon, false);
}
} else if (PingOperationFailure.UnableToCreateFile.toString().equals(res.failure)) {
// as long as there is one mon saying the ceph not working, the primary storage goes down
ErrorCode err = operr("the ceph primary storage[uuid:%s, name:%s] is down, as one mon[uuid:%s] reports" +
" an operation failure[%s]", self.getUuid(), self.getName(), mon.getSelf().getUuid(), res.error);
errors.add(err);
primaryStorageDown();
} else if (!res.success || PingOperationFailure.MonAddrChanged.toString().equals(res.failure)) {
// this mon is down(success == false, operationFailure == false), but the primary storage may still work as other mons may work
ErrorCode errorCode = operr("operation error, because:%s", res.error);
thisMonIsDown(errorCode);
} else {
throw new CloudRuntimeException("should not be here");
}
}
@Override
public void fail(ErrorCode errorCode) {
thisMonIsDown(errorCode);
}
});
}
}
// this is called once a mon return an operation failure
private void primaryStorageDown() {
if (!replied.compareAndSet(false, true)) {
return;
}
// set all mons to be disconnected
for (CephPrimaryStorageMonBase base : mons) {
base.changeStatus(MonStatus.Disconnected);
}
ErrorCode err = errf.stringToOperationError(String.format("failed to ping the ceph primary storage[uuid:%s, name:%s]",
self.getUuid(), self.getName()), errors);
completion.fail(err);
}
private void pingSuccess() {
if (!replied.compareAndSet(false, true)) {
return;
}
completion.success();
}
}
new Ping().ping();
}
@Override
protected void syncPhysicalCapacity(ReturnValueCompletion<PhysicalCapacityUsage> completion) {
PrimaryStorageCapacityVO cap = dbf.findByUuid(self.getUuid(), PrimaryStorageCapacityVO.class);
PhysicalCapacityUsage usage = new PhysicalCapacityUsage();
usage.availablePhysicalSize = cap.getAvailablePhysicalCapacity();
usage.totalPhysicalSize = cap.getTotalPhysicalCapacity();
completion.success(usage);
}
@Override
protected void handle(APIReconnectPrimaryStorageMsg msg) {
final APIReconnectPrimaryStorageEvent evt = new APIReconnectPrimaryStorageEvent(msg.getId());
// fire disconnected canonical event only if the current status is connected
boolean fireEvent = self.getStatus() == PrimaryStorageStatus.Connected;
self.setStatus(PrimaryStorageStatus.Connecting);
dbf.update(self);
connect(false, new Completion(msg) {
@Override
public void success() {
self = dbf.reload(self);
self.setStatus(PrimaryStorageStatus.Connected);
self = dbf.updateAndRefresh(self);
evt.setInventory(getSelfInventory());
bus.publish(evt);
}
@Override
public void fail(ErrorCode errorCode) {
self = dbf.reload(self);
self.setStatus(PrimaryStorageStatus.Disconnected);
self = dbf.updateAndRefresh(self);
if (fireEvent) {
fireDisconnectedCanonicalEvent(errorCode);
}
evt.setError(errorCode);
bus.publish(evt);
}
});
}
@Override
protected void handleApiMessage(APIMessage msg) {
if (msg instanceof APIAddMonToCephPrimaryStorageMsg) {
handle((APIAddMonToCephPrimaryStorageMsg) msg);
} else if (msg instanceof APIRemoveMonFromCephPrimaryStorageMsg) {
handle((APIRemoveMonFromCephPrimaryStorageMsg) msg);
} else if (msg instanceof APIUpdateCephPrimaryStorageMonMsg) {
handle((APIUpdateCephPrimaryStorageMonMsg) msg);
} else if (msg instanceof APIAddCephPrimaryStoragePoolMsg) {
handle((APIAddCephPrimaryStoragePoolMsg) msg);
} else if (msg instanceof APIDeleteCephPrimaryStoragePoolMsg) {
handle((APIDeleteCephPrimaryStoragePoolMsg) msg);
} else if (msg instanceof APIUpdateCephPrimaryStoragePoolMsg) {
handle((APIUpdateCephPrimaryStoragePoolMsg) msg);
} else if (msg instanceof APICleanUpTrashOnPrimaryStorageMsg) {
handle((APICleanUpTrashOnPrimaryStorageMsg) msg);
} else {
super.handleApiMessage(msg);
}
}
private void handle(APIUpdateCephPrimaryStoragePoolMsg msg) {
APIUpdateCephPrimaryStoragePoolEvent evt = new APIUpdateCephPrimaryStoragePoolEvent(msg.getId());
CephPrimaryStoragePoolVO vo = dbf.findByUuid(msg.getUuid(), CephPrimaryStoragePoolVO.class);
if (msg.getAliasName() != null) {
vo.setAliasName(msg.getAliasName());
}
if (msg.getDescription() != null) {
vo.setDescription(msg.getDescription());
}
dbf.update(vo);
evt.setInventory(CephPrimaryStoragePoolInventory.valueOf(vo));
bus.publish(evt);
}
private void handle(APIDeleteCephPrimaryStoragePoolMsg msg) {
APIDeleteCephPrimaryStoragePoolEvent evt = new APIDeleteCephPrimaryStoragePoolEvent(msg.getId());
CephPrimaryStoragePoolVO vo = dbf.findByUuid(msg.getUuid(), CephPrimaryStoragePoolVO.class);
dbf.remove(vo);
bus.publish(evt);
}
private void handle(APIAddCephPrimaryStoragePoolMsg msg) {
CephPrimaryStoragePoolVO vo = new CephPrimaryStoragePoolVO();
vo.setUuid(msg.getResourceUuid() == null ? Platform.getUuid() : msg.getResourceUuid());
vo.setDescription(msg.getDescription());
vo.setPoolName(msg.getPoolName());
if (msg.getAliasName() != null) {
vo.setAliasName(msg.getAliasName());
}
if (msg.getDescription() != null) {
vo.setDescription(msg.getDescription());
}
vo.setType(msg.getType());
vo.setPrimaryStorageUuid(self.getUuid());
vo = dbf.persistAndRefresh(vo);
AddPoolCmd cmd = new AddPoolCmd();
cmd.isCreate = msg.isCreate();
cmd.poolName = EncodingConversion.encodingToUnicode(msg.getPoolName());
APIAddCephPrimaryStoragePoolEvent evt = new APIAddCephPrimaryStoragePoolEvent(msg.getId());
CephPrimaryStoragePoolVO finalVo = vo;
httpCall(ADD_POOL_PATH, cmd, AddPoolRsp.class, new ReturnValueCompletion<AddPoolRsp>(msg) {
@Override
public void success(AddPoolRsp rsp) {
evt.setInventory(CephPrimaryStoragePoolInventory.valueOf(finalVo));
bus.publish(evt);
}
@Override
public void fail(ErrorCode errorCode) {
dbf.remove(finalVo);
evt.setError(errorCode);
bus.publish(evt);
}
});
}
private void handle(APIRemoveMonFromCephPrimaryStorageMsg msg) {
APIRemoveMonFromCephPrimaryStorageEvent evt = new APIRemoveMonFromCephPrimaryStorageEvent(msg.getId());
SimpleQuery<CephPrimaryStorageMonVO> q = dbf.createQuery(CephPrimaryStorageMonVO.class);
q.add(CephPrimaryStorageMonVO_.hostname, Op.IN, msg.getMonHostnames());
List<CephPrimaryStorageMonVO> vos = q.list();
dbf.removeCollection(vos, CephPrimaryStorageMonVO.class);
evt.setInventory(CephPrimaryStorageInventory.valueOf(dbf.reload(getSelf())));
bus.publish(evt);
}
private void handle(APIUpdateCephPrimaryStorageMonMsg msg) {
final APIUpdateCephPrimaryStorageMonEvent evt = new APIUpdateCephPrimaryStorageMonEvent(msg.getId());
CephPrimaryStorageMonVO monvo = dbf.findByUuid(msg.getMonUuid(), CephPrimaryStorageMonVO.class);
if (msg.getHostname() != null) {
monvo.setHostname(msg.getHostname());
}
if (msg.getMonPort() != null && msg.getMonPort() > 0 && msg.getMonPort() <= 65535) {
monvo.setMonPort(msg.getMonPort());
}
if (msg.getSshPort() != null && msg.getSshPort() > 0 && msg.getSshPort() <= 65535) {
monvo.setSshPort(msg.getSshPort());
}
if (msg.getSshUsername() != null) {
monvo.setSshUsername(msg.getSshUsername());
}
if (msg.getSshPassword() != null) {
monvo.setSshPassword(msg.getSshPassword());
}
dbf.update(monvo);
evt.setInventory(CephPrimaryStorageInventory.valueOf((dbf.reload(getSelf()))));
bus.publish(evt);
}
private void handle(final APIAddMonToCephPrimaryStorageMsg msg) {
final APIAddMonToCephPrimaryStorageEvent evt = new APIAddMonToCephPrimaryStorageEvent(msg.getId());
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("add-mon-ceph-primary-storage-%s", self.getUuid()));
chain.then(new ShareFlow() {
List<CephPrimaryStorageMonVO> monVOs = new ArrayList<CephPrimaryStorageMonVO>();
@Override
public void setup() {
flow(new Flow() {
String __name__ = "create-mon-in-db";
@Override
public void run(FlowTrigger trigger, Map data) {
for (String url : msg.getMonUrls()) {
CephPrimaryStorageMonVO monvo = new CephPrimaryStorageMonVO();
MonUri uri = new MonUri(url);
monvo.setUuid(Platform.getUuid());
monvo.setStatus(MonStatus.Connecting);
monvo.setHostname(uri.getHostname());
monvo.setMonAddr(monvo.getHostname());
monvo.setMonPort(uri.getMonPort());
monvo.setSshPort(uri.getSshPort());
monvo.setSshUsername(uri.getSshUsername());
monvo.setSshPassword(uri.getSshPassword());
monvo.setPrimaryStorageUuid(self.getUuid());
monVOs.add(monvo);
}
dbf.persistCollection(monVOs);
trigger.next();
}
@Override
public void rollback(FlowRollback trigger, Map data) {
dbf.removeCollection(monVOs, CephPrimaryStorageMonVO.class);
trigger.rollback();
}
});
flow(new NoRollbackFlow() {
String __name__ = "connect-mons";
@Override
public void run(final FlowTrigger trigger, Map data) {
List<CephPrimaryStorageMonBase> bases = CollectionUtils.transformToList(monVOs, new Function<CephPrimaryStorageMonBase, CephPrimaryStorageMonVO>() {
@Override
public CephPrimaryStorageMonBase call(CephPrimaryStorageMonVO arg) {
return new CephPrimaryStorageMonBase(arg);
}
});
final List<ErrorCode> errorCodes = new ArrayList<ErrorCode>();
final AsyncLatch latch = new AsyncLatch(bases.size(), new NoErrorCompletion(trigger) {
@Override
public void done() {
if (!errorCodes.isEmpty()) {
trigger.fail(operr( "unable to connect mons").causedBy(errorCodes));
} else {
trigger.next();
}
}
});
for (CephPrimaryStorageMonBase base : bases) {
base.connect(new Completion(trigger) {
@Override
public void success() {
latch.ack();
}
@Override
public void fail(ErrorCode errorCode) {
// one fails, all fail
errorCodes.add(errorCode);
latch.ack();
}
});
}
}
});
flow(new NoRollbackFlow() {
String __name__ = "check-mon-integrity";
@Override
public void run(final FlowTrigger trigger, Map data) {
List<CephPrimaryStorageMonBase> bases = CollectionUtils.transformToList(monVOs, new Function<CephPrimaryStorageMonBase, CephPrimaryStorageMonVO>() {
@Override
public CephPrimaryStorageMonBase call(CephPrimaryStorageMonVO arg) {
return new CephPrimaryStorageMonBase(arg);
}
});
final List<ErrorCode> errors = new ArrayList<ErrorCode>();
final AsyncLatch latch = new AsyncLatch(bases.size(), new NoErrorCompletion(trigger) {
@Override
public void done() {
// one fail, all fail
if (!errors.isEmpty()) {
trigger.fail(operr("unable to add mon to ceph primary storage").causedBy(errors));
} else {
trigger.next();
}
}
});
for (final CephPrimaryStorageMonBase base : bases) {
GetFactsCmd cmd = new GetFactsCmd();
cmd.uuid = self.getUuid();
cmd.monUuid = base.getSelf().getUuid();
base.httpCall(GET_FACTS, cmd, GetFactsRsp.class, new ReturnValueCompletion<GetFactsRsp>(latch) {
@Override
public void success(GetFactsRsp rsp) {
if (!rsp.isSuccess()) {
errors.add(operr("operation error, because:%s", rsp.getError()));
} else {
String fsid = rsp.fsid;
if (!getSelf().getFsid().equals(fsid)) {
errors.add(operr("the mon[ip:%s] returns a fsid[%s] different from the current fsid[%s] of the cep cluster," +
"are you adding a mon not belonging to current cluster mistakenly?", base.getSelf().getHostname(), fsid, getSelf().getFsid())
);
}
}
latch.ack();
}
@Override
public void fail(ErrorCode errorCode) {
errors.add(errorCode);
latch.ack();
}
});
}
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
evt.setInventory(CephPrimaryStorageInventory.valueOf(dbf.reload(getSelf())));
bus.publish(evt);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
evt.setError(errCode);
bus.publish(evt);
}
});
}
}).start();
}
@Override
protected void handleLocalMessage(Message msg) {
if (msg instanceof TakeSnapshotMsg) {
handle((TakeSnapshotMsg) msg);
} else if (msg instanceof CreateVolumeFromVolumeSnapshotOnPrimaryStorageMsg) {
handle((CreateVolumeFromVolumeSnapshotOnPrimaryStorageMsg) msg);
} else if (msg instanceof BackupVolumeSnapshotFromPrimaryStorageToBackupStorageMsg) {
handle((BackupVolumeSnapshotFromPrimaryStorageToBackupStorageMsg) msg);
} else if (msg instanceof CreateKvmSecretMsg) {
handle((CreateKvmSecretMsg) msg);
} else if (msg instanceof UploadBitsToBackupStorageMsg) {
handle((UploadBitsToBackupStorageMsg) msg);
} else if (msg instanceof SetupSelfFencerOnKvmHostMsg) {
handle((SetupSelfFencerOnKvmHostMsg) msg);
} else if (msg instanceof CancelSelfFencerOnKvmHostMsg) {
handle((CancelSelfFencerOnKvmHostMsg) msg);
} else if (msg instanceof DeleteImageCacheOnPrimaryStorageMsg) {
handle((DeleteImageCacheOnPrimaryStorageMsg) msg);
} else if (msg instanceof PurgeSnapshotOnPrimaryStorageMsg) {
handle((PurgeSnapshotOnPrimaryStorageMsg) msg);
} else if (msg instanceof CreateEmptyVolumeMsg) {
handle((CreateEmptyVolumeMsg) msg);
} else if (msg instanceof CephToCephMigrateVolumeSegmentMsg) {
handle((CephToCephMigrateVolumeSegmentMsg) msg);
} else if (msg instanceof GetVolumeSnapshotInfoMsg) {
handle((GetVolumeSnapshotInfoMsg) msg);
} else if (msg instanceof DownloadBitsFromKVMHostToPrimaryStorageMsg) {
handle((DownloadBitsFromKVMHostToPrimaryStorageMsg) msg);
} else if (msg instanceof CancelDownloadBitsFromKVMHostToPrimaryStorageMsg) {
handle((CancelDownloadBitsFromKVMHostToPrimaryStorageMsg) msg);
} else if ((msg instanceof CleanUpTrashOnPrimaryStroageMsg)) {
handle((CleanUpTrashOnPrimaryStroageMsg) msg);
} else {
super.handleLocalMessage(msg);
}
}
public static class CheckIsBitsExistingRsp extends AgentResponse {
private boolean existing;
public void setExisting(boolean existing) {
this.existing = existing;
}
public boolean isExisting() {
return existing;
}
}
private void handle(DownloadBitsFromKVMHostToPrimaryStorageMsg msg) {
DownloadBitsFromKVMHostToPrimaryStorageReply reply = new DownloadBitsFromKVMHostToPrimaryStorageReply();
GetKVMHostDownloadCredentialMsg gmsg = new GetKVMHostDownloadCredentialMsg();
gmsg.setHostUuid(msg.getSrcHostUuid());
if (PrimaryStorageSystemTags.PRIMARY_STORAGE_GATEWAY.hasTag(self.getUuid())) {
gmsg.setDataNetworkCidr(PrimaryStorageSystemTags.PRIMARY_STORAGE_GATEWAY.getTokenByResourceUuid(self.getUuid(), PrimaryStorageSystemTags.PRIMARY_STORAGE_GATEWAY_TOKEN));
}
bus.makeTargetServiceIdByResourceUuid(gmsg, HostConstant.SERVICE_ID, msg.getSrcHostUuid());
bus.send(gmsg, new CloudBusCallBack(reply) {
@Override
public void run(MessageReply rly) {
if (!rly.isSuccess()) {
reply.setError(rly.getError());
bus.reply(msg, reply);
return;
}
GetKVMHostDownloadCredentialReply grly = rly.castReply();
DownloadBitsFromKVMHostCmd cmd = new DownloadBitsFromKVMHostCmd();
cmd.setHostname(grly.getHostname());
cmd.setUsername(grly.getUsername());
cmd.setSshKey(grly.getSshKey());
cmd.setSshPort(grly.getSshPort());
cmd.setBackupStorageInstallPath(msg.getHostInstallPath());
cmd.setPrimaryStorageInstallPath(msg.getPrimaryStorageInstallPath());
cmd.setBandWidth(msg.getBandWidth());
cmd.setIdentificationCode(msg.getLongJobUuid() + msg.getPrimaryStorageInstallPath());
String randomFactor = msg.getLongJobUuid();
new HttpCaller<>(DOWNLOAD_BITS_FROM_KVM_HOST_PATH, cmd, AgentResponse.class, new ReturnValueCompletion<AgentResponse>(reply) {
@Override
public void success(AgentResponse returnValue) {
if (returnValue.isSuccess()) {
logger.info(String.format("successfully downloaded bits %s from kvm host %s to primary storage %s", cmd.getBackupStorageInstallPath(), msg.getSrcHostUuid(), msg.getPrimaryStorageUuid()));
bus.reply(msg, reply);
} else {
logger.error(String.format("failed to download bits %s from kvm host %s to primary storage %s", cmd.getBackupStorageInstallPath(), msg.getSrcHostUuid(), msg.getPrimaryStorageUuid()));
reply.setError(Platform.operr("operation error, because:%s", returnValue.getError()));
bus.reply(msg, reply);
}
}
@Override
public void fail(ErrorCode errorCode) {
logger.error(String.format("failed to download bits %s from kvm host %s to primary storage %s", cmd.getBackupStorageInstallPath(), msg.getSrcHostUuid(), msg.getPrimaryStorageUuid()));
reply.setError(errorCode);
bus.reply(msg, reply);
}
}).specifyOrder(randomFactor).call();
}
});
}
private void handle(CancelDownloadBitsFromKVMHostToPrimaryStorageMsg msg) {
CancelDownloadBitsFromKVMHostToPrimaryStorageReply reply = new CancelDownloadBitsFromKVMHostToPrimaryStorageReply();
CancelDownloadBitsFromKVMHostCmd cmd = new CancelDownloadBitsFromKVMHostCmd();
cmd.setPrimaryStorageInstallPath(msg.getPrimaryStorageInstallPath());
String randomFactor = msg.getLongJobUuid();
new HttpCaller<>(CANCEL_DOWNLOAD_BITS_FROM_KVM_HOST_PATH, cmd, AgentResponse.class, new ReturnValueCompletion<AgentResponse>(reply) {
@Override
public void success(AgentResponse returnValue) {
if (returnValue.isSuccess()) {
logger.info(String.format("successfully cancle downloaded bits to primary storage %s", msg.getPrimaryStorageUuid()));
} else {
logger.error(String.format("failed to cancel download bits to primary storage %s",msg.getPrimaryStorageUuid()));
reply.setError(Platform.operr("operation error, because:%s", returnValue.getError()));
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
logger.error(String.format("failed to cancel download bits to primary storage %s", msg.getPrimaryStorageUuid()));
reply.setError(errorCode);
bus.reply(msg, reply);
}
}).specifyOrder(randomFactor).tryNext().call();
}
private void handle(DeleteImageCacheOnPrimaryStorageMsg msg) {
DeleteImageCacheOnPrimaryStorageReply reply = new DeleteImageCacheOnPrimaryStorageReply();
DeleteImageCacheCmd cmd = new DeleteImageCacheCmd();
cmd.setFsId(getSelf().getFsid());
cmd.setUuid(self.getUuid());
cmd.imagePath = msg.getInstallPath().split("@")[0];
cmd.snapshotPath = msg.getInstallPath();
httpCall(DELETE_IMAGE_CACHE, cmd, AgentResponse.class, new ReturnValueCompletion<AgentResponse>(msg) {
@Override
public void success(AgentResponse rsp) {
if (!rsp.isSuccess()) {
reply.setError(operr("operation error, because:%s", rsp.getError()));
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(CancelSelfFencerOnKvmHostMsg msg) {
KvmCancelSelfFencerParam param = msg.getParam();
KvmCancelSelfFencerCmd cmd = new KvmCancelSelfFencerCmd();
cmd.uuid = self.getUuid();
cmd.fsId = getSelf().getFsid();
cmd.hostUuid = param.getHostUuid();
CancelSelfFencerOnKvmHostReply reply = new CancelSelfFencerOnKvmHostReply();
new KvmCommandSender(param.getHostUuid()).send(cmd, KVM_HA_CANCEL_SELF_FENCER, wrapper -> {
AgentResponse rsp = wrapper.getResponse(AgentResponse.class);
return rsp.isSuccess() ? null : operr("operation error, because:%s", rsp.getError());
}, new ReturnValueCompletion<KvmResponseWrapper>(msg) {
@Override
public void success(KvmResponseWrapper w) {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final SetupSelfFencerOnKvmHostMsg msg) {
KvmSetupSelfFencerParam param = msg.getParam();
KvmSetupSelfFencerCmd cmd = new KvmSetupSelfFencerCmd();
cmd.uuid = self.getUuid();
cmd.fsId = getSelf().getFsid();
cmd.hostUuid = param.getHostUuid();
cmd.interval = param.getInterval();
cmd.maxAttempts = param.getMaxAttempts();
cmd.storageCheckerTimeout = param.getStorageCheckerTimeout();
cmd.userKey = getSelf().getUserKey();
cmd.heartbeatImagePath = String.format("%s/ceph-ps-%s-host-hb-%s",
getDefaultRootVolumePoolName(),
self.getUuid(),
param.getHostUuid());
cmd.monUrls = CollectionUtils.transformToList(getSelf().getMons(), new Function<String, CephPrimaryStorageMonVO>() {
@Override
public String call(CephPrimaryStorageMonVO arg) {
return String.format("%s:%s", arg.getMonAddr(), arg.getMonPort());
}
});
final SetupSelfFencerOnKvmHostReply reply = new SetupSelfFencerOnKvmHostReply();
new KvmCommandSender(param.getHostUuid()).send(cmd, KVM_HA_SETUP_SELF_FENCER, new KvmCommandFailureChecker() {
@Override
public ErrorCode getError(KvmResponseWrapper wrapper) {
AgentResponse rsp = wrapper.getResponse(AgentResponse.class);
return rsp.isSuccess() ? null : operr("%s", rsp.getError());
}
}, new ReturnValueCompletion<KvmResponseWrapper>(msg) {
@Override
public void success(KvmResponseWrapper wrapper) {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final UploadBitsToBackupStorageMsg msg) {
checkCephFsId(msg.getPrimaryStorageUuid(), msg.getBackupStorageUuid());
SimpleQuery<BackupStorageVO> q = dbf.createQuery(BackupStorageVO.class);
q.select(BackupStorageVO_.type);
q.add(BackupStorageVO_.uuid, Op.EQ, msg.getBackupStorageUuid());
String bsType = q.findValue();
String path = CP_PATH;
String hostname = null;
if (!CephConstants.CEPH_BACKUP_STORAGE_TYPE.equals(bsType)) {
List<PrimaryStorageCommitExtensionPoint> exts = pluginRgty.getExtensionList(PrimaryStorageCommitExtensionPoint.class);
DebugUtils.Assert(exts.size() <= 1, "PrimaryStorageCommitExtensionPoint mustn't > 1");
if (exts.size() == 0) {
throw new OperationFailureException(operr(
"unable to upload bits to the backup storage[type:%s], we only support CEPH", bsType
));
} else {
path = exts.get(0).getCommitAgentPath(self.getType());
hostname = exts.get(0).getHostName(msg.getBackupStorageUuid());
DebugUtils.Assert(path != null, String.format("found the extension point: [%s], but return null path",
exts.get(0).getClass().getSimpleName()));
}
}
UploadCmd cmd = new UploadCmd();
cmd.sendCommandUrl = restf.getSendCommandUrl();
cmd.fsId = getSelf().getFsid();
cmd.srcPath = msg.getPrimaryStorageInstallPath();
cmd.dstPath = msg.getBackupStorageInstallPath();
if (msg.getImageUuid() != null) {
cmd.imageUuid = msg.getImageUuid();
ImageInventory inv = ImageInventory.valueOf(dbf.findByUuid(msg.getImageUuid(), ImageVO.class));
StringBuilder desc = new StringBuilder();
for (CreateImageExtensionPoint ext : pluginRgty.getExtensionList(CreateImageExtensionPoint.class)) {
String tmp = ext.getImageDescription(inv);
if (tmp != null && !tmp.trim().equals("")) {
desc.append(tmp);
}
}
cmd.description = desc.toString();
}
if (hostname != null) {
// imagestore hostname
cmd.hostname = hostname;
}
final UploadBitsToBackupStorageReply reply = new UploadBitsToBackupStorageReply();
httpCall(path, cmd, CpRsp.class, new ReturnValueCompletion<CpRsp>(msg) {
@Override
public void success(CpRsp rsp) {
if (rsp.installPath != null) {
reply.setInstallPath(rsp.installPath);
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final CreateKvmSecretMsg msg) {
final CreateKvmSecretReply reply = new CreateKvmSecretReply();
createSecretOnKvmHosts(msg.getHostUuids(), new Completion(msg) {
@Override
public void success() {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(BackupVolumeSnapshotFromPrimaryStorageToBackupStorageMsg msg) {
BackupVolumeSnapshotFromPrimaryStorageToBackupStorageReply reply = new BackupVolumeSnapshotFromPrimaryStorageToBackupStorageReply();
reply.setError(operr("backing up snapshots to backup storage is a depreciated feature, which will be removed in future version"));
bus.reply(msg, reply);
}
private void handle(final CreateVolumeFromVolumeSnapshotOnPrimaryStorageMsg msg) {
final CreateVolumeFromVolumeSnapshotOnPrimaryStorageReply reply = new CreateVolumeFromVolumeSnapshotOnPrimaryStorageReply();
final String volPath = makeDataVolumeInstallPath(msg.getVolumeUuid());
VolumeSnapshotInventory sp = msg.getSnapshot();
CpCmd cmd = new CpCmd();
cmd.resourceUuid = msg.getSnapshot().getVolumeUuid();
cmd.srcPath = sp.getPrimaryStorageInstallPath();
cmd.dstPath = volPath;
httpCall(CP_PATH, cmd, CpRsp.class, new ReturnValueCompletion<CpRsp>(msg) {
@Override
public void success(CpRsp rsp) {
reply.setInstallPath(volPath);
reply.setSize(rsp.size);
// current ceph has no way to get the actual size
long asize = rsp.actualSize == null ? 1 : rsp.actualSize;
reply.setActualSize(asize);
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
protected void handle(final RevertVolumeFromSnapshotOnPrimaryStorageMsg msg) {
final RevertVolumeFromSnapshotOnPrimaryStorageReply reply = new RevertVolumeFromSnapshotOnPrimaryStorageReply();
final TaskProgressRange parentStage = getTaskStage();
final TaskProgressRange ROLLBACK_SNAPSHOT_STAGE = new TaskProgressRange(0, 70);
final TaskProgressRange DELETE_ORIGINAL_SNAPSHOT_STAGE = new TaskProgressRange(30, 100);
final FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("revert-volume-[uuid:%s]-from-snapshot-[uuid:%s]-on-ceph-primary-storage",
msg.getVolume().getUuid(), msg.getSnapshot().getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
String originalVolumePath = msg.getVolume().getInstallPath();
// get volume path from snapshot path, just split @
String volumePath = msg.getSnapshot().getPrimaryStorageInstallPath().split("@")[0];
flow(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
TaskProgressRange stage = markTaskStage(parentStage, ROLLBACK_SNAPSHOT_STAGE);
RollbackSnapshotCmd cmd = new RollbackSnapshotCmd();
cmd.snapshotPath = msg.getSnapshot().getPrimaryStorageInstallPath();
httpCall(ROLLBACK_SNAPSHOT_PATH, cmd, RollbackSnapshotRsp.class, new ReturnValueCompletion<RollbackSnapshotRsp>(msg) {
@Override
public void success(RollbackSnapshotRsp returnValue) {
reply.setSize(returnValue.getSize());
reportProgress(stage.getEnd().toString());
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
}, TimeUnit.MILLISECONDS, msg.getTimeout());
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
reply.setNewVolumeInstallPath(volumePath);
bus.reply(msg, reply);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
reply.setError(errCode);
bus.reply(msg, reply);
}
});
}
}).start();
}
private ImageSpec makeImageSpec(VolumeInventory volume) {
ImageVO image = dbf.findByUuid(volume.getRootImageUuid(), ImageVO.class);
if (image == null) {
throw new OperationFailureException(operr("cannot reinit rootvolume [%s] because image [%s] has been deleted and imagecache cannot be found",
volume.getUuid(), volume.getRootImageUuid()));
}
ImageSpec imageSpec = new ImageSpec();
imageSpec.setInventory(ImageInventory.valueOf(image));
ImageBackupStorageRefInventory ref = CollectionUtils.find(image.getBackupStorageRefs(), new Function<ImageBackupStorageRefInventory, ImageBackupStorageRefVO>() {
@Override
public ImageBackupStorageRefInventory call(ImageBackupStorageRefVO arg) {
String fsid = Q.New(CephBackupStorageVO.class).eq(CephBackupStorageVO_.uuid, arg.getBackupStorageUuid()).select(CephBackupStorageVO_.fsid).findValue();
if (fsid != null && fsid.equals(getSelf().getFsid())) {
return ImageBackupStorageRefInventory.valueOf(arg);
}
return null;
}
});
if (ref == null) {
throw new OperationFailureException(operr("cannot find backupstorage to download image [%s] to primarystorage [%s]", volume.getRootImageUuid(), getSelf().getUuid()));
}
imageSpec.setSelectedBackupStorage(ImageBackupStorageRefInventory.valueOf(image.getBackupStorageRefs().iterator().next()));
return imageSpec;
}
protected void handle(final ReInitRootVolumeFromTemplateOnPrimaryStorageMsg msg) {
final ReInitRootVolumeFromTemplateOnPrimaryStorageReply reply = new ReInitRootVolumeFromTemplateOnPrimaryStorageReply();
final FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("reimage-vm-root-volume-%s", msg.getVolume().getUuid()));
chain.then(new ShareFlow() {
String originalVolumePath = msg.getVolume().getInstallPath();
String volumePath = makeResetImageRootVolumeInstallPath(msg.getVolume().getUuid());
String installUrl;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "download-image-to-cache";
@Override
public void run(final FlowTrigger trigger, Map data) {
installUrl = Q.New(ImageCacheVO.class).eq(ImageCacheVO_.imageUuid, msg.getVolume().getRootImageUuid()).
eq(ImageCacheVO_.primaryStorageUuid, msg.getPrimaryStorageUuid()).select(ImageCacheVO_.installUrl).findValue();
if (installUrl != null) {
trigger.next();
return;
}
DownloadVolumeTemplateToPrimaryStorageMsg dmsg = new DownloadVolumeTemplateToPrimaryStorageMsg();
dmsg.setTemplateSpec(makeImageSpec(msg.getVolume()));
dmsg.setPrimaryStorageUuid(msg.getPrimaryStorageUuid());
bus.makeTargetServiceIdByResourceUuid(dmsg, PrimaryStorageConstant.SERVICE_ID, dmsg.getPrimaryStorageUuid());
bus.send(dmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
return;
}
installUrl = ((DownloadVolumeTemplateToPrimaryStorageReply) reply).getImageCache().getInstallUrl();
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "clone-image";
@Override
public void run(final FlowTrigger trigger, Map data) {
CloneCmd cmd = new CloneCmd();
cmd.srcPath = installUrl;
cmd.dstPath = volumePath;
httpCall(CLONE_PATH, cmd, CloneRsp.class, new ReturnValueCompletion<CloneRsp>(trigger) {
@Override
public void fail(ErrorCode err) {
trigger.fail(err);
}
@Override
public void success(CloneRsp ret) {
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "delete-origin-root-volume-which-has-no-snapshot";
@Override
public void run(FlowTrigger trigger, Map data) {
SimpleQuery<VolumeSnapshotVO> sq = dbf.createQuery(VolumeSnapshotVO.class);
sq.add(VolumeSnapshotVO_.primaryStorageInstallPath, Op.LIKE,
String.format("%s%%", originalVolumePath));
sq.count();
if (sq.count() == 0) {
DeleteCmd cmd = new DeleteCmd();
cmd.installPath = originalVolumePath;
httpCall(DELETE_PATH, cmd, DeleteRsp.class, new ReturnValueCompletion<DeleteRsp>(null) {
@Override
public void success(DeleteRsp returnValue) {
logger.debug(String.format("successfully deleted %s", originalVolumePath));
}
@Override
public void fail(ErrorCode errorCode) {
//TODO GC
logger.warn(String.format("unable to delete %s, %s. Need a cleanup",
originalVolumePath, errorCode));
}
});
}
trigger.next();
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
reply.setNewVolumeInstallPath(volumePath);
bus.reply(msg, reply);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
reply.setError(errCode);
bus.reply(msg, reply);
}
});
}
}).start();
}
@Override
protected void handle(final DeleteSnapshotOnPrimaryStorageMsg msg) {
final DeleteSnapshotOnPrimaryStorageReply reply = new DeleteSnapshotOnPrimaryStorageReply();
DeleteSnapshotCmd cmd = new DeleteSnapshotCmd();
cmd.snapshotPath = msg.getSnapshot().getPrimaryStorageInstallPath();
httpCall(DELETE_SNAPSHOT_PATH, cmd, DeleteSnapshotRsp.class, new ReturnValueCompletion<DeleteSnapshotRsp>(msg) {
@Override
public void success(DeleteSnapshotRsp returnValue) {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
}, TimeUnit.MILLISECONDS, msg.getTimeout());
}
protected void handle(final PurgeSnapshotOnPrimaryStorageMsg msg) {
final PurgeSnapshotOnPrimaryStorageReply reply = new PurgeSnapshotOnPrimaryStorageReply();
PurgeSnapshotCmd cmd = new PurgeSnapshotCmd();
cmd.volumePath = msg.getVolumePath();
httpCall(PURGE_SNAPSHOT_PATH, cmd, PurgeSnapshotRsp.class, new ReturnValueCompletion<PurgeSnapshotRsp>(msg) {
@Override
public void success(PurgeSnapshotRsp returnValue) {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
@Override
protected void handle(MergeVolumeSnapshotOnPrimaryStorageMsg msg) {
MergeVolumeSnapshotOnPrimaryStorageReply reply = new MergeVolumeSnapshotOnPrimaryStorageReply();
bus.reply(msg, reply);
}
private void handle(final TakeSnapshotMsg msg) {
final TakeSnapshotReply reply = new TakeSnapshotReply();
final VolumeSnapshotInventory sp = msg.getStruct().getCurrent();
SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class);
q.select(VolumeVO_.installPath);
q.add(VolumeVO_.uuid, Op.EQ, sp.getVolumeUuid());
String volumePath = q.findValue();
final String spPath = String.format("%s@%s", volumePath, sp.getUuid());
CreateSnapshotCmd cmd = new CreateSnapshotCmd();
cmd.volumeUuid = sp.getVolumeUuid();
cmd.snapshotPath = spPath;
httpCall(CREATE_SNAPSHOT_PATH, cmd, CreateSnapshotRsp.class, new ReturnValueCompletion<CreateSnapshotRsp>(msg) {
@Override
public void success(CreateSnapshotRsp rsp) {
// current ceph has no way to get actual size
long asize = rsp.getActualSize() == null ? 0 : rsp.getActualSize();
sp.setSize(asize);
sp.setPrimaryStorageUuid(self.getUuid());
sp.setPrimaryStorageInstallPath(spPath);
sp.setType(VolumeSnapshotConstant.STORAGE_SNAPSHOT_TYPE.toString());
sp.setFormat(VolumeConstant.VOLUME_FORMAT_RAW);
reply.setInventory(sp);
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
@Override
public void attachHook(String clusterUuid, Completion completion) {
SimpleQuery<ClusterVO> q = dbf.createQuery(ClusterVO.class);
q.select(ClusterVO_.hypervisorType);
q.add(ClusterVO_.uuid, Op.EQ, clusterUuid);
String hvType = q.findValue();
if (KVMConstant.KVM_HYPERVISOR_TYPE.equals(hvType)) {
attachToKvmCluster(clusterUuid, completion);
} else {
completion.success();
}
}
private void createSecretOnKvmHosts(List<String> hostUuids, final Completion completion) {
final CreateKvmSecretCmd cmd = new CreateKvmSecretCmd();
cmd.setUserKey(getSelf().getUserKey());
String suuid = CephSystemTags.KVM_SECRET_UUID.getTokenByResourceUuid(self.getUuid(), CephSystemTags.KVM_SECRET_UUID_TOKEN);
DebugUtils.Assert(suuid != null, String.format("cannot find system tag[%s] for ceph primary storage[uuid:%s]", CephSystemTags.KVM_SECRET_UUID.getTagFormat(), self.getUuid()));
cmd.setUuid(suuid);
List<KVMHostAsyncHttpCallMsg> msgs = CollectionUtils.transformToList(hostUuids, new Function<KVMHostAsyncHttpCallMsg, String>() {
@Override
public KVMHostAsyncHttpCallMsg call(String huuid) {
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setCommand(cmd);
msg.setPath(KVM_CREATE_SECRET_PATH);
msg.setHostUuid(huuid);
msg.setNoStatusCheck(true);
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, huuid);
return msg;
}
});
bus.send(msgs, new CloudBusListCallBack(completion) {
@Override
public void run(List<MessageReply> replies) {
for (MessageReply r : replies) {
if (!r.isSuccess()) {
completion.fail(r.getError());
return;
}
KVMHostAsyncHttpCallReply kr = r.castReply();
CreateKvmSecretRsp rsp = kr.toResponse(CreateKvmSecretRsp.class);
if (!rsp.isSuccess()) {
completion.fail(operr("operation error, because:%s", rsp.getError()));
return;
}
}
completion.success();
}
});
}
private void attachToKvmCluster(String clusterUuid, Completion completion) {
SimpleQuery<HostVO> q = dbf.createQuery(HostVO.class);
q.select(HostVO_.uuid);
q.add(HostVO_.clusterUuid, Op.EQ, clusterUuid);
q.add(HostVO_.status, Op.EQ, HostStatus.Connected);
List<String> hostUuids = q.listValue();
if (hostUuids.isEmpty()) {
completion.success();
} else {
createSecretOnKvmHosts(hostUuids, completion);
}
}
@Override
public void deleteHook() {
List<String> poolNameLists = list(
getDefaultRootVolumePoolName(),
getDefaultDataVolumePoolName(),
getDefaultImageCachePoolName()
);
SQL.New(CephPrimaryStoragePoolVO.class)
.in(CephPrimaryStoragePoolVO_.poolName, poolNameLists).delete();
if (CephGlobalConfig.PRIMARY_STORAGE_DELETE_POOL.value(Boolean.class)) {
DeletePoolCmd cmd = new DeletePoolCmd();
cmd.poolNames = poolNameLists;
FutureReturnValueCompletion completion = new FutureReturnValueCompletion(null);
httpCall(DELETE_POOL_PATH, cmd, DeletePoolRsp.class, completion);
completion.await(TimeUnit.MINUTES.toMillis(30));
if (!completion.isSuccess()) {
throw new OperationFailureException(completion.getErrorCode());
}
}
String fsid = getSelf().getFsid();
new SQLBatch(){
@Override
protected void scripts() {
if(Q.New(CephBackupStorageVO.class).eq(CephBackupStorageVO_.fsid, fsid).find() == null){
SQL.New(CephCapacityVO.class).eq(CephCapacityVO_.fsid, fsid).delete();
}
}
}.execute();
dbf.removeCollection(getSelf().getMons(), CephPrimaryStorageMonVO.class);
}
private void handle(CreateEmptyVolumeMsg msg) {
final CreateEmptyVolumeReply reply = new CreateEmptyVolumeReply();
final CreateEmptyVolumeCmd cmd = new CreateEmptyVolumeCmd();
cmd.installPath = msg.getInstallPath();
cmd.size = msg.getSize();
cmd.shareable = msg.isShareable();
cmd.skipIfExisting = msg.isSkipIfExisting();
httpCall(CREATE_VOLUME_PATH, cmd, CreateEmptyVolumeRsp.class, new ReturnValueCompletion<CreateEmptyVolumeRsp>(msg) {
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
}
@Override
public void success(CreateEmptyVolumeRsp ret) {
bus.reply(msg, reply);
}
});
}
private void handle(CephToCephMigrateVolumeSegmentMsg msg) {
final CephToCephMigrateVolumeSegmentCmd cmd = new CephToCephMigrateVolumeSegmentCmd();
cmd.setParentUuid(msg.getParentUuid());
cmd.setResourceUuid(msg.getResourceUuid());
cmd.setSrcInstallPath(msg.getSrcInstallPath());
cmd.setDstInstallPath(msg.getDstInstallPath());
cmd.setDstMonHostname(msg.getDstMonHostname());
cmd.setDstMonSshUsername(msg.getDstMonSshUsername());
cmd.setDstMonSshPassword(msg.getDstMonSshPassword());
cmd.setDstMonSshPort(msg.getDstMonSshPort());
final CephToCephMigrateVolumeSegmentReply reply = new CephToCephMigrateVolumeSegmentReply();
httpCall(CEPH_TO_CEPH_MIGRATE_VOLUME_SEGMENT_PATH, cmd, StorageMigrationRsp.class, new ReturnValueCompletion<StorageMigrationRsp>(msg) {
@Override
public void success(StorageMigrationRsp returnValue) {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
}, TimeUnit.MILLISECONDS, msg.getTimeout());
}
private void handle(GetVolumeSnapshotInfoMsg msg) {
final GetVolumeSnapInfosCmd cmd = new GetVolumeSnapInfosCmd();
cmd.setVolumePath(msg.getVolumePath());
final GetVolumeSnapshotInfoReply reply = new GetVolumeSnapshotInfoReply();
httpCall(GET_VOLUME_SNAPINFOS_PATH, cmd, GetVolumeSnapInfosRsp.class, new ReturnValueCompletion<GetVolumeSnapInfosRsp>(msg) {
@Override
public void success(GetVolumeSnapInfosRsp returnValue) {
reply.setSnapInfos(returnValue.getSnapInfos());
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
@Override
public void handle(AskInstallPathForNewSnapshotMsg msg) {
AskInstallPathForNewSnapshotReply reply = new AskInstallPathForNewSnapshotReply();
bus.reply(msg, reply);
}
@Override
protected void handle(CheckVolumeSnapshotsOnPrimaryStorageMsg msg) {
final CheckVolumeSnapshotsOnPrimaryStorageReply reply = new CheckVolumeSnapshotsOnPrimaryStorageReply();
CheckSnapshotCompletedCmd cmd = new CheckSnapshotCompletedCmd();
cmd.setVolumePath(msg.getVolumeInstallPath());
cmd.snapshots = msg.getSnapshots().stream().map(VolumeSnapshotInventory::getUuid).collect(Collectors.toList());
httpCall(CHECK_SNAPSHOT_COMPLETED, cmd, CheckSnapshotCompletedRsp.class, new ReturnValueCompletion<CheckSnapshotCompletedRsp>(msg) {
@Override
public void success(CheckSnapshotCompletedRsp returnValue) {
reply.setCompleted(returnValue.completed);
if (returnValue.completed) {
/**
* complete the new snapshot installpath
*/
VolumeSnapshotVO snapshot = dbf.findByUuid(returnValue.snapshotUuid, VolumeSnapshotVO.class);
snapshot.setStatus(VolumeSnapshotStatus.Ready);
snapshot.setPrimaryStorageInstallPath(msg.getVolumeInstallPath() + "@" + snapshot.getUuid());
snapshot.setSize(returnValue.size);
snapshot.setPrimaryStorageUuid(self.getUuid());
snapshot.setType(VolumeSnapshotConstant.STORAGE_SNAPSHOT_TYPE.toString());
snapshot.setFormat(VolumeConstant.VOLUME_FORMAT_RAW);
dbf.updateAndRefresh(snapshot);
reply.setSnapshotUuid(returnValue.snapshotUuid);
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
bus.reply(msg, reply);
}
@Override
protected void handle(GetVolumeSnapshotSizeOnPrimaryStorageMsg msg) {
GetVolumeSnapshotSizeOnPrimaryStorageReply reply = new GetVolumeSnapshotSizeOnPrimaryStorageReply();
VolumeSnapshotVO snapshotVO = dbf.findByUuid(msg.getSnapshotUuid(), VolumeSnapshotVO.class);
String installPath = snapshotVO.getPrimaryStorageInstallPath();
GetVolumeSnapshotSizeCmd cmd = new GetVolumeSnapshotSizeCmd();
cmd.fsId = getSelf().getFsid();
cmd.uuid = self.getUuid();
cmd.volumeSnapshotUuid = snapshotVO.getUuid();
cmd.installPath = installPath;
httpCall(GET_VOLUME_SNAPSHOT_SIZE_PATH, cmd, GetVolumeSnapshotSizeRsp.class, new ReturnValueCompletion<GetVolumeSnapshotSizeRsp>(msg) {
@Override
public void success(GetVolumeSnapshotSizeRsp rsp) {
reply.setActualSize(rsp.actualSize);
reply.setSize(rsp.size);
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
}
| plugin/ceph/src/main/java/org/zstack/storage/ceph/primary/CephPrimaryStorageBase.java | package org.zstack.storage.ceph.primary;
import org.springframework.beans.factory.annotation.Autowired;
import org.zstack.core.Platform;
import org.zstack.core.asyncbatch.While;
import org.zstack.core.cloudbus.CloudBusCallBack;
import org.zstack.core.cloudbus.CloudBusListCallBack;
import org.zstack.core.componentloader.PluginRegistry;
import org.zstack.core.db.Q;
import org.zstack.core.db.SQL;
import org.zstack.core.db.SQLBatch;
import org.zstack.core.db.SimpleQuery;
import org.zstack.core.db.SimpleQuery.Op;
import org.zstack.core.thread.AsyncThread;
import org.zstack.core.thread.ChainTask;
import org.zstack.core.thread.SyncTaskChain;
import org.zstack.core.thread.ThreadFacade;
import org.zstack.core.timeout.ApiTimeoutManager;
import org.zstack.core.workflow.FlowChainBuilder;
import org.zstack.core.workflow.ShareFlow;
import org.zstack.header.HasThreadContext;
import org.zstack.header.agent.ReloadableCommand;
import org.zstack.header.cluster.ClusterVO;
import org.zstack.header.cluster.ClusterVO_;
import org.zstack.header.core.*;
import org.zstack.header.core.progress.TaskProgressRange;
import org.zstack.header.core.trash.CleanTrashResult;
import org.zstack.header.core.validation.Validation;
import org.zstack.header.core.workflow.*;
import org.zstack.header.errorcode.ErrorCode;
import org.zstack.header.errorcode.ErrorCodeList;
import org.zstack.header.errorcode.OperationFailureException;
import org.zstack.header.exception.CloudRuntimeException;
import org.zstack.header.host.HostConstant;
import org.zstack.header.host.HostStatus;
import org.zstack.header.host.HostVO;
import org.zstack.header.host.HostVO_;
import org.zstack.header.image.*;
import org.zstack.header.image.ImageConstant.ImageMediaType;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.Message;
import org.zstack.header.message.MessageReply;
import org.zstack.header.rest.RESTFacade;
import org.zstack.header.storage.backup.*;
import org.zstack.header.storage.primary.*;
import org.zstack.header.storage.primary.VolumeSnapshotCapability.VolumeSnapshotArrangementType;
import org.zstack.header.storage.snapshot.*;
import org.zstack.header.vm.VmInstanceSpec.ImageSpec;
import org.zstack.header.volume.*;
import org.zstack.identity.AccountManager;
import org.zstack.kvm.*;
import org.zstack.kvm.KvmSetupSelfFencerExtensionPoint.KvmCancelSelfFencerParam;
import org.zstack.kvm.KvmSetupSelfFencerExtensionPoint.KvmSetupSelfFencerParam;
import org.zstack.storage.backup.sftp.GetSftpBackupStorageDownloadCredentialMsg;
import org.zstack.storage.backup.sftp.GetSftpBackupStorageDownloadCredentialReply;
import org.zstack.storage.backup.sftp.SftpBackupStorageConstant;
import org.zstack.storage.ceph.*;
import org.zstack.storage.ceph.CephMonBase.PingResult;
import org.zstack.storage.ceph.backup.CephBackupStorageVO;
import org.zstack.storage.ceph.backup.CephBackupStorageVO_;
import org.zstack.storage.ceph.primary.CephPrimaryStorageMonBase.PingOperationFailure;
import org.zstack.storage.primary.PrimaryStorageBase;
import org.zstack.storage.primary.PrimaryStorageSystemTags;
import org.zstack.utils.*;
import org.zstack.utils.function.Function;
import org.zstack.utils.gson.JSONObjectUtil;
import org.zstack.utils.logging.CLogger;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
import static org.zstack.core.Platform.i18n;
import static org.zstack.core.Platform.operr;
import static org.zstack.core.progress.ProgressReportService.*;
import static org.zstack.utils.CollectionDSL.list;
/**
* Created by frank on 7/28/2015.
*/
public class CephPrimaryStorageBase extends PrimaryStorageBase {
private static final CLogger logger = Utils.getLogger(CephPrimaryStorageBase.class);
@Autowired
private RESTFacade restf;
@Autowired
private ThreadFacade thdf;
@Autowired
private ApiTimeoutManager timeoutMgr;
@Autowired
private CephImageCacheCleaner imageCacheCleaner;
@Autowired
private AccountManager acntMgr;
@Autowired
private PluginRegistry pluginRgty;
public CephPrimaryStorageBase() {
}
class ReconnectMonLock {
AtomicBoolean hold = new AtomicBoolean(false);
boolean lock() {
return hold.compareAndSet(false, true);
}
void unlock() {
hold.set(false);
}
}
ReconnectMonLock reconnectMonLock = new ReconnectMonLock();
public static class AgentCommand {
String fsId;
String uuid;
public String monUuid;
public String getFsId() {
return fsId;
}
public void setFsId(String fsId) {
this.fsId = fsId;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
public static class AgentResponse {
String error;
boolean success = true;
Long totalCapacity;
Long availableCapacity;
List<CephPoolCapacity> poolCapacities;
boolean xsky = false;
public String getError() {
return error;
}
public void setError(String error) {
this.success = false;
this.error = error;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public Long getTotalCapacity() {
return totalCapacity;
}
public void setTotalCapacity(Long totalCapacity) {
this.totalCapacity = totalCapacity;
}
public Long getAvailableCapacity() {
return availableCapacity;
}
public void setAvailableCapacity(Long availableCapacity) {
this.availableCapacity = availableCapacity;
}
public List<CephPoolCapacity> getPoolCapacities() {
return poolCapacities;
}
public void setPoolCapacities(List<CephPoolCapacity> poolCapacities) {
this.poolCapacities = poolCapacities;
}
public boolean isXsky() {
return xsky;
}
public void setXsky(boolean xsky) {
this.xsky = xsky;
}
}
public static class AddPoolCmd extends AgentCommand {
public String poolName;
public boolean isCreate;
}
public static class AddPoolRsp extends AgentResponse {
}
public static class DeletePoolRsp extends AgentResponse {
}
public static class GetVolumeSizeCmd extends AgentCommand {
public String volumeUuid;
public String installPath;
}
public static class GetVolumeSnapshotSizeCmd extends AgentCommand {
public String volumeSnapshotUuid;
public String installPath;
}
public static class GetVolumeSizeRsp extends AgentResponse {
public Long size;
public Long actualSize;
}
public static class GetVolumeSnapshotSizeRsp extends AgentResponse {
public Long size;
public Long actualSize;
}
public static class Pool {
String name;
boolean predefined;
}
public static class InitCmd extends AgentCommand {
List<Pool> pools;
Boolean nocephx = false;
public List<Pool> getPools() {
return pools;
}
public void setPools(List<Pool> pools) {
this.pools = pools;
}
public Boolean getNocephx() {
return nocephx;
}
public void setNocephx(Boolean nocephx) {
this.nocephx = nocephx;
}
}
public static class InitRsp extends AgentResponse {
String fsid;
String userKey;
public String getUserKey() {
return userKey;
}
public void setUserKey(String userKey) {
this.userKey = userKey;
}
public String getFsid() {
return fsid;
}
public void setFsid(String fsid) {
this.fsid = fsid;
}
}
public static class CheckCmd extends AgentCommand {
List<Pool> pools;
public List<Pool> getPools() {
return pools;
}
public void setPools(List<Pool> pools) {
this.pools = pools;
}
}
public static class CheckRsp extends AgentResponse{
}
public static class CreateEmptyVolumeCmd extends AgentCommand {
String installPath;
long size;
boolean shareable;
boolean skipIfExisting;
public boolean isShareable() {
return shareable;
}
public void setShareable(boolean shareable) {
this.shareable = shareable;
}
public String getInstallPath() {
return installPath;
}
public void setInstallPath(String installPath) {
this.installPath = installPath;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public void setSkipIfExisting(boolean skipIfExisting) {
this.skipIfExisting = skipIfExisting;
}
public boolean isSkipIfExisting() {
return skipIfExisting;
}
}
public static class CreateEmptyVolumeRsp extends AgentResponse {
}
public static class DeleteCmd extends AgentCommand {
String installPath;
public String getInstallPath() {
return installPath;
}
public void setInstallPath(String installPath) {
this.installPath = installPath;
}
}
public static class DeleteRsp extends AgentResponse {
}
public static class CloneCmd extends AgentCommand {
String srcPath;
String dstPath;
public String getSrcPath() {
return srcPath;
}
public void setSrcPath(String srcPath) {
this.srcPath = srcPath;
}
public String getDstPath() {
return dstPath;
}
public void setDstPath(String dstPath) {
this.dstPath = dstPath;
}
}
public static class CloneRsp extends AgentResponse {
}
public static class FlattenCmd extends AgentCommand {
String path;
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
public static class FlattenRsp extends AgentResponse {
}
public static class SftpDownloadCmd extends AgentCommand {
String sshKey;
String hostname;
String username;
int sshPort;
String backupStorageInstallPath;
String primaryStorageInstallPath;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getSshPort() {
return sshPort;
}
public void setSshPort(int sshPort) {
this.sshPort = sshPort;
}
public String getSshKey() {
return sshKey;
}
public void setSshKey(String sshKey) {
this.sshKey = sshKey;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getBackupStorageInstallPath() {
return backupStorageInstallPath;
}
public void setBackupStorageInstallPath(String backupStorageInstallPath) {
this.backupStorageInstallPath = backupStorageInstallPath;
}
public String getPrimaryStorageInstallPath() {
return primaryStorageInstallPath;
}
public void setPrimaryStorageInstallPath(String primaryStorageInstallPath) {
this.primaryStorageInstallPath = primaryStorageInstallPath;
}
}
public static class SftpDownloadRsp extends AgentResponse {
}
public static class SftpUpLoadCmd extends AgentCommand implements HasThreadContext{
String sendCommandUrl;
String primaryStorageInstallPath;
String backupStorageInstallPath;
String hostname;
String username;
String sshKey;
int sshPort;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getSshPort() {
return sshPort;
}
public void setSshPort(int sshPort) {
this.sshPort = sshPort;
}
public String getPrimaryStorageInstallPath() {
return primaryStorageInstallPath;
}
public void setPrimaryStorageInstallPath(String primaryStorageInstallPath) {
this.primaryStorageInstallPath = primaryStorageInstallPath;
}
public String getBackupStorageInstallPath() {
return backupStorageInstallPath;
}
public void setBackupStorageInstallPath(String backupStorageInstallPath) {
this.backupStorageInstallPath = backupStorageInstallPath;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getSshKey() {
return sshKey;
}
public void setSshKey(String sshKey) {
this.sshKey = sshKey;
}
public void setSendCommandUrl(String sendCommandUrl) {
this.sendCommandUrl = sendCommandUrl;
}
public String getSendCommandUrl() {
return sendCommandUrl;
}
}
public static class SftpUploadRsp extends AgentResponse {
}
public static class CreateSnapshotCmd extends AgentCommand {
boolean skipOnExisting;
String snapshotPath;
String volumeUuid;
public String getVolumeUuid() {
return volumeUuid;
}
public void setVolumeUuid(String volumeUuid) {
this.volumeUuid = volumeUuid;
}
public boolean isSkipOnExisting() {
return skipOnExisting;
}
public void setSkipOnExisting(boolean skipOnExisting) {
this.skipOnExisting = skipOnExisting;
}
public String getSnapshotPath() {
return snapshotPath;
}
public void setSnapshotPath(String snapshotPath) {
this.snapshotPath = snapshotPath;
}
}
public static class CreateSnapshotRsp extends AgentResponse {
Long size;
Long actualSize;
public Long getActualSize() {
return actualSize;
}
public void setActualSize(Long actualSize) {
this.actualSize = actualSize;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
}
public static class DeleteSnapshotCmd extends AgentCommand {
String snapshotPath;
public String getSnapshotPath() {
return snapshotPath;
}
public void setSnapshotPath(String snapshotPath) {
this.snapshotPath = snapshotPath;
}
}
public static class DeleteSnapshotRsp extends AgentResponse {
}
public static class ProtectSnapshotCmd extends AgentCommand {
String snapshotPath;
boolean ignoreError;
public boolean isIgnoreError() {
return ignoreError;
}
public void setIgnoreError(boolean ignoreError) {
this.ignoreError = ignoreError;
}
public String getSnapshotPath() {
return snapshotPath;
}
public void setSnapshotPath(String snapshotPath) {
this.snapshotPath = snapshotPath;
}
}
public static class ProtectSnapshotRsp extends AgentResponse {
}
public static class UnprotectedSnapshotCmd extends AgentCommand {
String snapshotPath;
public String getSnapshotPath() {
return snapshotPath;
}
public void setSnapshotPath(String snapshotPath) {
this.snapshotPath = snapshotPath;
}
}
public static class UnprotectedSnapshotRsp extends AgentResponse {
}
public static class CpCmd extends AgentCommand implements HasThreadContext{
String sendCommandUrl;
String resourceUuid;
String srcPath;
String dstPath;
}
public static class UploadCmd extends AgentCommand implements HasThreadContext{
public String sendCommandUrl;
public String imageUuid;
public String hostname;
public String srcPath;
public String dstPath;
public String description;
}
public static class CpRsp extends AgentResponse {
public Long size;
public Long actualSize;
public String installPath;
}
public static class RollbackSnapshotCmd extends AgentCommand implements HasThreadContext {
String snapshotPath;
public String getSnapshotPath() {
return snapshotPath;
}
public void setSnapshotPath(String snapshotPath) {
this.snapshotPath = snapshotPath;
}
}
public static class RollbackSnapshotRsp extends AgentResponse {
@Validation
long size;
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
}
public static class CheckIsBitsExistingCmd extends AgentCommand {
String installPath;
public void setInstallPath(String installPath) {
this.installPath = installPath;
}
public String getInstallPath() {
return installPath;
}
}
public static class CreateKvmSecretCmd extends KVMAgentCommands.AgentCommand {
String userKey;
String uuid;
public String getUserKey() {
return userKey;
}
public void setUserKey(String userKey) {
this.userKey = userKey;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
public static class CreateKvmSecretRsp extends AgentResponse {
}
public static class DeletePoolCmd extends AgentCommand {
List<String> poolNames;
public List<String> getPoolNames() {
return poolNames;
}
public void setPoolNames(List<String> poolNames) {
this.poolNames = poolNames;
}
}
public static class KvmSetupSelfFencerCmd extends AgentCommand {
public String heartbeatImagePath;
public String hostUuid;
public long interval;
public int maxAttempts;
public int storageCheckerTimeout;
public String userKey;
public List<String> monUrls;
}
public static class KvmCancelSelfFencerCmd extends AgentCommand {
public String hostUuid;
}
public static class GetFactsCmd extends AgentCommand {
}
public static class GetFactsRsp extends AgentResponse {
public String fsid;
public String monAddr;
}
public static class DeleteImageCacheCmd extends AgentCommand {
public String imagePath;
public String snapshotPath;
}
public static class PurgeSnapshotCmd extends AgentCommand {
public String volumePath;
}
public static class PurgeSnapshotRsp extends AgentResponse {
}
public static class CephToCephMigrateVolumeSegmentCmd extends AgentCommand {
String parentUuid;
String resourceUuid;
String srcInstallPath;
String dstInstallPath;
String dstMonHostname;
String dstMonSshUsername;
String dstMonSshPassword;
int dstMonSshPort;
public String getParentUuid() {
return parentUuid;
}
public void setParentUuid(String parentUuid) {
this.parentUuid = parentUuid;
}
public String getResourceUuid() {
return resourceUuid;
}
public void setResourceUuid(String resourceUuid) {
this.resourceUuid = resourceUuid;
}
public String getSrcInstallPath() {
return srcInstallPath;
}
public void setSrcInstallPath(String srcInstallPath) {
this.srcInstallPath = srcInstallPath;
}
public String getDstInstallPath() {
return dstInstallPath;
}
public void setDstInstallPath(String dstInstallPath) {
this.dstInstallPath = dstInstallPath;
}
public String getDstMonHostname() {
return dstMonHostname;
}
public void setDstMonHostname(String dstMonHostname) {
this.dstMonHostname = dstMonHostname;
}
public String getDstMonSshUsername() {
return dstMonSshUsername;
}
public void setDstMonSshUsername(String dstMonSshUsername) {
this.dstMonSshUsername = dstMonSshUsername;
}
public String getDstMonSshPassword() {
return dstMonSshPassword;
}
public void setDstMonSshPassword(String dstMonSshPassword) {
this.dstMonSshPassword = dstMonSshPassword;
}
public int getDstMonSshPort() {
return dstMonSshPort;
}
public void setDstMonSshPort(int dstMonSshPort) {
this.dstMonSshPort = dstMonSshPort;
}
}
// common response of storage migration
public static class StorageMigrationRsp extends AgentResponse {
}
public static class GetVolumeSnapInfosCmd extends AgentCommand {
private String volumePath;
public String getVolumePath() {
return volumePath;
}
public void setVolumePath(String volumePath) {
this.volumePath = volumePath;
}
}
public static class GetVolumeSnapInfosRsp extends AgentResponse {
private List<SnapInfo> snapInfos;
public List<SnapInfo> getSnapInfos() {
return snapInfos;
}
public void setSnapInfos(List<SnapInfo> snapInfos) {
this.snapInfos = snapInfos;
}
}
public static class CheckSnapshotCompletedCmd extends AgentCommand {
private String volumePath;
private List<String> snapshots; // uuids
public String getVolumePath() {
return volumePath;
}
public void setVolumePath(String volumePath) {
this.volumePath = volumePath;
}
public List<String> getSnapshots() {
return snapshots;
}
public void setSnapshots(List<String> snapshots) {
this.snapshots = snapshots;
}
}
public static class CheckSnapshotCompletedRsp extends AgentResponse {
public String snapshotUuid;
public boolean completed; // whether the snapshot create completed
public long size;
}
public static class DownloadBitsFromKVMHostCmd extends AgentCommand implements ReloadableCommand {
private String hostname;
private String username;
private String sshKey;
private int sshPort;
// it's file path on kvm host actually
private String backupStorageInstallPath;
private String primaryStorageInstallPath;
private Long bandWidth;
private String identificationCode;
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSshKey() {
return sshKey;
}
public void setSshKey(String sshKey) {
this.sshKey = sshKey;
}
public int getSshPort() {
return sshPort;
}
public void setSshPort(int sshPort) {
this.sshPort = sshPort;
}
public String getBackupStorageInstallPath() {
return backupStorageInstallPath;
}
public void setBackupStorageInstallPath(String backupStorageInstallPath) {
this.backupStorageInstallPath = backupStorageInstallPath;
}
public String getPrimaryStorageInstallPath() {
return primaryStorageInstallPath;
}
public void setPrimaryStorageInstallPath(String primaryStorageInstallPath) {
this.primaryStorageInstallPath = primaryStorageInstallPath;
}
public Long getBandWidth() {
return bandWidth;
}
public void setBandWidth(Long bandWidth) {
this.bandWidth = bandWidth;
}
@Override
public void setIdentificationCode(String identificationCode) {
this.identificationCode = identificationCode;
}
}
public static class CancelDownloadBitsFromKVMHostCmd extends AgentCommand {
private String primaryStorageInstallPath;
public String getPrimaryStorageInstallPath() {
return primaryStorageInstallPath;
}
public void setPrimaryStorageInstallPath(String primaryStorageInstallPath) {
this.primaryStorageInstallPath = primaryStorageInstallPath;
}
}
public static class SnapInfo implements Comparable<SnapInfo> {
long id;
String name;
long size;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
@Override
public int compareTo(SnapInfo snapInfo) {
return Long.compare(this.getId(), snapInfo.getId());
}
}
public static final String INIT_PATH = "/ceph/primarystorage/init";
public static final String CREATE_VOLUME_PATH = "/ceph/primarystorage/volume/createempty";
public static final String DELETE_PATH = "/ceph/primarystorage/delete";
public static final String CLONE_PATH = "/ceph/primarystorage/volume/clone";
public static final String FLATTEN_PATH = "/ceph/primarystorage/volume/flatten";
public static final String SFTP_DOWNLOAD_PATH = "/ceph/primarystorage/sftpbackupstorage/download";
public static final String SFTP_UPLOAD_PATH = "/ceph/primarystorage/sftpbackupstorage/upload";
public static final String CREATE_SNAPSHOT_PATH = "/ceph/primarystorage/snapshot/create";
public static final String DELETE_SNAPSHOT_PATH = "/ceph/primarystorage/snapshot/delete";
public static final String PURGE_SNAPSHOT_PATH = "/ceph/primarystorage/volume/purgesnapshots";
public static final String PROTECT_SNAPSHOT_PATH = "/ceph/primarystorage/snapshot/protect";
public static final String ROLLBACK_SNAPSHOT_PATH = "/ceph/primarystorage/snapshot/rollback";
public static final String UNPROTECT_SNAPSHOT_PATH = "/ceph/primarystorage/snapshot/unprotect";
public static final String CP_PATH = "/ceph/primarystorage/volume/cp";
public static final String KVM_CREATE_SECRET_PATH = "/vm/createcephsecret";
public static final String DELETE_POOL_PATH = "/ceph/primarystorage/deletepool";
public static final String GET_VOLUME_SIZE_PATH = "/ceph/primarystorage/getvolumesize";
public static final String GET_VOLUME_SNAPSHOT_SIZE_PATH = "/ceph/primarystorage/getvolumesnapshotsize";
public static final String KVM_HA_SETUP_SELF_FENCER = "/ha/ceph/setupselffencer";
public static final String KVM_HA_CANCEL_SELF_FENCER = "/ha/ceph/cancelselffencer";
public static final String GET_FACTS = "/ceph/primarystorage/facts";
public static final String DELETE_IMAGE_CACHE = "/ceph/primarystorage/deleteimagecache";
public static final String ADD_POOL_PATH = "/ceph/primarystorage/addpool";
public static final String CHECK_POOL_PATH = "/ceph/primarystorage/checkpool";
public static final String CHECK_BITS_PATH = "/ceph/primarystorage/snapshot/checkbits";
public static final String CEPH_TO_CEPH_MIGRATE_VOLUME_SEGMENT_PATH = "/ceph/primarystorage/volume/migratesegment";
public static final String GET_VOLUME_SNAPINFOS_PATH = "/ceph/primarystorage/volume/getsnapinfos";
public static final String DOWNLOAD_BITS_FROM_KVM_HOST_PATH = "/ceph/primarystorage/kvmhost/download";
public static final String CANCEL_DOWNLOAD_BITS_FROM_KVM_HOST_PATH = "/ceph/primarystorage/kvmhost/download/cancel";
public static final String CHECK_SNAPSHOT_COMPLETED = "/ceph/primarystorage/check/snapshot";
private final Map<String, BackupStorageMediator> backupStorageMediators = new HashMap<String, BackupStorageMediator>();
{
backupStorageMediators.put(SftpBackupStorageConstant.SFTP_BACKUP_STORAGE_TYPE, new SftpBackupStorageMediator());
backupStorageMediators.put(CephConstants.CEPH_BACKUP_STORAGE_TYPE, new CephBackupStorageMediator());
List<PrimaryStorageToBackupStorageMediatorExtensionPoint> exts = pluginRgty.getExtensionList(PrimaryStorageToBackupStorageMediatorExtensionPoint.class);
exts.forEach(ext -> backupStorageMediators.putAll(ext.getBackupStorageMediators()));
}
class UploadParam implements MediatorParam {
ImageInventory image;
String primaryStorageInstallPath;
String backupStorageInstallPath;
}
class SftpBackupStorageMediator extends BackupStorageMediator {
private void getSftpCredentials(final ReturnValueCompletion<GetSftpBackupStorageDownloadCredentialReply> completion) {
GetSftpBackupStorageDownloadCredentialMsg gmsg = new GetSftpBackupStorageDownloadCredentialMsg();
gmsg.setBackupStorageUuid(backupStorage.getUuid());
bus.makeTargetServiceIdByResourceUuid(gmsg, BackupStorageConstant.SERVICE_ID, backupStorage.getUuid());
bus.send(gmsg, new CloudBusCallBack(completion) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
completion.fail(reply.getError());
} else {
completion.success((GetSftpBackupStorageDownloadCredentialReply) reply);
}
}
});
}
@Override
public void download(final ReturnValueCompletion<String> completion) {
checkParam();
final MediatorDowloadParam dparam = (MediatorDowloadParam) param;
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("download-image-from-sftp-%s-to-ceph-%s", backupStorage.getUuid(), dparam.getPrimaryStorageUuid()));
chain.then(new ShareFlow() {
String sshkey;
int sshport;
String sftpHostname;
String username;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "get-sftp-credentials";
@Override
public void run(final FlowTrigger trigger, Map data) {
getSftpCredentials(new ReturnValueCompletion<GetSftpBackupStorageDownloadCredentialReply>(trigger) {
@Override
public void success(GetSftpBackupStorageDownloadCredentialReply greply) {
sshkey = greply.getSshKey();
sshport = greply.getSshPort();
sftpHostname = greply.getHostname();
username = greply.getUsername();
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "download-image";
@Override
public void run(final FlowTrigger trigger, Map data) {
SftpDownloadCmd cmd = new SftpDownloadCmd();
cmd.backupStorageInstallPath = dparam.getImage().getSelectedBackupStorage().getInstallPath();
cmd.hostname = sftpHostname;
cmd.username = username;
cmd.sshKey = sshkey;
cmd.sshPort = sshport;
cmd.primaryStorageInstallPath = dparam.getInstallPath();
httpCall(SFTP_DOWNLOAD_PATH, cmd, SftpDownloadRsp.class, new ReturnValueCompletion<SftpDownloadRsp>(trigger) {
@Override
public void success(SftpDownloadRsp returnValue) {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
completion.success(dparam.getInstallPath());
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
@Override
public void upload(final ReturnValueCompletion<String> completion) {
checkParam();
final UploadParam uparam = (UploadParam) param;
final TaskProgressRange parentStage = getTaskStage();
final TaskProgressRange PREPARATION_STAGE = new TaskProgressRange(0, 10);
final TaskProgressRange UPLOAD_STAGE = new TaskProgressRange(10, 100);
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("upload-image-ceph-%s-to-sftp-%s", self.getUuid(), backupStorage.getUuid()));
chain.then(new ShareFlow() {
String sshKey;
String hostname;
String username;
int sshPort;
String backupStorageInstallPath;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "get-sftp-credentials";
@Override
public void run(final FlowTrigger trigger, Map data) {
getSftpCredentials(new ReturnValueCompletion<GetSftpBackupStorageDownloadCredentialReply>(trigger) {
@Override
public void success(GetSftpBackupStorageDownloadCredentialReply returnValue) {
sshKey = returnValue.getSshKey();
hostname = returnValue.getHostname();
username = returnValue.getUsername();
sshPort = returnValue.getSshPort();
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "get-backup-storage-install-path";
@Override
public void run(final FlowTrigger trigger, Map data) {
TaskProgressRange stage = markTaskStage(parentStage, PREPARATION_STAGE);
BackupStorageAskInstallPathMsg msg = new BackupStorageAskInstallPathMsg();
msg.setBackupStorageUuid(backupStorage.getUuid());
msg.setImageUuid(uparam.image.getUuid());
msg.setImageMediaType(uparam.image.getMediaType());
bus.makeTargetServiceIdByResourceUuid(msg, BackupStorageConstant.SERVICE_ID, backupStorage.getUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
} else {
backupStorageInstallPath = ((BackupStorageAskInstallPathReply) reply).getInstallPath();
reportProgress(stage.getEnd().toString());
trigger.next();
}
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "upload-to-backup-storage";
@Override
public void run(final FlowTrigger trigger, Map data) {
TaskProgressRange stage = markTaskStage(parentStage, UPLOAD_STAGE);
SftpUpLoadCmd cmd = new SftpUpLoadCmd();
cmd.setSendCommandUrl(restf.getSendCommandUrl());
cmd.setBackupStorageInstallPath(backupStorageInstallPath);
cmd.setHostname(hostname);
cmd.setUsername(username);
cmd.setSshKey(sshKey);
cmd.setSshPort(sshPort);
cmd.setPrimaryStorageInstallPath(uparam.primaryStorageInstallPath);
httpCall(SFTP_UPLOAD_PATH, cmd, SftpUploadRsp.class, new ReturnValueCompletion<SftpUploadRsp>(trigger) {
@Override
public void success(SftpUploadRsp returnValue) {
reportProgress(stage.getEnd().toString());
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
reportProgress(parentStage.getEnd().toString());
completion.success(backupStorageInstallPath);
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
@Override
public boolean deleteWhenRollbackDownload() {
return true;
}
}
class CephBackupStorageMediator extends BackupStorageMediator {
public void checkParam() {
super.checkParam();
SimpleQuery<CephBackupStorageVO> q = dbf.createQuery(CephBackupStorageVO.class);
q.select(CephBackupStorageVO_.fsid);
q.add(CephBackupStorageVO_.uuid, Op.EQ, backupStorage.getUuid());
String bsFsid = q.findValue();
if (!getSelf().getFsid().equals(bsFsid)) {
throw new OperationFailureException(operr(
"the backup storage[uuid:%s, name:%s, fsid:%s] is not in the same ceph cluster" +
" with the primary storage[uuid:%s, name:%s, fsid:%s]", backupStorage.getUuid(),
backupStorage.getName(), bsFsid, self.getUuid(), self.getName(), getSelf().getFsid())
);
}
}
@Override
public void download(final ReturnValueCompletion<String> completion) {
checkParam();
final MediatorDowloadParam dparam = (MediatorDowloadParam) param;
if (ImageMediaType.DataVolumeTemplate.toString().equals(dparam.getImage().getInventory().getMediaType())) {
CpCmd cmd = new CpCmd();
cmd.srcPath = dparam.getImage().getSelectedBackupStorage().getInstallPath();
cmd.dstPath = dparam.getInstallPath();
httpCall(CP_PATH, cmd, CpRsp.class, new ReturnValueCompletion<CpRsp>(completion) {
@Override
public void success(CpRsp returnValue) {
completion.success(dparam.getInstallPath());
}
@Override
public void fail(ErrorCode errorCode) {
completion.fail(errorCode);
}
});
} else {
completion.success(dparam.getImage().getSelectedBackupStorage().getInstallPath());
}
}
@Override
public void upload(final ReturnValueCompletion<String> completion) {
checkParam();
final UploadParam uparam = (UploadParam) param;
final TaskProgressRange parentStage = getTaskStage();
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("upload-image-ceph-%s-to-ceph-%s", self.getUuid(), backupStorage.getUuid()));
chain.then(new ShareFlow() {
String backupStorageInstallPath;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "get-backup-storage-install-path";
@Override
public void run(final FlowTrigger trigger, Map data) {
BackupStorageAskInstallPathMsg msg = new BackupStorageAskInstallPathMsg();
msg.setBackupStorageUuid(backupStorage.getUuid());
msg.setImageUuid(uparam.image.getUuid());
msg.setImageMediaType(uparam.image.getMediaType());
bus.makeTargetServiceIdByResourceUuid(msg, BackupStorageConstant.SERVICE_ID, backupStorage.getUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
} else {
backupStorageInstallPath = ((BackupStorageAskInstallPathReply) reply).getInstallPath();
trigger.next();
}
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "cp-to-the-image";
@Override
public void run(final FlowTrigger trigger, Map data) {
CpCmd cmd = new CpCmd();
cmd.sendCommandUrl = restf.getSendCommandUrl();
cmd.srcPath = uparam.primaryStorageInstallPath;
cmd.dstPath = backupStorageInstallPath;
httpCall(CP_PATH, cmd, CpRsp.class, new ReturnValueCompletion<CpRsp>(trigger) {
@Override
public void success(CpRsp returnValue) {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
reportProgress(parentStage.getEnd().toString());
completion.success(backupStorageInstallPath);
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
@Override
public boolean deleteWhenRollbackDownload() {
return false;
}
}
private BackupStorageMediator getBackupStorageMediator(String bsUuid) {
BackupStorageVO bsvo = dbf.findByUuid(bsUuid, BackupStorageVO.class);
BackupStorageMediator mediator = backupStorageMediators.get(bsvo.getType());
if (mediator == null) {
throw new CloudRuntimeException(String.format("cannot find BackupStorageMediator for type[%s]", bsvo.getType()));
}
mediator.backupStorage = BackupStorageInventory.valueOf(bsvo);
return mediator;
}
private String makeRootVolumeInstallPath(String volUuid) {
String poolName = CephSystemTags.USE_CEPH_ROOT_POOL.getTokenByResourceUuid(volUuid, CephSystemTags.USE_CEPH_ROOT_POOL_TOKEN);
return String.format("ceph://%s/%s",getPoolName(poolName, getDefaultRootVolumePoolName()), volUuid);
}
private String makeResetImageRootVolumeInstallPath(String volUuid) {
return String.format("ceph://%s/reset-image-%s-%s",
getDefaultRootVolumePoolName(),
volUuid,
System.currentTimeMillis());
}
private String makeDataVolumeInstallPath(String volUuid) {
String poolName = CephSystemTags.USE_CEPH_PRIMARY_STORAGE_POOL.getTokenByResourceUuid(volUuid, CephSystemTags.USE_CEPH_PRIMARY_STORAGE_POOL_TOKEN);
return String.format("ceph://%s/%s",getPoolName(poolName, getDefaultDataVolumePoolName()), volUuid);
}
private String getPoolName(String customPoolName, String defaultPoolName){
return customPoolName != null ? customPoolName : defaultPoolName;
}
private String makeCacheInstallPath(String uuid) {
return String.format("ceph://%s/%s",
getDefaultImageCachePoolName(),
uuid);
}
public CephPrimaryStorageBase(PrimaryStorageVO self) {
super(self);
}
protected CephPrimaryStorageVO getSelf() {
return (CephPrimaryStorageVO) self;
}
private String getDefaultImageCachePoolName() {
return CephSystemTags.DEFAULT_CEPH_PRIMARY_STORAGE_IMAGE_CACHE_POOL.getTokenByResourceUuid(self.getUuid(), CephSystemTags.DEFAULT_CEPH_PRIMARY_STORAGE_IMAGE_CACHE_POOL_TOKEN);
}
private String getDefaultDataVolumePoolName() {
return CephSystemTags.DEFAULT_CEPH_PRIMARY_STORAGE_DATA_VOLUME_POOL.getTokenByResourceUuid(self.getUuid(), CephSystemTags.DEFAULT_CEPH_PRIMARY_STORAGE_DATA_VOLUME_POOL_TOKEN);
}
private String getDefaultRootVolumePoolName() {
return CephSystemTags.DEFAULT_CEPH_PRIMARY_STORAGE_ROOT_VOLUME_POOL.getTokenByResourceUuid(self.getUuid(), CephSystemTags.DEFAULT_CEPH_PRIMARY_STORAGE_ROOT_VOLUME_POOL_TOKEN);
}
protected CephPrimaryStorageInventory getSelfInventory() {
return CephPrimaryStorageInventory.valueOf(getSelf());
}
private void createEmptyVolume(final InstantiateVolumeOnPrimaryStorageMsg msg) {
final CreateEmptyVolumeCmd cmd = new CreateEmptyVolumeCmd();
if (VolumeType.Root.toString().equals(msg.getVolume().getType())) {
cmd.installPath = makeRootVolumeInstallPath(msg.getVolume().getUuid());
} else {
cmd.installPath = makeDataVolumeInstallPath(msg.getVolume().getUuid());
}
cmd.size = msg.getVolume().getSize();
cmd.setShareable(msg.getVolume().isShareable());
cmd.skipIfExisting = msg.isSkipIfExisting();
final InstantiateVolumeOnPrimaryStorageReply reply = new InstantiateVolumeOnPrimaryStorageReply();
httpCall(CREATE_VOLUME_PATH, cmd, CreateEmptyVolumeRsp.class, new ReturnValueCompletion<CreateEmptyVolumeRsp>(msg) {
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
}
@Override
public void success(CreateEmptyVolumeRsp ret) {
VolumeInventory vol = msg.getVolume();
vol.setInstallPath(cmd.getInstallPath());
vol.setFormat(VolumeConstant.VOLUME_FORMAT_RAW);
reply.setVolume(vol);
bus.reply(msg, reply);
}
});
}
private void cleanTrash(Long trashId, final ReturnValueCompletion<CleanTrashResult> completion) {
CleanTrashResult result = new CleanTrashResult();
StorageTrashSpec spec = trash.getTrash(self.getUuid(), trashId);
if (spec == null) {
completion.success(result);
return;
}
if (!trash.makeSureInstallPathNotUsed(spec)) {
logger.warn(String.format("%s is still in using by %s, only remove it from trash...", spec.getInstallPath(), spec.getResourceType()));
trash.removeFromDb(spec.getTrashId());
completion.success(result);
return;
}
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("clean-trash-on-volume-%s", spec.getInstallPath()));
chain.then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
PurgeSnapshotOnPrimaryStorageMsg msg = new PurgeSnapshotOnPrimaryStorageMsg();
msg.setPrimaryStorageUuid(self.getUuid());
msg.setVolumePath(spec.getInstallPath());
bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, self.getUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
logger.info(String.format("Purged all snapshots of volume %s.", spec.getInstallPath()));
} else {
logger.warn(String.format("Failed to purge snapshots of volume %s.", spec.getInstallPath()));
}
trigger.next();
}
});
}
}).then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
DeleteVolumeBitsOnPrimaryStorageMsg msg = new DeleteVolumeBitsOnPrimaryStorageMsg();
msg.setPrimaryStorageUuid(self.getUuid());
msg.setInstallPath(spec.getInstallPath());
bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, self.getUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
logger.info(String.format("Deleted volume %s in Trash.", spec.getInstallPath()));
} else {
logger.warn(String.format("Failed to delete volume %s in Trash.", spec.getInstallPath()));
}
trigger.next();
}
});
}
});
chain.done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
IncreasePrimaryStorageCapacityMsg imsg = new IncreasePrimaryStorageCapacityMsg();
imsg.setPrimaryStorageUuid(self.getUuid());
imsg.setDiskSize(spec.getSize());
bus.makeTargetServiceIdByResourceUuid(imsg, PrimaryStorageConstant.SERVICE_ID, self.getUuid());
bus.send(imsg);
logger.info(String.format("Returned space[size:%s] to PS %s after volume migration", spec.getSize(), self.getUuid()));
trash.removeFromDb(trashId);
result.setSize(spec.getSize());
result.setResourceUuids(CollectionDSL.list(spec.getResourceUuid()));
completion.success(result);
}
}).error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
}).start();
}
private void cleanUpTrash(Long trashId, final ReturnValueCompletion<CleanTrashResult> completion) {
if (trashId != null) {
cleanTrash(trashId, completion);
return;
}
CleanTrashResult result = new CleanTrashResult();
Map<String, StorageTrashSpec> trashs = trash.getTrashList(self.getUuid(), trashLists);
if (trashs.isEmpty()) {
completion.success(result);
return;
}
ErrorCodeList errorCodeList = new ErrorCodeList();
new While<>(trashs.entrySet()).all((t, coml) -> {
StorageTrashSpec spec = t.getValue();
if (!trash.makeSureInstallPathNotUsed(spec)) {
logger.warn(String.format("%s is still in using by %s, only remove it from trash...", spec.getInstallPath(), spec.getResourceType()));
trash.removeFromDb(spec.getTrashId());
coml.done();
return;
}
FlowChain chain = FlowChainBuilder.newSimpleFlowChain();
chain.setName(String.format("clean-trash-on-volume-%s", spec.getInstallPath()));
chain.then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
PurgeSnapshotOnPrimaryStorageMsg msg = new PurgeSnapshotOnPrimaryStorageMsg();
msg.setPrimaryStorageUuid(self.getUuid());
msg.setVolumePath(spec.getInstallPath());
bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, self.getUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
logger.info(String.format("Purged all snapshots of volume %s.", spec.getInstallPath()));
} else {
logger.warn(String.format("Failed to purge snapshots of volume %s.", spec.getInstallPath()));
}
trigger.next();
}
});
}
}).then(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
DeleteVolumeBitsOnPrimaryStorageMsg msg = new DeleteVolumeBitsOnPrimaryStorageMsg();
msg.setPrimaryStorageUuid(self.getUuid());
msg.setInstallPath(spec.getInstallPath());
bus.makeTargetServiceIdByResourceUuid(msg, PrimaryStorageConstant.SERVICE_ID, self.getUuid());
bus.send(msg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (reply.isSuccess()) {
logger.info(String.format("Deleted volume %s in Trash.", spec.getInstallPath()));
} else {
logger.warn(String.format("Failed to delete volume %s in Trash.", spec.getInstallPath()));
}
trigger.next();
}
});
}
});
chain.done(new FlowDoneHandler(coml) {
@Override
public void handle(Map data) {
IncreasePrimaryStorageCapacityMsg imsg = new IncreasePrimaryStorageCapacityMsg();
imsg.setPrimaryStorageUuid(self.getUuid());
imsg.setDiskSize(spec.getSize());
bus.makeTargetServiceIdByResourceUuid(imsg, PrimaryStorageConstant.SERVICE_ID, self.getUuid());
bus.send(imsg);
logger.info(String.format("Returned space[size:%s] to PS %s after volume migration", spec.getSize(), self.getUuid()));
result.getResourceUuids().add(spec.getResourceUuid());
updateTrashSize(result, spec.getSize());
trash.removeFromDb(t.getKey(), self.getUuid());
coml.done();
}
}).error(new FlowErrorHandler(coml) {
@Override
public void handle(ErrorCode errCode, Map data) {
errorCodeList.getCauses().add(errCode);
coml.done();
}
}).start();
}).run(new NoErrorCompletion() {
@Override
public void done() {
if (errorCodeList.getCauses().isEmpty()) {
completion.success(result);
} else {
completion.fail(errorCodeList.getCauses().get(0));
}
}
});
}
protected void handle(final CleanUpTrashOnPrimaryStroageMsg msg) {
MessageReply reply = new MessageReply();
thdf.chainSubmit(new ChainTask(msg) {
private String name = String.format("cleanup-trash-on-%s", self.getUuid());
@Override
public String getSyncSignature() {
return name;
}
@Override
public void run(SyncTaskChain chain) {
cleanUpTrash(msg.getTrashId(), new ReturnValueCompletion<CleanTrashResult>(msg) {
@Override
public void success(CleanTrashResult returnValue) {
bus.reply(msg, reply);
chain.next();
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
chain.next();
}
});
}
@Override
public String getName() {
return name;
}
});
}
@Override
protected void handle(final APICleanUpTrashOnPrimaryStorageMsg msg) {
APICleanUpTrashOnPrimaryStorageEvent evt = new APICleanUpTrashOnPrimaryStorageEvent(msg.getId());
thdf.chainSubmit(new ChainTask(msg) {
private String name = String.format("cleanup-trash-on-%s", self.getUuid());
@Override
public String getSyncSignature() {
return name;
}
@Override
public void run(SyncTaskChain chain) {
cleanUpTrash(msg.getTrashId(), new ReturnValueCompletion<CleanTrashResult>(chain) {
@Override
public void success(CleanTrashResult result) {
evt.setResult(result);
bus.publish(evt);
chain.next();
}
@Override
public void fail(ErrorCode errorCode) {
evt.setError(errorCode);
bus.publish(evt);
chain.next();
}
});
}
@Override
public String getName() {
return name;
}
});
}
@Override
protected void handle(APICleanUpImageCacheOnPrimaryStorageMsg msg) {
APICleanUpImageCacheOnPrimaryStorageEvent evt = new APICleanUpImageCacheOnPrimaryStorageEvent(msg.getId());
imageCacheCleaner.cleanup(msg.getUuid());
bus.publish(evt);
}
@Override
protected void handle(final InstantiateVolumeOnPrimaryStorageMsg msg) {
if (msg instanceof InstantiateRootVolumeFromTemplateOnPrimaryStorageMsg) {
createVolumeFromTemplate((InstantiateRootVolumeFromTemplateOnPrimaryStorageMsg) msg);
} else {
createEmptyVolume(msg);
}
}
class DownloadToCache {
ImageSpec image;
private void doDownload(final ReturnValueCompletion<ImageCacheVO> completion) {
ImageCacheVO cache = Q.New(ImageCacheVO.class)
.eq(ImageCacheVO_.primaryStorageUuid, self.getUuid())
.eq(ImageCacheVO_.imageUuid, image.getInventory().getUuid())
.find();
if (cache != null) {
completion.success(cache);
return;
}
final FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("prepare-image-cache-ceph-%s", self.getUuid()));
chain.then(new ShareFlow() {
String cachePath;
String snapshotPath;
@Override
public void setup() {
flow(new Flow() {
String __name__ = "allocate-primary-storage-capacity-for-image-cache";
boolean s = false;
@Override
public void run(final FlowTrigger trigger, Map data) {
AllocatePrimaryStorageMsg amsg = new AllocatePrimaryStorageMsg();
amsg.setRequiredPrimaryStorageUuid(self.getUuid());
amsg.setSize(image.getInventory().getActualSize());
amsg.setPurpose(PrimaryStorageAllocationPurpose.DownloadImage.toString());
amsg.setImageUuid(image.getInventory().getUuid());
amsg.setNoOverProvisioning(true);
bus.makeLocalServiceId(amsg, PrimaryStorageConstant.SERVICE_ID);
bus.send(amsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
} else {
s = true;
trigger.next();
}
}
});
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (s) {
IncreasePrimaryStorageCapacityMsg imsg = new IncreasePrimaryStorageCapacityMsg();
imsg.setNoOverProvisioning(true);
imsg.setPrimaryStorageUuid(self.getUuid());
imsg.setDiskSize(image.getInventory().getActualSize());
bus.makeLocalServiceId(imsg, PrimaryStorageConstant.SERVICE_ID);
bus.send(imsg);
}
trigger.rollback();
}
});
flow(new Flow() {
String __name__ = "download-from-backup-storage";
boolean deleteOnRollback;
@Override
public void run(final FlowTrigger trigger, Map data) {
MediatorDowloadParam param = new MediatorDowloadParam();
param.setImage(image);
param.setInstallPath(makeCacheInstallPath(image.getInventory().getUuid()));
param.setPrimaryStorageUuid(self.getUuid());
BackupStorageMediator mediator = getBackupStorageMediator(image.getSelectedBackupStorage().getBackupStorageUuid());
mediator.param = param;
deleteOnRollback = mediator.deleteWhenRollbackDownload();
mediator.download(new ReturnValueCompletion<String>(trigger) {
@Override
public void success(String path) {
cachePath = path;
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (deleteOnRollback && cachePath != null) {
DeleteCmd cmd = new DeleteCmd();
cmd.installPath = cachePath;
httpCall(DELETE_PATH, cmd, DeleteRsp.class, new ReturnValueCompletion<DeleteRsp>(null) {
@Override
public void success(DeleteRsp returnValue) {
logger.debug(String.format("successfully deleted %s", cachePath));
}
@Override
public void fail(ErrorCode errorCode) {
//TODO GC
logger.warn(String.format("unable to delete %s, %s. Need a cleanup", cachePath, errorCode));
}
});
}
trigger.rollback();
}
});
flow(new Flow() {
String __name__ = "create-snapshot";
boolean needCleanup = false;
@Override
public void run(final FlowTrigger trigger, Map data) {
snapshotPath = String.format("%s@%s", cachePath, image.getInventory().getUuid());
CreateSnapshotCmd cmd = new CreateSnapshotCmd();
cmd.skipOnExisting = true;
cmd.snapshotPath = snapshotPath;
httpCall(CREATE_SNAPSHOT_PATH, cmd, CreateSnapshotRsp.class, new ReturnValueCompletion<CreateSnapshotRsp>(trigger) {
@Override
public void success(CreateSnapshotRsp returnValue) {
needCleanup = true;
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
@Override
public void rollback(FlowRollback trigger, Map data) {
if (needCleanup) {
DeleteSnapshotCmd cmd = new DeleteSnapshotCmd();
cmd.snapshotPath = snapshotPath;
httpCall(DELETE_SNAPSHOT_PATH, cmd, DeleteSnapshotRsp.class, new ReturnValueCompletion<DeleteSnapshotRsp>(null) {
@Override
public void success(DeleteSnapshotRsp returnValue) {
logger.debug(String.format("successfully deleted the snapshot %s", snapshotPath));
}
@Override
public void fail(ErrorCode errorCode) {
//TODO
logger.warn(String.format("unable to delete the snapshot %s, %s. Need a cleanup", snapshotPath, errorCode));
}
});
}
trigger.rollback();
}
});
flow(new NoRollbackFlow() {
String __name__ = "protect-snapshot";
@Override
public void run(final FlowTrigger trigger, Map data) {
ProtectSnapshotCmd cmd = new ProtectSnapshotCmd();
cmd.snapshotPath = snapshotPath;
cmd.ignoreError = true;
httpCall(PROTECT_SNAPSHOT_PATH, cmd, ProtectSnapshotRsp.class, new ReturnValueCompletion<ProtectSnapshotRsp>(trigger) {
@Override
public void success(ProtectSnapshotRsp returnValue) {
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
ImageCacheVO cvo = new ImageCacheVO();
cvo.setMd5sum("not calculated");
cvo.setSize(image.getInventory().getActualSize());
cvo.setInstallUrl(snapshotPath);
cvo.setImageUuid(image.getInventory().getUuid());
cvo.setPrimaryStorageUuid(self.getUuid());
cvo.setMediaType(ImageMediaType.valueOf(image.getInventory().getMediaType()));
cvo.setState(ImageCacheState.ready);
cvo = dbf.persistAndRefresh(cvo);
completion.success(cvo);
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
completion.fail(errCode);
}
});
}
}).start();
}
void download(final ReturnValueCompletion<ImageCacheVO> completion) {
thdf.chainSubmit(new ChainTask(completion) {
@Override
public String getSyncSignature() {
return String.format("ceph-p-%s-download-image-%s", self.getUuid(), image.getInventory().getUuid());
}
@Override
public void run(final SyncTaskChain chain) {
ImageCacheVO cache = Q.New(ImageCacheVO.class)
.eq(ImageCacheVO_.primaryStorageUuid, self.getUuid())
.eq(ImageCacheVO_.imageUuid, image.getInventory().getUuid())
.find();
if (cache != null ){
final CheckIsBitsExistingCmd cmd = new CheckIsBitsExistingCmd();
cmd.setInstallPath(cache.getInstallUrl());
httpCall(CHECK_BITS_PATH, cmd, CheckIsBitsExistingRsp.class, new ReturnValueCompletion<CheckIsBitsExistingRsp>(chain) {
@Override
public void success(CheckIsBitsExistingRsp returnValue) {
if(returnValue.isExisting()) {
logger.debug("image has been existing");
completion.success(cache);
chain.next();
}else{
logger.debug("image not found, remove vo and re-download");
SimpleQuery<ImageCacheVO> q = dbf.createQuery(ImageCacheVO.class);
q.add(ImageCacheVO_.primaryStorageUuid, Op.EQ, self.getUuid());
q.add(ImageCacheVO_.imageUuid, Op.EQ, image.getInventory().getUuid());
ImageCacheVO cvo = q.find();
IncreasePrimaryStorageCapacityMsg imsg = new IncreasePrimaryStorageCapacityMsg();
imsg.setDiskSize(cvo.getSize());
imsg.setPrimaryStorageUuid(cvo.getPrimaryStorageUuid());
bus.makeTargetServiceIdByResourceUuid(imsg, PrimaryStorageConstant.SERVICE_ID, cvo.getPrimaryStorageUuid());
bus.send(imsg);
dbf.remove(cvo);
doDownload(new ReturnValueCompletion<ImageCacheVO>(chain) {
@Override
public void success(ImageCacheVO returnValue) {
completion.success(returnValue);
chain.next();
}
@Override
public void fail(ErrorCode errorCode) {
completion.fail(errorCode);
chain.next();
}
});
}
}
@Override
public void fail(ErrorCode errorCode) {
completion.fail(errorCode);
}
});
}else{
doDownload(new ReturnValueCompletion<ImageCacheVO>(chain) {
@Override
public void success(ImageCacheVO returnValue) {
completion.success(returnValue);
chain.next();
}
@Override
public void fail(ErrorCode errorCode) {
completion.fail(errorCode);
chain.next();
}
});
}
}
@Override
public String getName() {
return getSyncSignature();
}
});
}
}
private void createVolumeFromTemplate(final InstantiateRootVolumeFromTemplateOnPrimaryStorageMsg msg) {
final InstantiateVolumeOnPrimaryStorageReply reply = new InstantiateVolumeOnPrimaryStorageReply();
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("create-root-volume-%s", msg.getVolume().getUuid()));
chain.then(new ShareFlow() {
String cloneInstallPath;
String volumePath = makeRootVolumeInstallPath(msg.getVolume().getUuid());
ImageCacheInventory cache;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "download-image-to-cache";
@Override
public void run(final FlowTrigger trigger, Map data) {
DownloadVolumeTemplateToPrimaryStorageMsg dmsg = new DownloadVolumeTemplateToPrimaryStorageMsg();
dmsg.setPrimaryStorageUuid(msg.getPrimaryStorageUuid());
dmsg.setHostUuid(msg.getDestHost().getUuid());
dmsg.setTemplateSpec(msg.getTemplateSpec());
bus.makeTargetServiceIdByResourceUuid(dmsg, PrimaryStorageConstant.SERVICE_ID, dmsg.getPrimaryStorageUuid());
bus.send(dmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
return;
}
cache = ((DownloadVolumeTemplateToPrimaryStorageReply) reply).getImageCache();
cloneInstallPath = cache.getInstallUrl();
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "clone-image";
@Override
public void run(final FlowTrigger trigger, Map data) {
CloneCmd cmd = new CloneCmd();
cmd.srcPath = cloneInstallPath;
cmd.dstPath = volumePath;
httpCall(CLONE_PATH, cmd, CloneRsp.class, new ReturnValueCompletion<CloneRsp>(trigger) {
@Override
public void fail(ErrorCode err) {
trigger.fail(err);
}
@Override
public void success(CloneRsp ret) {
trigger.next();
}
});
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
VolumeInventory vol = msg.getVolume();
vol.setInstallPath(volumePath);
vol.setFormat(VolumeConstant.VOLUME_FORMAT_RAW);
reply.setVolume(vol);
ImageCacheVolumeRefVO ref = new ImageCacheVolumeRefVO();
ref.setImageCacheId(cache.getId());
ref.setPrimaryStorageUuid(self.getUuid());
ref.setVolumeUuid(vol.getUuid());
dbf.persist(ref);
bus.reply(msg, reply);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
reply.setError(errCode);
bus.reply(msg, reply);
}
});
}
}).start();
}
@Override
protected void handle(final DeleteVolumeOnPrimaryStorageMsg msg) {
DeleteCmd cmd = new DeleteCmd();
cmd.installPath = msg.getVolume().getInstallPath();
final DeleteVolumeOnPrimaryStorageReply reply = new DeleteVolumeOnPrimaryStorageReply();
httpCall(DELETE_PATH, cmd, DeleteRsp.class, new ReturnValueCompletion<DeleteRsp>(msg) {
@Override
public void fail(ErrorCode err) {
CephDeleteVolumeGC gc = new CephDeleteVolumeGC();
gc.NAME = String.format("gc-ceph-%s-volume-%s", self.getUuid(), msg.getVolume());
gc.primaryStorageUuid = self.getUuid();
gc.volume = msg.getVolume();
gc.submit(CephGlobalConfig.GC_INTERVAL.value(Long.class), TimeUnit.SECONDS);
bus.reply(msg, reply);
}
@Override
public void success(DeleteRsp ret) {
bus.reply(msg, reply);
}
});
}
@Override
protected void handle(final GetPrimaryStorageFolderListMsg msg) {
GetPrimaryStorageFolderListReply reply = new GetPrimaryStorageFolderListReply();
bus.reply(msg, reply);
}
@Override
protected void handle(DownloadVolumeTemplateToPrimaryStorageMsg msg) {
final DownloadVolumeTemplateToPrimaryStorageReply reply = new DownloadVolumeTemplateToPrimaryStorageReply();
DownloadToCache downloadToCache = new DownloadToCache();
downloadToCache.image = msg.getTemplateSpec();
downloadToCache.download(new ReturnValueCompletion<ImageCacheVO>(msg) {
@Override
public void success(ImageCacheVO cache) {
reply.setImageCache(ImageCacheInventory.valueOf(cache));
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
@Override
protected void handle(final DeleteBitsOnPrimaryStorageMsg msg) {
DeleteCmd cmd = new DeleteCmd();
cmd.installPath = msg.getInstallPath();
final DeleteBitsOnPrimaryStorageReply reply = new DeleteBitsOnPrimaryStorageReply();
httpCall(DELETE_PATH, cmd, DeleteRsp.class, new ReturnValueCompletion<DeleteRsp>(msg) {
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
}
@Override
public void success(DeleteRsp ret) {
bus.reply(msg, reply);
}
});
}
private void checkCephFsId(String psUuid, String bsUuid) {
CephPrimaryStorageVO cephPS = dbf.findByUuid(psUuid, CephPrimaryStorageVO.class);
DebugUtils.Assert(cephPS != null && cephPS.getFsid() != null, String.format("ceph ps: [%s] and its fsid cannot be null", psUuid));
CephBackupStorageVO cephBS = dbf.findByUuid(bsUuid, CephBackupStorageVO.class);
if (cephBS != null) {
DebugUtils.Assert(cephBS.getFsid() != null, String.format("fsid cannot be null in ceph bs:[%s]", bsUuid));
if (!cephPS.getFsid().equals(cephBS.getFsid())) {
throw new OperationFailureException(operr(
"fsid is not same between ps[%s] and bs[%s], create template is forbidden.", psUuid, bsUuid));
}
}
}
@Override
protected void handle(final CreateTemplateFromVolumeOnPrimaryStorageMsg msg) {
final CreateTemplateFromVolumeOnPrimaryStorageReply reply = new CreateTemplateFromVolumeOnPrimaryStorageReply();
final TaskProgressRange parentStage = getTaskStage();
final TaskProgressRange CREATE_SNAPSHOT_STAGE = new TaskProgressRange(0, 10);
final TaskProgressRange CREATE_IMAGE_STAGE = new TaskProgressRange(10, 100);
checkCephFsId(msg.getPrimaryStorageUuid(), msg.getBackupStorageUuid());
String volumeUuid = msg.getVolumeInventory().getUuid();
String imageUuid = msg.getImageInventory().getUuid();
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("create-snapshot-and-image-from-volume-%s", volumeUuid));
chain.then(new ShareFlow() {
VolumeSnapshotInventory snapshot;
CreateTemplateFromVolumeSnapshotReply imageReply;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "create-volume-snapshot";
@Override
public void run(final FlowTrigger trigger, Map data) {
String volumeAccountUuid = acntMgr.getOwnerAccountUuidOfResource(volumeUuid);
TaskProgressRange stage = markTaskStage(parentStage, CREATE_SNAPSHOT_STAGE);
// 1. create snapshot
CreateVolumeSnapshotMsg cmsg = new CreateVolumeSnapshotMsg();
cmsg.setName("Snapshot-" + volumeUuid);
cmsg.setDescription("Take snapshot for " + volumeUuid);
cmsg.setVolumeUuid(volumeUuid);
cmsg.setAccountUuid(volumeAccountUuid);
bus.makeLocalServiceId(cmsg, VolumeSnapshotConstant.SERVICE_ID);
bus.send(cmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply r) {
if (!r.isSuccess()) {
trigger.fail(r.getError());
return;
}
CreateVolumeSnapshotReply createVolumeSnapshotReply = (CreateVolumeSnapshotReply)r;
snapshot = createVolumeSnapshotReply.getInventory();
reportProgress(stage.getEnd().toString());
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "create-template-from-volume-snapshot";
@Override
public void run(final FlowTrigger trigger, Map data) {
// 2.create image
TaskProgressRange stage = markTaskStage(parentStage, CREATE_IMAGE_STAGE);
VolumeSnapshotVO vo = dbf.findByUuid(snapshot.getUuid(), VolumeSnapshotVO.class);
String treeUuid = vo.getTreeUuid();
CreateTemplateFromVolumeSnapshotMsg cmsg = new CreateTemplateFromVolumeSnapshotMsg();
cmsg.setSnapshotUuid(snapshot.getUuid());
cmsg.setImageUuid(imageUuid);
cmsg.setVolumeUuid(snapshot.getVolumeUuid());
cmsg.setTreeUuid(treeUuid);
cmsg.setBackupStorageUuid(msg.getBackupStorageUuid());
String resourceUuid = volumeUuid != null ? volumeUuid : treeUuid;
bus.makeTargetServiceIdByResourceUuid(cmsg, VolumeSnapshotConstant.SERVICE_ID, resourceUuid);
bus.send(cmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply r) {
if (!r.isSuccess()) {
trigger.fail(r.getError());
return;
}
imageReply = (CreateTemplateFromVolumeSnapshotReply)r;
reportProgress(stage.getEnd().toString());
trigger.next();
}
});
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
logger.warn(String.format("successfully create template[uuid:%s] from volume[uuid:%s]", imageUuid, volumeUuid));
reply.setTemplateBackupStorageInstallPath(imageReply.getBackupStorageInstallPath());
reply.setFormat(snapshot.getFormat());
bus.reply(msg, reply);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
logger.warn(String.format("failed to create template from volume[uuid:%s], because %s", volumeUuid, errCode));
reply.setError(errCode);
bus.reply(msg, reply);
}
});
}
}).start();
}
@Override
protected void handle(final DownloadDataVolumeToPrimaryStorageMsg msg) {
final DownloadDataVolumeToPrimaryStorageReply reply = new DownloadDataVolumeToPrimaryStorageReply();
BackupStorageMediator mediator = getBackupStorageMediator(msg.getBackupStorageRef().getBackupStorageUuid());
ImageSpec spec = new ImageSpec();
spec.setInventory(msg.getImage());
spec.setSelectedBackupStorage(msg.getBackupStorageRef());
MediatorDowloadParam param = new MediatorDowloadParam();
param.setImage(spec);
param.setInstallPath(makeDataVolumeInstallPath(msg.getVolumeUuid()));
param.setPrimaryStorageUuid(self.getUuid());
mediator.param = param;
mediator.download(new ReturnValueCompletion<String>(msg) {
@Override
public void success(String returnValue) {
reply.setInstallPath(returnValue);
reply.setFormat(VolumeConstant.VOLUME_FORMAT_RAW);
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
@Override
protected void handle(GetInstallPathForDataVolumeDownloadMsg msg) {
GetInstallPathForDataVolumeDownloadReply reply = new GetInstallPathForDataVolumeDownloadReply();
reply.setInstallPath(makeDataVolumeInstallPath(msg.getVolumeUuid()));
bus.reply(msg, reply);
}
@Override
protected void handle(final DeleteVolumeBitsOnPrimaryStorageMsg msg) {
DeleteCmd cmd = new DeleteCmd();
cmd.installPath = msg.getInstallPath();
final DeleteVolumeBitsOnPrimaryStorageReply reply = new DeleteVolumeBitsOnPrimaryStorageReply();
httpCall(DELETE_PATH, cmd, DeleteRsp.class, new ReturnValueCompletion<DeleteRsp>(msg) {
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
}
@Override
public void success(DeleteRsp ret) {
bus.reply(msg, reply);
}
});
}
@Override
protected void handle(final DownloadIsoToPrimaryStorageMsg msg) {
final DownloadIsoToPrimaryStorageReply reply = new DownloadIsoToPrimaryStorageReply();
DownloadToCache downloadToCache = new DownloadToCache();
downloadToCache.image = msg.getIsoSpec();
downloadToCache.download(new ReturnValueCompletion<ImageCacheVO>(msg) {
@Override
public void success(ImageCacheVO returnValue) {
reply.setInstallPath(returnValue.getInstallUrl());
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
@Override
protected void handle(DeleteIsoFromPrimaryStorageMsg msg) {
DeleteIsoFromPrimaryStorageReply reply = new DeleteIsoFromPrimaryStorageReply();
bus.reply(msg, reply);
}
@Override
protected void handle(AskVolumeSnapshotCapabilityMsg msg) {
AskVolumeSnapshotCapabilityReply reply = new AskVolumeSnapshotCapabilityReply();
VolumeSnapshotCapability cap = new VolumeSnapshotCapability();
cap.setSupport(true);
cap.setArrangementType(VolumeSnapshotArrangementType.INDIVIDUAL);
reply.setCapability(cap);
bus.reply(msg, reply);
}
@Override
protected void handle(final SyncVolumeSizeOnPrimaryStorageMsg msg) {
final SyncVolumeSizeOnPrimaryStorageReply reply = new SyncVolumeSizeOnPrimaryStorageReply();
final VolumeVO vol = dbf.findByUuid(msg.getVolumeUuid(), VolumeVO.class);
String installPath = vol.getInstallPath();
GetVolumeSizeCmd cmd = new GetVolumeSizeCmd();
cmd.fsId = getSelf().getFsid();
cmd.uuid = self.getUuid();
cmd.volumeUuid = msg.getVolumeUuid();
cmd.installPath = installPath;
httpCall(GET_VOLUME_SIZE_PATH, cmd, GetVolumeSizeRsp.class, new ReturnValueCompletion<GetVolumeSizeRsp>(msg) {
@Override
public void success(GetVolumeSizeRsp rsp) {
// current ceph has no way to get actual size
long asize = rsp.actualSize == null ? vol.getActualSize() : rsp.actualSize;
reply.setActualSize(asize);
reply.setSize(rsp.size);
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
protected <T extends AgentResponse> void httpCall(final String path, final AgentCommand cmd, final Class<T> retClass, final ReturnValueCompletion<T> callback) {
httpCall(path, cmd, retClass, callback, null, 0);
}
protected <T extends AgentResponse> void httpCall(final String path, final AgentCommand cmd, final Class<T> retClass, final ReturnValueCompletion<T> callback, TimeUnit unit, long timeout) {
new HttpCaller<>(path, cmd, retClass, callback, unit, timeout).call();
}
protected class HttpCaller<T extends AgentResponse> {
private Iterator<CephPrimaryStorageMonBase> it;
private List<ErrorCode> errorCodes = new ArrayList<ErrorCode>();
private final String path;
private final AgentCommand cmd;
private final Class<T> retClass;
private final ReturnValueCompletion<T> callback;
private final TimeUnit unit;
private final long timeout;
private String randomFactor = null;
private boolean tryNext = false;
HttpCaller(String path, AgentCommand cmd, Class<T> retClass, ReturnValueCompletion<T> callback) {
this(path, cmd, retClass, callback, null, 0);
}
HttpCaller(String path, AgentCommand cmd, Class<T> retClass, ReturnValueCompletion<T> callback, TimeUnit unit, long timeout) {
this.path = path;
this.cmd = cmd;
this.retClass = retClass;
this.callback = callback;
this.unit = unit;
this.timeout = timeout;
}
void call() {
it = prepareMons().iterator();
prepareCmd();
doCall();
}
// specify mons order by randomFactor to ensure that the same mon receive cmd every time.
HttpCaller<T> specifyOrder(String randomFactor) {
this.randomFactor = randomFactor;
return this;
}
HttpCaller<T> tryNext() {
this.tryNext = true;
return this;
}
private void prepareCmd() {
cmd.setUuid(self.getUuid());
cmd.setFsId(getSelf().getFsid());
}
private List<CephPrimaryStorageMonBase> prepareMons() {
final List<CephPrimaryStorageMonBase> mons = new ArrayList<CephPrimaryStorageMonBase>();
for (CephPrimaryStorageMonVO monvo : getSelf().getMons()) {
mons.add(new CephPrimaryStorageMonBase(monvo));
}
if (randomFactor != null) {
CollectionUtils.shuffleByKeySeed(mons, randomFactor, it -> it.getSelf().getUuid());
} else {
Collections.shuffle(mons);
}
mons.removeIf(it -> it.getSelf().getStatus() != MonStatus.Connected);
if (mons.isEmpty()) {
throw new OperationFailureException(operr(
"all ceph mons of primary storage[uuid:%s] are not in Connected state", self.getUuid())
);
}
return mons;
}
private void doCall() {
if (!it.hasNext()) {
callback.fail(operr(
"all mons failed to execute http call[%s], errors are %s", path, JSONObjectUtil.toJsonString(errorCodes))
);
return;
}
CephPrimaryStorageMonBase base = it.next();
cmd.monUuid = base.getSelf().getUuid();
ReturnValueCompletion<T> completion = new ReturnValueCompletion<T>(callback) {
@Override
public void success(T ret) {
if (!ret.success) {
if (tryNext) {
doCall();
} else {
callback.fail(operr("operation error, because:%s", ret.error));
}
return;
}
if (!(cmd instanceof InitCmd)) {
updateCapacityIfNeeded(ret);
}
callback.success(ret);
}
@Override
public void fail(ErrorCode errorCode) {
logger.warn(String.format("mon[%s] failed to execute http call[%s], error is: %s",
base.getSelf().getHostname(), path, JSONObjectUtil.toJsonString(errorCode)));
errorCodes.add(errorCode);
doCall();
}
};
if (unit == null) {
base.httpCall(path, cmd, retClass, completion);
} else {
base.httpCall(path, cmd, retClass, completion, unit, timeout);
}
}
}
private void updateCapacityIfNeeded(AgentResponse rsp) {
if (rsp.totalCapacity != null && rsp.availableCapacity != null) {
CephCapacity cephCapacity = new CephCapacity();
cephCapacity.setFsid(getSelf().getFsid());
cephCapacity.setAvailableCapacity(rsp.availableCapacity);
cephCapacity.setTotalCapacity(rsp.totalCapacity);
cephCapacity.setPoolCapacities(rsp.poolCapacities);
cephCapacity.setXsky(rsp.isXsky());
new CephCapacityUpdater().update(cephCapacity);
}
}
private void connect(final boolean newAdded, final Completion completion) {
final List<CephPrimaryStorageMonBase> mons = CollectionUtils.transformToList(getSelf().getMons(),
CephPrimaryStorageMonBase::new);
class Connector {
private List<ErrorCode> errorCodes = new ArrayList<>();
private Iterator<CephPrimaryStorageMonBase> it = mons.iterator();
void connect(final FlowTrigger trigger) {
if (!it.hasNext()) {
if (errorCodes.size() == mons.size()) {
if (errorCodes.isEmpty()) {
trigger.fail(operr("unable to connect to the ceph primary storage[uuid:%s]." +
" Failed to connect all ceph mons.", self.getUuid()));
} else {
trigger.fail(operr("unable to connect to the ceph primary storage[uuid:%s]." +
" Failed to connect all ceph mons. Errors are %s",
self.getUuid(), JSONObjectUtil.toJsonString(errorCodes)));
}
} else {
// reload because mon status changed
PrimaryStorageVO vo = dbf.reload(self);
if (vo == null) {
if (newAdded) {
if (!getSelf().getMons().isEmpty()) {
dbf.removeCollection(getSelf().getMons(), CephPrimaryStorageMonVO.class);
}
}
trigger.fail(operr("ceph primary storage[uuid:%s] may have been deleted.", self.getUuid()));
} else {
self = vo;
trigger.next();
}
}
return;
}
final CephPrimaryStorageMonBase base = it.next();
base.connect(new Completion(trigger) {
@Override
public void success() {
connect(trigger);
}
@Override
public void fail(ErrorCode errorCode) {
errorCodes.add(errorCode);
if (newAdded) {
// the mon fails to connect, remove it
dbf.remove(base.getSelf());
}
connect(trigger);
}
});
}
}
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("connect-ceph-primary-storage-%s", self.getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "connect-monitor";
@Override
public void run(FlowTrigger trigger, Map data) {
new Connector().connect(trigger);
}
});
flow(new NoRollbackFlow() {
String __name__ = "check-mon-integrity";
@Override
public void run(final FlowTrigger trigger, Map data) {
final Map<String, String> fsids = new HashMap<String, String>();
final List<CephPrimaryStorageMonBase> mons = CollectionUtils.transformToList(getSelf().getMons(), new Function<CephPrimaryStorageMonBase, CephPrimaryStorageMonVO>() {
@Override
public CephPrimaryStorageMonBase call(CephPrimaryStorageMonVO arg) {
return arg.getStatus() == MonStatus.Connected ? new CephPrimaryStorageMonBase(arg) : null;
}
});
DebugUtils.Assert(!mons.isEmpty(), "how can be no connected MON !!!???");
List<ErrorCode> errors = new ArrayList<>();
new While<>(mons).each((mon, compl) -> {
GetFactsCmd cmd = new GetFactsCmd();
cmd.uuid = self.getUuid();
cmd.monUuid = mon.getSelf().getUuid();
mon.httpCall(GET_FACTS, cmd, GetFactsRsp.class, new ReturnValueCompletion<GetFactsRsp>(compl) {
@Override
public void success(GetFactsRsp rsp) {
if (!rsp.success) {
// one mon cannot get the facts, directly error out
errors.add(Platform.operr("%s", rsp.getError()));
compl.allDone();
return;
}
CephPrimaryStorageMonVO monVO = dbf.reload(mon.getSelf());
if (monVO != null) {
fsids.put(monVO.getUuid(), rsp.fsid);
monVO.setMonAddr(rsp.monAddr == null ? monVO.getHostname() : rsp.monAddr);
dbf.update(monVO);
}
compl.done();
}
@Override
public void fail(ErrorCode errorCode) {
// one mon cannot get the facts, directly error out
errors.add(errorCode);
compl.allDone();
}
});
}).run(new NoErrorCompletion(trigger) {
@Override
public void done() {
if (!errors.isEmpty()) {
trigger.fail(errors.get(0));
return;
}
Set<String> set = new HashSet<>(fsids.values());
if (set.size() != 1) {
StringBuilder sb = new StringBuilder(i18n("the fsid returned by mons are mismatching, it seems the mons belong to different ceph clusters:\n"));
for (CephPrimaryStorageMonBase mon : mons) {
String fsid = fsids.get(mon.getSelf().getUuid());
sb.append(String.format("%s (mon ip) --> %s (fsid)\n", mon.getSelf().getHostname(), fsid));
}
throw new OperationFailureException(operr(sb.toString()));
}
// check if there is another ceph setup having the same fsid
String fsId = set.iterator().next();
SimpleQuery<CephPrimaryStorageVO> q = dbf.createQuery(CephPrimaryStorageVO.class);
q.add(CephPrimaryStorageVO_.fsid, Op.EQ, fsId);
q.add(CephPrimaryStorageVO_.uuid, Op.NOT_EQ, self.getUuid());
CephPrimaryStorageVO otherCeph = q.find();
if (otherCeph != null) {
throw new OperationFailureException(
operr("there is another CEPH primary storage[name:%s, uuid:%s] with the same" +
" FSID[%s], you cannot add the same CEPH setup as two different primary storage",
otherCeph.getName(), otherCeph.getUuid(), fsId)
);
}
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "check_pool";
@Override
public void run(FlowTrigger trigger, Map data) {
List<Pool> pools = new ArrayList<Pool>();
String primaryStorageUuid = self.getUuid();
Pool p = new Pool();
p.name = getDefaultImageCachePoolName();
p.predefined = CephSystemTags.PREDEFINED_PRIMARY_STORAGE_IMAGE_CACHE_POOL.hasTag(primaryStorageUuid);
pools.add(p);
p = new Pool();
p.name = getDefaultRootVolumePoolName();
p.predefined = CephSystemTags.PREDEFINED_PRIMARY_STORAGE_ROOT_VOLUME_POOL.hasTag(primaryStorageUuid);
pools.add(p);
p = new Pool();
p.name = getDefaultDataVolumePoolName();
p.predefined = CephSystemTags.PREDEFINED_PRIMARY_STORAGE_DATA_VOLUME_POOL.hasTag(primaryStorageUuid);
pools.add(p);
if(!newAdded){
CheckCmd check = new CheckCmd();
check.setPools(pools);
httpCall(CHECK_POOL_PATH, check, CheckRsp.class, new ReturnValueCompletion<CheckRsp>(trigger) {
@Override
public void fail(ErrorCode err) {
trigger.fail(err);
}
@Override
public void success(CheckRsp ret) {
trigger.next();
}
});
}else {
trigger.next();
}
}
});
flow(new NoRollbackFlow() {
String __name__ = "init";
@Override
public void run(final FlowTrigger trigger, Map data) {
List<Pool> pools = new ArrayList<Pool>();
String primaryStorageUuid = self.getUuid();
Pool p = new Pool();
p.name = getDefaultImageCachePoolName();
p.predefined = CephSystemTags.PREDEFINED_PRIMARY_STORAGE_IMAGE_CACHE_POOL.hasTag(primaryStorageUuid);
pools.add(p);
p = new Pool();
p.name = getDefaultRootVolumePoolName();
p.predefined = CephSystemTags.PREDEFINED_PRIMARY_STORAGE_ROOT_VOLUME_POOL.hasTag(primaryStorageUuid);
pools.add(p);
p = new Pool();
p.name = getDefaultDataVolumePoolName();
p.predefined = CephSystemTags.PREDEFINED_PRIMARY_STORAGE_DATA_VOLUME_POOL.hasTag(primaryStorageUuid);
pools.add(p);
InitCmd cmd = new InitCmd();
if (CephSystemTags.NO_CEPHX.hasTag(primaryStorageUuid)) {
cmd.nocephx = true;
}
cmd.pools = pools;
httpCall(INIT_PATH, cmd, InitRsp.class, new ReturnValueCompletion<InitRsp>(trigger) {
@Override
public void fail(ErrorCode err) {
trigger.fail(err);
}
@Override
public void success(InitRsp ret) {
if (getSelf().getFsid() == null) {
getSelf().setFsid(ret.fsid);
}
getSelf().setUserKey(ret.userKey);
self = dbf.updateAndRefresh(self);
CephCapacityUpdater updater = new CephCapacityUpdater();
CephCapacity cephCapacity = new CephCapacity();
cephCapacity.setFsid(ret.fsid);
cephCapacity.setAvailableCapacity(ret.availableCapacity);
cephCapacity.setTotalCapacity(ret.totalCapacity);
cephCapacity.setPoolCapacities(ret.poolCapacities);
cephCapacity.setXsky(ret.isXsky());
updater.update(cephCapacity, true);
trigger.next();
}
});
}
});
done(new FlowDoneHandler(completion) {
@Override
public void handle(Map data) {
completion.success();
}
});
error(new FlowErrorHandler(completion) {
@Override
public void handle(ErrorCode errCode, Map data) {
if (newAdded) {
PrimaryStorageVO vo = dbf.reload(self);
if (vo != null) {
self = vo;
}
if (!getSelf().getMons().isEmpty()) {
dbf.removeCollection(getSelf().getMons(), CephPrimaryStorageMonVO.class);
}
if (!getSelf().getPools().isEmpty()) {
dbf.removeCollection(getSelf().getPools(), CephPrimaryStoragePoolVO.class);
}
}
completion.fail(errCode);
}
});
}
}).start();
}
@Override
protected void connectHook(ConnectParam param, final Completion completion) {
connect(param.isNewAdded(), completion);
}
@Override
protected void pingHook(final Completion completion) {
final List<CephPrimaryStorageMonBase> mons = getSelf().getMons().stream()
.filter(mon -> !mon.getStatus().equals(MonStatus.Connecting)).map(CephPrimaryStorageMonBase::new).collect(Collectors.toList());
final List<ErrorCode> errors = new ArrayList<ErrorCode>();
class Ping {
private AtomicBoolean replied = new AtomicBoolean(false);
@AsyncThread
private void reconnectMon(final CephPrimaryStorageMonBase mon, boolean delay) {
if (!CephGlobalConfig.PRIMARY_STORAGE_MON_AUTO_RECONNECT.value(Boolean.class)) {
logger.debug(String.format("do not reconnect the ceph primary storage mon[uuid:%s] as the global config[%s] is set to false",
self.getUuid(), CephGlobalConfig.PRIMARY_STORAGE_MON_AUTO_RECONNECT.getCanonicalName()));
return;
}
// there has been a reconnect in process
if (!reconnectMonLock.lock()) {
logger.debug(String.format("ignore this call, reconnect ceph primary storage mon[uuid:%s] is in process", self.getUuid()));
return;
}
final NoErrorCompletion releaseLock = new NoErrorCompletion() {
@Override
public void done() {
reconnectMonLock.unlock();
}
};
try {
if (delay) {
try {
TimeUnit.SECONDS.sleep(CephGlobalConfig.PRIMARY_STORAGE_MON_RECONNECT_DELAY.value(Long.class));
} catch (InterruptedException ignored) {
}
}
mon.connect(new Completion(releaseLock) {
@Override
public void success() {
logger.debug(String.format("successfully reconnected the mon[uuid:%s] of the ceph primary" +
" storage[uuid:%s, name:%s]", mon.getSelf().getUuid(), self.getUuid(), self.getName()));
releaseLock.done();
}
@Override
public void fail(ErrorCode errorCode) {
logger.warn(String.format("failed to reconnect the mon[uuid:%s] server of the ceph primary" +
" storage[uuid:%s, name:%s], %s", mon.getSelf().getUuid(), self.getUuid(), self.getName(), errorCode));
releaseLock.done();
}
});
} catch (Throwable t) {
releaseLock.done();
logger.warn(t.getMessage(), t);
}
}
private void ping() {
final List<String> monUuids = mons.stream()
.map(m -> m.getSelf().getMonAddr())
.collect(Collectors.toList());
logger.info(String.format("ceph-ps-ping-mon: %s", String.join(",", monUuids)));
// this is only called when all mons are disconnected
final AsyncLatch latch = new AsyncLatch(mons.size(), new NoErrorCompletion() {
@Override
public void done() {
if (!replied.compareAndSet(false, true)) {
return;
}
ErrorCode err = errf.stringToOperationError(String.format("failed to ping the ceph primary storage[uuid:%s, name:%s]",
self.getUuid(), self.getName()), errors);
completion.fail(err);
}
});
for (final CephPrimaryStorageMonBase mon : mons) {
mon.ping(new ReturnValueCompletion<PingResult>(latch) {
private void thisMonIsDown(ErrorCode err) {
//TODO
logger.warn(String.format("cannot ping mon[uuid:%s] of the ceph primary storage[uuid:%s, name:%s], %s",
mon.getSelf().getUuid(), self.getUuid(), self.getName(), err));
errors.add(err);
mon.changeStatus(MonStatus.Disconnected);
reconnectMon(mon, true);
latch.ack();
}
@Override
public void success(PingResult res) {
if (res.success) {
// as long as there is one mon working, the primary storage works
pingSuccess();
if (mon.getSelf().getStatus() == MonStatus.Disconnected) {
reconnectMon(mon, false);
}
} else if (PingOperationFailure.UnableToCreateFile.toString().equals(res.failure)) {
// as long as there is one mon saying the ceph not working, the primary storage goes down
ErrorCode err = operr("the ceph primary storage[uuid:%s, name:%s] is down, as one mon[uuid:%s] reports" +
" an operation failure[%s]", self.getUuid(), self.getName(), mon.getSelf().getUuid(), res.error);
errors.add(err);
primaryStorageDown();
} else if (!res.success || PingOperationFailure.MonAddrChanged.toString().equals(res.failure)) {
// this mon is down(success == false, operationFailure == false), but the primary storage may still work as other mons may work
ErrorCode errorCode = operr("operation error, because:%s", res.error);
thisMonIsDown(errorCode);
} else {
throw new CloudRuntimeException("should not be here");
}
}
@Override
public void fail(ErrorCode errorCode) {
thisMonIsDown(errorCode);
}
});
}
}
// this is called once a mon return an operation failure
private void primaryStorageDown() {
if (!replied.compareAndSet(false, true)) {
return;
}
// set all mons to be disconnected
for (CephPrimaryStorageMonBase base : mons) {
base.changeStatus(MonStatus.Disconnected);
}
ErrorCode err = errf.stringToOperationError(String.format("failed to ping the ceph primary storage[uuid:%s, name:%s]",
self.getUuid(), self.getName()), errors);
completion.fail(err);
}
private void pingSuccess() {
if (!replied.compareAndSet(false, true)) {
return;
}
completion.success();
}
}
new Ping().ping();
}
@Override
protected void syncPhysicalCapacity(ReturnValueCompletion<PhysicalCapacityUsage> completion) {
PrimaryStorageCapacityVO cap = dbf.findByUuid(self.getUuid(), PrimaryStorageCapacityVO.class);
PhysicalCapacityUsage usage = new PhysicalCapacityUsage();
usage.availablePhysicalSize = cap.getAvailablePhysicalCapacity();
usage.totalPhysicalSize = cap.getTotalPhysicalCapacity();
completion.success(usage);
}
@Override
protected void handle(APIReconnectPrimaryStorageMsg msg) {
final APIReconnectPrimaryStorageEvent evt = new APIReconnectPrimaryStorageEvent(msg.getId());
// fire disconnected canonical event only if the current status is connected
boolean fireEvent = self.getStatus() == PrimaryStorageStatus.Connected;
self.setStatus(PrimaryStorageStatus.Connecting);
dbf.update(self);
connect(false, new Completion(msg) {
@Override
public void success() {
self = dbf.reload(self);
self.setStatus(PrimaryStorageStatus.Connected);
self = dbf.updateAndRefresh(self);
evt.setInventory(getSelfInventory());
bus.publish(evt);
}
@Override
public void fail(ErrorCode errorCode) {
self = dbf.reload(self);
self.setStatus(PrimaryStorageStatus.Disconnected);
self = dbf.updateAndRefresh(self);
if (fireEvent) {
fireDisconnectedCanonicalEvent(errorCode);
}
evt.setError(errorCode);
bus.publish(evt);
}
});
}
@Override
protected void handleApiMessage(APIMessage msg) {
if (msg instanceof APIAddMonToCephPrimaryStorageMsg) {
handle((APIAddMonToCephPrimaryStorageMsg) msg);
} else if (msg instanceof APIRemoveMonFromCephPrimaryStorageMsg) {
handle((APIRemoveMonFromCephPrimaryStorageMsg) msg);
} else if (msg instanceof APIUpdateCephPrimaryStorageMonMsg) {
handle((APIUpdateCephPrimaryStorageMonMsg) msg);
} else if (msg instanceof APIAddCephPrimaryStoragePoolMsg) {
handle((APIAddCephPrimaryStoragePoolMsg) msg);
} else if (msg instanceof APIDeleteCephPrimaryStoragePoolMsg) {
handle((APIDeleteCephPrimaryStoragePoolMsg) msg);
} else if (msg instanceof APIUpdateCephPrimaryStoragePoolMsg) {
handle((APIUpdateCephPrimaryStoragePoolMsg) msg);
} else if (msg instanceof APICleanUpTrashOnPrimaryStorageMsg) {
handle((APICleanUpTrashOnPrimaryStorageMsg) msg);
} else {
super.handleApiMessage(msg);
}
}
private void handle(APIUpdateCephPrimaryStoragePoolMsg msg) {
APIUpdateCephPrimaryStoragePoolEvent evt = new APIUpdateCephPrimaryStoragePoolEvent(msg.getId());
CephPrimaryStoragePoolVO vo = dbf.findByUuid(msg.getUuid(), CephPrimaryStoragePoolVO.class);
if (msg.getAliasName() != null) {
vo.setAliasName(msg.getAliasName());
}
if (msg.getDescription() != null) {
vo.setDescription(msg.getDescription());
}
dbf.update(vo);
evt.setInventory(CephPrimaryStoragePoolInventory.valueOf(vo));
bus.publish(evt);
}
private void handle(APIDeleteCephPrimaryStoragePoolMsg msg) {
APIDeleteCephPrimaryStoragePoolEvent evt = new APIDeleteCephPrimaryStoragePoolEvent(msg.getId());
CephPrimaryStoragePoolVO vo = dbf.findByUuid(msg.getUuid(), CephPrimaryStoragePoolVO.class);
dbf.remove(vo);
bus.publish(evt);
}
private void handle(APIAddCephPrimaryStoragePoolMsg msg) {
CephPrimaryStoragePoolVO vo = new CephPrimaryStoragePoolVO();
vo.setUuid(msg.getResourceUuid() == null ? Platform.getUuid() : msg.getResourceUuid());
vo.setDescription(msg.getDescription());
vo.setPoolName(msg.getPoolName());
if (msg.getAliasName() != null) {
vo.setAliasName(msg.getAliasName());
}
if (msg.getDescription() != null) {
vo.setDescription(msg.getDescription());
}
vo.setType(msg.getType());
vo.setPrimaryStorageUuid(self.getUuid());
vo = dbf.persistAndRefresh(vo);
AddPoolCmd cmd = new AddPoolCmd();
cmd.isCreate = msg.isCreate();
cmd.poolName = EncodingConversion.encodingToUnicode(msg.getPoolName());
APIAddCephPrimaryStoragePoolEvent evt = new APIAddCephPrimaryStoragePoolEvent(msg.getId());
CephPrimaryStoragePoolVO finalVo = vo;
httpCall(ADD_POOL_PATH, cmd, AddPoolRsp.class, new ReturnValueCompletion<AddPoolRsp>(msg) {
@Override
public void success(AddPoolRsp rsp) {
evt.setInventory(CephPrimaryStoragePoolInventory.valueOf(finalVo));
bus.publish(evt);
}
@Override
public void fail(ErrorCode errorCode) {
dbf.remove(finalVo);
evt.setError(errorCode);
bus.publish(evt);
}
});
}
private void handle(APIRemoveMonFromCephPrimaryStorageMsg msg) {
APIRemoveMonFromCephPrimaryStorageEvent evt = new APIRemoveMonFromCephPrimaryStorageEvent(msg.getId());
SimpleQuery<CephPrimaryStorageMonVO> q = dbf.createQuery(CephPrimaryStorageMonVO.class);
q.add(CephPrimaryStorageMonVO_.hostname, Op.IN, msg.getMonHostnames());
List<CephPrimaryStorageMonVO> vos = q.list();
dbf.removeCollection(vos, CephPrimaryStorageMonVO.class);
evt.setInventory(CephPrimaryStorageInventory.valueOf(dbf.reload(getSelf())));
bus.publish(evt);
}
private void handle(APIUpdateCephPrimaryStorageMonMsg msg) {
final APIUpdateCephPrimaryStorageMonEvent evt = new APIUpdateCephPrimaryStorageMonEvent(msg.getId());
CephPrimaryStorageMonVO monvo = dbf.findByUuid(msg.getMonUuid(), CephPrimaryStorageMonVO.class);
if (msg.getHostname() != null) {
monvo.setHostname(msg.getHostname());
}
if (msg.getMonPort() != null && msg.getMonPort() > 0 && msg.getMonPort() <= 65535) {
monvo.setMonPort(msg.getMonPort());
}
if (msg.getSshPort() != null && msg.getSshPort() > 0 && msg.getSshPort() <= 65535) {
monvo.setSshPort(msg.getSshPort());
}
if (msg.getSshUsername() != null) {
monvo.setSshUsername(msg.getSshUsername());
}
if (msg.getSshPassword() != null) {
monvo.setSshPassword(msg.getSshPassword());
}
dbf.update(monvo);
evt.setInventory(CephPrimaryStorageInventory.valueOf((dbf.reload(getSelf()))));
bus.publish(evt);
}
private void handle(final APIAddMonToCephPrimaryStorageMsg msg) {
final APIAddMonToCephPrimaryStorageEvent evt = new APIAddMonToCephPrimaryStorageEvent(msg.getId());
FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("add-mon-ceph-primary-storage-%s", self.getUuid()));
chain.then(new ShareFlow() {
List<CephPrimaryStorageMonVO> monVOs = new ArrayList<CephPrimaryStorageMonVO>();
@Override
public void setup() {
flow(new Flow() {
String __name__ = "create-mon-in-db";
@Override
public void run(FlowTrigger trigger, Map data) {
for (String url : msg.getMonUrls()) {
CephPrimaryStorageMonVO monvo = new CephPrimaryStorageMonVO();
MonUri uri = new MonUri(url);
monvo.setUuid(Platform.getUuid());
monvo.setStatus(MonStatus.Connecting);
monvo.setHostname(uri.getHostname());
monvo.setMonAddr(monvo.getHostname());
monvo.setMonPort(uri.getMonPort());
monvo.setSshPort(uri.getSshPort());
monvo.setSshUsername(uri.getSshUsername());
monvo.setSshPassword(uri.getSshPassword());
monvo.setPrimaryStorageUuid(self.getUuid());
monVOs.add(monvo);
}
dbf.persistCollection(monVOs);
trigger.next();
}
@Override
public void rollback(FlowRollback trigger, Map data) {
dbf.removeCollection(monVOs, CephPrimaryStorageMonVO.class);
trigger.rollback();
}
});
flow(new NoRollbackFlow() {
String __name__ = "connect-mons";
@Override
public void run(final FlowTrigger trigger, Map data) {
List<CephPrimaryStorageMonBase> bases = CollectionUtils.transformToList(monVOs, new Function<CephPrimaryStorageMonBase, CephPrimaryStorageMonVO>() {
@Override
public CephPrimaryStorageMonBase call(CephPrimaryStorageMonVO arg) {
return new CephPrimaryStorageMonBase(arg);
}
});
final List<ErrorCode> errorCodes = new ArrayList<ErrorCode>();
final AsyncLatch latch = new AsyncLatch(bases.size(), new NoErrorCompletion(trigger) {
@Override
public void done() {
if (!errorCodes.isEmpty()) {
trigger.fail(operr( "unable to connect mons").causedBy(errorCodes));
} else {
trigger.next();
}
}
});
for (CephPrimaryStorageMonBase base : bases) {
base.connect(new Completion(trigger) {
@Override
public void success() {
latch.ack();
}
@Override
public void fail(ErrorCode errorCode) {
// one fails, all fail
errorCodes.add(errorCode);
latch.ack();
}
});
}
}
});
flow(new NoRollbackFlow() {
String __name__ = "check-mon-integrity";
@Override
public void run(final FlowTrigger trigger, Map data) {
List<CephPrimaryStorageMonBase> bases = CollectionUtils.transformToList(monVOs, new Function<CephPrimaryStorageMonBase, CephPrimaryStorageMonVO>() {
@Override
public CephPrimaryStorageMonBase call(CephPrimaryStorageMonVO arg) {
return new CephPrimaryStorageMonBase(arg);
}
});
final List<ErrorCode> errors = new ArrayList<ErrorCode>();
final AsyncLatch latch = new AsyncLatch(bases.size(), new NoErrorCompletion(trigger) {
@Override
public void done() {
// one fail, all fail
if (!errors.isEmpty()) {
trigger.fail(operr("unable to add mon to ceph primary storage").causedBy(errors));
} else {
trigger.next();
}
}
});
for (final CephPrimaryStorageMonBase base : bases) {
GetFactsCmd cmd = new GetFactsCmd();
cmd.uuid = self.getUuid();
cmd.monUuid = base.getSelf().getUuid();
base.httpCall(GET_FACTS, cmd, GetFactsRsp.class, new ReturnValueCompletion<GetFactsRsp>(latch) {
@Override
public void success(GetFactsRsp rsp) {
if (!rsp.isSuccess()) {
errors.add(operr("operation error, because:%s", rsp.getError()));
} else {
String fsid = rsp.fsid;
if (!getSelf().getFsid().equals(fsid)) {
errors.add(operr("the mon[ip:%s] returns a fsid[%s] different from the current fsid[%s] of the cep cluster," +
"are you adding a mon not belonging to current cluster mistakenly?", base.getSelf().getHostname(), fsid, getSelf().getFsid())
);
}
}
latch.ack();
}
@Override
public void fail(ErrorCode errorCode) {
errors.add(errorCode);
latch.ack();
}
});
}
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
evt.setInventory(CephPrimaryStorageInventory.valueOf(dbf.reload(getSelf())));
bus.publish(evt);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
evt.setError(errCode);
bus.publish(evt);
}
});
}
}).start();
}
@Override
protected void handleLocalMessage(Message msg) {
if (msg instanceof TakeSnapshotMsg) {
handle((TakeSnapshotMsg) msg);
} else if (msg instanceof CreateVolumeFromVolumeSnapshotOnPrimaryStorageMsg) {
handle((CreateVolumeFromVolumeSnapshotOnPrimaryStorageMsg) msg);
} else if (msg instanceof BackupVolumeSnapshotFromPrimaryStorageToBackupStorageMsg) {
handle((BackupVolumeSnapshotFromPrimaryStorageToBackupStorageMsg) msg);
} else if (msg instanceof CreateKvmSecretMsg) {
handle((CreateKvmSecretMsg) msg);
} else if (msg instanceof UploadBitsToBackupStorageMsg) {
handle((UploadBitsToBackupStorageMsg) msg);
} else if (msg instanceof SetupSelfFencerOnKvmHostMsg) {
handle((SetupSelfFencerOnKvmHostMsg) msg);
} else if (msg instanceof CancelSelfFencerOnKvmHostMsg) {
handle((CancelSelfFencerOnKvmHostMsg) msg);
} else if (msg instanceof DeleteImageCacheOnPrimaryStorageMsg) {
handle((DeleteImageCacheOnPrimaryStorageMsg) msg);
} else if (msg instanceof PurgeSnapshotOnPrimaryStorageMsg) {
handle((PurgeSnapshotOnPrimaryStorageMsg) msg);
} else if (msg instanceof CreateEmptyVolumeMsg) {
handle((CreateEmptyVolumeMsg) msg);
} else if (msg instanceof CephToCephMigrateVolumeSegmentMsg) {
handle((CephToCephMigrateVolumeSegmentMsg) msg);
} else if (msg instanceof GetVolumeSnapshotInfoMsg) {
handle((GetVolumeSnapshotInfoMsg) msg);
} else if (msg instanceof DownloadBitsFromKVMHostToPrimaryStorageMsg) {
handle((DownloadBitsFromKVMHostToPrimaryStorageMsg) msg);
} else if (msg instanceof CancelDownloadBitsFromKVMHostToPrimaryStorageMsg) {
handle((CancelDownloadBitsFromKVMHostToPrimaryStorageMsg) msg);
} else if ((msg instanceof CleanUpTrashOnPrimaryStroageMsg)) {
handle((CleanUpTrashOnPrimaryStroageMsg) msg);
} else {
super.handleLocalMessage(msg);
}
}
public static class CheckIsBitsExistingRsp extends AgentResponse {
private boolean existing;
public void setExisting(boolean existing) {
this.existing = existing;
}
public boolean isExisting() {
return existing;
}
}
private void handle(DownloadBitsFromKVMHostToPrimaryStorageMsg msg) {
DownloadBitsFromKVMHostToPrimaryStorageReply reply = new DownloadBitsFromKVMHostToPrimaryStorageReply();
GetKVMHostDownloadCredentialMsg gmsg = new GetKVMHostDownloadCredentialMsg();
gmsg.setHostUuid(msg.getSrcHostUuid());
if (PrimaryStorageSystemTags.PRIMARY_STORAGE_GATEWAY.hasTag(self.getUuid())) {
gmsg.setDataNetworkCidr(PrimaryStorageSystemTags.PRIMARY_STORAGE_GATEWAY.getTokenByResourceUuid(self.getUuid(), PrimaryStorageSystemTags.PRIMARY_STORAGE_GATEWAY_TOKEN));
}
bus.makeTargetServiceIdByResourceUuid(gmsg, HostConstant.SERVICE_ID, msg.getSrcHostUuid());
bus.send(gmsg, new CloudBusCallBack(reply) {
@Override
public void run(MessageReply rly) {
if (!rly.isSuccess()) {
reply.setError(rly.getError());
bus.reply(msg, reply);
return;
}
GetKVMHostDownloadCredentialReply grly = rly.castReply();
DownloadBitsFromKVMHostCmd cmd = new DownloadBitsFromKVMHostCmd();
cmd.setHostname(grly.getHostname());
cmd.setUsername(grly.getUsername());
cmd.setSshKey(grly.getSshKey());
cmd.setSshPort(grly.getSshPort());
cmd.setBackupStorageInstallPath(msg.getHostInstallPath());
cmd.setPrimaryStorageInstallPath(msg.getPrimaryStorageInstallPath());
cmd.setBandWidth(msg.getBandWidth());
cmd.setIdentificationCode(msg.getLongJobUuid() + msg.getPrimaryStorageInstallPath());
String randomFactor = msg.getLongJobUuid();
new HttpCaller<>(DOWNLOAD_BITS_FROM_KVM_HOST_PATH, cmd, AgentResponse.class, new ReturnValueCompletion<AgentResponse>(reply) {
@Override
public void success(AgentResponse returnValue) {
if (returnValue.isSuccess()) {
logger.info(String.format("successfully downloaded bits %s from kvm host %s to primary storage %s", cmd.getBackupStorageInstallPath(), msg.getSrcHostUuid(), msg.getPrimaryStorageUuid()));
bus.reply(msg, reply);
} else {
logger.error(String.format("failed to download bits %s from kvm host %s to primary storage %s", cmd.getBackupStorageInstallPath(), msg.getSrcHostUuid(), msg.getPrimaryStorageUuid()));
reply.setError(Platform.operr("operation error, because:%s", returnValue.getError()));
bus.reply(msg, reply);
}
}
@Override
public void fail(ErrorCode errorCode) {
logger.error(String.format("failed to download bits %s from kvm host %s to primary storage %s", cmd.getBackupStorageInstallPath(), msg.getSrcHostUuid(), msg.getPrimaryStorageUuid()));
reply.setError(errorCode);
bus.reply(msg, reply);
}
}).specifyOrder(randomFactor).call();
}
});
}
private void handle(CancelDownloadBitsFromKVMHostToPrimaryStorageMsg msg) {
CancelDownloadBitsFromKVMHostToPrimaryStorageReply reply = new CancelDownloadBitsFromKVMHostToPrimaryStorageReply();
CancelDownloadBitsFromKVMHostCmd cmd = new CancelDownloadBitsFromKVMHostCmd();
cmd.setPrimaryStorageInstallPath(msg.getPrimaryStorageInstallPath());
String randomFactor = msg.getLongJobUuid();
new HttpCaller<>(CANCEL_DOWNLOAD_BITS_FROM_KVM_HOST_PATH, cmd, AgentResponse.class, new ReturnValueCompletion<AgentResponse>(reply) {
@Override
public void success(AgentResponse returnValue) {
if (returnValue.isSuccess()) {
logger.info(String.format("successfully cancle downloaded bits to primary storage %s", msg.getPrimaryStorageUuid()));
} else {
logger.error(String.format("failed to cancel download bits to primary storage %s",msg.getPrimaryStorageUuid()));
reply.setError(Platform.operr("operation error, because:%s", returnValue.getError()));
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
logger.error(String.format("failed to cancel download bits to primary storage %s", msg.getPrimaryStorageUuid()));
reply.setError(errorCode);
bus.reply(msg, reply);
}
}).specifyOrder(randomFactor).tryNext().call();
}
private void handle(DeleteImageCacheOnPrimaryStorageMsg msg) {
DeleteImageCacheOnPrimaryStorageReply reply = new DeleteImageCacheOnPrimaryStorageReply();
DeleteImageCacheCmd cmd = new DeleteImageCacheCmd();
cmd.setFsId(getSelf().getFsid());
cmd.setUuid(self.getUuid());
cmd.imagePath = msg.getInstallPath().split("@")[0];
cmd.snapshotPath = msg.getInstallPath();
httpCall(DELETE_IMAGE_CACHE, cmd, AgentResponse.class, new ReturnValueCompletion<AgentResponse>(msg) {
@Override
public void success(AgentResponse rsp) {
if (!rsp.isSuccess()) {
reply.setError(operr("operation error, because:%s", rsp.getError()));
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(CancelSelfFencerOnKvmHostMsg msg) {
KvmCancelSelfFencerParam param = msg.getParam();
KvmCancelSelfFencerCmd cmd = new KvmCancelSelfFencerCmd();
cmd.uuid = self.getUuid();
cmd.fsId = getSelf().getFsid();
cmd.hostUuid = param.getHostUuid();
CancelSelfFencerOnKvmHostReply reply = new CancelSelfFencerOnKvmHostReply();
new KvmCommandSender(param.getHostUuid()).send(cmd, KVM_HA_CANCEL_SELF_FENCER, wrapper -> {
AgentResponse rsp = wrapper.getResponse(AgentResponse.class);
return rsp.isSuccess() ? null : operr("operation error, because:%s", rsp.getError());
}, new ReturnValueCompletion<KvmResponseWrapper>(msg) {
@Override
public void success(KvmResponseWrapper w) {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final SetupSelfFencerOnKvmHostMsg msg) {
KvmSetupSelfFencerParam param = msg.getParam();
KvmSetupSelfFencerCmd cmd = new KvmSetupSelfFencerCmd();
cmd.uuid = self.getUuid();
cmd.fsId = getSelf().getFsid();
cmd.hostUuid = param.getHostUuid();
cmd.interval = param.getInterval();
cmd.maxAttempts = param.getMaxAttempts();
cmd.storageCheckerTimeout = param.getStorageCheckerTimeout();
cmd.userKey = getSelf().getUserKey();
cmd.heartbeatImagePath = String.format("%s/ceph-ps-%s-host-hb-%s",
getDefaultRootVolumePoolName(),
self.getUuid(),
param.getHostUuid());
cmd.monUrls = CollectionUtils.transformToList(getSelf().getMons(), new Function<String, CephPrimaryStorageMonVO>() {
@Override
public String call(CephPrimaryStorageMonVO arg) {
return String.format("%s:%s", arg.getMonAddr(), arg.getMonPort());
}
});
final SetupSelfFencerOnKvmHostReply reply = new SetupSelfFencerOnKvmHostReply();
new KvmCommandSender(param.getHostUuid()).send(cmd, KVM_HA_SETUP_SELF_FENCER, new KvmCommandFailureChecker() {
@Override
public ErrorCode getError(KvmResponseWrapper wrapper) {
AgentResponse rsp = wrapper.getResponse(AgentResponse.class);
return rsp.isSuccess() ? null : operr("%s", rsp.getError());
}
}, new ReturnValueCompletion<KvmResponseWrapper>(msg) {
@Override
public void success(KvmResponseWrapper wrapper) {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final UploadBitsToBackupStorageMsg msg) {
checkCephFsId(msg.getPrimaryStorageUuid(), msg.getBackupStorageUuid());
SimpleQuery<BackupStorageVO> q = dbf.createQuery(BackupStorageVO.class);
q.select(BackupStorageVO_.type);
q.add(BackupStorageVO_.uuid, Op.EQ, msg.getBackupStorageUuid());
String bsType = q.findValue();
String path = CP_PATH;
String hostname = null;
if (!CephConstants.CEPH_BACKUP_STORAGE_TYPE.equals(bsType)) {
List<PrimaryStorageCommitExtensionPoint> exts = pluginRgty.getExtensionList(PrimaryStorageCommitExtensionPoint.class);
DebugUtils.Assert(exts.size() <= 1, "PrimaryStorageCommitExtensionPoint mustn't > 1");
if (exts.size() == 0) {
throw new OperationFailureException(operr(
"unable to upload bits to the backup storage[type:%s], we only support CEPH", bsType
));
} else {
path = exts.get(0).getCommitAgentPath(self.getType());
hostname = exts.get(0).getHostName(msg.getBackupStorageUuid());
DebugUtils.Assert(path != null, String.format("found the extension point: [%s], but return null path",
exts.get(0).getClass().getSimpleName()));
}
}
UploadCmd cmd = new UploadCmd();
cmd.sendCommandUrl = restf.getSendCommandUrl();
cmd.fsId = getSelf().getFsid();
cmd.srcPath = msg.getPrimaryStorageInstallPath();
cmd.dstPath = msg.getBackupStorageInstallPath();
if (msg.getImageUuid() != null) {
cmd.imageUuid = msg.getImageUuid();
ImageInventory inv = ImageInventory.valueOf(dbf.findByUuid(msg.getImageUuid(), ImageVO.class));
StringBuilder desc = new StringBuilder();
for (CreateImageExtensionPoint ext : pluginRgty.getExtensionList(CreateImageExtensionPoint.class)) {
String tmp = ext.getImageDescription(inv);
if (tmp != null && !tmp.trim().equals("")) {
desc.append(tmp);
}
}
cmd.description = desc.toString();
}
if (hostname != null) {
// imagestore hostname
cmd.hostname = hostname;
}
final UploadBitsToBackupStorageReply reply = new UploadBitsToBackupStorageReply();
httpCall(path, cmd, CpRsp.class, new ReturnValueCompletion<CpRsp>(msg) {
@Override
public void success(CpRsp rsp) {
if (rsp.installPath != null) {
reply.setInstallPath(rsp.installPath);
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(final CreateKvmSecretMsg msg) {
final CreateKvmSecretReply reply = new CreateKvmSecretReply();
createSecretOnKvmHosts(msg.getHostUuids(), new Completion(msg) {
@Override
public void success() {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
private void handle(BackupVolumeSnapshotFromPrimaryStorageToBackupStorageMsg msg) {
BackupVolumeSnapshotFromPrimaryStorageToBackupStorageReply reply = new BackupVolumeSnapshotFromPrimaryStorageToBackupStorageReply();
reply.setError(operr("backing up snapshots to backup storage is a depreciated feature, which will be removed in future version"));
bus.reply(msg, reply);
}
private void handle(final CreateVolumeFromVolumeSnapshotOnPrimaryStorageMsg msg) {
final CreateVolumeFromVolumeSnapshotOnPrimaryStorageReply reply = new CreateVolumeFromVolumeSnapshotOnPrimaryStorageReply();
final String volPath = makeDataVolumeInstallPath(msg.getVolumeUuid());
VolumeSnapshotInventory sp = msg.getSnapshot();
CpCmd cmd = new CpCmd();
cmd.resourceUuid = msg.getSnapshot().getVolumeUuid();
cmd.srcPath = sp.getPrimaryStorageInstallPath();
cmd.dstPath = volPath;
httpCall(CP_PATH, cmd, CpRsp.class, new ReturnValueCompletion<CpRsp>(msg) {
@Override
public void success(CpRsp rsp) {
reply.setInstallPath(volPath);
reply.setSize(rsp.size);
// current ceph has no way to get the actual size
long asize = rsp.actualSize == null ? 1 : rsp.actualSize;
reply.setActualSize(asize);
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
protected void handle(final RevertVolumeFromSnapshotOnPrimaryStorageMsg msg) {
final RevertVolumeFromSnapshotOnPrimaryStorageReply reply = new RevertVolumeFromSnapshotOnPrimaryStorageReply();
final TaskProgressRange parentStage = getTaskStage();
final TaskProgressRange ROLLBACK_SNAPSHOT_STAGE = new TaskProgressRange(0, 70);
final TaskProgressRange DELETE_ORIGINAL_SNAPSHOT_STAGE = new TaskProgressRange(30, 100);
final FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("revert-volume-[uuid:%s]-from-snapshot-[uuid:%s]-on-ceph-primary-storage",
msg.getVolume().getUuid(), msg.getSnapshot().getUuid()));
chain.then(new ShareFlow() {
@Override
public void setup() {
String originalVolumePath = msg.getVolume().getInstallPath();
// get volume path from snapshot path, just split @
String volumePath = msg.getSnapshot().getPrimaryStorageInstallPath().split("@")[0];
flow(new NoRollbackFlow() {
@Override
public void run(FlowTrigger trigger, Map data) {
TaskProgressRange stage = markTaskStage(parentStage, ROLLBACK_SNAPSHOT_STAGE);
RollbackSnapshotCmd cmd = new RollbackSnapshotCmd();
cmd.snapshotPath = msg.getSnapshot().getPrimaryStorageInstallPath();
httpCall(ROLLBACK_SNAPSHOT_PATH, cmd, RollbackSnapshotRsp.class, new ReturnValueCompletion<RollbackSnapshotRsp>(msg) {
@Override
public void success(RollbackSnapshotRsp returnValue) {
reply.setSize(returnValue.getSize());
reportProgress(stage.getEnd().toString());
trigger.next();
}
@Override
public void fail(ErrorCode errorCode) {
trigger.fail(errorCode);
}
}, TimeUnit.MILLISECONDS, msg.getTimeout());
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
reply.setNewVolumeInstallPath(volumePath);
bus.reply(msg, reply);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
reply.setError(errCode);
bus.reply(msg, reply);
}
});
}
}).start();
}
private ImageSpec makeImageSpec(VolumeInventory volume) {
ImageVO image = dbf.findByUuid(volume.getRootImageUuid(), ImageVO.class);
if (image == null) {
throw new OperationFailureException(operr("cannot reinit rootvolume [%s] because image [%s] has been deleted and imagecache cannot be found",
volume.getUuid(), volume.getRootImageUuid()));
}
ImageSpec imageSpec = new ImageSpec();
imageSpec.setInventory(ImageInventory.valueOf(image));
ImageBackupStorageRefInventory ref = CollectionUtils.find(image.getBackupStorageRefs(), new Function<ImageBackupStorageRefInventory, ImageBackupStorageRefVO>() {
@Override
public ImageBackupStorageRefInventory call(ImageBackupStorageRefVO arg) {
String fsid = Q.New(CephBackupStorageVO.class).eq(CephBackupStorageVO_.uuid, arg.getBackupStorageUuid()).select(CephBackupStorageVO_.fsid).findValue();
if (fsid != null && fsid.equals(getSelf().getFsid())) {
return ImageBackupStorageRefInventory.valueOf(arg);
}
return null;
}
});
if (ref == null) {
throw new OperationFailureException(operr("cannot find backupstorage to download image [%s] to primarystorage [%s]", volume.getRootImageUuid(), getSelf().getUuid()));
}
imageSpec.setSelectedBackupStorage(ImageBackupStorageRefInventory.valueOf(image.getBackupStorageRefs().iterator().next()));
return imageSpec;
}
protected void handle(final ReInitRootVolumeFromTemplateOnPrimaryStorageMsg msg) {
final ReInitRootVolumeFromTemplateOnPrimaryStorageReply reply = new ReInitRootVolumeFromTemplateOnPrimaryStorageReply();
final FlowChain chain = FlowChainBuilder.newShareFlowChain();
chain.setName(String.format("reimage-vm-root-volume-%s", msg.getVolume().getUuid()));
chain.then(new ShareFlow() {
String originalVolumePath = msg.getVolume().getInstallPath();
String volumePath = makeResetImageRootVolumeInstallPath(msg.getVolume().getUuid());
String installUrl;
@Override
public void setup() {
flow(new NoRollbackFlow() {
String __name__ = "download-image-to-cache";
@Override
public void run(final FlowTrigger trigger, Map data) {
installUrl = Q.New(ImageCacheVO.class).eq(ImageCacheVO_.imageUuid, msg.getVolume().getRootImageUuid()).
eq(ImageCacheVO_.primaryStorageUuid, msg.getPrimaryStorageUuid()).select(ImageCacheVO_.installUrl).findValue();
if (installUrl != null) {
trigger.next();
return;
}
DownloadVolumeTemplateToPrimaryStorageMsg dmsg = new DownloadVolumeTemplateToPrimaryStorageMsg();
dmsg.setTemplateSpec(makeImageSpec(msg.getVolume()));
dmsg.setPrimaryStorageUuid(msg.getPrimaryStorageUuid());
bus.makeTargetServiceIdByResourceUuid(dmsg, PrimaryStorageConstant.SERVICE_ID, dmsg.getPrimaryStorageUuid());
bus.send(dmsg, new CloudBusCallBack(trigger) {
@Override
public void run(MessageReply reply) {
if (!reply.isSuccess()) {
trigger.fail(reply.getError());
return;
}
installUrl = ((DownloadVolumeTemplateToPrimaryStorageReply) reply).getImageCache().getInstallUrl();
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "clone-image";
@Override
public void run(final FlowTrigger trigger, Map data) {
CloneCmd cmd = new CloneCmd();
cmd.srcPath = installUrl;
cmd.dstPath = volumePath;
httpCall(CLONE_PATH, cmd, CloneRsp.class, new ReturnValueCompletion<CloneRsp>(trigger) {
@Override
public void fail(ErrorCode err) {
trigger.fail(err);
}
@Override
public void success(CloneRsp ret) {
trigger.next();
}
});
}
});
flow(new NoRollbackFlow() {
String __name__ = "delete-origin-root-volume-which-has-no-snapshot";
@Override
public void run(FlowTrigger trigger, Map data) {
SimpleQuery<VolumeSnapshotVO> sq = dbf.createQuery(VolumeSnapshotVO.class);
sq.add(VolumeSnapshotVO_.primaryStorageInstallPath, Op.LIKE,
String.format("%s%%", originalVolumePath));
sq.count();
if (sq.count() == 0) {
DeleteCmd cmd = new DeleteCmd();
cmd.installPath = originalVolumePath;
httpCall(DELETE_PATH, cmd, DeleteRsp.class, new ReturnValueCompletion<DeleteRsp>(null) {
@Override
public void success(DeleteRsp returnValue) {
logger.debug(String.format("successfully deleted %s", originalVolumePath));
}
@Override
public void fail(ErrorCode errorCode) {
//TODO GC
logger.warn(String.format("unable to delete %s, %s. Need a cleanup",
originalVolumePath, errorCode));
}
});
}
trigger.next();
}
});
done(new FlowDoneHandler(msg) {
@Override
public void handle(Map data) {
reply.setNewVolumeInstallPath(volumePath);
bus.reply(msg, reply);
}
});
error(new FlowErrorHandler(msg) {
@Override
public void handle(ErrorCode errCode, Map data) {
reply.setError(errCode);
bus.reply(msg, reply);
}
});
}
}).start();
}
@Override
protected void handle(final DeleteSnapshotOnPrimaryStorageMsg msg) {
final DeleteSnapshotOnPrimaryStorageReply reply = new DeleteSnapshotOnPrimaryStorageReply();
DeleteSnapshotCmd cmd = new DeleteSnapshotCmd();
cmd.snapshotPath = msg.getSnapshot().getPrimaryStorageInstallPath();
httpCall(DELETE_SNAPSHOT_PATH, cmd, DeleteSnapshotRsp.class, new ReturnValueCompletion<DeleteSnapshotRsp>(msg) {
@Override
public void success(DeleteSnapshotRsp returnValue) {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
}, TimeUnit.MILLISECONDS, msg.getTimeout());
}
protected void handle(final PurgeSnapshotOnPrimaryStorageMsg msg) {
final PurgeSnapshotOnPrimaryStorageReply reply = new PurgeSnapshotOnPrimaryStorageReply();
PurgeSnapshotCmd cmd = new PurgeSnapshotCmd();
cmd.volumePath = msg.getVolumePath();
httpCall(PURGE_SNAPSHOT_PATH, cmd, PurgeSnapshotRsp.class, new ReturnValueCompletion<PurgeSnapshotRsp>(msg) {
@Override
public void success(PurgeSnapshotRsp returnValue) {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
@Override
protected void handle(MergeVolumeSnapshotOnPrimaryStorageMsg msg) {
MergeVolumeSnapshotOnPrimaryStorageReply reply = new MergeVolumeSnapshotOnPrimaryStorageReply();
bus.reply(msg, reply);
}
private void handle(final TakeSnapshotMsg msg) {
final TakeSnapshotReply reply = new TakeSnapshotReply();
final VolumeSnapshotInventory sp = msg.getStruct().getCurrent();
SimpleQuery<VolumeVO> q = dbf.createQuery(VolumeVO.class);
q.select(VolumeVO_.installPath);
q.add(VolumeVO_.uuid, Op.EQ, sp.getVolumeUuid());
String volumePath = q.findValue();
final String spPath = String.format("%s@%s", volumePath, sp.getUuid());
CreateSnapshotCmd cmd = new CreateSnapshotCmd();
cmd.volumeUuid = sp.getVolumeUuid();
cmd.snapshotPath = spPath;
httpCall(CREATE_SNAPSHOT_PATH, cmd, CreateSnapshotRsp.class, new ReturnValueCompletion<CreateSnapshotRsp>(msg) {
@Override
public void success(CreateSnapshotRsp rsp) {
// current ceph has no way to get actual size
long asize = rsp.getActualSize() == null ? 0 : rsp.getActualSize();
sp.setSize(asize);
sp.setPrimaryStorageUuid(self.getUuid());
sp.setPrimaryStorageInstallPath(spPath);
sp.setType(VolumeSnapshotConstant.STORAGE_SNAPSHOT_TYPE.toString());
sp.setFormat(VolumeConstant.VOLUME_FORMAT_RAW);
reply.setInventory(sp);
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
@Override
public void attachHook(String clusterUuid, Completion completion) {
SimpleQuery<ClusterVO> q = dbf.createQuery(ClusterVO.class);
q.select(ClusterVO_.hypervisorType);
q.add(ClusterVO_.uuid, Op.EQ, clusterUuid);
String hvType = q.findValue();
if (KVMConstant.KVM_HYPERVISOR_TYPE.equals(hvType)) {
attachToKvmCluster(clusterUuid, completion);
} else {
completion.success();
}
}
private void createSecretOnKvmHosts(List<String> hostUuids, final Completion completion) {
final CreateKvmSecretCmd cmd = new CreateKvmSecretCmd();
cmd.setUserKey(getSelf().getUserKey());
String suuid = CephSystemTags.KVM_SECRET_UUID.getTokenByResourceUuid(self.getUuid(), CephSystemTags.KVM_SECRET_UUID_TOKEN);
DebugUtils.Assert(suuid != null, String.format("cannot find system tag[%s] for ceph primary storage[uuid:%s]", CephSystemTags.KVM_SECRET_UUID.getTagFormat(), self.getUuid()));
cmd.setUuid(suuid);
List<KVMHostAsyncHttpCallMsg> msgs = CollectionUtils.transformToList(hostUuids, new Function<KVMHostAsyncHttpCallMsg, String>() {
@Override
public KVMHostAsyncHttpCallMsg call(String huuid) {
KVMHostAsyncHttpCallMsg msg = new KVMHostAsyncHttpCallMsg();
msg.setCommand(cmd);
msg.setPath(KVM_CREATE_SECRET_PATH);
msg.setHostUuid(huuid);
msg.setNoStatusCheck(true);
bus.makeTargetServiceIdByResourceUuid(msg, HostConstant.SERVICE_ID, huuid);
return msg;
}
});
bus.send(msgs, new CloudBusListCallBack(completion) {
@Override
public void run(List<MessageReply> replies) {
for (MessageReply r : replies) {
if (!r.isSuccess()) {
completion.fail(r.getError());
return;
}
KVMHostAsyncHttpCallReply kr = r.castReply();
CreateKvmSecretRsp rsp = kr.toResponse(CreateKvmSecretRsp.class);
if (!rsp.isSuccess()) {
completion.fail(operr("operation error, because:%s", rsp.getError()));
return;
}
}
completion.success();
}
});
}
private void attachToKvmCluster(String clusterUuid, Completion completion) {
SimpleQuery<HostVO> q = dbf.createQuery(HostVO.class);
q.select(HostVO_.uuid);
q.add(HostVO_.clusterUuid, Op.EQ, clusterUuid);
q.add(HostVO_.status, Op.EQ, HostStatus.Connected);
List<String> hostUuids = q.listValue();
if (hostUuids.isEmpty()) {
completion.success();
} else {
createSecretOnKvmHosts(hostUuids, completion);
}
}
@Override
public void deleteHook() {
List<String> poolNameLists = list(
getDefaultRootVolumePoolName(),
getDefaultDataVolumePoolName(),
getDefaultImageCachePoolName()
);
SQL.New(CephPrimaryStoragePoolVO.class)
.in(CephPrimaryStoragePoolVO_.poolName, poolNameLists).delete();
if (CephGlobalConfig.PRIMARY_STORAGE_DELETE_POOL.value(Boolean.class)) {
DeletePoolCmd cmd = new DeletePoolCmd();
cmd.poolNames = poolNameLists;
FutureReturnValueCompletion completion = new FutureReturnValueCompletion(null);
httpCall(DELETE_POOL_PATH, cmd, DeletePoolRsp.class, completion);
completion.await(TimeUnit.MINUTES.toMillis(30));
if (!completion.isSuccess()) {
throw new OperationFailureException(completion.getErrorCode());
}
}
String fsid = getSelf().getFsid();
new SQLBatch(){
@Override
protected void scripts() {
if(Q.New(CephBackupStorageVO.class).eq(CephBackupStorageVO_.fsid, fsid).find() == null){
SQL.New(CephCapacityVO.class).eq(CephCapacityVO_.fsid, fsid).delete();
}
}
}.execute();
dbf.removeCollection(getSelf().getMons(), CephPrimaryStorageMonVO.class);
}
private void handle(CreateEmptyVolumeMsg msg) {
final CreateEmptyVolumeReply reply = new CreateEmptyVolumeReply();
final CreateEmptyVolumeCmd cmd = new CreateEmptyVolumeCmd();
cmd.installPath = msg.getInstallPath();
cmd.size = msg.getSize();
cmd.shareable = msg.isShareable();
cmd.skipIfExisting = msg.isSkipIfExisting();
httpCall(CREATE_VOLUME_PATH, cmd, CreateEmptyVolumeRsp.class, new ReturnValueCompletion<CreateEmptyVolumeRsp>(msg) {
@Override
public void fail(ErrorCode err) {
reply.setError(err);
bus.reply(msg, reply);
}
@Override
public void success(CreateEmptyVolumeRsp ret) {
bus.reply(msg, reply);
}
});
}
private void handle(CephToCephMigrateVolumeSegmentMsg msg) {
final CephToCephMigrateVolumeSegmentCmd cmd = new CephToCephMigrateVolumeSegmentCmd();
cmd.setParentUuid(msg.getParentUuid());
cmd.setResourceUuid(msg.getResourceUuid());
cmd.setSrcInstallPath(msg.getSrcInstallPath());
cmd.setDstInstallPath(msg.getDstInstallPath());
cmd.setDstMonHostname(msg.getDstMonHostname());
cmd.setDstMonSshUsername(msg.getDstMonSshUsername());
cmd.setDstMonSshPassword(msg.getDstMonSshPassword());
cmd.setDstMonSshPort(msg.getDstMonSshPort());
final CephToCephMigrateVolumeSegmentReply reply = new CephToCephMigrateVolumeSegmentReply();
httpCall(CEPH_TO_CEPH_MIGRATE_VOLUME_SEGMENT_PATH, cmd, StorageMigrationRsp.class, new ReturnValueCompletion<StorageMigrationRsp>(msg) {
@Override
public void success(StorageMigrationRsp returnValue) {
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
}, TimeUnit.MILLISECONDS, msg.getTimeout());
}
private void handle(GetVolumeSnapshotInfoMsg msg) {
final GetVolumeSnapInfosCmd cmd = new GetVolumeSnapInfosCmd();
cmd.setVolumePath(msg.getVolumePath());
final GetVolumeSnapshotInfoReply reply = new GetVolumeSnapshotInfoReply();
httpCall(GET_VOLUME_SNAPINFOS_PATH, cmd, GetVolumeSnapInfosRsp.class, new ReturnValueCompletion<GetVolumeSnapInfosRsp>(msg) {
@Override
public void success(GetVolumeSnapInfosRsp returnValue) {
reply.setSnapInfos(returnValue.getSnapInfos());
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
@Override
public void handle(AskInstallPathForNewSnapshotMsg msg) {
AskInstallPathForNewSnapshotReply reply = new AskInstallPathForNewSnapshotReply();
bus.reply(msg, reply);
}
@Override
protected void handle(CheckVolumeSnapshotsOnPrimaryStorageMsg msg) {
final CheckVolumeSnapshotsOnPrimaryStorageReply reply = new CheckVolumeSnapshotsOnPrimaryStorageReply();
CheckSnapshotCompletedCmd cmd = new CheckSnapshotCompletedCmd();
cmd.setVolumePath(msg.getVolumeInstallPath());
cmd.snapshots = msg.getSnapshots().stream().map(VolumeSnapshotInventory::getUuid).collect(Collectors.toList());
httpCall(CHECK_SNAPSHOT_COMPLETED, cmd, CheckSnapshotCompletedRsp.class, new ReturnValueCompletion<CheckSnapshotCompletedRsp>(msg) {
@Override
public void success(CheckSnapshotCompletedRsp returnValue) {
reply.setCompleted(returnValue.completed);
if (returnValue.completed) {
/**
* complete the new snapshot installpath
*/
VolumeSnapshotVO snapshot = dbf.findByUuid(returnValue.snapshotUuid, VolumeSnapshotVO.class);
snapshot.setStatus(VolumeSnapshotStatus.Ready);
snapshot.setPrimaryStorageInstallPath(msg.getVolumeInstallPath() + "@" + snapshot.getUuid());
snapshot.setSize(returnValue.size);
snapshot.setPrimaryStorageUuid(self.getUuid());
snapshot.setType(VolumeSnapshotConstant.STORAGE_SNAPSHOT_TYPE.toString());
snapshot.setFormat(VolumeConstant.VOLUME_FORMAT_RAW);
dbf.updateAndRefresh(snapshot);
reply.setSnapshotUuid(returnValue.snapshotUuid);
}
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
bus.reply(msg, reply);
}
@Override
protected void handle(GetVolumeSnapshotSizeOnPrimaryStorageMsg msg) {
GetVolumeSnapshotSizeOnPrimaryStorageReply reply = new GetVolumeSnapshotSizeOnPrimaryStorageReply();
VolumeSnapshotVO snapshotVO = dbf.findByUuid(msg.getSnapshotUuid(), VolumeSnapshotVO.class);
String installPath = snapshotVO.getPrimaryStorageInstallPath();
GetVolumeSnapshotSizeCmd cmd = new GetVolumeSnapshotSizeCmd();
cmd.fsId = getSelf().getFsid();
cmd.uuid = self.getUuid();
cmd.volumeSnapshotUuid = snapshotVO.getUuid();
cmd.installPath = installPath;
httpCall(GET_VOLUME_SNAPSHOT_SIZE_PATH, cmd, GetVolumeSnapshotSizeRsp.class, new ReturnValueCompletion<GetVolumeSnapshotSizeRsp>(msg) {
@Override
public void success(GetVolumeSnapshotSizeRsp rsp) {
reply.setActualSize(rsp.actualSize);
reply.setSize(rsp.size);
bus.reply(msg, reply);
}
@Override
public void fail(ErrorCode errorCode) {
reply.setError(errorCode);
bus.reply(msg, reply);
}
});
}
}
| add missing chain.next()
| plugin/ceph/src/main/java/org/zstack/storage/ceph/primary/CephPrimaryStorageBase.java | add missing chain.next() |
|
Java | apache-2.0 | 18801601c112354f47a992bf3dc3b2484801cc10 | 0 | raphw/byte-buddy,DALDEI/byte-buddy,raphw/byte-buddy,raphw/byte-buddy,CodingFabian/byte-buddy | package net.bytebuddy.agent;
import net.bytebuddy.test.utility.AgentAttachmentRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.Instrumentation;
import java.lang.reflect.Field;
import java.net.URL;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
public class ByteBuddyAgentInstallationTest {
@Rule
public MethodRule agentAttachmentRule = new AgentAttachmentRule();
@Before
public void setUp() throws Exception {
Field instrumentation = Installer.class.getDeclaredField("instrumentation");
instrumentation.setAccessible(true);
instrumentation.set(null, null);
}
@Test
@AgentAttachmentRule.Enforce
public void testAgentInstallation() throws Exception {
assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class));
}
@Test
@AgentAttachmentRule.Enforce
public void testAgentInstallationOtherClassLoader() throws Exception {
assertThat(new ClassLoader(null) {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
InputStream in = getResourceAsStream(name.replace('.', '/') + ".class");
if (in == null) {
throw new ClassNotFoundException(name);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
try {
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
} catch (IOException exception) {
throw new AssertionError(exception);
}
byte[] binaryRepresentation = out.toByteArray();
return defineClass(name, binaryRepresentation, 0, binaryRepresentation.length);
}
@Override
public InputStream getResourceAsStream(String name) {
return ByteBuddyAgentInstallationTest.class.getClassLoader().getResourceAsStream(name);
}
}.loadClass(ByteBuddyAgent.class.getName()).getDeclaredMethod("install").invoke(null), instanceOf(Instrumentation.class));
}
}
| byte-buddy-agent/src/test/java/net/bytebuddy/agent/ByteBuddyAgentInstallationTest.java | package net.bytebuddy.agent;
import net.bytebuddy.test.utility.AgentAttachmentRule;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.instrument.Instrumentation;
import java.net.URL;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
public class ByteBuddyAgentInstallationTest {
@Rule
public MethodRule agentAttachmentRule = new AgentAttachmentRule();
@Test
@AgentAttachmentRule.Enforce
public void testAgentInstallation() throws Exception {
assertThat(ByteBuddyAgent.install(), instanceOf(Instrumentation.class));
}
@Test
@AgentAttachmentRule.Enforce
public void testAgentInstallationOtherClassLoader() throws Exception {
assertThat(new ClassLoader(null) {
@Override
protected Class<?> findClass(String name) throws ClassNotFoundException {
InputStream in = getResourceAsStream(name.replace('.', '/') + ".class");
if (in == null) {
throw new ClassNotFoundException(name);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
try {
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
} catch (IOException exception) {
throw new AssertionError(exception);
}
byte[] binaryRepresentation = out.toByteArray();
return defineClass(name, binaryRepresentation, 0, binaryRepresentation.length);
}
@Override
public InputStream getResourceAsStream(String name) {
return ByteBuddyAgentInstallationTest.class.getClassLoader().getResourceAsStream(name);
}
}.loadClass(ByteBuddyAgent.class.getName()).getDeclaredMethod("install").invoke(null), instanceOf(Instrumentation.class));
}
}
| Improve test by forcing both attachment forms.
| byte-buddy-agent/src/test/java/net/bytebuddy/agent/ByteBuddyAgentInstallationTest.java | Improve test by forcing both attachment forms. |
|
Java | apache-2.0 | 18179de19556f4d2235a5264fe40a45dee149f3c | 0 | securny/syncope,giacomolm/syncope,giacomolm/syncope,giacomolm/syncope,NuwanSameera/syncope,apache/syncope,NuwanSameera/syncope,nscendoni/syncope,ilgrosso/syncope,securny/syncope,NuwanSameera/syncope,nscendoni/syncope,tmess567/syncope,tmess567/syncope,tmess567/syncope,nscendoni/syncope,nscendoni/syncope,apache/syncope,apache/syncope,tmess567/syncope,ilgrosso/syncope,ilgrosso/syncope,NuwanSameera/syncope,securny/syncope,giacomolm/syncope,apache/syncope,ilgrosso/syncope,securny/syncope | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.syncope.core.logic.init;
import java.io.StringWriter;
import java.util.Map;
import javax.sql.DataSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.syncope.common.lib.types.AnyTypeKind;
import org.apache.syncope.common.lib.types.CamelEntitlement;
import org.apache.syncope.core.misc.EntitlementsHolder;
import org.apache.syncope.core.misc.spring.ResourceWithFallbackLoader;
import org.apache.syncope.core.persistence.api.DomainsHolder;
import org.apache.syncope.core.persistence.api.SyncopeLoader;
import org.apache.syncope.core.persistence.api.entity.CamelRoute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSParser;
import org.w3c.dom.ls.LSSerializer;
@Component
public class CamelRouteLoader implements SyncopeLoader {
private static final Logger LOG = LoggerFactory.getLogger(CamelRouteLoader.class);
private static final boolean IS_JBOSS;
static {
IS_JBOSS = isJBoss();
}
private static boolean isJBoss() {
try {
Class.forName("org.jboss.vfs.VirtualFile");
LOG.debug("Running in JBoss AS / Wildfly, disabling {}", DOMImplementationRegistry.class.getName());
return true;
} catch (Throwable ex) {
LOG.debug("Not running in JBoss AS / Wildfly, enabling {}", DOMImplementationRegistry.class.getName());
return false;
}
}
@javax.annotation.Resource(name = "userRoutes")
private ResourceWithFallbackLoader userRoutesLoader;
@javax.annotation.Resource(name = "groupRoutes")
private ResourceWithFallbackLoader groupRoutesLoader;
@javax.annotation.Resource(name = "anyObjectRoutes")
private ResourceWithFallbackLoader anyObjectRoutesLoader;
@Autowired
private DomainsHolder domainsHolder;
@Override
public Integer getPriority() {
return 1000;
}
@Override
public void load() {
for (Map.Entry<String, DataSource> entry : domainsHolder.getDomains().entrySet()) {
loadRoutes(entry.getKey(), entry.getValue(),
userRoutesLoader.getResource(), AnyTypeKind.USER);
loadRoutes(entry.getKey(), entry.getValue(),
groupRoutesLoader.getResource(), AnyTypeKind.GROUP);
loadRoutes(entry.getKey(), entry.getValue(),
anyObjectRoutesLoader.getResource(), AnyTypeKind.ANY_OBJECT);
}
EntitlementsHolder.getInstance().init(CamelEntitlement.values());
}
private String nodeToString(final Node content, final DOMImplementationLS domImpl) {
StringWriter writer = new StringWriter();
try {
LSSerializer serializer = domImpl.createLSSerializer();
serializer.getDomConfig().setParameter("xml-declaration", false);
LSOutput lso = domImpl.createLSOutput();
lso.setCharacterStream(writer);
serializer.write(content, lso);
} catch (Exception e) {
LOG.debug("While serializing route node", e);
}
return writer.toString();
}
private String nodeToString(final Node content, final TransformerFactory tf) {
String output = StringUtils.EMPTY;
try {
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(content), new StreamResult(writer));
output = writer.getBuffer().toString();
} catch (TransformerException e) {
LOG.debug("While serializing route node", e);
}
return output;
}
private void loadRoutes(
final String domain, final DataSource dataSource, final Resource resource, final AnyTypeKind anyTypeKind) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
boolean shouldLoadRoutes = jdbcTemplate.queryForList(
String.format("SELECT * FROM %s WHERE ANYTYPEKIND = ?", CamelRoute.class.getSimpleName()),
new Object[] { anyTypeKind.name() }).
isEmpty();
if (shouldLoadRoutes) {
try {
TransformerFactory tf = null;
DOMImplementationLS domImpl = null;
NodeList routeNodes;
// When https://issues.jboss.org/browse/WFLY-4416 is resolved, this is not needed any more
if (IS_JBOSS) {
tf = TransformerFactory.newInstance();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(resource.getInputStream());
routeNodes = doc.getDocumentElement().getElementsByTagName("route");
} else {
DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
domImpl = (DOMImplementationLS) reg.getDOMImplementation("LS");
LSInput lsinput = domImpl.createLSInput();
lsinput.setByteStream(resource.getInputStream());
LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
routeNodes = parser.parse(lsinput).getDocumentElement().getElementsByTagName("route");
}
for (int s = 0; s < routeNodes.getLength(); s++) {
Node routeElement = routeNodes.item(s);
String routeContent = IS_JBOSS
? nodeToString(routeNodes.item(s), tf)
: nodeToString(routeNodes.item(s), domImpl);
String routeId = ((Element) routeElement).getAttribute("id");
jdbcTemplate.update(
String.format("INSERT INTO %s(NAME, ANYTYPEKIND, CONTENT) VALUES (?, ?, ?)",
CamelRoute.class.getSimpleName()),
new Object[] { routeId, anyTypeKind.name(), routeContent });
LOG.info("[{}] Route successfully loaded: {}", domain, routeId);
}
} catch (Exception e) {
LOG.error("[{}] Route load failed", domain, e);
}
}
}
}
| ext/camel/logic/src/main/java/org/apache/syncope/core/logic/init/CamelRouteLoader.java | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.syncope.core.logic.init;
import java.io.StringWriter;
import java.util.Map;
import javax.sql.DataSource;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.lang3.StringUtils;
import org.apache.syncope.common.lib.types.AnyTypeKind;
import org.apache.syncope.common.lib.types.CamelEntitlement;
import org.apache.syncope.core.misc.EntitlementsHolder;
import org.apache.syncope.core.misc.spring.ResourceWithFallbackLoader;
import org.apache.syncope.core.persistence.api.DomainsHolder;
import org.apache.syncope.core.persistence.api.SyncopeLoader;
import org.apache.syncope.core.persistence.api.entity.CamelRoute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSInput;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSParser;
import org.w3c.dom.ls.LSSerializer;
@Component
public class CamelRouteLoader implements SyncopeLoader {
private static final Logger LOG = LoggerFactory.getLogger(CamelRouteLoader.class);
private static final boolean IS_JBOSS;
static {
IS_JBOSS = isJBoss();
}
private static boolean isJBoss() {
try {
Class.forName("org.jboss.vfs.VirtualFile");
return true;
} catch (Throwable ex) {
return false;
}
}
@javax.annotation.Resource(name = "userRoutes")
private ResourceWithFallbackLoader userRoutesLoader;
@javax.annotation.Resource(name = "groupRoutes")
private ResourceWithFallbackLoader groupRoutesLoader;
@javax.annotation.Resource(name = "anyObjectRoutes")
private ResourceWithFallbackLoader anyObjectRoutesLoader;
@Autowired
private DomainsHolder domainsHolder;
@Override
public Integer getPriority() {
return 1000;
}
@Override
public void load() {
for (Map.Entry<String, DataSource> entry : domainsHolder.getDomains().entrySet()) {
loadRoutes(entry.getKey(), entry.getValue(),
userRoutesLoader.getResource(), AnyTypeKind.USER);
loadRoutes(entry.getKey(), entry.getValue(),
groupRoutesLoader.getResource(), AnyTypeKind.GROUP);
loadRoutes(entry.getKey(), entry.getValue(),
anyObjectRoutesLoader.getResource(), AnyTypeKind.ANY_OBJECT);
}
EntitlementsHolder.getInstance().init(CamelEntitlement.values());
}
private String nodeToString(final Node content, final DOMImplementationLS domImpl) {
StringWriter writer = new StringWriter();
try {
LSSerializer serializer = domImpl.createLSSerializer();
serializer.getDomConfig().setParameter("xml-declaration", false);
LSOutput lso = domImpl.createLSOutput();
lso.setCharacterStream(writer);
serializer.write(content, lso);
} catch (Exception e) {
LOG.debug("While serializing route node", e);
}
return writer.toString();
}
private String nodeToString(final Node content, final TransformerFactory tf) {
String output = StringUtils.EMPTY;
try {
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter writer = new StringWriter();
transformer.transform(new DOMSource(content), new StreamResult(writer));
output = writer.getBuffer().toString();
} catch (TransformerException e) {
LOG.debug("While serializing route node", e);
}
return output;
}
private void loadRoutes(
final String domain, final DataSource dataSource, final Resource resource, final AnyTypeKind anyTypeKind) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
boolean shouldLoadRoutes = jdbcTemplate.queryForList(
String.format("SELECT * FROM %s WHERE ANYTYPEKIND = ?", CamelRoute.class.getSimpleName()),
new Object[] { anyTypeKind.name() }).
isEmpty();
if (shouldLoadRoutes) {
try {
TransformerFactory tf = null;
DOMImplementationLS domImpl = null;
NodeList routeNodes;
// When https://issues.jboss.org/browse/WFLY-4416 is resolved, this is not needed any more
if (IS_JBOSS) {
tf = TransformerFactory.newInstance();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(resource.getInputStream());
routeNodes = doc.getDocumentElement().getElementsByTagName("route");
} else {
DOMImplementationRegistry reg = DOMImplementationRegistry.newInstance();
domImpl = (DOMImplementationLS) reg.getDOMImplementation("LS");
LSInput lsinput = domImpl.createLSInput();
lsinput.setByteStream(resource.getInputStream());
LSParser parser = domImpl.createLSParser(DOMImplementationLS.MODE_SYNCHRONOUS, null);
routeNodes = parser.parse(lsinput).getDocumentElement().getElementsByTagName("route");
}
for (int s = 0; s < routeNodes.getLength(); s++) {
Node routeElement = routeNodes.item(s);
String routeContent = IS_JBOSS
? nodeToString(routeNodes.item(s), tf)
: nodeToString(routeNodes.item(s), domImpl);
String routeId = ((Element) routeElement).getAttribute("id");
jdbcTemplate.update(
String.format("INSERT INTO %s(NAME, ANYTYPEKIND, CONTENT) VALUES (?, ?, ?)",
CamelRoute.class.getSimpleName()),
new Object[] { routeId, anyTypeKind.name(), routeContent });
LOG.info("[{}] Route successfully loaded: {}", domain, routeId);
}
} catch (Exception e) {
LOG.error("[{}] Route load failed", domain, e);
}
}
}
}
| [SYNCOPE-738] Adding some logging
| ext/camel/logic/src/main/java/org/apache/syncope/core/logic/init/CamelRouteLoader.java | [SYNCOPE-738] Adding some logging |
|
Java | apache-2.0 | bd7cc4e60fcefa7140b536d41a74a4263e155edc | 0 | dbrimley/hazelcast,emre-aydin/hazelcast,tkountis/hazelcast,tufangorel/hazelcast,mesutcelik/hazelcast,mdogan/hazelcast,mdogan/hazelcast,tkountis/hazelcast,tkountis/hazelcast,dbrimley/hazelcast,dsukhoroslov/hazelcast,tufangorel/hazelcast,emre-aydin/hazelcast,mdogan/hazelcast,mesutcelik/hazelcast,Donnerbart/hazelcast,juanavelez/hazelcast,dbrimley/hazelcast,emre-aydin/hazelcast,Donnerbart/hazelcast,Donnerbart/hazelcast,dsukhoroslov/hazelcast,juanavelez/hazelcast,tufangorel/hazelcast,mesutcelik/hazelcast | /*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.discovery;
import com.hazelcast.aws.AwsDiscoveryStrategyFactory;
import com.hazelcast.aws.AwsProperties;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientAwsConfig;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.config.ClientNetworkConfig;
import com.hazelcast.client.spi.impl.AwsAddressProvider;
import com.hazelcast.client.spi.properties.ClientProperty;
import com.hazelcast.config.DiscoveryStrategyConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.nio.Address;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.SlowTest;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static com.hazelcast.aws.AwsProperties.CONNECTION_TIMEOUT_SECONDS;
import static com.hazelcast.aws.AwsProperties.PORT;
import static com.hazelcast.aws.AwsProperties.TAG_KEY;
import static com.hazelcast.aws.AwsProperties.TAG_VALUE;
import static com.hazelcast.test.JenkinsDetector.isOnJenkins;
import static com.hazelcast.util.CollectionUtil.isNotEmpty;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeThat;
/**
* NOTE: This tests needs AWS credentials to be set as environment variables!
* <p>
* Please set {@code AWS_ACCESS_KEY_ID} and {@code AWS_SECRET_ACCESS_KEY} with the according values.
*/
@RunWith(HazelcastParallelClassRunner.class)
@Category({SlowTest.class, ParallelTest.class})
public class AwsCloudDiscoveryTest {
private static final String ACCESS_KEY = AwsProperties.ACCESS_KEY.getDefinition().key();
private static final String SECRET_KEY = AwsProperties.SECRET_KEY.getDefinition().key();
private static final String AWS_TEST_TAG = "aws-test-tag";
private static final String AWS_TEST_TAG_VALUE = "aws-tag-value-1";
@Test
public void testAwsClient_MemberNonDefaultPortConfig() {
Map<String, Comparable> props = new HashMap<String, Comparable>();
props.put(PORT.getDefinition().key(), "60000");
props.put(ACCESS_KEY, System.getenv("AWS_ACCESS_KEY_ID"));
props.put(SECRET_KEY, System.getenv("AWS_SECRET_ACCESS_KEY"));
props.put(TAG_KEY.getDefinition().key(), AWS_TEST_TAG);
props.put(TAG_VALUE.getDefinition().key(), AWS_TEST_TAG_VALUE);
props.put(CONNECTION_TIMEOUT_SECONDS.getDefinition().key(), "10");
if (isOnJenkins()) {
assertNotNull("AWS_ACCESS_KEY_ID is not set", props.get(ACCESS_KEY));
assertNotNull("AWS_SECRET_ACCESS_KEY is not set", props.get(SECRET_KEY));
} else {
assumeThat("AWS_ACCESS_KEY_ID is not set", props.get(ACCESS_KEY), Matchers.<Comparable>notNullValue());
assumeThat("AWS_SECRET_ACCESS_KEY is not set", props.get(SECRET_KEY), Matchers.<Comparable>notNullValue());
}
ClientConfig config = new ClientConfig();
config.getNetworkConfig().getDiscoveryConfig()
.addDiscoveryStrategyConfig(new DiscoveryStrategyConfig(new AwsDiscoveryStrategyFactory(), props));
config.setProperty(ClientProperty.DISCOVERY_SPI_ENABLED.getName(), "true");
config.setProperty(ClientProperty.DISCOVERY_SPI_PUBLIC_IP_ENABLED.getName(), "true");
HazelcastInstance client = HazelcastClient.newHazelcastClient(config);
IMap<Object, Object> map = client.getMap("MyMap");
map.put(1, 5);
assertEquals(5, map.get(1));
}
@Test
public void testAwsAddressProvider() {
ClientConfig clientConfig = new ClientConfig();
ClientAwsConfig clientAwsConfig = new ClientAwsConfig();
String awsAccessKeyId = System.getenv("AWS_ACCESS_KEY_ID");
String awsSecretAccessKey = System.getenv("AWS_SECRET_ACCESS_KEY");
if (isOnJenkins()) {
assertNotNull("AWS_ACCESS_KEY_ID is not set", awsAccessKeyId);
assertNotNull("AWS_SECRET_ACCESS_KEY is not set", awsSecretAccessKey);
clientAwsConfig.setInsideAws(true);
} else {
assumeThat("AWS_ACCESS_KEY_ID is not set", awsAccessKeyId, Matchers.<String>notNullValue());
assumeThat("AWS_SECRET_ACCESS_KEY is not set", awsSecretAccessKey, Matchers.<String>notNullValue());
clientAwsConfig.setInsideAws(false);
}
ClientNetworkConfig clientNetworkConfig = clientConfig.getNetworkConfig();
clientNetworkConfig.setAwsConfig(clientAwsConfig);
clientAwsConfig.setEnabled(true)
.setAccessKey(awsAccessKeyId)
.setSecretKey(awsSecretAccessKey)
.setTagKey(AWS_TEST_TAG)
.setTagValue(AWS_TEST_TAG_VALUE);
HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
IMap<Object, Object> map = client.getMap("MyMap");
map.put(1, 5);
assertEquals(5, map.get(1));
AwsAddressProvider awsAddressProvider = new AwsAddressProvider(clientAwsConfig, client.getLoggingService());
Collection<Address> addresses = awsAddressProvider.loadAddresses();
assertTrue(isNotEmpty(addresses));
}
}
| hazelcast-client/src/test/java/com/hazelcast/client/discovery/AwsCloudDiscoveryTest.java | /*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.client.discovery;
import com.hazelcast.aws.AwsDiscoveryStrategyFactory;
import com.hazelcast.aws.AwsProperties;
import com.hazelcast.client.HazelcastClient;
import com.hazelcast.client.config.ClientAwsConfig;
import com.hazelcast.client.config.ClientConfig;
import com.hazelcast.client.config.ClientNetworkConfig;
import com.hazelcast.client.spi.impl.AwsAddressProvider;
import com.hazelcast.client.spi.properties.ClientProperty;
import com.hazelcast.config.DiscoveryStrategyConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.nio.Address;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.annotation.ParallelTest;
import com.hazelcast.test.annotation.SlowTest;
import com.hazelcast.util.CollectionUtil;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static com.hazelcast.aws.AwsProperties.CONNECTION_TIMEOUT_SECONDS;
import static com.hazelcast.aws.AwsProperties.PORT;
import static com.hazelcast.aws.AwsProperties.TAG_KEY;
import static com.hazelcast.aws.AwsProperties.TAG_VALUE;
import static com.hazelcast.test.JenkinsDetector.isOnJenkins;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assume.assumeThat;
/**
* NOTE: This tests needs AWS credentials to be set as environment variables!
* <p>
* Please set {@code AWS_ACCESS_KEY_ID} and {@code AWS_SECRET_ACCESS_KEY} with the according values.
*/
@RunWith(HazelcastParallelClassRunner.class)
@Category({SlowTest.class, ParallelTest.class})
public class AwsCloudDiscoveryTest {
private static final String ACCESS_KEY = AwsProperties.ACCESS_KEY.getDefinition().key();
private static final String SECRET_KEY = AwsProperties.SECRET_KEY.getDefinition().key();
private static final String AWS_TEST_TAG = "aws-test-tag";
private static final String AWS_TEST_TAG_VALUE = "aws-tag-value-1";
@Test
public void testAwsClient_MemberNonDefaultPortConfig() {
Map<String, Comparable> props = new HashMap<String, Comparable>();
props.put(PORT.getDefinition().key(), "60000");
props.put(ACCESS_KEY, System.getenv("AWS_ACCESS_KEY_ID"));
props.put(SECRET_KEY, System.getenv("AWS_SECRET_ACCESS_KEY"));
props.put(TAG_KEY.getDefinition().key(), AWS_TEST_TAG);
props.put(TAG_VALUE.getDefinition().key(), AWS_TEST_TAG_VALUE);
props.put(CONNECTION_TIMEOUT_SECONDS.getDefinition().key(), "10");
if (isOnJenkins()) {
assertNotNull("AWS_ACCESS_KEY_ID is not set", props.get(ACCESS_KEY));
assertNotNull("AWS_SECRET_ACCESS_KEY is not set", props.get(SECRET_KEY));
} else {
assumeThat("AWS_ACCESS_KEY_ID is not set", props.get(ACCESS_KEY), Matchers.<Comparable>notNullValue());
assumeThat("AWS_SECRET_ACCESS_KEY is not set", props.get(SECRET_KEY), Matchers.<Comparable>notNullValue());
}
ClientConfig config = new ClientConfig();
config.getNetworkConfig().getDiscoveryConfig()
.addDiscoveryStrategyConfig(new DiscoveryStrategyConfig(new AwsDiscoveryStrategyFactory(), props));
config.setProperty(ClientProperty.DISCOVERY_SPI_ENABLED.getName(), "true");
config.setProperty(ClientProperty.DISCOVERY_SPI_PUBLIC_IP_ENABLED.getName(), "true");
HazelcastInstance client = HazelcastClient.newHazelcastClient(config);
IMap<Object, Object> map = client.getMap("MyMap");
map.put(1, 5);
assertEquals(5, map.get(1));
}
@Test
public void testAwsAddressProvider() {
ClientConfig clientConfig = new ClientConfig();
ClientAwsConfig clientAwsConfig = new ClientAwsConfig();
String awsAccessKeyId = System.getenv("AWS_ACCESS_KEY_ID");
String awsSecretAccessKey = System.getenv("AWS_SECRET_ACCESS_KEY");
if (isOnJenkins()) {
assertNotNull("AWS_ACCESS_KEY_ID is not set", awsAccessKeyId);
assertNotNull("AWS_SECRET_ACCESS_KEY is not set", awsSecretAccessKey);
clientAwsConfig.setInsideAws(true);
} else {
assumeThat("AWS_ACCESS_KEY_ID is not set", awsAccessKeyId, Matchers.<Comparable>notNullValue());
assumeThat("AWS_SECRET_ACCESS_KEY is not set", awsSecretAccessKey, Matchers.<Comparable>notNullValue());
clientAwsConfig.setInsideAws(false);
}
ClientNetworkConfig clientNetworkConfig = clientConfig.getNetworkConfig();
clientNetworkConfig.setAwsConfig(clientAwsConfig);
clientAwsConfig.setEnabled(true).setAccessKey(awsAccessKeyId)
.setSecretKey(awsSecretAccessKey).setTagKey(AWS_TEST_TAG)
.setTagValue(AWS_TEST_TAG_VALUE);
HazelcastInstance client = HazelcastClient.newHazelcastClient(clientConfig);
IMap<Object, Object> map = client.getMap("MyMap");
map.put(1, 5);
assertEquals(5, map.get(1));
AwsAddressProvider awsAddressProvider = new AwsAddressProvider(clientAwsConfig, client.getLoggingService());
Collection<Address> addresses = awsAddressProvider.loadAddresses();
CollectionUtil.isNotEmpty(addresses);
}
}
| Small cleanup of AwsCloudDiscoveryTest
| hazelcast-client/src/test/java/com/hazelcast/client/discovery/AwsCloudDiscoveryTest.java | Small cleanup of AwsCloudDiscoveryTest |
|
Java | bsd-2-clause | 841d699c32c729794a70508cd9b6d7bedfe2beb1 | 0 | chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio | /*
* Copyright (c) 2003-2004, jMonkeyEngine - Mojo Monkey Coding
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the Mojo Monkey Coding, jME, jMonkey Engine, nor the
* names of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package com.jme.scene;
import java.io.Serializable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.logging.Level;
import java.util.ArrayList;
import com.jme.intersection.CollisionData;
import com.jme.intersection.CollisionResults;
import com.jme.math.Vector2f;
import com.jme.math.Vector3f;
import com.jme.math.Matrix3f;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.Renderer;
import com.jme.system.JmeException;
import com.jme.util.LoggingSystem;
import com.jme.bounding.OBBTree;
/**
* <code>TriMesh</code> defines a geometry mesh. This mesh defines a three
* dimensional object via a collection of points, colors, normals and textures.
* The points are referenced via a indices array. This array instructs the
* renderer the order in which to draw the points, creating triangles on every
* three points.
*
* @author Mark Powell
* @version $Id: TriMesh.java,v 1.29 2004-09-10 23:59:05 mojomonkey Exp $
*/
public class TriMesh extends Geometry implements Serializable {
protected int[] indices;
private transient IntBuffer indexBuffer;
protected int triangleQuantity = -1;
/** This tree is only built on calls too updateCollisionTree. */
private OBBTree collisionTree;
/** This is and should only be used by collision detection. */
private Matrix3f worldMatrot;
/**
* Empty Constructor to be used internally only.
*/
public TriMesh() {
}
/**
* Constructor instantiates a new <code>TriMesh</code> object.
*
* @param name
* the name of the scene element. This is required for
* identification and comparision purposes.
*/
public TriMesh(String name) {
super(name);
}
/**
* Constructor instantiates a new <code>TriMesh</code> object. Provided
* are the attributes that make up the mesh all attributes may be null,
* except for vertices and indices.
*
* @param name
* the name of the scene element. This is required for
* identification and comparision purposes.
* @param vertices
* the vertices of the geometry.
* @param normal
* the normals of the geometry.
* @param color
* the colors of the geometry.
* @param texture
* the texture coordinates of the mesh.
* @param indices
* the indices of the vertex array.
*/
public TriMesh(String name, Vector3f[] vertices, Vector3f[] normal,
ColorRGBA[] color, Vector2f[] texture, int[] indices) {
super(name, vertices, normal, color, texture);
if (null == indices) {
LoggingSystem.getLogger().log(Level.WARNING,
"Indices may not be" + " null.");
throw new JmeException("Indices may not be null.");
}
this.indices = indices;
triangleQuantity = indices.length / 3;
updateIndexBuffer();
LoggingSystem.getLogger().log(Level.INFO, "TriMesh created.");
}
/**
* Recreates the geometric information of this TriMesh from scratch. The
* index and vertex array must not be null, but the others may be. Every 3
* indices define an index in the <code>vertices</code> array that
* refrences a vertex of a triangle.
*
* @param vertices
* The vertex information for this TriMesh.
* @param normal
* The normal information for this TriMesh.
* @param color
* The color information for this TriMesh.
* @param texture
* The texture information for this TriMesh.
* @param indices
* The index information for this TriMesh.
* @see #reconstruct(com.jme.math.Vector3f[], com.jme.math.Vector3f[],
* com.jme.renderer.ColorRGBA[], com.jme.math.Vector2f[])
*/
public void reconstruct(Vector3f[] vertices, Vector3f[] normal,
ColorRGBA[] color, Vector2f[] texture, int[] indices) {
super.reconstruct(vertices, normal, color, texture);
if (null == indices) {
LoggingSystem.getLogger().log(Level.WARNING,
"Indices may not be" + " null.");
throw new JmeException("Indices may not be null.");
}
this.indices = indices;
triangleQuantity = indices.length / 3;
updateIndexBuffer();
LoggingSystem.getLogger().log(Level.INFO, "TriMesh reconstructed.");
}
/**
*
* <code>getIndices</code> retrieves the indices into the vertex array.
*
* @return the indices into the vertex array.
*/
public int[] getIndices() {
return indices;
}
/**
*
* <code>getIndexAsBuffer</code> retrieves the indices array as an
* <code>IntBuffer</code>.
*
* @return the indices array as an <code>IntBuffer</code>.
*/
public IntBuffer getIndexAsBuffer() {
return indexBuffer;
}
/**
* Stores in the <code>storage</code> array the indices of triangle
* <code>i</code>. If <code>i</code> is an invalid index, or if
* <code>storage.length!=3</code>, then nothing happens
*
* @param i
* The index of the triangle to get.
* @param storage
* The array that will hold the i's indexes.
*/
public void getTriangle(int i, int[] storage) {
if (i < triangleQuantity && storage.length == 3) {
int iBase = 3 * i;
storage[0] = indices[iBase++];
storage[1] = indices[iBase++];
storage[2] = indices[iBase];
}
}
/**
* Stores in the <code>vertices</code> array the vertex values of triangle
* <code>i</code>. If <code>i</code> is an invalid triangle index,
* nothing happens.
*
* @param i
* @param vertices
*/
public void getTriangle(int i, Vector3f[] vertices) {
//System.out.println(i + ", " + triangleQuantity);
if (i < triangleQuantity && i >= 0) {
int iBase = 3 * i;
vertices[0] = vertex[indices[iBase++]];
vertices[1] = vertex[indices[iBase++]];
vertices[2] = vertex[indices[iBase]];
}
}
/**
* Returns the number of triangles this TriMesh contains.
*
* @return The current number of triangles.
*/
public int getTriangleQuantity() {
return triangleQuantity;
}
/**
*
* <code>setIndices</code> sets the index array for this
* <code>TriMesh</code>.
*
* @param indices
* the index array.
*/
public void setIndices(int[] indices) {
this.indices = indices;
triangleQuantity = indices.length / 3;
updateIndexBuffer();
}
/**
* <code>draw</code> calls super to set the render state then passes
* itself to the renderer.
*
* @param r
* the renderer to display
*/
public void draw(Renderer r) {
if (!r.isProcessingQueue()) {
if (r.checkAndAdd(this))
return;
}
super.draw(r);
r.draw(this);
}
/**
* <code>drawBounds</code> calls super to set the render state then passes
* itself to the renderer.
*
* @param r
* the renderer to display
*/
public void drawBounds(Renderer r) {
r.drawBounds(this);
}
/**
*
* <code>setIndexBuffers</code> creates the <code>IntBuffer</code> that
* contains the indices array.
*
*/
public void updateIndexBuffer() {
if (indices == null) {
return;
}
if (indexBuffer == null || indexBuffer.capacity() < indices.length) {
indexBuffer = ByteBuffer.allocateDirect(
4 * (triangleQuantity >= 0 ? triangleQuantity * 3
: indices.length)).order(ByteOrder.nativeOrder())
.asIntBuffer();
}
indexBuffer.clear();
indexBuffer.put(indices, 0,
triangleQuantity >= 0 ? triangleQuantity * 3 : indices.length);
indexBuffer.flip();
}
/**
* Clears the buffers of this TriMesh. The buffers include its indexBuffer,
* and all Geometry buffers.
*/
public void clearBuffers() {
super.clearBuffers();
indexBuffer = null;
}
/**
* Sets this geometry's index buffer as a refrence to the passed
* <code>IntBuffer</code>. Incorrectly built IntBuffers can have
* undefined results. Use with care.
*
* @param toSet
* The <code>IntBuffer</code> to set this geometry's index
* buffer to
*/
public void setIndexBuffer(IntBuffer toSet) {
indexBuffer = toSet;
}
/**
* Used with Serialization. Do not call this directly.
*
* @param in
* @throws IOException
* @throws ClassNotFoundException
* @see java.io.Serializable
*/
private void readObject(java.io.ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
updateIndexBuffer();
}
/**
* This function creates a collision tree from the TriMesh's current
* information. If the information changes, the tree needs to be updated.
*/
public void updateCollisionTree() {
if (collisionTree == null)
collisionTree = new OBBTree();
collisionTree.construct(this);
}
/**
* determines if this TriMesh has made contact with the give scene. The
* scene is recursively transversed until a trimesh is found, at which time
* the two trimesh OBBTrees are then compared to find the triangles that
* hit.
*/
public void hasCollision(Spatial scene, CollisionResults results) {
if (this == scene) {
return;
}
if (getWorldBound().intersects(scene.getWorldBound())) {
if ((scene instanceof Node)) {
Node parent = (Node) scene;
for (int i = 0; i < parent.getQuantity(); i++) {
hasCollision(parent.getChild(i), results);
}
} else {
ArrayList a = new ArrayList();
ArrayList b = new ArrayList();
//find the triangle that is being hit.
//add this node and the triangle to the CollisionResults list.
findIntersectionTriangles((TriMesh) scene, a, b);
CollisionData data = new CollisionData((TriMesh) scene, a, b);
results.addCollisionData(data);
}
}
}
/**
* This function checks for intersection between this trimesh and the given
* one. On the first intersection, true is returned.
*
* @param toCheck
* The intersection testing mesh.
* @return True if they intersect.
*/
public boolean hasTriangleCollision(TriMesh toCheck) {
if (collisionTree == null || toCheck.collisionTree == null)
return false;
else {
if (worldMatrot == null)
worldMatrot = worldRotation.toRotationMatrix();
else
worldMatrot = worldRotation.toRotationMatrix(worldMatrot);
collisionTree.bounds.transform(worldMatrot, worldTranslation,
worldScale, collisionTree.worldBounds);
toCheck.worldMatrot = toCheck.worldRotation.toRotationMatrix();
return collisionTree.intersect(toCheck.collisionTree);
}
}
/**
* This function finds all intersections between this trimesh and the
* checking one. The intersections are stored as Integer objects of Triangle
* indexes in each of the parameters.
*
* @param toCheck
* The TriMesh to check.
* @param thisIndex
* The array of triangle indexes intersecting in this mesh.
* @param otherIndex
* The array of triangle indexes intersecting in the given mesh.
*/
public void findIntersectionTriangles(TriMesh toCheck, ArrayList thisIndex,
ArrayList otherIndex) {
if (collisionTree == null || toCheck.collisionTree == null)
return;
else {
if (worldMatrot == null)
worldMatrot = worldRotation.toRotationMatrix();
else
worldMatrot = worldRotation.toRotationMatrix(worldMatrot);
collisionTree.bounds.transform(worldMatrot, worldTranslation,
worldScale, collisionTree.worldBounds);
toCheck.worldMatrot = toCheck.worldRotation.toRotationMatrix();
collisionTree.intersect(toCheck.collisionTree, thisIndex,
otherIndex);
}
}
/**
* This function is <b>ONLY </b> to be used by the intersection testing
* code. It should not be called by users. It returns a matrix3f
* representation of the mesh's world rotation.
*
* @return This mesh's world rotation.
*/
public Matrix3f findWorldRotMat() {
return worldMatrot;
}
} | src/com/jme/scene/TriMesh.java | /*
* Copyright (c) 2003-2004, jMonkeyEngine - Mojo Monkey Coding
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the Mojo Monkey Coding, jME, jMonkey Engine, nor the
* names of its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
package com.jme.scene;
import java.io.Serializable;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.util.logging.Level;
import java.util.ArrayList;
import com.jme.intersection.CollisionData;
import com.jme.intersection.CollisionResults;
import com.jme.math.Vector2f;
import com.jme.math.Vector3f;
import com.jme.math.Matrix3f;
import com.jme.renderer.ColorRGBA;
import com.jme.renderer.Renderer;
import com.jme.system.JmeException;
import com.jme.util.LoggingSystem;
import com.jme.bounding.OBBTree;
/**
* <code>TriMesh</code> defines a geometry mesh. This mesh defines a three
* dimensional object via a collection of points, colors, normals and textures.
* The points are referenced via a indices array. This array instructs the
* renderer the order in which to draw the points, creating triangles on every
* three points.
*
* @author Mark Powell
* @version $Id: TriMesh.java,v 1.28 2004-09-10 22:36:10 mojomonkey Exp $
*/
public class TriMesh extends Geometry implements Serializable {
protected int[] indices;
private transient IntBuffer indexBuffer;
protected int triangleQuantity = -1;
/** This tree is only built on calls too updateCollisionTree. */
private OBBTree collisionTree;
/** This is and should only be used by collision detection. */
private Matrix3f worldMatrot;
/**
* Empty Constructor to be used internally only.
*/
public TriMesh() {
}
/**
* Constructor instantiates a new <code>TriMesh</code> object.
*
* @param name
* the name of the scene element. This is required for
* identification and comparision purposes.
*/
public TriMesh(String name) {
super(name);
}
/**
* Constructor instantiates a new <code>TriMesh</code> object. Provided
* are the attributes that make up the mesh all attributes may be null,
* except for vertices and indices.
*
* @param name
* the name of the scene element. This is required for
* identification and comparision purposes.
* @param vertices
* the vertices of the geometry.
* @param normal
* the normals of the geometry.
* @param color
* the colors of the geometry.
* @param texture
* the texture coordinates of the mesh.
* @param indices
* the indices of the vertex array.
*/
public TriMesh(String name, Vector3f[] vertices, Vector3f[] normal,
ColorRGBA[] color, Vector2f[] texture, int[] indices) {
super(name, vertices, normal, color, texture);
if (null == indices) {
LoggingSystem.getLogger().log(Level.WARNING,
"Indices may not be" + " null.");
throw new JmeException("Indices may not be null.");
}
this.indices = indices;
triangleQuantity = indices.length / 3;
updateIndexBuffer();
LoggingSystem.getLogger().log(Level.INFO, "TriMesh created.");
}
/**
* Recreates the geometric information of this TriMesh from scratch. The
* index and vertex array must not be null, but the others may be. Every 3
* indices define an index in the <code>vertices</code> array that
* refrences a vertex of a triangle.
*
* @param vertices
* The vertex information for this TriMesh.
* @param normal
* The normal information for this TriMesh.
* @param color
* The color information for this TriMesh.
* @param texture
* The texture information for this TriMesh.
* @param indices
* The index information for this TriMesh.
* @see #reconstruct(com.jme.math.Vector3f[], com.jme.math.Vector3f[],
* com.jme.renderer.ColorRGBA[], com.jme.math.Vector2f[])
*/
public void reconstruct(Vector3f[] vertices, Vector3f[] normal,
ColorRGBA[] color, Vector2f[] texture, int[] indices) {
super.reconstruct(vertices, normal, color, texture);
if (null == indices) {
LoggingSystem.getLogger().log(Level.WARNING,
"Indices may not be" + " null.");
throw new JmeException("Indices may not be null.");
}
this.indices = indices;
triangleQuantity = indices.length / 3;
updateIndexBuffer();
LoggingSystem.getLogger().log(Level.INFO, "TriMesh reconstructed.");
}
/**
*
* <code>getIndices</code> retrieves the indices into the vertex array.
*
* @return the indices into the vertex array.
*/
public int[] getIndices() {
return indices;
}
/**
*
* <code>getIndexAsBuffer</code> retrieves the indices array as an
* <code>IntBuffer</code>.
*
* @return the indices array as an <code>IntBuffer</code>.
*/
public IntBuffer getIndexAsBuffer() {
return indexBuffer;
}
/**
* Stores in the <code>storage</code> array the indices of triangle
* <code>i</code>. If <code>i</code> is an invalid index, or if
* <code>storage.length!=3</code>, then nothing happens
*
* @param i
* The index of the triangle to get.
* @param storage
* The array that will hold the i's indexes.
*/
public void getTriangle(int i, int[] storage) {
if (i < triangleQuantity && storage.length == 3) {
int iBase = 3 * i;
storage[0] = indices[iBase++];
storage[1] = indices[iBase++];
storage[2] = indices[iBase];
}
}
/**
* Stores in the <code>vertices</code> array the vertex values of triangle
* <code>i</code>. If <code>i</code> is an invalid triangle index,
* nothing happens.
*
* @param i
* @param vertices
*/
public void getTriangle(int i, Vector3f[] vertices) {
//System.out.println(i + ", " + triangleQuantity);
if (i < triangleQuantity && i >= 0) {
int iBase = 3 * i;
vertices[0] = vertex[indices[iBase++]];
vertices[1] = vertex[indices[iBase++]];
vertices[2] = vertex[indices[iBase]];
}
}
/**
* Returns the number of triangles this TriMesh contains.
*
* @return The current number of triangles.
*/
public int getTriangleQuantity() {
return triangleQuantity;
}
/**
*
* <code>setIndices</code> sets the index array for this
* <code>TriMesh</code>.
*
* @param indices
* the index array.
*/
public void setIndices(int[] indices) {
this.indices = indices;
triangleQuantity = indices.length / 3;
updateIndexBuffer();
}
/**
* <code>draw</code> calls super to set the render state then passes
* itself to the renderer.
*
* @param r
* the renderer to display
*/
public void draw(Renderer r) {
if (!r.isProcessingQueue()) {
if (r.checkAndAdd(this))
return;
}
super.draw(r);
r.draw(this);
}
/**
* <code>drawBounds</code> calls super to set the render state then passes
* itself to the renderer.
*
* @param r
* the renderer to display
*/
public void drawBounds(Renderer r) {
r.drawBounds(this);
}
/**
*
* <code>setIndexBuffers</code> creates the <code>IntBuffer</code> that
* contains the indices array.
*
*/
public void updateIndexBuffer() {
if (indices == null) {
return;
}
if (indexBuffer == null || indexBuffer.capacity() < indices.length) {
indexBuffer = ByteBuffer.allocateDirect(
4 * (triangleQuantity >= 0 ? triangleQuantity * 3
: indices.length)).order(ByteOrder.nativeOrder())
.asIntBuffer();
}
indexBuffer.clear();
indexBuffer.put(indices, 0,
triangleQuantity >= 0 ? triangleQuantity * 3 : indices.length);
indexBuffer.flip();
}
/**
* Clears the buffers of this TriMesh. The buffers include its indexBuffer,
* and all Geometry buffers.
*/
public void clearBuffers() {
super.clearBuffers();
indexBuffer = null;
}
/**
* Sets this geometry's index buffer as a refrence to the passed
* <code>IntBuffer</code>. Incorrectly built IntBuffers can have
* undefined results. Use with care.
*
* @param toSet
* The <code>IntBuffer</code> to set this geometry's index
* buffer to
*/
public void setIndexBuffer(IntBuffer toSet) {
indexBuffer = toSet;
}
/**
* Used with Serialization. Do not call this directly.
*
* @param in
* @throws IOException
* @throws ClassNotFoundException
* @see java.io.Serializable
*/
private void readObject(java.io.ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
updateIndexBuffer();
}
/**
* This function creates a collision tree from the TriMesh's current
* information. If the information changes, the tree needs to be updated.
*/
public void updateCollisionTree() {
if (collisionTree == null)
collisionTree = new OBBTree();
collisionTree.construct(this);
}
/**
* determines if this TriMesh has made contact with the give scene. The
* scene is recursively transversed until a trimesh is found, at which time
* the two trimesh OBBTrees are then compared to find the triangles that
* hit.
*/
public void hasCollision(Spatial scene, CollisionResults results) {
System.out.println(getName() + " has collided with " + scene.getName());
if (this == scene) {
return;
}
if (getWorldBound().intersects(scene.getWorldBound())) {
if ((scene instanceof Node)) {
Node parent = (Node) scene;
for (int i = 0; i < parent.getQuantity(); i++) {
hasCollision(parent.getChild(i), results);
}
} else {
ArrayList a = new ArrayList();
ArrayList b = new ArrayList();
//find the triangle that is being hit.
//add this node and the triangle to the CollisionResults list.
findIntersectionTriangles((TriMesh) scene, a, b);
CollisionData data = new CollisionData((TriMesh) scene, a, b);
results.addCollisionData(data);
}
}
}
/**
* This function checks for intersection between this trimesh and the given
* one. On the first intersection, true is returned.
*
* @param toCheck
* The intersection testing mesh.
* @return True if they intersect.
*/
public boolean hasTriangleCollision(TriMesh toCheck) {
if (collisionTree == null || toCheck.collisionTree == null)
return false;
else {
if (worldMatrot == null)
worldMatrot = worldRotation.toRotationMatrix();
else
worldMatrot = worldRotation.toRotationMatrix(worldMatrot);
collisionTree.bounds.transform(worldMatrot, worldTranslation,
worldScale, collisionTree.worldBounds);
toCheck.worldMatrot = toCheck.worldRotation.toRotationMatrix();
return collisionTree.intersect(toCheck.collisionTree);
}
}
/**
* This function finds all intersections between this trimesh and the
* checking one. The intersections are stored as Integer objects of Triangle
* indexes in each of the parameters.
*
* @param toCheck
* The TriMesh to check.
* @param thisIndex
* The array of triangle indexes intersecting in this mesh.
* @param otherIndex
* The array of triangle indexes intersecting in the given mesh.
*/
public void findIntersectionTriangles(TriMesh toCheck, ArrayList thisIndex,
ArrayList otherIndex) {
if (collisionTree == null || toCheck.collisionTree == null)
return;
else {
if (worldMatrot == null)
worldMatrot = worldRotation.toRotationMatrix();
else
worldMatrot = worldRotation.toRotationMatrix(worldMatrot);
collisionTree.bounds.transform(worldMatrot, worldTranslation,
worldScale, collisionTree.worldBounds);
toCheck.worldMatrot = toCheck.worldRotation.toRotationMatrix();
collisionTree.intersect(toCheck.collisionTree, thisIndex,
otherIndex);
}
}
/**
* This function is <b>ONLY </b> to be used by the intersection testing
* code. It should not be called by users. It returns a matrix3f
* representation of the mesh's world rotation.
*
* @return This mesh's world rotation.
*/
public Matrix3f findWorldRotMat() {
return worldMatrot;
}
} | Removed System.out.println (should never have made it into CVS)
git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@1877 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
| src/com/jme/scene/TriMesh.java | Removed System.out.println (should never have made it into CVS) |
|
Java | apache-2.0 | 5b89b1c3d250ddbc5f9e65d1a160a660d38e2d00 | 0 | kristianolsson/tools4j,kristianolsson/tools4j | config/config-runtime-api/src/main/java/org/deephacks/tools4j/config/Property.java | /**
* 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.deephacks.tools4j.config;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* A property indentify a single configurable detail that is configurable within a
* larger, cohesive concept. It should be possible to change properties atomically in
* isolation, that is, changing a property should not coincidentally force other properties
* to change in order to guarantee predicatble behaviour.
*
* <p>
* Changing a property should never cause system failure or malfunctioning. Make sure
* properties have proper validation rules so that administrators cannot accidentally
* misconfigure the system.
* </p>
* <p>
* Properties are used to mark a fields of configurable classes as configurable.
* </p>
*
* <p>
* <ul>
* <li>Property fields can be single-valued or multi-valued using any subclass of {@link java.util.Collection} type.</li>
* <li>Property fields can be <b>final</b> in which case it is considered immutable.</li>
* <li>Property fields are not allowed to be <b>transient</b>.</li>
* <li>Property fields are not allowed to be non-<b>final</b> <b>static</b>.</li>
* <li>Property fields can reference other {@link Config} classes, single or multiple using any subclass of
* {@link java.util.Collection} type.</li>
* <li>Property fields can have default values. These are used if no values have been set.</li>
* </p>
*
* @author Kristoffer Sjogren
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD })
@Inherited
public @interface Property {
/**
* Names are informative and comprehensible by an administrative user that
* clearly reveales the intent of the property.
* <p>
* Names will be displayed to administrative users.
* </p>
* @return
*/
String name();
/**
* <p>
* An informative description of the property that tells why it exists,
* what it does, how it is used and how changes affect the behaviour
* of the system.
* <p>
* Properties within the same class may affect each other, and if so,
* do describe these inter-dependencies.
* </p>
* <p>
* Description will be displayed to administrative users.
* </p>
* @return A description.
*/
String desc();
}
| removed @Property was not part of last commit
| config/config-runtime-api/src/main/java/org/deephacks/tools4j/config/Property.java | removed @Property was not part of last commit |
||
Java | mit | 5309097aa68a093388ba9d87c434224d60896d05 | 0 | yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods,yzhnasa/TASSEL-iRods | package net.maizegenetics.dna.map;
import cern.colt.GenericSorting;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import net.maizegenetics.dna.tag.TagCountMutable;
import net.maizegenetics.dna.tag.Tags;
import net.maizegenetics.dna.tag.SAMUtils;
import net.maizegenetics.dna.BaseEncoder;
import net.maizegenetics.dna.snp.GenotypeTable;
import net.maizegenetics.dna.snp.GenotypeTableUtils;
import net.maizegenetics.dna.snp.ImportUtils;
import net.maizegenetics.dna.snp.NucleotideAlignmentConstants;
import net.maizegenetics.util.MultiMemberGZIPInputStream;
/**
* Holds tag data compressed in long and a physical position. This can have two
* variations either include redundant positions or only unique positions. If
* redundant than tags that map to multiple regions should be placed adjacently
*
* Default 40 bytes per position. If we have 10,000,000 million positions then
* this will be at 400M byte data structure.
*
* User: ed
*/
public class TagsOnPhysicalMap extends AbstractTagsOnPhysicalMap {
int[] endPosition; // chromosomal position of the common adapter end of the tag (smaller than bestStartPos if tag matches minus bestStrand) // 4 bytes
byte[] divergence; // number of diverging bp (edit distance) from reference, unknown = Byte.MIN_VALUE
byte[] dcoP, mapP; //Round(Log2(P)), unknown Byte.MIN_VALUE
boolean redundantTags = true; // this field has not been utilized yet
public static enum SAMFormat {
BWA, BOWTIE2
}; // Supported SAM formats (each program defines some custom features)
private SAMFormat mySAMFormat = SAMFormat.BWA; // BWA by default
public TagsOnPhysicalMap() {
}
public TagsOnPhysicalMap(String inFile, boolean binary) {
if (binary) {
readBinaryFile(new File(inFile));
} else {
readTextFile(new File(inFile));
}
initPhysicalSort();
}
public TagsOnPhysicalMap(int rows) {
initMatrices(rows);
}
public TagsOnPhysicalMap(int rows, int tagLengthInLong, int maxVariants) {
this.tagLengthInLong = tagLengthInLong;
this.myMaxVariants = maxVariants;
initMatrices(rows);
}
public TagsOnPhysicalMap(Tags readList) {
tagLengthInLong = readList.getTagSizeInLong();
initMatrices(readList.getTagCount());
for (int i = 0; i < readList.getTagCount(); i++) {
for (int j = 0; j < tagLengthInLong; j++) {
tags[j][i] = readList.getTag(i)[j];
}
}
}
public TagsOnPhysicalMap(TagsOnPhysicalMap oldTOPM, boolean filterDuplicates) {
this.tagLengthInLong = oldTOPM.tagLengthInLong;
this.myMaxVariants = oldTOPM.myMaxVariants;
oldTOPM.sortTable(true);
int uniqueCnt = 1;
for (int i = 1; i < oldTOPM.getSize(); i++) {
if (!Arrays.equals(oldTOPM.getTag(i - 1), oldTOPM.getTag(i))) {
uniqueCnt++;
}
}
System.out.println("The Physical Map File has UniqueTags:" + uniqueCnt + " TotalLocations:" + oldTOPM.getSize());
initMatrices(uniqueCnt);
this.myNumTags = uniqueCnt;
uniqueCnt = 0;
this.copyTagMapRow(oldTOPM, 0, 0, filterDuplicates);
for (int i = 1; i < oldTOPM.getTagCount(); i++) {
// System.out.println(this.getTag(uniqueCnt)[1]+":"+ oldTOPM.getTag(i)[1]);
// System.out.println(":"+ oldTOPM.getTag(i)[1]);
if (!Arrays.equals(this.getTag(uniqueCnt), oldTOPM.getTag(i))) {
uniqueCnt++;
// copyTagMapRow(oldTOPM, i, uniqueCnt, filterDuplicates);
} else {
// System.out.printf("i=%d uniqueCnt=%d %n",i, uniqueCnt);
}
copyTagMapRow(oldTOPM, i, uniqueCnt, filterDuplicates);
}
initPhysicalSort();
}
void initMatrices(int rows) {
tags = new long[tagLengthInLong][rows]; // 16 bytes
tagLength = new byte[rows]; // length of tag (number of bases) // 1 byte
multimaps = new byte[rows]; // number of locations this tagSet maps to, unknown = Byte.MIN_VALUE
bestChr = new int[rows]; // 4 bytes
bestStrand = new byte[rows]; // 1 = same sense as reference FASTA file. -1 = opposite sense. unknown = Byte.MIN_VALUE // 1 byte
bestStartPos = new int[rows]; // chromosomal position of the barcoded end of the tag // 4 bytes
endPosition = new int[rows]; // chromosomal position of the common adapter end of the tag (smaller than bestStartPos if tag matches minus bestStrand) // 4 bytes
divergence = new byte[rows]; // number of diverging bp from reference, unknown = Byte.MIN_VALUE
variantOffsets = new byte[rows][]; // offset from position minimum, maximum number of variants is defined above // myMaxVariants bytes
variantDefs = new byte[rows][]; // allele state - A, C, G, T or some indel definition // myMaxVariants bytes
dcoP = new byte[rows];
mapP = new byte[rows]; // Round(Log2(P)), unknown = Byte.MIN_VALUE; if these disagree with the location, then set the p to negative
myNumTags = rows;
// try{
// System.out.println("Sleeping after memory creation");
// Thread.sleep(100000);
// } catch(Exception e) {
// System.out.println(e);
// }
}
public void expandMaxVariants(int newMaxVariants) {
if (newMaxVariants <= this.myMaxVariants) {
System.out.println("TagsOnPhysicalMap.expandMaxVariants(" + newMaxVariants + ") not performed because newMaxVariants (" + newMaxVariants
+ ") <= current maxVariants (" + this.myMaxVariants + ")");
return;
}
int oldMaxVariants = this.myMaxVariants;
byte[][] newVariantPosOff = new byte[myNumTags][newMaxVariants];
byte[][] newVariantDef = new byte[myNumTags][newMaxVariants];
for (int t = 0; t < myNumTags; ++t) {
for (int v = 0; v < this.myMaxVariants; ++v) {
newVariantPosOff[t][v] = this.variantOffsets[t][v];
newVariantDef[t][v] = this.variantDefs[t][v];
}
for (int v = this.myMaxVariants; v < newMaxVariants; ++v) {
newVariantPosOff[t][v] = Byte.MIN_VALUE;
newVariantDef[t][v] = Byte.MIN_VALUE;
}
}
this.myMaxVariants = newMaxVariants;
this.variantOffsets = newVariantPosOff;
this.variantDefs = newVariantDef;
System.out.println("TagsOnPhysicalMap maxVariants expanded from " + oldMaxVariants + " to " + newMaxVariants);
}
/**
* This helps collapse identical reads from different regions of the genome
* together.
*
* @param sourceTOPM
* @param sourceRow
* @param destRow
* @param merge
*/
public void copyTagMapRow(TagsOnPhysicalMap sourceTOPM, int sourceRow, int destRow, boolean merge) {
boolean overwrite = true;
long[] ctag = sourceTOPM.getTag(sourceRow);
if (Arrays.equals(ctag, this.getTag(destRow)) && merge) {
overwrite = false;
}
for (int i = 0; i < tagLengthInLong; i++) {
tags[i][destRow] = ctag[i];
}
if (overwrite) {
tagLength[destRow] = sourceTOPM.tagLength[sourceRow];
multimaps[destRow] = sourceTOPM.multimaps[sourceRow];
bestChr[destRow] = sourceTOPM.bestChr[sourceRow];
bestStrand[destRow] = sourceTOPM.bestStrand[sourceRow];
bestStartPos[destRow] = sourceTOPM.bestStartPos[sourceRow];
endPosition[destRow] = sourceTOPM.endPosition[sourceRow];
divergence[destRow] = sourceTOPM.divergence[sourceRow];
for (int j = 0; j < myMaxVariants; j++) {
variantOffsets[destRow][j] = sourceTOPM.variantOffsets[sourceRow][j];
variantDefs[destRow][j] = sourceTOPM.variantOffsets[sourceRow][j];
}
dcoP[destRow] = sourceTOPM.dcoP[sourceRow];
mapP[destRow] = sourceTOPM.mapP[sourceRow];
} else {
//tagLength[destRow]=tagLength[sourceRow];
if ((bestChr[destRow] != sourceTOPM.bestChr[sourceRow])
|| (bestStrand[destRow] != sourceTOPM.bestStrand[sourceRow])
|| (bestStartPos[destRow] != sourceTOPM.bestStartPos[sourceRow])
|| (endPosition[destRow] != sourceTOPM.endPosition[sourceRow])) {
multimaps[destRow] += sourceTOPM.multimaps[sourceRow];
bestChr[destRow] = bestStrand[destRow] = Byte.MIN_VALUE;
bestStartPos[destRow] = endPosition[destRow] = Integer.MIN_VALUE;
}
//dcoP[destRow]=dcoP[sourceRow];
//mapP[destRow]=mapP[sourceRow];
}
}
public long sortTable(boolean byHaplotype) {
System.out.print("Starting Read Table Sort ...");
if (byHaplotype == false) {
//TODO change the signature at some time
System.out.print("ERROR: Position sorting has been eliminated ...");
return -1;
}
long time = System.currentTimeMillis();
GenericSorting.quickSort(0, tags[0].length, this, this);
long totalTime = System.currentTimeMillis() - time;
System.out.println("Done in " + totalTime + "ms");
initPhysicalSort();
return totalTime;
}
protected void readBinaryFile(File currentFile) {
int tagsInput = 0;
try {
DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(currentFile), 65536));
System.out.println("File = " + currentFile);
myNumTags = dis.readInt();
// myNumTags=100000;
tagLengthInLong = dis.readInt();
myMaxVariants = dis.readInt();
initMatrices(myNumTags);
for (int row = 0; row < myNumTags; row++) {
for (int j = 0; j < tagLengthInLong; j++) {
tags[j][row] = dis.readLong();
}
tagLength[row] = dis.readByte();
multimaps[row] = dis.readByte();
bestChr[row] = dis.readInt();
bestStrand[row] = dis.readByte();
bestStartPos[row] = dis.readInt();
endPosition[row] = dis.readInt();
divergence[row] = dis.readByte();
byte[] currVD=new byte[myMaxVariants];
byte[] currVO=new byte[myMaxVariants];
int numWithData=0;
for (int j = 0; j < myMaxVariants; j++) {
currVO[j] = dis.readByte();
currVD[j] = dis.readByte();
if((currVD[j]>0xf)&&(GenotypeTableUtils.isHeterozygous(currVD[j]))) {//ascii bytes need to be converted to TASSEL 4
// System.out.printf("row:%d vd:%d %n", row, variantDefs[row][j]);
currVD[j]=NucleotideAlignmentConstants.getNucleotideAlleleByte(String.valueOf((char)currVD[j]));
}
if(currVO[j]!=TOPMInterface.BYTE_MISSING) numWithData++;
}
if(numWithData>0) {
variantDefs[row]=Arrays.copyOf(currVD, numWithData);
variantOffsets[row]=Arrays.copyOf(currVO, numWithData);
}
dcoP[row] = dis.readByte();
mapP[row] = dis.readByte();
tagsInput++;
if (row % 1000000 == 0) {
System.out.println("TagMapFile Row Read:" + row);
}
}
dis.close();
} catch (Exception e) {
System.out.println("Error tagsInput=" + tagsInput + " e=" + e);
}
System.out.println("Count of Tags=" + tagsInput);
}
public boolean variantsDefined(int tagIndex) {
for (int i = 0; i < myMaxVariants; i++) {
if ((variantOffsets[tagIndex][i] != Byte.MIN_VALUE) && (variantDefs[tagIndex][i] != Byte.MIN_VALUE)) {
return true;
}
}
return false;
}
public void readTextFile(File inFile) {
System.out.println("Reading tag alignment from:" + inFile.toString());
String[] inputLine = {"NotRead"};
try {
BufferedReader br = new BufferedReader(new FileReader(inFile), 65536);
inputLine = br.readLine().split("\t");
//Parse header line (Number of tags, number of Long ints per tag, maximum variant bases per tag).
this.myNumTags = Integer.parseInt(inputLine[0]);
this.tagLengthInLong = Integer.parseInt(inputLine[1]);
this.myMaxVariants = Integer.parseInt(inputLine[2]);
// initMatrices(9000000);
initMatrices(myNumTags);
//Loop through remaining lines, store contents in a series of arrays indexed by row number
for (int row = 0; row < myNumTags; row++) {
inputLine = br.readLine().split("\t");
int c = 0;
long[] tt = BaseEncoder.getLongArrayFromSeq(inputLine[c++]);
for (int j = 0; j < tt.length; j++) {
tags[j][row] = tt[j];
}
tagLength[row] = parseByteWMissing(inputLine[c++]);
multimaps[row] = parseByteWMissing(inputLine[c++]);
bestChr[row] = parseIntWMissing(inputLine[c++]);
bestStrand[row] = parseByteWMissing(inputLine[c++]);
bestStartPos[row] = parseIntWMissing(inputLine[c++]);
endPosition[row] = parseIntWMissing(inputLine[c++]);
divergence[row] = parseByteWMissing(inputLine[c++]);
byte[] currVD=new byte[myMaxVariants];
byte[] currVO=new byte[myMaxVariants];
int numWithData=0;
for (int j = 0; j < myMaxVariants; j++) {
currVO[j] = parseByteWMissing(inputLine[c++]);
currVD[j] = parseCharWMissing(inputLine[c++]);
if(currVO[j]!=TOPMInterface.BYTE_MISSING) numWithData++;
}
variantDefs[row]=Arrays.copyOf(currVD, numWithData);
variantOffsets[row]=Arrays.copyOf(currVO, numWithData);
dcoP[row] = parseByteWMissing(inputLine[c++]);
mapP[row] = parseByteWMissing(inputLine[c++]);
if (row % 1000000 == 0) {
System.out.println("Row Read:" + row);
}
}
} catch (Exception e) {
System.out.println("Catch in reading TagOnPhysicalMap file e=" + e);
e.printStackTrace();
System.out.println("Line:"+Arrays.toString(inputLine));
}
System.out.println("Number of tags in file:" + myNumTags);
}
@Override
public int getReadIndexForPositionIndex(int posIndex) {
return indicesOfSortByPosition[posIndex];
}
@Override
public int[] getPositionArray(int index) {
int[] r = {bestChr[index], bestStrand[index], bestStartPos[index]};
return r;
}
// public int getReadIndex(byte chr, byte bestStrand, int posMin) {
// // dep_ReadWithPositionInfo querySHP=new dep_ReadWithPositionInfo(bestChr, bestStrand, posMin);
// // PositionComparator posCompare = new PositionComparator();
// // int hit1=Arrays.binarySearch(shp, querySHP, posCompare);
// int hit1=-1; //redo
// return hit1;
// }
public static byte parseCharWMissing(String s) {
if (s.equals("*")) {
return Byte.MIN_VALUE;
}
try{
byte r=NucleotideAlignmentConstants.getNucleotideAlleleByte(s);
return r;
} catch(IllegalArgumentException e) {
int i = Integer.parseInt(s);
if (i > 127) {return 127;}
byte r=NucleotideAlignmentConstants.getNucleotideAlleleByte(String.valueOf((char)i));
return r;
}
}
public static byte parseByteWMissing(String s) {
if (s.equals("*")) {
return Byte.MIN_VALUE;
}
int i;
try {
i = Integer.parseInt(s);
if (i > 127) {
return 127;
}
return (byte) i;
} catch (NumberFormatException nf) {
return Byte.MIN_VALUE;
}
}
public static int parseIntWMissing(String s) {
if (s.equals("*")) {
return Integer.MIN_VALUE;
}
int i;
try {
i = Integer.parseInt(s);
return i;
} catch (NumberFormatException nf) {
return Integer.MIN_VALUE;
}
}
@Override
public byte getMultiMaps(int index) {
return multimaps[index];
}
@Override
public int getEndPosition(int index) {
return endPosition[index];
}
@Override
public byte getDivergence(int index) {
return divergence[index];
}
@Override
public byte getMapP(int index) {
return mapP[index];
}
@Override
public byte getDcoP(int index) {
return dcoP[index];
}
@Override
public void setChromoPosition(int index, int chromosome, byte strand, int positionMin,
int positionMax) {
this.bestChr[index] = chromosome;
this.bestStrand[index] = strand;
this.bestStartPos[index] = positionMin;
this.endPosition[index] = positionMax;
}
@Override
public void setDivergence(int index, byte divergence) {
this.divergence[index] = divergence;
}
@Override
public void setMapP(int index, byte mapP) {
this.mapP[index] = mapP;
}
@Override
public void setMapP(int index, double mapP) {
if (Double.isInfinite(mapP)) {
this.mapP[index] = Byte.MAX_VALUE;
return;
}
if (Double.isNaN(mapP) || (mapP < 0) || (mapP > 1)) {
this.mapP[index] = Byte.MIN_VALUE;
return;
}
if (mapP < 1e-126) {
this.mapP[index] = Byte.MAX_VALUE;
return;
}
this.mapP[index] = (byte) (-Math.round(Math.log10(mapP)));
}
@Override
public int addVariant(int tagIndex, byte offset, byte base) {
// code for ragged arrays
if (variantOffsets[tagIndex] == null) {
variantOffsets[tagIndex] = new byte[]{offset};
variantDefs[tagIndex] = new byte[]{base};
return 0;
} else {
if (variantOffsets[tagIndex].length == myMaxVariants) {
return -1; // no free space
}
variantOffsets[tagIndex] = Arrays.copyOf(variantOffsets[tagIndex], variantOffsets[tagIndex].length+1);
variantOffsets[tagIndex][variantOffsets[tagIndex].length-1] = offset;
variantDefs[tagIndex] = Arrays.copyOf(variantDefs[tagIndex], variantDefs[tagIndex].length+1);
variantDefs[tagIndex][variantDefs[tagIndex].length-1] = base;
return variantDefs.length-1;
}
// This commented out code was for non-ragged arrays, where Byte.MIN_VALUE (=TOPMInterface.BYTE_MISSING) signified the absence of a defined variant
// for (int i = 0; i < myMaxVariants; i++) {
// if ((variantOffsets[tagIndex][i] == Byte.MIN_VALUE) && (variantDefs[tagIndex][i] == Byte.MIN_VALUE)) {
// variantOffsets[tagIndex][i] = offset;
// variantDefs[tagIndex][i] = base;
// return i;
// }
// }
// return -1; //no free space
}
/**
* Decodes bitwise flags from the code in SAM field 3. The code is a 32-bit
* integer, so I boolean AND the flag value with the code, and compare the
* result with the flag value. If they are equal, that means all bits set in
* the flag number were set in the code (i.e., that flag is turned on).
*/
private boolean flagSet(int code, int flag) {
int flagValue = 1 << flag; //1<<flag is equivalent to 2^flag
return ((code & flagValue) == flagValue);
}
/**
* Reads SAM files output from BWA or bowtie2
*/
public void readSAMFile(String inputFileName, int tagLengthInLong) {
System.out.println("Reading SAM format tag alignment from: " + inputFileName);
this.tagLengthInLong = tagLengthInLong;
String inputStr = "Nothing has been read from the file yet";
int nHeaderLines = countTagsInSAMfile(inputFileName); // detects if the file is bowtie2, initializes topm matrices
int tagIndex = Integer.MIN_VALUE;
try {
BufferedReader br;
if (inputFileName.endsWith(".gz")) {
br = new BufferedReader(new InputStreamReader(new MultiMemberGZIPInputStream(new FileInputStream(new File(inputFileName)))));
} else {
br = new BufferedReader(new FileReader(new File(inputFileName)), 65536);
}
for (int i = 0; i < nHeaderLines; i++) {
br.readLine();
} // Skip over the header
for (tagIndex = 0; tagIndex < myNumTags; tagIndex++) {
inputStr = br.readLine();
parseSAMAlignment(inputStr, tagIndex);
if (tagIndex % 1000000 == 0) {
System.out.println("Read " + tagIndex + " tags.");
}
}
br.close();
} catch (Exception e) {
System.out.println("\n\nCatch in reading SAM alignment file at tag " + tagIndex + ":\n\t" + inputStr + "\nError: " + e + "\n\n");
e.printStackTrace();
System.exit(1);
}
}
private int countTagsInSAMfile(String inputFileName) {
mySAMFormat = SAMFormat.BWA; // format is BWA by default
myNumTags = 0;
int nHeaderLines = 0;
String currLine = null;
try {
String[] inputLine;
ArrayList<String> chrNames = new ArrayList<String>();
BufferedReader br;
if (inputFileName.endsWith(".gz")) {
br = new BufferedReader(new InputStreamReader(new MultiMemberGZIPInputStream(new FileInputStream(new File(inputFileName)))));
} else {
br = new BufferedReader(new FileReader(new File(inputFileName)), 65536);
}
while ((currLine = br.readLine()) != null) {
inputLine = currLine.split("\\s");
if (inputLine[0].contains("@")) {
//SAM files produced by Bowtie2 contain the string "@PG ID:bowtie2 PN:bowtie2 "
if (inputLine[1].contains("bowtie2")) {
mySAMFormat = SAMFormat.BOWTIE2;
}
nHeaderLines++;
} else {
String chr = inputLine[2];
if (!chrNames.contains(chr)) {
chrNames.add(chr);
}
myNumTags++;
if (myNumTags % 1000000 == 0) {
System.out.println("Counted " + myNumTags + " tags.");
}
}
}
br.close();
System.out.println("Found " + myNumTags + " tags in SAM file. Assuming " + mySAMFormat + " file format.");
} catch (Exception e) {
System.out.println("Catch in counting lines of alignment file at line " + currLine + ": " + e);
e.printStackTrace();
System.exit(1);
}
initMatrices(myNumTags);
return nHeaderLines;
}
private void parseSAMAlignment(String inputStr, int tagIndex) {
String[] inputLine = inputStr.split("\t");
int name = 0, flag = 1, chr = 2, pos = 3, cigar = 5, tagS = 9; // column indices in inputLine
String nullS = this.getNullTag();
if ((Integer.parseInt(inputLine[flag]) & 4) == 4) { // bit 0x4 (= 2^2 = 4) is set: NO ALIGNMENT
recordLackOfSAMAlign(tagIndex, inputLine[tagS], inputLine[name], nullS);
} else { // aligns to one or more positions
HashMap<String, Integer> SAMFields = parseOptionalFieldsFromSAMAlignment(inputLine);
byte bestHits = (byte) Math.min(SAMFields.get("nBestHits"), Byte.MAX_VALUE);
byte editDist = (byte) Math.min(SAMFields.get("editDist"), Byte.MAX_VALUE);
byte currStrand = (Integer.parseInt(inputLine[flag]) == 16) ? (byte) -1 : (byte) 1;
recordSAMAlign(
tagIndex,
inputLine[tagS],
inputLine[name],
nullS,
bestHits,
inputLine[chr],
currStrand,
Integer.parseInt(inputLine[pos]),
inputLine[cigar],
editDist);
}
}
private HashMap<String, Integer> parseOptionalFieldsFromSAMAlignment(String[] inputLine) {
HashMap<String, Integer> SAMFields = new HashMap<String, Integer>();
if (mySAMFormat == SAMFormat.BWA) {
for (int field = 11; field < inputLine.length; field++) { // Loop through all the optional field of the SAM alignment
if (inputLine[field].regionMatches(0, "X0", 0, 2)) { // X0 = SAM format for # of "high-quality" alignments of this query. Specific to BWA.
SAMFields.put("nBestHits", Integer.parseInt(inputLine[field].split(":")[2]));
} else if (inputLine[field].regionMatches(0, "NM", 0, 2)) { // NM = SAM format for edit distance to the reference. Common to BWA and Bowtie2.
SAMFields.put("editDist", Integer.parseInt(inputLine[field].split(":")[2]));
}
}
} else { // bowtie2 -M format
for (int field = 11; field < inputLine.length; field++) { // Loop through all the optional field of the SAM alignment
if (inputLine[field].regionMatches(0, "AS", 0, 2)) { // AS = SAM format for alignment score of the best alignment. Specific to bowtie2.
SAMFields.put("bestScore", Integer.parseInt(inputLine[field].split(":")[2]));
} else if (inputLine[field].regionMatches(0, "XS", 0, 2)) { // XS = SAM format for alignment score of 2nd best alignment. Specific to bowtie2.
SAMFields.put("nextScore", Integer.parseInt(inputLine[field].split(":")[2]));
} else if (inputLine[field].regionMatches(0, "NM", 0, 2)) { // NM = SAM format for edit distance to the reference. Common to BWA and Bowtie2.
SAMFields.put("editDist", Integer.parseInt(inputLine[field].split(":")[2]));
}
}
if (SAMFields.containsKey("bestScore")) {
if (SAMFields.containsKey("nextScore")) {
if (SAMFields.get("bestScore") > SAMFields.get("nextScore")) {
SAMFields.put("nBestHits", 1);
} else {
SAMFields.put("nBestHits", 99); // 99 will stand for an unknown # of multiple hits
}
} else {
SAMFields.put("nBestHits", 1);
}
}
}
return SAMFields;
}
private void recordLackOfSAMAlign(int tagIndex, String tagS, String tagName, String nullS) {
recordTagFromSAMAlignment(tagIndex, tagS, tagName, nullS, (byte) 1);
multimaps[tagIndex] = 0; // or should this be unknown = Byte.MIN_VALUE???
bestChr[tagIndex] = Integer.MIN_VALUE;
bestStrand[tagIndex] = Byte.MIN_VALUE;
bestStartPos[tagIndex] = Integer.MIN_VALUE;
endPosition[tagIndex] = Integer.MIN_VALUE;
divergence[tagIndex] = Byte.MIN_VALUE;
// // no longer necessary for ragged arrays
// for (int var = 0; var < myMaxVariants; var++) {
// variantOffsets[tagIndex][var] = Byte.MIN_VALUE;
// variantDefs[tagIndex][var] = Byte.MIN_VALUE;
// }
dcoP[tagIndex] = Byte.MIN_VALUE;
mapP[tagIndex] = Byte.MIN_VALUE;
}
private void recordSAMAlign(int tagIndex, String tagS, String tagName, String nullS, byte nBestHits, String chrS, byte strand, int pos, String cigar, byte editDist) {
recordTagFromSAMAlignment(tagIndex, tagS, tagName, nullS, strand);
multimaps[tagIndex] = nBestHits;
if (nBestHits == 1) {
bestChr[tagIndex] = parseChrString(chrS);
this.bestStrand[tagIndex] = strand;
recordStartEndPostionFromSAMAlign(tagIndex, strand, pos, cigar);
} else {
bestChr[tagIndex] = Integer.MIN_VALUE;
this.bestStrand[tagIndex] = Byte.MIN_VALUE;
bestStartPos[tagIndex] = Integer.MIN_VALUE;
endPosition[tagIndex] = Integer.MIN_VALUE;
}
divergence[tagIndex] = editDist;
// // no longer necessary for ragged arrays
// for (int var = 0; var < myMaxVariants; var++) {
// variantOffsets[tagIndex][var] = Byte.MIN_VALUE;
// variantDefs[tagIndex][var] = Byte.MIN_VALUE;
// }
dcoP[tagIndex] = Byte.MIN_VALUE;
mapP[tagIndex] = Byte.MIN_VALUE;
}
private void recordTagFromSAMAlignment(int tagIndex, String tagS, String tagName, String nullS, byte strand) {
if (strand == -1) {
tagS = BaseEncoder.getReverseComplement(tagS);
}
if (tagS.length() < tagLengthInLong * 32) { // pad with polyA
tagS = tagS + nullS;
tagS = tagS.substring(0, (tagLengthInLong * 32));
}
long[] tagSequence = BaseEncoder.getLongArrayFromSeq(tagS);
for (int chunk = 0; chunk < tagLengthInLong; chunk++) {
tags[chunk][tagIndex] = tagSequence[chunk];
}
tagName = tagName.replaceFirst("count=[0-9]+", "");
tagName = tagName.replaceFirst("length=", "");
tagLength[tagIndex] = Byte.parseByte(tagName);
}
private int parseChrString(String chrS) {
int chr = Integer.MIN_VALUE;
chrS = chrS.replace("chr", "");
try {
chr = Integer.parseInt(chrS);
} catch (NumberFormatException e) {
System.out.println("\n\nSAMConverterPlugin detected a non-numeric chromosome name: " + chrS
+ "\n\nPlease change the FASTA headers in your reference genome sequence to integers "
+ "(>1, >2, >3, etc.) OR to 'chr' followed by an integer (>chr1, >chr2, >chr3, etc.)\n\n");
System.exit(1);
}
return chr;
}
private void recordStartEndPostionFromSAMAlign(int tagIndex, byte strand, int pos, String cigar) {
int[] alignSpan = SAMUtils.adjustCoordinates(cigar, pos);
try {
if (strand == 1) {
bestStartPos[tagIndex] = alignSpan[0];
endPosition[tagIndex] = alignSpan[1];
} else if (strand == -1) {
bestStartPos[tagIndex] = alignSpan[1];
endPosition[tagIndex] = alignSpan[0];
} else {
throw new Exception("Unexpected value for strand: " + strand + "(expect 1 or -1)");
}
} catch (Exception e) {
System.out.println("Error in recordStartEndPostionFromSAMAlign: " + e);
e.printStackTrace();
System.exit(1);
}
}
@Override
public void swap(int index1, int index2) {
long tl;
for (int i = 0; i < tagLengthInLong; i++) {
tl = tags[i][index1];
tags[i][index1] = tags[i][index2];
tags[i][index2] = tl;
}
int tb;
tb = tagLength[index1];
tagLength[index1] = tagLength[index2];
tagLength[index2] = (byte) tb;
tb = multimaps[index1];
multimaps[index1] = multimaps[index2];
multimaps[index2] = (byte) tb;
tb = bestChr[index1];
bestChr[index1] = bestChr[index2];
bestChr[index2] = tb;
tb = bestStrand[index1];
bestStrand[index1] = bestStrand[index2];
bestStrand[index2] = (byte) tb;
int ti;
ti = bestStartPos[index1];
bestStartPos[index1] = bestStartPos[index2];
bestStartPos[index2] = ti;
ti = endPosition[index1];
endPosition[index1] = endPosition[index2];
endPosition[index2] = ti;
tb = divergence[index1];
divergence[index1] = divergence[index2];
divergence[index2] = (byte) tb;
byte[] tba = variantOffsets[index1];
variantOffsets[index1] = variantOffsets[index2];
variantOffsets[index2] = tba;
tba = variantDefs[index1];
variantDefs[index1] = variantDefs[index2];
variantDefs[index2] = tba;
// for (int j = 0; j < myMaxVariants; j++) {
// tb = variantOffsets[index1][j];
// variantOffsets[index1][j] = variantOffsets[index2][j];
// variantOffsets[index2][j] = (byte) tb;
// tb = variantDefs[index1][j];
// variantDefs[index1][j] = variantDefs[index2][j];
// variantDefs[index2][j] = (byte) tb;
// }
tb = dcoP[index1];
dcoP[index1] = dcoP[index2];
dcoP[index2] = (byte) tb;
tb = mapP[index1];
mapP[index1] = mapP[index2];
mapP[index2] = (byte) tb;
}
@Override
public int compare(int index1, int index2) {
for (int i = 0; i < tagLengthInLong; i++) {
if (tags[i][index1] < tags[i][index2]) {
return -1;
}
if (tags[i][index1] > tags[i][index2]) {
return 1;
}
}
if (bestChr[index1] < bestChr[index2]) {
return -1;
}
if (bestChr[index1] > bestChr[index2]) {
return 1;
}
if (bestStartPos[index1] < bestStartPos[index2]) {
return -1;
}
if (bestStartPos[index1] > bestStartPos[index2]) {
return 1;
}
if (bestStrand[index1] < bestStrand[index2]) {
return -1;
}
if (bestStrand[index1] > bestStrand[index2]) {
return 1;
}
return 0;
}
@Override
public void setVariantDef(int tagIndex, int variantIndex, byte def) {
variantDefs[tagIndex][variantIndex] = (byte) NucleotideAlignmentConstants.NUCLEOTIDE_ALLELES[0][def].charAt(0);
}
@Override
public void setVariantPosOff(int tagIndex, int variantIndex, byte offset) {
variantOffsets[tagIndex][variantIndex] = offset;
}
@Override
public int getMaxNumVariants() {
return myMaxVariants;
}
/**
* First, find unique tags by concatenating them into a TagCountMutable
* object and collapsing duplicate rows.
*/
private static TagsOnPhysicalMap uniqueTags(String[] filenames) {
//Find dimensions of concatenated file
int tagLengthInLong = 0, maxVariants = 0, tagNum = 0;
for (String name : filenames) {
TagsOnPhysicalMap file = new TagsOnPhysicalMap(name, true);
tagNum += file.myNumTags;
if (file.myMaxVariants > maxVariants) {
maxVariants = file.myMaxVariants;
}
if (file.getTagSizeInLong() > tagLengthInLong) {
tagLengthInLong = file.getTagSizeInLong();
}
}
//Create new concatenated file
TagCountMutable tc = new TagCountMutable(tagLengthInLong, tagNum);
for (String name : filenames) {
TagsOnPhysicalMap file = new TagsOnPhysicalMap(name, true);
for (int i = 0; i < file.myNumTags; i++) {
tc.addReadCount(file.getTag(i), file.getTagLength(i), 1);
}
}
//Reduce concatenated file to unique tags
tc.collapseCounts();
tc.shrinkToCurrentRows();
TagsOnPhysicalMap result = new TagsOnPhysicalMap(tc);
result.expandMaxVariants(maxVariants);
result.clearVariants();
return result;
}
/**
* Merges several TOPM files into one, removing duplicate rows. Variants
* from matching tags are combined in the output file. If there are more
* variants in the input files than can fit in the output, extra variants
* are discarded with no particular order.
*/
public static TagsOnPhysicalMap merge(String[] filenames) {
TagsOnPhysicalMap output = uniqueTags(filenames);
System.out.println(
"Output file will contain "
+ output.myNumTags + " unique tags, "
+ output.getTagSizeInLong() + " longs/tag, "
+ output.myMaxVariants + " variants. ");
for (String name : filenames) {
TagsOnPhysicalMap file = new TagsOnPhysicalMap(name, true);
int varsAdded = 0, varsSkipped = 0;
for (int inTag = 0; inTag < file.myNumTags; inTag++) { //Loop over tags in input
//Find index of corresponding tag in output file, and copy attributes from input to output
int outTag = output.getTagIndex(file.getTag(inTag));
copyTagAttributes(file, inTag, output, outTag);
//For corresponding tags, compare variants
for (int outVar = 0; outVar < output.myMaxVariants; outVar++) {
byte outOff = output.getVariantPosOff(outTag, outVar);
if (outOff != BYTE_MISSING) {//Skip filled output variants or re-initialize them
varsSkipped++;
continue;
}
for (int inVar = 0; inVar < file.myMaxVariants; inVar++) {
byte offset = file.getVariantPosOff(inTag, outVar);
byte def = file.getVariantDef(inTag, outVar);
if (offset == BYTE_MISSING) {
continue; //Skip blank input variants
}
//If we get here, output variant is blank and input variant is non-blank at the same tag & variant indices
varsAdded++;
output.setVariantPosOff(outTag, outVar, offset);
output.setVariantDef(outTag, outVar, def);
file.setVariantPosOff(inTag, inVar, Byte.MIN_VALUE); //Erase this variant so it isn't encountered again
break; //Go to next output variant after copying
}
}
}
System.out.println(varsAdded + " variants added.");
System.out.println(varsSkipped + " variants skipped.");
}
return output;
}
/**
* Copies values of everything BUT tag sequence and variant data (i.e. tag
* attributes) from one TOPM file to another.
*/
private static void copyTagAttributes(TagsOnPhysicalMap input, int inTag, TagsOnPhysicalMap output, int outTag) {
output.tagLength[outTag] = input.tagLength[inTag];
output.multimaps[outTag] = input.multimaps[inTag];
output.bestChr[outTag] = input.bestChr[inTag];
output.bestStrand[outTag] = input.bestStrand[inTag];
output.bestStartPos[outTag] = input.bestStartPos[inTag];
output.endPosition[outTag] = input.endPosition[inTag];
output.divergence[outTag] = input.divergence[inTag];
output.dcoP[outTag] = input.dcoP[inTag];
output.mapP[outTag] = input.mapP[inTag];
}
/**
* Fills the variant definition & offset arrays with the value of
* "byteMissing".
*/
public void clearVariants() {
for (int i = 0; i < getTagCount(); i++) {
Arrays.fill(variantDefs[i], BYTE_MISSING);
Arrays.fill(variantOffsets[i], BYTE_MISSING);
}
}
/**
* Fills the variant definition & offset at the given indices with the value
* of "byteMissing".
*/
private void clearVariant(int tag, int variant) {
setVariantDef(tag, variant, BYTE_MISSING);
setVariantPosOff(tag, variant, BYTE_MISSING);
}
/**
* Clears variant sites that are not found in the supplied alignments.
*/
public void filter(String[] filenames) {
HashMap<String, Integer> hapmapSites = new HashMap<String, Integer>();
//Map all site positions from all alignments to their index.
for (String filename : filenames) {
System.out.println("Filtering out sites from " + filename + ".");
hapmapSites.putAll(hapmapSites(ImportUtils.readFromHapmap(filename, null)));
}
System.out.println("There are " + hapmapSites.size() + " sites in the hapmap files.");
//Map all tag variant positions to their index.
HashMap<String, Integer> topmSites = uniqueSites(); //Map tag variant positions to bases
//Sites should be a subset of tag variants, so check that there are fewer of them.
System.out.println("Found " + topmSites.size() + " unique sites in " + myNumTags + " tags in TOPM.");
if (topmSites.size() < hapmapSites.size()) {
System.out.println("Warning: more unique sites exist in hapmap file.");
}
//Next, check that each alignment site is present in If not, either there was no more room or something is wrong.
HashSet<Integer> fullSites = fullTagPositions(); //Tags which already have the maximum number of variants
ArrayList<String> insertedSites = new ArrayList<String>(); //Sites that don't correspond to a real tag
ArrayList<String> skippedSites = new ArrayList<String>(); //Real sites that were skipped due to "full tags"
int basePerTag = tagLengthInLong * 32;
for (String hapmapSNP : hapmapSites.keySet().toArray(new String[hapmapSites.size()])) {
int chr = Integer.parseInt(hapmapSNP.split("\\t")[0]);
int pos = Integer.parseInt(hapmapSNP.split("\\t")[1]);
if (topmSites.get(hapmapSNP) == null) {
// System.out.print("Warning: SNP "+chr+":"+pos+" is not in TOPM. ");
boolean inRange = false;
for (int i = -basePerTag; i < basePerTag; i++) {
if (fullSites.contains(i + pos)) {
inRange = true;
break;
}
}
if (inRange) {
skippedSites.add(hapmapSNP);
// System.out.println("However, it is within range of a tag with the max. number of variants.");
} else {
insertedSites.add(hapmapSNP);
System.out.println();
}
hapmapSites.remove(hapmapSNP);
continue;
}
}
System.out.println("The following SNPs were not in the TOPM, but are within range of a tag with the max. number of variants:");
for (String site : skippedSites) {
System.out.println(site);
}
System.out.println("The following SNPs were not in the TOPM, and do not correspond to any known tag:");
for (String site : insertedSites) {
System.out.println(site);
}
//Remove any sites from the TOPM that are absent in the alignment
int removedSites = 0;
for (int tag = 0; tag < myNumTags; tag++) {
int chr = getChromosome(tag);
int pos = getStartPosition(tag);
for (int variant = 0; variant < myMaxVariants; variant++) {
byte off = getVariantPosOff(tag, variant);
String site = chr + "\t" + (pos + off);
if (!hapmapSites.containsKey(site)) {
clearVariant(tag, variant);
removedSites++;
}
}
}
topmSites = uniqueSites();
System.out.println("Removed " + removedSites + " TOPM sites not present in alignment and ignored " + insertedSites.size() + " alignment sites not present in TOPM.");
System.out.println("There are " + topmSites.size() + " sites in the TOPM now, as compared to " + hapmapSites.size() + " sites in the alignment.");
if (topmSites.size() != hapmapSites.size()) {
System.out.println("Warning: number of filtered sites does not match number of alignment sites.");
}
}
/**
* Returns the start positions of tags whose variant arrays are full.
*/
public HashSet<Integer> fullTagPositions() {
HashSet<Integer> result = new HashSet<Integer>();
for (int i = 0; i < myNumTags; i++) {
boolean variantsFull = true;
for (int j = 0; j < myMaxVariants; j++) {
byte off = getVariantPosOff(i, j);
if (off == Byte.MIN_VALUE) {
variantsFull = false;
break;
}
}
if (variantsFull) {
result.add(getStartPosition(i));
}
}
return result;
}
/**
* Maps unique sites (i.e. bestChr and position) to the indices of the
* tags in which they are found.
*/
public HashMap<String, Integer> uniqueSites() {
HashMap<String, Integer> snps = new HashMap<String, Integer>();
for (int tag = 0; tag < myNumTags; tag++) { //Visit each tag in TOPM
for (int variant = 0; variant < myMaxVariants; variant++) { //Visit each variant in TOPM
byte off = getVariantPosOff(tag, variant);
if (off == BYTE_MISSING) {
continue;
}
int a = getStartPosition(tag);
int b = getVariantPosOff(tag, variant);
int c = a + b;
String pos = getChromosome(tag) + "\t" + c;
snps.put(pos, tag);
}
}
return snps;
}
public static HashMap<String, Integer> hapmapSites(GenotypeTable file) {
HashMap<String, Integer> snps = new HashMap<String, Integer>();
for (int site = 0; site < file.numberOfSites(); site++) { //Visit each site
String pos = (file.chromosomeName(site) + "\t"
+ file.chromosomalPosition(site));
if (file.chromosomalPosition(site) > 2000000000) {
System.out.println(pos);
}
snps.put(pos, site);
}
return snps;
}
/**
* Returns an array whose indices are the number of mappings and whose
* elements are the number of tags with that mapping.
*/
public int[] mappingDistribution() {
int[] result = new int[128]; //Only up to 127 multiple mappings are stored.
for (int i = 0; i < myNumTags; i++) {
if (multimaps[i] > (result.length - 1)) {
result[127]++;
}
if (multimaps[i] == BYTE_MISSING) {
result[0]++;
continue;
} else {
result[multimaps[i]]++;
}
}
return result;
}
}
| src/net/maizegenetics/dna/map/TagsOnPhysicalMap.java | package net.maizegenetics.dna.map;
import cern.colt.GenericSorting;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import net.maizegenetics.dna.tag.TagCountMutable;
import net.maizegenetics.dna.tag.Tags;
import net.maizegenetics.dna.tag.SAMUtils;
import net.maizegenetics.dna.BaseEncoder;
import net.maizegenetics.dna.snp.GenotypeTable;
import net.maizegenetics.dna.snp.GenotypeTableUtils;
import net.maizegenetics.dna.snp.ImportUtils;
import net.maizegenetics.dna.snp.NucleotideAlignmentConstants;
import net.maizegenetics.util.MultiMemberGZIPInputStream;
/**
* Holds tag data compressed in long and a physical position. This can have two
* variations either include redundant positions or only unique positions. If
* redundant than tags that map to multiple regions should be placed adjacently
*
* Default 40 bytes per position. If we have 10,000,000 million positions then
* this will be at 400M byte data structure.
*
* User: ed
*/
public class TagsOnPhysicalMap extends AbstractTagsOnPhysicalMap {
int[] endPosition; // chromosomal position of the common adapter end of the tag (smaller than bestStartPos if tag matches minus bestStrand) // 4 bytes
byte[] divergence; // number of diverging bp (edit distance) from reference, unknown = Byte.MIN_VALUE
byte[] dcoP, mapP; //Round(Log2(P)), unknown Byte.MIN_VALUE
boolean redundantTags = true; // this field has not been utilized yet
public static enum SAMFormat {
BWA, BOWTIE2
}; // Supported SAM formats (each program defines some custom features)
private SAMFormat mySAMFormat = SAMFormat.BWA; // BWA by default
public TagsOnPhysicalMap() {
}
public TagsOnPhysicalMap(String inFile, boolean binary) {
if (binary) {
readBinaryFile(new File(inFile));
} else {
readTextFile(new File(inFile));
}
initPhysicalSort();
}
public TagsOnPhysicalMap(int rows) {
initMatrices(rows);
}
public TagsOnPhysicalMap(int rows, int tagLengthInLong, int maxVariants) {
this.tagLengthInLong = tagLengthInLong;
this.myMaxVariants = maxVariants;
initMatrices(rows);
}
public TagsOnPhysicalMap(Tags readList) {
tagLengthInLong = readList.getTagSizeInLong();
initMatrices(readList.getTagCount());
for (int i = 0; i < readList.getTagCount(); i++) {
for (int j = 0; j < tagLengthInLong; j++) {
tags[j][i] = readList.getTag(i)[j];
}
}
}
public TagsOnPhysicalMap(TagsOnPhysicalMap oldTOPM, boolean filterDuplicates) {
this.tagLengthInLong = oldTOPM.tagLengthInLong;
this.myMaxVariants = oldTOPM.myMaxVariants;
oldTOPM.sortTable(true);
int uniqueCnt = 1;
for (int i = 1; i < oldTOPM.getSize(); i++) {
if (!Arrays.equals(oldTOPM.getTag(i - 1), oldTOPM.getTag(i))) {
uniqueCnt++;
}
}
System.out.println("The Physical Map File has UniqueTags:" + uniqueCnt + " TotalLocations:" + oldTOPM.getSize());
initMatrices(uniqueCnt);
this.myNumTags = uniqueCnt;
uniqueCnt = 0;
this.copyTagMapRow(oldTOPM, 0, 0, filterDuplicates);
for (int i = 1; i < oldTOPM.getTagCount(); i++) {
// System.out.println(this.getTag(uniqueCnt)[1]+":"+ oldTOPM.getTag(i)[1]);
// System.out.println(":"+ oldTOPM.getTag(i)[1]);
if (!Arrays.equals(this.getTag(uniqueCnt), oldTOPM.getTag(i))) {
uniqueCnt++;
// copyTagMapRow(oldTOPM, i, uniqueCnt, filterDuplicates);
} else {
// System.out.printf("i=%d uniqueCnt=%d %n",i, uniqueCnt);
}
copyTagMapRow(oldTOPM, i, uniqueCnt, filterDuplicates);
}
initPhysicalSort();
}
void initMatrices(int rows) {
tags = new long[tagLengthInLong][rows]; // 16 bytes
tagLength = new byte[rows]; // length of tag (number of bases) // 1 byte
multimaps = new byte[rows]; // number of locations this tagSet maps to, unknown = Byte.MIN_VALUE
bestChr = new int[rows]; // 4 bytes
bestStrand = new byte[rows]; // 1 = same sense as reference FASTA file. -1 = opposite sense. unknown = Byte.MIN_VALUE // 1 byte
bestStartPos = new int[rows]; // chromosomal position of the barcoded end of the tag // 4 bytes
endPosition = new int[rows]; // chromosomal position of the common adapter end of the tag (smaller than bestStartPos if tag matches minus bestStrand) // 4 bytes
divergence = new byte[rows]; // number of diverging bp from reference, unknown = Byte.MIN_VALUE
variantOffsets = new byte[rows][myMaxVariants]; // offset from position minimum, maximum number of variants is defined above // myMaxVariants bytes
variantDefs = new byte[rows][myMaxVariants]; // allele state - A, C, G, T or some indel definition // myMaxVariants bytes
dcoP = new byte[rows];
mapP = new byte[rows]; // Round(Log2(P)), unknown = Byte.MIN_VALUE; if these disagree with the location, then set the p to negative
myNumTags = rows;
// try{
// System.out.println("Sleeping after memory creation");
// Thread.sleep(100000);
// } catch(Exception e) {
// System.out.println(e);
// }
}
public void expandMaxVariants(int newMaxVariants) {
if (newMaxVariants <= this.myMaxVariants) {
System.out.println("TagsOnPhysicalMap.expandMaxVariants(" + newMaxVariants + ") not performed because newMaxVariants (" + newMaxVariants
+ ") <= current maxVariants (" + this.myMaxVariants + ")");
return;
}
int oldMaxVariants = this.myMaxVariants;
byte[][] newVariantPosOff = new byte[myNumTags][newMaxVariants];
byte[][] newVariantDef = new byte[myNumTags][newMaxVariants];
for (int t = 0; t < myNumTags; ++t) {
for (int v = 0; v < this.myMaxVariants; ++v) {
newVariantPosOff[t][v] = this.variantOffsets[t][v];
newVariantDef[t][v] = this.variantDefs[t][v];
}
for (int v = this.myMaxVariants; v < newMaxVariants; ++v) {
newVariantPosOff[t][v] = Byte.MIN_VALUE;
newVariantDef[t][v] = Byte.MIN_VALUE;
}
}
this.myMaxVariants = newMaxVariants;
this.variantOffsets = newVariantPosOff;
this.variantDefs = newVariantDef;
System.out.println("TagsOnPhysicalMap maxVariants expanded from " + oldMaxVariants + " to " + newMaxVariants);
}
/**
* This helps collapse identical reads from different regions of the genome
* together.
*
* @param sourceTOPM
* @param sourceRow
* @param destRow
* @param merge
*/
public void copyTagMapRow(TagsOnPhysicalMap sourceTOPM, int sourceRow, int destRow, boolean merge) {
boolean overwrite = true;
long[] ctag = sourceTOPM.getTag(sourceRow);
if (Arrays.equals(ctag, this.getTag(destRow)) && merge) {
overwrite = false;
}
for (int i = 0; i < tagLengthInLong; i++) {
tags[i][destRow] = ctag[i];
}
if (overwrite) {
tagLength[destRow] = sourceTOPM.tagLength[sourceRow];
multimaps[destRow] = sourceTOPM.multimaps[sourceRow];
bestChr[destRow] = sourceTOPM.bestChr[sourceRow];
bestStrand[destRow] = sourceTOPM.bestStrand[sourceRow];
bestStartPos[destRow] = sourceTOPM.bestStartPos[sourceRow];
endPosition[destRow] = sourceTOPM.endPosition[sourceRow];
divergence[destRow] = sourceTOPM.divergence[sourceRow];
for (int j = 0; j < myMaxVariants; j++) {
variantOffsets[destRow][j] = sourceTOPM.variantOffsets[sourceRow][j];
variantDefs[destRow][j] = sourceTOPM.variantOffsets[sourceRow][j];
}
dcoP[destRow] = sourceTOPM.dcoP[sourceRow];
mapP[destRow] = sourceTOPM.mapP[sourceRow];
} else {
//tagLength[destRow]=tagLength[sourceRow];
if ((bestChr[destRow] != sourceTOPM.bestChr[sourceRow])
|| (bestStrand[destRow] != sourceTOPM.bestStrand[sourceRow])
|| (bestStartPos[destRow] != sourceTOPM.bestStartPos[sourceRow])
|| (endPosition[destRow] != sourceTOPM.endPosition[sourceRow])) {
multimaps[destRow] += sourceTOPM.multimaps[sourceRow];
bestChr[destRow] = bestStrand[destRow] = Byte.MIN_VALUE;
bestStartPos[destRow] = endPosition[destRow] = Integer.MIN_VALUE;
}
//dcoP[destRow]=dcoP[sourceRow];
//mapP[destRow]=mapP[sourceRow];
}
}
public long sortTable(boolean byHaplotype) {
System.out.print("Starting Read Table Sort ...");
if (byHaplotype == false) {
//TODO change the signature at some time
System.out.print("ERROR: Position sorting has been eliminated ...");
return -1;
}
long time = System.currentTimeMillis();
GenericSorting.quickSort(0, tags[0].length, this, this);
long totalTime = System.currentTimeMillis() - time;
System.out.println("Done in " + totalTime + "ms");
initPhysicalSort();
return totalTime;
}
protected void readBinaryFile(File currentFile) {
int tagsInput = 0;
try {
DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(currentFile), 65536));
System.out.println("File = " + currentFile);
myNumTags = dis.readInt();
// myNumTags=100000;
tagLengthInLong = dis.readInt();
myMaxVariants = dis.readInt();
initMatrices(myNumTags);
for (int row = 0; row < myNumTags; row++) {
for (int j = 0; j < tagLengthInLong; j++) {
tags[j][row] = dis.readLong();
}
tagLength[row] = dis.readByte();
multimaps[row] = dis.readByte();
bestChr[row] = dis.readInt();
bestStrand[row] = dis.readByte();
bestStartPos[row] = dis.readInt();
endPosition[row] = dis.readInt();
divergence[row] = dis.readByte();
byte[] currVD=new byte[myMaxVariants];
byte[] currVO=new byte[myMaxVariants];
int numWithData=0;
for (int j = 0; j < myMaxVariants; j++) {
currVO[j] = dis.readByte();
currVD[j] = dis.readByte();
if((currVD[j]>0xf)&&(GenotypeTableUtils.isHeterozygous(currVD[j]))) {//ascii bytes need to be converted to TASSEL 4
// System.out.printf("row:%d vd:%d %n", row, variantDefs[row][j]);
currVD[j]=NucleotideAlignmentConstants.getNucleotideAlleleByte(String.valueOf((char)currVD[j]));
}
if(currVO[j]!=TOPMInterface.BYTE_MISSING) numWithData++;
}
if(numWithData>0) {
variantDefs[row]=Arrays.copyOf(currVD, numWithData);
variantOffsets[row]=Arrays.copyOf(currVO, numWithData);
}
dcoP[row] = dis.readByte();
mapP[row] = dis.readByte();
tagsInput++;
if (row % 1000000 == 0) {
System.out.println("TagMapFile Row Read:" + row);
}
}
dis.close();
} catch (Exception e) {
System.out.println("Error tagsInput=" + tagsInput + " e=" + e);
}
System.out.println("Count of Tags=" + tagsInput);
}
public boolean variantsDefined(int tagIndex) {
for (int i = 0; i < myMaxVariants; i++) {
if ((variantOffsets[tagIndex][i] != Byte.MIN_VALUE) && (variantDefs[tagIndex][i] != Byte.MIN_VALUE)) {
return true;
}
}
return false;
}
public void readTextFile(File inFile) {
System.out.println("Reading tag alignment from:" + inFile.toString());
String[] inputLine = {"NotRead"};
try {
BufferedReader br = new BufferedReader(new FileReader(inFile), 65536);
inputLine = br.readLine().split("\t");
//Parse header line (Number of tags, number of Long ints per tag, maximum variant bases per tag).
this.myNumTags = Integer.parseInt(inputLine[0]);
this.tagLengthInLong = Integer.parseInt(inputLine[1]);
this.myMaxVariants = Integer.parseInt(inputLine[2]);
// initMatrices(9000000);
initMatrices(myNumTags);
//Loop through remaining lines, store contents in a series of arrays indexed by row number
for (int row = 0; row < myNumTags; row++) {
inputLine = br.readLine().split("\t");
int c = 0;
long[] tt = BaseEncoder.getLongArrayFromSeq(inputLine[c++]);
for (int j = 0; j < tt.length; j++) {
tags[j][row] = tt[j];
}
tagLength[row] = parseByteWMissing(inputLine[c++]);
multimaps[row] = parseByteWMissing(inputLine[c++]);
bestChr[row] = parseIntWMissing(inputLine[c++]);
bestStrand[row] = parseByteWMissing(inputLine[c++]);
bestStartPos[row] = parseIntWMissing(inputLine[c++]);
endPosition[row] = parseIntWMissing(inputLine[c++]);
divergence[row] = parseByteWMissing(inputLine[c++]);
byte[] currVD=new byte[myMaxVariants];
byte[] currVO=new byte[myMaxVariants];
int numWithData=0;
for (int j = 0; j < myMaxVariants; j++) {
currVO[j] = parseByteWMissing(inputLine[c++]);
currVD[j] = parseCharWMissing(inputLine[c++]);
if(currVO[j]!=TOPMInterface.BYTE_MISSING) numWithData++;
}
variantDefs[row]=Arrays.copyOf(currVD, numWithData);
variantOffsets[row]=Arrays.copyOf(currVO, numWithData);
dcoP[row] = parseByteWMissing(inputLine[c++]);
mapP[row] = parseByteWMissing(inputLine[c++]);
if (row % 1000000 == 0) {
System.out.println("Row Read:" + row);
}
}
} catch (Exception e) {
System.out.println("Catch in reading TagOnPhysicalMap file e=" + e);
e.printStackTrace();
System.out.println("Line:"+Arrays.toString(inputLine));
}
System.out.println("Number of tags in file:" + myNumTags);
}
@Override
public int getReadIndexForPositionIndex(int posIndex) {
return indicesOfSortByPosition[posIndex];
}
@Override
public int[] getPositionArray(int index) {
int[] r = {bestChr[index], bestStrand[index], bestStartPos[index]};
return r;
}
// public int getReadIndex(byte chr, byte bestStrand, int posMin) {
// // dep_ReadWithPositionInfo querySHP=new dep_ReadWithPositionInfo(bestChr, bestStrand, posMin);
// // PositionComparator posCompare = new PositionComparator();
// // int hit1=Arrays.binarySearch(shp, querySHP, posCompare);
// int hit1=-1; //redo
// return hit1;
// }
public static byte parseCharWMissing(String s) {
if (s.equals("*")) {
return Byte.MIN_VALUE;
}
try{
byte r=NucleotideAlignmentConstants.getNucleotideAlleleByte(s);
return r;
} catch(IllegalArgumentException e) {
int i = Integer.parseInt(s);
if (i > 127) {return 127;}
byte r=NucleotideAlignmentConstants.getNucleotideAlleleByte(String.valueOf((char)i));
return r;
}
}
public static byte parseByteWMissing(String s) {
if (s.equals("*")) {
return Byte.MIN_VALUE;
}
int i;
try {
i = Integer.parseInt(s);
if (i > 127) {
return 127;
}
return (byte) i;
} catch (NumberFormatException nf) {
return Byte.MIN_VALUE;
}
}
public static int parseIntWMissing(String s) {
if (s.equals("*")) {
return Integer.MIN_VALUE;
}
int i;
try {
i = Integer.parseInt(s);
return i;
} catch (NumberFormatException nf) {
return Integer.MIN_VALUE;
}
}
@Override
public byte getMultiMaps(int index) {
return multimaps[index];
}
@Override
public int getEndPosition(int index) {
return endPosition[index];
}
@Override
public byte getDivergence(int index) {
return divergence[index];
}
@Override
public byte getMapP(int index) {
return mapP[index];
}
@Override
public byte getDcoP(int index) {
return dcoP[index];
}
@Override
public void setChromoPosition(int index, int chromosome, byte strand, int positionMin,
int positionMax) {
this.bestChr[index] = chromosome;
this.bestStrand[index] = strand;
this.bestStartPos[index] = positionMin;
this.endPosition[index] = positionMax;
}
@Override
public void setDivergence(int index, byte divergence) {
this.divergence[index] = divergence;
}
@Override
public void setMapP(int index, byte mapP) {
this.mapP[index] = mapP;
}
@Override
public void setMapP(int index, double mapP) {
if (Double.isInfinite(mapP)) {
this.mapP[index] = Byte.MAX_VALUE;
return;
}
if (Double.isNaN(mapP) || (mapP < 0) || (mapP > 1)) {
this.mapP[index] = Byte.MIN_VALUE;
return;
}
if (mapP < 1e-126) {
this.mapP[index] = Byte.MAX_VALUE;
return;
}
this.mapP[index] = (byte) (-Math.round(Math.log10(mapP)));
}
@Override
public int addVariant(int tagIndex, byte offset, byte base) {
for (int i = 0; i < myMaxVariants; i++) {
if ((variantOffsets[tagIndex][i] == Byte.MIN_VALUE) && (variantDefs[tagIndex][i] == Byte.MIN_VALUE)) {
variantOffsets[tagIndex][i] = offset;
variantDefs[tagIndex][i] = base;
return i;
}
}
return -1; //no free space
}
/**
* Decodes bitwise flags from the code in SAM field 3. The code is a 32-bit
* integer, so I boolean AND the flag value with the code, and compare the
* result with the flag value. If they are equal, that means all bits set in
* the flag number were set in the code (i.e., that flag is turned on).
*/
private boolean flagSet(int code, int flag) {
int flagValue = 1 << flag; //1<<flag is equivalent to 2^flag
return ((code & flagValue) == flagValue);
}
/**
* Reads SAM files output from BWA or bowtie2
*/
public void readSAMFile(String inputFileName, int tagLengthInLong) {
System.out.println("Reading SAM format tag alignment from: " + inputFileName);
this.tagLengthInLong = tagLengthInLong;
String inputStr = "Nothing has been read from the file yet";
int nHeaderLines = countTagsInSAMfile(inputFileName); // detects if the file is bowtie2, initializes topm matrices
int tagIndex = Integer.MIN_VALUE;
try {
BufferedReader br;
if (inputFileName.endsWith(".gz")) {
br = new BufferedReader(new InputStreamReader(new MultiMemberGZIPInputStream(new FileInputStream(new File(inputFileName)))));
} else {
br = new BufferedReader(new FileReader(new File(inputFileName)), 65536);
}
for (int i = 0; i < nHeaderLines; i++) {
br.readLine();
} // Skip over the header
for (tagIndex = 0; tagIndex < myNumTags; tagIndex++) {
inputStr = br.readLine();
parseSAMAlignment(inputStr, tagIndex);
if (tagIndex % 1000000 == 0) {
System.out.println("Read " + tagIndex + " tags.");
}
}
br.close();
} catch (Exception e) {
System.out.println("\n\nCatch in reading SAM alignment file at tag " + tagIndex + ":\n\t" + inputStr + "\nError: " + e + "\n\n");
e.printStackTrace();
System.exit(1);
}
}
private int countTagsInSAMfile(String inputFileName) {
mySAMFormat = SAMFormat.BWA; // format is BWA by default
myNumTags = 0;
int nHeaderLines = 0;
String currLine = null;
try {
String[] inputLine;
ArrayList<String> chrNames = new ArrayList<String>();
BufferedReader br;
if (inputFileName.endsWith(".gz")) {
br = new BufferedReader(new InputStreamReader(new MultiMemberGZIPInputStream(new FileInputStream(new File(inputFileName)))));
} else {
br = new BufferedReader(new FileReader(new File(inputFileName)), 65536);
}
while ((currLine = br.readLine()) != null) {
inputLine = currLine.split("\\s");
if (inputLine[0].contains("@")) {
//SAM files produced by Bowtie2 contain the string "@PG ID:bowtie2 PN:bowtie2 "
if (inputLine[1].contains("bowtie2")) {
mySAMFormat = SAMFormat.BOWTIE2;
}
nHeaderLines++;
} else {
String chr = inputLine[2];
if (!chrNames.contains(chr)) {
chrNames.add(chr);
}
myNumTags++;
if (myNumTags % 1000000 == 0) {
System.out.println("Counted " + myNumTags + " tags.");
}
}
}
br.close();
System.out.println("Found " + myNumTags + " tags in SAM file. Assuming " + mySAMFormat + " file format.");
} catch (Exception e) {
System.out.println("Catch in counting lines of alignment file at line " + currLine + ": " + e);
e.printStackTrace();
System.exit(1);
}
initMatrices(myNumTags);
return nHeaderLines;
}
private void parseSAMAlignment(String inputStr, int tagIndex) {
String[] inputLine = inputStr.split("\t");
int name = 0, flag = 1, chr = 2, pos = 3, cigar = 5, tagS = 9; // column indices in inputLine
String nullS = this.getNullTag();
if ((Integer.parseInt(inputLine[flag]) & 4) == 4) { // bit 0x4 (= 2^2 = 4) is set: NO ALIGNMENT
recordLackOfSAMAlign(tagIndex, inputLine[tagS], inputLine[name], nullS);
} else { // aligns to one or more positions
HashMap<String, Integer> SAMFields = parseOptionalFieldsFromSAMAlignment(inputLine);
byte bestHits = (byte) Math.min(SAMFields.get("nBestHits"), Byte.MAX_VALUE);
byte editDist = (byte) Math.min(SAMFields.get("editDist"), Byte.MAX_VALUE);
byte currStrand = (Integer.parseInt(inputLine[flag]) == 16) ? (byte) -1 : (byte) 1;
recordSAMAlign(
tagIndex,
inputLine[tagS],
inputLine[name],
nullS,
bestHits,
inputLine[chr],
currStrand,
Integer.parseInt(inputLine[pos]),
inputLine[cigar],
editDist);
}
}
private HashMap<String, Integer> parseOptionalFieldsFromSAMAlignment(String[] inputLine) {
HashMap<String, Integer> SAMFields = new HashMap<String, Integer>();
if (mySAMFormat == SAMFormat.BWA) {
for (int field = 11; field < inputLine.length; field++) { // Loop through all the optional field of the SAM alignment
if (inputLine[field].regionMatches(0, "X0", 0, 2)) { // X0 = SAM format for # of "high-quality" alignments of this query. Specific to BWA.
SAMFields.put("nBestHits", Integer.parseInt(inputLine[field].split(":")[2]));
} else if (inputLine[field].regionMatches(0, "NM", 0, 2)) { // NM = SAM format for edit distance to the reference. Common to BWA and Bowtie2.
SAMFields.put("editDist", Integer.parseInt(inputLine[field].split(":")[2]));
}
}
} else { // bowtie2 -M format
for (int field = 11; field < inputLine.length; field++) { // Loop through all the optional field of the SAM alignment
if (inputLine[field].regionMatches(0, "AS", 0, 2)) { // AS = SAM format for alignment score of the best alignment. Specific to bowtie2.
SAMFields.put("bestScore", Integer.parseInt(inputLine[field].split(":")[2]));
} else if (inputLine[field].regionMatches(0, "XS", 0, 2)) { // XS = SAM format for alignment score of 2nd best alignment. Specific to bowtie2.
SAMFields.put("nextScore", Integer.parseInt(inputLine[field].split(":")[2]));
} else if (inputLine[field].regionMatches(0, "NM", 0, 2)) { // NM = SAM format for edit distance to the reference. Common to BWA and Bowtie2.
SAMFields.put("editDist", Integer.parseInt(inputLine[field].split(":")[2]));
}
}
if (SAMFields.containsKey("bestScore")) {
if (SAMFields.containsKey("nextScore")) {
if (SAMFields.get("bestScore") > SAMFields.get("nextScore")) {
SAMFields.put("nBestHits", 1);
} else {
SAMFields.put("nBestHits", 99); // 99 will stand for an unknown # of multiple hits
}
} else {
SAMFields.put("nBestHits", 1);
}
}
}
return SAMFields;
}
private void recordLackOfSAMAlign(int tagIndex, String tagS, String tagName, String nullS) {
recordTagFromSAMAlignment(tagIndex, tagS, tagName, nullS, (byte) 1);
multimaps[tagIndex] = 0; // or should this be unknown = Byte.MIN_VALUE???
bestChr[tagIndex] = Integer.MIN_VALUE;
bestStrand[tagIndex] = Byte.MIN_VALUE;
bestStartPos[tagIndex] = Integer.MIN_VALUE;
endPosition[tagIndex] = Integer.MIN_VALUE;
divergence[tagIndex] = Byte.MIN_VALUE;
for (int var = 0; var < myMaxVariants; var++) {
variantOffsets[tagIndex][var] = Byte.MIN_VALUE;
variantDefs[tagIndex][var] = Byte.MIN_VALUE;
}
dcoP[tagIndex] = Byte.MIN_VALUE;
mapP[tagIndex] = Byte.MIN_VALUE;
}
private void recordSAMAlign(int tagIndex, String tagS, String tagName, String nullS, byte nBestHits, String chrS, byte strand, int pos, String cigar, byte editDist) {
recordTagFromSAMAlignment(tagIndex, tagS, tagName, nullS, strand);
multimaps[tagIndex] = nBestHits;
if (nBestHits == 1) {
bestChr[tagIndex] = parseChrString(chrS);
this.bestStrand[tagIndex] = strand;
recordStartEndPostionFromSAMAlign(tagIndex, strand, pos, cigar);
} else {
bestChr[tagIndex] = Integer.MIN_VALUE;
this.bestStrand[tagIndex] = Byte.MIN_VALUE;
bestStartPos[tagIndex] = Integer.MIN_VALUE;
endPosition[tagIndex] = Integer.MIN_VALUE;
}
divergence[tagIndex] = editDist;
for (int var = 0; var < myMaxVariants; var++) {
variantOffsets[tagIndex][var] = Byte.MIN_VALUE;
variantDefs[tagIndex][var] = Byte.MIN_VALUE;
}
dcoP[tagIndex] = Byte.MIN_VALUE;
mapP[tagIndex] = Byte.MIN_VALUE;
}
private void recordTagFromSAMAlignment(int tagIndex, String tagS, String tagName, String nullS, byte strand) {
if (strand == -1) {
tagS = BaseEncoder.getReverseComplement(tagS);
}
if (tagS.length() < tagLengthInLong * 32) { // pad with polyA
tagS = tagS + nullS;
tagS = tagS.substring(0, (tagLengthInLong * 32));
}
long[] tagSequence = BaseEncoder.getLongArrayFromSeq(tagS);
for (int chunk = 0; chunk < tagLengthInLong; chunk++) {
tags[chunk][tagIndex] = tagSequence[chunk];
}
tagName = tagName.replaceFirst("count=[0-9]+", "");
tagName = tagName.replaceFirst("length=", "");
tagLength[tagIndex] = Byte.parseByte(tagName);
}
private int parseChrString(String chrS) {
int chr = Integer.MIN_VALUE;
chrS = chrS.replace("chr", "");
try {
chr = Integer.parseInt(chrS);
} catch (NumberFormatException e) {
System.out.println("\n\nSAMConverterPlugin detected a non-numeric chromosome name: " + chrS
+ "\n\nPlease change the FASTA headers in your reference genome sequence to integers "
+ "(>1, >2, >3, etc.) OR to 'chr' followed by an integer (>chr1, >chr2, >chr3, etc.)\n\n");
System.exit(1);
}
return chr;
}
private void recordStartEndPostionFromSAMAlign(int tagIndex, byte strand, int pos, String cigar) {
int[] alignSpan = SAMUtils.adjustCoordinates(cigar, pos);
try {
if (strand == 1) {
bestStartPos[tagIndex] = alignSpan[0];
endPosition[tagIndex] = alignSpan[1];
} else if (strand == -1) {
bestStartPos[tagIndex] = alignSpan[1];
endPosition[tagIndex] = alignSpan[0];
} else {
throw new Exception("Unexpected value for strand: " + strand + "(expect 1 or -1)");
}
} catch (Exception e) {
System.out.println("Error in recordStartEndPostionFromSAMAlign: " + e);
e.printStackTrace();
System.exit(1);
}
}
@Override
public void swap(int index1, int index2) {
long tl;
for (int i = 0; i < tagLengthInLong; i++) {
tl = tags[i][index1];
tags[i][index1] = tags[i][index2];
tags[i][index2] = tl;
}
int tb;
tb = tagLength[index1];
tagLength[index1] = tagLength[index2];
tagLength[index2] = (byte) tb;
tb = multimaps[index1];
multimaps[index1] = multimaps[index2];
multimaps[index2] = (byte) tb;
tb = bestChr[index1];
bestChr[index1] = bestChr[index2];
bestChr[index2] = tb;
tb = bestStrand[index1];
bestStrand[index1] = bestStrand[index2];
bestStrand[index2] = (byte) tb;
int ti;
ti = bestStartPos[index1];
bestStartPos[index1] = bestStartPos[index2];
bestStartPos[index2] = ti;
ti = endPosition[index1];
endPosition[index1] = endPosition[index2];
endPosition[index2] = ti;
tb = divergence[index1];
divergence[index1] = divergence[index2];
divergence[index2] = (byte) tb;
for (int j = 0; j < myMaxVariants; j++) {
tb = variantOffsets[index1][j];
variantOffsets[index1][j] = variantOffsets[index2][j];
variantOffsets[index2][j] = (byte) tb;
tb = variantDefs[index1][j];
variantDefs[index1][j] = variantDefs[index2][j];
variantDefs[index2][j] = (byte) tb;
}
tb = dcoP[index1];
dcoP[index1] = dcoP[index2];
dcoP[index2] = (byte) tb;
tb = mapP[index1];
mapP[index1] = mapP[index2];
mapP[index2] = (byte) tb;
}
@Override
public int compare(int index1, int index2) {
for (int i = 0; i < tagLengthInLong; i++) {
if (tags[i][index1] < tags[i][index2]) {
return -1;
}
if (tags[i][index1] > tags[i][index2]) {
return 1;
}
}
if (bestChr[index1] < bestChr[index2]) {
return -1;
}
if (bestChr[index1] > bestChr[index2]) {
return 1;
}
if (bestStartPos[index1] < bestStartPos[index2]) {
return -1;
}
if (bestStartPos[index1] > bestStartPos[index2]) {
return 1;
}
if (bestStrand[index1] < bestStrand[index2]) {
return -1;
}
if (bestStrand[index1] > bestStrand[index2]) {
return 1;
}
return 0;
}
@Override
public void setVariantDef(int tagIndex, int variantIndex, byte def) {
variantDefs[tagIndex][variantIndex] = (byte) NucleotideAlignmentConstants.NUCLEOTIDE_ALLELES[0][def].charAt(0);
}
@Override
public void setVariantPosOff(int tagIndex, int variantIndex, byte offset) {
variantOffsets[tagIndex][variantIndex] = offset;
}
@Override
public int getMaxNumVariants() {
return myMaxVariants;
}
/**
* First, find unique tags by concatenating them into a TagCountMutable
* object and collapsing duplicate rows.
*/
private static TagsOnPhysicalMap uniqueTags(String[] filenames) {
//Find dimensions of concatenated file
int tagLengthInLong = 0, maxVariants = 0, tagNum = 0;
for (String name : filenames) {
TagsOnPhysicalMap file = new TagsOnPhysicalMap(name, true);
tagNum += file.myNumTags;
if (file.myMaxVariants > maxVariants) {
maxVariants = file.myMaxVariants;
}
if (file.getTagSizeInLong() > tagLengthInLong) {
tagLengthInLong = file.getTagSizeInLong();
}
}
//Create new concatenated file
TagCountMutable tc = new TagCountMutable(tagLengthInLong, tagNum);
for (String name : filenames) {
TagsOnPhysicalMap file = new TagsOnPhysicalMap(name, true);
for (int i = 0; i < file.myNumTags; i++) {
tc.addReadCount(file.getTag(i), file.getTagLength(i), 1);
}
}
//Reduce concatenated file to unique tags
tc.collapseCounts();
tc.shrinkToCurrentRows();
TagsOnPhysicalMap result = new TagsOnPhysicalMap(tc);
result.expandMaxVariants(maxVariants);
result.clearVariants();
return result;
}
/**
* Merges several TOPM files into one, removing duplicate rows. Variants
* from matching tags are combined in the output file. If there are more
* variants in the input files than can fit in the output, extra variants
* are discarded with no particular order.
*/
public static TagsOnPhysicalMap merge(String[] filenames) {
TagsOnPhysicalMap output = uniqueTags(filenames);
System.out.println(
"Output file will contain "
+ output.myNumTags + " unique tags, "
+ output.getTagSizeInLong() + " longs/tag, "
+ output.myMaxVariants + " variants. ");
for (String name : filenames) {
TagsOnPhysicalMap file = new TagsOnPhysicalMap(name, true);
int varsAdded = 0, varsSkipped = 0;
for (int inTag = 0; inTag < file.myNumTags; inTag++) { //Loop over tags in input
//Find index of corresponding tag in output file, and copy attributes from input to output
int outTag = output.getTagIndex(file.getTag(inTag));
copyTagAttributes(file, inTag, output, outTag);
//For corresponding tags, compare variants
for (int outVar = 0; outVar < output.myMaxVariants; outVar++) {
byte outOff = output.getVariantPosOff(outTag, outVar);
if (outOff != BYTE_MISSING) {//Skip filled output variants or re-initialize them
varsSkipped++;
continue;
}
for (int inVar = 0; inVar < file.myMaxVariants; inVar++) {
byte offset = file.getVariantPosOff(inTag, outVar);
byte def = file.getVariantDef(inTag, outVar);
if (offset == BYTE_MISSING) {
continue; //Skip blank input variants
}
//If we get here, output variant is blank and input variant is non-blank at the same tag & variant indices
varsAdded++;
output.setVariantPosOff(outTag, outVar, offset);
output.setVariantDef(outTag, outVar, def);
file.setVariantPosOff(inTag, inVar, Byte.MIN_VALUE); //Erase this variant so it isn't encountered again
break; //Go to next output variant after copying
}
}
}
System.out.println(varsAdded + " variants added.");
System.out.println(varsSkipped + " variants skipped.");
}
return output;
}
/**
* Copies values of everything BUT tag sequence and variant data (i.e. tag
* attributes) from one TOPM file to another.
*/
private static void copyTagAttributes(TagsOnPhysicalMap input, int inTag, TagsOnPhysicalMap output, int outTag) {
output.tagLength[outTag] = input.tagLength[inTag];
output.multimaps[outTag] = input.multimaps[inTag];
output.bestChr[outTag] = input.bestChr[inTag];
output.bestStrand[outTag] = input.bestStrand[inTag];
output.bestStartPos[outTag] = input.bestStartPos[inTag];
output.endPosition[outTag] = input.endPosition[inTag];
output.divergence[outTag] = input.divergence[inTag];
output.dcoP[outTag] = input.dcoP[inTag];
output.mapP[outTag] = input.mapP[inTag];
}
/**
* Fills the variant definition & offset arrays with the value of
* "byteMissing".
*/
public void clearVariants() {
for (int i = 0; i < getTagCount(); i++) {
Arrays.fill(variantDefs[i], BYTE_MISSING);
Arrays.fill(variantOffsets[i], BYTE_MISSING);
}
}
/**
* Fills the variant definition & offset at the given indices with the value
* of "byteMissing".
*/
private void clearVariant(int tag, int variant) {
setVariantDef(tag, variant, BYTE_MISSING);
setVariantPosOff(tag, variant, BYTE_MISSING);
}
/**
* Clears variant sites that are not found in the supplied alignments.
*/
public void filter(String[] filenames) {
HashMap<String, Integer> hapmapSites = new HashMap<String, Integer>();
//Map all site positions from all alignments to their index.
for (String filename : filenames) {
System.out.println("Filtering out sites from " + filename + ".");
hapmapSites.putAll(hapmapSites(ImportUtils.readFromHapmap(filename, null)));
}
System.out.println("There are " + hapmapSites.size() + " sites in the hapmap files.");
//Map all tag variant positions to their index.
HashMap<String, Integer> topmSites = uniqueSites(); //Map tag variant positions to bases
//Sites should be a subset of tag variants, so check that there are fewer of them.
System.out.println("Found " + topmSites.size() + " unique sites in " + myNumTags + " tags in TOPM.");
if (topmSites.size() < hapmapSites.size()) {
System.out.println("Warning: more unique sites exist in hapmap file.");
}
//Next, check that each alignment site is present in If not, either there was no more room or something is wrong.
HashSet<Integer> fullSites = fullTagPositions(); //Tags which already have the maximum number of variants
ArrayList<String> insertedSites = new ArrayList<String>(); //Sites that don't correspond to a real tag
ArrayList<String> skippedSites = new ArrayList<String>(); //Real sites that were skipped due to "full tags"
int basePerTag = tagLengthInLong * 32;
for (String hapmapSNP : hapmapSites.keySet().toArray(new String[hapmapSites.size()])) {
int chr = Integer.parseInt(hapmapSNP.split("\\t")[0]);
int pos = Integer.parseInt(hapmapSNP.split("\\t")[1]);
if (topmSites.get(hapmapSNP) == null) {
// System.out.print("Warning: SNP "+chr+":"+pos+" is not in TOPM. ");
boolean inRange = false;
for (int i = -basePerTag; i < basePerTag; i++) {
if (fullSites.contains(i + pos)) {
inRange = true;
break;
}
}
if (inRange) {
skippedSites.add(hapmapSNP);
// System.out.println("However, it is within range of a tag with the max. number of variants.");
} else {
insertedSites.add(hapmapSNP);
System.out.println();
}
hapmapSites.remove(hapmapSNP);
continue;
}
}
System.out.println("The following SNPs were not in the TOPM, but are within range of a tag with the max. number of variants:");
for (String site : skippedSites) {
System.out.println(site);
}
System.out.println("The following SNPs were not in the TOPM, and do not correspond to any known tag:");
for (String site : insertedSites) {
System.out.println(site);
}
//Remove any sites from the TOPM that are absent in the alignment
int removedSites = 0;
for (int tag = 0; tag < myNumTags; tag++) {
int chr = getChromosome(tag);
int pos = getStartPosition(tag);
for (int variant = 0; variant < myMaxVariants; variant++) {
byte off = getVariantPosOff(tag, variant);
String site = chr + "\t" + (pos + off);
if (!hapmapSites.containsKey(site)) {
clearVariant(tag, variant);
removedSites++;
}
}
}
topmSites = uniqueSites();
System.out.println("Removed " + removedSites + " TOPM sites not present in alignment and ignored " + insertedSites.size() + " alignment sites not present in TOPM.");
System.out.println("There are " + topmSites.size() + " sites in the TOPM now, as compared to " + hapmapSites.size() + " sites in the alignment.");
if (topmSites.size() != hapmapSites.size()) {
System.out.println("Warning: number of filtered sites does not match number of alignment sites.");
}
}
/**
* Returns the start positions of tags whose variant arrays are full.
*/
public HashSet<Integer> fullTagPositions() {
HashSet<Integer> result = new HashSet<Integer>();
for (int i = 0; i < myNumTags; i++) {
boolean variantsFull = true;
for (int j = 0; j < myMaxVariants; j++) {
byte off = getVariantPosOff(i, j);
if (off == Byte.MIN_VALUE) {
variantsFull = false;
break;
}
}
if (variantsFull) {
result.add(getStartPosition(i));
}
}
return result;
}
/**
* Maps unique sites (i.e. bestChr and position) to the indices of the
* tags in which they are found.
*/
public HashMap<String, Integer> uniqueSites() {
HashMap<String, Integer> snps = new HashMap<String, Integer>();
for (int tag = 0; tag < myNumTags; tag++) { //Visit each tag in TOPM
for (int variant = 0; variant < myMaxVariants; variant++) { //Visit each variant in TOPM
byte off = getVariantPosOff(tag, variant);
if (off == BYTE_MISSING) {
continue;
}
int a = getStartPosition(tag);
int b = getVariantPosOff(tag, variant);
int c = a + b;
String pos = getChromosome(tag) + "\t" + c;
snps.put(pos, tag);
}
}
return snps;
}
public static HashMap<String, Integer> hapmapSites(GenotypeTable file) {
HashMap<String, Integer> snps = new HashMap<String, Integer>();
for (int site = 0; site < file.numberOfSites(); site++) { //Visit each site
String pos = (file.chromosomeName(site) + "\t"
+ file.chromosomalPosition(site));
if (file.chromosomalPosition(site) > 2000000000) {
System.out.println(pos);
}
snps.put(pos, site);
}
return snps;
}
/**
* Returns an array whose indices are the number of mappings and whose
* elements are the number of tags with that mapping.
*/
public int[] mappingDistribution() {
int[] result = new int[128]; //Only up to 127 multiple mappings are stored.
for (int i = 0; i < myNumTags; i++) {
if (multimaps[i] > (result.length - 1)) {
result[127]++;
}
if (multimaps[i] == BYTE_MISSING) {
result[0]++;
continue;
} else {
result[multimaps[i]]++;
}
}
return result;
}
}
| Additional changes needed so it works with ragged arrays for variantOffsets[] and variantDefs[]
| src/net/maizegenetics/dna/map/TagsOnPhysicalMap.java | Additional changes needed so it works with ragged arrays for variantOffsets[] and variantDefs[] |
|
Java | mit | c2bfa7452b0af3ab66f3a61a63d684a3a38b9099 | 0 | trujunzhang/IEATTA-ANDROID,trujunzhang/IEATTA-ANDROID | package org.ieatta.activity.leadimages;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.location.Location;
import android.support.annotation.ColorInt;
import android.support.annotation.DimenRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import org.ieatta.R;
import org.ieatta.activity.LeadImage;
import org.ieatta.activity.PageProperties;
import org.ieatta.activity.PageTitle;
import org.ieatta.activity.Page;
import org.ieatta.activity.PageFragment;
import org.ieatta.tasks.FragmentTask;
import org.ieatta.views.ObservableWebView;
import org.json.JSONException;
import org.json.JSONObject;
import org.wikipedia.concurrency.RecurringTask;
import org.wikipedia.util.DimenUtil;
import java.util.LinkedList;
import java.util.List;
import bolts.Continuation;
import bolts.Task;
import static org.wikipedia.util.DimenUtil.getContentTopOffsetPx;
public class LeadImagesHandler {
public interface OnContentHeightChangedListener {
void onContentHeightChanged(int contentHeight);
}
private List<OnContentHeightChangedListener> onContentHeightChangedListeners = new LinkedList<>();
public void addOnContentHeightChangedListener(OnContentHeightChangedListener onContentHeightChangedListener) {
onContentHeightChangedListeners.add(onContentHeightChangedListener);
}
/**
* Minimum screen height for enabling lead images. If the screen is smaller than
* this height, lead images will not be displayed, and will be substituted with just
* the page title.
*/
private static final int MIN_SCREEN_HEIGHT_DP = 480;
public interface OnLeadImageLayoutListener {
void onLayoutComplete(int sequence);
}
@NonNull
private final PageFragment parentFragment;
@NonNull
private final ObservableWebView webView;
@NonNull
private final ArticleHeaderView articleHeaderView;
private View image;
private int displayHeightDp;
private float faceYOffsetNormalized;
private float displayDensity;
private RecurringTask task;
public LeadImagesHandler(@NonNull final PageFragment parentFragment,
@NonNull ObservableWebView webView,
@NonNull ArticleHeaderView articleHeaderView) {
this.articleHeaderView = articleHeaderView;
this.articleHeaderView.setMenuBarCallback(new MenuBarCallback());
this.parentFragment = parentFragment;
this.webView = webView;
image = articleHeaderView.getImage();
initDisplayDimensions();
initWebView();
initArticleHeaderView();
// hide ourselves by default
hide();
}
private void initWebView() {
webView.addOnScrollChangeListener(articleHeaderView);
webView.addOnClickListener(new ObservableWebView.OnClickListener() {
@Override
public boolean onClick(float x, float y) {
// if the click event is within the area of the lead image, then the user
// must have wanted to click on the lead image!
if (getPage() != null && isLeadImageEnabled() && y < (articleHeaderView.getHeight() - webView.getScrollY())) {
// String imageName = getPage().getPageProperties().getLeadImageName();
// if (imageName != null) {
// PageTitle imageTitle = new PageTitle("File:" + imageName,
// getTitle().getSite());
// GalleryActivity.showGallery(getActivity(),
// parentFragment.getTitleOriginal(), imageTitle,
// GalleryFunnel.SOURCE_LEAD_IMAGE);
// }
return true;
}
return false;
}
});
}
/**
* Completely hide the lead image view. Useful in case of network errors, etc.
* The only way to "show" the lead image view is by calling the beginLayout function.
*/
public void hide() {
articleHeaderView.hide();
}
@Nullable
public Bitmap getLeadImageBitmap() {
return isLeadImageEnabled() ? articleHeaderView.copyBitmap() : null;
}
public boolean isLeadImageEnabled() {
return true;
// return IEAApp.getInstance().isImageDownloadEnabled()
// && displayHeightDp >= MIN_SCREEN_HEIGHT_DP
// && !TextUtils.isEmpty(getLeadImageUrl());
}
public void updateBookmark(boolean bookmarkSaved) {
articleHeaderView.updateBookmark(bookmarkSaved);
}
public void updateNavigate(@Nullable Location geo) {
articleHeaderView.updateNavigate(geo != null);
}
public void updateMenuItemsVisibilities(int source) {
articleHeaderView.updateMenuItemsVisibilities(source);
}
public void setAnimationPaused(boolean paused) {
articleHeaderView.setAnimationPaused(paused);
}
/**
* Returns the normalized (0.0 to 1.0) vertical focus position of the lead image.
* A value of 0.0 represents the top of the image, and 1.0 represents the bottom.
* The "focus position" is currently defined by automatic face detection, but may be
* defined by other factors in the future.
*
* @return Normalized vertical focus position.
*/
public float getLeadImageFocusY() {
return faceYOffsetNormalized;
}
/**
* Triggers a chain of events that will lay out the lead image, page title, and other
* elements, at the end of which the WebView contents may begin to be composed.
* These events (performed asynchronously) are in the following order:
* - Dynamically resize the page title TextView and, if necessary, adjust its font size
* based on the length of our page title.
* - Dynamically resize the lead image container view and restyle it, if necessary, depending
* on whether the page contains a lead image, and whether our screen resolution is high
* enough to warrant a lead image.
* - Send a "padding" event to the WebView so that any subsequent content that's added to it
* will be correctly offset to account for the lead image view (or lack of it)
* - Make the lead image view visible.
* - Fire a callback to the provided Listener indicating that the rest of the WebView content
* can now be loaded.
* - Fetch and display the WikiData description for this page, if available.
* <p/>
* Realistically, the whole process will happen very quickly, and almost unnoticeably to the
* user. But it still needs to be asynchronous because we're dynamically laying out views, and
* because the padding "event" that we send to the WebView must come before any other content
* is sent to it, so that the effect doesn't look jarring to the user.
*
* @param listener Listener that will receive an event when the layout is completed.
*/
public void beginLayout(OnLeadImageLayoutListener listener,
int sequence) {
if (getPage() == null) {
return;
}
initDisplayDimensions();
if (this.getPage().getPageProperties().getLeadImageCount() < 2) {
LeadImagesHandler.this.recurringLeadImages();
} else {
if (task != null) {
task.closeTask();
task = null;
}
task = new RecurringTask();
// set the page title text, and honor any HTML formatting in the title
task.periodicTask(new RecurringTask.RecurringEvent() {
@Override
public void everyTask() {
LeadImagesHandler.this.recurringLeadImages();
}
}, 0, 20);
}
articleHeaderView.setTitle(Html.fromHtml(getPage().getDisplayTitle()));
// articleHeaderView.setLocale(getPage().getTitle().getSite().getLanguageCode());
// Set the subtitle, too, so text measurements are accurate.
layoutWikiDataDescription(getTitle().getDescription());
layoutViews(listener, sequence);
}
private void recurringLeadImages() {
if (this.getPage() == null) {
return;
}
final PageProperties pageProperties = this.getPage().getPageProperties();
pageProperties.getCurrentLeadImage().onSuccess(new Continuation<LeadImage, Void>() {
@Override
public Void then(Task<LeadImage> task) throws Exception {
LeadImagesHandler.this.loadLeadImage(task.getResult());
pageProperties.nextLeadImage();
return null;
}
}, Task.UI_THREAD_EXECUTOR);
}
/**
* The final step in the layout process:
* Apply sizing and styling to our page title and lead image views, based on how large our
* page title ended up, and whether we should display the lead image.
*
* @param listener Listener that will receive an event when the layout is completed.
*/
private void layoutViews(OnLeadImageLayoutListener listener, int sequence) {
if (!isFragmentAdded()) {
return;
}
if (isMainPage()) {
articleHeaderView.hide();
} else {
if (!isLeadImageEnabled()) {
articleHeaderView.showText();
} else {
articleHeaderView.showTextImage();
}
}
// tell our listener that it's ok to start loading the rest of the WebView content
listener.onLayoutComplete(sequence);
}
private void updatePadding() {
int padding;
if (isMainPage()) {
padding = Math.round(getContentTopOffsetPx(getActivity()) / displayDensity);
} else {
int height = articleHeaderView.getHeight();
for (OnContentHeightChangedListener listener : onContentHeightChangedListeners) {
listener.onContentHeightChanged(height);
}
padding = Math.round(height / displayDensity);
}
setWebViewPaddingTop(padding);
}
private void setWebViewPaddingTop(int padding) {
JSONObject payload = new JSONObject();
try {
payload.put("paddingTop", padding);
} catch (JSONException e) {
throw new RuntimeException(e);
}
// bridge.sendMessage("setPaddingTop", payload);
}
/**
* Final step in the WikiData description process: lay out the description, and animate it
* into place, along with the page title.
*
* @param description WikiData description to be shown.
*/
private void layoutWikiDataDescription(@Nullable final String description) {
if (TextUtils.isEmpty(description)) {
articleHeaderView.setSubtitle(null);
} else {
int titleLineCount = articleHeaderView.getLineCount();
articleHeaderView.setSubtitle(description);
// Only show the description if it's two lines or less.
if ((articleHeaderView.getLineCount() - titleLineCount) > 2) {
articleHeaderView.setSubtitle(null);
}
}
}
/**
* Determines and sets displayDensity and displayHeightDp for the lead images layout.
*/
private void initDisplayDimensions() {
// preload the display density, since it will be used in a lot of places
displayDensity = DimenUtil.getDensityScalar();
int displayHeightPx = DimenUtil.getDisplayHeightPx();
displayHeightDp = (int) (displayHeightPx / displayDensity);
}
// private void loadLeadImage(String url) {
// loadLeadImage(url);
// }
/**
* @param leadImage Nullable URL with no scheme. For example, foo.bar.com/ instead of
* http://foo.bar.com/.
*/
private void loadLeadImage(@Nullable LeadImage leadImage) {
if (!isMainPage() && leadImage != null && isLeadImageEnabled()) {
articleHeaderView.setImageYScalar(0);
articleHeaderView.loadImage(leadImage);
} else {
articleHeaderView.loadImage(null);
}
}
// /**
// * @return Nullable URL with no scheme. For example, foo.bar.com/ instead of
// * http://foo.bar.com/.
// */
// @Nullable
// private String getLeadImageUrl() {
// return getPage() == null ? null : getPage().getPageProperties().getLeadImageUrl();
// }
@Nullable
private Location getGeo() {
// return getPage() == null ? null : getPage().getPageProperties().getGeo();
return null;
}
private void startKenBurnsAnimation() {
Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.lead_image_zoom);
image.startAnimation(anim);
}
private void initArticleHeaderView() {
articleHeaderView.setOnImageLoadListener(new ImageLoadListener());
articleHeaderView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
@SuppressWarnings("checkstyle:parameternumber")
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
updatePadding();
}
});
}
private boolean isMainPage() {
FragmentTask task = parentFragment.getTask();
return task != null && task.isMainPage();
}
private PageTitle getTitle() {
return parentFragment.getTitle();
}
@Nullable
private Page getPage() {
return parentFragment.getPage();
}
private boolean isFragmentAdded() {
return parentFragment.isAdded();
}
private float getDimension(@DimenRes int id) {
return getResources().getDimension(id);
}
private Resources getResources() {
return getActivity().getResources();
}
private FragmentActivity getActivity() {
return parentFragment.getActivity();
}
private class MenuBarCallback extends ArticleMenuBarView.DefaultCallback {
@Override
public void onBookmarkClick(boolean bookmarkSaved) {
// if (getPage() == null) {
// return;
// }
//
// if (bookmarkSaved) {
// saveBookmark();
// } else {
// deleteBookmark();
// }
}
@Override
public void onShareClick() {
// if (getPage() != null) {
// ShareUtil.shareText(getActivity(), getPage().getTitle());
// }
}
@Override
public void onNavigateClick() {
openGeoIntent();
}
private void saveBookmark() {
}
private void deleteBookmark() {
}
private void openGeoIntent() {
if (getGeo() != null) {
// UriUtil.sendGeoIntent(getActivity(), getGeo(), getTitle().getDisplayText());
}
}
}
private class ImageLoadListener implements ImageViewWithFace.OnImageLoadListener {
@Override
public void onImageLoaded(final int bmpHeight, @Nullable final PointF faceLocation, @ColorInt final int mainColor) {
articleHeaderView.post(new Runnable() {
@Override
public void run() {
if (isFragmentAdded()) {
applyFaceLocationOffset(bmpHeight, faceLocation);
articleHeaderView.setMenuBarColor(mainColor);
startKenBurnsAnimation();
}
}
});
}
@Override
public void onImageFailed() {
articleHeaderView.resetMenuBarColor();
}
private void applyFaceLocationOffset(int bmpHeight, @Nullable PointF faceLocation) {
faceYOffsetNormalized = faceYScalar(bmpHeight, faceLocation);
articleHeaderView.setImageYScalar(constrainScalar(faceYOffsetNormalized));
}
private float constrainScalar(float scalar) {
scalar = Math.max(0, scalar);
scalar = Math.min(scalar, 1);
return scalar;
}
private float faceYScalar(int bmpHeight, @Nullable PointF faceLocation) {
final float defaultOffsetScalar = .25f;
float scalar = defaultOffsetScalar;
if (faceLocation != null) {
scalar = faceLocation.y;
// TODO: if it is desirable to offset to the nose, replace this arbitrary hardcoded
// value with a proportion. FaceDetector.eyesDistance() presumably provides
// the interpupillary distance in pixels. We can multiply this measurement by
// the proportion of the length of the nose to the IPD.
scalar -= getDimension(R.dimen.face_detection_nose_y_offset) / bmpHeight;
}
return scalar;
}
}
public int getParallaxScrollY() {
return this.articleHeaderView.parallaxScrollY;
}
}
| app/src/main/java/org/ieatta/activity/leadimages/LeadImagesHandler.java | package org.ieatta.activity.leadimages;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.location.Location;
import android.support.annotation.ColorInt;
import android.support.annotation.DimenRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import org.ieatta.R;
import org.ieatta.activity.LeadImage;
import org.ieatta.activity.PageProperties;
import org.ieatta.activity.PageTitle;
import org.ieatta.activity.Page;
import org.ieatta.activity.PageFragment;
import org.ieatta.tasks.FragmentTask;
import org.ieatta.views.ObservableWebView;
import org.json.JSONException;
import org.json.JSONObject;
import org.wikipedia.concurrency.RecurringTask;
import org.wikipedia.util.DimenUtil;
import java.util.LinkedList;
import java.util.List;
import bolts.Continuation;
import bolts.Task;
import static org.wikipedia.util.DimenUtil.getContentTopOffsetPx;
public class LeadImagesHandler {
public interface OnContentHeightChangedListener {
void onContentHeightChanged(int contentHeight);
}
private List<OnContentHeightChangedListener> onContentHeightChangedListeners = new LinkedList<>();
public void addOnContentHeightChangedListener(OnContentHeightChangedListener onContentHeightChangedListener) {
onContentHeightChangedListeners.add(onContentHeightChangedListener);
}
/**
* Minimum screen height for enabling lead images. If the screen is smaller than
* this height, lead images will not be displayed, and will be substituted with just
* the page title.
*/
private static final int MIN_SCREEN_HEIGHT_DP = 480;
public interface OnLeadImageLayoutListener {
void onLayoutComplete(int sequence);
}
@NonNull
private final PageFragment parentFragment;
@NonNull
private final ObservableWebView webView;
@NonNull
private final ArticleHeaderView articleHeaderView;
private View image;
private int displayHeightDp;
private float faceYOffsetNormalized;
private float displayDensity;
private RecurringTask task;
public LeadImagesHandler(@NonNull final PageFragment parentFragment,
@NonNull ObservableWebView webView,
@NonNull ArticleHeaderView articleHeaderView) {
this.articleHeaderView = articleHeaderView;
this.articleHeaderView.setMenuBarCallback(new MenuBarCallback());
this.parentFragment = parentFragment;
this.webView = webView;
image = articleHeaderView.getImage();
initDisplayDimensions();
initWebView();
initArticleHeaderView();
// hide ourselves by default
hide();
}
private void initWebView() {
webView.addOnScrollChangeListener(articleHeaderView);
webView.addOnClickListener(new ObservableWebView.OnClickListener() {
@Override
public boolean onClick(float x, float y) {
// if the click event is within the area of the lead image, then the user
// must have wanted to click on the lead image!
if (getPage() != null && isLeadImageEnabled() && y < (articleHeaderView.getHeight() - webView.getScrollY())) {
// String imageName = getPage().getPageProperties().getLeadImageName();
// if (imageName != null) {
// PageTitle imageTitle = new PageTitle("File:" + imageName,
// getTitle().getSite());
// GalleryActivity.showGallery(getActivity(),
// parentFragment.getTitleOriginal(), imageTitle,
// GalleryFunnel.SOURCE_LEAD_IMAGE);
// }
return true;
}
return false;
}
});
}
/**
* Completely hide the lead image view. Useful in case of network errors, etc.
* The only way to "show" the lead image view is by calling the beginLayout function.
*/
public void hide() {
articleHeaderView.hide();
}
@Nullable
public Bitmap getLeadImageBitmap() {
return isLeadImageEnabled() ? articleHeaderView.copyBitmap() : null;
}
public boolean isLeadImageEnabled() {
return true;
// return IEAApp.getInstance().isImageDownloadEnabled()
// && displayHeightDp >= MIN_SCREEN_HEIGHT_DP
// && !TextUtils.isEmpty(getLeadImageUrl());
}
public void updateBookmark(boolean bookmarkSaved) {
articleHeaderView.updateBookmark(bookmarkSaved);
}
public void updateNavigate(@Nullable Location geo) {
articleHeaderView.updateNavigate(geo != null);
}
public void updateMenuItemsVisibilities(int source) {
articleHeaderView.updateMenuItemsVisibilities(source);
}
public void setAnimationPaused(boolean paused) {
articleHeaderView.setAnimationPaused(paused);
}
/**
* Returns the normalized (0.0 to 1.0) vertical focus position of the lead image.
* A value of 0.0 represents the top of the image, and 1.0 represents the bottom.
* The "focus position" is currently defined by automatic face detection, but may be
* defined by other factors in the future.
*
* @return Normalized vertical focus position.
*/
public float getLeadImageFocusY() {
return faceYOffsetNormalized;
}
/**
* Triggers a chain of events that will lay out the lead image, page title, and other
* elements, at the end of which the WebView contents may begin to be composed.
* These events (performed asynchronously) are in the following order:
* - Dynamically resize the page title TextView and, if necessary, adjust its font size
* based on the length of our page title.
* - Dynamically resize the lead image container view and restyle it, if necessary, depending
* on whether the page contains a lead image, and whether our screen resolution is high
* enough to warrant a lead image.
* - Send a "padding" event to the WebView so that any subsequent content that's added to it
* will be correctly offset to account for the lead image view (or lack of it)
* - Make the lead image view visible.
* - Fire a callback to the provided Listener indicating that the rest of the WebView content
* can now be loaded.
* - Fetch and display the WikiData description for this page, if available.
* <p/>
* Realistically, the whole process will happen very quickly, and almost unnoticeably to the
* user. But it still needs to be asynchronous because we're dynamically laying out views, and
* because the padding "event" that we send to the WebView must come before any other content
* is sent to it, so that the effect doesn't look jarring to the user.
*
* @param listener Listener that will receive an event when the layout is completed.
*/
public void beginLayout(OnLeadImageLayoutListener listener,
int sequence) {
if (getPage() == null) {
return;
}
initDisplayDimensions();
if (this.getPage().getPageProperties().getLeadImageCount() < 2) {
LeadImagesHandler.this.recurringLeadImages();
} else {
if (task != null) {
task.closeTask();
task = null;
}
task = new RecurringTask();
// set the page title text, and honor any HTML formatting in the title
task.periodicTask(new RecurringTask.RecurringEvent() {
@Override
public void everyTask() {
LeadImagesHandler.this.recurringLeadImages();
}
}, 0, 10);
}
articleHeaderView.setTitle(Html.fromHtml(getPage().getDisplayTitle()));
// articleHeaderView.setLocale(getPage().getTitle().getSite().getLanguageCode());
// Set the subtitle, too, so text measurements are accurate.
layoutWikiDataDescription(getTitle().getDescription());
layoutViews(listener, sequence);
}
private void recurringLeadImages() {
if (this.getPage() == null) {
return;
}
final PageProperties pageProperties = this.getPage().getPageProperties();
pageProperties.getCurrentLeadImage().onSuccess(new Continuation<LeadImage, Void>() {
@Override
public Void then(Task<LeadImage> task) throws Exception {
LeadImagesHandler.this.loadLeadImage(task.getResult());
pageProperties.nextLeadImage();
return null;
}
}, Task.UI_THREAD_EXECUTOR);
}
/**
* The final step in the layout process:
* Apply sizing and styling to our page title and lead image views, based on how large our
* page title ended up, and whether we should display the lead image.
*
* @param listener Listener that will receive an event when the layout is completed.
*/
private void layoutViews(OnLeadImageLayoutListener listener, int sequence) {
if (!isFragmentAdded()) {
return;
}
if (isMainPage()) {
articleHeaderView.hide();
} else {
if (!isLeadImageEnabled()) {
articleHeaderView.showText();
} else {
articleHeaderView.showTextImage();
}
}
// tell our listener that it's ok to start loading the rest of the WebView content
listener.onLayoutComplete(sequence);
}
private void updatePadding() {
int padding;
if (isMainPage()) {
padding = Math.round(getContentTopOffsetPx(getActivity()) / displayDensity);
} else {
int height = articleHeaderView.getHeight();
for (OnContentHeightChangedListener listener : onContentHeightChangedListeners) {
listener.onContentHeightChanged(height);
}
padding = Math.round(height / displayDensity);
}
setWebViewPaddingTop(padding);
}
private void setWebViewPaddingTop(int padding) {
JSONObject payload = new JSONObject();
try {
payload.put("paddingTop", padding);
} catch (JSONException e) {
throw new RuntimeException(e);
}
// bridge.sendMessage("setPaddingTop", payload);
}
/**
* Final step in the WikiData description process: lay out the description, and animate it
* into place, along with the page title.
*
* @param description WikiData description to be shown.
*/
private void layoutWikiDataDescription(@Nullable final String description) {
if (TextUtils.isEmpty(description)) {
articleHeaderView.setSubtitle(null);
} else {
int titleLineCount = articleHeaderView.getLineCount();
articleHeaderView.setSubtitle(description);
// Only show the description if it's two lines or less.
if ((articleHeaderView.getLineCount() - titleLineCount) > 2) {
articleHeaderView.setSubtitle(null);
}
}
}
/**
* Determines and sets displayDensity and displayHeightDp for the lead images layout.
*/
private void initDisplayDimensions() {
// preload the display density, since it will be used in a lot of places
displayDensity = DimenUtil.getDensityScalar();
int displayHeightPx = DimenUtil.getDisplayHeightPx();
displayHeightDp = (int) (displayHeightPx / displayDensity);
}
// private void loadLeadImage(String url) {
// loadLeadImage(url);
// }
/**
* @param leadImage Nullable URL with no scheme. For example, foo.bar.com/ instead of
* http://foo.bar.com/.
*/
private void loadLeadImage(@Nullable LeadImage leadImage) {
if (!isMainPage() && leadImage != null && isLeadImageEnabled()) {
articleHeaderView.setImageYScalar(0);
articleHeaderView.loadImage(leadImage);
} else {
articleHeaderView.loadImage(null);
}
}
// /**
// * @return Nullable URL with no scheme. For example, foo.bar.com/ instead of
// * http://foo.bar.com/.
// */
// @Nullable
// private String getLeadImageUrl() {
// return getPage() == null ? null : getPage().getPageProperties().getLeadImageUrl();
// }
@Nullable
private Location getGeo() {
// return getPage() == null ? null : getPage().getPageProperties().getGeo();
return null;
}
private void startKenBurnsAnimation() {
Animation anim = AnimationUtils.loadAnimation(getActivity(), R.anim.lead_image_zoom);
image.startAnimation(anim);
}
private void initArticleHeaderView() {
articleHeaderView.setOnImageLoadListener(new ImageLoadListener());
articleHeaderView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
@SuppressWarnings("checkstyle:parameternumber")
public void onLayoutChange(View v, int left, int top, int right, int bottom,
int oldLeft, int oldTop, int oldRight, int oldBottom) {
updatePadding();
}
});
}
private boolean isMainPage() {
FragmentTask task = parentFragment.getTask();
return task != null && task.isMainPage();
}
private PageTitle getTitle() {
return parentFragment.getTitle();
}
@Nullable
private Page getPage() {
return parentFragment.getPage();
}
private boolean isFragmentAdded() {
return parentFragment.isAdded();
}
private float getDimension(@DimenRes int id) {
return getResources().getDimension(id);
}
private Resources getResources() {
return getActivity().getResources();
}
private FragmentActivity getActivity() {
return parentFragment.getActivity();
}
private class MenuBarCallback extends ArticleMenuBarView.DefaultCallback {
@Override
public void onBookmarkClick(boolean bookmarkSaved) {
// if (getPage() == null) {
// return;
// }
//
// if (bookmarkSaved) {
// saveBookmark();
// } else {
// deleteBookmark();
// }
}
@Override
public void onShareClick() {
// if (getPage() != null) {
// ShareUtil.shareText(getActivity(), getPage().getTitle());
// }
}
@Override
public void onNavigateClick() {
openGeoIntent();
}
private void saveBookmark() {
}
private void deleteBookmark() {
}
private void openGeoIntent() {
if (getGeo() != null) {
// UriUtil.sendGeoIntent(getActivity(), getGeo(), getTitle().getDisplayText());
}
}
}
private class ImageLoadListener implements ImageViewWithFace.OnImageLoadListener {
@Override
public void onImageLoaded(final int bmpHeight, @Nullable final PointF faceLocation, @ColorInt final int mainColor) {
articleHeaderView.post(new Runnable() {
@Override
public void run() {
if (isFragmentAdded()) {
applyFaceLocationOffset(bmpHeight, faceLocation);
articleHeaderView.setMenuBarColor(mainColor);
startKenBurnsAnimation();
}
}
});
}
@Override
public void onImageFailed() {
articleHeaderView.resetMenuBarColor();
}
private void applyFaceLocationOffset(int bmpHeight, @Nullable PointF faceLocation) {
faceYOffsetNormalized = faceYScalar(bmpHeight, faceLocation);
articleHeaderView.setImageYScalar(constrainScalar(faceYOffsetNormalized));
}
private float constrainScalar(float scalar) {
scalar = Math.max(0, scalar);
scalar = Math.min(scalar, 1);
return scalar;
}
private float faceYScalar(int bmpHeight, @Nullable PointF faceLocation) {
final float defaultOffsetScalar = .25f;
float scalar = defaultOffsetScalar;
if (faceLocation != null) {
scalar = faceLocation.y;
// TODO: if it is desirable to offset to the nose, replace this arbitrary hardcoded
// value with a proportion. FaceDetector.eyesDistance() presumably provides
// the interpupillary distance in pixels. We can multiply this measurement by
// the proportion of the length of the nose to the IPD.
scalar -= getDimension(R.dimen.face_detection_nose_y_offset) / bmpHeight;
}
return scalar;
}
}
public int getParallaxScrollY() {
return this.articleHeaderView.parallaxScrollY;
}
}
| IEATTA for Android.
| app/src/main/java/org/ieatta/activity/leadimages/LeadImagesHandler.java | IEATTA for Android. |
|
Java | mit | 9cc9418ccd854778f22be83dcebddc103ad05659 | 0 | henrikor2/bridlensis,henrikor2/bridlensis | package bridlensis;
import java.io.PrintStream;
public class Logger {
public static final int ERROR = 0;
public static final int WARN = 1;
public static final int INFO = 2;
public static final int DEBUG = 3;
private static Logger instance = null;
public static Logger getInstance() {
if (instance == null) {
instance = new Logger();
}
return instance;
}
private PrintStream output;
private int level;
private Logger() {
output = System.out;
level = INFO;
}
public void setPrintStream(PrintStream printStream) {
output = printStream;
}
public void setLogLevel(int level) {
this.level = level;
}
private void log(int level, String msg) {
if (level <= this.level) {
output.println(msg);
}
}
public void error(BridleNSISException e) {
log(ERROR, e.getMessage());
}
public void warn(InputReader reader, String message) {
warn(String.format("%s, line %d: %s", reader.getFile(),
reader.getLinesRead(), message));
}
public void warn(String message) {
log(WARN, message);
}
public void info(String message) {
log(INFO, message);
}
public void info(InputReader reader, String message) {
info(String.format("%s, line %d: %s", reader.getFile(),
reader.getLinesRead(), message));
}
public void debug(String message) {
log(DEBUG, message);
}
public void debug(InputReader reader, String message) {
debug(String.format("%s, line %d: %s", reader.getFile(),
reader.getLinesRead(), message));
}
}
| src/main/java/bridlensis/Logger.java | package bridlensis;
import java.io.PrintStream;
public class Logger {
private static final int ERROR = 4;
private static final int WARN = 3;
private static final int INFO = 2;
private static final int DEBUG = 1;
private static Logger instance = null;
public static Logger getInstance() {
if (instance == null) {
instance = new Logger();
}
return instance;
}
private PrintStream output;
private int level;
private Logger() {
output = System.out;
level = INFO;
}
public void setPrintStream(PrintStream printStream) {
output = printStream;
}
private void log(int level, String msg) {
if (level >= this.level) {
output.println(msg);
}
}
public void error(BridleNSISException e) {
log(ERROR, e.getMessage());
}
public void warn(InputReader reader, String message) {
warn(String.format("%s, line %d: %s", reader.getFile(),
reader.getLinesRead(), message));
}
public void warn(String message) {
log(WARN, message);
}
public void info(String message) {
log(INFO, message);
}
public void info(InputReader reader, String message) {
info(String.format("%s, line %d: %s", reader.getFile(),
reader.getLinesRead(), message));
}
public void debug(String message) {
log(DEBUG, message);
}
public void debug(InputReader reader, String message) {
debug(String.format("%s, line %d: %s", reader.getFile(),
reader.getLinesRead(), message));
}
}
| Change the log levels so that ERROR = lowest(0) and DEBUG = highest(3).
| src/main/java/bridlensis/Logger.java | Change the log levels so that ERROR = lowest(0) and DEBUG = highest(3). |
|
Java | mit | 91527df490552327e2beb3e2c54bbfaa76589084 | 0 | intelchen/jenkins,amuniz/jenkins,bkmeneguello/jenkins,soenter/jenkins,morficus/jenkins,1and1/jenkins,fbelzunc/jenkins,duzifang/my-jenkins,viqueen/jenkins,oleg-nenashev/jenkins,svanoort/jenkins,liupugong/jenkins,bkmeneguello/jenkins,ChrisA89/jenkins,jpederzolli/jenkins-1,pjanouse/jenkins,arunsingh/jenkins,gitaccountforprashant/gittest,tangkun75/jenkins,bpzhang/jenkins,dariver/jenkins,tangkun75/jenkins,SebastienGllmt/jenkins,AustinKwang/jenkins,morficus/jenkins,mdonohue/jenkins,msrb/jenkins,vlajos/jenkins,intelchen/jenkins,christ66/jenkins,olivergondza/jenkins,andresrc/jenkins,bpzhang/jenkins,dariver/jenkins,maikeffi/hudson,rlugojr/jenkins,guoxu0514/jenkins,1and1/jenkins,damianszczepanik/jenkins,v1v/jenkins,ns163/jenkins,keyurpatankar/hudson,varmenise/jenkins,Krasnyanskiy/jenkins,patbos/jenkins,chbiel/jenkins,wuwen5/jenkins,batmat/jenkins,lindzh/jenkins,bkmeneguello/jenkins,amuniz/jenkins,6WIND/jenkins,gorcz/jenkins,DanielWeber/jenkins,CodeShane/jenkins,AustinKwang/jenkins,shahharsh/jenkins,paulwellnerbou/jenkins,ns163/jenkins,fbelzunc/jenkins,aduprat/jenkins,rsandell/jenkins,Krasnyanskiy/jenkins,aldaris/jenkins,NehemiahMi/jenkins,svanoort/jenkins,wuwen5/jenkins,albers/jenkins,singh88/jenkins,alvarolobato/jenkins,Krasnyanskiy/jenkins,seanlin816/jenkins,pjanouse/jenkins,albers/jenkins,rsandell/jenkins,amuniz/jenkins,wuwen5/jenkins,rlugojr/jenkins,godfath3r/jenkins,ndeloof/jenkins,kzantow/jenkins,varmenise/jenkins,jhoblitt/jenkins,evernat/jenkins,my7seven/jenkins,ydubreuil/jenkins,brunocvcunha/jenkins,SebastienGllmt/jenkins,singh88/jenkins,gusreiber/jenkins,khmarbaise/jenkins,tastatur/jenkins,mattclark/jenkins,amuniz/jenkins,daniel-beck/jenkins,escoem/jenkins,ajshastri/jenkins,paulwellnerbou/jenkins,jk47/jenkins,sathiya-mit/jenkins,chbiel/jenkins,albers/jenkins,oleg-nenashev/jenkins,MichaelPranovich/jenkins_sc,mrooney/jenkins,csimons/jenkins,NehemiahMi/jenkins,292388900/jenkins,aldaris/jenkins,daniel-beck/jenkins,Jimilian/jenkins,daniel-beck/jenkins,vlajos/jenkins,ajshastri/jenkins,lilyJi/jenkins,protazy/jenkins,jk47/jenkins,azweb76/jenkins,msrb/jenkins,MarkEWaite/jenkins,my7seven/jenkins,akshayabd/jenkins,albers/jenkins,patbos/jenkins,recena/jenkins,huybrechts/hudson,gitaccountforprashant/gittest,patbos/jenkins,liorhson/jenkins,intelchen/jenkins,aquarellian/jenkins,SebastienGllmt/jenkins,jglick/jenkins,292388900/jenkins,samatdav/jenkins,CodeShane/jenkins,christ66/jenkins,ikedam/jenkins,rashmikanta-1984/jenkins,lilyJi/jenkins,samatdav/jenkins,ChrisA89/jenkins,tfennelly/jenkins,huybrechts/hudson,jpederzolli/jenkins-1,akshayabd/jenkins,1and1/jenkins,mcanthony/jenkins,shahharsh/jenkins,jenkinsci/jenkins,hashar/jenkins,paulwellnerbou/jenkins,pselle/jenkins,rashmikanta-1984/jenkins,christ66/jenkins,svanoort/jenkins,Jimilian/jenkins,jcsirot/jenkins,rsandell/jenkins,vijayto/jenkins,ajshastri/jenkins,duzifang/my-jenkins,Jimilian/jenkins,gitaccountforprashant/gittest,maikeffi/hudson,vvv444/jenkins,olivergondza/jenkins,singh88/jenkins,pjanouse/jenkins,recena/jenkins,escoem/jenkins,FTG-003/jenkins,6WIND/jenkins,SebastienGllmt/jenkins,stephenc/jenkins,fbelzunc/jenkins,yonglehou/jenkins,arcivanov/jenkins,ErikVerheul/jenkins,guoxu0514/jenkins,hplatou/jenkins,292388900/jenkins,stephenc/jenkins,Vlatombe/jenkins,protazy/jenkins,jenkinsci/jenkins,samatdav/jenkins,noikiy/jenkins,DoctorQ/jenkins,SebastienGllmt/jenkins,viqueen/jenkins,soenter/jenkins,luoqii/jenkins,guoxu0514/jenkins,evernat/jenkins,chbiel/jenkins,vvv444/jenkins,yonglehou/jenkins,mrooney/jenkins,my7seven/jenkins,wuwen5/jenkins,ikedam/jenkins,ChrisA89/jenkins,keyurpatankar/hudson,godfath3r/jenkins,MichaelPranovich/jenkins_sc,kzantow/jenkins,kzantow/jenkins,FarmGeek4Life/jenkins,aquarellian/jenkins,duzifang/my-jenkins,pjanouse/jenkins,NehemiahMi/jenkins,lordofthejars/jenkins,AustinKwang/jenkins,scoheb/jenkins,vvv444/jenkins,jhoblitt/jenkins,aduprat/jenkins,ikedam/jenkins,escoem/jenkins,lordofthejars/jenkins,svanoort/jenkins,iqstack/jenkins,hemantojhaa/jenkins,jglick/jenkins,Jimilian/jenkins,my7seven/jenkins,Vlatombe/jenkins,svanoort/jenkins,seanlin816/jenkins,6WIND/jenkins,jcsirot/jenkins,MichaelPranovich/jenkins_sc,my7seven/jenkins,ErikVerheul/jenkins,iqstack/jenkins,jpederzolli/jenkins-1,christ66/jenkins,daniel-beck/jenkins,FTG-003/jenkins,aquarellian/jenkins,maikeffi/hudson,oleg-nenashev/jenkins,recena/jenkins,NehemiahMi/jenkins,soenter/jenkins,olivergondza/jenkins,guoxu0514/jenkins,jpederzolli/jenkins-1,jpbriend/jenkins,tastatur/jenkins,CodeShane/jenkins,tfennelly/jenkins,viqueen/jenkins,gusreiber/jenkins,lindzh/jenkins,escoem/jenkins,SenolOzer/jenkins,varmenise/jenkins,huybrechts/hudson,Jochen-A-Fuerbacher/jenkins,jglick/jenkins,ydubreuil/jenkins,godfath3r/jenkins,everyonce/jenkins,viqueen/jenkins,khmarbaise/jenkins,hemantojhaa/jenkins,rashmikanta-1984/jenkins,protazy/jenkins,MarkEWaite/jenkins,hemantojhaa/jenkins,vlajos/jenkins,singh88/jenkins,azweb76/jenkins,DoctorQ/jenkins,SenolOzer/jenkins,luoqii/jenkins,batmat/jenkins,wuwen5/jenkins,liorhson/jenkins,6WIND/jenkins,liupugong/jenkins,ChrisA89/jenkins,pselle/jenkins,hplatou/jenkins,ErikVerheul/jenkins,ns163/jenkins,dariver/jenkins,chbiel/jenkins,keyurpatankar/hudson,svanoort/jenkins,vvv444/jenkins,kohsuke/hudson,rlugojr/jenkins,arunsingh/jenkins,wangyikai/jenkins,paulmillar/jenkins,FarmGeek4Life/jenkins,mcanthony/jenkins,Krasnyanskiy/jenkins,mattclark/jenkins,shahharsh/jenkins,jenkinsci/jenkins,jenkinsci/jenkins,verbitan/jenkins,jglick/jenkins,SenolOzer/jenkins,bkmeneguello/jenkins,iqstack/jenkins,sathiya-mit/jenkins,dennisjlee/jenkins,dennisjlee/jenkins,scoheb/jenkins,chbiel/jenkins,FarmGeek4Life/jenkins,godfath3r/jenkins,mrooney/jenkins,lilyJi/jenkins,paulmillar/jenkins,tangkun75/jenkins,rashmikanta-1984/jenkins,csimons/jenkins,csimons/jenkins,kzantow/jenkins,wuwen5/jenkins,alvarolobato/jenkins,yonglehou/jenkins,ydubreuil/jenkins,lilyJi/jenkins,jenkinsci/jenkins,tastatur/jenkins,lilyJi/jenkins,hashar/jenkins,scoheb/jenkins,tfennelly/jenkins,mrooney/jenkins,aldaris/jenkins,aquarellian/jenkins,tfennelly/jenkins,DoctorQ/jenkins,Jochen-A-Fuerbacher/jenkins,duzifang/my-jenkins,hplatou/jenkins,protazy/jenkins,ChrisA89/jenkins,elkingtonmcb/jenkins,alvarolobato/jenkins,Jochen-A-Fuerbacher/jenkins,Vlatombe/jenkins,rsandell/jenkins,tastatur/jenkins,gitaccountforprashant/gittest,Vlatombe/jenkins,jpbriend/jenkins,alvarolobato/jenkins,evernat/jenkins,wangyikai/jenkins,paulwellnerbou/jenkins,NehemiahMi/jenkins,CodeShane/jenkins,akshayabd/jenkins,andresrc/jenkins,vjuranek/jenkins,soenter/jenkins,jk47/jenkins,arcivanov/jenkins,guoxu0514/jenkins,verbitan/jenkins,MarkEWaite/jenkins,amruthsoft9/Jenkis,dbroady1/jenkins,damianszczepanik/jenkins,mrooney/jenkins,wangyikai/jenkins,lindzh/jenkins,jhoblitt/jenkins,godfath3r/jenkins,paulwellnerbou/jenkins,mcanthony/jenkins,ikedam/jenkins,patbos/jenkins,jpbriend/jenkins,soenter/jenkins,liorhson/jenkins,recena/jenkins,my7seven/jenkins,aduprat/jenkins,Ykus/jenkins,FarmGeek4Life/jenkins,FTG-003/jenkins,rsandell/jenkins,Krasnyanskiy/jenkins,liupugong/jenkins,ErikVerheul/jenkins,keyurpatankar/hudson,dariver/jenkins,vvv444/jenkins,lindzh/jenkins,verbitan/jenkins,vvv444/jenkins,scoheb/jenkins,gorcz/jenkins,alvarolobato/jenkins,DoctorQ/jenkins,SenolOzer/jenkins,SenolOzer/jenkins,jglick/jenkins,FTG-003/jenkins,everyonce/jenkins,mattclark/jenkins,liupugong/jenkins,luoqii/jenkins,kohsuke/hudson,Ykus/jenkins,Ykus/jenkins,pselle/jenkins,KostyaSha/jenkins,KostyaSha/jenkins,ikedam/jenkins,duzifang/my-jenkins,jpederzolli/jenkins-1,Krasnyanskiy/jenkins,kohsuke/hudson,mdonohue/jenkins,CodeShane/jenkins,sathiya-mit/jenkins,rashmikanta-1984/jenkins,damianszczepanik/jenkins,vlajos/jenkins,sathiya-mit/jenkins,hplatou/jenkins,damianszczepanik/jenkins,FTG-003/jenkins,Ykus/jenkins,stephenc/jenkins,KostyaSha/jenkins,v1v/jenkins,jpbriend/jenkins,keyurpatankar/hudson,tastatur/jenkins,patbos/jenkins,mattclark/jenkins,azweb76/jenkins,wangyikai/jenkins,jglick/jenkins,elkingtonmcb/jenkins,elkingtonmcb/jenkins,keyurpatankar/hudson,akshayabd/jenkins,ydubreuil/jenkins,ErikVerheul/jenkins,batmat/jenkins,jhoblitt/jenkins,keyurpatankar/hudson,gitaccountforprashant/gittest,aduprat/jenkins,aquarellian/jenkins,1and1/jenkins,liupugong/jenkins,liupugong/jenkins,mdonohue/jenkins,paulwellnerbou/jenkins,petermarcoen/jenkins,dennisjlee/jenkins,Jimilian/jenkins,arunsingh/jenkins,FTG-003/jenkins,hemantojhaa/jenkins,paulmillar/jenkins,fbelzunc/jenkins,gitaccountforprashant/gittest,singh88/jenkins,liupugong/jenkins,amruthsoft9/Jenkis,1and1/jenkins,paulwellnerbou/jenkins,FarmGeek4Life/jenkins,khmarbaise/jenkins,MarkEWaite/jenkins,jpbriend/jenkins,liorhson/jenkins,ndeloof/jenkins,christ66/jenkins,hashar/jenkins,jpederzolli/jenkins-1,jhoblitt/jenkins,godfath3r/jenkins,MichaelPranovich/jenkins_sc,protazy/jenkins,gorcz/jenkins,tangkun75/jenkins,protazy/jenkins,lordofthejars/jenkins,6WIND/jenkins,SenolOzer/jenkins,mdonohue/jenkins,recena/jenkins,dbroady1/jenkins,sathiya-mit/jenkins,dbroady1/jenkins,Jochen-A-Fuerbacher/jenkins,my7seven/jenkins,iqstack/jenkins,rlugojr/jenkins,huybrechts/hudson,jenkinsci/jenkins,intelchen/jenkins,ndeloof/jenkins,vjuranek/jenkins,khmarbaise/jenkins,dbroady1/jenkins,gusreiber/jenkins,gorcz/jenkins,pjanouse/jenkins,gitaccountforprashant/gittest,DoctorQ/jenkins,azweb76/jenkins,escoem/jenkins,brunocvcunha/jenkins,viqueen/jenkins,v1v/jenkins,NehemiahMi/jenkins,kohsuke/hudson,csimons/jenkins,dariver/jenkins,ajshastri/jenkins,ndeloof/jenkins,vlajos/jenkins,hashar/jenkins,luoqii/jenkins,hemantojhaa/jenkins,akshayabd/jenkins,ns163/jenkins,noikiy/jenkins,varmenise/jenkins,seanlin816/jenkins,olivergondza/jenkins,mattclark/jenkins,v1v/jenkins,elkingtonmcb/jenkins,duzifang/my-jenkins,morficus/jenkins,daniel-beck/jenkins,msrb/jenkins,stephenc/jenkins,292388900/jenkins,SebastienGllmt/jenkins,amruthsoft9/Jenkis,alvarolobato/jenkins,Jimilian/jenkins,jk47/jenkins,amruthsoft9/Jenkis,batmat/jenkins,escoem/jenkins,yonglehou/jenkins,azweb76/jenkins,scoheb/jenkins,samatdav/jenkins,kzantow/jenkins,stephenc/jenkins,292388900/jenkins,gusreiber/jenkins,jcsirot/jenkins,samatdav/jenkins,amuniz/jenkins,ErikVerheul/jenkins,luoqii/jenkins,ChrisA89/jenkins,Jochen-A-Fuerbacher/jenkins,dbroady1/jenkins,kohsuke/hudson,aldaris/jenkins,olivergondza/jenkins,everyonce/jenkins,varmenise/jenkins,elkingtonmcb/jenkins,jhoblitt/jenkins,mdonohue/jenkins,sathiya-mit/jenkins,kzantow/jenkins,ydubreuil/jenkins,iqstack/jenkins,chbiel/jenkins,AustinKwang/jenkins,varmenise/jenkins,seanlin816/jenkins,daniel-beck/jenkins,MichaelPranovich/jenkins_sc,msrb/jenkins,csimons/jenkins,hashar/jenkins,pselle/jenkins,MarkEWaite/jenkins,ErikVerheul/jenkins,rashmikanta-1984/jenkins,brunocvcunha/jenkins,amuniz/jenkins,arcivanov/jenkins,dennisjlee/jenkins,dbroady1/jenkins,KostyaSha/jenkins,MarkEWaite/jenkins,vjuranek/jenkins,verbitan/jenkins,scoheb/jenkins,petermarcoen/jenkins,azweb76/jenkins,Vlatombe/jenkins,vjuranek/jenkins,vijayto/jenkins,tangkun75/jenkins,AustinKwang/jenkins,yonglehou/jenkins,recena/jenkins,gusreiber/jenkins,liorhson/jenkins,everyonce/jenkins,noikiy/jenkins,evernat/jenkins,brunocvcunha/jenkins,amuniz/jenkins,morficus/jenkins,gusreiber/jenkins,khmarbaise/jenkins,NehemiahMi/jenkins,mcanthony/jenkins,hashar/jenkins,stephenc/jenkins,sathiya-mit/jenkins,FTG-003/jenkins,AustinKwang/jenkins,oleg-nenashev/jenkins,ajshastri/jenkins,viqueen/jenkins,iqstack/jenkins,arunsingh/jenkins,samatdav/jenkins,patbos/jenkins,verbitan/jenkins,292388900/jenkins,bpzhang/jenkins,aduprat/jenkins,luoqii/jenkins,andresrc/jenkins,seanlin816/jenkins,jhoblitt/jenkins,oleg-nenashev/jenkins,intelchen/jenkins,DanielWeber/jenkins,pselle/jenkins,alvarolobato/jenkins,jk47/jenkins,hashar/jenkins,lilyJi/jenkins,ns163/jenkins,tastatur/jenkins,wangyikai/jenkins,FarmGeek4Life/jenkins,DanielWeber/jenkins,yonglehou/jenkins,292388900/jenkins,MarkEWaite/jenkins,dariver/jenkins,oleg-nenashev/jenkins,seanlin816/jenkins,DanielWeber/jenkins,ndeloof/jenkins,bkmeneguello/jenkins,wuwen5/jenkins,dennisjlee/jenkins,brunocvcunha/jenkins,everyonce/jenkins,lordofthejars/jenkins,gorcz/jenkins,andresrc/jenkins,rlugojr/jenkins,shahharsh/jenkins,duzifang/my-jenkins,guoxu0514/jenkins,tastatur/jenkins,fbelzunc/jenkins,singh88/jenkins,petermarcoen/jenkins,tfennelly/jenkins,gusreiber/jenkins,arcivanov/jenkins,kohsuke/hudson,pjanouse/jenkins,morficus/jenkins,1and1/jenkins,ikedam/jenkins,rashmikanta-1984/jenkins,oleg-nenashev/jenkins,maikeffi/hudson,petermarcoen/jenkins,DanielWeber/jenkins,hplatou/jenkins,shahharsh/jenkins,daniel-beck/jenkins,Ykus/jenkins,jk47/jenkins,chbiel/jenkins,lilyJi/jenkins,tfennelly/jenkins,brunocvcunha/jenkins,khmarbaise/jenkins,paulmillar/jenkins,CodeShane/jenkins,huybrechts/hudson,damianszczepanik/jenkins,jpbriend/jenkins,pselle/jenkins,rsandell/jenkins,viqueen/jenkins,batmat/jenkins,mrooney/jenkins,MichaelPranovich/jenkins_sc,batmat/jenkins,DanielWeber/jenkins,maikeffi/hudson,evernat/jenkins,vjuranek/jenkins,vlajos/jenkins,keyurpatankar/hudson,ajshastri/jenkins,tfennelly/jenkins,jpbriend/jenkins,jk47/jenkins,1and1/jenkins,akshayabd/jenkins,jcsirot/jenkins,hplatou/jenkins,jcsirot/jenkins,mdonohue/jenkins,AustinKwang/jenkins,jcsirot/jenkins,6WIND/jenkins,mrooney/jenkins,scoheb/jenkins,shahharsh/jenkins,arcivanov/jenkins,kzantow/jenkins,KostyaSha/jenkins,fbelzunc/jenkins,mcanthony/jenkins,huybrechts/hudson,seanlin816/jenkins,morficus/jenkins,godfath3r/jenkins,arunsingh/jenkins,varmenise/jenkins,pjanouse/jenkins,vijayto/jenkins,paulmillar/jenkins,vjuranek/jenkins,elkingtonmcb/jenkins,FarmGeek4Life/jenkins,aduprat/jenkins,aldaris/jenkins,vijayto/jenkins,mdonohue/jenkins,Vlatombe/jenkins,dennisjlee/jenkins,wangyikai/jenkins,Jochen-A-Fuerbacher/jenkins,vijayto/jenkins,jcsirot/jenkins,recena/jenkins,amruthsoft9/Jenkis,andresrc/jenkins,maikeffi/hudson,SebastienGllmt/jenkins,csimons/jenkins,maikeffi/hudson,dariver/jenkins,amruthsoft9/Jenkis,msrb/jenkins,lindzh/jenkins,lindzh/jenkins,everyonce/jenkins,gorcz/jenkins,bpzhang/jenkins,rlugojr/jenkins,paulmillar/jenkins,dennisjlee/jenkins,azweb76/jenkins,CodeShane/jenkins,tangkun75/jenkins,soenter/jenkins,petermarcoen/jenkins,shahharsh/jenkins,everyonce/jenkins,jenkinsci/jenkins,petermarcoen/jenkins,Krasnyanskiy/jenkins,tangkun75/jenkins,bkmeneguello/jenkins,vjuranek/jenkins,protazy/jenkins,albers/jenkins,lordofthejars/jenkins,ikedam/jenkins,arcivanov/jenkins,KostyaSha/jenkins,aldaris/jenkins,Jimilian/jenkins,DoctorQ/jenkins,hemantojhaa/jenkins,jpederzolli/jenkins-1,vijayto/jenkins,SenolOzer/jenkins,noikiy/jenkins,v1v/jenkins,lordofthejars/jenkins,paulmillar/jenkins,liorhson/jenkins,aquarellian/jenkins,verbitan/jenkins,vvv444/jenkins,arunsingh/jenkins,morficus/jenkins,mcanthony/jenkins,brunocvcunha/jenkins,patbos/jenkins,mcanthony/jenkins,damianszczepanik/jenkins,ydubreuil/jenkins,MichaelPranovich/jenkins_sc,msrb/jenkins,aldaris/jenkins,petermarcoen/jenkins,samatdav/jenkins,lindzh/jenkins,bpzhang/jenkins,ChrisA89/jenkins,singh88/jenkins,albers/jenkins,noikiy/jenkins,soenter/jenkins,kohsuke/hudson,christ66/jenkins,KostyaSha/jenkins,damianszczepanik/jenkins,rlugojr/jenkins,verbitan/jenkins,noikiy/jenkins,pselle/jenkins,akshayabd/jenkins,huybrechts/hudson,amruthsoft9/Jenkis,DanielWeber/jenkins,andresrc/jenkins,iqstack/jenkins,jglick/jenkins,vijayto/jenkins,arunsingh/jenkins,olivergondza/jenkins,olivergondza/jenkins,Ykus/jenkins,MarkEWaite/jenkins,andresrc/jenkins,fbelzunc/jenkins,shahharsh/jenkins,maikeffi/hudson,rsandell/jenkins,v1v/jenkins,Jochen-A-Fuerbacher/jenkins,DoctorQ/jenkins,jenkinsci/jenkins,wangyikai/jenkins,arcivanov/jenkins,ndeloof/jenkins,gorcz/jenkins,Vlatombe/jenkins,intelchen/jenkins,ikedam/jenkins,dbroady1/jenkins,daniel-beck/jenkins,6WIND/jenkins,stephenc/jenkins,svanoort/jenkins,kohsuke/hudson,christ66/jenkins,mattclark/jenkins,evernat/jenkins,aquarellian/jenkins,elkingtonmcb/jenkins,DoctorQ/jenkins,ns163/jenkins,v1v/jenkins,evernat/jenkins,bkmeneguello/jenkins,hplatou/jenkins,msrb/jenkins,liorhson/jenkins,aduprat/jenkins,batmat/jenkins,khmarbaise/jenkins,albers/jenkins,csimons/jenkins,yonglehou/jenkins,vlajos/jenkins,bpzhang/jenkins,luoqii/jenkins,ydubreuil/jenkins,lordofthejars/jenkins,damianszczepanik/jenkins,KostyaSha/jenkins,mattclark/jenkins,hemantojhaa/jenkins,gorcz/jenkins,Ykus/jenkins,guoxu0514/jenkins,escoem/jenkins,ns163/jenkins,noikiy/jenkins,bpzhang/jenkins,ndeloof/jenkins,intelchen/jenkins,rsandell/jenkins,ajshastri/jenkins | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Red Hat, Inc., Stephen Connolly, Tom Huybrechts
*
* 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 hudson.model;
import hudson.FilePath;
import hudson.Util;
import hudson.model.Queue.Executable;
import hudson.model.queue.Executables;
import hudson.model.queue.SubTask;
import hudson.model.queue.Tasks;
import hudson.model.queue.WorkUnit;
import hudson.security.ACL;
import hudson.util.InterceptingProxy;
import hudson.util.TimeUnit2;
import jenkins.model.CauseOfInterruption;
import jenkins.model.CauseOfInterruption.UserInterruption;
import jenkins.model.InterruptedBuildAction;
import jenkins.model.Jenkins;
import org.acegisecurity.Authentication;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.annotation.concurrent.GuardedBy;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import static hudson.model.queue.Executables.*;
import static java.util.logging.Level.*;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
/**
* Thread that executes builds.
* Since 1.536, {@link Executor}s start threads on-demand.
* The entire logic should use {@link #isActive()} instead of {@link #isAlive()}
* in order to check if the {@link Executor} it ready to take tasks.
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Executor extends Thread implements ModelObject {
protected final @Nonnull Computer owner;
private final Queue queue;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
@GuardedBy("lock")
private long startTime;
/**
* Used to track when a job was last executed.
*/
private final long creationTime = System.currentTimeMillis();
/**
* Executor number that identifies it among other executors for the same {@link Computer}.
*/
private int number;
/**
* {@link hudson.model.Queue.Executable} being executed right now, or null if the executor is idle.
*/
@GuardedBy("lock")
private Queue.Executable executable;
/**
* When {@link Queue} allocates a work for this executor, this field is set
* and the executor is {@linkplain Thread#start() started}.
*/
@GuardedBy("lock")
private WorkUnit workUnit;
private Throwable causeOfDeath;
private boolean induceDeath;
@GuardedBy("lock")
private boolean started;
/**
* When the executor is interrupted, we allow the code that interrupted the thread to override the
* result code it prefers.
*/
@GuardedBy("lock")
private Result interruptStatus;
/**
* Cause of interruption. Access needs to be synchronized.
*/
@GuardedBy("lock")
private final List<CauseOfInterruption> causes = new Vector<CauseOfInterruption>();
public Executor(@Nonnull Computer owner, int n) {
super("Executor #"+n+" for "+owner.getDisplayName());
this.owner = owner;
this.queue = Jenkins.getInstance().getQueue();
this.number = n;
}
@Override
public void interrupt() {
interrupt(Result.ABORTED);
}
/**
* Interrupt the execution,
* but instead of marking the build as aborted, mark it as specified result.
*
* @since 1.417
*/
public void interrupt(Result result) {
Authentication a = Jenkins.getAuthentication();
if (a == ACL.SYSTEM)
interrupt(result, new CauseOfInterruption[0]);
else {
// worth recording who did it
// avoid using User.get() to avoid deadlock.
interrupt(result, new UserInterruption(a.getName()));
}
}
/**
* Interrupt the execution. Mark the cause and the status accordingly.
*/
public void interrupt(Result result, CauseOfInterruption... causes) {
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, String.format("%s is interrupted(%s): %s", getDisplayName(), result, Util.join(Arrays.asList(causes),",")), new InterruptedException());
lock.writeLock().lock();
try {
if (!started) {
// not yet started, so simply dispose this
owner.removeExecutor(this);
return;
}
interruptStatus = result;
for (CauseOfInterruption c : causes) {
if (!this.causes.contains(c))
this.causes.add(c);
}
} finally {
lock.writeLock().unlock();
}
super.interrupt();
}
public Result abortResult() {
lock.readLock().lock();
try {
Result r = interruptStatus;
if (r == null) r =
Result.ABORTED; // this is when we programmatically throw InterruptedException instead of calling the interrupt method.
return r;
} finally {
lock.readLock().unlock();
}
}
/**
* report cause of interruption and record it to the build, if available.
*
* @since 1.425
*/
public void recordCauseOfInterruption(Run<?,?> build, TaskListener listener) {
List<CauseOfInterruption> r;
// atomically get&clear causes.
lock.writeLock().lock();
try {
if (causes.isEmpty()) return;
r = new ArrayList<CauseOfInterruption>(causes);
causes.clear();
} finally {
lock.writeLock().unlock();
}
build.addAction(new InterruptedBuildAction(r));
for (CauseOfInterruption c : r)
c.print(listener);
}
/**
* There are some cases where an executor is started but the node is removed or goes off-line before we are ready
* to start executing the assigned work unit. This method is called to clear the assigned work unit so that
* the {@link Queue#maintain()} method can return the item to the buildable state.
*
* Note: once we create the {@link Executable} we cannot unwind the state and the build will have to end up being
* marked as a failure.
*/
private void resetWorkUnit(String reason) {
StringWriter writer = new StringWriter();
PrintWriter pw = new PrintWriter(writer);
try {
pw.printf("%s grabbed %s from queue but %s %s. ", getName(), workUnit, owner.getDisplayName(), reason);
if (owner.getTerminatedBy().isEmpty()) {
pw.print("No termination trace available.");
} else {
pw.println("Termination trace follows:");
for (Computer.TerminationRequest request: owner.getTerminatedBy()) {
request.printStackTrace(pw);
}
}
} finally {
pw.close();
}
LOGGER.log(WARNING, writer.toString());
lock.writeLock().lock();
try {
if (executable != null) {
throw new IllegalStateException("Cannot reset the work unit after the executable has been created");
}
workUnit = null;
} finally {
lock.writeLock().unlock();
}
}
@Override
public void run() {
if (!owner.isOnline()) {
resetWorkUnit("went off-line before the task's worker thread started");
owner.removeExecutor(this);
queue.scheduleMaintenance();
return;
}
if (owner.getNode() == null) {
resetWorkUnit("was removed before the task's worker thread started");
owner.removeExecutor(this);
queue.scheduleMaintenance();
return;
}
final WorkUnit workUnit;
lock.writeLock().lock();
try {
startTime = System.currentTimeMillis();
workUnit = this.workUnit;
} finally {
lock.writeLock().unlock();
}
ACL.impersonate(ACL.SYSTEM);
try {
if (induceDeath) throw new ThreadDeath();
SubTask task;
// transition from idle to building.
// perform this state change as an atomic operation wrt other queue operations
task = Queue.withLock(new java.util.concurrent.Callable<SubTask>() {
@Override
public SubTask call() throws Exception {
if (!owner.isOnline()) {
resetWorkUnit("went off-line before the task's worker thread was ready to execute");
return null;
}
if (owner.getNode() == null) {
resetWorkUnit("was removed before the task's worker thread was ready to execute");
return null;
}
// after this point we cannot unwind the assignment of the work unit, if the owner
// is removed or goes off-line then the build will just have to fail.
workUnit.setExecutor(Executor.this);
queue.onStartExecuting(Executor.this);
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" grabbed "+workUnit+" from queue");
SubTask task = workUnit.work;
Executable executable = task.createExecutable();
lock.writeLock().lock();
try {
Executor.this.executable = executable;
} finally {
lock.writeLock().unlock();
}
workUnit.setExecutable(executable);
return task;
}
});
Executable executable;
lock.readLock().lock();
try {
if (this.workUnit == null) {
// we called resetWorkUnit, so bail. Outer finally will remove this and schedule queue maintenance
return;
}
executable = this.executable;
} finally {
lock.readLock().unlock();
}
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" is going to execute "+executable);
Throwable problems = null;
try {
workUnit.context.synchronizeStart();
// this code handles the behavior of null Executables returned
// by tasks. In such case Jenkins starts the workUnit in order
// to report results to console outputs.
if (executable == null) {
throw new Error("The null Executable has been created for "+workUnit+". The task cannot be executed");
}
if (executable instanceof Actionable) {
for (Action action: workUnit.context.actions) {
((Actionable) executable).addAction(action);
}
}
ACL.impersonate(workUnit.context.item.authenticate());
setName(getName() + " : executing " + executable.toString());
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" is now executing "+executable);
queue.execute(executable, task);
} catch (Throwable e) {
// for some reason the executor died. this is really
// a bug in the code, but we don't want the executor to die,
// so just leave some info and go on to build other things
LOGGER.log(Level.SEVERE, "Executor threw an exception", e);
workUnit.context.abort(e);
problems = e;
} finally {
long time = System.currentTimeMillis()-startTime;
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" completed "+executable+" in "+time+"ms");
try {
workUnit.context.synchronizeEnd(executable,problems,time);
} catch (InterruptedException e) {
workUnit.context.abort(e);
} finally {
workUnit.setExecutor(null);
}
}
} catch (InterruptedException e) {
LOGGER.log(FINE, getName()+" interrupted",e);
// die peacefully
} catch(Exception e) {
causeOfDeath = e;
LOGGER.log(SEVERE, "Unexpected executor death", e);
} catch (Error e) {
causeOfDeath = e;
LOGGER.log(SEVERE, "Unexpected executor death", e);
} finally {
for (RuntimeException e1: owner.getTerminatedBy()) LOGGER.log(Level.WARNING, String.format("%s termination trace", getName()), e1);
if (causeOfDeath==null)
// let this thread die and be replaced by a fresh unstarted instance
owner.removeExecutor(this);
queue.scheduleMaintenance();
}
}
/**
* For testing only. Simulate a fatal unexpected failure.
*/
public void killHard() {
induceDeath = true;
}
/**
* Returns the current build this executor is running.
*
* @return
* null if the executor is idle.
*/
@Exported
public @CheckForNull Queue.Executable getCurrentExecutable() {
lock.readLock().lock();
try {
return executable;
} finally {
lock.readLock().unlock();
}
}
/**
* Returns the current {@link WorkUnit} (of {@link #getCurrentExecutable() the current executable})
* that this executor is running.
*
* @return
* null if the executor is idle.
*/
@Exported
public WorkUnit getCurrentWorkUnit() {
lock.readLock().lock();
try {
return workUnit;
} finally {
lock.readLock().unlock();
}
}
/**
* If {@linkplain #getCurrentExecutable() current executable} is {@link AbstractBuild},
* return the workspace that this executor is using, or null if the build hasn't gotten
* to that point yet.
*/
public FilePath getCurrentWorkspace() {
lock.readLock().lock();
try {
if (executable == null) {
return null;
}
if (executable instanceof AbstractBuild) {
AbstractBuild ab = (AbstractBuild) executable;
return ab.getWorkspace();
}
return null;
} finally {
lock.readLock().unlock();
}
}
/**
* Same as {@link #getName()}.
*/
public String getDisplayName() {
return "Executor #"+getNumber();
}
/**
* Gets the executor number that uniquely identifies it among
* other {@link Executor}s for the same computer.
*
* @return
* a sequential number starting from 0.
*/
@Exported
public int getNumber() {
return number;
}
/**
* Returns true if this {@link Executor} is ready for action.
*/
@Exported
public boolean isIdle() {
lock.readLock().lock();
try {
return workUnit == null && executable == null;
} finally {
lock.readLock().unlock();
}
}
/**
* The opposite of {@link #isIdle()} — the executor is doing some work.
*/
public boolean isBusy() {
lock.readLock().lock();
try {
return workUnit != null || executable != null;
} finally {
lock.readLock().unlock();
}
}
/**
* Check if executor is ready to accept tasks.
* This method becomes the critical one since 1.536, which introduces the
* on-demand creation of executor threads. The entire logic should use
* this method instead of {@link #isAlive()}, because it provides wrong
* information for non-started threads.
* @return True if the executor is available for tasks
* @since 1.536
*/
public boolean isActive() {
lock.readLock().lock();
try {
return !started || isAlive();
} finally {
lock.readLock().unlock();
}
}
/**
* Returns true if this executor is waiting for a task to execute.
*/
public boolean isParking() {
lock.readLock().lock();
try {
return !started;
} finally {
lock.readLock().unlock();
}
}
/**
* If this thread dies unexpectedly, obtain the cause of the failure.
*
* @return null if the death is expected death or the thread is {@link #isAlive() still alive}.
* @since 1.142
*/
public Throwable getCauseOfDeath() {
return causeOfDeath;
}
/**
* Returns the progress of the current build in the number between 0-100.
*
* @return -1
* if it's impossible to estimate the progress.
*/
@Exported
public int getProgress() {
long d;
lock.readLock().lock();
try {
if (executable == null) {
return -1;
}
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d < 0) {
return -1;
}
int num = (int) (getElapsedTime() * 100 / d);
if (num >= 100) {
num = 99;
}
return num;
}
/**
* Returns true if the current build is likely stuck.
*
* <p>
* This is a heuristics based approach, but if the build is suspiciously taking for a long time,
* this method returns true.
*/
@Exported
public boolean isLikelyStuck() {
long d;
long elapsed;
lock.readLock().lock();
try {
if (executable == null) {
return false;
}
elapsed = getElapsedTime();
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d >= 0) {
// if it's taking 10 times longer than ETA, consider it stuck
return d * 10 < elapsed;
} else {
// if no ETA is available, a build taking longer than a day is considered stuck
return TimeUnit2.MILLISECONDS.toHours(elapsed) > 24;
}
}
public long getElapsedTime() {
lock.readLock().lock();
try {
return System.currentTimeMillis() - startTime;
} finally {
lock.readLock().unlock();
}
}
/**
* Returns the number of milli-seconds the currently executing job spent in the queue
* waiting for an available executor. This excludes the quiet period time of the job.
* @since 1.440
*/
public long getTimeSpentInQueue() {
lock.readLock().lock();
try {
return startTime - workUnit.context.item.buildableStartMilliseconds;
} finally {
lock.readLock().unlock();
}
}
/**
* Gets the string that says how long since this build has started.
*
* @return
* string like "3 minutes" "1 day" etc.
*/
public String getTimestampString() {
return Util.getPastTimeString(getElapsedTime());
}
/**
* Computes a human-readable text that shows the expected remaining time
* until the build completes.
*/
public String getEstimatedRemainingTime() {
long d;
lock.readLock().lock();
try {
if (executable == null) {
return Messages.Executor_NotAvailable();
}
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d < 0) {
return Messages.Executor_NotAvailable();
}
long eta = d - getElapsedTime();
if (eta <= 0) {
return Messages.Executor_NotAvailable();
}
return Util.getTimeSpanString(eta);
}
/**
* The same as {@link #getEstimatedRemainingTime()} but return
* it as a number of milli-seconds.
*/
public long getEstimatedRemainingTimeMillis() {
long d;
lock.readLock().lock();
try {
if (executable == null) {
return -1;
}
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d < 0) {
return -1;
}
long eta = d - getElapsedTime();
if (eta <= 0) {
return -1;
}
return eta;
}
/**
* Can't start executor like you normally start a thread.
*
* @see #start(WorkUnit)
*/
@Override
public void start() {
throw new UnsupportedOperationException();
}
/*protected*/ void start(WorkUnit task) {
lock.writeLock().lock();
try {
this.workUnit = task;
super.start();
started = true;
} finally {
lock.writeLock().unlock();
}
}
/**
* @deprecated as of 1.489
* Use {@link #doStop()}.
*/
@RequirePOST
public void doStop( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
doStop().generateResponse(req,rsp,this);
}
/**
* Stops the current build.
*
* @since 1.489
*/
@RequirePOST
public HttpResponse doStop() {
lock.writeLock().lock(); // need write lock as interrupt will change the field
try {
if (executable != null) {
Tasks.getOwnerTaskOf(getParentOf(executable)).checkAbortPermission();
interrupt();
}
} finally {
lock.writeLock().unlock();
}
return HttpResponses.forwardToPreviousPage();
}
/**
* Throws away this executor and get a new one.
*/
@RequirePOST
public HttpResponse doYank() {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
if (isAlive())
throw new Failure("Can't yank a live executor");
owner.removeExecutor(this);
return HttpResponses.redirectViaContextPath("/");
}
/**
* Checks if the current user has a permission to stop this build.
*/
public boolean hasStopPermission() {
lock.readLock().lock();
try {
return executable != null && Tasks.getOwnerTaskOf(getParentOf(executable)).hasAbortPermission();
} finally {
lock.readLock().unlock();
}
}
public @Nonnull Computer getOwner() {
return owner;
}
/**
* Returns when this executor started or should start being idle.
*/
public long getIdleStartMilliseconds() {
lock.readLock().lock();
try {
if (isIdle())
return Math.max(creationTime, owner.getConnectTime());
else {
return Math.max(startTime + Math.max(0, Executables.getEstimatedDurationFor(executable)),
System.currentTimeMillis() + 15000);
}
} finally {
lock.readLock().unlock();
}
}
/**
* Exposes the executor to the remote API.
*/
public Api getApi() {
return new Api(this);
}
/**
* Creates a proxy object that executes the callee in the context that impersonates
* this executor. Useful to export an object to a remote channel.
*/
public <T> T newImpersonatingProxy(Class<T> type, T core) {
return new InterceptingProxy() {
protected Object call(Object o, Method m, Object[] args) throws Throwable {
final Executor old = IMPERSONATION.get();
IMPERSONATION.set(Executor.this);
try {
return m.invoke(o,args);
} finally {
IMPERSONATION.set(old);
}
}
}.wrap(type,core);
}
/**
* Returns the executor of the current thread or null if current thread is not an executor.
*/
public static @CheckForNull Executor currentExecutor() {
Thread t = Thread.currentThread();
if (t instanceof Executor) return (Executor) t;
return IMPERSONATION.get();
}
/**
* Returns the estimated duration for the executable.
* Protects against {@link AbstractMethodError}s if the {@link Executable} implementation
* was compiled against Hudson < 1.383
*
* @deprecated as of 1.388
* Use {@link Executables#getEstimatedDurationFor(Queue.Executable)}
*/
public static long getEstimatedDurationFor(Executable e) {
return Executables.getEstimatedDurationFor(e);
}
/**
* Mechanism to allow threads (in particular the channel request handling threads) to
* run on behalf of {@link Executor}.
*/
private static final ThreadLocal<Executor> IMPERSONATION = new ThreadLocal<Executor>();
private static final Logger LOGGER = Logger.getLogger(Executor.class.getName());
}
| core/src/main/java/hudson/model/Executor.java | /*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Brian Westrich, Red Hat, Inc., Stephen Connolly, Tom Huybrechts
*
* 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 hudson.model;
import hudson.FilePath;
import hudson.Util;
import hudson.model.Queue.Executable;
import hudson.model.queue.Executables;
import hudson.model.queue.SubTask;
import hudson.model.queue.Tasks;
import hudson.model.queue.WorkUnit;
import hudson.security.ACL;
import hudson.util.InterceptingProxy;
import hudson.util.TimeUnit2;
import jenkins.model.CauseOfInterruption;
import jenkins.model.CauseOfInterruption.UserInterruption;
import jenkins.model.InterruptedBuildAction;
import jenkins.model.Jenkins;
import org.acegisecurity.Authentication;
import org.kohsuke.stapler.HttpResponse;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;
import javax.annotation.concurrent.GuardedBy;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import static hudson.model.queue.Executables.*;
import static java.util.logging.Level.*;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
/**
* Thread that executes builds.
* Since 1.536, {@link Executor}s start threads on-demand.
* The entire logic should use {@link #isActive()} instead of {@link #isAlive()}
* in order to check if the {@link Executor} it ready to take tasks.
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Executor extends Thread implements ModelObject {
protected final @Nonnull Computer owner;
private final Queue queue;
private final ReadWriteLock lock = new ReentrantReadWriteLock();
@GuardedBy("#lock")
private long startTime;
/**
* Used to track when a job was last executed.
*/
private final long creationTime = System.currentTimeMillis();
/**
* Executor number that identifies it among other executors for the same {@link Computer}.
*/
private int number;
/**
* {@link hudson.model.Queue.Executable} being executed right now, or null if the executor is idle.
*/
@GuardedBy("#lock")
private Queue.Executable executable;
/**
* When {@link Queue} allocates a work for this executor, this field is set
* and the executor is {@linkplain Thread#start() started}.
*/
@GuardedBy("#lock")
private WorkUnit workUnit;
private Throwable causeOfDeath;
private boolean induceDeath;
@GuardedBy("#lock")
private boolean started;
/**
* When the executor is interrupted, we allow the code that interrupted the thread to override the
* result code it prefers.
*/
@GuardedBy("#lock")
private Result interruptStatus;
/**
* Cause of interruption. Access needs to be synchronized.
*/
@GuardedBy("#lock")
private final List<CauseOfInterruption> causes = new Vector<CauseOfInterruption>();
public Executor(@Nonnull Computer owner, int n) {
super("Executor #"+n+" for "+owner.getDisplayName());
this.owner = owner;
this.queue = Jenkins.getInstance().getQueue();
this.number = n;
}
@Override
public void interrupt() {
interrupt(Result.ABORTED);
}
/**
* Interrupt the execution,
* but instead of marking the build as aborted, mark it as specified result.
*
* @since 1.417
*/
public void interrupt(Result result) {
Authentication a = Jenkins.getAuthentication();
if (a == ACL.SYSTEM)
interrupt(result, new CauseOfInterruption[0]);
else {
// worth recording who did it
// avoid using User.get() to avoid deadlock.
interrupt(result, new UserInterruption(a.getName()));
}
}
/**
* Interrupt the execution. Mark the cause and the status accordingly.
*/
public void interrupt(Result result, CauseOfInterruption... causes) {
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, String.format("%s is interrupted(%s): %s", getDisplayName(), result, Util.join(Arrays.asList(causes),",")), new InterruptedException());
lock.writeLock().lock();
try {
if (!started) {
// not yet started, so simply dispose this
owner.removeExecutor(this);
return;
}
interruptStatus = result;
for (CauseOfInterruption c : causes) {
if (!this.causes.contains(c))
this.causes.add(c);
}
} finally {
lock.writeLock().unlock();
}
super.interrupt();
}
public Result abortResult() {
lock.readLock().lock();
try {
Result r = interruptStatus;
if (r == null) r =
Result.ABORTED; // this is when we programmatically throw InterruptedException instead of calling the interrupt method.
return r;
} finally {
lock.readLock().unlock();
}
}
/**
* report cause of interruption and record it to the build, if available.
*
* @since 1.425
*/
public void recordCauseOfInterruption(Run<?,?> build, TaskListener listener) {
List<CauseOfInterruption> r;
// atomically get&clear causes.
lock.writeLock().lock();
try {
if (causes.isEmpty()) return;
r = new ArrayList<CauseOfInterruption>(causes);
causes.clear();
} finally {
lock.writeLock().unlock();
}
build.addAction(new InterruptedBuildAction(r));
for (CauseOfInterruption c : r)
c.print(listener);
}
/**
* There are some cases where an executor is started but the node is removed or goes off-line before we are ready
* to start executing the assigned work unit. This method is called to clear the assigned work unit so that
* the {@link Queue#maintain()} method can return the item to the buildable state.
*
* Note: once we create the {@link Executable} we cannot unwind the state and the build will have to end up being
* marked as a failure.
*/
private void resetWorkUnit(String reason) {
StringWriter writer = new StringWriter();
PrintWriter pw = new PrintWriter(writer);
try {
pw.printf("%s grabbed %s from queue but %s %s. ", getName(), workUnit, owner.getDisplayName(), reason);
if (owner.getTerminatedBy().isEmpty()) {
pw.print("No termination trace available.");
} else {
pw.println("Termination trace follows:");
for (Computer.TerminationRequest request: owner.getTerminatedBy()) {
request.printStackTrace(pw);
}
}
} finally {
pw.close();
}
LOGGER.log(WARNING, writer.toString());
lock.writeLock().lock();
try {
if (executable != null) {
throw new IllegalStateException("Cannot reset the work unit after the executable has been created");
}
workUnit = null;
} finally {
lock.writeLock().unlock();
}
}
@Override
public void run() {
if (!owner.isOnline()) {
resetWorkUnit("went off-line before the task's worker thread started");
owner.removeExecutor(this);
queue.scheduleMaintenance();
return;
}
if (owner.getNode() == null) {
resetWorkUnit("was removed before the task's worker thread started");
owner.removeExecutor(this);
queue.scheduleMaintenance();
return;
}
final WorkUnit workUnit;
lock.writeLock().lock();
try {
startTime = System.currentTimeMillis();
workUnit = this.workUnit;
} finally {
lock.writeLock().unlock();
}
ACL.impersonate(ACL.SYSTEM);
try {
if (induceDeath) throw new ThreadDeath();
SubTask task;
// transition from idle to building.
// perform this state change as an atomic operation wrt other queue operations
task = Queue.withLock(new java.util.concurrent.Callable<SubTask>() {
@Override
public SubTask call() throws Exception {
if (!owner.isOnline()) {
resetWorkUnit("went off-line before the task's worker thread was ready to execute");
return null;
}
if (owner.getNode() == null) {
resetWorkUnit("was removed before the task's worker thread was ready to execute");
return null;
}
// after this point we cannot unwind the assignment of the work unit, if the owner
// is removed or goes off-line then the build will just have to fail.
workUnit.setExecutor(Executor.this);
queue.onStartExecuting(Executor.this);
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" grabbed "+workUnit+" from queue");
SubTask task = workUnit.work;
Executable executable = task.createExecutable();
lock.writeLock().lock();
try {
Executor.this.executable = executable;
} finally {
lock.writeLock().unlock();
}
workUnit.setExecutable(executable);
return task;
}
});
Executable executable;
lock.readLock().lock();
try {
if (this.workUnit == null) {
// we called resetWorkUnit, so bail. Outer finally will remove this and schedule queue maintenance
return;
}
executable = this.executable;
} finally {
lock.readLock().unlock();
}
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" is going to execute "+executable);
Throwable problems = null;
try {
workUnit.context.synchronizeStart();
// this code handles the behavior of null Executables returned
// by tasks. In such case Jenkins starts the workUnit in order
// to report results to console outputs.
if (executable == null) {
throw new Error("The null Executable has been created for "+workUnit+". The task cannot be executed");
}
if (executable instanceof Actionable) {
for (Action action: workUnit.context.actions) {
((Actionable) executable).addAction(action);
}
}
ACL.impersonate(workUnit.context.item.authenticate());
setName(getName() + " : executing " + executable.toString());
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" is now executing "+executable);
queue.execute(executable, task);
} catch (Throwable e) {
// for some reason the executor died. this is really
// a bug in the code, but we don't want the executor to die,
// so just leave some info and go on to build other things
LOGGER.log(Level.SEVERE, "Executor threw an exception", e);
workUnit.context.abort(e);
problems = e;
} finally {
long time = System.currentTimeMillis()-startTime;
if (LOGGER.isLoggable(FINE))
LOGGER.log(FINE, getName()+" completed "+executable+" in "+time+"ms");
try {
workUnit.context.synchronizeEnd(executable,problems,time);
} catch (InterruptedException e) {
workUnit.context.abort(e);
} finally {
workUnit.setExecutor(null);
}
}
} catch (InterruptedException e) {
LOGGER.log(FINE, getName()+" interrupted",e);
// die peacefully
} catch(Exception e) {
causeOfDeath = e;
LOGGER.log(SEVERE, "Unexpected executor death", e);
} catch (Error e) {
causeOfDeath = e;
LOGGER.log(SEVERE, "Unexpected executor death", e);
} finally {
for (RuntimeException e1: owner.getTerminatedBy()) LOGGER.log(Level.WARNING, String.format("%s termination trace", getName()), e1);
if (causeOfDeath==null)
// let this thread die and be replaced by a fresh unstarted instance
owner.removeExecutor(this);
queue.scheduleMaintenance();
}
}
/**
* For testing only. Simulate a fatal unexpected failure.
*/
public void killHard() {
induceDeath = true;
}
/**
* Returns the current build this executor is running.
*
* @return
* null if the executor is idle.
*/
@Exported
public @CheckForNull Queue.Executable getCurrentExecutable() {
lock.readLock().lock();
try {
return executable;
} finally {
lock.readLock().unlock();
}
}
/**
* Returns the current {@link WorkUnit} (of {@link #getCurrentExecutable() the current executable})
* that this executor is running.
*
* @return
* null if the executor is idle.
*/
@Exported
public WorkUnit getCurrentWorkUnit() {
lock.readLock().lock();
try {
return workUnit;
} finally {
lock.readLock().unlock();
}
}
/**
* If {@linkplain #getCurrentExecutable() current executable} is {@link AbstractBuild},
* return the workspace that this executor is using, or null if the build hasn't gotten
* to that point yet.
*/
public FilePath getCurrentWorkspace() {
lock.readLock().lock();
try {
if (executable == null) {
return null;
}
if (executable instanceof AbstractBuild) {
AbstractBuild ab = (AbstractBuild) executable;
return ab.getWorkspace();
}
return null;
} finally {
lock.readLock().unlock();
}
}
/**
* Same as {@link #getName()}.
*/
public String getDisplayName() {
return "Executor #"+getNumber();
}
/**
* Gets the executor number that uniquely identifies it among
* other {@link Executor}s for the same computer.
*
* @return
* a sequential number starting from 0.
*/
@Exported
public int getNumber() {
return number;
}
/**
* Returns true if this {@link Executor} is ready for action.
*/
@Exported
public boolean isIdle() {
lock.readLock().lock();
try {
return workUnit == null && executable == null;
} finally {
lock.readLock().unlock();
}
}
/**
* The opposite of {@link #isIdle()} — the executor is doing some work.
*/
public boolean isBusy() {
lock.readLock().lock();
try {
return workUnit != null || executable != null;
} finally {
lock.readLock().unlock();
}
}
/**
* Check if executor is ready to accept tasks.
* This method becomes the critical one since 1.536, which introduces the
* on-demand creation of executor threads. The entire logic should use
* this method instead of {@link #isAlive()}, because it provides wrong
* information for non-started threads.
* @return True if the executor is available for tasks
* @since 1.536
*/
public boolean isActive() {
lock.readLock().lock();
try {
return !started || isAlive();
} finally {
lock.readLock().unlock();
}
}
/**
* Returns true if this executor is waiting for a task to execute.
*/
public boolean isParking() {
lock.readLock().lock();
try {
return !started;
} finally {
lock.readLock().unlock();
}
}
/**
* If this thread dies unexpectedly, obtain the cause of the failure.
*
* @return null if the death is expected death or the thread is {@link #isAlive() still alive}.
* @since 1.142
*/
public Throwable getCauseOfDeath() {
return causeOfDeath;
}
/**
* Returns the progress of the current build in the number between 0-100.
*
* @return -1
* if it's impossible to estimate the progress.
*/
@Exported
public int getProgress() {
long d;
lock.readLock().lock();
try {
if (executable == null) {
return -1;
}
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d < 0) {
return -1;
}
int num = (int) (getElapsedTime() * 100 / d);
if (num >= 100) {
num = 99;
}
return num;
}
/**
* Returns true if the current build is likely stuck.
*
* <p>
* This is a heuristics based approach, but if the build is suspiciously taking for a long time,
* this method returns true.
*/
@Exported
public boolean isLikelyStuck() {
long d;
long elapsed;
lock.readLock().lock();
try {
if (executable == null) {
return false;
}
elapsed = getElapsedTime();
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d >= 0) {
// if it's taking 10 times longer than ETA, consider it stuck
return d * 10 < elapsed;
} else {
// if no ETA is available, a build taking longer than a day is considered stuck
return TimeUnit2.MILLISECONDS.toHours(elapsed) > 24;
}
}
public long getElapsedTime() {
lock.readLock().lock();
try {
return System.currentTimeMillis() - startTime;
} finally {
lock.readLock().unlock();
}
}
/**
* Returns the number of milli-seconds the currently executing job spent in the queue
* waiting for an available executor. This excludes the quiet period time of the job.
* @since 1.440
*/
public long getTimeSpentInQueue() {
lock.readLock().lock();
try {
return startTime - workUnit.context.item.buildableStartMilliseconds;
} finally {
lock.readLock().unlock();
}
}
/**
* Gets the string that says how long since this build has started.
*
* @return
* string like "3 minutes" "1 day" etc.
*/
public String getTimestampString() {
return Util.getPastTimeString(getElapsedTime());
}
/**
* Computes a human-readable text that shows the expected remaining time
* until the build completes.
*/
public String getEstimatedRemainingTime() {
long d;
lock.readLock().lock();
try {
if (executable == null) {
return Messages.Executor_NotAvailable();
}
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d < 0) {
return Messages.Executor_NotAvailable();
}
long eta = d - getElapsedTime();
if (eta <= 0) {
return Messages.Executor_NotAvailable();
}
return Util.getTimeSpanString(eta);
}
/**
* The same as {@link #getEstimatedRemainingTime()} but return
* it as a number of milli-seconds.
*/
public long getEstimatedRemainingTimeMillis() {
long d;
lock.readLock().lock();
try {
if (executable == null) {
return -1;
}
d = Executables.getEstimatedDurationFor(executable);
} finally {
lock.readLock().unlock();
}
if (d < 0) {
return -1;
}
long eta = d - getElapsedTime();
if (eta <= 0) {
return -1;
}
return eta;
}
/**
* Can't start executor like you normally start a thread.
*
* @see #start(WorkUnit)
*/
@Override
public void start() {
throw new UnsupportedOperationException();
}
/*protected*/ void start(WorkUnit task) {
lock.writeLock().lock();
try {
this.workUnit = task;
super.start();
started = true;
} finally {
lock.writeLock().unlock();
}
}
/**
* @deprecated as of 1.489
* Use {@link #doStop()}.
*/
@RequirePOST
public void doStop( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
doStop().generateResponse(req,rsp,this);
}
/**
* Stops the current build.
*
* @since 1.489
*/
@RequirePOST
public HttpResponse doStop() {
lock.writeLock().lock(); // need write lock as interrupt will change the field
try {
if (executable != null) {
Tasks.getOwnerTaskOf(getParentOf(executable)).checkAbortPermission();
interrupt();
}
} finally {
lock.writeLock().unlock();
}
return HttpResponses.forwardToPreviousPage();
}
/**
* Throws away this executor and get a new one.
*/
@RequirePOST
public HttpResponse doYank() {
Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER);
if (isAlive())
throw new Failure("Can't yank a live executor");
owner.removeExecutor(this);
return HttpResponses.redirectViaContextPath("/");
}
/**
* Checks if the current user has a permission to stop this build.
*/
public boolean hasStopPermission() {
lock.readLock().lock();
try {
return executable != null && Tasks.getOwnerTaskOf(getParentOf(executable)).hasAbortPermission();
} finally {
lock.readLock().unlock();
}
}
public @Nonnull Computer getOwner() {
return owner;
}
/**
* Returns when this executor started or should start being idle.
*/
public long getIdleStartMilliseconds() {
lock.readLock().lock();
try {
if (isIdle())
return Math.max(creationTime, owner.getConnectTime());
else {
return Math.max(startTime + Math.max(0, Executables.getEstimatedDurationFor(executable)),
System.currentTimeMillis() + 15000);
}
} finally {
lock.readLock().unlock();
}
}
/**
* Exposes the executor to the remote API.
*/
public Api getApi() {
return new Api(this);
}
/**
* Creates a proxy object that executes the callee in the context that impersonates
* this executor. Useful to export an object to a remote channel.
*/
public <T> T newImpersonatingProxy(Class<T> type, T core) {
return new InterceptingProxy() {
protected Object call(Object o, Method m, Object[] args) throws Throwable {
final Executor old = IMPERSONATION.get();
IMPERSONATION.set(Executor.this);
try {
return m.invoke(o,args);
} finally {
IMPERSONATION.set(old);
}
}
}.wrap(type,core);
}
/**
* Returns the executor of the current thread or null if current thread is not an executor.
*/
public static @CheckForNull Executor currentExecutor() {
Thread t = Thread.currentThread();
if (t instanceof Executor) return (Executor) t;
return IMPERSONATION.get();
}
/**
* Returns the estimated duration for the executable.
* Protects against {@link AbstractMethodError}s if the {@link Executable} implementation
* was compiled against Hudson < 1.383
*
* @deprecated as of 1.388
* Use {@link Executables#getEstimatedDurationFor(Queue.Executable)}
*/
public static long getEstimatedDurationFor(Executable e) {
return Executables.getEstimatedDurationFor(e);
}
/**
* Mechanism to allow threads (in particular the channel request handling threads) to
* run on behalf of {@link Executor}.
*/
private static final ThreadLocal<Executor> IMPERSONATION = new ThreadLocal<Executor>();
private static final Logger LOGGER = Logger.getLogger(Executor.class.getName());
}
| fix guarded by values
| core/src/main/java/hudson/model/Executor.java | fix guarded by values |
|
Java | mit | a060814110bd83ba47e765a1cfadf6aef2514493 | 0 | pshields/futility,pshields/futility | /** @file Brain.java
* Player agent's central logic and memory center.
*
* @author Team F(utility)
*/
package futility;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.LinkedList;
/**
* This class contains the player's sensory data parsing and strategy computation algorithms.
*/
public class Brain implements Runnable {
/**
* Enumerator representing the possible strategies that may be used by this
* player agent.
*
* DASH_AROUND_THE_FIELD_CLOCKWISE tells the player to dash around
* the field boundaries clockwise.
*
* DASH_TOWARDS_THE_BALL_AND KICK implements a simple soccer strategy:
* 1. Run towards the ball.
* 2. Rotate around it until you can see the opponent's goal.
* 3. Kick the ball towards said goal.
*
* LOOK_AROUND tells the player to look around in a circle.
*
* GET_BETWEEN_BALL_AND_GOAL is pretty self explanatory
*/
public enum Strategy {
PRE_KICK_OFF_POSITION,
PRE_KICK_OFF_ANGLE,
DRIBBLE_KICK,
ACTIVE_INTERCEPT,
DASH_TOWARDS_BALL_AND_KICK,
LOOK_AROUND,
GET_BETWEEN_BALL_AND_GOAL,
PRE_FREE_KICK_POSITION,
PRE_CORNER_KICK_POSITION,
WING_POSITION,
KICK_BALL_OUT_OF_PENELTY_AREA
}
///////////////////////////////////////////////////////////////////////////
// MEMBER VARIABLES
///////////////////////////////////////////////////////////////////////////
Client client;
Player player;
public int time;
public PlayerRole.Role role;
// Self info & Play mode
private String playMode;
private SenseInfo curSenseInfo, lastSenseInfo;
public AccelerationVector acceleration;
public VelocityVector velocity;
private boolean isPositioned = false;
HashMap<String, FieldObject> fieldObjects = new HashMap<String, FieldObject>(100);
ArrayDeque<String> hearMessages = new ArrayDeque<String>();
LinkedList<Player> lastSeenOpponents = new LinkedList<Player>();
LinkedList<Settings.RESPONSE>responseHistory = new LinkedList<Settings.RESPONSE>();
private long timeLastSee = 0;
private long timeLastSenseBody = 0;
private int lastRan = -1;
private Strategy currentStrategy = Strategy.LOOK_AROUND;
private boolean updateStrategy = true;
///////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
///////////////////////////////////////////////////////////////////////////
/**
* This is the primary constructor for the Brain class.
*
* @param player a back-reference to the invoking player
* @param client the server client by which to send commands, etc.
*/
public Brain(Player player, Client client) {
this.player = player;
this.client = client;
this.curSenseInfo = new SenseInfo();
this.lastSenseInfo = new SenseInfo();
this.velocity = new VelocityVector();
this.acceleration = new AccelerationVector();
// Load the HashMap
for (int i = 0; i < Settings.STATIONARY_OBJECTS.length; i++) {
StationaryObject object = Settings.STATIONARY_OBJECTS[i];
//client.log(Log.DEBUG, String.format("Adding %s to my HashMap...", object.id));
fieldObjects.put(object.id, object);
}
// Load the response history
this.responseHistory.add(Settings.RESPONSE.NONE);
this.responseHistory.add(Settings.RESPONSE.NONE);
}
///////////////////////////////////////////////////////////////////////////
// GAME LOGIC
///////////////////////////////////////////////////////////////////////////
/**
* Returns this player's acceleration along the x axis. Shortcut function. Remember that
* accelerations are usually reset to 0 by the soccer server at the beginning of each time
* step.
*
* @return this player's acceleration along the x axis
*/
private final double accelX() {
return this.acceleration.getX();
}
/**
* Returns this player's acceleration along the y axis. Shortcut function.
*
* @return this player's acceleration along the y axis
*/
private final double accelY() {
return this.acceleration.getY();
}
/**
* Returns the direction, in radians, of the player at the current time.
*/
private final double dir() {
return Math.toRadians(this.player.direction.getDirection());
}
/**
* Assesses the utility of a strategy for the current time step.
*
* @param strategy the strategy to assess the utility of
* @return an assessment of the strategy's utility in the range [0.0, 1.0]
*/
private final double assessUtility(Strategy strategy) {
double utility = 0;
switch (strategy) {
case PRE_FREE_KICK_POSITION:
case PRE_CORNER_KICK_POSITION:
case PRE_KICK_OFF_POSITION:
// Check play mode, reposition as necessary.
if ( canUseMove() )
utility = 1 - (isPositioned ? 1 : 0);
break;
case PRE_KICK_OFF_ANGLE:
if ( isPositioned )
{
utility = this.player.team.side == 'r' ?
( this.canSee(Ball.ID) ? 0.0 : 1.0 ) : 0.0;
}
break;
case WING_POSITION:
if ( ( role == PlayerRole.Role.LEFT_WING
|| role == PlayerRole.Role.RIGHT_WING ) )
{
utility = 0.95;
}
break;
case DRIBBLE_KICK: // Unimplemented
Rectangle OPP_PENALTY_AREA = ( this.player.team.side == 'l' ) ?
Settings.PENALTY_AREA_RIGHT : Settings.PENALTY_AREA_LEFT;
// If the agent is a goalie, don't dribble!
// If we're in the opponent's strike zone, don't dribble! Go for score!
if ( this.role == PlayerRole.Role.GOALIE || this.player.inRectangle(OPP_PENALTY_AREA) ) {
utility = 0.0;
}
else {
utility = ( this.canKickBall() && this.canSee(
this.player.getOpponentGoalId()) ) ?
0.95 : 0.0;
}
break;
case DASH_TOWARDS_BALL_AND_KICK:
if (this.role == PlayerRole.Role.STRIKER) {
utility = 0.95;
}
else {
// Utility is high if the player is within ~ 5.0 meters of the ball
utility = Math.max(1.0, Math.pow(this.getOrCreate(Ball.ID).curInfo.distance / 5.0, -1.0));
}
break;
case LOOK_AROUND:
if (this.player.position.getPosition().isUnknown()) {
utility = 1.0;
}
else {
double conf = this.player.position.getConfidence(this.time);
if (conf > 0.01) {
utility = 1.0 - conf;
}
else {
utility = 0.0;
}
}
break;
case GET_BETWEEN_BALL_AND_GOAL:
// estimate our confidence of where the ball and the player are on the field
double ballConf = this.getOrCreate(Ball.ID).position.getConfidence(this.time);
double playerConf = this.player.position.getConfidence(this.time);
double conf = (ballConf + playerConf) / 2;
double initial = 1;
if (this.player.team.side == Settings.LEFT_SIDE) {
if (this.getOrCreate(Ball.ID).position.getX() < this.player.position.getX()) {
initial = 0.6;
} else {
initial = 0.9;
}
} else {
if (this.getOrCreate(Ball.ID).position.getX() > this.player.position.getX()) {
initial = 0.6;
} else {
initial = 0.9;
}
}
if (this.role == PlayerRole.Role.GOALIE || this.role == PlayerRole.Role.LEFT_DEFENDER || this.role == PlayerRole.Role.RIGHT_DEFENDER) {
initial *= 1;
} else {
initial *= 0.25;
}
if (!this.canSee("(b)")) {
initial = 0;
}
utility = initial * conf;
break;
case KICK_BALL_OUT_OF_PENELTY_AREA:
if(PlayerRole.isOnDefenseAndNotGoalie(role)){
final Rectangle myPeneltyBox = getMyPeneltyArea();
if(myPeneltyBox.contains(getOrCreate(Ball.ID))){
utility = 0.9;
}
}
else{
utility = 0.1;
}
break;
default:
utility = 0;
break;
}
return utility;
}
/**
* Checks if the play mode allows Move commands
*
* @return true if move commands can be issued.
*/
private final boolean canUseMove() {
return (
playMode.equals( "before_kick_off" ) ||
playMode.startsWith( "goal_r_") ||
playMode.startsWith( "goal_l_" ) ||
playMode.startsWith( "free_kick_" ) ||
playMode.startsWith( "corner_kick_" )
);
}
/**
* A rough estimate of whether the player can kick the ball, dependent
* on its distance to the ball and whether it is inside the playing field.
*
* @return true if the player is on the field and within kicking distance
*/
public final boolean canKickBall() {
if (!player.inRectangle(Settings.FIELD)) {
return false;
}
FieldObject ball = this.getOrCreate(Ball.ID);
if (ball.curInfo.time != time) {
return false;
}
return ball.curInfo.distance < Futil.kickable_radius();
}
/**
* True if and only if the ball was seen in the most recently-parsed 'see' message.
*/
public final boolean canSee(String id) {
if (!this.fieldObjects.containsKey(id)) {
Log.e("Can't see " + id + "!");
return false;
}
FieldObject obj = this.fieldObjects.get(id);
return obj.curInfo.time == this.time;
}
/**
* Accelerates the player in the direction of its body.
*
* @param power the power of the acceleration (0 to 100)
*/
private final void dash(double power) {
// Update this player's acceleration
this.acceleration.addPolar(this.dir(), this.effort());
this.client.sendCommand(Settings.Commands.DASH, Double.toString(power));
}
/**
* Accelerates the player in the direction of its body, offset by the given
* angle.
*
* @param power the power of the acceleration (0 to 100)
* @param offset an offset to be applied to the player's direction,
* yielding the direction of acceleration
*/
public final void dash(double power, double offset) {
this.acceleration.addPolar(this.dir() + offset, this.edp(power));
client.sendCommand(Settings.Commands.DASH, Double.toString(power), Double.toString(offset));
}
/**
* Determines the strategy with the current highest utility.
*
* @return the strategy this brain thinks is optimal for the current time step
*/
private final Strategy determineOptimalStrategy() {
Strategy optimalStrategy = this.currentStrategy;
if (this.updateStrategy) {
double bestUtility = 0;
for (Strategy strategy : Strategy.values()) {
double utility = this.assessUtility(strategy);
if (utility > bestUtility) {
bestUtility = utility;
optimalStrategy = strategy;
}
}
}
return optimalStrategy;
}
/**
* Returns this player's effective dash power. Refer to the soccer server manual for more information.
*
* @return this player's effective dash power
*/
private final double edp(double power) {
return this.effort() * Settings.DASH_POWER_RATE * power;
}
/**
* Returns an effort value for this player. If one wasn't received this time step, we guess.
*/
private final double effort() {
return this.curSenseInfo.effort;
}
/**
* Executes a strategy for the player in the current time step.
*
* @param strategy the strategy to execute
*/
private final void executeStrategy(Strategy strategy) {
FieldObject ball = this.getOrCreate(Ball.ID);
FieldObject goal = this.getOrCreate(this.player.getOpponentGoalId());
// Opponent goal
FieldObject opGoal = this.getOrCreate(this.player.getOpponentGoalId());
// Our goal
FieldObject ourGoal = this.getOrCreate(this.player.getGoalId());
switch (strategy) {
case PRE_FREE_KICK_POSITION:
if (playMode.equals("free_kick_l")) {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.FREE_KICK_L_FORMATION[player.number]);
} else {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.FREE_KICK_R_FORMATION[player.number]);
}
this.isPositioned = true;
// Since we have now moved back into formation, derivatives
// strategies such as LOOK_AROUND should become dominant.
break;
case PRE_CORNER_KICK_POSITION:
if (playMode.equals("corner_kick_l")) {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.CORNER_KICK_L_FORMATION[player.number]);
} else {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.CORNER_KICK_R_FORMATION[player.number]);
}
this.isPositioned = true;
// Since we have now moved back into formation, derivatives
// strategies such as LOOK_AROUND should become dominant.
break;
case PRE_KICK_OFF_POSITION:
this.move(Settings.FORMATION[player.number]);
this.isPositioned = true;
// Since we have now moved back into formation, derivatives
// strategies such as LOOK_AROUND should become dominant.
break;
case PRE_KICK_OFF_ANGLE:
this.turn(30);
break;
case WING_POSITION:
// If ball is close, dash toward it.
// Otherwise, stay off to side.
if ( ball.position.getConfidence(this.time) <= 0.1 )
{
turn(7.0);
}
else if ( ball.curInfo.distance < 5.0d || canUseMove() )
{
dash(40.0, Futil.simplifyAngle(player.relativeAngleTo(ball) ));
}
else
{
// Stay near ball, but not too close.
Point b_future = Futil.estimatePositionOf(ball, 3, time).getPosition();
Vector2D new_pos = b_future.asVector().addPolar(
( role == PlayerRole.Role.LEFT_WING ? 40.0 : -40.0 ), 8.0);
dash( Math.min(4, ball.curInfo.distance / 3.0d ) * new_pos.magnitude(), new_pos.direction());
}
break;
case DRIBBLE_KICK:
/*
* Find a dribble angle, weighted by presence of opponents.
* Determine dribble velocity based on current velocity.
* Dribble!
*/
// Predict next position:
Vector2D v_new = Futil.estimatePositionOf(this.player, 2, this.time).getPosition().asVector();
Vector2D v_target = v_new.add( findDribbleAngle() );
Vector2D v_ball = v_target.add( new Vector2D( -1 * ball.position.getX(),
-1 * ball.position.getY() ) );
double traj_power = Math.min(Settings.PLAYER_PARAMS.POWER_MAX,
( v_ball.magnitude() / (1 + Settings.BALL_PARAMS.BALL_DECAY ) ) * 10); // values of 1 or 2 do not give very useful kicks.
// Kick!
Log.i("Kick trajectory power: " + traj_power);
kick( traj_power, Futil.simplifyAngle( Math.toDegrees(v_ball.direction()) ) );
break;
case DASH_TOWARDS_BALL_AND_KICK:
Log.d("Estimated ball position: " + ball.position.render(this.time));
Log.d("Estimated opponent goal position: " + opGoal.position.render(this.time));
if (this.canKickBall()) {
if (this.canSee(this.player.getOpponentGoalId())) {
kick(100.0, this.player.relativeAngleTo(opGoal));
}
else {
dash(30.0, 90.0);
}
}
else if (ball.position.getConfidence(this.time) > 0.1) {
double approachAngle;
approachAngle = Futil.simplifyAngle(this.player.relativeAngleTo(ball));
if (Math.abs(approachAngle) > 10) {
this.turn(approachAngle);
}
else {
dash(50.0, approachAngle);
}
}
else {
turn(7.0);
}
break;
case LOOK_AROUND:
turn(7);
break;
case GET_BETWEEN_BALL_AND_GOAL:
double xmid = (ball.position.getX() + ourGoal.position.getX()) / 2;
double ymid = (ball.position.getY() + ourGoal.position.getY()) / 2;
Point midpoint = new Point(xmid, ymid);
this.moveTowards(midpoint);
break;
case KICK_BALL_OUT_OF_PENELTY_AREA:
if(canSee(Ball.ID)){
if(canKickBall()){
kick(100, player.relativeAngleTo(goal));
}
else{
moveTowards(ball.position.getPosition());
}
}
else{
//can't see the ball so do nothing
break;
}
break;
default:
break;
}
}
/**
* Finds the optimum angle to kick the ball toward within a kickable
* area.
*
* @param p Point to build angle from
* @return the vector to dribble toward.
*/
private final Vector2D findDribbleAngle() {
// TODO STUB: Need algorithm for a weighted dribble angle.
double d_length = Math.max(1.0, Futil.kickable_radius() );
// 5.0 is arbitrary in case nothing is visible; attempt to kick
// toward the lateral center of the field.
double d_angle = 5.0 * -1.0 * Math.signum( this.player.position.getY() );
// If opponents are visible, try to kick away from them.
if ( !lastSeenOpponents.isEmpty() )
{
double weight = 0.0d;
double w_angle = 0.0d;
for ( Player i : lastSeenOpponents )
{
double i_angle = player.relativeAngleTo(i);
double new_weight = Math.max(weight, Math.min(1.0,
1 / player.distanceTo(i) * Math.abs(
1 / ( i_angle == 0.0 ? 1.0 : i_angle ) ) ) );
if ( new_weight > weight )
w_angle = i_angle;
}
// Keep the angle within [-90,90]. Kick forward, not backward!
d_angle = Math.max( Math.abs( w_angle ) - 180, -90 ) * Math.signum( w_angle );
}
// Otherwise kick toward the goal.
else if ( this.canSee( this.player.getOpponentGoalId() ) )
d_angle += this.player.relativeAngleTo(
this.getOrCreate(this.player.getOpponentGoalId()));
Log.i("Dribble angle chosen: " + d_angle);
Vector2D d_vec = new Vector2D(0.0, 0.0);
d_vec = d_vec.addPolar(Math.toRadians(d_angle), d_length); // ?!
return d_vec;
/*
* Proposed algorithm:
*
* Finding highest weight opponent:
* W_i = ( 1 / opponent_distance ) * abs( 1 / opponent_angle ) )
*
* Finding RELATIVE angle:
* d_angle = max( abs( Opp_w_relative_angle ) - 180, -90 )
* * signum( Opp_w_relative_angle )
*/
}
/**
* Gets a field object from fieldObjects, or creates it if it doesn't yet exist.
*
* @param id the object's id
* @return the field object
*/
private final FieldObject getOrCreate(String id) {
if (this.fieldObjects.containsKey(id)) {
return this.fieldObjects.get(id);
}
else {
return FieldObject.create(id);
}
}
/**
* Infers the position and direction of this brain's associated player given two boundary flags
* on the same side seen in the current time step.
*
* @param o1 the first flag
* @param o2 the second flag
*/
private final void inferPositionAndDirection(FieldObject o1, FieldObject o2) {
// x1, x2, y1 and y2 are relative Cartesian coordinates to the flags
double x1 = Math.cos(Math.toRadians(o1.curInfo.direction)) * o1.curInfo.distance;
double y1 = Math.sin(Math.toRadians(o1.curInfo.direction)) * o1.curInfo.distance;
double x2 = Math.cos(Math.toRadians(o2.curInfo.direction)) * o2.curInfo.distance;
double y2 = Math.sin(Math.toRadians(o2.curInfo.direction)) * o2.curInfo.distance;
double direction = -Math.toDegrees(Math.atan((y2 - y1) / (x2 - x1)));
// Need to reverse the direction if looking closer to west and using horizontal boundary flags
if (o1.position.getY() == o2.position.getY()) {
if (Math.signum(o2.position.getX() - o1.position.getX()) != Math.signum(x2 - x1)) {
direction += 180.0;
}
}
// Need to offset the direction by +/- 90 degrees if using vertical boundary flags
else if (o1.position.getX() == o1.position.getX()) {
if (Math.signum(o2.position.getY() - o1.position.getY()) != Math.signum(x2 - x1)) {
direction += 270.0;
}
else {
direction += 90.0;
}
}
this.player.direction.update(Futil.simplifyAngle(direction), 0.95, this.time);
double x = o1.position.getX() - o1.curInfo.distance * Math.cos(Math.toRadians(direction + o1.curInfo.direction));
double y = o1.position.getY() - o1.curInfo.distance * Math.sin(Math.toRadians(direction + o1.curInfo.direction));
double distance = this.player.position.getPosition().distanceTo(new Point(x, y));
this.player.position.update(x, y, 0.95, this.time);
}
/**
* Moves the player to the specified coordinates (server coords).
*
* @param p the Point object to pass coordinates with (must be in server coordinates).
*/
public void move(Point p)
{
move(p.getX(), p.getY());
}
/**
* Moves the player to the specified coordinates (server coords).
*
* @param x x-coordinate
* @param y y-coordinate
*/
public void move(double x, double y) {
client.sendCommand(Settings.Commands.MOVE, Double.toString(x), Double.toString(y));
this.player.position.update(x, y, 1.0, this.time);
}
/**
* Overrides the strategy selection system. Used in tests.
*/
public void overrideStrategy(Strategy strategy) {
this.currentStrategy = strategy;
this.updateStrategy = false;
}
/**
* Kicks the ball in the direction of the player.
*
* @param power the level of power with which to kick (0 to 100)
*/
public void kick(double power) {
client.sendCommand(Settings.Commands.KICK, Double.toString(power));
}
/**
* Kicks the ball in the player's direction, offset by the given angle.
*
* @param power the level of power with which to kick (0 to 100)
* @param offset an angle in degrees to be added to the player's direction, yielding the direction of the kick
*/
public void kick(double power, double offset) {
client.sendCommand(Settings.Commands.KICK, Double.toString(power), Double.toString(offset));
}
/**
* Parses a message from the soccer server. This method is called whenever
* a message from the server is received.
*
* @param message the message (string), exactly as it was received
*/
public void parseMessage(String message) {
long timeReceived = System.currentTimeMillis();
message = Futil.sanitize(message);
// Handle `sense_body` messages
if (message.startsWith("(sense_body")) {
curSenseInfo.copy(lastSenseInfo);
curSenseInfo.reset();
this.timeLastSenseBody = timeReceived;
curSenseInfo.time = Futil.extractTime(message);
this.time = curSenseInfo.time;
// TODO better nested parentheses parsing logic; perhaps
// reconcile with Patrick's parentheses logic?
Log.d("Received a `sense_body` message at time step " + time + ".");
String parts[] = message.split("\\(");
for ( String i : parts ) // for each structured argument:
{
// Clean the string, and break it down into the base arguments.
String nMsg = i.split("\\)")[0].trim();
if ( nMsg.isEmpty() ) continue;
String nArgs[] = nMsg.split("\\s");
// Check for specific argument types; ignore unknown arguments.
if ( nArgs[0].contains("view_mode") )
{ // Player's current view mode
curSenseInfo.viewQuality = nArgs[1];
curSenseInfo.viewWidth = nArgs[2];
}
else if ( nArgs[0].contains("stamina") )
{ // Player's stamina data
curSenseInfo.stamina = Double.parseDouble(nArgs[1]);
curSenseInfo.effort = Double.parseDouble(nArgs[2]);
curSenseInfo.staminaCapacity = Double.parseDouble(nArgs[3]);
}
else if ( nArgs[0].contains("speed") )
{ // Player's speed data
curSenseInfo.amountOfSpeed = Double.parseDouble(nArgs[1]);
curSenseInfo.directionOfSpeed = Double.parseDouble(nArgs[2]);
// Update velocity variable
double dir = this.dir() + Math.toRadians(curSenseInfo.directionOfSpeed);
this.velocity.setPolar(dir, curSenseInfo.amountOfSpeed);
}
else if ( nArgs[0].contains("head_angle") )
{ // Player's head angle
curSenseInfo.headAngle = Double.parseDouble(nArgs[1]);
}
else if ( nArgs[0].contains("ball") || nArgs[0].contains("player")
|| nArgs[0].contains("post") )
{ // COLLISION flags; limitation of this loop approach is we
// can't handle nested parentheses arguments well.
// Luckily these flags only occur in the collision structure.
curSenseInfo.collision = nArgs[0];
}
}
// If the brain has responded to two see messages in a row, it's time to respond to a sense_body.
if (this.responseHistory.get(0) == Settings.RESPONSE.SEE && this.responseHistory.get(1) == Settings.RESPONSE.SEE) {
this.run();
this.responseHistory.push(Settings.RESPONSE.SENSE_BODY);
this.responseHistory.removeLast();
}
}
// Handle `hear` messages
else if (message.startsWith("(hear"))
{
String parts[] = message.split("\\s");
this.time = Integer.parseInt(parts[1]);
if ( parts[2].startsWith("s") || parts[2].startsWith("o") || parts[2].startsWith("c") )
{
// TODO logic for self, on-line coach, and trainer coach.
// Self could potentially be for feedback,
// On-line coach will require coach language parsing,
// And trainer likely will as well. Outside of Sprint #2 scope.
return;
}
else
{
// Check for a referee message, otherwise continue.
String nMsg = parts[3].split("\\)")[0]; // Retrieve the message.
if ( nMsg.startsWith("goal_l_") )
nMsg = "goal_l_";
else if ( nMsg.startsWith("goal_r_") )
nMsg = "goal_r_";
if ( parts[2].startsWith("r") // Referee;
&& Settings.PLAY_MODES.contains(nMsg) ) // Play Mode?
{
playMode = nMsg;
this.isPositioned = false;
}
else
hearMessages.add( nMsg );
}
}
// Handle `see` messages
else if (message.startsWith("(see")) {
this.timeLastSee = timeReceived;
this.time = Futil.extractTime(message);
Log.d("Received `see` message at time step " + this.time);
LinkedList<String> infos = Futil.extractInfos(message);
lastSeenOpponents.clear();
for (String info : infos) {
String id = Futil.extractId(info);
if (Futil.isUniqueFieldObject(id)) {
FieldObject obj = this.getOrCreate(id);
obj.update(this.player, info, this.time);
this.fieldObjects.put(id, obj);
if ( id.startsWith("(p \"") && !( id.startsWith(this.player.team.name, 4) ) )
lastSeenOpponents.add( (Player)obj );
}
}
// Immediately run for the current step. Since our computations takes only a few
// milliseconds, it's okay to start running over half-way into the 100ms cycle.
// That means two out of every three time steps will be executed here.
this.run();
// Make sure we stay in sync with the mid-way `see`s
if (this.timeLastSee - this.timeLastSenseBody > 30) {
this.responseHistory.clear();
this.responseHistory.add(Settings.RESPONSE.SEE);
this.responseHistory.add(Settings.RESPONSE.SEE);
}
else {
this.responseHistory.add(Settings.RESPONSE.SEE);
this.responseHistory.removeLast();
}
}
// Handle init messages
else if (message.startsWith("(init")) {
String[] parts = message.split("\\s");
char teamSide = message.charAt(6);
if (teamSide == Settings.LEFT_SIDE) {
player.team.side = Settings.LEFT_SIDE;
player.otherTeam.side = Settings.RIGHT_SIDE;
}
else if (teamSide == Settings.RIGHT_SIDE) {
player.team.side = Settings.RIGHT_SIDE;
player.otherTeam.side = Settings.LEFT_SIDE;
}
else {
// Raise error
Log.e("Could not parse teamSide.");
}
player.number = Integer.parseInt(parts[2]);
this.role = Settings.PLAYER_ROLES[this.player.number - 1];
playMode = parts[3].split("\\)")[0];
}
else if (message.startsWith("(server_param")) {
parseServerParameters(message);
}
}
/**
* Parses the initial parameters received from the server.
*
* @param message the parameters message received from the server
*/
public void parseServerParameters(String message)
{
String parts[] = message.split("\\(");
for ( String i : parts ) // for each structured argument:
{
// Clean the string, and break it down into the base arguments.
String nMsg = i.split("\\)")[0].trim();
if ( nMsg.isEmpty() ) continue;
String nArgs[] = nMsg.split("\\s");
// Check for specific argument types; ignore unknown arguments.
if (nArgs[0].startsWith("dash_power_rate"))
Settings.setDashPowerRate(Double.parseDouble(nArgs[1]));
if ( nArgs[0].startsWith("goal_width") )
Settings.setGoalHeight(Double.parseDouble(nArgs[1]));
// Ball arguments:
else if ( nArgs[0].startsWith("ball") )
ServerParams_Ball.Builder.dataParser(nArgs);
// Player arguments:
else if ( nArgs[0].startsWith("player") || nArgs[0].startsWith("min")
|| nArgs[0].startsWith("max") )
ServerParams_Player.Builder.dataParser(nArgs);
}
// Rebuild all parameter objects with updated parameters.
Settings.rebuildParams();
}
/**
* Responds for the current time step.
*/
public void run() {
final long startTime = System.currentTimeMillis();
final long endTime;
int expectedNextRun = this.lastRan + 1;
if (this.time > expectedNextRun) {
Log.e("Brain did not run during time step " + expectedNextRun + ".");
}
this.lastRan = this.time;
this.acceleration.reset();
this.updatePositionAndDirection();
this.currentStrategy = this.determineOptimalStrategy();
Log.i("Current strategy: " + this.currentStrategy);
this.executeStrategy(this.currentStrategy);
Log.d("Estimated player position: " + this.player.position.render(this.time) + ".");
Log.d("Estimated player direction: " + this.player.direction.render(this.time) + ".");
endTime = System.currentTimeMillis();
final long duration = endTime - startTime;
Log.d("Took " + duration + " ms (plus small overhead) to run at time " + this.time + ".");
if (duration > 35) {
Log.e("Took " + duration + " ms (plus small overhead) to run at time " + this.time + ".");
}
}
/**
* Adds the given angle to the player's current direction.
*
* @param offset an angle in degrees to add to the player's current direction
*/
public final void turn(double offset) {
double moment = Futil.toValidMoment(offset);
client.sendCommand(Settings.Commands.TURN, moment);
// TODO Potentially take magnitude of offset into account in the
// determination of the new confidence in the player's position.
player.direction.update(player.direction.getDirection() + moment, 0.95 * player.direction.getConfidence(this.time), this.time);
}
/**
* Updates the player's current direction to be the given direction.
*
* @param direction angle in degrees, assuming soccer server coordinate system
*/
public final void turnTo(double direction) {
this.turn(this.player.relativeAngleTo(direction));
}
/**
* Send commands to move the player to a point at maximum power
* @param point the point to move to
*/
private final void moveTowards(Point point){
moveTowards(point, 100d);
}
/**
* Send commands to move the player to a point with the given power
* @param point to move towards
* @param power to move at
*/
private final void moveTowards(Point point, double power){
final double x = player.position.getX() - point.getX();
final double y = player.position.getY() - point.getY();
final double theta = Math.toDegrees(Math.atan2(y, x));
turnTo(theta);
dash(power);
}
/**
* Updates this this brain's belief about the associated player's position and direction
* at the current time step.
*/
private final void updatePositionAndDirection() {
// Infer from the most-recent `see` if it happened in the current time-step
for (int i = 0; i < 4; i++) {
LinkedList<FieldObject> flagsOnSide = new LinkedList<FieldObject>();
for (String id : Settings.BOUNDARY_FLAG_GROUPS[i]) {
FieldObject flag = this.fieldObjects.get(id);
if (flag.curInfo.time == this.time) {
flagsOnSide.add(flag);
}
else {
//Log.i("Flag " + id + "last updated at time " + flag.info.time + ", not " + this.time);
}
if (flagsOnSide.size() > 1) {
this.inferPositionAndDirection(flagsOnSide.poll(), flagsOnSide.poll());
return;
}
}
}
// TODO Handle other cases
Log.e("Did not update position or direction at time " + this.time);
}
/**
* @return {@link Settings#PENALTY_AREA_LEFT} if player is on the left team, or {@link Settings#PENALTY_AREA_RIGHT} if on the right team.
*/
final public Rectangle getMyPeneltyArea(){
if(player.team == null) throw new NullPointerException("Player team not initialized while getting penelty area.");
return player.team.side == 'l' ? Settings.PENALTY_AREA_LEFT : Settings.PENALTY_AREA_RIGHT;
}
/**
* Returns this player's x velocity. Shortcut function.
*
* @return this player's x velocity
*/
private final double velX() {
return this.velocity.getX();
}
/**
* Returns this player's y velocity. Shortcut function.
*
* @return this player's y velocity
*/
private final double velY() {
return this.velocity.getY();
}
/**
* Returns this player's x.
*
* @return this player's x-coordinate
*/
private final double x() {
return this.player.position.getPosition().getX();
}
/**
* Returns this player's y.
*
* @return this player's y coordinate
*/
private final double y() {
return this.player.position.getPosition().getY();
}
}
| src/futility/Brain.java | /** @file Brain.java
* Player agent's central logic and memory center.
*
* @author Team F(utility)
*/
package futility;
import java.util.ArrayDeque;
import java.util.HashMap;
import java.util.LinkedList;
/**
* This class contains the player's sensory data parsing and strategy computation algorithms.
*/
public class Brain implements Runnable {
/**
* Enumerator representing the possible strategies that may be used by this
* player agent.
*
* DASH_AROUND_THE_FIELD_CLOCKWISE tells the player to dash around
* the field boundaries clockwise.
*
* DASH_TOWARDS_THE_BALL_AND KICK implements a simple soccer strategy:
* 1. Run towards the ball.
* 2. Rotate around it until you can see the opponent's goal.
* 3. Kick the ball towards said goal.
*
* LOOK_AROUND tells the player to look around in a circle.
*
* GET_BETWEEN_BALL_AND_GOAL is pretty self explanatory
*/
public enum Strategy {
PRE_KICK_OFF_POSITION,
PRE_KICK_OFF_ANGLE,
DRIBBLE_KICK,
ACTIVE_INTERCEPT,
DASH_TOWARDS_BALL_AND_KICK,
LOOK_AROUND,
GET_BETWEEN_BALL_AND_GOAL,
PRE_FREE_KICK_POSITION,
PRE_CORNER_KICK_POSITION,
KICK_BALL_OUT_OF_PENELTY_AREA
}
///////////////////////////////////////////////////////////////////////////
// MEMBER VARIABLES
///////////////////////////////////////////////////////////////////////////
Client client;
Player player;
public int time;
public PlayerRole.Role role;
// Self info & Play mode
private String playMode;
private SenseInfo curSenseInfo, lastSenseInfo;
public AccelerationVector acceleration;
public VelocityVector velocity;
private boolean isPositioned = false;
HashMap<String, FieldObject> fieldObjects = new HashMap<String, FieldObject>(100);
ArrayDeque<String> hearMessages = new ArrayDeque<String>();
LinkedList<Player> lastSeenOpponents = new LinkedList<Player>();
LinkedList<Settings.RESPONSE>responseHistory = new LinkedList<Settings.RESPONSE>();
private long timeLastSee = 0;
private long timeLastSenseBody = 0;
private int lastRan = -1;
private Strategy currentStrategy = Strategy.LOOK_AROUND;
private boolean updateStrategy = true;
///////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
///////////////////////////////////////////////////////////////////////////
/**
* This is the primary constructor for the Brain class.
*
* @param player a back-reference to the invoking player
* @param client the server client by which to send commands, etc.
*/
public Brain(Player player, Client client) {
this.player = player;
this.client = client;
this.curSenseInfo = new SenseInfo();
this.lastSenseInfo = new SenseInfo();
this.velocity = new VelocityVector();
this.acceleration = new AccelerationVector();
// Load the HashMap
for (int i = 0; i < Settings.STATIONARY_OBJECTS.length; i++) {
StationaryObject object = Settings.STATIONARY_OBJECTS[i];
//client.log(Log.DEBUG, String.format("Adding %s to my HashMap...", object.id));
fieldObjects.put(object.id, object);
}
// Load the response history
this.responseHistory.add(Settings.RESPONSE.NONE);
this.responseHistory.add(Settings.RESPONSE.NONE);
}
///////////////////////////////////////////////////////////////////////////
// GAME LOGIC
///////////////////////////////////////////////////////////////////////////
/**
* Returns this player's acceleration along the x axis. Shortcut function. Remember that
* accelerations are usually reset to 0 by the soccer server at the beginning of each time
* step.
*
* @return this player's acceleration along the x axis
*/
private final double accelX() {
return this.acceleration.getX();
}
/**
* Returns this player's acceleration along the y axis. Shortcut function.
*
* @return this player's acceleration along the y axis
*/
private final double accelY() {
return this.acceleration.getY();
}
/**
* Returns the direction, in radians, of the player at the current time.
*/
private final double dir() {
return Math.toRadians(this.player.direction.getDirection());
}
/**
* Assesses the utility of a strategy for the current time step.
*
* @param strategy the strategy to assess the utility of
* @return an assessment of the strategy's utility in the range [0.0, 1.0]
*/
private final double assessUtility(Strategy strategy) {
double utility = 0;
switch (strategy) {
case PRE_FREE_KICK_POSITION:
case PRE_CORNER_KICK_POSITION:
case PRE_KICK_OFF_POSITION:
// Check play mode, reposition as necessary.
if ( canUseMove() )
utility = 1 - (isPositioned ? 1 : 0);
break;
case PRE_KICK_OFF_ANGLE:
if ( isPositioned )
{
utility = this.player.team.side == 'r' ?
( this.canSee(Ball.ID) ? 0.0 : 1.0 ) : 0.0;
}
break;
case DRIBBLE_KICK: // Unimplemented
Rectangle OPP_PENALTY_AREA = ( this.player.team.side == 'l' ) ?
Settings.PENALTY_AREA_RIGHT : Settings.PENALTY_AREA_LEFT;
// If the agent is a goalie, don't dribble!
// If we're in the opponent's strike zone, don't dribble! Go for score!
if ( this.role == PlayerRole.Role.GOALIE || this.player.inRectangle(OPP_PENALTY_AREA) ) {
utility = 0.0;
}
else {
utility = ( this.canKickBall() && this.canSee(
this.player.getOpponentGoalId()) ) ?
0.95 : 0.0;
}
break;
case DASH_TOWARDS_BALL_AND_KICK:
if (this.role == PlayerRole.Role.STRIKER) {
utility = 0.95;
}
else {
// Utility is high if the player is within ~ 5.0 meters of the ball
utility = Math.max(1.0, Math.pow(this.getOrCreate(Ball.ID).curInfo.distance / 5.0, -1.0));
}
break;
case LOOK_AROUND:
if (this.player.position.getPosition().isUnknown()) {
utility = 1.0;
}
else {
double conf = this.player.position.getConfidence(this.time);
if (conf > 0.01) {
utility = 1.0 - conf;
}
else {
utility = 0.0;
}
}
break;
case GET_BETWEEN_BALL_AND_GOAL:
// estimate our confidence of where the ball and the player are on the field
double ballConf = this.getOrCreate(Ball.ID).position.getConfidence(this.time);
double playerConf = this.player.position.getConfidence(this.time);
double conf = (ballConf + playerConf) / 2;
double initial = 1;
if (this.player.team.side == Settings.LEFT_SIDE) {
if (this.getOrCreate(Ball.ID).position.getX() < this.player.position.getX()) {
initial = 0.6;
} else {
initial = 0.9;
}
} else {
if (this.getOrCreate(Ball.ID).position.getX() > this.player.position.getX()) {
initial = 0.6;
} else {
initial = 0.9;
}
}
if (this.role == PlayerRole.Role.GOALIE || this.role == PlayerRole.Role.LEFT_DEFENDER || this.role == PlayerRole.Role.RIGHT_DEFENDER) {
initial *= 1;
} else {
initial *= 0.25;
}
if (!this.canSee("(b)")) {
initial = 0;
}
utility = initial * conf;
break;
case KICK_BALL_OUT_OF_PENELTY_AREA:
if(PlayerRole.isOnDefenseAndNotGoalie(role)){
final Rectangle myPeneltyBox = getMyPeneltyArea();
if(myPeneltyBox.contains(getOrCreate(Ball.ID))){
utility = 0.9;
}
}
else{
utility = 0.1;
}
break;
default:
utility = 0;
break;
}
return utility;
}
/**
* Checks if the play mode allows Move commands
*
* @return true if move commands can be issued.
*/
private final boolean canUseMove() {
return (
playMode.equals( "before_kick_off" ) ||
playMode.startsWith( "goal_r_") ||
playMode.startsWith( "goal_l_" ) ||
playMode.startsWith( "free_kick_" ) ||
playMode.startsWith( "corner_kick_" )
);
}
/**
* A rough estimate of whether the player can kick the ball, dependent
* on its distance to the ball and whether it is inside the playing field.
*
* @return true if the player is on the field and within kicking distance
*/
public final boolean canKickBall() {
if (!player.inRectangle(Settings.FIELD)) {
return false;
}
FieldObject ball = this.getOrCreate(Ball.ID);
if (ball.curInfo.time != time) {
return false;
}
return ball.curInfo.distance < Futil.kickable_radius();
}
/**
* True if and only if the ball was seen in the most recently-parsed 'see' message.
*/
public final boolean canSee(String id) {
if (!this.fieldObjects.containsKey(id)) {
Log.e("Can't see " + id + "!");
return false;
}
FieldObject obj = this.fieldObjects.get(id);
return obj.curInfo.time == this.time;
}
/**
* Accelerates the player in the direction of its body.
*
* @param power the power of the acceleration (0 to 100)
*/
private final void dash(double power) {
// Update this player's acceleration
this.acceleration.addPolar(this.dir(), this.effort());
this.client.sendCommand(Settings.Commands.DASH, Double.toString(power));
}
/**
* Accelerates the player in the direction of its body, offset by the given
* angle.
*
* @param power the power of the acceleration (0 to 100)
* @param offset an offset to be applied to the player's direction,
* yielding the direction of acceleration
*/
public final void dash(double power, double offset) {
this.acceleration.addPolar(this.dir() + offset, this.edp(power));
client.sendCommand(Settings.Commands.DASH, Double.toString(power), Double.toString(offset));
}
/**
* Determines the strategy with the current highest utility.
*
* @return the strategy this brain thinks is optimal for the current time step
*/
private final Strategy determineOptimalStrategy() {
Strategy optimalStrategy = this.currentStrategy;
if (this.updateStrategy) {
double bestUtility = 0;
for (Strategy strategy : Strategy.values()) {
double utility = this.assessUtility(strategy);
if (utility > bestUtility) {
bestUtility = utility;
optimalStrategy = strategy;
}
}
}
return optimalStrategy;
}
/**
* Returns this player's effective dash power. Refer to the soccer server manual for more information.
*
* @return this player's effective dash power
*/
private final double edp(double power) {
return this.effort() * Settings.DASH_POWER_RATE * power;
}
/**
* Returns an effort value for this player. If one wasn't received this time step, we guess.
*/
private final double effort() {
return this.curSenseInfo.effort;
}
/**
* Executes a strategy for the player in the current time step.
*
* @param strategy the strategy to execute
*/
private final void executeStrategy(Strategy strategy) {
FieldObject ball = this.getOrCreate(Ball.ID);
FieldObject goal = this.getOrCreate(this.player.getOpponentGoalId());
// Opponent goal
FieldObject opGoal = this.getOrCreate(this.player.getOpponentGoalId());
// Our goal
FieldObject ourGoal = this.getOrCreate(this.player.getGoalId());
switch (strategy) {
case PRE_FREE_KICK_POSITION:
if (playMode.equals("free_kick_l")) {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.FREE_KICK_L_FORMATION[player.number]);
} else {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.FREE_KICK_R_FORMATION[player.number]);
}
this.isPositioned = true;
// Since we have now moved back into formation, derivatives
// strategies such as LOOK_AROUND should become dominant.
break;
case PRE_CORNER_KICK_POSITION:
if (playMode.equals("corner_kick_l")) {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.CORNER_KICK_L_FORMATION[player.number]);
} else {
if (this.player.team.side == Settings.LEFT_SIDE) {
//TODO
} else {
//TODO
}
this.move(Settings.CORNER_KICK_R_FORMATION[player.number]);
}
this.isPositioned = true;
// Since we have now moved back into formation, derivatives
// strategies such as LOOK_AROUND should become dominant.
break;
case PRE_KICK_OFF_POSITION:
this.move(Settings.FORMATION[player.number]);
this.isPositioned = true;
// Since we have now moved back into formation, derivatives
// strategies such as LOOK_AROUND should become dominant.
break;
case PRE_KICK_OFF_ANGLE:
this.turn(30);
break;
case DRIBBLE_KICK:
/*
* Find a dribble angle, weighted by presence of opponents.
* Determine dribble velocity based on current velocity.
* Dribble!
*/
// Predict next position:
Vector2D v_new = Futil.estimatePositionOf(this.player, 2, this.time).getPosition().asVector();
Vector2D v_target = v_new.add( findDribbleAngle() );
Vector2D v_ball = v_target.add( new Vector2D( -1 * ball.position.getX(),
-1 * ball.position.getY() ) );
double traj_power = Math.min(Settings.PLAYER_PARAMS.POWER_MAX,
( v_ball.magnitude() / (1 + Settings.BALL_PARAMS.BALL_DECAY ) ) * 10); // values of 1 or 2 do not give very useful kicks.
// Kick!
Log.i("Kick trajectory power: " + traj_power);
kick( traj_power, Futil.simplifyAngle( Math.toDegrees(v_ball.direction()) ) );
break;
case DASH_TOWARDS_BALL_AND_KICK:
Log.d("Estimated ball position: " + ball.position.render(this.time));
Log.d("Estimated opponent goal position: " + opGoal.position.render(this.time));
if (this.canKickBall()) {
if (this.canSee(this.player.getOpponentGoalId())) {
kick(100.0, this.player.relativeAngleTo(opGoal));
}
else {
dash(30.0, 90.0);
}
}
else if (ball.position.getConfidence(this.time) > 0.1) {
double approachAngle;
approachAngle = Futil.simplifyAngle(this.player.relativeAngleTo(ball));
if (Math.abs(approachAngle) > 10) {
this.turn(approachAngle);
}
else {
dash(50.0, approachAngle);
}
}
else {
turn(7.0);
}
break;
case LOOK_AROUND:
turn(7);
break;
case GET_BETWEEN_BALL_AND_GOAL:
double xmid = (ball.position.getX() + ourGoal.position.getX()) / 2;
double ymid = (ball.position.getY() + ourGoal.position.getY()) / 2;
Point midpoint = new Point(xmid, ymid);
this.moveTowards(midpoint);
break;
case KICK_BALL_OUT_OF_PENELTY_AREA:
if(canSee(Ball.ID)){
if(canKickBall()){
kick(100, player.relativeAngleTo(goal));
}
else{
moveTowards(ball.position.getPosition());
}
}
else{
//can't see the ball so do nothing
break;
}
break;
default:
break;
}
}
/**
* Finds the optimum angle to kick the ball toward within a kickable
* area.
*
* @param p Point to build angle from
* @return the vector to dribble toward.
*/
private final Vector2D findDribbleAngle() {
// TODO STUB: Need algorithm for a weighted dribble angle.
double d_length = Math.max(1.0, Futil.kickable_radius() );
// 5.0 is arbitrary in case nothing is visible; attempt to kick
// toward the lateral center of the field.
double d_angle = 5.0 * -1.0 * Math.signum( this.player.position.getY() );
// If opponents are visible, try to kick away from them.
if ( !lastSeenOpponents.isEmpty() )
{
double weight = 0.0d;
double w_angle = 0.0d;
for ( Player i : lastSeenOpponents )
{
double i_angle = player.relativeAngleTo(i);
double new_weight = Math.max(weight, Math.min(1.0,
1 / player.distanceTo(i) * Math.abs(
1 / ( i_angle == 0.0 ? 1.0 : i_angle ) ) ) );
if ( new_weight > weight )
w_angle = i_angle;
}
// Keep the angle within [-90,90]. Kick forward, not backward!
d_angle = Math.max( Math.abs( w_angle ) - 180, -90 ) * Math.signum( w_angle );
}
// Otherwise kick toward the goal.
else if ( this.canSee( this.player.getOpponentGoalId() ) )
d_angle += this.player.relativeAngleTo(
this.getOrCreate(this.player.getOpponentGoalId()));
Log.i("Dribble angle chosen: " + d_angle);
Vector2D d_vec = new Vector2D(0.0, 0.0);
d_vec = d_vec.addPolar(Math.toRadians(d_angle), d_length); // ?!
return d_vec;
/*
* Proposed algorithm:
*
* Finding highest weight opponent:
* W_i = ( 1 / opponent_distance ) * abs( 1 / opponent_angle ) )
*
* Finding RELATIVE angle:
* d_angle = max( abs( Opp_w_relative_angle ) - 180, -90 )
* * signum( Opp_w_relative_angle )
*/
}
/**
* Gets a field object from fieldObjects, or creates it if it doesn't yet exist.
*
* @param id the object's id
* @return the field object
*/
private final FieldObject getOrCreate(String id) {
if (this.fieldObjects.containsKey(id)) {
return this.fieldObjects.get(id);
}
else {
return FieldObject.create(id);
}
}
/**
* Infers the position and direction of this brain's associated player given two boundary flags
* on the same side seen in the current time step.
*
* @param o1 the first flag
* @param o2 the second flag
*/
private final void inferPositionAndDirection(FieldObject o1, FieldObject o2) {
// x1, x2, y1 and y2 are relative Cartesian coordinates to the flags
double x1 = Math.cos(Math.toRadians(o1.curInfo.direction)) * o1.curInfo.distance;
double y1 = Math.sin(Math.toRadians(o1.curInfo.direction)) * o1.curInfo.distance;
double x2 = Math.cos(Math.toRadians(o2.curInfo.direction)) * o2.curInfo.distance;
double y2 = Math.sin(Math.toRadians(o2.curInfo.direction)) * o2.curInfo.distance;
double direction = -Math.toDegrees(Math.atan((y2 - y1) / (x2 - x1)));
// Need to reverse the direction if looking closer to west and using horizontal boundary flags
if (o1.position.getY() == o2.position.getY()) {
if (Math.signum(o2.position.getX() - o1.position.getX()) != Math.signum(x2 - x1)) {
direction += 180.0;
}
}
// Need to offset the direction by +/- 90 degrees if using vertical boundary flags
else if (o1.position.getX() == o1.position.getX()) {
if (Math.signum(o2.position.getY() - o1.position.getY()) != Math.signum(x2 - x1)) {
direction += 270.0;
}
else {
direction += 90.0;
}
}
this.player.direction.update(Futil.simplifyAngle(direction), 0.95, this.time);
double x = o1.position.getX() - o1.curInfo.distance * Math.cos(Math.toRadians(direction + o1.curInfo.direction));
double y = o1.position.getY() - o1.curInfo.distance * Math.sin(Math.toRadians(direction + o1.curInfo.direction));
double distance = this.player.position.getPosition().distanceTo(new Point(x, y));
this.player.position.update(x, y, 0.95, this.time);
}
/**
* Moves the player to the specified coordinates (server coords).
*
* @param p the Point object to pass coordinates with (must be in server coordinates).
*/
public void move(Point p)
{
move(p.getX(), p.getY());
}
/**
* Moves the player to the specified coordinates (server coords).
*
* @param x x-coordinate
* @param y y-coordinate
*/
public void move(double x, double y) {
client.sendCommand(Settings.Commands.MOVE, Double.toString(x), Double.toString(y));
this.player.position.update(x, y, 1.0, this.time);
}
/**
* Overrides the strategy selection system. Used in tests.
*/
public void overrideStrategy(Strategy strategy) {
this.currentStrategy = strategy;
this.updateStrategy = false;
}
/**
* Kicks the ball in the direction of the player.
*
* @param power the level of power with which to kick (0 to 100)
*/
public void kick(double power) {
client.sendCommand(Settings.Commands.KICK, Double.toString(power));
}
/**
* Kicks the ball in the player's direction, offset by the given angle.
*
* @param power the level of power with which to kick (0 to 100)
* @param offset an angle in degrees to be added to the player's direction, yielding the direction of the kick
*/
public void kick(double power, double offset) {
client.sendCommand(Settings.Commands.KICK, Double.toString(power), Double.toString(offset));
}
/**
* Parses a message from the soccer server. This method is called whenever
* a message from the server is received.
*
* @param message the message (string), exactly as it was received
*/
public void parseMessage(String message) {
long timeReceived = System.currentTimeMillis();
message = Futil.sanitize(message);
// Handle `sense_body` messages
if (message.startsWith("(sense_body")) {
curSenseInfo.copy(lastSenseInfo);
curSenseInfo.reset();
this.timeLastSenseBody = timeReceived;
curSenseInfo.time = Futil.extractTime(message);
this.time = curSenseInfo.time;
// TODO better nested parentheses parsing logic; perhaps
// reconcile with Patrick's parentheses logic?
Log.d("Received a `sense_body` message at time step " + time + ".");
String parts[] = message.split("\\(");
for ( String i : parts ) // for each structured argument:
{
// Clean the string, and break it down into the base arguments.
String nMsg = i.split("\\)")[0].trim();
if ( nMsg.isEmpty() ) continue;
String nArgs[] = nMsg.split("\\s");
// Check for specific argument types; ignore unknown arguments.
if ( nArgs[0].contains("view_mode") )
{ // Player's current view mode
curSenseInfo.viewQuality = nArgs[1];
curSenseInfo.viewWidth = nArgs[2];
}
else if ( nArgs[0].contains("stamina") )
{ // Player's stamina data
curSenseInfo.stamina = Double.parseDouble(nArgs[1]);
curSenseInfo.effort = Double.parseDouble(nArgs[2]);
curSenseInfo.staminaCapacity = Double.parseDouble(nArgs[3]);
}
else if ( nArgs[0].contains("speed") )
{ // Player's speed data
curSenseInfo.amountOfSpeed = Double.parseDouble(nArgs[1]);
curSenseInfo.directionOfSpeed = Double.parseDouble(nArgs[2]);
// Update velocity variable
double dir = this.dir() + Math.toRadians(curSenseInfo.directionOfSpeed);
this.velocity.setPolar(dir, curSenseInfo.amountOfSpeed);
}
else if ( nArgs[0].contains("head_angle") )
{ // Player's head angle
curSenseInfo.headAngle = Double.parseDouble(nArgs[1]);
}
else if ( nArgs[0].contains("ball") || nArgs[0].contains("player")
|| nArgs[0].contains("post") )
{ // COLLISION flags; limitation of this loop approach is we
// can't handle nested parentheses arguments well.
// Luckily these flags only occur in the collision structure.
curSenseInfo.collision = nArgs[0];
}
}
// If the brain has responded to two see messages in a row, it's time to respond to a sense_body.
if (this.responseHistory.get(0) == Settings.RESPONSE.SEE && this.responseHistory.get(1) == Settings.RESPONSE.SEE) {
this.run();
this.responseHistory.push(Settings.RESPONSE.SENSE_BODY);
this.responseHistory.removeLast();
}
}
// Handle `hear` messages
else if (message.startsWith("(hear"))
{
String parts[] = message.split("\\s");
this.time = Integer.parseInt(parts[1]);
if ( parts[2].startsWith("s") || parts[2].startsWith("o") || parts[2].startsWith("c") )
{
// TODO logic for self, on-line coach, and trainer coach.
// Self could potentially be for feedback,
// On-line coach will require coach language parsing,
// And trainer likely will as well. Outside of Sprint #2 scope.
return;
}
else
{
// Check for a referee message, otherwise continue.
String nMsg = parts[3].split("\\)")[0]; // Retrieve the message.
if ( nMsg.startsWith("goal_l_") )
nMsg = "goal_l_";
else if ( nMsg.startsWith("goal_r_") )
nMsg = "goal_r_";
if ( parts[2].startsWith("r") // Referee;
&& Settings.PLAY_MODES.contains(nMsg) ) // Play Mode?
{
playMode = nMsg;
this.isPositioned = false;
}
else
hearMessages.add( nMsg );
}
}
// Handle `see` messages
else if (message.startsWith("(see")) {
this.timeLastSee = timeReceived;
this.time = Futil.extractTime(message);
Log.d("Received `see` message at time step " + this.time);
LinkedList<String> infos = Futil.extractInfos(message);
lastSeenOpponents.clear();
for (String info : infos) {
String id = Futil.extractId(info);
if (Futil.isUniqueFieldObject(id)) {
FieldObject obj = this.getOrCreate(id);
obj.update(this.player, info, this.time);
this.fieldObjects.put(id, obj);
if ( id.startsWith("(p \"") && !( id.startsWith(this.player.team.name, 4) ) )
lastSeenOpponents.add( (Player)obj );
}
}
// Immediately run for the current step. Since our computations takes only a few
// milliseconds, it's okay to start running over half-way into the 100ms cycle.
// That means two out of every three time steps will be executed here.
this.run();
// Make sure we stay in sync with the mid-way `see`s
if (this.timeLastSee - this.timeLastSenseBody > 30) {
this.responseHistory.clear();
this.responseHistory.add(Settings.RESPONSE.SEE);
this.responseHistory.add(Settings.RESPONSE.SEE);
}
else {
this.responseHistory.add(Settings.RESPONSE.SEE);
this.responseHistory.removeLast();
}
}
// Handle init messages
else if (message.startsWith("(init")) {
String[] parts = message.split("\\s");
char teamSide = message.charAt(6);
if (teamSide == Settings.LEFT_SIDE) {
player.team.side = Settings.LEFT_SIDE;
player.otherTeam.side = Settings.RIGHT_SIDE;
}
else if (teamSide == Settings.RIGHT_SIDE) {
player.team.side = Settings.RIGHT_SIDE;
player.otherTeam.side = Settings.LEFT_SIDE;
}
else {
// Raise error
Log.e("Could not parse teamSide.");
}
player.number = Integer.parseInt(parts[2]);
this.role = Settings.PLAYER_ROLES[this.player.number - 1];
playMode = parts[3].split("\\)")[0];
}
else if (message.startsWith("(server_param")) {
parseServerParameters(message);
}
}
/**
* Parses the initial parameters received from the server.
*
* @param message the parameters message received from the server
*/
public void parseServerParameters(String message)
{
String parts[] = message.split("\\(");
for ( String i : parts ) // for each structured argument:
{
// Clean the string, and break it down into the base arguments.
String nMsg = i.split("\\)")[0].trim();
if ( nMsg.isEmpty() ) continue;
String nArgs[] = nMsg.split("\\s");
// Check for specific argument types; ignore unknown arguments.
if (nArgs[0].startsWith("dash_power_rate"))
Settings.setDashPowerRate(Double.parseDouble(nArgs[1]));
if ( nArgs[0].startsWith("goal_width") )
Settings.setGoalHeight(Double.parseDouble(nArgs[1]));
// Ball arguments:
else if ( nArgs[0].startsWith("ball") )
ServerParams_Ball.Builder.dataParser(nArgs);
// Player arguments:
else if ( nArgs[0].startsWith("player") || nArgs[0].startsWith("min")
|| nArgs[0].startsWith("max") )
ServerParams_Player.Builder.dataParser(nArgs);
}
// Rebuild all parameter objects with updated parameters.
Settings.rebuildParams();
}
/**
* Responds for the current time step.
*/
public void run() {
final long startTime = System.currentTimeMillis();
final long endTime;
int expectedNextRun = this.lastRan + 1;
if (this.time > expectedNextRun) {
Log.e("Brain did not run during time step " + expectedNextRun + ".");
}
this.lastRan = this.time;
this.acceleration.reset();
this.updatePositionAndDirection();
this.currentStrategy = this.determineOptimalStrategy();
Log.i("Current strategy: " + this.currentStrategy);
this.executeStrategy(this.currentStrategy);
Log.d("Estimated player position: " + this.player.position.render(this.time) + ".");
Log.d("Estimated player direction: " + this.player.direction.render(this.time) + ".");
endTime = System.currentTimeMillis();
final long duration = endTime - startTime;
Log.d("Took " + duration + " ms (plus small overhead) to run at time " + this.time + ".");
if (duration > 35) {
Log.e("Took " + duration + " ms (plus small overhead) to run at time " + this.time + ".");
}
}
/**
* Adds the given angle to the player's current direction.
*
* @param offset an angle in degrees to add to the player's current direction
*/
public final void turn(double offset) {
double moment = Futil.toValidMoment(offset);
client.sendCommand(Settings.Commands.TURN, moment);
// TODO Potentially take magnitude of offset into account in the
// determination of the new confidence in the player's position.
player.direction.update(player.direction.getDirection() + moment, 0.95 * player.direction.getConfidence(this.time), this.time);
}
/**
* Updates the player's current direction to be the given direction.
*
* @param direction angle in degrees, assuming soccer server coordinate system
*/
public final void turnTo(double direction) {
this.turn(this.player.relativeAngleTo(direction));
}
/**
* Send commands to move the player to a point at maximum power
* @param point the point to move to
*/
private final void moveTowards(Point point){
moveTowards(point, 100d);
}
/**
* Send commands to move the player to a point with the given power
* @param point to move towards
* @param power to move at
*/
private final void moveTowards(Point point, double power){
final double x = player.position.getX() - point.getX();
final double y = player.position.getY() - point.getY();
final double theta = Math.toDegrees(Math.atan2(y, x));
turnTo(theta);
dash(power);
}
/**
* Updates this this brain's belief about the associated player's position and direction
* at the current time step.
*/
private final void updatePositionAndDirection() {
// Infer from the most-recent `see` if it happened in the current time-step
for (int i = 0; i < 4; i++) {
LinkedList<FieldObject> flagsOnSide = new LinkedList<FieldObject>();
for (String id : Settings.BOUNDARY_FLAG_GROUPS[i]) {
FieldObject flag = this.fieldObjects.get(id);
if (flag.curInfo.time == this.time) {
flagsOnSide.add(flag);
}
else {
//Log.i("Flag " + id + "last updated at time " + flag.info.time + ", not " + this.time);
}
if (flagsOnSide.size() > 1) {
this.inferPositionAndDirection(flagsOnSide.poll(), flagsOnSide.poll());
return;
}
}
}
// TODO Handle other cases
Log.e("Did not update position or direction at time " + this.time);
}
/**
* @return {@link Settings#PENALTY_AREA_LEFT} if player is on the left team, or {@link Settings#PENALTY_AREA_RIGHT} if on the right team.
*/
final public Rectangle getMyPeneltyArea(){
if(player.team == null) throw new NullPointerException("Player team not initialized while getting penelty area.");
return player.team.side == 'l' ? Settings.PENALTY_AREA_LEFT : Settings.PENALTY_AREA_RIGHT;
}
/**
* Returns this player's x velocity. Shortcut function.
*
* @return this player's x velocity
*/
private final double velX() {
return this.velocity.getX();
}
/**
* Returns this player's y velocity. Shortcut function.
*
* @return this player's y velocity
*/
private final double velY() {
return this.velocity.getY();
}
/**
* Returns this player's x.
*
* @return this player's x-coordinate
*/
private final double x() {
return this.player.position.getPosition().getX();
}
/**
* Returns this player's y.
*
* @return this player's y coordinate
*/
private final double y() {
return this.player.position.getPosition().getY();
}
}
| merging changes
| src/futility/Brain.java | merging changes |
|
Java | agpl-3.0 | fa68f8b2d5aa86ca9ea5bfe4a59715961c4cccfd | 0 | mbrossard/cryptonit-applet | package org.cryptonit;
/**
* @author Mathias Brossard
*/
import javacard.framework.APDU;
import javacard.framework.Applet;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import javacard.framework.JCSystem;
import javacard.framework.OwnerPIN;
import javacard.framework.Util;
import javacard.security.CryptoException;
import javacard.security.Key;
import javacard.security.KeyBuilder;
import javacard.security.KeyPair;
import javacard.security.RSAPublicKey;
import javacardx.apdu.ExtendedLength;
import javacardx.crypto.Cipher;
public class CryptonitApplet extends Applet implements ExtendedLength {
private final OwnerPIN pin;
private final FileIndex index;
private Key[] keys = null;
private boolean[] authenticated = null;
private Cipher rsa_cipher = null;
private IOBuffer io = null;
private final static byte PIN_MAX_LENGTH = 8;
private final static byte PIN_MAX_TRIES = 5;
public static final byte INS_GET_DATA = (byte) 0xCB;
public static final byte INS_GET_RESPONSE = (byte) 0xC0;
public static final byte INS_PUT_DATA = (byte) 0xDB;
public static final byte INS_VERIFY_PIN = (byte) 0x20;
public static final byte INS_GENERAL_AUTHENTICATE = (byte) 0x87;
public static final byte INS_CHANGE_REFERENCE_DATA = (byte) 0x24;
public static final byte INS_GENERATE_ASYMMETRIC_KEYPAIR = (byte) 0x47;
public static final short SW_PIN_TRIES_REMAINING = 0x63C0;
public static final short SW_AUTHENTICATION_METHOD_BLOCKED = 0x6983;
protected CryptonitApplet(byte[] bArray, short bOffset, byte bLength) {
pin = new OwnerPIN(PIN_MAX_TRIES, PIN_MAX_LENGTH);
pin.update(new byte[]{
0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38
}, (short) 0, (byte) 8);
index = new FileIndex();
keys = new Key[(byte) 4];
authenticated = JCSystem.makeTransientBooleanArray((short) 1, JCSystem.CLEAR_ON_DESELECT);
rsa_cipher = Cipher.getInstance(Cipher.ALG_RSA_NOPAD, false);
io = new IOBuffer(index);
register();
}
public static void install(byte[] bArray, short bOffset, byte bLength) {
new CryptonitApplet(bArray, bOffset, bLength);
}
@Override
public void process(APDU apdu) {
byte buffer[] = apdu.getBuffer();
byte ins = buffer[ISO7816.OFFSET_INS];
if (apdu.isSecureMessagingCLA()) {
ISOException.throwIt(ISO7816.SW_SECURE_MESSAGING_NOT_SUPPORTED);
}
switch (ins) {
case ISO7816.INS_SELECT:
doSelect(apdu);
break;
case INS_VERIFY_PIN:
doVerifyPin(apdu);
break;
case INS_CHANGE_REFERENCE_DATA:
doChangePIN(apdu);
break;
case INS_GET_DATA:
doGetData(apdu);
break;
case INS_GET_RESPONSE:
io.getResponse(apdu);
break;
case INS_PUT_DATA:
doPutData(apdu);
break;
case INS_GENERATE_ASYMMETRIC_KEYPAIR:
doGenerateKeyPair(apdu);
break;
case INS_GENERAL_AUTHENTICATE:
doPrivateKeyOperation(apdu);
break;
default:
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
}
}
private void doSelect(APDU apdu) throws ISOException {
byte[] buf = apdu.getBuffer();
byte p1 = buf[ISO7816.OFFSET_P1];
byte p2 = buf[ISO7816.OFFSET_P2];
if((p1 == (byte) 0x04) && (p2 == (byte) 0x00)) {
final byte [] apt = {
/* Application property template */
(byte) 0x61, (byte) 0x11,
/* - Application identifier of application */
(byte) 0x4F, (byte) 0x06,
(byte) 0x00, (byte) 0x00, (byte) 0x10, (byte) 0x00, (byte) 0x01,
(byte) 0x00,
/* - Coexistent tag allocation authority */
(byte) 0x79, (byte) 0x07,
/* - Application identifier */
(byte) 0x4F, (byte) 0x05,
(byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08
};
io.sendBuffer(apt, (short) apt.length, apdu);
return;
}
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
}
private void doVerifyPin(APDU apdu) throws ISOException {
byte[] buf = apdu.getBuffer();
byte p1 = buf[ISO7816.OFFSET_P1];
byte p2 = buf[ISO7816.OFFSET_P2];
short offset, lc = apdu.setIncomingAndReceive();
if ((p1 != (byte) 0x00 && p1 != (byte) 0xFF) || (p2 != (byte) 0x80)) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}
if (p1 == (byte) 0xFF) {
authenticated[0] = false;
ISOException.throwIt(ISO7816.SW_NO_ERROR);
}
if ((lc != apdu.getIncomingLength()) || lc != (short) 8) {
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
}
offset = apdu.getOffsetCdata();
if (pin.getTriesRemaining() == 0) {
ISOException.throwIt(SW_AUTHENTICATION_METHOD_BLOCKED);
}
if (!pin.check(buf, offset, (byte) lc)) {
authenticated[0] = false;
ISOException.throwIt((short) (SW_PIN_TRIES_REMAINING | pin.getTriesRemaining()));
} else {
authenticated[0] = true;
ISOException.throwIt(ISO7816.SW_NO_ERROR);
}
}
private void doChangePIN(APDU apdu) {
}
private void doGetData(APDU apdu) throws ISOException {
byte[] buf = apdu.getBuffer();
byte p1 = buf[ISO7816.OFFSET_P1];
byte p2 = buf[ISO7816.OFFSET_P2];
short lc = apdu.setIncomingAndReceive();
short offset = apdu.getOffsetCdata();
if (p1 != (byte) 0x3F || p2 != (byte) 0xFF) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}
if (lc != apdu.getIncomingLength()) {
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
}
if (buf[offset] != (byte) 0x5C) {
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
}
switch (buf[(short) (offset + 1)]) {
case 0x1:
if (buf[(short) (offset + 2)] == (byte) 0x7E) {
io.sendFile(FileIndex.DISCOVERY, apdu, (short) 0);
return;
}
break;
case 0x3:
if ((buf[(short) (offset + 2)] != (byte) 0x5F)
|| (buf[(short) (offset + 3)] != (byte) 0xC1)
|| (buf[(short) (offset + 4)] == (byte) 0x4)
|| (buf[(short) (offset + 4)] > (byte) 0xA)) {
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
}
byte id = (byte) (buf[(byte) (offset + 4)] - 1);
if (((id == (byte) 0x2) || (id == (byte) 0x7)
|| (id == (byte) 0x8)) && authenticated[0] == false) {
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
}
io.sendFile(id, apdu, (short) 0);
return;
default:
}
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
}
private void doPutData(APDU apdu) throws ISOException {
byte[] buf = apdu.getBuffer();
byte p1 = buf[ISO7816.OFFSET_P1];
byte p2 = buf[ISO7816.OFFSET_P2];
short lc = apdu.setIncomingAndReceive();
short offset = apdu.getOffsetCdata();
if (p1 != (byte) 0x3F || p2 != (byte) 0xFF) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}
if (authenticated[0] == false) {
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
}
if (lc != apdu.getIncomingLength() || lc < (byte) 0x06) {
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
}
if (buf[offset] != (byte) 0x5C) {
ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED);
}
if ((buf[(short) (offset + 1)] != (byte) 0x03)
|| (buf[(short) (offset + 2)] != (byte) 0x5F)
|| (buf[(short) (offset + 3)] != (byte) 0xC1)) {
ISOException.throwIt(ISO7816.SW_DATA_INVALID);
}
byte id = (byte) (buf[(short) (offset + 4)] - 1);
if ((id == (byte) 0x03)
|| (id > (byte) 0x0A)) {
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
}
if (buf[(short) (offset + 5)] != (byte) 0x53) {
ISOException.throwIt(ISO7816.SW_DATA_INVALID);
}
offset += 6;
short l = (short) buf[offset];
if ((buf[offset] & (byte) 0x80) == 0) {
offset += 1;
} else if (buf[offset] == (byte) 0x81) {
l = (short) (buf[(short) (offset + 1)]);
offset += 2;
} else if (buf[offset] == (byte) 0x82) {
l = Util.getShort(buf, (short) (offset + 1));
offset += 3;
} else {
ISOException.throwIt(ISO7816.SW_UNKNOWN);
}
if ((short) (l - offset + apdu.getOffsetCdata()) > lc) {
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
}
index.entries[id].content = new byte[l];
Util.arrayCopy(buf, offset, index.entries[id].content, (short) 0, l);
}
private byte keyMapping(byte keyRef) {
switch (keyRef) {
case (byte) 0x9A:
return 0;
case (byte) 0x9C:
return 1;
case (byte) 0x9D:
return 2;
case (byte) 0x9E:
return 3;
default:
return (byte) 0xFF;
}
}
private void doGenerateKeyPair(APDU apdu) throws ISOException {
byte[] buf = apdu.getBuffer();
byte p1 = buf[ISO7816.OFFSET_P1];
byte p2 = buf[ISO7816.OFFSET_P2];
short lc = apdu.setIncomingAndReceive();
short offset = apdu.getOffsetCdata();
if ((p1 != (byte) 0x00) || (keyMapping(p2) == (byte) 0xFF)) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}
byte[] prefix = new byte[]{
(byte) 0xAC, (byte) 0x03, (byte) 0x80, (byte) 0x01
};
if (Util.arrayCompare(buf, offset, prefix,
(byte) 0, (byte) prefix.length) != 0) {
ISOException.throwIt(ISO7816.SW_WRONG_DATA);
}
switch (buf[(short) (offset + 4)]) {
case 0x07:
doGenRSA(apdu, buf[ISO7816.OFFSET_P2]);
break;
case 0x11:
case 0x14:
default:
ISOException.throwIt(ISO7816.SW_WRONG_DATA);
}
}
private void sendRSAPublicKey(APDU apdu, RSAPublicKey key) {
short off = 0;
byte[] buf = new byte[271];
byte[] header = new byte[]{
(byte) 0x7F, (byte) 0x49, (byte) 0x82, (byte) 0x01, (byte) 0x09,
(byte) 0x81, (byte) 0x82, (byte) 0x01, (byte) 0x00
};
Util.arrayCopy(header, (short) 0, buf, (short) 0, (short) header.length);
off += header.length;
short l = key.getModulus(buf, off);
if (l > 0x0100) {
buf[(short) 0x04] = (byte) (l - 0x0100 + 9);
buf[(short) 0x08] = (byte) (l - 0x0100);
}
off += l;
buf[off++] = (byte) 0x82;
buf[off++] = (byte) 0x03;
off += key.getExponent(buf, off);
io.sendBuffer(buf, off, apdu);
}
void doGenRSA(APDU apdu, byte keyRef) {
KeyPair kp = null;
byte id = keyMapping(keyRef);
try {
kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_2048);
} catch (CryptoException e) {
if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM) {
ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED);
}
ISOException.throwIt(ISO7816.SW_UNKNOWN);
}
if (kp != null) {
kp.genKeyPair();
if (keys[id] != null) {
keys[id].clearKey();
}
keys[id] = kp.getPrivate();
sendRSAPublicKey(apdu, (RSAPublicKey) kp.getPublic());
}
}
public static short decodeLength(byte[] buf, short offset) {
byte b = buf[offset];
short s = buf[offset];
if ((b & (byte) 0x80) != 0) {
offset += 1;
if (b == (byte) 0x81) {
s = (short) (0x00FF & buf[offset]);
} else if (b == (byte) 0x82) {
s = Util.getShort(buf, offset);
} else {
ISOException.throwIt(ISO7816.SW_UNKNOWN);
}
}
return s;
}
public static short lengthLength(short l) {
return (short) ((l < 128) ? 1 : ((l < 256) ? 2 : 3));
}
public static short getTag(byte[] buf, short off, short length, byte tag) {
short end = (short) (off + length - 1);
while ((off < end) && (buf[off] != tag)) {
short l = decodeLength(buf, (short) (off + 1));
off += lengthLength(l) + l + 1;
}
return off;
}
private void doPrivateKeyOperation(APDU apdu) throws ISOException {
byte[] buf = apdu.getBuffer();
byte p1 = buf[ISO7816.OFFSET_P1];
byte p2 = buf[ISO7816.OFFSET_P2];
short lc = apdu.setIncomingAndReceive();
short offset = apdu.getOffsetCdata();
short id = keyMapping(p2);
if (keys[id] == null) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}
if (keys[id].getType() == KeyBuilder.TYPE_RSA_CRT_PRIVATE
|| keys[id].getType() == KeyBuilder.TYPE_RSA_PRIVATE) {
// Add checks
}
short cur = offset;
if (buf[cur++] != (byte) 0x7C) {
ISOException.throwIt(ISO7816.SW_DATA_INVALID);
}
cur += lengthLength(decodeLength(buf, cur));
short m = getTag(buf, cur, lc, (byte) 0x81);
if (m < lc && buf[m] == (byte) 0x81) {
short k = decodeLength(buf, (short) (m + 1));
m += lengthLength(k) + 1;
byte[] signature = null;
short l = 0;
if (keys[id].getType() == KeyBuilder.TYPE_RSA_CRT_PRIVATE) {
if (k != 256) {
ISOException.throwIt(ISO7816.SW_DATA_INVALID);
}
l = (short) 264;
signature = new byte[l];
Util.arrayCopy(new byte[]{
(byte) 0x7C, (byte) 0x82, (byte) 0x01, (byte) 0x04,
(byte) 0x82, (byte) 0x82, (byte) 0x01, (byte) 0x00
}, (short) 0, signature, (short) 0, (short) 8);
rsa_cipher.init(keys[id], Cipher.MODE_DECRYPT);
try {
k = rsa_cipher.doFinal(buf, m, k, signature, (short) 8);
} catch (CryptoException e) {
if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM) {
ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED);
}
ISOException.throwIt(ISO7816.SW_UNKNOWN);
}
}
io.sendBuffer(signature, l, apdu);
return;
}
}
}
| src/org/cryptonit/CryptonitApplet.java | package org.cryptonit;
/**
* @author Mathias Brossard
*/
import javacard.framework.APDU;
import javacard.framework.Applet;
import javacard.framework.ISO7816;
import javacard.framework.ISOException;
import javacard.framework.JCSystem;
import javacard.framework.OwnerPIN;
import javacard.framework.Util;
import javacard.security.CryptoException;
import javacard.security.Key;
import javacard.security.KeyBuilder;
import javacard.security.KeyPair;
import javacard.security.RSAPublicKey;
import javacardx.apdu.ExtendedLength;
import javacardx.crypto.Cipher;
public class CryptonitApplet extends Applet implements ExtendedLength {
private final OwnerPIN pin;
private final FileIndex index;
private Key[] keys = null;
private boolean[] authenticated = null;
private Cipher rsa_cipher = null;
private IOBuffer io = null;
private final static byte PIN_MAX_LENGTH = 8;
private final static byte PIN_MAX_TRIES = 5;
public static final byte INS_GET_DATA = (byte) 0xCB;
public static final byte INS_GET_RESPONSE = (byte) 0xC0;
public static final byte INS_PUT_DATA = (byte) 0xDB;
public static final byte INS_VERIFY_PIN = (byte) 0x20;
public static final byte INS_GENERAL_AUTHENTICATE = (byte) 0x87;
public static final byte INS_GENERATE_ASYMMETRIC_KEYPAIR = (byte) 0x47;
public static final short SW_PIN_TRIES_REMAINING = 0x63C0;
public static final short SW_AUTHENTICATION_METHOD_BLOCKED = 0x6983;
protected CryptonitApplet(byte[] bArray, short bOffset, byte bLength) {
pin = new OwnerPIN(PIN_MAX_TRIES, PIN_MAX_LENGTH);
pin.update(new byte[]{
0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38
}, (short) 0, (byte) 8);
index = new FileIndex();
keys = new Key[(byte) 4];
authenticated = JCSystem.makeTransientBooleanArray((short) 1, JCSystem.CLEAR_ON_DESELECT);
rsa_cipher = Cipher.getInstance(Cipher.ALG_RSA_NOPAD, false);
io = new IOBuffer(index);
register();
}
public static void install(byte[] bArray, short bOffset, byte bLength) {
new CryptonitApplet(bArray, bOffset, bLength);
}
@Override
public void process(APDU apdu) {
byte buffer[] = apdu.getBuffer();
byte ins = buffer[ISO7816.OFFSET_INS];
if (apdu.isSecureMessagingCLA()) {
ISOException.throwIt(ISO7816.SW_SECURE_MESSAGING_NOT_SUPPORTED);
}
switch (ins) {
case ISO7816.INS_SELECT:
doSelect(apdu);
break;
case INS_VERIFY_PIN:
doVerifyPin(apdu);
break;
case INS_GET_DATA:
doGetData(apdu);
break;
case INS_GET_RESPONSE:
io.getResponse(apdu);
break;
case INS_PUT_DATA:
doPutData(apdu);
break;
case INS_GENERATE_ASYMMETRIC_KEYPAIR:
doGenerateKeyPair(apdu);
break;
case INS_GENERAL_AUTHENTICATE:
doPrivateKeyOperation(apdu);
break;
default:
ISOException.throwIt(ISO7816.SW_INS_NOT_SUPPORTED);
}
}
private void doSelect(APDU apdu) throws ISOException {
byte[] buf = apdu.getBuffer();
byte p1 = buf[ISO7816.OFFSET_P1];
byte p2 = buf[ISO7816.OFFSET_P2];
if((p1 == (byte) 0x04) && (p2 == (byte) 0x00)) {
final byte [] apt = {
/* Application property template */
(byte) 0x61, (byte) 0x11,
/* - Application identifier of application */
(byte) 0x4F, (byte) 0x06,
(byte) 0x00, (byte) 0x00, (byte) 0x10, (byte) 0x00, (byte) 0x01,
(byte) 0x00,
/* - Coexistent tag allocation authority */
(byte) 0x79, (byte) 0x07,
/* - Application identifier */
(byte) 0x4F, (byte) 0x05,
(byte) 0xA0, (byte) 0x00, (byte) 0x00, (byte) 0x03, (byte) 0x08
};
io.sendBuffer(apt, (short) apt.length, apdu);
return;
}
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
}
private void doVerifyPin(APDU apdu) throws ISOException {
byte[] buf = apdu.getBuffer();
byte p1 = buf[ISO7816.OFFSET_P1];
byte p2 = buf[ISO7816.OFFSET_P2];
short offset, lc = apdu.setIncomingAndReceive();
if ((p1 != (byte) 0x00 && p1 != (byte) 0xFF) || (p2 != (byte) 0x80)) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}
if (p1 == (byte) 0xFF) {
authenticated[0] = false;
ISOException.throwIt(ISO7816.SW_NO_ERROR);
}
if ((lc != apdu.getIncomingLength()) || lc != (short) 8) {
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
}
offset = apdu.getOffsetCdata();
if (pin.getTriesRemaining() == 0) {
ISOException.throwIt(SW_AUTHENTICATION_METHOD_BLOCKED);
}
if (!pin.check(buf, offset, (byte) lc)) {
authenticated[0] = false;
ISOException.throwIt((short) (SW_PIN_TRIES_REMAINING | pin.getTriesRemaining()));
} else {
authenticated[0] = true;
ISOException.throwIt(ISO7816.SW_NO_ERROR);
}
}
private void doGetData(APDU apdu) throws ISOException {
byte[] buf = apdu.getBuffer();
byte p1 = buf[ISO7816.OFFSET_P1];
byte p2 = buf[ISO7816.OFFSET_P2];
short lc = apdu.setIncomingAndReceive();
short offset = apdu.getOffsetCdata();
if (p1 != (byte) 0x3F || p2 != (byte) 0xFF) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}
if (lc != apdu.getIncomingLength()) {
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
}
if (buf[offset] != (byte) 0x5C) {
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
}
switch (buf[(short) (offset + 1)]) {
case 0x1:
if (buf[(short) (offset + 2)] == (byte) 0x7E) {
io.sendFile(FileIndex.DISCOVERY, apdu, (short) 0);
return;
}
break;
case 0x3:
if ((buf[(short) (offset + 2)] != (byte) 0x5F)
|| (buf[(short) (offset + 3)] != (byte) 0xC1)
|| (buf[(short) (offset + 4)] == (byte) 0x4)
|| (buf[(short) (offset + 4)] > (byte) 0xA)) {
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
}
byte id = (byte) (buf[(byte) (offset + 4)] - 1);
if (((id == (byte) 0x2) || (id == (byte) 0x7)
|| (id == (byte) 0x8)) && authenticated[0] == false) {
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
}
io.sendFile(id, apdu, (short) 0);
return;
default:
}
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
}
private void doPutData(APDU apdu) throws ISOException {
byte[] buf = apdu.getBuffer();
byte p1 = buf[ISO7816.OFFSET_P1];
byte p2 = buf[ISO7816.OFFSET_P2];
short lc = apdu.setIncomingAndReceive();
short offset = apdu.getOffsetCdata();
if (p1 != (byte) 0x3F || p2 != (byte) 0xFF) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}
if (authenticated[0] == false) {
ISOException.throwIt(ISO7816.SW_SECURITY_STATUS_NOT_SATISFIED);
}
if (lc != apdu.getIncomingLength() || lc < (byte) 0x06) {
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
}
if (buf[offset] != (byte) 0x5C) {
ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED);
}
if ((buf[(short) (offset + 1)] != (byte) 0x03)
|| (buf[(short) (offset + 2)] != (byte) 0x5F)
|| (buf[(short) (offset + 3)] != (byte) 0xC1)) {
ISOException.throwIt(ISO7816.SW_DATA_INVALID);
}
byte id = (byte) (buf[(short) (offset + 4)] - 1);
if ((id == (byte) 0x03)
|| (id > (byte) 0x0A)) {
ISOException.throwIt(ISO7816.SW_FILE_NOT_FOUND);
}
if (buf[(short) (offset + 5)] != (byte) 0x53) {
ISOException.throwIt(ISO7816.SW_DATA_INVALID);
}
offset += 6;
short l = (short) buf[offset];
if ((buf[offset] & (byte) 0x80) == 0) {
offset += 1;
} else if (buf[offset] == (byte) 0x81) {
l = (short) (buf[(short) (offset + 1)]);
offset += 2;
} else if (buf[offset] == (byte) 0x82) {
l = Util.getShort(buf, (short) (offset + 1));
offset += 3;
} else {
ISOException.throwIt(ISO7816.SW_UNKNOWN);
}
if ((short) (l - offset + apdu.getOffsetCdata()) > lc) {
ISOException.throwIt(ISO7816.SW_WRONG_LENGTH);
}
index.entries[id].content = new byte[l];
Util.arrayCopy(buf, offset, index.entries[id].content, (short) 0, l);
}
private byte keyMapping(byte keyRef) {
switch (keyRef) {
case (byte) 0x9A:
return 0;
case (byte) 0x9C:
return 1;
case (byte) 0x9D:
return 2;
case (byte) 0x9E:
return 3;
default:
return (byte) 0xFF;
}
}
private void doGenerateKeyPair(APDU apdu) throws ISOException {
byte[] buf = apdu.getBuffer();
byte p1 = buf[ISO7816.OFFSET_P1];
byte p2 = buf[ISO7816.OFFSET_P2];
short lc = apdu.setIncomingAndReceive();
short offset = apdu.getOffsetCdata();
if ((p1 != (byte) 0x00) || (keyMapping(p2) == (byte) 0xFF)) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}
byte[] prefix = new byte[]{
(byte) 0xAC, (byte) 0x03, (byte) 0x80, (byte) 0x01
};
if (Util.arrayCompare(buf, offset, prefix,
(byte) 0, (byte) prefix.length) != 0) {
ISOException.throwIt(ISO7816.SW_WRONG_DATA);
}
switch (buf[(short) (offset + 4)]) {
case 0x07:
doGenRSA(apdu, buf[ISO7816.OFFSET_P2]);
break;
case 0x11:
case 0x14:
default:
ISOException.throwIt(ISO7816.SW_WRONG_DATA);
}
}
private void sendRSAPublicKey(APDU apdu, RSAPublicKey key) {
short off = 0;
byte[] buf = new byte[271];
byte[] header = new byte[]{
(byte) 0x7F, (byte) 0x49, (byte) 0x82, (byte) 0x01, (byte) 0x09,
(byte) 0x81, (byte) 0x82, (byte) 0x01, (byte) 0x00
};
Util.arrayCopy(header, (short) 0, buf, (short) 0, (short) header.length);
off += header.length;
short l = key.getModulus(buf, off);
if (l > 0x0100) {
buf[(short) 0x04] = (byte) (l - 0x0100 + 9);
buf[(short) 0x08] = (byte) (l - 0x0100);
}
off += l;
buf[off++] = (byte) 0x82;
buf[off++] = (byte) 0x03;
off += key.getExponent(buf, off);
io.sendBuffer(buf, off, apdu);
}
void doGenRSA(APDU apdu, byte keyRef) {
KeyPair kp = null;
byte id = keyMapping(keyRef);
try {
kp = new KeyPair(KeyPair.ALG_RSA_CRT, KeyBuilder.LENGTH_RSA_2048);
} catch (CryptoException e) {
if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM) {
ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED);
}
ISOException.throwIt(ISO7816.SW_UNKNOWN);
}
if (kp != null) {
kp.genKeyPair();
if (keys[id] != null) {
keys[id].clearKey();
}
keys[id] = kp.getPrivate();
sendRSAPublicKey(apdu, (RSAPublicKey) kp.getPublic());
}
}
public static short decodeLength(byte[] buf, short offset) {
byte b = buf[offset];
short s = buf[offset];
if ((b & (byte) 0x80) != 0) {
offset += 1;
if (b == (byte) 0x81) {
s = (short) (0x00FF & buf[offset]);
} else if (b == (byte) 0x82) {
s = Util.getShort(buf, offset);
} else {
ISOException.throwIt(ISO7816.SW_UNKNOWN);
}
}
return s;
}
public static short lengthLength(short l) {
return (short) ((l < 128) ? 1 : ((l < 256) ? 2 : 3));
}
public static short getTag(byte[] buf, short off, short length, byte tag) {
short end = (short) (off + length - 1);
while ((off < end) && (buf[off] != tag)) {
short l = decodeLength(buf, (short) (off + 1));
off += lengthLength(l) + l + 1;
}
return off;
}
private void doPrivateKeyOperation(APDU apdu) throws ISOException {
byte[] buf = apdu.getBuffer();
byte p1 = buf[ISO7816.OFFSET_P1];
byte p2 = buf[ISO7816.OFFSET_P2];
short lc = apdu.setIncomingAndReceive();
short offset = apdu.getOffsetCdata();
short id = keyMapping(p2);
if (keys[id] == null) {
ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
}
if (keys[id].getType() == KeyBuilder.TYPE_RSA_CRT_PRIVATE
|| keys[id].getType() == KeyBuilder.TYPE_RSA_PRIVATE) {
// Add checks
}
short cur = offset;
if (buf[cur++] != (byte) 0x7C) {
ISOException.throwIt(ISO7816.SW_DATA_INVALID);
}
cur += lengthLength(decodeLength(buf, cur));
short m = getTag(buf, cur, lc, (byte) 0x81);
if (m < lc && buf[m] == (byte) 0x81) {
short k = decodeLength(buf, (short) (m + 1));
m += lengthLength(k) + 1;
byte[] signature = null;
short l = 0;
if (keys[id].getType() == KeyBuilder.TYPE_RSA_CRT_PRIVATE) {
if (k != 256) {
ISOException.throwIt(ISO7816.SW_DATA_INVALID);
}
l = (short) 264;
signature = new byte[l];
Util.arrayCopy(new byte[]{
(byte) 0x7C, (byte) 0x82, (byte) 0x01, (byte) 0x04,
(byte) 0x82, (byte) 0x82, (byte) 0x01, (byte) 0x00
}, (short) 0, signature, (short) 0, (short) 8);
rsa_cipher.init(keys[id], Cipher.MODE_DECRYPT);
try {
k = rsa_cipher.doFinal(buf, m, k, signature, (short) 8);
} catch (CryptoException e) {
if (e.getReason() == CryptoException.NO_SUCH_ALGORITHM) {
ISOException.throwIt(ISO7816.SW_FUNC_NOT_SUPPORTED);
}
ISOException.throwIt(ISO7816.SW_UNKNOWN);
}
}
io.sendBuffer(signature, l, apdu);
return;
}
}
}
| Starting on PIN change function
| src/org/cryptonit/CryptonitApplet.java | Starting on PIN change function |
|
Java | agpl-3.0 | e6f6f2f498a6573084515c77037315c14c797e50 | 0 | VietOpenCPS/opencps-v2,VietOpenCPS/opencps-v2 | package org.opencps.dossiermgt.action.util;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.opencps.dossiermgt.model.Dossier;
import org.opencps.dossiermgt.model.DossierFile;
import org.opencps.dossiermgt.model.Registration;
import org.opencps.dossiermgt.service.DossierFileLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierLocalServiceUtil;
import org.opencps.dossiermgt.service.RegistrationLocalServiceUtil;
import org.opencps.dossiermgt.service.comparator.DossierFileComparator;
import org.opencps.usermgt.action.ApplicantActions;
import org.opencps.usermgt.action.impl.ApplicantActionsImpl;
import org.opencps.usermgt.model.Employee;
import org.opencps.usermgt.service.EmployeeLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
public class AutoFillFormData {
public static String sampleDataBinding(String sampleData, long dossierId, ServiceContext serviceContext) {
// TODO Auto-generated method stub
JSONObject result = JSONFactoryUtil.createJSONObject();
try {
Dossier dossier = DossierLocalServiceUtil.fetchDossier(dossierId);
result = JSONFactoryUtil.createJSONObject(sampleData);
String _subjectName = StringPool.BLANK;
String _subjectId = StringPool.BLANK;
String _address = StringPool.BLANK;
String _cityCode = StringPool.BLANK;
String _cityName = StringPool.BLANK;
String _districtCode = StringPool.BLANK;
String _districtName = StringPool.BLANK;
String _wardCode = StringPool.BLANK;
String _wardName = StringPool.BLANK;
String _contactName = StringPool.BLANK;
String _contactTelNo = StringPool.BLANK;
String _contactEmail = StringPool.BLANK;
// TODO
String _dossierFileNo = StringPool.BLANK;
String _dossierFileDate = StringPool.BLANK;
String _receiveDate = StringPool.BLANK;
String _dossierNo = StringPool.BLANK;
String _employee_employeeNo = StringPool.BLANK;
String _employee_fullName = StringPool.BLANK;
String _employee_title = StringPool.BLANK;
String _applicantName = StringPool.BLANK;
String _applicantIdType = StringPool.BLANK;
String _applicantIdNo = StringPool.BLANK;
String _applicantIdDate = StringPool.BLANK;
String _curDate = StringPool.BLANK;
SimpleDateFormat sfd = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
_curDate = sfd.format(new Date());
if (Validator.isNotNull(dossier)) {
_receiveDate = Validator.isNotNull(dossier.getReceiveDate())?dossier.getReceiveDate().toGMTString():StringPool.BLANK;
_dossierNo = dossier.getDossierNo();
}
// get data applicant or employee
ApplicantActions applicantActions = new ApplicantActionsImpl();
try {
Registration registration = RegistrationLocalServiceUtil.getLastSubmittingByUser(dossier.getGroupId(), serviceContext.getUserId(), true);
if (Validator.isNotNull(registration)) {
JSONObject applicantJSON = JSONFactoryUtil.createJSONObject(JSONFactoryUtil.looseSerialize(registration));
_subjectName = applicantJSON.getString("applicantName");
_subjectId = applicantJSON.getString("applicantId");
_address = applicantJSON.getString("address");
_cityCode = applicantJSON.getString("cityCode");
_cityName = applicantJSON.getString("cityName");
_districtCode = applicantJSON.getString("districtCode");
_districtName = applicantJSON.getString("districtName");
_wardCode = applicantJSON.getString("wardCode");
_wardName = applicantJSON.getString("wardName");
_contactName = applicantJSON.getString("contactName");
_contactTelNo = applicantJSON.getString("contactTelNo");
_contactEmail = applicantJSON.getString("contactEmail");
_applicantName = applicantJSON.getString("applicantName");
_applicantIdType = applicantJSON.getString("applicantIdType");
_applicantIdNo = applicantJSON.getString("applicantIdNo");
_applicantIdDate = applicantJSON.getString("applicantIdDate");
} else {
String applicantStr = applicantActions.getApplicantByUserId(serviceContext);
JSONObject applicantJSON = JSONFactoryUtil.createJSONObject(applicantStr);
_subjectName = applicantJSON.getString("applicantName");
_subjectId = applicantJSON.getString("applicantId");
_address = applicantJSON.getString("address");
_cityCode = applicantJSON.getString("cityCode");
_cityName = applicantJSON.getString("cityName");
_districtCode = applicantJSON.getString("districtCode");
_districtName = applicantJSON.getString("districtName");
_wardCode = applicantJSON.getString("wardCode");
_wardName = applicantJSON.getString("wardName");
_contactName = applicantJSON.getString("contactName");
_contactTelNo = applicantJSON.getString("contactTelNo");
_contactEmail = applicantJSON.getString("contactEmail");
_applicantName = applicantJSON.getString("applicantName");
_applicantIdType = applicantJSON.getString("applicantIdType");
_applicantIdNo = applicantJSON.getString("applicantIdNo");
_applicantIdDate = applicantJSON.getString("applicantIdDate");
}
} catch (PortalException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(dossier.getGroupId(), serviceContext.getUserId());
JSONObject employeeJSON = JSONFactoryUtil.createJSONObject(JSONFactoryUtil.looseSerialize(employee));
_log.info("GET EMPLOYEE ____");
_log.info(employeeJSON);
_employee_employeeNo = employeeJSON.getString("employeeNo");
_employee_fullName = employeeJSON.getString("fullName");
_employee_title = employeeJSON.getString("title");
} catch (Exception e) {
_log.info("NOT FOUN EMPLOYEE" + serviceContext.getUserId());
_log.error(e);
}
// process sampleData
if (Validator.isNull(sampleData)) {
sampleData = "{}";
}
Map<String, Object> jsonMap = jsonToMap(result);
for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
String value = String.valueOf(entry.getValue());
if (value.startsWith("_") && !value.contains(":")) {
if (value.equals("_subjectName")) {
jsonMap.put(entry.getKey(), _subjectName);
} else if (value.equals("_subjectId")) {
jsonMap.put(entry.getKey(), _subjectId);
} else if (value.equals("_address")) {
jsonMap.put(entry.getKey(), _address);
} else if (value.equals("_cityCode")) {
jsonMap.put(entry.getKey(), _cityCode);
} else if (value.equals("_cityName")) {
jsonMap.put(entry.getKey(), _cityName);
} else if (value.equals("_districtCode")) {
jsonMap.put(entry.getKey(), _districtCode);
} else if (value.equals("_districtName")) {
jsonMap.put(entry.getKey(), _districtName);
} else if (value.equals("_wardCode")) {
jsonMap.put(entry.getKey(), _wardCode);
} else if (value.equals("_wardName")) {
jsonMap.put(entry.getKey(), _wardName);
} else if (value.equals("_contactName")) {
jsonMap.put(entry.getKey(), _contactName);
} else if (value.equals("_contactTelNo")) {
jsonMap.put(entry.getKey(), _contactTelNo);
} else if (value.equals("_contactEmail")) {
jsonMap.put(entry.getKey(), _contactEmail);
} else if (value.equals("_receiveDate")) {
jsonMap.put(entry.getKey(), _receiveDate);
} else if (value.equals("_dossierNo")) {
jsonMap.put(entry.getKey(), _dossierNo);
} else if (value.equals("_employee_employeeNo")) {
jsonMap.put(entry.getKey(), _employee_employeeNo);
} else if (value.equals("_employee_fullName")) {
jsonMap.put(entry.getKey(), _employee_fullName);
}else if (value.equals("_employee_title")) {
jsonMap.put(entry.getKey(), _employee_title);
} else if (value.equals("_applicantName")) {
jsonMap.put(entry.getKey(), _applicantName);
} else if (value.equals("_applicantIdType")) {
jsonMap.put(entry.getKey(), _applicantIdType);
} else if (value.equals("_applicantIdNo")) {
jsonMap.put(entry.getKey(), _applicantIdNo);
} else if (value.equals("_applicantIdDate")) {
jsonMap.put(entry.getKey(), _applicantIdDate);
}else if (value.equals("_curDate")) {
jsonMap.put(entry.getKey(), _curDate);
}
} else if (value.startsWith("_") && value.contains(":")) {
String resultBinding = StringPool.BLANK;
String[] valueSplit = value.split(":");
for (String string : valueSplit) {
if (string.equals("_subjectName")) {
resultBinding += ", " + _subjectName;
} else if (string.equals("_subjectId")) {
resultBinding += ", " + _subjectId;
} else if (string.equals("_address")) {
resultBinding += ", " + _address;
} else if (string.equals("_wardCode")) {
resultBinding += ", " + _wardCode;
} else if (string.equals("_wardName")) {
resultBinding += ", " + _wardName;
} else if (string.equals("_districtCode")) {
resultBinding += ", " + _districtCode;
} else if (string.equals("_districtName")) {
resultBinding += ", " + _districtName;
} else if (string.equals("_cityCode")) {
resultBinding += ", " + _cityCode;
} else if (string.equals("_cityName")) {
resultBinding += ", " + _cityName;
} else if (string.equals("_contactName")) {
resultBinding += ", " + _contactName;
} else if (string.equals("_contactTelNo")) {
resultBinding += ", " + _contactTelNo;
} else if (string.equals("_contactEmail")) {
resultBinding += ", " + _contactEmail;
} else if (value.equals("_receiveDate")) {
resultBinding += ", " + _receiveDate;
} else if (value.equals("_dossierNo")) {
resultBinding += ", " + _dossierNo;
} else if (value.equals("_employee_employeeNo")) {
resultBinding += ", " + _employee_employeeNo;
} else if (value.equals("_employee_fullName")) {
resultBinding += ", " + _employee_fullName;
}else if (value.equals("_employee_title")) {
resultBinding += ", " + _employee_title;
} else if (value.equals("_applicantName")) {
resultBinding += ", " + _applicantName;
} else if (value.equals("_applicantIdType")) {
resultBinding += ", " + _applicantIdType;
} else if (value.equals("_applicantIdNo")) {
resultBinding += ", " + _applicantIdNo;
} else if (value.equals("_applicantIdDate")) {
resultBinding += ", " + _applicantIdDate;
} else if (value.equals("_curDate")) {
resultBinding += ", " + _curDate;
}
}
jsonMap.put(entry.getKey(), resultBinding.replaceFirst(", ", StringPool.BLANK));
} else if (value.startsWith("#") && value.contains("@")) {
String newString = value.substring(1);
String[] stringSplit = newString.split("@");
String variable = stringSplit[0];
String paper = stringSplit[1];
try {
DossierFile dossierFile = DossierFileLocalServiceUtil.getDossierFileByDID_FTNO_First(dossierId,
paper, false, new DossierFileComparator(false, "createDate", Date.class));
if (Validator.isNotNull(dossierFile) && Validator.isNotNull(dossierFile.getFormData()) && dossierFile.getFormData().trim().length() != 0) {
JSONObject jsonOtherData = JSONFactoryUtil.createJSONObject(dossierFile.getFormData());
Map<String, Object> jsonOtherMap = jsonToMap(jsonOtherData);
String myCHK = StringPool.BLANK;
try {
if (variable.contains(":")) {
String[] variableMuti = variable.split(":");
for (String string : variableMuti) {
myCHK += ", " + jsonOtherMap.get(string).toString();
}
myCHK = myCHK.replaceFirst(", ", "");
}else{
myCHK = jsonOtherMap.get(variable).toString();
}
} catch (Exception e) {
// TODO: handle exception
}
if (myCHK.startsWith("#")) {
jsonMap.put(entry.getKey(), "");
} else {
jsonMap.put(entry.getKey(), myCHK.toString());
}
} else {
jsonMap.put(entry.getKey(), "");
}
} catch (SystemException e) {
e.printStackTrace();
}
}
}
for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
if (entry.getValue().getClass().getName().contains("JSONArray")) {
result.put(entry.getKey(), (JSONArray) entry.getValue());
} else if (entry.getValue().getClass().getName().contains("JSONObject")) {
result.put(entry.getKey(), (JSONObject) entry.getValue());
} else {
result.put(entry.getKey(), entry.getValue() + "");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return result.toJSONString();
}
public static Map<String, Object> jsonToMap(JSONObject json) {
Map<String, Object> retMap = new HashMap<String, Object>();
if (Validator.isNotNull(json)) {
try {
retMap = toMap(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return retMap;
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while (keysItr.hasNext()) {
String key = keysItr.next();
Object value = null;
if (Validator.isNotNull(object.getJSONArray(key))) {
value = (JSONArray) object.getJSONArray(key);
map.put(key, value);
}
else if (Validator.isNotNull(object.getJSONObject(key))) {
value = (JSONObject) object.getJSONObject(key);
map.put(key, value);
}
else {
value = object.getString(key);
map.put(key, value);
}
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < array.length(); i++) {
Object value = array.getJSONObject(i);
if (value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
private static final Log _log = LogFactoryUtil.getLog(AutoFillFormData.class);
}
| modules/backend-dossiermgt/backend-dossiermgt-service/src/main/java/org/opencps/dossiermgt/action/util/AutoFillFormData.java | package org.opencps.dossiermgt.action.util;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.opencps.dossiermgt.model.Dossier;
import org.opencps.dossiermgt.model.DossierFile;
import org.opencps.dossiermgt.model.Registration;
import org.opencps.dossiermgt.service.DossierFileLocalServiceUtil;
import org.opencps.dossiermgt.service.DossierLocalServiceUtil;
import org.opencps.dossiermgt.service.RegistrationLocalServiceUtil;
import org.opencps.dossiermgt.service.comparator.DossierFileComparator;
import org.opencps.usermgt.action.ApplicantActions;
import org.opencps.usermgt.action.impl.ApplicantActionsImpl;
import org.opencps.usermgt.model.Employee;
import org.opencps.usermgt.service.EmployeeLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.service.ServiceContext;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.Validator;
public class AutoFillFormData {
public static String sampleDataBinding(String sampleData, long dossierId, ServiceContext serviceContext) {
// TODO Auto-generated method stub
JSONObject result = JSONFactoryUtil.createJSONObject();
try {
Dossier dossier = DossierLocalServiceUtil.fetchDossier(dossierId);
result = JSONFactoryUtil.createJSONObject(sampleData);
String _subjectName = StringPool.BLANK;
String _subjectId = StringPool.BLANK;
String _address = StringPool.BLANK;
String _cityCode = StringPool.BLANK;
String _cityName = StringPool.BLANK;
String _districtCode = StringPool.BLANK;
String _districtName = StringPool.BLANK;
String _wardCode = StringPool.BLANK;
String _wardName = StringPool.BLANK;
String _contactName = StringPool.BLANK;
String _contactTelNo = StringPool.BLANK;
String _contactEmail = StringPool.BLANK;
// TODO
String _dossierFileNo = StringPool.BLANK;
String _dossierFileDate = StringPool.BLANK;
String _receiveDate = StringPool.BLANK;
String _dossierNo = StringPool.BLANK;
String _employee_employeeNo = StringPool.BLANK;
String _employee_fullName = StringPool.BLANK;
String _employee_title = StringPool.BLANK;
String _applicantName = StringPool.BLANK;
String _applicantIdType = StringPool.BLANK;
String _applicantIdNo = StringPool.BLANK;
String _applicantIdDate = StringPool.BLANK;
String _curDate = StringPool.BLANK;
SimpleDateFormat sfd = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
_curDate = sfd.format(new Date());
if (Validator.isNotNull(dossier)) {
_receiveDate = Validator.isNotNull(dossier.getReceiveDate())?dossier.getReceiveDate().toGMTString():StringPool.BLANK;
_dossierNo = dossier.getDossierNo();
}
// get data applicant or employee
ApplicantActions applicantActions = new ApplicantActionsImpl();
try {
Registration registration = RegistrationLocalServiceUtil.getLastSubmittingByUser(dossier.getGroupId(), serviceContext.getUserId(), true);
if (Validator.isNotNull(registration)) {
JSONObject applicantJSON = JSONFactoryUtil.createJSONObject(JSONFactoryUtil.looseSerialize(registration));
_subjectName = applicantJSON.getString("applicantName");
_subjectId = applicantJSON.getString("applicantId");
_address = applicantJSON.getString("address");
_cityCode = applicantJSON.getString("cityCode");
_cityName = applicantJSON.getString("cityName");
_districtCode = applicantJSON.getString("districtCode");
_districtName = applicantJSON.getString("districtName");
_wardCode = applicantJSON.getString("wardCode");
_wardName = applicantJSON.getString("wardName");
_contactName = applicantJSON.getString("contactName");
_contactTelNo = applicantJSON.getString("contactTelNo");
_contactEmail = applicantJSON.getString("contactEmail");
_applicantName = applicantJSON.getString("applicantName");
_applicantIdType = applicantJSON.getString("applicantIdType");
_applicantIdNo = applicantJSON.getString("applicantIdNo");
_applicantIdDate = applicantJSON.getString("applicantIdDate");
} else {
String applicantStr = applicantActions.getApplicantByUserId(serviceContext);
JSONObject applicantJSON = JSONFactoryUtil.createJSONObject(applicantStr);
_subjectName = applicantJSON.getString("applicantName");
_subjectId = applicantJSON.getString("applicantId");
_address = applicantJSON.getString("address");
_cityCode = applicantJSON.getString("cityCode");
_cityName = applicantJSON.getString("cityName");
_districtCode = applicantJSON.getString("districtCode");
_districtName = applicantJSON.getString("districtName");
_wardCode = applicantJSON.getString("wardCode");
_wardName = applicantJSON.getString("wardName");
_contactName = applicantJSON.getString("contactName");
_contactTelNo = applicantJSON.getString("contactTelNo");
_contactEmail = applicantJSON.getString("contactEmail");
_applicantName = applicantJSON.getString("applicantName");
_applicantIdType = applicantJSON.getString("applicantIdType");
_applicantIdNo = applicantJSON.getString("applicantIdNo");
_applicantIdDate = applicantJSON.getString("applicantIdDate");
}
} catch (PortalException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Employee employee = EmployeeLocalServiceUtil.fetchByF_mappingUserId(dossier.getGroupId(), serviceContext.getUserId());
JSONObject employeeJSON = JSONFactoryUtil.createJSONObject(JSONFactoryUtil.looseSerialize(employee));
_log.info(employeeJSON);
_employee_employeeNo = employeeJSON.getString("employeeNo");
_employee_fullName = employeeJSON.getString("fullName");
_employee_title = employeeJSON.getString("title");
} catch (Exception e) {
_log.info("NOT FOUN EMPLOYEE" + serviceContext.getUserId());
_log.error(e);
}
// process sampleData
if (Validator.isNull(sampleData)) {
sampleData = "{}";
}
Map<String, Object> jsonMap = jsonToMap(result);
for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
String value = String.valueOf(entry.getValue());
if (value.startsWith("_") && !value.contains(":")) {
if (value.equals("_subjectName")) {
jsonMap.put(entry.getKey(), _subjectName);
} else if (value.equals("_subjectId")) {
jsonMap.put(entry.getKey(), _subjectId);
} else if (value.equals("_address")) {
jsonMap.put(entry.getKey(), _address);
} else if (value.equals("_cityCode")) {
jsonMap.put(entry.getKey(), _cityCode);
} else if (value.equals("_cityName")) {
jsonMap.put(entry.getKey(), _cityName);
} else if (value.equals("_districtCode")) {
jsonMap.put(entry.getKey(), _districtCode);
} else if (value.equals("_districtName")) {
jsonMap.put(entry.getKey(), _districtName);
} else if (value.equals("_wardCode")) {
jsonMap.put(entry.getKey(), _wardCode);
} else if (value.equals("_wardName")) {
jsonMap.put(entry.getKey(), _wardName);
} else if (value.equals("_contactName")) {
jsonMap.put(entry.getKey(), _contactName);
} else if (value.equals("_contactTelNo")) {
jsonMap.put(entry.getKey(), _contactTelNo);
} else if (value.equals("_contactEmail")) {
jsonMap.put(entry.getKey(), _contactEmail);
} else if (value.equals("_receiveDate")) {
jsonMap.put(entry.getKey(), _receiveDate);
} else if (value.equals("_dossierNo")) {
jsonMap.put(entry.getKey(), _dossierNo);
} else if (value.equals("_employee_employeeNo")) {
jsonMap.put(entry.getKey(), _employee_employeeNo);
} else if (value.equals("_employee_fullName")) {
jsonMap.put(entry.getKey(), _employee_fullName);
}else if (value.equals("_employee_title")) {
jsonMap.put(entry.getKey(), _employee_title);
} else if (value.equals("_applicantName")) {
jsonMap.put(entry.getKey(), _applicantName);
} else if (value.equals("_applicantIdType")) {
jsonMap.put(entry.getKey(), _applicantIdType);
} else if (value.equals("_applicantIdNo")) {
jsonMap.put(entry.getKey(), _applicantIdNo);
} else if (value.equals("_applicantIdDate")) {
jsonMap.put(entry.getKey(), _applicantIdDate);
}else if (value.equals("_curDate")) {
jsonMap.put(entry.getKey(), _curDate);
}
} else if (value.startsWith("_") && value.contains(":")) {
String resultBinding = StringPool.BLANK;
String[] valueSplit = value.split(":");
for (String string : valueSplit) {
if (string.equals("_subjectName")) {
resultBinding += ", " + _subjectName;
} else if (string.equals("_subjectId")) {
resultBinding += ", " + _subjectId;
} else if (string.equals("_address")) {
resultBinding += ", " + _address;
} else if (string.equals("_wardCode")) {
resultBinding += ", " + _wardCode;
} else if (string.equals("_wardName")) {
resultBinding += ", " + _wardName;
} else if (string.equals("_districtCode")) {
resultBinding += ", " + _districtCode;
} else if (string.equals("_districtName")) {
resultBinding += ", " + _districtName;
} else if (string.equals("_cityCode")) {
resultBinding += ", " + _cityCode;
} else if (string.equals("_cityName")) {
resultBinding += ", " + _cityName;
} else if (string.equals("_contactName")) {
resultBinding += ", " + _contactName;
} else if (string.equals("_contactTelNo")) {
resultBinding += ", " + _contactTelNo;
} else if (string.equals("_contactEmail")) {
resultBinding += ", " + _contactEmail;
} else if (value.equals("_receiveDate")) {
resultBinding += ", " + _receiveDate;
} else if (value.equals("_dossierNo")) {
resultBinding += ", " + _dossierNo;
} else if (value.equals("_employee_employeeNo")) {
resultBinding += ", " + _employee_employeeNo;
} else if (value.equals("_employee_fullName")) {
resultBinding += ", " + _employee_fullName;
}else if (value.equals("_employee_title")) {
resultBinding += ", " + _employee_title;
} else if (value.equals("_applicantName")) {
resultBinding += ", " + _applicantName;
} else if (value.equals("_applicantIdType")) {
resultBinding += ", " + _applicantIdType;
} else if (value.equals("_applicantIdNo")) {
resultBinding += ", " + _applicantIdNo;
} else if (value.equals("_applicantIdDate")) {
resultBinding += ", " + _applicantIdDate;
} else if (value.equals("_curDate")) {
resultBinding += ", " + _curDate;
}
}
jsonMap.put(entry.getKey(), resultBinding.replaceFirst(", ", StringPool.BLANK));
} else if (value.startsWith("#") && value.contains("@")) {
String newString = value.substring(1);
String[] stringSplit = newString.split("@");
String variable = stringSplit[0];
String paper = stringSplit[1];
try {
DossierFile dossierFile = DossierFileLocalServiceUtil.getDossierFileByDID_FTNO_First(dossierId,
paper, false, new DossierFileComparator(false, "createDate", Date.class));
if (Validator.isNotNull(dossierFile) && Validator.isNotNull(dossierFile.getFormData()) && dossierFile.getFormData().trim().length() != 0) {
JSONObject jsonOtherData = JSONFactoryUtil.createJSONObject(dossierFile.getFormData());
Map<String, Object> jsonOtherMap = jsonToMap(jsonOtherData);
String myCHK = StringPool.BLANK;
try {
if (variable.contains(":")) {
String[] variableMuti = variable.split(":");
for (String string : variableMuti) {
myCHK += ", " + jsonOtherMap.get(string).toString();
}
myCHK = myCHK.replaceFirst(", ", "");
}else{
myCHK = jsonOtherMap.get(variable).toString();
}
} catch (Exception e) {
// TODO: handle exception
}
if (myCHK.startsWith("#")) {
jsonMap.put(entry.getKey(), "");
} else {
jsonMap.put(entry.getKey(), myCHK.toString());
}
} else {
jsonMap.put(entry.getKey(), "");
}
} catch (SystemException e) {
e.printStackTrace();
}
}
}
for (Map.Entry<String, Object> entry : jsonMap.entrySet()) {
if (entry.getValue().getClass().getName().contains("JSONArray")) {
result.put(entry.getKey(), (JSONArray) entry.getValue());
} else if (entry.getValue().getClass().getName().contains("JSONObject")) {
result.put(entry.getKey(), (JSONObject) entry.getValue());
} else {
result.put(entry.getKey(), entry.getValue() + "");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return result.toJSONString();
}
public static Map<String, Object> jsonToMap(JSONObject json) {
Map<String, Object> retMap = new HashMap<String, Object>();
if (Validator.isNotNull(json)) {
try {
retMap = toMap(json);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return retMap;
}
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
Map<String, Object> map = new HashMap<String, Object>();
Iterator<String> keysItr = object.keys();
while (keysItr.hasNext()) {
String key = keysItr.next();
Object value = null;
if (Validator.isNotNull(object.getJSONArray(key))) {
value = (JSONArray) object.getJSONArray(key);
map.put(key, value);
}
else if (Validator.isNotNull(object.getJSONObject(key))) {
value = (JSONObject) object.getJSONObject(key);
map.put(key, value);
}
else {
value = object.getString(key);
map.put(key, value);
}
}
return map;
}
public static List<Object> toList(JSONArray array) throws JSONException {
List<Object> list = new ArrayList<Object>();
for (int i = 0; i < array.length(); i++) {
Object value = array.getJSONObject(i);
if (value instanceof JSONObject) {
value = toMap((JSONObject) value);
}
list.add(value);
}
return list;
}
private static final Log _log = LogFactoryUtil.getLog(AutoFillFormData.class);
}
| GET EMPLOYEE | modules/backend-dossiermgt/backend-dossiermgt-service/src/main/java/org/opencps/dossiermgt/action/util/AutoFillFormData.java | GET EMPLOYEE |
|
Java | agpl-3.0 | b59e0c201f6a5aeac79dce932dedb5a2140be4a1 | 0 | duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test | 5afd6dba-2e60-11e5-9284-b827eb9e62be | hello.java | 5af7f560-2e60-11e5-9284-b827eb9e62be | 5afd6dba-2e60-11e5-9284-b827eb9e62be | hello.java | 5afd6dba-2e60-11e5-9284-b827eb9e62be |
|
Java | lgpl-2.1 | e3c55b15832848ce5e50c975743cc15d20a7f135 | 0 | seeburger-ag/jboss-remoting | /*
* JBoss, Home of Professional Open Source
* Copyright 2011, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.remoting3.remote;
import static org.jboss.remoting3.remote.RemoteLogger.log;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import org.jboss.remoting3.Attachments;
import org.jboss.remoting3.Channel;
import org.jboss.remoting3.ChannelBusyException;
import org.jboss.remoting3.Connection;
import org.jboss.remoting3.MessageCancelledException;
import org.jboss.remoting3.MessageOutputStream;
import org.jboss.remoting3.NotOpenException;
import org.jboss.remoting3.RemotingOptions;
import org.jboss.remoting3.spi.AbstractHandleableCloseable;
import org.jboss.remoting3.spi.ConnectionHandlerContext;
import org.xnio.Bits;
import org.xnio.Option;
import org.xnio.Pooled;
import org.xnio.channels.Channels;
import org.xnio.channels.ConnectedMessageChannel;
/**
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
final class RemoteConnectionChannel extends AbstractHandleableCloseable<Channel> implements Channel {
static final IntIndexer<RemoteConnectionChannel> INDEXER = new IntIndexer<RemoteConnectionChannel>() {
public int getKey(final RemoteConnectionChannel argument) {
return argument.channelId;
}
public boolean equals(final RemoteConnectionChannel argument, final int index) {
return argument.channelId == index;
}
};
private final RemoteConnectionHandler connectionHandler;
private final ConnectionHandlerContext connectionHandlerContext;
private final RemoteConnection connection;
private final int channelId;
private final IntIndexMap<OutboundMessage> outboundMessages = new IntIndexHashMap<OutboundMessage>(OutboundMessage.INDEXER, Equaller.IDENTITY, 512, 0.5f);
private final IntIndexMap<InboundMessage> inboundMessages = new IntIndexHashMap<InboundMessage>(InboundMessage.INDEXER, Equaller.IDENTITY, 512, 0.5f);
private final int outboundWindow;
private final int inboundWindow;
private final Attachments attachments = new Attachments();
private final Queue<InboundMessage> inboundMessageQueue = new ArrayDeque<InboundMessage>();
private final int maxOutboundMessages;
private final int maxInboundMessages;
private volatile int channelState = 0;
private static final AtomicIntegerFieldUpdater<RemoteConnectionChannel> channelStateUpdater = AtomicIntegerFieldUpdater.newUpdater(RemoteConnectionChannel.class, "channelState");
private Receiver nextReceiver;
private static final int WRITE_CLOSED = (1 << 31);
private static final int READ_CLOSED = (1 << 30);
private static final int OUTBOUND_MESSAGES_MASK = (1 << 15) - 1;
private static final int ONE_OUTBOUND_MESSAGE = 1;
private static final int INBOUND_MESSAGES_MASK = ((1 << 30) - 1) & ~OUTBOUND_MESSAGES_MASK;
private static final int ONE_INBOUND_MESSAGE = (1 << 15);
RemoteConnectionChannel(final RemoteConnectionHandler connectionHandler, final RemoteConnection connection, final int channelId, final int outboundWindow, final int inboundWindow, final int maxOutboundMessages, final int maxInboundMessages) {
super(connectionHandler.getConnectionContext().getConnectionProviderContext().getExecutor(), true);
connectionHandlerContext = connectionHandler.getConnectionContext();
this.connectionHandler = connectionHandler;
this.connection = connection;
this.channelId = channelId;
this.outboundWindow = outboundWindow;
this.inboundWindow = inboundWindow;
this.maxOutboundMessages = maxOutboundMessages;
this.maxInboundMessages = maxInboundMessages;
}
void openOutboundMessage() throws IOException {
int oldState, newState;
do {
oldState = channelState;
if ((oldState & WRITE_CLOSED) != 0) {
throw new NotOpenException("Writes closed");
}
final int outboundCount = oldState & OUTBOUND_MESSAGES_MASK;
if (outboundCount == maxOutboundMessages) {
throw new ChannelBusyException("Too many open outbound writes");
}
newState = oldState + ONE_OUTBOUND_MESSAGE;
} while (!casState(oldState, newState));
log.tracef("Opened outbound message on %s", this);
}
private int incrementState(final int count) {
final int oldState = channelStateUpdater.getAndAdd(this, count);
if (log.isTraceEnabled()) {
final int newState = oldState + count;
log.tracef("CAS %s\n\told: RS=%s WS=%s IM=%d OM=%d\n\tnew: RS=%s WS=%s IM=%d OM=%d", this,
Boolean.valueOf((oldState & READ_CLOSED) != 0),
Boolean.valueOf((oldState & WRITE_CLOSED) != 0),
Integer.valueOf((oldState & INBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_INBOUND_MESSAGE)),
Integer.valueOf((oldState & OUTBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_OUTBOUND_MESSAGE)),
Boolean.valueOf((newState & READ_CLOSED) != 0),
Boolean.valueOf((newState & WRITE_CLOSED) != 0),
Integer.valueOf((newState & INBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_INBOUND_MESSAGE)),
Integer.valueOf((newState & OUTBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_OUTBOUND_MESSAGE))
);
}
return oldState;
}
private boolean casState(final int oldState, final int newState) {
final boolean result = channelStateUpdater.compareAndSet(this, oldState, newState);
if (result && log.isTraceEnabled()) {
log.tracef("CAS %s\n\told: RS=%s WS=%s IM=%d OM=%d\n\tnew: RS=%s WS=%s IM=%d OM=%d", this,
Boolean.valueOf((oldState & READ_CLOSED) != 0),
Boolean.valueOf((oldState & WRITE_CLOSED) != 0),
Integer.valueOf((oldState & INBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_INBOUND_MESSAGE)),
Integer.valueOf((oldState & OUTBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_OUTBOUND_MESSAGE)),
Boolean.valueOf((newState & READ_CLOSED) != 0),
Boolean.valueOf((newState & WRITE_CLOSED) != 0),
Integer.valueOf((newState & INBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_INBOUND_MESSAGE)),
Integer.valueOf((newState & OUTBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_OUTBOUND_MESSAGE))
);
}
return result;
}
void closeOutboundMessage() {
int oldState = incrementState(-ONE_OUTBOUND_MESSAGE);
if (oldState == (WRITE_CLOSED | READ_CLOSED)) {
// no messages left and read & write closed
log.tracef("Closed outbound message on %s (unregistering)", this);
unregister();
} else {
log.tracef("Closed outbound message on %s", this);
}
}
boolean openInboundMessage() {
int oldState, newState;
do {
oldState = channelState;
if ((oldState & READ_CLOSED) != 0) {
log.tracef("Refusing inbound message on %s (reads closed)", this);
return false;
}
final int inboundCount = oldState & INBOUND_MESSAGES_MASK;
if (inboundCount == maxInboundMessages) {
log.tracef("Refusing inbound message on %s (too many concurrent reads)", this);
return false;
}
newState = oldState + ONE_INBOUND_MESSAGE;
} while (!casState(oldState, newState));
log.tracef("Opened inbound message on %s", this);
return true;
}
void closeInboundMessage() {
int oldState = incrementState(-ONE_INBOUND_MESSAGE);
if (oldState == (WRITE_CLOSED | READ_CLOSED)) {
// no messages left and read & write closed
log.tracef("Closed inbound message on %s (unregistering)", this);
unregister();
} else {
log.tracef("Closed inbound message on %s", this);
}
}
void closeReads() {
int oldState, newState;
do {
oldState = channelState;
if ((oldState & READ_CLOSED) != 0) {
return;
}
newState = oldState | READ_CLOSED;
} while (!casState(oldState, newState));
if (oldState == WRITE_CLOSED) {
// no channels
log.tracef("Closed channel reads on %s (unregistering)", this);
unregister();
} else {
log.tracef("Closed channel reads on %s", this);
}
notifyEnd();
}
boolean closeWrites() {
int oldState, newState;
do {
oldState = channelState;
if ((oldState & WRITE_CLOSED) != 0) {
return false;
}
newState = oldState | WRITE_CLOSED;
} while (!casState(oldState, newState));
if (oldState == READ_CLOSED) {
// no channels and read was closed
log.tracef("Closed channel writes on %s (unregistering)", this);
unregister();
} else {
log.tracef("Closed channel writes on %s", this);
}
return true;
}
boolean closeReadsAndWrites() {
int oldState, newState;
do {
oldState = channelState;
if ((oldState & (READ_CLOSED | WRITE_CLOSED)) == (READ_CLOSED | WRITE_CLOSED)) {
return false;
}
newState = oldState | READ_CLOSED | WRITE_CLOSED;
} while (!casState(oldState, newState));
if ((oldState & WRITE_CLOSED) == 0) {
// we're sending the write close request asynchronously
Pooled<ByteBuffer> pooled = connection.allocate();
boolean ok = false;
try {
ByteBuffer byteBuffer = pooled.getResource();
byteBuffer.put(Protocol.CHANNEL_SHUTDOWN_WRITE);
byteBuffer.putInt(channelId);
byteBuffer.flip();
ok = true;
connection.send(pooled);
} finally {
if (! ok) pooled.free();
}
log.tracef("Closed channel reads on %s", this);
}
if ((oldState & (INBOUND_MESSAGES_MASK | OUTBOUND_MESSAGES_MASK)) == 0) {
// there were no channels open
log.tracef("Closed channel reads and writes on %s (unregistering)", this);
unregister();
} else {
log.tracef("Closed channel reads and writes on %s", this);
}
notifyEnd();
return true;
}
private void notifyEnd() {
synchronized (connection) {
if (nextReceiver != null) {
final Receiver receiver = nextReceiver;
nextReceiver = null;
try {
getExecutor().execute(new Runnable() {
public void run() {
receiver.handleEnd(RemoteConnectionChannel.this);
}
});
} catch (Throwable t) {
connection.handleException(new IOException("Fatal connection error", t));
return;
}
}
}
}
private void unregister() {
log.tracef("Unregistering %s", this);
closeAsync();
connectionHandler.handleChannelClosed(this);
}
public MessageOutputStream writeMessage() throws IOException {
int tries = 50;
IntIndexMap<OutboundMessage> outboundMessages = this.outboundMessages;
openOutboundMessage();
boolean ok = false;
try {
final Random random = ProtocolUtils.randomHolder.get();
while (tries > 0) {
final int id = random.nextInt() & 0xfffe;
if (! outboundMessages.containsKey(id)) {
OutboundMessage message = new OutboundMessage((short) id, this, outboundWindow);
OutboundMessage existing = outboundMessages.putIfAbsent(message);
if (existing == null) {
ok = true;
return message;
}
}
tries --;
}
throw log.channelBusy();
} finally {
if (! ok) {
closeOutboundMessage();
}
}
}
void free(OutboundMessage outboundMessage) {
if (outboundMessages.remove(outboundMessage)) {
log.tracef("Removed %s", outboundMessage);
closeOutboundMessage();
} else {
log.tracef("Got redundant free for %s", outboundMessage);
}
}
public void writeShutdown() throws IOException {
if (closeWrites()) {
Pooled<ByteBuffer> pooled = connection.allocate();
try {
ByteBuffer byteBuffer = pooled.getResource();
byteBuffer.put(Protocol.CHANNEL_SHUTDOWN_WRITE);
byteBuffer.putInt(channelId);
byteBuffer.flip();
ConnectedMessageChannel channel = connection.getChannel();
Channels.sendBlocking(channel, byteBuffer);
Channels.flushBlocking(channel);
} finally {
pooled.free();
}
}
}
void handleRemoteClose() {
closeReadsAndWrites();
}
void handleIncomingWriteShutdown() {
closeReads();
}
public void receiveMessage(final Receiver handler) {
synchronized (connection) {
if (inboundMessageQueue.isEmpty()) {
if (nextReceiver != null) {
throw new IllegalStateException("Message handler already queued");
}
nextReceiver = handler;
} else {
if ((channelState & READ_CLOSED) != 0) {
getExecutor().execute(new Runnable() {
public void run() {
handler.handleEnd(RemoteConnectionChannel.this);
}
});
} else {
final InboundMessage message = inboundMessageQueue.remove();
try {
getExecutor().execute(new Runnable() {
public void run() {
handler.handleMessage(RemoteConnectionChannel.this, message.messageInputStream);
}
});
} catch (Throwable t) {
connection.handleException(new IOException("Fatal connection error", t));
return;
}
}
}
connection.notify();
}
}
private static Set<Option<?>> SUPPORTED_OPTIONS = Option.setBuilder()
.add(RemotingOptions.MAX_INBOUND_MESSAGES)
.add(RemotingOptions.MAX_OUTBOUND_MESSAGES)
.create();
public boolean supportsOption(final Option<?> option) {
return SUPPORTED_OPTIONS.contains(option);
}
public <T> T getOption(final Option<T> option) {
if (option == RemotingOptions.MAX_INBOUND_MESSAGES) {
return option.cast(maxInboundMessages);
} else if (option == RemotingOptions.MAX_OUTBOUND_MESSAGES) {
return option.cast(maxOutboundMessages);
} else {
return null;
}
}
public <T> T setOption(final Option<T> option, final T value) throws IllegalArgumentException {
return null;
}
void handleMessageData(final Pooled<ByteBuffer> message) {
boolean ok1 = false;
try {
ByteBuffer buffer = message.getResource();
int id = buffer.getShort() & 0xffff;
int flags = buffer.get() & 0xff;
final InboundMessage inboundMessage;
if ((flags & Protocol.MSG_FLAG_NEW) != 0) {
if (! openInboundMessage()) {
asyncCloseMessage(id);
return;
}
boolean ok2 = false;
try {
inboundMessage = new InboundMessage((short) id, this, inboundWindow);
final InboundMessage existing = inboundMessages.putIfAbsent(inboundMessage);
if (existing != null) {
existing.cancel();
asyncCloseMessage(id);
return;
}
synchronized(connection) {
if (nextReceiver != null) {
final Receiver receiver = nextReceiver;
nextReceiver = null;
try {
getExecutor().execute(new Runnable() {
public void run() {
receiver.handleMessage(RemoteConnectionChannel.this, inboundMessage.messageInputStream);
}
});
ok2 = true;
} catch (Throwable t) {
connection.handleException(new IOException("Fatal connection error", t));
return;
}
} else {
inboundMessageQueue.add(inboundMessage);
ok2 = true;
}
}
} finally {
if (! ok2) freeInboundMessage((short) id);
}
} else {
inboundMessage = inboundMessages.get(id);
if (inboundMessage == null) {
log.tracef("Ignoring message on channel %s for unknown message ID %04x", this, Integer.valueOf(id));
return;
}
}
inboundMessage.handleIncoming(message);
ok1 = true;
} finally {
if (! ok1) message.free();
}
}
private void asyncCloseMessage(final int id) {
Pooled<ByteBuffer> pooled = connection.allocate();
boolean ok = false;
try {
ByteBuffer byteBuffer = pooled.getResource();
byteBuffer.put(Protocol.MESSAGE_ASYNC_CLOSE);
byteBuffer.putInt(channelId);
byteBuffer.putShort((short) id);
byteBuffer.flip();
ok = true;
connection.send(pooled);
} finally {
if (! ok) pooled.free();
}
}
void handleWindowOpen(final Pooled<ByteBuffer> pooled) {
ByteBuffer buffer = pooled.getResource();
int id = buffer.getShort() & 0xffff;
final OutboundMessage outboundMessage = outboundMessages.get(id);
if (outboundMessage == null) {
// ignore; probably harmless...?
return;
}
outboundMessage.acknowledge(buffer.getInt() & 0x7FFFFFFF);
}
void handleAsyncClose(final Pooled<ByteBuffer> pooled) {
ByteBuffer buffer = pooled.getResource();
int id = buffer.getShort() & 0xffff;
final OutboundMessage outboundMessage = outboundMessages.get(id);
if (outboundMessage == null) {
// ignore; probably harmless...?
return;
}
outboundMessage.closeAsync();
}
public Attachments getAttachments() {
return attachments;
}
public Connection getConnection() {
return connectionHandlerContext.getConnection();
}
@Override
protected void closeAction() throws IOException {
closeReadsAndWrites();
closeMessages();
closeComplete();
}
private void closeMessages() {
for (InboundMessage message : inboundMessages) {
message.inputStream.pushException(new MessageCancelledException());
}
for (OutboundMessage message : outboundMessages) {
message.cancel();
}
}
RemoteConnection getRemoteConnection() {
return connection;
}
int getChannelId() {
return channelId;
}
void freeInboundMessage(final short id) {
if (inboundMessages.removeKey(id & 0xffff) != null) {
closeInboundMessage();
}
}
Pooled<ByteBuffer> allocate(final byte protoId) {
final Pooled<ByteBuffer> pooled = connection.allocate();
final ByteBuffer buffer = pooled.getResource();
buffer.put(protoId);
buffer.putInt(channelId);
return pooled;
}
public String toString() {
return String.format("Channel ID %08x (%s) of %s", Integer.valueOf(channelId), (channelId & 0x80000000) == 0 ? "inbound" : "outbound", connection);
}
void dumpState(final StringBuilder b) {
final int state = channelState;
final int inboundMessageCnt = (state & INBOUND_MESSAGES_MASK) >>> (Integer.numberOfTrailingZeros(ONE_INBOUND_MESSAGE));
final int outboundMessageCnt = (state & OUTBOUND_MESSAGES_MASK) >>> (Integer.numberOfTrailingZeros(ONE_OUTBOUND_MESSAGE));
b.append(" ").append(String.format("%s channel ID %08x summary:\n", (channelId & 0x80000000) == 0 ? "Inbound" : "Outbound", channelId));
b.append(" ").append("* Flags: ");
if (Bits.allAreSet(state, READ_CLOSED)) b.append("read-closed ");
if (Bits.allAreSet(state, WRITE_CLOSED)) b.append("write-closed ");
b.append('\n');
b.append(" ").append("* ").append(inboundMessageQueue.size()).append(" pending inbound messages\n");
b.append(" ").append("* ").append(inboundMessageCnt).append(" (max ").append(maxInboundMessages).append(") inbound messages\n");
b.append(" ").append("* ").append(outboundMessageCnt).append(" (max ").append(maxOutboundMessages).append(") outbound messages\n");
b.append(" ").append("* Pending inbound messages:\n");
for (InboundMessage inboundMessage : inboundMessageQueue) {
inboundMessage.dumpState(b);
}
b.append(" ").append("* Inbound messages:\n");
for (InboundMessage inboundMessage : inboundMessages) {
inboundMessage.dumpState(b);
}
b.append(" ").append("* Outbound messages:\n");
for (OutboundMessage outboundMessage : outboundMessages) {
outboundMessage.dumpState(b);
}
}
}
| src/main/java/org/jboss/remoting3/remote/RemoteConnectionChannel.java | /*
* JBoss, Home of Professional Open Source
* Copyright 2011, JBoss Inc., and individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.remoting3.remote;
import static org.jboss.remoting3.remote.RemoteLogger.log;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import org.jboss.remoting3.Attachments;
import org.jboss.remoting3.Channel;
import org.jboss.remoting3.ChannelBusyException;
import org.jboss.remoting3.Connection;
import org.jboss.remoting3.MessageCancelledException;
import org.jboss.remoting3.MessageOutputStream;
import org.jboss.remoting3.NotOpenException;
import org.jboss.remoting3.RemotingOptions;
import org.jboss.remoting3.spi.AbstractHandleableCloseable;
import org.jboss.remoting3.spi.ConnectionHandlerContext;
import org.xnio.Bits;
import org.xnio.Option;
import org.xnio.Pooled;
import org.xnio.channels.Channels;
import org.xnio.channels.ConnectedMessageChannel;
/**
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
final class RemoteConnectionChannel extends AbstractHandleableCloseable<Channel> implements Channel {
static final IntIndexer<RemoteConnectionChannel> INDEXER = new IntIndexer<RemoteConnectionChannel>() {
public int getKey(final RemoteConnectionChannel argument) {
return argument.channelId;
}
public boolean equals(final RemoteConnectionChannel argument, final int index) {
return argument.channelId == index;
}
};
private final RemoteConnectionHandler connectionHandler;
private final ConnectionHandlerContext connectionHandlerContext;
private final RemoteConnection connection;
private final int channelId;
private final IntIndexMap<OutboundMessage> outboundMessages = new IntIndexHashMap<OutboundMessage>(OutboundMessage.INDEXER, Equaller.IDENTITY, 512, 0.5f);
private final IntIndexMap<InboundMessage> inboundMessages = new IntIndexHashMap<InboundMessage>(InboundMessage.INDEXER, Equaller.IDENTITY, 512, 0.5f);
private final int outboundWindow;
private final int inboundWindow;
private final Attachments attachments = new Attachments();
private final Queue<InboundMessage> inboundMessageQueue = new ArrayDeque<InboundMessage>();
private final int maxOutboundMessages;
private final int maxInboundMessages;
private volatile int channelState = 0;
private static final AtomicIntegerFieldUpdater<RemoteConnectionChannel> channelStateUpdater = AtomicIntegerFieldUpdater.newUpdater(RemoteConnectionChannel.class, "channelState");
private Receiver nextReceiver;
private static final int WRITE_CLOSED = (1 << 31);
private static final int READ_CLOSED = (1 << 30);
private static final int OUTBOUND_MESSAGES_MASK = (1 << 15) - 1;
private static final int ONE_OUTBOUND_MESSAGE = 1;
private static final int INBOUND_MESSAGES_MASK = ((1 << 30) - 1) & ~OUTBOUND_MESSAGES_MASK;
private static final int ONE_INBOUND_MESSAGE = (1 << 15);
RemoteConnectionChannel(final RemoteConnectionHandler connectionHandler, final RemoteConnection connection, final int channelId, final int outboundWindow, final int inboundWindow, final int maxOutboundMessages, final int maxInboundMessages) {
super(connectionHandler.getConnectionContext().getConnectionProviderContext().getExecutor(), true);
connectionHandlerContext = connectionHandler.getConnectionContext();
this.connectionHandler = connectionHandler;
this.connection = connection;
this.channelId = channelId;
this.outboundWindow = outboundWindow;
this.inboundWindow = inboundWindow;
this.maxOutboundMessages = maxOutboundMessages;
this.maxInboundMessages = maxInboundMessages;
}
void openOutboundMessage() throws IOException {
int oldState, newState;
do {
oldState = channelState;
if ((oldState & WRITE_CLOSED) != 0) {
throw new NotOpenException("Writes closed");
}
final int outboundCount = oldState & OUTBOUND_MESSAGES_MASK;
if (outboundCount == maxOutboundMessages) {
throw new ChannelBusyException("Too many open outbound writes");
}
newState = oldState + ONE_OUTBOUND_MESSAGE;
} while (!casState(oldState, newState));
log.tracef("Opened outbound message on %s", this);
}
private int incrementState(final int count) {
final int oldState = channelStateUpdater.getAndAdd(this, count);
if (log.isTraceEnabled()) {
final int newState = oldState + count;
log.tracef("CAS %s\n\told: RS=%s WS=%s IM=%d OM=%d\n\tnew: RS=%s WS=%s IM=%d OM=%d", this,
Boolean.valueOf((oldState & READ_CLOSED) != 0),
Boolean.valueOf((oldState & WRITE_CLOSED) != 0),
Integer.valueOf((oldState & INBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_INBOUND_MESSAGE)),
Integer.valueOf((oldState & OUTBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_OUTBOUND_MESSAGE)),
Boolean.valueOf((newState & READ_CLOSED) != 0),
Boolean.valueOf((newState & WRITE_CLOSED) != 0),
Integer.valueOf((newState & INBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_INBOUND_MESSAGE)),
Integer.valueOf((newState & OUTBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_OUTBOUND_MESSAGE))
);
}
return oldState;
}
private boolean casState(final int oldState, final int newState) {
final boolean result = channelStateUpdater.compareAndSet(this, oldState, newState);
if (result && log.isTraceEnabled()) {
log.tracef("CAS %s\n\told: RS=%s WS=%s IM=%d OM=%d\n\tnew: RS=%s WS=%s IM=%d OM=%d", this,
Boolean.valueOf((oldState & READ_CLOSED) != 0),
Boolean.valueOf((oldState & WRITE_CLOSED) != 0),
Integer.valueOf((oldState & INBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_INBOUND_MESSAGE)),
Integer.valueOf((oldState & OUTBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_OUTBOUND_MESSAGE)),
Boolean.valueOf((newState & READ_CLOSED) != 0),
Boolean.valueOf((newState & WRITE_CLOSED) != 0),
Integer.valueOf((newState & INBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_INBOUND_MESSAGE)),
Integer.valueOf((newState & OUTBOUND_MESSAGES_MASK) >> Integer.numberOfTrailingZeros(ONE_OUTBOUND_MESSAGE))
);
}
return result;
}
void closeOutboundMessage() {
int oldState = incrementState(-ONE_OUTBOUND_MESSAGE);
if (oldState == (WRITE_CLOSED | READ_CLOSED)) {
// no messages left and read & write closed
log.tracef("Closed outbound message on %s (unregistering)", this);
unregister();
} else {
log.tracef("Closed outbound message on %s", this);
}
}
boolean openInboundMessage() {
int oldState, newState;
do {
oldState = channelState;
if ((oldState & READ_CLOSED) != 0) {
log.tracef("Refusing inbound message on %s (reads closed)", this);
return false;
}
final int inboundCount = oldState & INBOUND_MESSAGES_MASK;
if (inboundCount == maxInboundMessages) {
log.tracef("Refusing inbound message on %s (too many concurrent reads)", this);
return false;
}
newState = oldState + ONE_INBOUND_MESSAGE;
} while (!casState(oldState, newState));
log.tracef("Opened inbound message on %s", this);
return true;
}
void closeInboundMessage() {
int oldState = incrementState(-ONE_INBOUND_MESSAGE);
if (oldState == (WRITE_CLOSED | READ_CLOSED)) {
// no messages left and read & write closed
log.tracef("Closed inbound message on %s (unregistering)", this);
unregister();
} else {
log.tracef("Closed inbound message on %s", this);
}
}
void closeReads() {
int oldState, newState;
do {
oldState = channelState;
if ((oldState & READ_CLOSED) != 0) {
return;
}
newState = oldState | READ_CLOSED;
} while (!casState(oldState, newState));
if (oldState == WRITE_CLOSED) {
// no channels
log.tracef("Closed channel reads on %s (unregistering)", this);
unregister();
} else {
log.tracef("Closed channel reads on %s", this);
}
notifyEnd();
}
boolean closeWrites() {
int oldState, newState;
do {
oldState = channelState;
if ((oldState & WRITE_CLOSED) != 0) {
return false;
}
newState = oldState | WRITE_CLOSED;
} while (!casState(oldState, newState));
if (oldState == READ_CLOSED) {
// no channels and read was closed
log.tracef("Closed channel writes on %s (unregistering)", this);
unregister();
} else {
log.tracef("Closed channel writes on %s", this);
}
return true;
}
boolean closeReadsAndWrites() {
int oldState, newState;
do {
oldState = channelState;
if ((oldState & (READ_CLOSED | WRITE_CLOSED)) == (READ_CLOSED | WRITE_CLOSED)) {
return false;
}
newState = oldState | READ_CLOSED | WRITE_CLOSED;
} while (!casState(oldState, newState));
if ((oldState & WRITE_CLOSED) == 0) {
// we're sending the write close request asynchronously
Pooled<ByteBuffer> pooled = connection.allocate();
boolean ok = false;
try {
ByteBuffer byteBuffer = pooled.getResource();
byteBuffer.put(Protocol.CHANNEL_SHUTDOWN_WRITE);
byteBuffer.putInt(channelId);
byteBuffer.flip();
ok = true;
connection.send(pooled);
} finally {
if (! ok) pooled.free();
}
log.tracef("Closed channel reads on %s", this);
}
if ((oldState & (INBOUND_MESSAGES_MASK | OUTBOUND_MESSAGES_MASK)) == 0) {
// there were no channels open
log.tracef("Closed channel reads and writes on %s (unregistering)", this);
unregister();
} else {
log.tracef("Closed channel reads and writes on %s", this);
}
notifyEnd();
return true;
}
private void notifyEnd() {
synchronized (connection) {
if (nextReceiver != null) {
final Receiver receiver = nextReceiver;
nextReceiver = null;
try {
getExecutor().execute(new Runnable() {
public void run() {
receiver.handleEnd(RemoteConnectionChannel.this);
}
});
} catch (Throwable t) {
connection.handleException(new IOException("Fatal connection error", t));
return;
}
}
}
}
private void unregister() {
log.tracef("Unregistering %s", this);
closeAsync();
connectionHandler.handleChannelClosed(this);
}
public MessageOutputStream writeMessage() throws IOException {
int tries = 50;
IntIndexMap<OutboundMessage> outboundMessages = this.outboundMessages;
openOutboundMessage();
boolean ok = false;
try {
final Random random = ProtocolUtils.randomHolder.get();
while (tries > 0) {
final int id = random.nextInt() & 0xfffe;
if (! outboundMessages.containsKey(id)) {
OutboundMessage message = new OutboundMessage((short) id, this, outboundWindow);
OutboundMessage existing = outboundMessages.putIfAbsent(message);
if (existing == null) {
ok = true;
return message;
}
}
tries --;
}
throw log.channelBusy();
} finally {
if (! ok) {
closeOutboundMessage();
}
}
}
void free(OutboundMessage outboundMessage) {
if (outboundMessages.remove(outboundMessage)) {
log.tracef("Removed %s", outboundMessage);
closeOutboundMessage();
} else {
log.tracef("Got redundant free for %s", outboundMessage);
}
}
public void writeShutdown() throws IOException {
if (closeWrites()) {
Pooled<ByteBuffer> pooled = connection.allocate();
try {
ByteBuffer byteBuffer = pooled.getResource();
byteBuffer.put(Protocol.CHANNEL_SHUTDOWN_WRITE);
byteBuffer.putInt(channelId);
byteBuffer.flip();
ConnectedMessageChannel channel = connection.getChannel();
Channels.sendBlocking(channel, byteBuffer);
Channels.flushBlocking(channel);
} finally {
pooled.free();
}
}
}
void handleRemoteClose() {
closeReadsAndWrites();
}
void handleIncomingWriteShutdown() {
closeReads();
}
public void receiveMessage(final Receiver handler) {
synchronized (connection) {
if (inboundMessageQueue.isEmpty()) {
if (nextReceiver != null) {
throw new IllegalStateException("Message handler already queued");
}
nextReceiver = handler;
} else {
if ((channelState & READ_CLOSED) != 0) {
getExecutor().execute(new Runnable() {
public void run() {
handler.handleEnd(RemoteConnectionChannel.this);
}
});
} else {
final InboundMessage message = inboundMessageQueue.remove();
try {
getExecutor().execute(new Runnable() {
public void run() {
handler.handleMessage(RemoteConnectionChannel.this, message.messageInputStream);
}
});
} catch (Throwable t) {
connection.handleException(new IOException("Fatal connection error", t));
return;
}
}
}
connection.notify();
}
}
private static Set<Option<?>> SUPPORTED_OPTIONS = Option.setBuilder()
.add(RemotingOptions.MAX_INBOUND_MESSAGES)
.add(RemotingOptions.MAX_OUTBOUND_MESSAGES)
.create();
public boolean supportsOption(final Option<?> option) {
return SUPPORTED_OPTIONS.contains(option);
}
public <T> T getOption(final Option<T> option) {
if (option == RemotingOptions.MAX_INBOUND_MESSAGES) {
return option.cast(maxInboundMessages);
} else if (option == RemotingOptions.MAX_OUTBOUND_MESSAGES) {
return option.cast(maxOutboundMessages);
} else {
return null;
}
}
public <T> T setOption(final Option<T> option, final T value) throws IllegalArgumentException {
return null;
}
void handleMessageData(final Pooled<ByteBuffer> message) {
boolean ok1 = false;
try {
ByteBuffer buffer = message.getResource();
int id = buffer.getShort() & 0xffff;
int flags = buffer.get() & 0xff;
final InboundMessage inboundMessage;
if ((flags & Protocol.MSG_FLAG_NEW) != 0) {
if (! openInboundMessage()) {
asyncCloseMessage(id);
return;
}
boolean ok2 = false;
try {
inboundMessage = new InboundMessage((short) id, this, inboundWindow);
final InboundMessage existing = inboundMessages.putIfAbsent(inboundMessage);
if (existing != null) {
existing.cancel();
asyncCloseMessage(id);
return;
}
synchronized(connection) {
if (nextReceiver != null) {
final Receiver receiver = nextReceiver;
nextReceiver = null;
try {
getExecutor().execute(new Runnable() {
public void run() {
receiver.handleMessage(RemoteConnectionChannel.this, inboundMessage.messageInputStream);
}
});
ok2 = true;
} catch (Throwable t) {
connection.handleException(new IOException("Fatal connection error", t));
return;
}
} else {
inboundMessageQueue.add(inboundMessage);
ok2 = true;
}
}
} finally {
if (! ok2) closeInboundMessage();
}
} else {
inboundMessage = inboundMessages.get(id);
if (inboundMessage == null) {
log.tracef("Ignoring message on channel %s for unknown message ID %04x", this, Integer.valueOf(id));
return;
}
}
inboundMessage.handleIncoming(message);
ok1 = true;
} finally {
if (! ok1) message.free();
}
}
private void asyncCloseMessage(final int id) {
Pooled<ByteBuffer> pooled = connection.allocate();
boolean ok = false;
try {
ByteBuffer byteBuffer = pooled.getResource();
byteBuffer.put(Protocol.MESSAGE_ASYNC_CLOSE);
byteBuffer.putInt(channelId);
byteBuffer.putShort((short) id);
byteBuffer.flip();
ok = true;
connection.send(pooled);
} finally {
if (! ok) pooled.free();
}
}
void handleWindowOpen(final Pooled<ByteBuffer> pooled) {
ByteBuffer buffer = pooled.getResource();
int id = buffer.getShort() & 0xffff;
final OutboundMessage outboundMessage = outboundMessages.get(id);
if (outboundMessage == null) {
// ignore; probably harmless...?
return;
}
outboundMessage.acknowledge(buffer.getInt() & 0x7FFFFFFF);
}
void handleAsyncClose(final Pooled<ByteBuffer> pooled) {
ByteBuffer buffer = pooled.getResource();
int id = buffer.getShort() & 0xffff;
final OutboundMessage outboundMessage = outboundMessages.get(id);
if (outboundMessage == null) {
// ignore; probably harmless...?
return;
}
outboundMessage.closeAsync();
}
public Attachments getAttachments() {
return attachments;
}
public Connection getConnection() {
return connectionHandlerContext.getConnection();
}
@Override
protected void closeAction() throws IOException {
closeReadsAndWrites();
closeMessages();
closeComplete();
}
private void closeMessages() {
for (InboundMessage message : inboundMessages) {
message.inputStream.pushException(new MessageCancelledException());
}
for (OutboundMessage message : outboundMessages) {
message.cancel();
}
}
RemoteConnection getRemoteConnection() {
return connection;
}
int getChannelId() {
return channelId;
}
void freeInboundMessage(final short id) {
closeInboundMessage();
inboundMessages.removeKey(id & 0xffff);
}
Pooled<ByteBuffer> allocate(final byte protoId) {
final Pooled<ByteBuffer> pooled = connection.allocate();
final ByteBuffer buffer = pooled.getResource();
buffer.put(protoId);
buffer.putInt(channelId);
return pooled;
}
public String toString() {
return String.format("Channel ID %08x (%s) of %s", Integer.valueOf(channelId), (channelId & 0x80000000) == 0 ? "inbound" : "outbound", connection);
}
void dumpState(final StringBuilder b) {
final int state = channelState;
final int inboundMessageCnt = (state & INBOUND_MESSAGES_MASK) >>> (Integer.numberOfTrailingZeros(ONE_INBOUND_MESSAGE));
final int outboundMessageCnt = (state & OUTBOUND_MESSAGES_MASK) >>> (Integer.numberOfTrailingZeros(ONE_OUTBOUND_MESSAGE));
b.append(" ").append(String.format("%s channel ID %08x summary:\n", (channelId & 0x80000000) == 0 ? "Inbound" : "Outbound", channelId));
b.append(" ").append("* Flags: ");
if (Bits.allAreSet(state, READ_CLOSED)) b.append("read-closed ");
if (Bits.allAreSet(state, WRITE_CLOSED)) b.append("write-closed ");
b.append('\n');
b.append(" ").append("* ").append(inboundMessageQueue.size()).append(" pending inbound messages\n");
b.append(" ").append("* ").append(inboundMessageCnt).append(" (max ").append(maxInboundMessages).append(") inbound messages\n");
b.append(" ").append("* ").append(outboundMessageCnt).append(" (max ").append(maxOutboundMessages).append(") outbound messages\n");
b.append(" ").append("* Pending inbound messages:\n");
for (InboundMessage inboundMessage : inboundMessageQueue) {
inboundMessage.dumpState(b);
}
b.append(" ").append("* Inbound messages:\n");
for (InboundMessage inboundMessage : inboundMessages) {
inboundMessage.dumpState(b);
}
b.append(" ").append("* Outbound messages:\n");
for (OutboundMessage outboundMessage : outboundMessages) {
outboundMessage.dumpState(b);
}
}
}
| Prevent double-free of inbound message
| src/main/java/org/jboss/remoting3/remote/RemoteConnectionChannel.java | Prevent double-free of inbound message |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.