answer
stringlengths 17
10.2M
|
|---|
package bakatxt.core;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.TreeSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import bakatxt.log.BakaLogger;
public class Database implements DatabaseInterface {
private static final String LINE_SEPARATOR = System
.getProperty("line.separator");
private static final String SPACE = " ";
private static final String MESSAGE_FILE_CHANGE = "File changed. Current filename is \"%1$s\".";
private static final String MESSAGE_OUTPUT_FILENAME = "Filename: %1$s"
+ LINE_SEPARATOR;
private static final String TAG_OPEN = "[";
private static final String TAG_CLOSE = "]";
private static final String TAG_TITLE = TAG_OPEN + "TITLE" + TAG_CLOSE;
private static final String FILE_COMMENT = TAG_OPEN + "-" + TAG_CLOSE
+ SPACE;
private static final String FILE_HEADER = FILE_COMMENT
+ "BakaTXT Human-Readable Human-Fixable Database";
private static final String FILE_VERSION = FILE_COMMENT + "alpha v0.0";
private static final String FILE_WARNING = FILE_COMMENT
+ "Each task has to be in the same line";
private static final String TAG_DELETED = "9999";
private static final String TAG_DONE = "5000";
private static final String TAG_FLOATING = "0000";
private static final Charset CHARSET_DEFAULT = Charset.forName("UTF-8");
private static final byte[] EMPTY_BYTE = {};
private static final OpenOption[] OPEN_OPTIONS = {
StandardOpenOption.CREATE, StandardOpenOption.APPEND };
private static final Logger LOGGER = Logger.getLogger(Database.class
.getName());
private static Database _database = null;
private Path _userFile;
private BufferedWriter _outputStream;
private HashMap<String, LinkedList<Task>> _bakaMap;
private TreeSet<String> _sortedKeys;
private boolean _removeDone;
private Database(String fileName) {
assert (_database == null);
try {
BakaLogger.setup();
} catch (SecurityException | IOException ex) {
BakaLogger.setup(true);
} finally {
LOGGER.setLevel(Level.INFO);
setEnvironment(fileName);
LOGGER.info("Database setup completed");
}
}
public static Database getInstance() {
if (_database == null) {
_database = new Database("mytestfile.txt");
}
return _database;
}
private void setEnvironment(String fileName) {
initializeFilePath(fileName);
initializeOutputStream();
initializeVariables();
}
private void initializeVariables() {
updateMemory();
_removeDone = false;
}
private void initializeFilePath(String fileName) {
_userFile = Paths.get(fileName);
}
private void initializeOutputStream() {
try {
_outputStream = Files.newBufferedWriter(_userFile, CHARSET_DEFAULT,
OPEN_OPTIONS);
} catch (IOException ex) {
LOGGER.severe("BufferedWriter failed");
}
}
private void updateMemory() {
LOGGER.info("bakaMap update initialized");
_bakaMap = new HashMap<String, LinkedList<Task>>();
try (BufferedReader inputStream = Files.newBufferedReader(_userFile,
CHARSET_DEFAULT)) {
String line;
while ((line = inputStream.readLine()) != null) {
if (line.isEmpty()) {
continue;
} else if (line.contains(TAG_DONE) && _removeDone) {
Task doneTask = new Task(line);
doneTask.setDeleted(true);
addTaskToMap(doneTask);
} else if (line.contains(TAG_TITLE)) {
Task task = new Task(line);
addTaskToMap(task);
}
}
} catch (IOException ex) {
ex.printStackTrace();
LOGGER.severe("bakaMap update failed");
}
}
private void addTaskToMap(Task task) {
LOGGER.info("add to bakaMap");
String key = task.getKey();
if (!_bakaMap.containsKey(key)) {
_bakaMap.put(key, new LinkedList<Task>());
}
LinkedList<Task> target = _bakaMap.get(key);
target.add(task);
}
@Override
public String setFile(String fileName) {
setEnvironment(fileName);
String output = String.format(MESSAGE_FILE_CHANGE, getFileName());
return output;
}
@Override
public String getFileName() {
return _userFile.toString();
}
private void sort() {
_sortedKeys = new TreeSet<String>(_bakaMap.keySet());
for (Map.Entry<String, LinkedList<Task>> entry : _bakaMap.entrySet()) {
LinkedList<Task> today = entry.getValue();
Collections.sort(today);
}
}
@Override
public String toString() {
String lineOne = String.format(MESSAGE_OUTPUT_FILENAME, getFileName());
return lineOne;
}
@Override
public boolean add(Task task) {
LOGGER.info("add task initialized");
task.setDeleted(false);
addTaskToMap(task);
return dirtyWrite(task.toString());
}
@Override
public boolean delete(Task task) {
LOGGER.info("delete task initialized");
String key = task.getKey();
LinkedList<Task> target = _bakaMap.get(key);
if (target == null) {
return false;
}
boolean isRemoved = target.remove(task);
if (isRemoved) {
task.setDeleted(true);
addTaskToMap(task);
dirtyWrite(task.toString());
} else {
return isRemoved;
}
return updateFile();
}
@Override
public void close() {
LOGGER.info("end Database initialized");
updateFile();
try {
_outputStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
_database = null;
BakaLogger.teardown();
}
private boolean updateFile() {
LOGGER.info("update file initialized");
// tempCreation();
resetFile();
writeFileComments();
return writeLinesToFile();
}
private void writeFileComments() {
try {
_outputStream.write(FILE_HEADER);
_outputStream.newLine();
_outputStream.write(FILE_VERSION);
_outputStream.newLine();
_outputStream.write(FILE_WARNING);
_outputStream.newLine();
_outputStream.newLine();
_outputStream.flush();
} catch (IOException ex) {
LOGGER.severe("unable to write to file!");
}
}
private boolean writeLinesToFile() {
LOGGER.info("write to file initialized");
try {
sort();
for (String key : _sortedKeys) {
if (key.contains(TAG_DONE) && _removeDone) {
continue;
}
LinkedList<Task> listToWrite = _bakaMap.get(key);
for (Task task : listToWrite) {
_outputStream.write(task.toString());
_outputStream.newLine();
}
_outputStream.newLine();
_outputStream.flush();
}
return true;
} catch (IOException ex) {
LOGGER.severe("unable to write to file!");
return false;
}
}
private void resetFile() {
LOGGER.info("reset file initialized");
try {
Files.write(_userFile, EMPTY_BYTE);
} catch (IOException ex) {
LOGGER.severe("file reset failed");
}
}
private void tempCreation() {
// copy userFile into tempFile
Path tempFile;
try {
tempFile = Files.createTempFile("bakatxt", "old");
Files.copy(_userFile, tempFile, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
LOGGER.warning("Temp creation failed");
}
LOGGER.info("Temp creation completed");
}
@Override
public boolean setDone(Task task, boolean isDone) {
LOGGER.info("done status change initialized");
assert (isExist(task));
delete(task);
task.setDone(isDone);
return add(task);
}
@Override
public LinkedList<Task> getTaskWithTitle(String title) {
LinkedList<Task> result = new LinkedList<Task>();
sort();
for (String key : _sortedKeys) {
if (key.contains(TAG_DELETED)) {
continue;
}
LinkedList<Task> today = _bakaMap.get(key);
for (Task task : today) {
String taskTitle = task.getTitle().toLowerCase();
if (taskTitle.contains(title.toLowerCase())) {
result.add(task);
}
}
}
return result;
}
@Override
public LinkedList<Task> getTasksWithDate(String key) {
LinkedList<Task> result = new LinkedList<Task>();
if (key == null) {
for (Map.Entry<String, LinkedList<Task>> entry : _bakaMap
.entrySet()) {
if (entry.getKey().contains(TAG_FLOATING)) {
result.addAll(entry.getValue());
}
}
} else if (_bakaMap.containsKey(key)) {
result = _bakaMap.get(key);
}
return result;
}
@Override
public LinkedList<Task> getAllTasks() {
LinkedList<Task> all = new LinkedList<Task>();
sort();
for (String key : _sortedKeys) {
if (key.contains(TAG_DELETED)) {
continue;
}
all.addAll(_bakaMap.get(key));
}
return all;
}
@Override
public LinkedList<Task> getAllUndoneTasks() {
LinkedList<Task> undone = new LinkedList<Task>();
sort();
for (String key : _sortedKeys) {
if (!key.contains(TAG_DONE) && !key.contains(TAG_DELETED)) {
LinkedList<Task> today = _bakaMap.get(key);
undone.addAll(today);
}
}
return undone;
}
@Override
public boolean setFloating(Task task, boolean isFloating) {
LOGGER.info("set floating status initialized");
delete(task);
task.setFloating(isFloating);
add(task);
return updateFile();
}
private boolean dirtyWrite(String line) {
try {
_outputStream.write(line);
_outputStream.newLine();
_outputStream.flush();
return true;
} catch (IOException ex) {
return false;
}
}
@Override
public void removeDone() {
LOGGER.info("delete done initialized");
_removeDone = true;
updateFile();
updateMemory();
_removeDone = false;
}
@Override
public void clear() {
for (String key : _sortedKeys) {
if (!key.contains(TAG_DELETED)) {
for (Task task : _bakaMap.get(key)) {
task.setDeleted(true);
}
}
}
updateFile();
updateMemory();
}
}
|
package com.ikvant.loriapp.database;
import android.arch.persistence.room.TypeConverter;
import com.ikvant.loriapp.database.project.Project;
import com.ikvant.loriapp.database.tags.Tag;
import com.ikvant.loriapp.database.task.Task;
import com.ikvant.loriapp.database.user.User;
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;
public class Converters {
private static DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.UK);
@TypeConverter
public static Project projectFromId(String id) {
return id == null ? null : new Project(id);
}
@TypeConverter
public static String projectToId(Project project) {
return project == null ? null : project.getId();
}
@TypeConverter
public static Task taskFromTaskId(String id) {
return id == null ? null : new Task(id);
}
@TypeConverter
public static String taskToTaskId(Task task) {
return task == null ? null : task.getId();
}
@TypeConverter
public static User userFromUserId(String id) {
return id == null ? null : new User(id);
}
@TypeConverter
public static String userToUserId(User user) {
return user == null ? null : user.getId();
}
@TypeConverter
public static Date dateFromString(String formatString) {
try {
return dateFormat.parse(formatString);
} catch (ParseException e) {
return null;
}
}
@TypeConverter
public static String dateToString(Date date) {
return dateFormat.format(date);
}
@TypeConverter
public static String tagsToString(List<Tag> tags) {
StringBuilder buffer = new StringBuilder();
for (Tag tag : tags) {
buffer.append(tag.getId()).append(":").append(tag.getName()).append(";");
}
return buffer.toString();
}
@TypeConverter
public static List<Tag> stringToTags(String str) {
List<Tag> tags = new ArrayList<>();
if (!"".equals(str)) {
String[] tagStrings = str.split(";");
for (String tag : tagStrings) {
String[] info = tag.split(":");
tags.add(new Tag(info[0], info[1]));
}
}
return tags;
}
}
|
package com.teamdev.jxmaps.examples;
import com.teamdev.jxmaps.ControlPosition;
import com.teamdev.jxmaps.LatLng;
import com.teamdev.jxmaps.Map;
import com.teamdev.jxmaps.MapOptions;
import com.teamdev.jxmaps.MapReadyHandler;
import com.teamdev.jxmaps.MapStatus;
import com.teamdev.jxmaps.MapTypeControlOptions;
import com.teamdev.jxmaps.StreetViewAddressControlOptions;
import com.teamdev.jxmaps.StreetViewPanoramaOptions;
import com.teamdev.jxmaps.StreetViewPov;
import com.teamdev.jxmaps.swing.MapView;
import javax.swing.*;
import java.awt.*;
/**
* This example demonstrates how to display street view panorama with a map.
*
* @author Vitaly Eremenko
*/
public class StreetViewExample extends MapView {
public StreetViewExample() {
super(true);
// Setting of a ready handler to MapView object. onMapReady will be called when map initialization is done and
// the map object is ready to use. Current implementation of onMapReady customizes the map object.
setOnMapReadyHandler(new MapReadyHandler() {
@Override
public void onMapReady(MapStatus status) {
// Check if the map is loaded correctly
if (status == MapStatus.MAP_STATUS_OK) {
// Getting the associated map object
Map map = getMap();
// Creating a map options object
MapOptions mapOptions = new MapOptions(map);
// Creating a map type control options object
MapTypeControlOptions controlOptions = new MapTypeControlOptions(map);
// Changing position of the map type control
controlOptions.setPosition(ControlPosition.TOP_RIGHT);
// Setting map type control options
mapOptions.setMapTypeControlOptions(controlOptions);
// Setting map options
map.setOptions(mapOptions);
// Setting the map center
map.setCenter(new LatLng(map, 51.500871, -0.1222632));
// Setting initial zoom value
map.setZoom(13.0);
// Creating a street view panorama options object
StreetViewPanoramaOptions options = new StreetViewPanoramaOptions(map);
// Creating a street view address control options object
StreetViewAddressControlOptions svControlOptions = new StreetViewAddressControlOptions(map);
// Changing position of the address control on the panorama
svControlOptions.setPosition(ControlPosition.TOP_RIGHT);
// Setting address control options
options.setAddressControlOptions(svControlOptions);
// Setting street view panorama options
getPanorama().setOptions(options);
// Setting initial position of the street view
getPanorama().setPosition(map.getCenter());
// Creating point of view object
StreetViewPov pov = new StreetViewPov(map);
// Setting heading for the point of view
pov.setHeading(270);
// Setting pitch for the point of view
pov.setPitch(20);
// Applying the point of view to the panorama object
getPanorama().setPov(pov);
}
}
});
}
public static void main(String[] args) {
final StreetViewExample sample = new StreetViewExample();
JFrame frame = new JFrame("Street View");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(sample, BorderLayout.CENTER);
frame.setSize(700, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
|
package com.juyuejk.myapplication;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("MainActivity", "jajja");
Log.d("MainActivity", "jajja");
Log.d("MainActivity", "jajja3");
Log.d("MainActivity", "jajja4");
}
}
|
package com.peterjosling.scroball;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import de.umass.lastfm.*;
import de.umass.lastfm.Track;
import de.umass.lastfm.scrobble.ScrobbleData;
import de.umass.lastfm.scrobble.ScrobbleResult;
public class LastfmClient {
private static final String API_KEY = "e0189dd89bed85023712c63544325558";
private static final String API_SECRET = "747ea338a0e071b7d3d14c1a64e13567";
private final Session session;
public LastfmClient(String userAgent, String sessionKey) {
Caller.getInstance().setUserAgent(userAgent);
session = Session.createSession(API_KEY, API_SECRET, sessionKey);
}
public void updateNowPlaying(final String artist, final String track) {
new AsyncTask<Object, Object, ScrobbleResult>() {
@Override
protected ScrobbleResult doInBackground(Object... params) {
return Track.updateNowPlaying(artist, track, session);
}
@Override
protected void onPostExecute(ScrobbleResult scrobbleResult) {
// TODO remove
System.out.println(scrobbleResult);
}
}.execute();
}
public void scrobbleTracks(final List<Scrobble> scrobbles, final Handler.Callback callback) {
final List<ScrobbleData> scrobbleData = new ArrayList<>();
for (Scrobble scrobble : scrobbles) {
com.peterjosling.scroball.Track track = scrobble.track();
scrobbleData.add(new ScrobbleData(track.artist(), track.track(), scrobble.timestamp()));
}
new AsyncTask<Object, Object, List<ScrobbleResult>>() {
@Override
protected List<ScrobbleResult> doInBackground(Object... params) {
return Track.scrobble(scrobbleData, session);
}
@Override
protected void onPostExecute(List<ScrobbleResult> results) {
Message message = Message.obtain();
message.obj = results;
callback.handleMessage(message);
System.out.println(Arrays.toString(results.toArray()));
}
}.execute();
}
public void getTrackInfo(final String artist, final String track, final Handler.Callback callback) {
new AsyncTask<Object, Object, Track>() {
@Override
protected Track doInBackground(Object... params) {
return Track.getInfo(artist, track, session.getApiKey());
}
@Override
protected void onPostExecute(Track updatedTrack) {
Message message = Message.obtain();
if (updatedTrack != null) {
message.obj = ImmutableTrack.builder()
.artist(artist)
.track(track)
.duration(updatedTrack.getDuration() * 1000)
.build();
}
callback.handleMessage(message);
}
}.execute();
}
}
|
package net.minecraftforge.common;
public class ForgeVersion
{
//This number is incremented every time we remove deprecated code/major API changes, never reset
public static final int majorVersion = 7;
//This number is incremented every minecraft release, never reset
public static final int minorVersion = 8;
//This number is incremented every time a interface changes or new major feature is added, and reset every Minecraft version
public static final int revisionVersion = 1;
//This number is incremented every time Jenkins builds Forge, and never reset. Should always be 0 in the repo code.
public static final int buildVersion = 0;
public static int getMajorVersion()
{
return majorVersion;
}
public static int getMinorVersion()
{
return minorVersion;
}
public static int getRevisionVersion()
{
return revisionVersion;
}
public static int getBuildVersion()
{
return buildVersion;
}
public static String getVersion()
{
return String.format("%d.%d.%d.%d", majorVersion, minorVersion, revisionVersion, buildVersion);
}
}
|
package com.xlythe.sms.fragment;
import android.Manifest;
import android.animation.ValueAnimator;
import android.content.Context;
import android.hardware.display.DisplayManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.support.v4.hardware.display.DisplayManagerCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.xlythe.sms.R;
import com.xlythe.sms.view.camera.BaseCameraView;
import com.xlythe.textmanager.text.ImageAttachment;
import com.xlythe.textmanager.text.Text;
import com.xlythe.textmanager.text.TextManager;
import com.xlythe.textmanager.text.VideoAttachment;
import java.io.File;
import java.util.Formatter;
import java.util.Locale;
import static com.xlythe.sms.util.PermissionUtils.hasPermissions;
public class CameraFragment extends Fragment implements BaseCameraView.OnImageCapturedListener, BaseCameraView.OnVideoCapturedListener {
public static final String ARG_MESSAGE = "message";
private static final String[] REQUIRED_PERMISSIONS = {
Manifest.permission.CAMERA,
Manifest.permission.RECORD_AUDIO,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
private static final int REQUEST_CODE_REQUIRED_PERMISSIONS = 3;
private static final String PHOTO_DESTINATION = "photo.jpg";
private static final String VIDEO_DESTINATION = "video.mp4";
private static final long VIDEO_MAX_DURATION = 10 * 1000;
private View mCameraHolder;
private View mPermissionPrompt;
private BaseCameraView mCamera;
private TextView mDuration;
private ProgressBar mProgress;
private ProgressBarAnimator mAnimator = new ProgressBarAnimator();
private Text mText;
private DisplayManager.DisplayListener mDisplayListener;
public static CameraFragment newInstance(Text text) {
CameraFragment fragment = new CameraFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_MESSAGE, text);
fragment.setArguments(args);
return fragment;
}
@Override
public void onImageCaptured(final File file) {
TextManager.getInstance(getContext()).send(new ImageAttachment(Uri.fromFile(file))).to(mText);
}
@Override
public void onVideoCaptured(final File file) {
TextManager.getInstance(getContext()).send(new VideoAttachment(Uri.fromFile(file))).to(mText);
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_CODE_REQUIRED_PERMISSIONS) {
if (hasPermissions(getContext(), REQUIRED_PERMISSIONS)) {
showCamera();
} else {
showPermissionPrompt();
}
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (Build.VERSION.SDK_INT > 17) {
mDisplayListener = new DisplayManager.DisplayListener() {
@Override
public void onDisplayAdded(int displayId) {}
@Override
public void onDisplayRemoved(int displayId) {}
@Override
public void onDisplayChanged(int displayId) {
if (hasPermissions(getContext(), REQUIRED_PERMISSIONS)) {
mCamera.close();
mCamera.open();
}
}
};
DisplayManager displayManager = (DisplayManager) context.getSystemService(Context.DISPLAY_SERVICE);
displayManager.registerDisplayListener(mDisplayListener, new Handler());
}
}
@Override
public void onDetach() {
super.onDetach();
if (Build.VERSION.SDK_INT > 17) {
DisplayManager displayManager = (DisplayManager) getContext().getSystemService(Context.DISPLAY_SERVICE);
displayManager.unregisterDisplayListener(mDisplayListener);
}
}
@Override
public void onResume() {
super.onResume();
if (hasPermissions(getContext(), REQUIRED_PERMISSIONS)) {
showCamera();
} else {
showPermissionPrompt();
}
}
private void showCamera() {
mCameraHolder.setVisibility(View.VISIBLE);
mPermissionPrompt.setVisibility(View.GONE);
mCamera.open();
}
private void showPermissionPrompt() {
mCameraHolder.setVisibility(View.GONE);
mPermissionPrompt.setVisibility(View.VISIBLE);
}
private String stringForTime(int timeMs) {
int totalSeconds = timeMs / 1000;
int seconds = totalSeconds % 60;
int minutes = (totalSeconds / 60) % 60;
int hours = totalSeconds / 3600;
Formatter formatter = new Formatter(Locale.getDefault());
if (hours > 0) {
return formatter.format("%d:%02d:%02d", hours, minutes, seconds).toString();
} else {
return formatter.format("%02d:%02d", minutes, seconds).toString();
}
}
public class ProgressBarAnimator extends ValueAnimator {
public ProgressBarAnimator() {
setInterpolator(new LinearInterpolator());
setFloatValues(0f, 1f);
addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float percent = (float) animation.getAnimatedValue();
onUpdate(percent);
}
});
}
public void onUpdate(float percent) {
mProgress.setProgress((int) (percent * 10000));
mDuration.setText(stringForTime((int) (percent * 10000)));
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_camera, container, false);
mText = getArguments().getParcelable(ARG_MESSAGE);
mCameraHolder = rootView.findViewById(R.id.layout_camera);
mCamera = (BaseCameraView) rootView.findViewById(R.id.camera);
mCamera.setOnImageCapturedListener(this);
mCamera.setOnVideoCapturedListener(this);
final ImageView toggleCamera = (ImageView) mCameraHolder.findViewById(R.id.btn_toggle_camera);
toggleCamera.setVisibility(mCamera.hasFrontFacingCamera() ? View.VISIBLE : View.GONE);
toggleCamera.setImageResource(mCamera.isUsingFrontFacingCamera() ? R.drawable.camera_back : R.drawable.camera_front);
toggleCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCamera.toggleCamera();
toggleCamera.setImageResource(mCamera.isUsingFrontFacingCamera() ? R.drawable.camera_back : R.drawable.camera_front);
}
});
mProgress = (ProgressBar) mCameraHolder.findViewById(R.id.seek);
mProgress.setMax(10000);
mDuration = (TextView) mCameraHolder.findViewById(R.id.duration);
mDuration.setVisibility(View.GONE);
final ImageView capture = (ImageView) mCameraHolder.findViewById(R.id.btn_capture);
capture.setEnabled(TextManager.getInstance(getContext()).isDefaultSmsPackage());
capture.setOnTouchListener(new View.OnTouchListener() {
private final int TAP = 1;
private final int HOLD = 2;
private final int RELEASE = 3;
private final long LONG_PRESS = ViewConfiguration.getLongPressTimeout();
private final long RELEASE_TIMEOUT = LONG_PRESS + VIDEO_MAX_DURATION;
private long start;
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case TAP:
onTap();
break;
case HOLD:
onHold();
break;
case RELEASE:
onRelease();
break;
}
}
};
private void onTap() {
mCamera.takePicture(new File(getContext().getCacheDir(), PHOTO_DESTINATION));
}
private void onHold() {
vibrate();
mCamera.startRecording(new File(getContext().getCacheDir(), VIDEO_DESTINATION));
mDuration.setVisibility(View.VISIBLE);
mAnimator.setDuration(VIDEO_MAX_DURATION).start();
}
private void onRelease() {
mCamera.stopRecording();
mAnimator.cancel();
mProgress.setProgress(0);
mDuration.setVisibility(View.GONE);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
toggleCamera.setVisibility(View.GONE);
capture.setImageResource(R.drawable.btn_record_press);
start = System.currentTimeMillis();
mHandler.sendEmptyMessageDelayed(HOLD, LONG_PRESS);
mHandler.sendEmptyMessageDelayed(RELEASE, RELEASE_TIMEOUT);
break;
case MotionEvent.ACTION_CANCEL:
toggleCamera.setVisibility(View.GONE);
capture.setImageResource(R.drawable.btn_record);
clearHandler();
if (delta() > LONG_PRESS && delta() < RELEASE_TIMEOUT) {
mHandler.sendEmptyMessage(RELEASE);
}
break;
case MotionEvent.ACTION_UP:
toggleCamera.setVisibility(View.VISIBLE);
capture.setImageResource(R.drawable.btn_record);
clearHandler();
if (delta() < LONG_PRESS) {
mHandler.sendEmptyMessage(TAP);
} else if (delta() < RELEASE_TIMEOUT) {
mHandler.sendEmptyMessage(RELEASE);
}
break;
}
return true;
}
private long delta() {
return System.currentTimeMillis() - start;
}
private void vibrate() {
Vibrator vibrator = (Vibrator) getContext().getSystemService(Context.VIBRATOR_SERVICE);
if (vibrator.hasVibrator()) {
vibrator.vibrate(25);
}
}
private void clearHandler() {
mHandler.removeMessages(TAP);
mHandler.removeMessages(HOLD);
mHandler.removeMessages(RELEASE);
}
});
mPermissionPrompt = rootView.findViewById(R.id.permission_error);
mPermissionPrompt.findViewById(R.id.request_permissions).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
requestPermissions(REQUIRED_PERMISSIONS, REQUEST_CODE_REQUIRED_PERMISSIONS);
}
});
return rootView;
}
@Override
public void onPause() {
mCamera.close();
super.onPause();
}
}
|
package d4ngle_studios.com.skatboard;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import android.graphics.Typeface;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ToggleButton;
/**
* This is the Entry Page
*/
public class EntryPage extends ActionBarActivity {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* catch unexpected error
*/
Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler());
setContentView(R.layout.activity_entry_page);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_entry_page, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {@link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
@Override
public int getCount() {
// Show 3 total pages.
return 3;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private List<ToggleButton> playerButtons;
private List<ToggleButton> numberJacksButtons;
private List<ToggleButton> valueSuitsButtons;
private List<CheckBox> additionalInfoCheckboxes;
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_entry_page, container, false);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "font/icomoon.ttf");
ToggleButton buttonPlayer1 = (ToggleButton) rootView.findViewById(R.id.imageButtonPlayer1);
ToggleButton buttonPlayer2 = (ToggleButton) rootView.findViewById(R.id.imageButtonPlayer2);
ToggleButton buttonPlayer3 = (ToggleButton) rootView.findViewById(R.id.imageButtonPlayer3);
ToggleButton buttonPlayer4 = (ToggleButton) rootView.findViewById(R.id.imageButtonPlayer4);
ToggleButton buttonNumberJacks1 = (ToggleButton) rootView.findViewById(R.id.numberJacks1);
ToggleButton buttonNumberJacks2 = (ToggleButton) rootView.findViewById(R.id.numberJacks2);
ToggleButton buttonNumberJacks3 = (ToggleButton) rootView.findViewById(R.id.numberJacks3);
ToggleButton buttonNumberJacks4 = (ToggleButton) rootView.findViewById(R.id.numberJacks4);
ToggleButton buttonValueSuitsDiamonds = (ToggleButton) rootView.findViewById(R.id.valueSuitsDiamonds);
ToggleButton buttonValueSuitsHearts = (ToggleButton) rootView.findViewById(R.id.valueSuitsHearts);
ToggleButton buttonValueSuitsSpades = (ToggleButton) rootView.findViewById(R.id.valueSuitsSpades);
ToggleButton buttonValueSuitsClubs = (ToggleButton) rootView.findViewById(R.id.valueSuitsClubs);
ToggleButton buttonValueSuitsGrand = (ToggleButton) rootView.findViewById(R.id.valueGrand);
CheckBox checkBoxHand = (CheckBox) rootView.findViewById(R.id.checkBoxHand);
CheckBox checkBoxOuvert = (CheckBox) rootView.findViewById(R.id.checkBoxOuvert);
CheckBox checkBoxSchneider = (CheckBox) rootView.findViewById(R.id.checkBoxSchneider);
CheckBox checkBoxSchneiderAngesagt = (CheckBox) rootView.findViewById(R.id.checkBoxSchneiderAngesagt);
CheckBox checkBoxSchwarz = (CheckBox) rootView.findViewById(R.id.checkBoxSchwarz);
CheckBox checkBoxSchwarzAngesagt = (CheckBox) rootView.findViewById(R.id.checkBoxSchwarzAngesagt);
final EditText resultTextfield = (EditText) rootView.findViewById(R.id.editTextPoints);
Button buttonCompute = (Button) rootView.findViewById(R.id.buttonCompute);
final TextView toggleAdditionalInfoMore = (TextView) rootView.findViewById(R.id.additional_info_more);
final TextView toggleAdditionalInfoLess = (TextView) rootView.findViewById(R.id.additional_info_less);
final GridLayout additionalGameInfo = (GridLayout) rootView.findViewById(R.id.additionalGameInfoView);
//TODO Depending on ScreenSize: !
additionalGameInfo.setVisibility(View.GONE);
playerButtons = Arrays.asList(buttonPlayer1, buttonPlayer2, buttonPlayer3, buttonPlayer4);
numberJacksButtons = Arrays.asList(buttonNumberJacks1, buttonNumberJacks2, buttonNumberJacks3, buttonNumberJacks4);
valueSuitsButtons = Arrays.asList(buttonValueSuitsDiamonds, buttonValueSuitsHearts, buttonValueSuitsSpades, buttonValueSuitsClubs, buttonValueSuitsGrand);
additionalInfoCheckboxes = Arrays.asList(checkBoxHand, checkBoxOuvert, checkBoxSchneider, checkBoxSchneiderAngesagt, checkBoxSchwarz, checkBoxSchwarzAngesagt);
for (ToggleButton b : playerButtons) {
b.setTypeface(font);
addToggleButtonOnClickListener(b, playerButtons, resultTextfield);
}
for (ToggleButton b : numberJacksButtons) {
b.setTypeface(font);
addToggleButtonOnClickListener(b, numberJacksButtons, resultTextfield);
}
for (ToggleButton b : valueSuitsButtons) {
b.setTypeface(font);
addToggleButtonOnClickListener(b, valueSuitsButtons, resultTextfield);
}
for (CheckBox c : additionalInfoCheckboxes) {
addCheckboxOnClickListener(c, resultTextfield);
}
toggleAdditionalInfoMore.setTypeface(font);
toggleAdditionalInfoMore.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
additionalGameInfo.setVisibility(View.VISIBLE);
toggleAdditionalInfoMore.setVisibility(View.GONE);
}
});
toggleAdditionalInfoLess.setTypeface(font);
toggleAdditionalInfoLess.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
additionalGameInfo.setVisibility(View.GONE);
toggleAdditionalInfoMore.setVisibility(View.VISIBLE);
}
});
buttonCompute.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateGameValue(resultTextfield);
}
});
return rootView;
}
private void addCheckboxOnClickListener(CheckBox c, final EditText resultTextfield) {
c.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
updateGameValue(resultTextfield);
}
});
}
private void updateGameValue(EditText resultTextfield) {
int happyPlayers = getHappyPlayers();
int jacksValue = getMathValue(getCheckedButton(numberJacksButtons));
int gameColorValue = getMathValue(getCheckedButton(valueSuitsButtons));
if (jacksValue != 0 && gameColorValue != 0) {
int modifier = 1 + getAdditionalGameInfo();
int result = (jacksValue + modifier) * gameColorValue;
if (happyPlayers > 1) {
result = result * 2;
}
resultTextfield.setText("" + result);
}
}
private int getAdditionalGameInfo() {
int result = 0;
for (CheckBox box : additionalInfoCheckboxes) {
if (box.isChecked()) {
result++;
}
}
return result;
}
private int getHappyPlayers() {
int count = 0;
for (ToggleButton button : playerButtons) {
if (button.isChecked()) {
count++;
}
}
return count;
}
private int getMathValue(ToggleButton button) {
if (null == button) {
return 0;
}
switch (button.getId()) {
case R.id.numberJacks1:
return 1;
case R.id.numberJacks2:
return 2;
case R.id.numberJacks3:
return 3;
case R.id.numberJacks4:
return 4;
case R.id.valueSuitsDiamonds:
return 9;
case R.id.valueSuitsHearts:
return 10;
case R.id.valueSuitsSpades:
return 11;
case R.id.valueSuitsClubs:
return 12;
case R.id.valueGrand:
return 24;
}
return 0;
}
private static boolean isVisiblePlayer(LinearLayout playersLayout, View view) {
return true;
}
private void addToggleButtonOnClickListener(ToggleButton button, final List<ToggleButton> buttonList, final EditText resultTextfield) {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateButtonGroup(v, buttonList);
updateGameValue(resultTextfield);
}
}
);
}
private void updateButtonGroup(View v, List<ToggleButton> buttonList) {
for (ToggleButton b : buttonList) {
if (b.getId() != v.getId()) {
if (buttonList.equals(playerButtons)) {
//Player Button was checked before
if (!((ToggleButton)v).isChecked()) {
b.setChecked(true);
} else {
b.setChecked(false);
}
} else {
b.setChecked(false);
}
}
}
}
private ToggleButton getCheckedButton(List<ToggleButton> buttonList) {
for (ToggleButton b : buttonList) {
if (b.isChecked()) {
return b;
}
}
return null;
}
}
}
|
package com.ibm.bi.dml.parser;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.HashMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import com.ibm.bi.dml.utils.LanguageException;
import com.ibm.json.java.JSONObject;
import com.ibm.bi.dml.parser.Statement;
public class DataExpression extends Expression {
private DataOp _opcode;
private HashMap<String, Expression> _varParams;
public DataExpression(DataOp op, HashMap<String,Expression> varParams) {
_kind = Kind.DataOp;
_opcode = op;
_varParams = varParams;
}
public DataExpression(DataOp op) {
_kind = Kind.DataOp;
_opcode = op;
_varParams = new HashMap<String,Expression>();
}
public DataExpression() {
_kind = Kind.DataOp;
_opcode = DataOp.INVALID;
_varParams = new HashMap<String,Expression>();
}
public Expression rewriteExpression(String prefix) throws LanguageException {
HashMap<String,Expression> newVarParams = new HashMap<String,Expression>();
for (String key : _varParams.keySet()){
Expression newExpr = _varParams.get(key).rewriteExpression(prefix);
newVarParams.put(key, newExpr);
}
DataExpression retVal = new DataExpression(_opcode, newVarParams);
retVal._beginLine = this._beginLine;
retVal._beginColumn = this._beginColumn;
retVal._endLine = this._endLine;
retVal._endColumn = this._endColumn;
return retVal;
}
public void setOpCode(DataOp op) {
_opcode = op;
}
public DataOp getOpCode() {
return _opcode;
}
public HashMap<String,Expression> getVarParams() {
return _varParams;
}
public void setVarParams(HashMap<String, Expression> varParams) {
_varParams = varParams;
}
public Expression getVarParam(String name) {
return _varParams.get(name);
}
public void addVarParam(String name, Expression value){
_varParams.put(name, value);
// if required, initialize values
if (_beginLine == 0) _beginLine = value.getBeginLine();
if (_beginColumn == 0) _beginColumn = value.getBeginColumn();
if (_endLine == 0) _endLine = value.getEndLine();
if (_endColumn == 0) _endColumn = value.getEndColumn();
// update values
if (_beginLine > value.getBeginLine()){
_beginLine = value.getBeginLine();
_beginColumn = value.getBeginColumn();
}
else if (_beginLine == value.getBeginLine() &&_beginColumn > value.getBeginColumn()){
_beginColumn = value.getBeginColumn();
}
if (_endLine < value.getEndLine()){
_endLine = value.getEndLine();
_endColumn = value.getEndColumn();
}
else if (_endLine == value.getEndLine() && _endColumn < value.getEndColumn()){
_endColumn = value.getEndColumn();
}
}
public void removeVarParam(String name) {
_varParams.remove(name);
}
/**
* Validate parse tree : Process Data Expression in an assignment
* statement
*
* @throws LanguageException
* @throws ParseException
* @throws IOException
*/
public void validateExpression(HashMap<String, DataIdentifier> ids, HashMap<String, ConstIdentifier> currConstVars)
throws LanguageException {
// validate all input parameters
for ( String s : getVarParams().keySet() ) {
getVarParam(s).validateExpression(ids, currConstVars);
if ( getVarParam(s).getOutput().getDataType() != DataType.SCALAR ) {
throw new LanguageException(this.printErrorLocation() + "Non-scalar data types are not supported for data expression.", LanguageException.LanguageErrorCodes.INVALID_PARAMETERS);
}
}
// IMPORTANT: for each operation, one must handle unnamed parameters
switch (this.getOpCode()) {
case READ:
if (getVarParam(Statement.DATATYPEPARAM) != null && !(getVarParam(Statement.DATATYPEPARAM) instanceof StringIdentifier))
throw new LanguageException(this.printErrorLocation() + "for read statement, parameter " + Statement.DATATYPEPARAM + " can only be a string. " +
"Valid values are: " + Statement.MATRIX_DATA_TYPE +", " + Statement.SCALAR_DATA_TYPE);
String dataTypeString = (getVarParam(Statement.DATATYPEPARAM) == null) ? null : getVarParam(Statement.DATATYPEPARAM).toString();
// disallow certain parameters while reading a scalar
if (dataTypeString != null && dataTypeString.equalsIgnoreCase(Statement.SCALAR_DATA_TYPE)){
if ( getVarParam(Statement.READROWPARAM) != null
|| getVarParam(Statement.READCOLPARAM) != null
|| getVarParam(Statement.ROWBLOCKCOUNTPARAM) != null
|| getVarParam(Statement.COLUMNBLOCKCOUNTPARAM) != null
|| getVarParam(Statement.FORMAT_TYPE) != null )
throw new LanguageException(this.printErrorLocation() + "Invalid parameters in read statement of a scalar: " +
toString() + ". Only " + Statement.VALUETYPEPARAM + " is allowed.", LanguageException.LanguageErrorCodes.INVALID_PARAMETERS);
}
JSONObject configObject = null;
// read the configuration file
String filename = null;
if (getVarParam(Statement.IO_FILENAME) instanceof ConstIdentifier){
filename = getVarParam(Statement.IO_FILENAME).toString() +".mtd";
}
else if (getVarParam(Statement.IO_FILENAME) instanceof BinaryExpression){
BinaryExpression expr = (BinaryExpression)getVarParam(Statement.IO_FILENAME);
if (expr.getKind()== Expression.Kind.BinaryOp){
Expression.BinaryOp op = expr.getOpCode();
switch (op){
case PLUS:
filename = "";
filename = fileNameCat(expr, currConstVars, filename);
// Since we have computed the value of filename, we update
// varParams with a const string value
StringIdentifier fileString = new StringIdentifier(filename);
fileString.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn());
removeVarParam(Statement.IO_FILENAME);
addVarParam(Statement.IO_FILENAME, fileString);
filename = filename + ".mtd";
break;
default:
throw new LanguageException(this.printErrorLocation() + "for InputStatement, parameter " + Statement.IO_FILENAME + " can only be const string concatenations. ");
}
}
}
else {
throw new LanguageException(this.printErrorLocation() + "for InputStatement, parameter " + Statement.IO_FILENAME + " can only be a const string or const string concatenations. ");
}
configObject = readMetadataFile(filename);
// if the MTD file exists, check the values specified in read statement match values in metadata MTD file
if (configObject != null){
for (Object key : configObject.keySet()){
if (!InputStatement.isValidParamName(key.toString(),true))
throw new LanguageException(this.printErrorLocation() + "MTD file " + filename + " contains invalid parameter name: " + key);
// if the InputStatement parameter is a constant, then verify value matches MTD metadata file
if (getVarParam(key.toString()) != null && (getVarParam(key.toString()) instanceof ConstIdentifier)
&& !getVarParam(key.toString()).toString().equalsIgnoreCase(configObject.get(key).toString()) ){
throw new LanguageException(this.printErrorLocation() + "parameter " + key.toString() + " has conflicting values in read statement definition and metadata. " +
"Config file value: " + configObject.get(key).toString() + " from MTD file. Read statement value: " + getVarParam(key.toString()));
}
else {
// if the InputStatement does not specify parameter value, then add MTD metadata file value to parameter list
if (getVarParam(key.toString()) == null){
StringIdentifier strId = new StringIdentifier(configObject.get(key).toString());
strId.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn());
addVarParam(key.toString(), strId);
}
}
}
}
else {
System.out.println("INFO: metadata file: " + new Path(filename) + " not provided");
}
dataTypeString = (getVarParam(Statement.DATATYPEPARAM) == null) ? null : getVarParam(Statement.DATATYPEPARAM).toString();
if ( dataTypeString == null || dataTypeString.equalsIgnoreCase(Statement.MATRIX_DATA_TYPE) ) {
// set data type
_output.setDataType(DataType.MATRIX);
// set number non-zeros
Expression ennz = this.getVarParam("nnz");
long nnz = -1;
if( ennz != null )
{
nnz = new Long(ennz.toString());
_output.setNnz(nnz);
}
// Following dimension checks must be done when data type = MATRIX_DATA_TYPE
// initialize size of target data identifier to UNKNOWN
_output.setDimensions(-1, -1);
if ( getVarParam(Statement.READROWPARAM) == null || getVarParam(Statement.READCOLPARAM) == null)
throw new LanguageException(this.printErrorLocation() + "Missing or incomplete dimension information in read statement", LanguageException.LanguageErrorCodes.INVALID_PARAMETERS);
if (getVarParam(Statement.READROWPARAM) instanceof ConstIdentifier && getVarParam(Statement.READCOLPARAM) instanceof ConstIdentifier) {
// these are strings that are long values
Long dim1 = (getVarParam(Statement.READROWPARAM) == null) ? null : new Long (getVarParam(Statement.READROWPARAM).toString());
Long dim2 = (getVarParam(Statement.READCOLPARAM) == null) ? null : new Long(getVarParam(Statement.READCOLPARAM).toString());
if ( dim1 <= 0 || dim2 <= 0 ) {
throw new LanguageException(this.printErrorLocation() + "Invalid dimension information in read statement", LanguageException.LanguageErrorCodes.INVALID_PARAMETERS);
}
// set dim1 and dim2 values
if (dim1 != null && dim2 != null){
_output.setDimensions(dim1, dim2);
} else if ((dim1 != null) || (dim2 != null)) {
throw new LanguageException(this.printErrorLocation() + "Partial dimension information in read statement", LanguageException.LanguageErrorCodes.INVALID_PARAMETERS);
}
}
// initialize block dimensions to UNKNOWN
_output.setBlockDimensions(-1, -1);
// find "format": 1=text, 2=binary
int format = 1; // default is "text"
if (getVarParam(Statement.FORMAT_TYPE) == null || getVarParam(Statement.FORMAT_TYPE).toString().equalsIgnoreCase("text")){
format = 1;
} else if ( getVarParam(Statement.FORMAT_TYPE).toString().equalsIgnoreCase("binary") ) {
format = 2;
} else {
throw new LanguageException(this.printErrorLocation() + "Invalid format in statement: " + this.toString());
}
if (getVarParam(Statement.ROWBLOCKCOUNTPARAM) instanceof ConstIdentifier && getVarParam(Statement.COLUMNBLOCKCOUNTPARAM) instanceof ConstIdentifier) {
Long rowBlockCount = (getVarParam(Statement.ROWBLOCKCOUNTPARAM) == null) ? null : new Long(getVarParam(Statement.ROWBLOCKCOUNTPARAM).toString());
Long columnBlockCount = (getVarParam(Statement.COLUMNBLOCKCOUNTPARAM) == null) ? null : new Long (getVarParam(Statement.COLUMNBLOCKCOUNTPARAM).toString());
if ((rowBlockCount != null) && (columnBlockCount != null)) {
_output.setBlockDimensions(rowBlockCount, columnBlockCount);
} else if ((rowBlockCount != null) || (columnBlockCount != null)) {
throw new LanguageException(this.printErrorLocation() + "Partial block dimension information in read statement", LanguageException.LanguageErrorCodes.INVALID_PARAMETERS);
} else {
_output.setBlockDimensions(-1, -1);
}
}
// block dimensions must be -1x-1 when format="text"
// and they must be 1000x1000 when format="binary"
if ( (format == 1 && (_output.getRowsInBlock() != -1 || _output.getColumnsInBlock() != -1))
|| (format == 2 && (_output.getRowsInBlock() != DMLTranslator.DMLBlockSize || _output.getColumnsInBlock() != DMLTranslator.DMLBlockSize)))
throw new LanguageException(this.printErrorLocation() + "Invalid block dimensions (" + _output.getRowsInBlock() + "," + _output.getColumnsInBlock() + ") when format=" + getVarParam(Statement.FORMAT_TYPE) + " in \"" + this.toString() + "\".");
}
else if ( dataTypeString.equalsIgnoreCase(Statement.SCALAR_DATA_TYPE)) {
_output.setDataType(DataType.SCALAR);
_output.setNnz(-1L);
}
else{
throw new LanguageException(this.printErrorLocation() + "Unknown Data Type " + dataTypeString + ". Valid values: " + Statement.SCALAR_DATA_TYPE +", " + Statement.MATRIX_DATA_TYPE, LanguageException.LanguageErrorCodes.INVALID_PARAMETERS);
}
// handle value type parameter
if (getVarParam(Statement.VALUETYPEPARAM) != null && !(getVarParam(Statement.VALUETYPEPARAM) instanceof StringIdentifier))
throw new LanguageException(this.printErrorLocation() + "for InputStatement, parameter " + Statement.VALUETYPEPARAM + " can only be a string. " +
"Valid values are: " + Statement.DOUBLE_VALUE_TYPE +", " + Statement.INT_VALUE_TYPE + ", " + Statement.BOOLEAN_VALUE_TYPE + ", " + Statement.STRING_VALUE_TYPE,
LanguageException.LanguageErrorCodes.INVALID_PARAMETERS);
// Identify the value type (used only for InputStatement)
String valueTypeString = getVarParam(Statement.VALUETYPEPARAM) == null ? null : getVarParam(Statement.VALUETYPEPARAM).toString();
if (valueTypeString != null) {
if (valueTypeString.equalsIgnoreCase(Statement.DOUBLE_VALUE_TYPE)) {
_output.setValueType(ValueType.DOUBLE);
} else if (valueTypeString.equalsIgnoreCase(Statement.STRING_VALUE_TYPE)) {
_output.setValueType(ValueType.STRING);
} else if (valueTypeString.equalsIgnoreCase(Statement.INT_VALUE_TYPE)) {
_output.setValueType(ValueType.INT);
} else if (valueTypeString.equalsIgnoreCase(Statement.BOOLEAN_VALUE_TYPE)) {
_output.setValueType(ValueType.BOOLEAN);
} else{
throw new LanguageException(this.printErrorLocation() + "Unknown Value Type " + valueTypeString
+ ". Valid values are: " + Statement.DOUBLE_VALUE_TYPE +", " + Statement.INT_VALUE_TYPE + ", " + Statement.BOOLEAN_VALUE_TYPE + ", " + Statement.STRING_VALUE_TYPE,
LanguageException.LanguageErrorCodes.INVALID_PARAMETERS);
}
} else {
_output.setValueType(ValueType.DOUBLE);
}
break;
case WRITE:
if (getVarParam(Statement.IO_FILENAME) instanceof BinaryExpression){
BinaryExpression expr = (BinaryExpression)getVarParam(Statement.IO_FILENAME);
if (expr.getKind()== Expression.Kind.BinaryOp){
Expression.BinaryOp op = expr.getOpCode();
switch (op){
case PLUS:
filename = "";
filename = fileNameCat(expr, currConstVars, filename);
// Since we have computed the value of filename, we update
// varParams with a const string value
StringIdentifier fileString = new StringIdentifier(filename);
fileString.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn());
removeVarParam(Statement.IO_FILENAME);
addVarParam(Statement.IO_FILENAME, fileString);
break;
default:
throw new LanguageException(this.printErrorLocation() + "for OutputStatement, parameter " + Statement.IO_FILENAME + " can only be a const string or const string concatenations. ");
}
}
}
if (getVarParam(Statement.FORMAT_TYPE) == null || getVarParam(Statement.FORMAT_TYPE).toString().equalsIgnoreCase("text"))
_output.setBlockDimensions(-1, -1);
else if (getVarParam(Statement.FORMAT_TYPE).toString().equalsIgnoreCase("binary"))
_output.setBlockDimensions(DMLTranslator.DMLBlockSize, DMLTranslator.DMLBlockSize);
else
throw new LanguageException(this.printErrorLocation() + "Invalid format in statement: " + this.toString());
break;
case RAND:
for (String key : _varParams.keySet()){
boolean found = false;
for (String name : RandStatement.RAND_VALID_PARAM_NAMES){
if (name.equals(key))
found = true;
}
if (!found)
throw new LanguageException(this.printErrorLocation() + "unexpected parameter \"" + key +
"\". Legal parameters for Rand statement are "
+ "(capitalization-sensitive): " + RandStatement.RAND_ROWS
+ ", " + RandStatement.RAND_COLS + ", " + RandStatement.RAND_MIN + ", " + RandStatement.RAND_MAX
+ ", " + RandStatement.RAND_SPARSITY + ", " + RandStatement.RAND_SEED + ", " + RandStatement.RAND_PDF);
}
//TODO: Leo Need to check with Doug about the data types
// DoubleIdentifiers for RAND_ROWS and RAND_COLS have already been converted into IntIdentifier in RandStatment.addExprParam()
if (getVarParam(RandStatement.RAND_ROWS) instanceof StringIdentifier || getVarParam(RandStatement.RAND_ROWS) instanceof BooleanIdentifier)
throw new LanguageException(this.printErrorLocation() + "for Rand statement " + RandStatement.RAND_ROWS + " has incorrect data type");
if (getVarParam(RandStatement.RAND_COLS) instanceof StringIdentifier || getVarParam(RandStatement.RAND_COLS) instanceof BooleanIdentifier)
throw new LanguageException(this.printErrorLocation() + "for Rand statement " + RandStatement.RAND_COLS + " has incorrect data type");
if (getVarParam(RandStatement.RAND_MAX) instanceof StringIdentifier || getVarParam(RandStatement.RAND_MAX) instanceof BooleanIdentifier)
throw new LanguageException(this.printErrorLocation() + "for Rand statement " + RandStatement.RAND_MAX + " has incorrect data type");
if (getVarParam(RandStatement.RAND_MIN) instanceof StringIdentifier || getVarParam(RandStatement.RAND_MIN) instanceof BooleanIdentifier)
throw new LanguageException(this.printErrorLocation() + "for Rand statement " + RandStatement.RAND_MIN + " has incorrect data type");
if (!(getVarParam(RandStatement.RAND_SPARSITY) instanceof DoubleIdentifier || getVarParam(RandStatement.RAND_SPARSITY) instanceof IntIdentifier))
throw new LanguageException(this.printErrorLocation() + "for Rand statement " + RandStatement.RAND_SPARSITY + " has incorrect data type");
if (!(getVarParam(RandStatement.RAND_SEED) instanceof IntIdentifier))
throw new LanguageException(this.printErrorLocation() + "for Rand statement " + RandStatement.RAND_SEED + " has incorrect data type");
if (!(getVarParam(RandStatement.RAND_PDF) instanceof StringIdentifier))
throw new LanguageException(this.printErrorLocation() + "for Rand statement " + RandStatement.RAND_PDF + " has incorrect data type");
long rowsLong = -1L, colsLong = -1L;
// HANDLE ROWS
Expression rowsExpr = getVarParam(RandStatement.RAND_ROWS);
if (rowsExpr instanceof IntIdentifier) {
if (((IntIdentifier)rowsExpr).getValue() >= 1 ) {
rowsLong = ((IntIdentifier)rowsExpr).getValue();
}
else {
throw new LanguageException(this.printErrorLocation() + "In rand statement, can only assign rows a long " +
"(integer) value >= 1 -- attempted to assign value: " + ((IntIdentifier)rowsExpr).getValue());
}
}
else if (rowsExpr instanceof DoubleIdentifier) {
if (((DoubleIdentifier)rowsExpr).getValue() >= 1 ) {
rowsLong = new Double((Math.floor(((DoubleIdentifier)rowsExpr).getValue()))).longValue();
}
else {
throw new LanguageException(this.printErrorLocation() + "In rand statement, can only assign rows a long " +
"(integer) value >= 1 -- attempted to assign value: " + rowsExpr.toString());
}
}
else if (rowsExpr instanceof DataIdentifier && !(rowsExpr instanceof IndexedIdentifier)) {
// check if the DataIdentifier variable is a ConstIdentifier
String identifierName = ((DataIdentifier)rowsExpr).getName();
if (currConstVars.containsKey(identifierName)){
// handle int constant
ConstIdentifier constValue = currConstVars.get(identifierName);
if (constValue instanceof IntIdentifier){
if (((IntIdentifier)constValue).getValue() < 1)
throw new LanguageException(this.printErrorLocation() + "In rand statement, can only assign rows a long " +
"(integer) value >= 1 -- attempted to assign value: " + constValue.toString());
// update row expr with new IntIdentifier
long roundedValue = ((IntIdentifier)constValue).getValue();
rowsExpr = new IntIdentifier(roundedValue);
rowsExpr.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn());
addVarParam(RandStatement.RAND_ROWS, rowsExpr);
rowsLong = roundedValue;
}
// handle double constant
else if (constValue instanceof DoubleIdentifier){
if (((DoubleIdentifier)constValue).getValue() < 1.0)
throw new LanguageException(this.printErrorLocation() + "In rand statement, can only assign rows a long " +
"(integer) value >= 1 -- attempted to assign value: " + constValue.toString());
// update row expr with new IntIdentifier (rounded down)
long roundedValue = new Double (Math.floor(((DoubleIdentifier)constValue).getValue())).longValue();
rowsExpr = new IntIdentifier(roundedValue);
rowsExpr.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn());
addVarParam(RandStatement.RAND_ROWS, rowsExpr);
rowsLong = roundedValue;
}
else {
// exception -- rows must be integer or double constant
throw new LanguageException(this.printErrorLocation() + "In rand statement, can only assign rows a long " +
"(integer) value >= 1 -- attempted to assign value: " + constValue.toString());
}
}
else {
// handle general expression
rowsExpr.validateExpression(ids, currConstVars);
}
}
else {
// handle general expression
rowsExpr.validateExpression(ids, currConstVars);
}
// HANDLE COLUMNS
Expression colsExpr = getVarParam(RandStatement.RAND_COLS);
if (colsExpr instanceof IntIdentifier) {
if (((IntIdentifier)colsExpr).getValue() >= 1 ) {
colsLong = ((IntIdentifier)colsExpr).getValue();
}
else {
throw new LanguageException(this.printErrorLocation() + "In rand statement, can only assign cols a long " +
"(integer) value >= 1 -- attempted to assign value: " + colsExpr.toString());
}
}
else if (colsExpr instanceof DoubleIdentifier) {
if (((DoubleIdentifier)colsExpr).getValue() >= 1 ) {
colsLong = new Double((Math.floor(((DoubleIdentifier)colsExpr).getValue()))).longValue();
}
else {
throw new LanguageException(this.printErrorLocation() + "In rand statement, can only assign rows a long " +
"(integer) value >= 1 -- attempted to assign value: " + colsExpr.toString());
}
}
else if (colsExpr instanceof DataIdentifier && !(colsExpr instanceof IndexedIdentifier)) {
// check if the DataIdentifier variable is a ConstIdentifier
String identifierName = ((DataIdentifier)colsExpr).getName();
if (currConstVars.containsKey(identifierName)){
// handle int constant
ConstIdentifier constValue = currConstVars.get(identifierName);
if (constValue instanceof IntIdentifier){
if (((IntIdentifier)constValue).getValue() < 1)
throw new LanguageException(this.printErrorLocation() + "In rand statement, can only assign cols a long " +
"(integer) value >= 1 -- attempted to assign value: " + constValue.toString());
// update col expr with new IntIdentifier
long roundedValue = ((IntIdentifier)constValue).getValue();
colsExpr = new IntIdentifier(roundedValue);
colsExpr.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn());
addVarParam(RandStatement.RAND_COLS, colsExpr);
colsLong = roundedValue;
}
// handle double constant
else if (constValue instanceof DoubleIdentifier){
if (((DoubleIdentifier)constValue).getValue() < 1)
throw new LanguageException(this.printErrorLocation() + "In rand statement, can only assign cols a long " +
"(integer) value >= 1 -- attempted to assign value: " + constValue.toString());
// update col expr with new IntIdentifier (rounded down)
long roundedValue = new Double (Math.floor(((DoubleIdentifier)constValue).getValue())).longValue();
colsExpr = new IntIdentifier(roundedValue);
colsExpr.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn());
addVarParam(RandStatement.RAND_COLS, colsExpr);
colsLong = roundedValue;
}
else {
// exception -- rows must be integer or double constant
throw new LanguageException(this.printErrorLocation() + "In rand statement, can only assign cols a long " +
"(integer) value >= 1 -- attempted to assign value: " + constValue.toString());
}
}
else {
// handle general expression
colsExpr.validateExpression(ids, currConstVars);
}
}
else {
// handle general expression
colsExpr.validateExpression(ids, currConstVars);
}
// HANDLE MIN
Expression minExpr = getVarParam(RandStatement.RAND_MIN);
// perform constant propogation
if (minExpr instanceof DataIdentifier && !(minExpr instanceof IndexedIdentifier)) {
// check if the DataIdentifier variable is a ConstIdentifier
String identifierName = ((DataIdentifier)minExpr).getName();
if (currConstVars.containsKey(identifierName)){
// handle int constant
ConstIdentifier constValue = currConstVars.get(identifierName);
if (constValue instanceof IntIdentifier){
// update min expr with new IntIdentifier
long roundedValue = ((IntIdentifier)constValue).getValue();
minExpr = new DoubleIdentifier(roundedValue);
minExpr.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn());
addVarParam(RandStatement.RAND_MIN, minExpr);
}
// handle double constant
else if (constValue instanceof DoubleIdentifier){
// update col expr with new IntIdentifier (rounded down)
double roundedValue = ((DoubleIdentifier)constValue).getValue();
minExpr = new DoubleIdentifier(roundedValue);
minExpr.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn());
addVarParam(RandStatement.RAND_MIN, minExpr);
}
else {
// exception -- rows must be integer or double constant
throw new LanguageException(this.printErrorLocation() + "In rand statement, can only assign min a numerical " +
"value -- attempted to assign: " + constValue.toString());
}
}
else {
// handle general expression
minExpr.validateExpression(ids, currConstVars);
}
}
else {
// handle general expression
minExpr.validateExpression(ids, currConstVars);
}
// HANDLE MAX
Expression maxExpr = getVarParam(RandStatement.RAND_MAX);
// perform constant propogation
if (maxExpr instanceof DataIdentifier && !(maxExpr instanceof IndexedIdentifier)) {
// check if the DataIdentifier variable is a ConstIdentifier
String identifierName = ((DataIdentifier)maxExpr).getName();
if (currConstVars.containsKey(identifierName)){
// handle int constant
ConstIdentifier constValue = currConstVars.get(identifierName);
if (constValue instanceof IntIdentifier){
// update min expr with new IntIdentifier
long roundedValue = ((IntIdentifier)constValue).getValue();
maxExpr = new DoubleIdentifier(roundedValue);
maxExpr.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn());
addVarParam(RandStatement.RAND_MAX, maxExpr);
}
// handle double constant
else if (constValue instanceof DoubleIdentifier){
// update col expr with new IntIdentifier (rounded down)
double roundedValue = ((DoubleIdentifier)constValue).getValue();
maxExpr = new DoubleIdentifier(roundedValue);
maxExpr.setAllPositions(this.getBeginLine(), this.getBeginColumn(), this.getEndLine(), this.getEndColumn());
addVarParam(RandStatement.RAND_MAX, maxExpr);
}
else {
// exception -- rows must be integer or double constant
throw new LanguageException(this.printErrorLocation() + "In rand statement, can only assign max a numerical " +
"value -- attempted to assign: " + constValue.toString());
}
}
else {
// handle general expression
maxExpr.validateExpression(ids, currConstVars);
}
}
else {
// handle general expression
maxExpr.validateExpression(ids, currConstVars);
}
_output.setFormatType(FormatType.BINARY);
_output.setDataType(DataType.MATRIX);
_output.setValueType(ValueType.DOUBLE);
_output.setDimensions(rowsLong, colsLong);
if (_output instanceof IndexedIdentifier){
((IndexedIdentifier) _output).setOriginalDimensions(_output.getDim1(), _output.getDim2());
}
//_output.computeDataType();
if (_output instanceof IndexedIdentifier){
System.out.println(this.printWarningLocation() + "Output for Rand Statement may have incorrect size information");
}
break;
default:
throw new LanguageException(this.printErrorLocation() + "Unsupported Data expression"
+ this.getOpCode(),
LanguageException.LanguageErrorCodes.INVALID_PARAMETERS);
}
return;
}
private String fileNameCat(BinaryExpression expr, HashMap<String, ConstIdentifier> currConstVars, String filename)throws LanguageException{
// Processing the left node first
if (expr.getLeft() instanceof BinaryExpression
&& ((BinaryExpression)expr.getLeft()).getKind()== BinaryExpression.Kind.BinaryOp
&& ((BinaryExpression)expr.getLeft()).getOpCode() == BinaryOp.PLUS){
filename = fileNameCat((BinaryExpression)expr.getLeft(), currConstVars, filename)+ filename;
}
else if (expr.getLeft() instanceof StringIdentifier){
filename = ((StringIdentifier)expr.getLeft()).getValue()+ filename;
}
else if (expr.getLeft() instanceof DataIdentifier
&& ((DataIdentifier)expr.getLeft()).getDataType() == Expression.DataType.SCALAR
&& ((DataIdentifier)expr.getLeft()).getKind() == Expression.Kind.Data
&& ((DataIdentifier)expr.getLeft()).getValueType() == Expression.ValueType.STRING){
String name = ((DataIdentifier)expr.getLeft()).getName();
filename = ((StringIdentifier)currConstVars.get(name)).getValue() + filename;
}
else {
throw new LanguageException(this.printErrorLocation() + "Parameter " + Statement.IO_FILENAME + " only supports a const string or const string concatenations.");
}
// Now process the right node
if (expr.getRight()instanceof BinaryExpression
&& ((BinaryExpression)expr.getRight()).getKind()== BinaryExpression.Kind.BinaryOp
&& ((BinaryExpression)expr.getRight()).getOpCode() == BinaryOp.PLUS){
filename = filename + fileNameCat((BinaryExpression)expr.getRight(), currConstVars, filename);
}
else if (expr.getRight() instanceof StringIdentifier){
filename = filename + ((StringIdentifier)expr.getRight()).getValue();
}
else if (expr.getRight() instanceof DataIdentifier
&& ((DataIdentifier)expr.getRight()).getDataType() == Expression.DataType.SCALAR
&& ((DataIdentifier)expr.getRight()).getKind() == Expression.Kind.Data
&& ((DataIdentifier)expr.getRight()).getValueType() == Expression.ValueType.STRING){
String name = ((DataIdentifier)expr.getRight()).getName();
filename = filename + ((StringIdentifier)currConstVars.get(name)).getValue();
}
else {
throw new LanguageException(this.printErrorLocation() + "Parameter " + Statement.IO_FILENAME + " only supports a const string or const string concatenations.");
}
return filename;
}
public String toString() {
StringBuffer sb = new StringBuffer(_opcode.toString() + "(");
for (String key : _varParams.keySet()){
sb.append("," + key + "=" + _varParams.get(key));
}
sb.append(" )");
return sb.toString();
}
@Override
public VariableSet variablesRead() {
VariableSet result = new VariableSet();
for (String s : _varParams.keySet()) {
result.addVariables ( _varParams.get(s).variablesRead() );
}
return result;
}
@Override
public VariableSet variablesUpdated() {
VariableSet result = new VariableSet();
for (String s : _varParams.keySet()) {
result.addVariables ( _varParams.get(s).variablesUpdated() );
}
result.addVariable(((DataIdentifier)this.getOutput()).getName(), (DataIdentifier)this.getOutput());
return result;
}
public JSONObject readMetadataFile(String filename) throws LanguageException {
JSONObject retVal = null;
boolean exists = false;
FileSystem fs = null;
try {
fs = FileSystem.get(new Configuration());
} catch (Exception e){
e.printStackTrace();
throw new LanguageException(this.printErrorLocation() + "could not read the configuration file.");
}
Path pt = new Path(filename);
try {
if (fs.exists(pt)){
exists = true;
}
} catch (Exception e){
exists = false;
}
try {
// CASE: filename is a directory -- process as a directory
if (exists && fs.getFileStatus(pt).isDir()){
// read directory contents
retVal = new JSONObject();
FileStatus[] stats = fs.listStatus(pt);
for(FileStatus stat : stats){
Path childPath = stat.getPath(); // gives directory name
if (childPath.getName().startsWith("part")){
BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(childPath)));
JSONObject childObj = JSONObject.parse(br);
for (Object key : childObj.keySet()){
retVal.put(key, childObj.get(key));
}
}
}
}
// CASE: filename points to a file
else if (exists){
BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(pt)));
retVal = JSONObject.parse(br);
}
return retVal;
} catch (Exception e){
throw new LanguageException(this.printErrorLocation() + "error reading and/or parsing MTD file with path " + pt.toString());
}
}
} // end class
|
package edu.usc.parknpay.owner;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import edu.usc.parknpay.R;
import edu.usc.parknpay.TemplateActivity;
import edu.usc.parknpay.database.ParkingSpot;
import edu.usc.parknpay.database.User;
public class AddSpotActivity extends TemplateActivity {
EditText street, city, state, zipCode, notes;
CheckBox handicapped;
Spinner size, cancel;
Button doneButton;
ImageView parkingSpotPhoto;
Uri selectedImage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_spot);
super.onCreateDrawer();
toolbarSetup();
initializeEdits();
addListeners();
setSpinners();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return false;
}
protected void toolbarSetup() {
Toolbar mToolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolBar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Add a Space");
}
protected void initializeEdits() {
street = (EditText) findViewById(R.id.streetEdit);
city = (EditText) findViewById(R.id.cityEdit);
state = (EditText) findViewById(R.id.stateEdit);
zipCode = (EditText) findViewById(R.id.zipEdit);
notes = (EditText) findViewById(R.id.notesEdit);
handicapped = (CheckBox) findViewById(R.id.checkBox);
size = (Spinner) findViewById(R.id.sizeSpinner);
cancel = (Spinner) findViewById(R.id.cancelSpinner);
doneButton = (Button) findViewById(R.id.button);
parkingSpotPhoto = (ImageView) findViewById(R.id.spotPhoto);
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == RESULT_OK){
}
break;
case 1:
if(resultCode == RESULT_OK){
selectedImage = imageReturnedIntent.getData();
parkingSpotPhoto.setImageURI(selectedImage);
}
break;
}
}
protected void setSpinners(){
List<String> sizeArray = new ArrayList<>();
sizeArray.add("Normal");
sizeArray.add("Compact");
sizeArray.add("SUV");
sizeArray.add("Truck");
ArrayAdapter<String> sizeAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, sizeArray);
sizeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
size.setAdapter(sizeAdapter);
List<String> cancelArray = new ArrayList<>();
cancelArray.add("Policy 1");
cancelArray.add("Policy 2");
cancelArray.add("Policy 3");
ArrayAdapter<String> cancelAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, cancelArray);
cancelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
cancel.setAdapter(cancelAdapter);
}
public void addSpot(View view) {
if (selectedImage == null) {
Toast.makeText(AddSpotActivity.this, "Please upload a photo.", Toast.LENGTH_SHORT).show();
return;
}
String notesFinal = notes.getText().toString();
String sizeFinal = size.getSelectedItem().toString();
String cancelFinal = cancel.getSelectedItem().toString();
boolean handicappedFinal = handicapped.isChecked();
DatabaseReference Ref = FirebaseDatabase.getInstance().getReference();
String parkingSpotID = UUID.randomUUID().toString();
String userId = User.getInstance().getId();
StorageReference firebaseStorage = FirebaseStorage.getInstance().getReference().child(userId + "/Spots/" + parkingSpotID);
firebaseStorage.putFile(selectedImage);
// Parking-Spots table
ParkingSpot spot = new ParkingSpot("Swaggin spot", userId, sizeFinal, 0, handicappedFinal, notesFinal, cancelFinal);
Ref.child("Parking-Spots").child(parkingSpotID).setValue(spot);
// Add to User with list of parking spots table
Ref.child("Owner-To-Spots").child(userId).child(parkingSpotID).setValue(true);
Intent intent = new Intent(getApplicationContext(), OwnerMainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
protected void addListeners() {
parkingSpotPhoto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
}
});
}
}
|
package fi.jyu.ln.luontonurkka;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.InputStream;
import java.net.URL;
import java.util.Iterator;
import fi.jyu.ln.luontonurkka.tools.DownloadImageTask;
import fi.jyu.ln.luontonurkka.tools.DownloadTextTask;
import fi.jyu.ln.luontonurkka.tools.OnTaskCompleted;
import static fi.jyu.ln.luontonurkka.R.id.species_content_text;
import static fi.jyu.ln.luontonurkka.R.id.species_toolbar_img;
import static fi.jyu.ln.luontonurkka.R.id.species_toolbar_layout;
public class SpeciesActivity extends AppCompatActivity {
Species species;
private static final int DESCRIPTION_LENGTH = 1000;
private String speciesDesc;
private Bitmap speciesImg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_species_view);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// get species from intent
species = (Species)getIntent().getSerializableExtra("Species");
// set title to species name
CollapsingToolbarLayout layout = (CollapsingToolbarLayout)this.findViewById(species_toolbar_layout);
layout.setTitle(species.getName());
layout.setExpandedTitleColor(Color.WHITE);
layout.setCollapsedTitleTextColor(Color.WHITE);
// get img
/*final ImageView imgView = (ImageView)this.findViewById(species_toolbar_img);
imgView.setImageResource(R.drawable.kissa);*/
String id = species.getIdFin();
if(id.length() < 1)
id = species.getIdEng();
OnTaskCompleted task = new OnTaskCompleted() {
@Override
public void onTaskCompleted(String result) {
Log.d(getClass().toString(), "TEXT");
if(result != null)
setTextComplete(result);
}
@Override
public void onTaskCompleted(Bitmap result) {
Log.d(getClass().toString(), "IMG");
if(result != null)
setImgComplete(result);
}
};
new DownloadTextTask(task).execute("https://fi.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&pageids=" + id);
new DownloadImageTask(task).execute("https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_March_2010-1.jpg");
/*// get text from wikipage
final TextView contentTextView = (TextView)this.findViewById(species_content_text);
contentTextView.setText("Lataa...");
OnTaskCompleted task = new OnTaskCompleted() {
@Override
public void onTaskCompleted(String result) {
try {
final JSONObject obj = new JSONObject(result);
Iterator<String> keys = obj.getJSONObject("query").getJSONObject("pages").keys();
if (keys.hasNext()) {
final String firstKey = (String)keys.next();
String desc = obj.getJSONObject("query").getJSONObject("pages").getJSONObject(firstKey).getString("extract");
if(desc.length() > DESCRIPTION_LENGTH) {
desc = desc.substring(0,DESCRIPTION_LENGTH) + "...";
}
contentTextView.setText(desc);
Button wikiButton = (Button)findViewById(R.id.species_content_button_wiki);
wikiButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openWikiPage(firstKey);
}
});
wikiButton.setVisibility(View.VISIBLE);
}
} catch (JSONException je) {
Log.w(getClass().toString(), je.getMessage());
}
}
@Override
public void onTaskCompleted(Bitmap result) {
}
};
new DownloadTextTask(task).execute("https://fi.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=" + species.getName());*/
}
protected void openWikiPage(String pageId) {
Intent wikiIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://fi.wikipedia.org/?curid=" + pageId));
startActivity(wikiIntent);
}
private void setTextComplete(String text) {
speciesDesc = text;
checkLoadingComplete();
}
private void setImgComplete(Bitmap img) {
speciesImg = img;
checkLoadingComplete();
}
private void checkLoadingComplete() {
if(speciesImg != null && speciesDesc != null) {
TextView textView = (TextView)findViewById(R.id.species_content_text);
textView.setText(speciesDesc);
ImageView imgView = (ImageView)findViewById(R.id.species_toolbar_img);
imgView.setImageBitmap(speciesImg);
ProgressBar loadingBar = (ProgressBar)findViewById(R.id.species_loading);
Button wikiButton = (Button)findViewById(R.id.species_content_button_wiki);
loadingBar.setVisibility(View.INVISIBLE);
wikiButton.setVisibility(View.VISIBLE);
textView.setVisibility(View.VISIBLE);
imgView.setVisibility(View.VISIBLE);
}
}
}
|
package org.wikipedia.theme;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.content.ContextCompat;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import com.google.android.material.button.MaterialButton;
import org.wikipedia.Constants;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.activity.FragmentUtil;
import org.wikipedia.analytics.AppearanceChangeFunnel;
import org.wikipedia.events.WebViewInvalidateEvent;
import org.wikipedia.page.ExtendedBottomSheetDialogFragment;
import org.wikipedia.page.PageActivity;
import org.wikipedia.settings.Prefs;
import org.wikipedia.util.DimenUtil;
import org.wikipedia.util.FeedbackUtil;
import org.wikipedia.util.ResourceUtil;
import org.wikipedia.views.DiscreteSeekBar;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.Unbinder;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.functions.Consumer;
import static org.wikipedia.Constants.INTENT_EXTRA_INVOKE_SOURCE;
public class ThemeChooserDialog extends ExtendedBottomSheetDialogFragment {
@BindView(R.id.buttonDecreaseTextSize) TextView buttonDecreaseTextSize;
@BindView(R.id.buttonIncreaseTextSize) TextView buttonIncreaseTextSize;
@BindView(R.id.text_size_percent) TextView textSizePercent;
@BindView(R.id.text_size_seek_bar) DiscreteSeekBar textSizeSeekBar;
@BindView(R.id.button_font_family_sans_serif) MaterialButton buttonFontFamilySansSerif;
@BindView(R.id.button_font_family_serif) MaterialButton buttonFontFamilySerif;
@BindView(R.id.button_theme_light) MaterialButton buttonThemeLight;
@BindView(R.id.button_theme_dark) MaterialButton buttonThemeDark;
@BindView(R.id.button_theme_black) MaterialButton buttonThemeBlack;
@BindView(R.id.button_theme_sepia) MaterialButton buttonThemeSepia;
@BindView(R.id.theme_chooser_dark_mode_dim_images_switch) SwitchCompat dimImagesSwitch;
@BindView(R.id.theme_chooser_match_system_theme_switch) SwitchCompat matchSystemThemeSwitch;
@BindView(R.id.font_change_progress_bar) ProgressBar fontChangeProgressBar;
public interface Callback {
void onToggleDimImages();
void onCancel();
}
private enum FontSizeAction { INCREASE, DECREASE, RESET }
private WikipediaApp app;
private Unbinder unbinder;
private AppearanceChangeFunnel funnel;
private Constants.InvokeSource invokeSource;
private CompositeDisposable disposables = new CompositeDisposable();
private static final int ACTIVATE_BUTTON_STROKE_WIDTH = DimenUtil.roundedDpToPx(2f);
private boolean updatingFont = false;
public static ThemeChooserDialog newInstance(@NonNull Constants.InvokeSource source) {
ThemeChooserDialog dialog = new ThemeChooserDialog();
Bundle args = new Bundle();
args.putSerializable(INTENT_EXTRA_INVOKE_SOURCE, source);
dialog.setArguments(args);
return dialog;
}
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dialog_theme_chooser, container);
unbinder = ButterKnife.bind(this, rootView);
buttonDecreaseTextSize.setOnClickListener(new FontSizeButtonListener(FontSizeAction.DECREASE));
buttonIncreaseTextSize.setOnClickListener(new FontSizeButtonListener(FontSizeAction.INCREASE));
FeedbackUtil.setButtonLongPressToast(buttonDecreaseTextSize, buttonIncreaseTextSize);
buttonThemeLight.setOnClickListener(new ThemeButtonListener(Theme.LIGHT));
buttonThemeDark.setOnClickListener(new ThemeButtonListener(Theme.DARK));
buttonThemeBlack.setOnClickListener(new ThemeButtonListener(Theme.BLACK));
buttonThemeSepia.setOnClickListener(new ThemeButtonListener(Theme.SEPIA));
buttonFontFamilySansSerif.setOnClickListener(new FontFamilyListener());
buttonFontFamilySerif.setOnClickListener(new FontFamilyListener());
textSizeSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int value, boolean fromUser) {
if (!fromUser) {
return;
}
int currentMultiplier = Prefs.getTextSizeMultiplier();
boolean changed = app.setFontSizeMultiplier(textSizeSeekBar.getValue());
if (changed) {
updatingFont = true;
updateFontSize();
funnel.logFontSizeChange(currentMultiplier, Prefs.getTextSizeMultiplier());
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
updateComponents();
if (!(requireActivity() instanceof PageActivity)) {
disableBackgroundDim();
}
return rootView;
}
@Override
public void onStart() {
super.onStart();
BottomSheetBehavior.from((View) getView().getParent()).setPeekHeight(DimenUtil
.roundedDpToPx(DimenUtil.getDimension(R.dimen.themeChooserSheetPeekHeight)));
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = WikipediaApp.getInstance();
invokeSource = (Constants.InvokeSource) getArguments().getSerializable(INTENT_EXTRA_INVOKE_SOURCE);
disposables.add(app.getBus().subscribe(new EventBusConsumer()));
funnel = new AppearanceChangeFunnel(app, app.getWikiSite(), invokeSource);
}
@Override
public void onDestroyView() {
super.onDestroyView();
unbinder.unbind();
}
@Override
public void onDestroy() {
super.onDestroy();
disposables.clear();
}
@Override
public void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
if (callback() != null) {
// noinspection ConstantConditions
callback().onCancel();
}
}
@OnCheckedChanged(R.id.theme_chooser_dark_mode_dim_images_switch)
void onToggleDimImages(boolean enabled) {
if (enabled == Prefs.shouldDimDarkModeImages()) {
return;
}
Prefs.setDimDarkModeImages(enabled);
if (callback() != null) {
// noinspection ConstantConditions
callback().onToggleDimImages();
}
}
@OnCheckedChanged(R.id.theme_chooser_match_system_theme_switch)
void onToggleMatchSystemTheme(boolean enabled) {
if (enabled == Prefs.shouldMatchSystemTheme()) {
return;
}
Prefs.setMatchSystemTheme(enabled);
Theme currentTheme = app.getCurrentTheme();
if (isMatchingSystemThemeEnabled()) {
switch (WikipediaApp.getInstance().getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK) {
case Configuration.UI_MODE_NIGHT_YES:
if (!WikipediaApp.getInstance().getCurrentTheme().isDark()) {
app.setCurrentTheme(!app.unmarshalTheme(Prefs.getPreviousThemeId()).isDark() ? Theme.BLACK : app.unmarshalTheme(Prefs.getPreviousThemeId()));
Prefs.setPreviousThemeId(currentTheme.getMarshallingId());
}
break;
case Configuration.UI_MODE_NIGHT_NO:
if (WikipediaApp.getInstance().getCurrentTheme().isDark()) {
app.setCurrentTheme(app.unmarshalTheme(Prefs.getPreviousThemeId()).isDark() ? Theme.LIGHT : app.unmarshalTheme(Prefs.getPreviousThemeId()));
Prefs.setPreviousThemeId(currentTheme.getMarshallingId());
}
break;
default:
break;
}
}
conditionallyDisableThemeButtons();
}
@SuppressWarnings("checkstyle:magicnumber")
private void conditionallyDisableThemeButtons() {
buttonThemeLight.setAlpha((isMatchingSystemThemeEnabled() && (WikipediaApp.getInstance().getCurrentTheme().isDark())) ? 0.2f : 1.0f);
buttonThemeSepia.setAlpha((isMatchingSystemThemeEnabled() && (WikipediaApp.getInstance().getCurrentTheme().isDark())) ? 0.2f : 1.0f);
buttonThemeDark.setAlpha((isMatchingSystemThemeEnabled() && (!WikipediaApp.getInstance().getCurrentTheme().isDark())) ? 0.2f : 1.0f);
buttonThemeBlack.setAlpha((isMatchingSystemThemeEnabled() && (!WikipediaApp.getInstance().getCurrentTheme().isDark())) ? 0.2f : 1.0f);
buttonThemeLight.setEnabled(!isMatchingSystemThemeEnabled() || (!WikipediaApp.getInstance().getCurrentTheme().isDark()));
buttonThemeSepia.setEnabled(!isMatchingSystemThemeEnabled() || (!WikipediaApp.getInstance().getCurrentTheme().isDark()));
buttonThemeDark.setEnabled(!isMatchingSystemThemeEnabled() || (WikipediaApp.getInstance().getCurrentTheme().isDark()));
buttonThemeBlack.setEnabled(!isMatchingSystemThemeEnabled() || (WikipediaApp.getInstance().getCurrentTheme().isDark()));
}
private boolean isMatchingSystemThemeEnabled() {
return Prefs.shouldMatchSystemTheme() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q;
}
private void updateComponents() {
updateFontSize();
updateFontFamily();
updateThemeButtons();
updateDimImagesSwitch();
updateMatchSystemThemeSwitch();
}
private void updateMatchSystemThemeSwitch() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
matchSystemThemeSwitch.setVisibility(View.VISIBLE);
matchSystemThemeSwitch.setChecked(Prefs.shouldMatchSystemTheme());
conditionallyDisableThemeButtons();
} else {
matchSystemThemeSwitch.setVisibility(View.GONE);
}
}
@SuppressWarnings("checkstyle:magicnumber")
private void updateFontSize() {
int mult = Prefs.getTextSizeMultiplier();
textSizeSeekBar.setValue(mult);
String percentStr = getString(R.string.text_size_percent,
(int) (100 * (1 + mult * DimenUtil.getFloat(R.dimen.textSizeMultiplierFactor))));
textSizePercent.setText(mult == 0
? getString(R.string.text_size_percent_default, percentStr) : percentStr);
if (updatingFont) {
fontChangeProgressBar.setVisibility(View.VISIBLE);
} else {
fontChangeProgressBar.setVisibility(View.GONE);
}
}
private void updateFontFamily() {
buttonFontFamilySansSerif.setStrokeWidth(Prefs.getFontFamily().equals(buttonFontFamilySansSerif.getTag()) ? ACTIVATE_BUTTON_STROKE_WIDTH : 0);
buttonFontFamilySerif.setStrokeWidth(Prefs.getFontFamily().equals(buttonFontFamilySerif.getTag()) ? ACTIVATE_BUTTON_STROKE_WIDTH : 0);
}
private void updateThemeButtons() {
updateThemeButtonStroke(buttonThemeLight, app.getCurrentTheme() == Theme.LIGHT);
updateThemeButtonStroke(buttonThemeSepia, app.getCurrentTheme() == Theme.SEPIA);
updateThemeButtonStroke(buttonThemeDark, app.getCurrentTheme() == Theme.DARK);
updateThemeButtonStroke(buttonThemeBlack, app.getCurrentTheme() == Theme.BLACK);
}
private void updateThemeButtonStroke(@NonNull MaterialButton button, boolean selected) {
button.setStrokeWidth(selected ? ACTIVATE_BUTTON_STROKE_WIDTH : 0);
button.setClickable(!selected);
}
private void updateDimImagesSwitch() {
dimImagesSwitch.setChecked(Prefs.shouldDimDarkModeImages());
dimImagesSwitch.setEnabled(app.getCurrentTheme().isDark());
dimImagesSwitch.setTextColor(dimImagesSwitch.isEnabled()
? ResourceUtil.getThemedColor(requireContext(), R.attr.section_title_color)
: ContextCompat.getColor(requireContext(), R.color.black26));
}
private final class ThemeButtonListener implements View.OnClickListener {
private Theme theme;
private ThemeButtonListener(Theme theme) {
this.theme = theme;
}
@Override
public void onClick(View v) {
if (app.getCurrentTheme() != theme) {
funnel.logThemeChange(app.getCurrentTheme(), theme);
app.setCurrentTheme(theme);
}
}
}
private final class FontFamilyListener implements View.OnClickListener {
@Override
public void onClick(View v) {
if (v.getTag() != null) {
String newFontFamily = (String) v.getTag();
funnel.logFontThemeChange(Prefs.getFontFamily(), newFontFamily);
app.setFontFamily(newFontFamily);
}
}
}
private final class FontSizeButtonListener implements View.OnClickListener {
private FontSizeAction action;
private FontSizeButtonListener(FontSizeAction action) {
this.action = action;
}
@Override
public void onClick(View view) {
boolean changed = false;
int currentMultiplier = Prefs.getTextSizeMultiplier();
if (action == FontSizeAction.INCREASE) {
changed = app.setFontSizeMultiplier(Prefs.getTextSizeMultiplier() + 1);
} else if (action == FontSizeAction.DECREASE) {
changed = app.setFontSizeMultiplier(Prefs.getTextSizeMultiplier() - 1);
} else if (action == FontSizeAction.RESET) {
changed = app.setFontSizeMultiplier(0);
}
if (changed) {
updatingFont = true;
updateFontSize();
funnel.logFontSizeChange(currentMultiplier, Prefs.getTextSizeMultiplier());
}
}
}
private class EventBusConsumer implements Consumer<Object> {
@Override
public void accept(Object event) {
if (event instanceof WebViewInvalidateEvent) {
updatingFont = false;
updateComponents();
}
}
}
@Nullable
public Callback callback() {
return FragmentUtil.getCallback(this, Callback.class);
}
}
|
package org.pm4j.core.pm.impl;
import static org.pm4j.core.pm.api.PmCacheApi.clearPmCache;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.validation.metadata.BeanDescriptor;
import javax.validation.metadata.ConstraintDescriptor;
import javax.validation.metadata.PropertyDescriptor;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pm4j.common.cache.CacheStrategy;
import org.pm4j.common.cache.CacheStrategyNoCache;
import org.pm4j.common.converter.string.StringConverter;
import org.pm4j.common.converter.string.StringConverterParseException;
import org.pm4j.common.converter.value.ValueConverter;
import org.pm4j.common.converter.value.ValueConverterDefault;
import org.pm4j.common.expr.Expression.SyntaxVersion;
import org.pm4j.common.util.CompareUtil;
import org.pm4j.common.util.collection.MapUtil;
import org.pm4j.common.util.reflection.BeanAttrAccessor;
import org.pm4j.common.util.reflection.BeanAttrAccessorImpl;
import org.pm4j.common.util.reflection.ClassUtil;
import org.pm4j.common.util.reflection.GenericTypeUtil;
import org.pm4j.common.util.reflection.ReflectionException;
import org.pm4j.core.exception.PmConverterException;
import org.pm4j.core.exception.PmResourceData;
import org.pm4j.core.exception.PmRuntimeException;
import org.pm4j.core.exception.PmValidationException;
import org.pm4j.core.pm.PmAttr;
import org.pm4j.core.pm.PmAttrString;
import org.pm4j.core.pm.PmBean;
import org.pm4j.core.pm.PmCommandDecorator;
import org.pm4j.core.pm.PmConstants;
import org.pm4j.core.pm.PmDataInput;
import org.pm4j.core.pm.PmEvent;
import org.pm4j.core.pm.PmMessage;
import org.pm4j.core.pm.PmMessage.Severity;
import org.pm4j.core.pm.PmObject;
import org.pm4j.core.pm.PmOption;
import org.pm4j.core.pm.PmOptionSet;
import org.pm4j.core.pm.annotation.PmAttrCfg;
import org.pm4j.core.pm.annotation.PmCacheCfg2;
import org.pm4j.core.pm.annotation.PmAttrCfg.HideIf;
import org.pm4j.core.pm.annotation.PmAttrCfg.Restriction;
import org.pm4j.core.pm.annotation.PmAttrCfg.Validate;
import org.pm4j.core.pm.annotation.PmCacheCfg;
import org.pm4j.core.pm.annotation.PmCacheCfg.CacheMode;
import org.pm4j.core.pm.annotation.PmCacheCfg2.Cache;
import org.pm4j.core.pm.annotation.PmCacheCfg2.Observe;
import org.pm4j.core.pm.annotation.PmCommandCfg;
import org.pm4j.core.pm.annotation.PmCommandCfg.BEFORE_DO;
import org.pm4j.core.pm.annotation.PmOptionCfg;
import org.pm4j.core.pm.annotation.PmOptionCfg.NullOption;
import org.pm4j.core.pm.annotation.PmTitleCfg;
import org.pm4j.core.pm.api.PmCacheApi;
import org.pm4j.core.pm.api.PmCacheApi.CacheKind;
import org.pm4j.core.pm.api.PmEventApi;
import org.pm4j.core.pm.api.PmExpressionApi;
import org.pm4j.core.pm.api.PmLocalizeApi;
import org.pm4j.core.pm.api.PmMessageApi;
import org.pm4j.core.pm.api.PmMessageUtil;
import org.pm4j.core.pm.impl.InternalPmCacheCfgUtil.CacheMetaData;
import org.pm4j.core.pm.impl.cache.CacheStrategyBase;
import org.pm4j.core.pm.impl.cache.CacheStrategyRequest;
import org.pm4j.core.pm.impl.converter.PmConverterErrorMessage;
import org.pm4j.core.pm.impl.converter.PmConverterOptionBased;
import org.pm4j.core.pm.impl.options.GenericOptionSetDef;
import org.pm4j.core.pm.impl.options.OptionSetDefNoOption;
import org.pm4j.core.pm.impl.options.PmOptionSetDef;
import org.pm4j.core.pm.impl.pathresolver.PassThroughPathResolver;
import org.pm4j.core.pm.impl.pathresolver.PathResolver;
import org.pm4j.core.pm.impl.pathresolver.PmExpressionPathResolver;
import org.pm4j.navi.NaviLink;
/**
* <p> Basic implementation for PM attributes. </p>
*
* <p> Note: If you are looking for a generic PmAttr implementation
* for use in client code, use PmAttrImpl, not this base class. </p>
*
* TODOC:
*
* @param <T_PM_VALUE>
* The external PM api type.<br>
* Examples:<br>
* For a string field: the type {@link String};<br>
* For a bean reference: the PM class for the referenced bean.
* @param <T_BEAN_VALUE>
* The bean field type. <br>
* Examples:<br>
* For a string field: the type {@link String};<br>
* For a reference: The referenced class.
*
* @author olaf boede
*/
public abstract class PmAttrBase<T_PM_VALUE, T_BEAN_VALUE>
extends PmDataInputBase
implements PmAttr<T_PM_VALUE> {
private static final Log LOG = LogFactory.getLog(PmAttrBase.class);
/**
* Indicates if the value was explicitly set. This information is especially
* important for the default value logic. Default values may have only effect
* on values that are not explicitly set.
*/
private boolean valueChangedBySetValue = false;
/**
* Contains optional attribute data that in most cases doesn't exist for usual
* bean attributes.
*/
/* package */ PmAttrDataContainer<T_PM_VALUE, T_BEAN_VALUE> dataContainer;
/**
* Keeps a reference to the entered value in case of buffered data entry.
*/
private Object bufferedValue = UNKNOWN_VALUE_INDICATOR;
/** A cache member. Is only used in case for {@link ValueAccessReflection}. */
private PmBean<Object> parentPmBean;
/** The decorators to execute before and after setting the attribute value. */
private Collection<PmCommandDecorator> valueChangeDecorators = Collections.emptyList();
/** Converts between external and backing values. */
private ValueConverter<T_PM_VALUE, T_BEAN_VALUE> valueConverter;
/** Converts between external value type and its string representation. */
private StringConverter<T_PM_VALUE> stringConverter;
/** A lightweight helper that provides converter operation context information. */
private AttrConverterCtxt converterCtxt = makeConverterCtxt();
/**
* @param pmParent The PM hierarchy parent.
*/
public PmAttrBase(PmObject pmParent) {
super(pmParent);
}
@Override
public final PmOptionSet getOptionSet() {
MetaData md = getOwnMetaData();
Object ov = md.optionsCache.cacheStrategy.getCachedValue(this);
if (ov != CacheStrategy.NO_CACHE_VALUE) {
// just return the cache hit (if there was one)
return (PmOptionSet) ov;
}
else {
try {
return md.optionsCache.cacheStrategy.setAndReturnCachedValue(this, getOptionSetImpl());
}
catch (RuntimeException e) {
PmRuntimeException forwardedEx = PmRuntimeException.asPmRuntimeException(this, e);
// TODO olaf: Logging is required here for JSF.
// Move to AttrToJsfViewConnectorWithValueChangeListener.
LOG.error("getOptionSet failed", forwardedEx);
throw forwardedEx;
}
}
}
/**
* Override this method to provide a specific option set.
* <p>
* Alternatively you may use {@link PmOptionCfg} in combination with an
* overridden {@link #getOptionValues()} method.
*
* @return An option set. In case of no options an empty option set.
*/
protected PmOptionSet getOptionSetImpl() {
PmOptionSet os = getOwnMetaData().optionSetDef.makeOptions(this);
return os;
}
/**
* A combination of {@link PmOptionCfg} and the implementation of this method
* may be used to define the options for the attribute value.
* <p>
* The id, title and value attributes of the annotation will be applied to
* the items of the provided object set to create the option set.
*
* @return The object to generate the options from.<br>
* May return <code>null</code> in case of no option values.
*/
// XXX olaf: is currently public because of the package location of OptionSetDefBase.
public Iterable<?> getOptionValues() {
throw new PmRuntimeException(this, "Please don't forget to implement getOptionValues() if you don't specifiy the options in the @PmOptions annotation.");
}
// XXX olaf: is currently public because of the package location of OptionSetDefBase.
/**
* Provides the attribute type specific default definition, if an option set
* should contain a <code>null</code> option definition or not.
* <p>
* Usualy non-list attributes provide the default
* {@link PmOptionCfg.NullOption#FOR_OPTIONAL_ATTR} and list attributes
* {@link PmOptionCfg.NullOption#NO}.
*
* @return The attribute type specific null-option generation default value.
*/
public NullOption getNullOptionDefault() {
return NullOption.FOR_OPTIONAL_ATTR;
}
/**
* Checks first if the PM is enabled.<br>
* Only if that's the case the logic provided by {@link #isPmReadonlyImpl()}
* will be used.
*/
@Override
public final boolean isRequired() {
// Required embedded attributes get only really required if their embedding
// attribute is also required.
MetaData md = getOwnMetaData();
if (md.embeddedAttr && !md.deprValidation &&
!((PmAttr<?>)getPmParent()).isRequired()) {
return false;
}
return isPmEnabled() &&
isRequiredImpl();
}
/**
* Subclasses may implement here specific logic.
* <p>
* Please notice that the result of the external {@link #isRequired()} method
* is influenced by the {@link #isPmEnabled()} result: A disabled attribute is
* automatically NOT required.
* <p>
* The default implementation provides for attributes that are embedded in another
* attribute the required state of the embedding parent attribute.
*
* @return <code>true</code> if the attribute is required.
*/
protected boolean isRequiredImpl() {
boolean required = false;
MetaData md = getOwnMetaData();
switch (md.valueRestriction) {
case REQUIRED: required = true; break;
case REQUIRED_IF_VISIBLE: required = isPmVisible(); break;
case READ_ONLY: required = false; break;
default: required = md.required; break;
}
return required;
}
@Override
protected boolean isPmReadonlyImpl() {
MetaData md = getOwnMetaData();
return super.isPmReadonlyImpl() ||
// A disabled parent attribute switches each child attribute to be read-only.
// Is not implemented in isPmEnabledImpl() to preserve the contract that
// the domain developer 'owns' that method completely.
(!md.deprValidation &&
md.embeddedAttr && !getPmParent().isPmEnabled());
}
@Override
public final boolean isPmEnabled() {
// link enable status to read only even if the default impl of isPmEnabledImpl is overwritten
// The read-only check is done first because some domain implementations of isPmEnabledImpl()
// are implemented in a way that fails under some read-only conditions (e.g. in case of a missing backing bean).
return !isPmReadonly() && super.isPmEnabled();
}
// TODO olaf: move common logic to isPmVisible. Additional effort: ensure that isPmVisible stays final
// for all PM sub classes.
@Override
protected boolean isPmVisibleImpl() {
boolean visible = super.isPmVisibleImpl();
if (visible && getOwnMetaData().hideIfEmptyValue) {
visible = !isEmptyValue(getValue());
}
if (visible && getOwnMetaData().hideIfDefaultValue) {
visible = !ObjectUtils.equals(getValue(), getDefaultValue());
}
return visible;
}
@Override
protected void getPmStyleClassesImpl(Set<String> styleClassSet) {
super.getPmStyleClassesImpl(styleClassSet);
if (isRequired()) {
styleClassSet.add(STYLE_CLASS_REQUIRED);
}
}
@Override
public void clearPmInvalidValues() {
boolean wasValid = isPmValid();
if (dataContainer != null) {
if (dataContainer.invalidValue != null) {
dataContainer.invalidValue = null;
}
}
if (!wasValid) {
for (PmMessage m : PmMessageApi.getMessages(this, Severity.ERROR)) {
this.getPmConversationImpl()._clearPmMessage(m);
}
PmEventApi.firePmEvent(this, PmEvent.VALIDATION_STATE_CHANGE);
}
}
/**
* The default implementation compares the results of {@link #getValueLocalized()}
* according to the collation sequence of the current {@link Locale}.
*
* @deprecated PM based compare operations are no longer supported. Please compare the related data objects.
*/
@Override
@Deprecated
public int compareTo(PmObject otherPm) {
return PmUtil.getAbsoluteName(this).equals(PmUtil.getAbsoluteName(otherPm))
? CompareUtil.compare(getValueLocalized(), ((PmAttr<?>)otherPm).getValueLocalized(), getPmConversation().getPmLocale())
: super.compareTo(otherPm);
}
/**
* Checks if two instances represent the same value.
* <p>
* Sub classes may override this method to provide their specific equals-conditions.
* <p>
* This correct implementation of this method is important for the changed state handling.
*
* @see #isPmValueChanged()
* @see #onPmValueChange(PmEvent)
* @see PmEvent#VALUE_CHANGE
*
* @param v1 A value. May be <code>null</code>.
* @param v2 Another value. May be <code>null</code>.
* @return <code>true</code> if both parameters represent the same value.
*/
protected boolean equalValues(T_PM_VALUE v1, T_PM_VALUE v2) {
return ObjectUtils.equals(v1, v2);
}
@SuppressWarnings("unchecked")
@Override
public final T_PM_VALUE getValue() {
MetaData md = getOwnMetaData();
Object ov = md.valueCache.cacheStrategy.getCachedValue(this);
if (ov != CacheStrategy.NO_CACHE_VALUE) {
// just return the cache hit (if there was one)
return (T_PM_VALUE) ov;
}
else {
try {
T_PM_VALUE v = null;
if (isInvalidValue() &&
dataContainer.invalidValue.isPmValueSet()) {
v = dataContainer.invalidValue.getPmValue();
}
else {
// In case of converter problems: Return the current value.
v = getValueImpl();
}
return (T_PM_VALUE) md.valueCache.cacheStrategy.setAndReturnCachedValue(this, v);
}
catch (RuntimeException e) {
PmRuntimeException forwardedEx = PmRuntimeException.asPmRuntimeException(this, e);
// TODO olaf: Logging is required here for JSF.
// Move to AttrToJsfViewConnectorWithValueChangeListener.
LOG.error("getValue failed", forwardedEx);
throw forwardedEx;
}
}
}
@Override
public final void setValue(T_PM_VALUE value) {
// TODO olaf: Lazy behavior is required here for JSF. Usually an exception should be thrown.
// Move to AttrToJsfViewConnectorWithValueChangeListener.
if (!isPmReadonly()) {
SetValueContainer<T_PM_VALUE> vc = SetValueContainer.makeWithPmValue(this, value);
setValueImpl(vc);
}
else {
// XXX olaf: is only a workaround for the standard jsf-form behavior...
// Approach: add a configuration parameter
if (LOG.isInfoEnabled()) {
LOG.info("Ignored setValue() call for read-only attribute: " + PmUtil.getPmLogString(this));
}
}
}
@Override
public final String getValueAsString() {
try {
T_PM_VALUE value;
if (isInvalidValue()) {
if (dataContainer.invalidValue.isStringValueSet()) {
return dataContainer.invalidValue.getStringValue();
}
else {
value = dataContainer.invalidValue.getPmValue();
}
}
else {
value = getValue();
}
return (value != null || isConvertingNullValueImpl())
? valueToStringImpl(value)
: null;
}
catch (PmRuntimeException pmrex) {
throw pmrex;
}
catch (RuntimeException e) {
PmRuntimeException forwardedEx = PmRuntimeException.asPmRuntimeException(this, e);
LOG.error("getValueAsString failed", forwardedEx);
throw forwardedEx;
}
}
/**
* The default implementation returns the result of {@link #getValueAsString()}.<br>
* If the attribute has options it tries to identify the selected option and returns the
* title for the current option.
*/
@Override
public String getValueLocalized() {
String valueAsString = getValueAsString();
PmOptionSet os = getOptionSet();
if (os != null) {
PmOption option = os.findOptionForIdString(valueAsString);
if (option != null) {
return option.getPmTitle();
}
}
// default:
return valueAsString;
}
/**
* The default implementation returns 0.
*/
@Override
public int getMinLen() {
return getOwnMetaDataWithoutPmInitCall().minLen;
}
@Override
public int getMaxLen() {
return getOwnMetaDataWithoutPmInitCall().getMaxLen();
}
@Override
public final void setValueAsString(String text) {
zz_ensurePmInitialization();
SetValueContainer<T_PM_VALUE> vc = new SetValueContainer<T_PM_VALUE>(this, text);
try {
if (isPmReadonly() &&
getFormatString() != null) {
// Some UI controls (e.g. SWT Text) send an immediate value change event when they get initialized.
// To prevent unnecessary (and problematic) set value loops, nothing happens if the actual
// value gets set to a read-only attribute.
// In case of formatted string representations the value change detection mechanism on value level
// may detect a change if the format does not represent all details of the actual value.
// To prevent such effects, this code checks if the formatted string output is still the same...
// TODO: What about changing a
if (! StringUtils.equalsIgnoreCase(getValueAsString(), vc.getStringValue())) {
throw new PmRuntimeException(this, "Illegal attempt to set a new value to a read only attribute.");
}
return;
}
clearPmInvalidValues();
try {
vc.setPmValue(StringUtils.isNotBlank(text) || isConvertingNullValueImpl()
? stringToValueImpl(text)
: null);
} catch (PmRuntimeException e) {
PmResourceData resData = e.getResourceData();
if (resData == null) {
setInvalidValue(vc);
getPmConversationImpl().getPmExceptionHandler().onException(this, e, false);
} else {
setAndPropagateValueConverterMessage(vc, e, resData.msgKey, resData.msgArgs);
if (LOG.isDebugEnabled()) {
LOG.debug("String to value conversion failed in attribute '" + PmUtil.getPmLogString(this) + "'. String value: " + text);
}
}
return;
} catch (PmConverterException e) {
PmResourceData resData = e.getResourceData();
Object[] args = Arrays.copyOf(resData.msgArgs, resData.msgArgs.length+1);
args[resData.msgArgs.length] = getPmTitle();
setAndPropagateValueConverterMessage(vc, e, resData.msgKey, args);
if (LOG.isDebugEnabled()) {
Throwable cause = e.getParseException() != null ? e.getParseException() : e.getCause();
LOG.debug("String to value conversion failed in attribute '" + PmUtil.getPmLogString(this) +
"'. String value: '" + text +
"'. Caused by: " + e.getMessage(),
cause);
}
return;
} catch (RuntimeException e) {
setInvalidValue(vc);
getPmConversationImpl().getPmExceptionHandler().onException(this, e, false);
if (LOG.isDebugEnabled()) {
LOG.debug("String to value conversion failed in attribute '" + PmUtil.getPmLogString(this) + "'. String value: " + text,
e);
}
return;
}
setValueImpl(vc);
}
catch (RuntimeException e) {
PmRuntimeException pme = PmRuntimeException.asPmRuntimeException(this, e);
PmMessageUtil.makeExceptionMsg(this, Severity.ERROR, pme);
LOG.error("setValueAsString failed to set value '" + vc.getStringValue() + "'", pme);
throw pme;
}
}
@Override
public void resetPmValues() {
boolean isWritable = !isPmReadonly();
if (isWritable) {
PmCacheApi.clearPmCache(this);
}
clearPmInvalidValues();
if (isWritable) {
T_PM_VALUE dv = getDefaultValue();
// TODO olaf: handle scalar values!
// if (dv == null && getOwnMetaData().primitiveType) {
// getOwnMetaData().
setValue(dv);
if (dataContainer != null) {
dataContainer.originalValue = UNCHANGED_VALUE_INDICATOR;
}
}
super.resetPmValues();
}
@Override
protected void clearCachedPmValues(Set<PmCacheApi.CacheKind> cacheSet) {
if (pmInitState != PmInitState.INITIALIZED)
return;
super.clearCachedPmValues(cacheSet);
MetaData md = getOwnMetaData();
if (cacheSet.contains(PmCacheApi.CacheKind.VALUE)) {
md.valueCache.cacheStrategy.clear(this);
}
if (cacheSet.contains(PmCacheApi.CacheKind.OPTIONS)) {
md.optionsCache.cacheStrategy.clear(this);
}
}
/**
* Gets attribute value directly from the bound data source. Does not use the
* cache and does not consider any temporarily set invalid values.
*
* @return The current attribute value.
*/
public final T_PM_VALUE getUncachedValidValue() {
return getValueImpl();
}
/**
*
* @return
*/
// TODO oboede: is there a use case that is not covered by overriding getBackingValueImpl()?
// Can we make this method final and private?
protected T_PM_VALUE getValueImpl() {
try {
// the method will try to populate pmValue with different approaches
// and return it as result
T_BEAN_VALUE beanAttrValue = getBackingValue();
T_PM_VALUE pmValue = PmAttrUtil.backingValueToValue(this, beanAttrValue);
// return the converted value if it is not an "empty value".
// Otherwise continue with default value logic.
if(!isEmptyValue(pmValue)) {
return pmValue;
}
// Default values may have only effect if the value was not set by the user:
if (valueChangedBySetValue) {
return pmValue;
}
// At this point pmValue is still either null or empty.
// If a default value exists this shall be used to populate it.
// The default value will be shown in read-only scenarios instead of
// the real 'null' value.
T_PM_VALUE defaultValue = getDefaultValue();
if (defaultValue != null) {
// The backing value gets changed within the 'get' functionality.
// This is ok according to the default value logic. See: Wiki entry TODO
// This modification can't be done for disabled attributes, since this
// operation may fail in some cases. (E.g. if the backing bean is 'null'.)
// FIXME oboede: It was not possible to ask 'isPmEnabled' because some isPmEnabledImpl
// code asked 'getValue()', which generates a stack overflow.
// We need a clear documented way to fix this issue.
if (!isPmReadonly()) {
T_BEAN_VALUE defaultBeanAttrValue = convertPmValueToBackingValue(defaultValue);
setBackingValue(defaultBeanAttrValue);
}
return defaultValue;
}
// If non of the above approaches was successful we can do nothing else
// then return the pmValue that is either null or an empty list.
return pmValue;
}
catch (Exception e) {
throw PmRuntimeException.asPmRuntimeException(this, e);
}
}
/**
* Performs a smart set operation.
* Validates the value before applying it.
*
* @param value The new value.
* @return <code>true</code> when the attribute value was really changed.
*/
// TODO oboede: make it final or package private? Which functionality is not covered by setBackingValueImpl()?
protected boolean setValueImpl(SetValueContainer<T_PM_VALUE> value) {
PmEventApi.ensureThreadEventSource(this);
MetaData metaData = getOwnMetaData();
try {
assert value.isPmValueSet();
T_PM_VALUE newPmValue = value.getPmValue();
T_PM_VALUE currentValue = getUncachedValidValue();
// Check both values for null-value because they might be different but
// may both represent a null-value.
boolean pmValueChanged = (! equalValues(currentValue, newPmValue)) &&
(! (isEmptyValue(newPmValue) && isEmptyValue(currentValue)));
ValueChangeCommandImpl<T_PM_VALUE> cmd = new ValueChangeCommandImpl<T_PM_VALUE>(this, currentValue, newPmValue);
// New game. Forget all the old invalid stuff.
clearPmInvalidValues();
// FIXME olaf: read only control should be done within the calling setValueAsString method!
// The set operation should not be performed in this case. Check for side effects...
if (pmValueChanged && isPmReadonly()) {
PmMessageApi.addMessage(this, Severity.ERROR, PmConstants.MSGKEY_VALIDATION_READONLY);
return false;
}
if (metaData.validate == Validate.BEFORE_SET || isValidatingOnSetPmValue()) {
// Validate even if nothing was changed. The currentValue may be invalid too.
// Example: New object with empty attributes values.
try {
validate(newPmValue);
}
// TODO: we have to handle other validation exceptions too.
catch (PmValidationException e) {
PmResourceData resData = e.getResourceData();
setAndPropagateInvalidValue(value, resData.msgKey, resData.msgArgs);
return false;
}
}
if (pmValueChanged) {
if (!beforeValueChange(currentValue, newPmValue)) {
LOG.debug("Value '" + getPmRelativeName() + "' was not changed because of the beforeDo result of the beforeValueChange() implementation");
return false;
}
for (PmCommandDecorator d : getValueChangeDecorators()) {
if (!d.beforeDo(cmd)) {
LOG.debug("Value '" + getPmRelativeName() + "' was not changed because of the beforeDo result of decorator: " + d);
return false;
}
}
// TODO olaf: a quick hack to hide password data. Should be done more general for other field names too.
if (LOG.isDebugEnabled() && !ObjectUtils.equals(getPmName(), "password")) {
LOG.debug("Changing PM value of '" + PmUtil.getPmLogString(this) + "' from '" + currentValue + "' to '" + newPmValue + "'.");
}
T_BEAN_VALUE backingValue = PmAttrUtil.valueToBackingValue(this, newPmValue);
// Ensure that primitive backing values will not be set to null.
if ((backingValue == null) && getOwnMetaData().primitiveType) {
// TODO oboede: This misleading error message will be here for one release only to minimize
// compatibility risks. It will be replaced by the exception below in release v0.8.
setAndPropagateInvalidValue(value, PmConstants.MSGKEY_VALIDATION_MISSING_REQUIRED_VALUE);
return false;
// throw new PmRuntimeException(this, "Unable to set a primitive value to null.\n" +
// "You may override 'isConvertingNullValueImpl' and implement a null value conversion (override convertPmValueToBackingValue or configure a valueConverter) to get that feature.");
}
setBackingValueInternal(backingValue);
metaData.valueCache.cacheStrategy.setAndReturnCachedValue(this, newPmValue);
// From now on the value should be handled as intentionally modified.
// That means that the default value shouldn't be returned, even if the
// value was set to <code>null</code>.
valueChangedBySetValue = true;
setValueChanged(currentValue, newPmValue);
// optional after-set validation done before afterChange calls. See: Validate.AFTER_SET.
// TODO olaf: Check domain exception handling here. After an exception the value is
// changed but no event will get fired.
if (metaData.validate == Validate.AFTER_SET) {
pmValidate();
}
// internal after-change logic before external after-change logic.
afterValueChange(currentValue, newPmValue);
// tighter coupled value change decorators before more unspecific event listeners
for (PmCommandDecorator d : getValueChangeDecorators()) {
d.afterDo(cmd);
}
PmEventApi.firePmEvent(this, PmEvent.VALUE_CHANGE);
// after all post-processing it's really done and available for undo calls.
getPmConversation().getPmCommandHistory().commandDone(cmd);
return true;
}
else {
return false;
}
} catch (RuntimeException e) {
getPmConversationImpl().getPmExceptionHandler().onException(this, e, false);
return false;
}
}
/**
* Gets called before a value change will be applied.
* <p>
* It may be overridden for application specific needs.<br>
* It may prevent the change to be applied by returning <code>false</code>.
* <p>
* <b>PLEASE NOTE</b>: If an attribute value change should cause a parallel
* change of some other data, the related code should <b>not</b> be located
* here.<br>
* Please use the methods {@link #afterValueChange(Object, Object)} or
* {@link #setBackingValueImpl(Object)} to adjust other data.
* <p>
* Reason: A <code>beforeValueChange</code> call does only report the
* intention to change the value. It's final execution may still be prevented
* by another value change decorator.
*
* @param oldValue
* The old (current) attribute value.
* @param newValue
* The new value that should be applied.
* @return A return value <code>false</code> will prevent the value change.
*/
protected boolean beforeValueChange(T_PM_VALUE oldValue, T_PM_VALUE newValue) {
return true;
}
/**
* A method that may be overridden to add domain specific after value change logic.
* <p>
* It's called
* <ul>
* <li><b>after</b> changing the attribute value,</li>
* <li><b>before</b> the after-do method calls to registered value change decorators and
* <li><b>before</b> sending the value change event to registered listeners.</li>
* </ul>
*
* @param oldValue The old attribute value.
* @param newValue The new (current) value.
*
* @see #addValueChangeDecorator(PmCommandDecorator)
* @see PmEventApi#addPmEventListener(PmObject, int, org.pm4j.core.pm.PmEventListener)
*/
protected void afterValueChange(T_PM_VALUE oldValue, T_PM_VALUE newValue) {
}
/**
* Indicates if the value was explicitly set. This information is especially
* important for the default value logic. Default values may have only effect
* on values that are not explicitly set.
*/
protected final boolean isValueChangedBySetValue() {
return valueChangedBySetValue;
}
/**
* Gets called whenever a string value needs to be converted to the attribute value type.
* <p>
* The default implementation uses the converter provided by {@link #getStringConverter()}.
*
* @param s The string to convert.
* @return The converted value.
* @throws PmConverterException If the given string can't be converted.
*/
protected T_PM_VALUE stringToValueImpl(String s) throws PmConverterException {
try {
return (T_PM_VALUE) getStringConverter().stringToValue(converterCtxt, s);
} catch (StringConverterParseException e) {
throw new PmConverterException(this, e);
}
}
/**
* Gets called whenever the attribute value needs to be represented as a string.
* <p>
* The default implementation uses the converter provided by {@link #getStringConverter()}.
*
* @param v A value to convert.
* @return The string representation.
*/
protected String valueToStringImpl(T_PM_VALUE v) {
return getStringConverter().valueToString(converterCtxt, v);
}
/**
* @return The converter that translates from and to the corresponding string value representation.
*/
public final StringConverter<T_PM_VALUE> getStringConverter() {
if (stringConverter == null) {
zz_ensurePmInitialization();
stringConverter = getStringConverterImpl();
if (stringConverter == null) {
throw new PmRuntimeException(this, "Please ensure that getStringConverterImpl() does not return null.");
}
}
return stringConverter;
}
/**
* A factory method that defines the value string converter to use.
* <p>
* Corresponding external interface: {@link #getStringConverter()}
*
* @return The attribute value string converter. Never <code>null</code>.
*/
@SuppressWarnings("unchecked")
protected StringConverter<T_PM_VALUE> getStringConverterImpl() {
StringConverter<T_PM_VALUE> c = (StringConverter<T_PM_VALUE>) getOwnMetaData().stringConverter;
if (c == null) {
throw new PmRuntimeException(this, "Missing value converter.");
}
return c;
}
/** @return The converter operation context. */
protected AttrConverterCtxt getConverterCtxt() {
return converterCtxt;
}
/** A factory method that provides the attribute type specific converter context reference. */
protected AttrConverterCtxt makeConverterCtxt() {
return new AttrConverterCtxt(this);
}
@Override
protected boolean isPmValueChangedImpl() {
return (dataContainer != null &&
dataContainer.originalValue != UNCHANGED_VALUE_INDICATOR) ||
super.isPmValueChangedImpl();
}
/**
* Sub classes may override this to define their attribute specific time zone.
*
* @return The externally visible time zone.
*/
protected TimeZone getPmTimeZoneImpl() {
return getPmConversation().getPmTimeZone();
}
@Override
protected void setPmValueChangedImpl(boolean newChangedState) {
setValueChanged(UNKNOWN_VALUE_INDICATOR, newChangedState
? CHANGED_VALUE_INDICATOR
: UNCHANGED_VALUE_INDICATOR);
if (newChangedState == false) {
valueChangedBySetValue = false;
}
super.setPmValueChangedImpl(newChangedState);
}
static final String UNCHANGED_VALUE_INDICATOR = "
static final String CHANGED_VALUE_INDICATOR = "
static final String UNKNOWN_VALUE_INDICATOR = "
/**
* Detects a change by checking the <code>oldValue</code> and <code>newValue</code>
* parameters.
* <p>
* Passing {@link #UNCHANGED_VALUE_INDICATOR} as <code>newValue</code> causes
* a change of the internal managed <code>originalValue</code> to 'unchanged'.<br>
* This way the current attribute value gets accepted as the 'original unchange'
* value.
*
* @param oldValue The old value.
* @param newValue The new value.
*/
private void setValueChanged(Object oldValue, Object newValue) {
boolean fireStateChange = false;
// Reset to an unchanged value state. Accepts the current value as the original one.
if (newValue == UNCHANGED_VALUE_INDICATOR) {
// prevent creation of a data container only to store the default value...
if (dataContainer != null) {
fireStateChange = (dataContainer.originalValue != UNCHANGED_VALUE_INDICATOR);
dataContainer.originalValue = UNCHANGED_VALUE_INDICATOR;
}
}
// Set the value:
else {
// Setting the attribute to the original value leads to an 'unchanged' state.
if (ObjectUtils.equals(zz_getDataContainer().originalValue, newValue)) {
fireStateChange = (dataContainer.originalValue != UNCHANGED_VALUE_INDICATOR);
dataContainer.originalValue = UNCHANGED_VALUE_INDICATOR;
}
// Setting a value which is not the original one:
else {
// Remember the current value as the original one if the attribute was in an unchanged
// state:
if (dataContainer.originalValue == UNCHANGED_VALUE_INDICATOR) {
fireStateChange = true;
dataContainer.originalValue = oldValue;
}
else {
// If the attribute gets changed back to its original value: Mark it as unchanged.
if (ObjectUtils.equals(dataContainer.originalValue, newValue)) {
fireStateChange = true;
dataContainer.originalValue = UNCHANGED_VALUE_INDICATOR;
}
}
}
}
if (fireStateChange) {
PmEventApi.firePmEvent(this, PmEvent.VALUE_CHANGED_STATE_CHANGE);
}
}
/**
* The default implementation provides the default value provided by the
* annotation {@link PmAttrCfg#defaultValue()}.
* <p>
* Subclasses may override the method {@link #getDefaultValueImpl()} to provide
* some special implementation.
*
* @return The default value for this attribute.
*/
protected final T_PM_VALUE getDefaultValue() {
return getDefaultValueImpl();
}
/**
* Reads a PM request attribute with the name of the attribute.
*
* @return The read request attribute, converted to the attribute specific
* type. <code>null</code> if there is no default value attribute
* within the given request.
* @deprecated remove as soon as a customer scenario is cleaned.
*/
private T_PM_VALUE getDefaultValueFromRequest() {
String reqValue = getPmConversationImpl().getPmToViewTechnologyConnector().readRequestValue(getPmName());
try {
return (reqValue != null)
? stringToValueImpl(reqValue)
: null;
} catch (PmConverterException e) {
throw new PmRuntimeException(this, e);
}
}
/**
* The default implementation provides the value provided by {@link PmAttrCfg#defaultValue()}.
* <p>
* Subclasses may override this method to provide some special implementation.
*
* @return The default value for this attribute.
*/
protected T_PM_VALUE getDefaultValueImpl() {
MetaData md = getOwnMetaData();
T_PM_VALUE defaultValue = null;
if (StringUtils.isNotBlank(md.defaultValueString)) {
try {
defaultValue = stringToValueImpl(md.defaultValueString);
} catch (PmConverterException e) {
throw new PmRuntimeException(this, e);
}
}
return (T_PM_VALUE) (defaultValue != null
? defaultValue
: getDefaultValueFromRequest());
}
/**
* Sets the invalid value and propagates a {@link PmValidationMessage} to the
* conversation.
*
* @param invValue
* The invalid value.
* @param msgKey
* Key for the user message.
* @param msgArgs
* Values for the user message.
*/
private void setAndPropagateInvalidValue(SetValueContainer<T_PM_VALUE> invValue, String msgKey, Object... msgArgs) {
getPmConversationImpl().addPmMessage(new PmValidationMessage(this, invValue, null, msgKey, msgArgs));
setInvalidValue(invValue);
}
/**
* Sets the invalid value and notifies listeners
*
* @param invValue
* The invalid value.
*/
private void setInvalidValue(SetValueContainer<T_PM_VALUE> invValue) {
zz_getDataContainer().invalidValue = invValue;
PmEventApi.firePmEvent(this, PmEvent.VALIDATION_STATE_CHANGE);
}
/**
* @param invValue
* The invalid value.
* @param msgKey
* Key for the user message.
* @param msgArgs
* Values for the user message.
*/
private void setAndPropagateValueConverterMessage(SetValueContainer<T_PM_VALUE> invValue, Throwable cause, String msgKey,
Object... msgArgs) {
this.getPmConversationImpl().addPmMessage(new PmConverterErrorMessage(this, invValue, cause, msgKey, msgArgs));
setInvalidValue(invValue);
}
/**
* @return <code>true</code> when there is an invalid user data entry.
*/
private final boolean isInvalidValue() {
return (dataContainer != null) && (dataContainer.invalidValue != null);
}
/**
* Checks the attribute type specific <code>null</code> or empty value
* condition.
*
* @return <code>true</code> when the value is a <code>null</code> or empty
* value equivalent.
*/
protected boolean isEmptyValue(T_PM_VALUE value) {
return (value == null);
}
/**
* If this method returns <code>true</code>, each {@link #setValue(Object)} will cause an
* immediate call to {@link #pmValidate()}.
* <p>
* Alternatively validation is usually triggered by a command.
*
* @deprecated Please use {@link PmAttrCfg#validate()} using the parameter {@link PmAttrCfg.Validate#BEFORE_SET}.
*/
@Deprecated
protected boolean isValidatingOnSetPmValue() {
return false;
}
/**
* The default validation checks just the required condition.
* More specific attribute classes have to add their specific validation
* by overriding this method.
*
* @param value The value to validate.
*/
protected void validate(T_PM_VALUE value) throws PmValidationException {
if (getOwnMetaData().deprValidation &&
isRequired() &&
isEmptyValue(value)) {
throw new PmValidationException(PmMessageApi.makeRequiredMessageResData(this));
}
// Check for the length of the number String representation if enabled
// FIXME oboede: disabled for an integration
// if (getOwnMetaDataWithoutPmInitCall().isValidateLengths()) {
if (this instanceof PmAttrString) {
String valueAsString = (value != null || isConvertingNullValueImpl()) ? valueToStringImpl(value) : null;
if (valueAsString != null) {
if (valueAsString.length() < getMinLen()) {
throw new PmValidationException(this, PmConstants.MSGKEY_VALIDATION_VALUE_TOO_SHORT, getMinLen());
}
if (valueAsString.length() > getMaxLen()) {
throw new PmValidationException(this, PmConstants.MSGKEY_VALIDATION_VALUE_TOO_LONG, getMaxLen());
}
}
}
}
/**
* Check the JSR-303 bean validation constraints for this attribute.
* <p>
* All found violations are reported as error messages in relation to this attribute.
*/
void performJsr303Validations() {
Object validationBean = getOwnMetaData().valueAccessStrategy.getPropertyContainingBean(this);
if (validationBean != null && getOwnMetaData().validationFieldName != null) {
BeanValidationPmUtil.validateProperty(this, validationBean, getOwnMetaData().validationFieldName);
}
}
/**
* Attribute validation logic.
*
* @param <T> The attribute PM type.
*/
public static class AttrValidator<T extends PmAttrBase<?, ?>> extends ObjectValidator<T> {
@Override
protected boolean shouldValidate(T pm) {
// visibility is considered here to support attribute exchange via visibility switch.
return pm.isPmVisible() &&
pm.isPmEnabled() &&
// A validation can only be performed if the last setValue() did not generate a converter exception.
// Otherwise the attribute will simply stay in its value converter error state.
!pm.hasPmConverterErrors();
}
@SuppressWarnings("unchecked")
@Override
protected void validateImpl(T pm) throws PmValidationException {
// TODO: move to common logic? Problem to solve: converter messages need to be preserved.
// Clears all messages, inclusive converter messages.
pm.getPmConversationImpl().clearPmMessages(pm, null);
// Validates sub PMs.
super.validateImpl(pm);
// In case of a required composite attribute:
// If all required sub-PMs report a 'required' error only a single required
// message will be shown for the whole attribue.
if (pm.isRequired() && PmAttrUtil.isEmptyValue(pm, pm.getValue())) {
// if all required sub-attrs report a required warning, this
// should be replaced by a required warning for the main attr
List<PmMessage> childReqMsgs = new ArrayList<PmMessage>();
int reqChildCount = 0;
for (PmAttr<?> c : PmUtil.getPmChildrenOfType(pm, PmAttr.class)) {
if (c.isRequired()) {
++reqChildCount;
for (PmMessage m : PmMessageApi.getMessages(c, Severity.ERROR)) {
// XXX oboede: is only a fragile resource key based
// identification.
if (PmConstants.MSGKEY_VALIDATION_MISSING_REQUIRED_VALUE.equals(m.getMsgKey())) {
childReqMsgs.add(m);
}
}
}
}
if (reqChildCount == childReqMsgs.size()) {
PmConversationImpl convPm = pm.getPmConversationImpl();
for (PmMessage m : childReqMsgs) {
convPm.clearPmMessage(m);
}
throw new PmValidationException(PmMessageApi.makeRequiredMessageResData(pm));
}
}
// Start further attribute validation only if attribute parts are valid.
if (pm.isPmValid()) {
((PmAttrBase<Object, ?>)pm).validate((Object)pm.getValue());
pm.performJsr303Validations();
}
}
}
@Override
protected Validator makePmValidator() {
return getOwnMetaDataWithoutPmInitCall().deprValidation
? new DeprAttrValidator<Object>()
: new AttrValidator<PmAttrBase<?,?>>();
}
boolean hasPmConverterErrors() {
for (PmMessage m : getPmConversation().getPmMessages(this, Severity.ERROR)) {
if (m instanceof PmConverterErrorMessage) {
return true;
}
}
// no converter message found.
return false;
}
public boolean isBufferedPmValueMode() {
PmDataInput parentPmCtxt = PmUtil.getPmParentOfType(this, PmDataInput.class);
return parentPmCtxt.isBufferedPmValueMode();
}
@SuppressWarnings("unchecked")
public void commitBufferedPmChanges() {
if (isBufferedPmValueMode() &&
bufferedValue != UNKNOWN_VALUE_INDICATOR) {
setBackingValueImpl((T_BEAN_VALUE)bufferedValue);
bufferedValue = UNKNOWN_VALUE_INDICATOR;
}
}
public void rollbackBufferedPmChanges() {
bufferedValue = UNKNOWN_VALUE_INDICATOR;
}
/**
* Converts the backing attribute value to the external attribute value.
* <p>
* The default implementation uses the {@link ValueConverter} provided by
* {@link #getValueConverter()}.
* <p>
* ATTENTION: this method will be made protected soon. Please use
* {@link PmAttrUtil#backingValueToValue(PmAttrBase, Object)}.
*/
public T_PM_VALUE convertBackingValueToPmValue(T_BEAN_VALUE backingValue) {
return getValueConverter().toExternalValue(converterCtxt, backingValue);
}
/**
* Converts the external attribute value to the backing attribute value.
* <p>
* The default implementation uses the {@link ValueConverter} provided by
* {@link #getValueConverter()}.
* <p>
* ATTENTION: this method will be made protected soon. Please use
* {@link PmAttrUtil#valueToBackingValue(PmAttrBase, Object)}.
*/
public T_BEAN_VALUE convertPmValueToBackingValue(T_PM_VALUE externalValue) {
return getValueConverter().toInternalValue(converterCtxt, externalValue);
}
/** Provides the value converter that translates between backing- and external value. */
final ValueConverter<T_PM_VALUE, T_BEAN_VALUE> getValueConverter() {
if (valueConverter == null) {
zz_ensurePmInitialization();
valueConverter = getValueConverterImpl();
if (valueConverter == null) {
throw new PmRuntimeException(this, "Please ensure that getValueConverterImpl() does not return null.");
}
}
return (ValueConverter<T_PM_VALUE, T_BEAN_VALUE>) valueConverter;
}
/**
* Provides the value converter used to convert between backing value to external value type.<br>
* The default implementation uses the information provided in {@link PmAttrCfg#valueConverter()}.
* If nothing is configured there a simple pass-through converter will be provided.
* <p>
* Advanced usage:<br>
* To provide a shared stateless {@link ValueConverter}, you may call
* {@link MetaData#setValueConverter(org.pm4j.core.pm.PmAttr.ValueConverter)} within {@link #initMetaData(org.pm4j.core.pm.impl.PmObjectBase.MetaData)}.
*
* @return The converter to use. Should not be <code>null</code>.
*/
@SuppressWarnings("unchecked")
protected ValueConverter<T_PM_VALUE, T_BEAN_VALUE> getValueConverterImpl() {
MetaData md = getOwnMetaData();
return (ValueConverter<T_PM_VALUE, T_BEAN_VALUE>)(
(md.valueConverter != null)
? md.valueConverter
: ValueConverterDefault.INSTANCE);
}
/**
* Defines if <code>null</code> values passed to the converter methods.
* <p>
* Override this method if your <code>null</code> values should be converted to
* a not-<code>null</code> value.
* <p>
* By default <code>null</code> values will not be passed to converters. But
* in some very special cases domain code wants to convert a null to some real
* value (e.g. false).<br>
* In that special situation this method should be return
* <code>true</code> and the corresponding converter methods should provide
* the algorithm to handle null-to-value and value-to-null translations.
*
* @see {@link #stringToValueImpl(String)}
* @see {@link #valueToStringImpl(Object)}
* @see {@link #getValueConverterImpl()}
* @see {@link PmAttrUtil#backingValueToValue(PmAttrBase, Object)}
* @see {@link PmAttrUtil#convertExternalValue(PmAttrBase, Object)}
*/
protected boolean isConvertingNullValueImpl() {
return false;
}
/**
* Provides the bound backing value of this attribute.
* <p>
* Does not use the optionally configured value cache.
*
* @return the bound backing value.
*/
@SuppressWarnings("unchecked")
public final T_BEAN_VALUE getBackingValue() {
return (bufferedValue != UNKNOWN_VALUE_INDICATOR)
? (T_BEAN_VALUE)bufferedValue
: getBackingValueImpl();
}
/**
* Sets the backing value of the attribute directly.<br>
* It also:
* <ul>
* <li>clears value caches to ensure that the new state gets externally visible<br>
* <li>clears existing invalid attribute value messages</li>
* <li>marks the attribute as unchanged (because it's usually not a user change)</li>
* </ul>
* Please use it with care because this call may fail in case of attributes
* that are not intended for modification. E.g. in case of calculated
* attributes that support only read operations.
* <p>
* In difference to {@link #setValue(Object)} this method also does not
* consider attribute enablement.
*
* @param value
* The value to assign directly to the bound backing value storage.
*/
public final void setBackingValue(T_BEAN_VALUE value) {
setBackingValueInternal(value);
clearPmCache(this, CacheKind.VALUE);
clearPmInvalidValues();
setPmValueChanged(false);
}
final void setBackingValueInternal(T_BEAN_VALUE value) {
if (isBufferedPmValueMode()) {
bufferedValue = value;
}
else {
setBackingValueImpl(value);
}
}
/**
* Provides the internal (non PM) data type representation of the attribute value.
* <p>
* Attributes may override this method to provide a specific implementation.
*
* @return The value (internal data type representation).
*/
@SuppressWarnings("unchecked")
protected T_BEAN_VALUE getBackingValueImpl() {
return (T_BEAN_VALUE) getOwnMetaData().valueAccessStrategy.getValue(this);
}
/**
* Sets the internal (non PM) data type representation of the attribute value.
* <p>
* Attributes may override this method to provide a specific implementation.
*
* @param value The value to assign (internal data type representation).
*/
protected void setBackingValueImpl(T_BEAN_VALUE value) {
getOwnMetaData().valueAccessStrategy.setValue(this, value);
}
@Override
public String getFormatString() {
String key = getOwnMetaData().formatResKey;
String format = null;
// 1. fix resource key definition
if (key != null) {
format = PmLocalizeApi.findLocalization(this, key);
if (format == null) {
throw new PmRuntimeException(this, "No resource string found for configured format resource key '" + key +"'.");
}
}
// 2. no fix key: try to find a postfix based definition
else {
key = getPmResKey() + PmConstants.RESKEY_POSTFIX_FORMAT;
format = PmLocalizeApi.findLocalization(this, key);
// 3. Try a default key (if defined for this attribute)
if (format == null) {
key = getFormatDefaultResKey();
if (key != null) {
format = PmLocalizeApi.findLocalization(this, key);
}
}
}
return format;
}
@Override
public Class<?> getValueType() {
Type t = GenericTypeUtil.resolveGenericArgument(PmAttrBase.class, getClass(), 0);
if (t instanceof ParameterizedType) {
t = ((ParameterizedType)t).getRawType();
}
if (!(t instanceof Class)) {
throw new PmRuntimeException(this, "Unable to handle an attribute value type that is not a class or interface. Found type: " + t);
}
return (Class<?>) t;
}
/**
* Concrete attribute classes may specify here a default format resource key
* as a fallback for unspecified format localizations.
*
* @return The fallback resource key or <code>null</code> if there is none.
*/
protected String getFormatDefaultResKey() {
return null;
}
/** INTERNAL method. */
protected void addValueChangeDecorator(PmCommandDecorator decorator) {
if (valueChangeDecorators.isEmpty()) {
valueChangeDecorators = new ArrayList<PmCommandDecorator>();
}
valueChangeDecorators.add(decorator);
}
/**
* @return The set of decorators to consider on value change.
*/
protected Collection<PmCommandDecorator> getValueChangeDecorators() {
return valueChangeDecorators;
}
/**
* Provides a data container. Creates it on the fly when it does not already
* exist.
*
* @return The container for optional data parts.
*/
final PmAttrDataContainer<T_PM_VALUE, T_BEAN_VALUE> zz_getDataContainer() {
if (dataContainer == null) {
dataContainer = new PmAttrDataContainer<T_PM_VALUE, T_BEAN_VALUE>();
}
return dataContainer;
}
// XXX olaf: really required? May be solved by overriding initMetaData too.
protected PmOptionSetDef<?> makeOptionSetDef(PmOptionCfg cfg, Method getOptionValuesMethod) {
return cfg != null
? new GenericOptionSetDef(this, cfg, getOptionValuesMethod)
: OptionSetDefNoOption.INSTANCE;
}
@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
@Override
protected void initMetaData(PmObjectBase.MetaData metaData) {
super.initMetaData(metaData);
MetaData myMetaData = (MetaData) metaData;
Class<?> beanClass = (getPmParent() instanceof PmBean)
? ((PmBean)getPmParent()).getPmBeanClass()
: null;
myMetaData.embeddedAttr = getPmParent() instanceof PmAttr;
PmAttrCfg fieldAnnotation = AnnotationUtil.findAnnotation(this, PmAttrCfg.class);
zz_readBeanValidationRestrictions(beanClass, fieldAnnotation, myMetaData);
// read the option configuration first from the getOptionValues()
// method. If not found there: From the attribute- and class declaration.
Method getOptionValuesMethod = null;
PmOptionCfg optionCfg = null;
try {
getOptionValuesMethod = getClass().getMethod("getOptionValues");
if (getOptionValuesMethod.getDeclaringClass() != PmAttrBase.class) {
optionCfg = getOptionValuesMethod.getAnnotation(PmOptionCfg.class);
// XXX: not really fine for security contexts.
getOptionValuesMethod.setAccessible(true);
}
else {
getOptionValuesMethod = null;
}
} catch (Exception e) {
throw new PmRuntimeException(this, "Unable to access method 'getOptionValues'.", e);
}
if (optionCfg == null) {
optionCfg = AnnotationUtil.findAnnotation(this, PmOptionCfg.class);
}
myMetaData.optionSetDef = (PmOptionSetDef)
makeOptionSetDef(optionCfg, getOptionValuesMethod);
if (myMetaData.optionSetDef != OptionSetDefNoOption.INSTANCE) {
myMetaData.setStringConverter(
new PmConverterOptionBased(optionCfg != null ? optionCfg.id() : ""));
}
// TODO olaf: implement a simplified and more consistent option implementation...
if (optionCfg != null) {
myMetaData.nullOption = optionCfg.nullOption();
}
PmAttrCfg.AttrAccessKind accessKindCfgValue = PmAttrCfg.AttrAccessKind.DEFAULT;
boolean useReflection = true;
if (fieldAnnotation != null) {
myMetaData.hideIfEmptyValue = fieldAnnotation.hideWhenEmpty();
// The HideIf enum is the leading attribute. So override the value of hideIfEmptyValue
// even it is set by fieldAnnotation.hideWhenEmpty().
for (HideIf hideIf : fieldAnnotation.hideIf()) {
if (HideIf.DEFAULT_VALUE == hideIf) {
myMetaData.hideIfDefaultValue = true;
} else if (HideIf.EMPTY_VALUE == hideIf) {
myMetaData.hideIfEmptyValue = true;
} else {
throw new PmRuntimeException(this, "Unknown value: " + hideIf.name());
}
}
myMetaData.setReadOnly((fieldAnnotation.valueRestriction() == Restriction.READ_ONLY) || fieldAnnotation.readOnly());
// The pm can force more constraints. It should not define less constraints as
// the bean validation definition:
if (fieldAnnotation.required()) {
myMetaData.required = true;
}
// TODO: replace 'required' and 'readOnly'.
if (fieldAnnotation.valueRestriction() != Restriction.NONE) {
myMetaData.valueRestriction = fieldAnnotation.valueRestriction();
}
myMetaData.validate = fieldAnnotation.validate();
accessKindCfgValue = fieldAnnotation.accessKind();
myMetaData.formatResKey = StringUtils.defaultIfEmpty(fieldAnnotation.formatResKey(), null);
if (StringUtils.isNotEmpty(fieldAnnotation.defaultValue())) {
myMetaData.defaultValueString = fieldAnnotation.defaultValue();
}
myMetaData.maxLen = fieldAnnotation.maxLen();
myMetaData.minLen = fieldAnnotation.minLen();
if (myMetaData.maxLen != -1 &&
myMetaData.minLen > myMetaData.maxLen) {
throw new PmRuntimeException(this, "minLen(" + myMetaData.minLen +
") > maxLen(" + myMetaData.maxLen + ")");
}
switch (accessKindCfgValue) {
case DEFAULT:
if (StringUtils.isNotBlank(fieldAnnotation.valuePath())) {
SyntaxVersion syntaxVersion = PmExpressionApi.getSyntaxVersion(this);
myMetaData.valuePathResolver = PmExpressionPathResolver.parse(fieldAnnotation.valuePath(), syntaxVersion);
int lastDotPos = fieldAnnotation.valuePath().lastIndexOf('.');
if (lastDotPos > 0) {
String parentPath = fieldAnnotation.valuePath().substring(0, lastDotPos);
myMetaData.valueContainingObjPathResolver = PmExpressionPathResolver.parse(parentPath, syntaxVersion);
}
useReflection = false;
myMetaData.valueAccessStrategy = ValueAccessByExpression.INSTANCE;
}
break;
case OVERRIDE:
useReflection = false;
myMetaData.valueAccessStrategy = ValueAccessOverride.INSTANCE;
break;
case SESSIONPROPERTY:
useReflection = false;
myMetaData.valueAccessStrategy = ValueAccessSessionProperty.INSTANCE;
break;
case LOCALVALUE:
useReflection = false;
myMetaData.valueAccessStrategy = ValueAccessLocal.INSTANCE;
break;
default:
throw new PmRuntimeException(this, "Unknown annotation kind: " + fieldAnnotation.accessKind());
}
if (fieldAnnotation.valueConverter() != ValueConverter.class) {
myMetaData.valueConverter = ClassUtil.newInstance(fieldAnnotation.valueConverter());
}
}
// Automatic reflection access is only supported for fix PmAttr fields in a PmBean container:
if (useReflection &&
myMetaData.isPmField &&
beanClass != null) {
try {
myMetaData.beanAttrAccessor = new BeanAttrAccessorImpl(beanClass, getPmName());
if (myMetaData.beanAttrAccessor.getFieldClass().isPrimitive()) {
myMetaData.primitiveType = true;
if (fieldAnnotation == null) {
myMetaData.required = true;
}
}
myMetaData.valueAccessStrategy = ValueAccessReflection.INSTANCE;
}
catch (ReflectionException e) {
if (ClassUtil.findMethods(getClass(), "getBackingValueImpl").size() > 1) {
myMetaData.valueAccessStrategy = ValueAccessOverride.INSTANCE;
} else {
PmObjectUtil.throwAsPmRuntimeException(this, e);
}
}
}
// Use default attribute title provider if no specific provider was configured.
if (metaData.getPmTitleProvider() == getPmConversation().getPmDefaults().getPmTitleProvider()) {
metaData.setPmTitleProvider(getPmConversation().getPmDefaults().getPmAttrTitleProvider());
}
// -- Cache configuration --
List cacheAnnotations = InternalPmCacheCfgUtil.findCacheCfgsInPmHierarchy(this, new ArrayList());
if (!cacheAnnotations.isEmpty()) {
myMetaData.optionsCache = InternalPmCacheCfgUtil.readCacheMetaData(this, CacheKind.OPTIONS, cacheAnnotations, InternalAttrCacheStrategyFactory.INSTANCE);
myMetaData.valueCache = InternalPmCacheCfgUtil.readCacheMetaData(this, CacheKind.VALUE, cacheAnnotations, InternalAttrCacheStrategyFactory.INSTANCE);
}
}
private void zz_readBeanValidationRestrictions(Class<?> beanClass, PmAttrCfg fieldAnnotation, MetaData myMetaData) {
if (BeanValidationPmUtil.getBeanValidator() == null)
return;
Class<?> srcClass = ((fieldAnnotation != null) &&
(fieldAnnotation.beanInfoClass() != Void.class))
? fieldAnnotation.beanInfoClass()
: beanClass;
if (srcClass != null) {
BeanDescriptor beanDescriptor = BeanValidationPmUtil.getBeanValidator().getConstraintsForClass(srcClass);
if (beanDescriptor != null) {
myMetaData.validationFieldName = (fieldAnnotation != null) &&
(StringUtils.isNotBlank(fieldAnnotation.beanInfoField()))
? fieldAnnotation.beanInfoField()
: myMetaData.getName();
PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty(myMetaData.validationFieldName);
if (propertyDescriptor == null ||
propertyDescriptor.getConstraintDescriptors().isEmpty()) {
myMetaData.validationFieldName = null;
}
else {
for (ConstraintDescriptor<?> cd : propertyDescriptor.getConstraintDescriptors()) {
initMetaDataBeanConstraint(cd);
}
}
}
}
}
/**
* Gets called for each found {@link ConstraintDescriptor}.<br>
* The default implementation just checks the {@link NotNull} restrictions.<br/>
* Sub classes override this method to consider other restrictions.
*
* @param cd The {@link ConstraintDescriptor} to consider for this attribute.
*/
protected void initMetaDataBeanConstraint(ConstraintDescriptor<?> cd) {
MetaData metaData = getOwnMetaDataWithoutPmInitCall();
if (cd.getAnnotation() instanceof NotNull) {
metaData.valueRestriction = Restriction.REQUIRED;
}
else if (cd.getAnnotation() instanceof Size) {
Size annotation = (Size)cd.getAnnotation();
if (annotation.min() > 0) {
metaData.minLen = annotation.min();
}
if (annotation.max() < Integer.MAX_VALUE) {
metaData.maxLen = annotation.max();
}
}
}
/**
* Shared meta data for all attributes of the same kind.
* E.g. for all 'myapp.User.name' attributes.
*/
protected static class MetaData extends PmObjectBase.MetaData {
static final Object NOT_INITIALIZED = "NOT_INITIALIZED";
/* package */ BeanAttrAccessor beanAttrAccessor;
private PmOptionSetDef<PmAttr<?>> optionSetDef = OptionSetDefNoOption.INSTANCE;
private PmOptionCfg.NullOption nullOption = NullOption.DEFAULT;
private boolean hideIfDefaultValue = false;
private boolean hideIfEmptyValue = false;
private boolean required;
private Restriction valueRestriction = Restriction.NONE;
/* package */ boolean primitiveType;
private boolean embeddedAttr;
private PathResolver valuePathResolver;
private PathResolver valueContainingObjPathResolver = PassThroughPathResolver.INSTANCE;
private String formatResKey;
private String defaultValueString;
private CacheMetaData optionsCache = CacheMetaData.NO_CACHE;
private CacheMetaData valueCache = CacheMetaData.NO_CACHE;
private StringConverter<?> stringConverter;
private ValueConverter<?, ?> valueConverter;
/* package */ BackingValueAccessStrategy valueAccessStrategy = ValueAccessLocal.INSTANCE;
/** Name of the field configured for JSR 303-validation.<br>
* Is <code>null</code> if there is nothing to validate this way. */
private String validationFieldName;
private PmAttrCfg.Validate validate = PmAttrCfg.Validate.ON_VALIDATE_CALL;
/** if to validate length of the value String representation */
private boolean validateLengths = true;
private int maxLen = -1;
private int minLen = 0;
private int maxLenDefault;
/** Creates meta data using a maxDefaultLen of 255. */
public MetaData() {
this(255);
}
/**
* @param maxDefaultLen the attribute type specific maximum number of characters.
*/
public MetaData(int maxDefaultLen) {
this.maxLenDefault = maxDefaultLen;
}
@Override
protected void onPmInit(PmObjectBase pm) {
super.onPmInit(pm);
InternalPmCacheCfgUtil.registerClearOnListeners(pm, CacheKind.OPTIONS, optionsCache.cacheClearOn);
InternalPmCacheCfgUtil.registerClearOnListeners(pm, CacheKind.VALUE, valueCache.cacheClearOn);
}
/** @return The statically defined option set algorithm. */
public PmOptionSetDef<PmAttr<?>> getOptionSetDef() { return optionSetDef; }
public PmOptionCfg.NullOption getNullOption() { return nullOption; }
public String getFormatResKey() { return formatResKey; }
public void setFormatResKey(String formatResKey) { this.formatResKey = formatResKey; }
public StringConverter<?> getStringConverter() { return stringConverter; }
/**
* Defines a <b>state less</b> string converter. Converters that need to have PM state information
* should be provided by overriding {@link PmAttrBase#getStringConverterImpl()}.
* @param converter The state less string converter.
*/
public void setStringConverter(StringConverter<?> converter) { this.stringConverter = converter; }
/**
* Defines a <b>state less</b> value converter. Converters that need to have PM state information
* should be provided by overriding {@link PmAttrBase#getValueConverterImpl()}.
* @param stringConverter The state less value converter.
*/
public void setValueConverter(ValueConverter<?, ?> vc) { this.valueConverter = vc; }
public boolean isRequired() { return required; }
public void setRequired(boolean required) { this.required = required; }
public int getMinLen() { return minLen; }
public int getMaxLen() {
if (maxLen == -1) {
maxLen = getMaxLenDefault();
}
return maxLen;
}
/**
* Provides the attribute type specific default max length.
*
* @return The maximal number of characters default.
*/
protected int getMaxLenDefault() {
return maxLenDefault;
}
/**
* @return <code>true</code> if the attribute is child of another attr.
*/
public boolean isEmbeddedAttr() {
return embeddedAttr;
}
/**
* @return the validateLengths
*/
public boolean isValidateLengths() {
// FIXME oboede: re-activate that asap.
return false; // validateLengths;
}
/**
* @param validateLengths the validateLengths to set
*/
public void setValidateLengths(boolean validateLengths) {
this.validateLengths = validateLengths;
}
}
/**
* The default implementation defines meta data for an attribute with
* 'unlimited' length ({@link Short#MAX_VALUE}).
*/
@Override
protected PmObjectBase.MetaData makeMetaData() {
return new MetaData(Short.MAX_VALUE);
}
private final MetaData getOwnMetaData() {
return (MetaData) getPmMetaData();
}
private final MetaData getOwnMetaDataWithoutPmInitCall() {
return (MetaData) getPmMetaDataWithoutPmInitCall();
}
interface BackingValueAccessStrategy {
Object getValue(PmAttrBase<?, ?> attr);
void setValue(PmAttrBase<?, ?> attr, Object value);
Object getPropertyContainingBean(PmAttrBase<?, ?> attr);
}
static class ValueAccessLocal implements BackingValueAccessStrategy {
static final BackingValueAccessStrategy INSTANCE = new ValueAccessLocal();
@Override
public Object getValue(PmAttrBase<?, ?> attr) {
return attr.dataContainer != null
? attr.dataContainer.localValue
: null;
}
@Override
public void setValue(PmAttrBase<?, ?> attr, Object value) {
attr.zz_getDataContainer().localValue = value;
}
@Override
public Object getPropertyContainingBean(PmAttrBase<?, ?> attr) {
return null;
}
}
static class ValueAccessSessionProperty implements BackingValueAccessStrategy {
static final BackingValueAccessStrategy INSTANCE = new ValueAccessSessionProperty();
@Override
public Object getValue(PmAttrBase<?, ?> attr) {
return attr.getPmConversation().getPmNamedObject(PmUtil.getAbsoluteName(attr));
}
@Override
public void setValue(PmAttrBase<?, ?> attr, Object value) {
attr.getPmConversation().setPmNamedObject(PmUtil.getAbsoluteName(attr), value);
}
@Override
public Object getPropertyContainingBean(PmAttrBase<?, ?> attr) {
return null;
}
}
// TODO: should disappear as soon as the value strategy configuration is complete.
static class ValueAccessOverride implements BackingValueAccessStrategy {
static final BackingValueAccessStrategy INSTANCE = new ValueAccessOverride();
@Override
public Object getValue(PmAttrBase<?, ?> attr) {
throw new PmRuntimeException(attr, "getBackingValueImpl() method is not implemented.");
}
@Override
public void setValue(PmAttrBase<?, ?> attr, Object value) {
throw new PmRuntimeException(attr, "setBackingValueImpl() method is not implemented.");
}
@Override
public Object getPropertyContainingBean(PmAttrBase<?, ?> attr) {
return null;
}
}
static class ValueAccessByExpression implements BackingValueAccessStrategy {
static final BackingValueAccessStrategy INSTANCE = new ValueAccessByExpression();
@Override
public Object getValue(PmAttrBase<?, ?> attr) {
return attr.getOwnMetaData().valuePathResolver.getValue(attr.getPmParent());
}
@Override
public void setValue(PmAttrBase<?, ?> attr, Object value) {
attr.getOwnMetaData().valuePathResolver.setValue(attr.getPmParent(), value);
}
@Override
public Object getPropertyContainingBean(PmAttrBase<?, ?> attr) {
return attr.getOwnMetaData().valueContainingObjPathResolver.getValue(attr.getPmParent());
}
}
static class ValueAccessReflection implements BackingValueAccessStrategy {
static final BackingValueAccessStrategy INSTANCE = new ValueAccessReflection();
@Override
public Object getValue(PmAttrBase<?, ?> attr) {
Object bean = getParentPmBean(attr).getPmBean();
return bean != null
? attr.getOwnMetaData().beanAttrAccessor.<Object>getBeanAttrValue(bean)
: null;
}
@Override
public void setValue(PmAttrBase<?, ?> attr, Object value) {
Object bean = getParentPmBean(attr).getPmBean();
if (bean == null) {
throw new PmRuntimeException(attr, "Unable to access an attribute value for a backing pmBean that is 'null'.");
}
attr.getOwnMetaData().beanAttrAccessor.setBeanAttrValue(bean, value);
}
@Override
public Object getPropertyContainingBean(PmAttrBase<?, ?> attr) {
return getParentPmBean(attr).getPmBean();
}
@SuppressWarnings("unchecked")
private PmBean<Object> getParentPmBean(PmAttrBase<?, ?> attr) {
if (attr.parentPmBean == null) {
attr.parentPmBean = PmUtil.getPmParentOfType(attr, PmBean.class);
}
return attr.parentPmBean;
}
}
/**
* A command that changes an attribute value.
*/
@PmTitleCfg(resKey="pmValueChangeCommand")
@PmCommandCfg(beforeDo=BEFORE_DO.DO_NOTHING)
public static class ValueChangeCommandImpl<T_VALUE> extends PmCommandImpl implements ValueChangeCommand<T_VALUE> {
private final T_VALUE oldValue;
private final T_VALUE newValue;
public ValueChangeCommandImpl(PmAttrBase<T_VALUE,?> changedPmAttr, T_VALUE oldValue, T_VALUE newValue) {
super(changedPmAttr);
this.oldValue = oldValue;
this.newValue = newValue;
setUndoCommand(new ValueChangeCommandImpl<T_VALUE>(this));
}
/**
* Constructor for the corresponding undo command.
*
* @param doCommand The command to undo.
*/
private ValueChangeCommandImpl(ValueChangeCommandImpl<T_VALUE> doCommand) {
super(doCommand.getPmParent());
this.newValue = doCommand.oldValue;
this.oldValue = doCommand.newValue;
setUndoCommand(doCommand);
}
@Override @SuppressWarnings("unchecked")
protected void doItImpl() throws Exception {
((PmAttrBase<Object, ?>)getPmParent()).setValue(newValue);
}
/**
* The referenced presentation model should be enabled.
*/
@Override
protected boolean isPmEnabledImpl() {
return super.isPmEnabledImpl() && getPmParent().isPmEnabled();
}
protected NaviLink afterDo(boolean changeCommandHistory) {
if (changeCommandHistory) {
getPmConversationImpl().getPmCommandHistory().commandDone(this);
}
// PmEventApi.firePmEvent(this, PmEvent.EXEC_COMMAND);
return null;
}
public T_VALUE getNewValue() {
return newValue;
}
public T_VALUE getOldValue() {
return oldValue;
}
@SuppressWarnings("unchecked")
@Override
public PmAttr<T_VALUE> getPmAttr() {
return (PmAttr<T_VALUE>) getPmParent();
}
}
}
|
package org.worshipsongs.utils;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.preference.PreferenceManager;
import org.junit.After;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.worshipsongs.CommonConstants;
import org.worshipsongs.BuildConfig;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
/**
* Author : Madasamy
* Version : 3.x
*/
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 22)
public class CommonUtilsTest
{
private SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(RuntimeEnvironment.application.getApplicationContext());
@After
public void tearDown()
{
sharedPreferences.edit().clear().apply();
}
@Test
public void testIsProductionMode()
{
System.out.println("--isProductionMode
assertTrue(CommonUtils.isProductionMode());
}
@Test
public void testIsJellyBeanMrOrGreater()
{
System.out.println("--isJellyBeanMrOrGreater
assertTrue(CommonUtils.isJellyBeanMrOrGreater());
}
@Config(sdk = Build.VERSION_CODES.JELLY_BEAN)
@Test
public void testIsNotJellyBeanMR()
{
System.out.println("--isNotJellyBeanMR
assertFalse(CommonUtils.isJellyBeanMrOrGreater());
}
@Test
public void testIsLolliPopOrGreater()
{
System.out.println("--isLolliPopOrGreater
assertTrue(CommonUtils.isLollipopOrGreater());
}
@Config(sdk = Build.VERSION_CODES.KITKAT)
@Test
public void testIsNotLollipop()
{
System.out.println("--IsNotLollipop
assertFalse(CommonUtils.isLollipopOrGreater());
}
//Note: Update this test every major release
@Test
public void testGetProjectVersion()
{
String version = CommonUtils.getProjectVersion();
assertTrue(version.contains("3."));
}
@Test
public void testIsNotImportedDatabase() throws Exception
{
assertTrue(CommonUtils.isNotImportedDatabase());
}
@Test
public void testIsImportedDatabase() throws Exception
{
sharedPreferences.edit().putBoolean(CommonConstants.SHOW_REVERT_DATABASE_BUTTON_KEY, true).apply();
assertFalse(CommonUtils.isNotImportedDatabase());
}
@Test
public void testIsNewVersion()
{
assertTrue(CommonUtils.isNewVersion("3.x", "100.34"));
}
@Test
public void testIsNewVersionEmptyVersionInPropertyFile()
{
assertTrue(CommonUtils.isNewVersion("3.x", ""));
}
@Test
public void testIsNotNewVersion() throws PackageManager.NameNotFoundException
{
assertFalse(CommonUtils.isNewVersion("3.x", "3.x"));
}
}
|
package uk.gov.openregister.store.postgresql;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.IntNode;
import com.fasterxml.jackson.databind.node.TextNode;
import org.joda.time.DateTime;
import org.postgresql.util.PGobject;
import play.libs.Json;
import uk.gov.openregister.domain.Record;
import uk.gov.openregister.domain.RecordVersionInfo;
import uk.gov.openregister.store.DatabaseConflictException;
import uk.gov.openregister.store.DatabaseException;
import uk.gov.openregister.store.Store;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
public class PostgresqlStore implements Store {
private final DBInfo dbInfo;
private Database database;
private final DatabaseSchema databaseSchema;
public PostgresqlStore(DBInfo dbInfo, DataSource dataSource) {
this.dbInfo = dbInfo;
this.database = new Database(dataSource);
databaseSchema = new DatabaseSchema(database, dbInfo);
databaseSchema.createIfNotExist();
}
@Override
public void save(Record record) {
String hash = record.getHash();
PGobject entryObject = createPGObject(record.normalisedEntry());
try (Connection connection = database.getConnection()) {
connection.setAutoCommit(false);
final String searchableText = canonicalizeEntryText(record.getEntry());
try (PreparedStatement st = connection.prepareStatement("INSERT INTO " + dbInfo.tableName + " (hash, entry, lastUpdated, searchable) " +
"( select ?,?,?,to_tsvector(?) where not exists ( select 1 from " + dbInfo.tableName + " where entry ->>?=?))")) {
st.setObject(1, hash);
st.setObject(2, entryObject);
st.setTimestamp(3, new Timestamp(record.getLastUpdated().getMillis()));
st.setString(4, searchableText);
st.setObject(5, dbInfo.primaryKey);
st.setObject(6, primaryKeyValue(record));
int result = st.executeUpdate();
if (result == 0) {
throw new DatabaseException("No record inserted, a record with primary key value already exists");
}
}
try (PreparedStatement st = connection.prepareStatement("INSERT INTO " + dbInfo.historyTableName + "(hash, entry, lastUpdated) VALUES(?, ?, ?)")) {
st.setObject(1, hash);
st.setObject(2, entryObject);
st.setTimestamp(3, new Timestamp(record.getLastUpdated().getMillis()));
st.executeUpdate();
}
connection.commit();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void update(String oldhash, Record record) {
try (Connection connection = database.getConnection()) {
connection.setAutoCommit(false);
String newHash = record.getHash();
PGobject entryObject = createPGObject(record.normalisedEntry());
entryObject.setType("jsonb");
Timestamp timestamp = new Timestamp(record.getLastUpdated().getMillis());
String searchableText = canonicalizeEntryText(record.getEntry());
try (PreparedStatement st = connection.prepareStatement("INSERT INTO " + dbInfo.tableName + " (hash, entry, lastUpdated, previousEntryHash, searchable) " +
"( select ?,?,?,?,to_tsvector(?) where exists ( select 1 from " + dbInfo.tableName + " where hash=? and entry ->>?=?))")) {
st.setObject(1, newHash);
st.setObject(2, entryObject);
st.setTimestamp(3, timestamp);
st.setObject(4, oldhash);
st.setString(5, searchableText);
st.setObject(6, oldhash);
st.setObject(7, dbInfo.primaryKey);
st.setObject(8, primaryKeyValue(record));
int result = st.executeUpdate();
if (result == 0) {
throw new DatabaseConflictException("Either this record is outdated or attempted to update the primary key value.");
}
}
try (PreparedStatement st = connection.prepareStatement("DELETE FROM " + dbInfo.tableName + " where hash=?")) {
st.setObject(1, oldhash);
st.executeUpdate();
}
try (PreparedStatement st = connection.prepareStatement("INSERT INTO " + dbInfo.historyTableName + "(hash, entry, lastUpdated, previousEntryHash) VALUES(?, ?, ?, ?)")) {
st.setObject(1, newHash);
st.setObject(2, entryObject);
st.setTimestamp(3, timestamp);
st.setObject(4, oldhash);
st.executeUpdate();
}
connection.commit();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public void deleteAll() {
databaseSchema.drop();
databaseSchema.createIfNotExist();
}
@Override
public Optional<Record> findByKV(String key, String value) {
String query = String.format("SELECT * FROM %s WHERE entry @> '{\"%s\":\"%s\"}'::jsonb", dbInfo.tableName, key, value);
return database.<Optional<Record>>select(query).andThen(this::toOptionalRecord);
}
@Override
public List<RecordVersionInfo> previousVersions(String hash) {
// XXX hackity hack
List<RecordVersionInfo> versions = new ArrayList<>();
String currentHash = hash;
while (true) {
String previousHash = database.<String>select("SELECT previousEntryHash FROM " + dbInfo.historyTableName +
" WHERE hash = ?", currentHash
).andThen(resultSet -> {
resultSet.next();
return resultSet.getString("previousEntryHash");
});
if (previousHash == null || previousHash.isEmpty()) {
break;
}
Record record = findByHash(previousHash).get();
versions.add(
new RecordVersionInfo(record.getHash(), record.getLastUpdated())
);
currentHash = previousHash;
}
return versions;
}
@Override
public Optional<Record> findByHash(String hash) {
return database.<Optional<Record>>select("SELECT * FROM " + dbInfo.historyTableName + " WHERE hash = ?", hash).andThen(this::toOptionalRecord);
}
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
@Override
public List<Record> search(Map<String, String> map, int offset, int limit, boolean historic, boolean exact) {
final StringBuilder sqlBuilder = new StringBuilder("");
if (!map.isEmpty()) {
sqlBuilder.append(" WHERE ");
if (exact) {
sqlBuilder.append(map.keySet().stream().map(k -> String.format("entry @> '{\"%s\"=\"%s\"}'", k, map.get(k))).collect(Collectors.joining(" AND ")));
} else {
sqlBuilder.append("hash in (SELECT hash FROM " + dbInfo.tableName + " WHERE searchable @@ to_tsquery('" + map.values().stream().collect(Collectors.joining("&")).replaceAll("\\s", "&") + "'))");
map.forEach((k, v) -> sqlBuilder.append(" AND entry->>'" + k + "' ILIKE '%" + map.get(k) + "%'"));
}
}
return executeSearch(sqlBuilder.toString(), offset, limit, historic);
}
@Override
public List<Record> search(String query, int offset, int limit, boolean historic) {
String sql = "";
if (!dbInfo.keys.isEmpty()) {
String where = query.replaceAll("[\\p{Blank}]+", " & ");
if (!query.trim().isEmpty())
sql += " WHERE searchable @@ to_tsquery('" + where + "')";
}
return executeSearch(sql, offset, limit, historic);
}
private List<Record> executeSearch(String where, int offset, int limit, boolean historic) {
String sql = "SELECT * FROM " + (historic ? dbInfo.historyTableName : dbInfo.tableName);
sql += where;
if (historic) {
sql += " ORDER BY lastUpdated DESC";
}
sql += " LIMIT " + limit;
sql += " OFFSET " + offset;
return database.<List<Record>>select(sql).andThen(this::getRecords);
}
@Override
public long count() {
return database.<Long>select("select count from " + dbInfo.tableName + "_row_count").andThen(rs -> rs.next() ? rs.getLong(1) : 0);
}
@Override
public void fastImport(List<Record> records) {
try (Connection connection = database.getConnection()) {
connection.setAutoCommit(false);
try (PreparedStatement st1 = connection.prepareStatement("INSERT INTO " + dbInfo.tableName + " (hash, entry, lastUpdated, searchable) VALUES(?, ?, ?, to_tsvector(?))");
PreparedStatement st2 = connection.prepareStatement("INSERT INTO " + dbInfo.historyTableName + "(hash, entry, lastUpdated) VALUES(?, ?, ?)")) {
for (Record record : records) {
String hash = record.getHash();
PGobject entryObject = createPGObject(record.normalisedEntry());
entryObject.setType("jsonb");
Timestamp timestamp = new Timestamp(record.getLastUpdated().getMillis());
st1.setObject(1, hash);
st1.setObject(2, entryObject);
st1.setTimestamp(3, timestamp);
st1.setString(4, canonicalizeEntryText(record.getEntry()));
st1.addBatch();
st2.setObject(1, hash);
st2.setObject(2, entryObject);
st2.setObject(3, timestamp);
st2.addBatch();
}
st1.executeBatch();
st2.executeBatch();
}
connection.commit();
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
public static String canonicalizeEntryText(JsonNode entry) {
return ((Map<String, Object>) Json.fromJson(entry, Map.class))
.values()
.stream()
.map(v -> {
if (v instanceof List) return String.join(" ", (List<String>) v);
else return v.toString();
})
.filter(s -> !s.trim().equals(""))
.collect(Collectors.joining(" "));
}
//TODO: this will be deleted when we know the datatype of primary key
private Object primaryKeyValue(Record record) {
JsonNode jsonNode = record.getEntry().get(dbInfo.primaryKey);
if (jsonNode instanceof TextNode) {
return jsonNode.textValue();
} else if (jsonNode instanceof IntNode) {
return jsonNode.intValue();
} else {
throw new RuntimeException("Confirm is it acceptable???");
}
}
private PGobject createPGObject(String data) {
PGobject pgo = new PGobject();
pgo.setType("jsonb");
try {
pgo.setValue(data);
} catch (Exception e) { //success: api setter throws checked exception
}
return pgo;
}
private Optional<Record> toOptionalRecord(ResultSet resultSet) throws IOException, SQLException {
if (resultSet != null && resultSet.next()) {
return Optional.of(toRecord(resultSet));
} else {
return Optional.empty();
}
}
private Record toRecord(ResultSet resultSet) throws SQLException, IOException {
final String entry = resultSet.getString("entry");
final Timestamp lastUpdated = resultSet.getTimestamp("lastUpdated");
return new Record(new ObjectMapper().readValue(entry, JsonNode.class), new DateTime(lastUpdated.getTime()));
}
private List<Record> getRecords(ResultSet resultSet) throws SQLException, IOException {
List<Record> result = new ArrayList<>();
while (resultSet.next()) {
result.add(toRecord(resultSet));
}
return result;
}
}
|
package taskmgt.Models;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import taskmgt.TaskSystem;
public class Project implements Serializable, Comparable<Project>{
//Attributes
private int id;
private String title;
private TeamLeader owner;
private Date startDate;
private Date endDate;
private State status;
private LinkedList<User> members = new LinkedList();
private LinkedList<Task> tasks = new LinkedList();
private final ModelType type = ModelType.Project;
private final SimpleDateFormat simpleDate = new SimpleDateFormat("MM/dd/yyyy");
//Constructor
public Project(String title,String owner, Date startDate, Date endDate){
this.title=title;
this.owner=(TeamLeader)TaskSystem.getUserByEmail(owner);
this.startDate=startDate;
this.endDate=endDate;
this.status=State.New;
this.setID();
}
public Project(String[] strArr) {
this.id = Integer.parseInt(strArr[0]);
this.title = strArr[1];
this.owner = (TeamLeader)TaskSystem.getUserByEmail(strArr[2]);
try {
this.startDate = simpleDate.parse(strArr[3]);
this.endDate = simpleDate.parse(strArr[4]);
} catch (ParseException ex) {
Logger.getLogger(Project.class.getName()).log(Level.SEVERE, null, ex);
}
this.status = State.valueOf(strArr[5]);
}
//Get
public int getID() { return this.id; }
public String getTitle() { return this.title; }
public String getOwner() { return this.owner.getEmail(); }
public Date getStartDate() { return this.startDate; }
public Date getEndDate() { return this.endDate; }
public State getStatus() { return this.status; }
public ModelType getType() { return this.type; }
public LinkedList<User> getMembers() { return this.members; }
public LinkedList<Task> getTasks() { return this.tasks; }
//Set
public void setTitle(String title){ this.title=title;}
public void setOwner(String owner){this.owner=(TeamLeader)TaskSystem.getUserByEmail(owner);}
public void setStartDate(Date startDate){this.startDate=startDate;}
public void setEndDate(Date endDate){this.endDate=endDate;}
// public void setStatus(State status){this.status=status;}
public void setMembers(LinkedList<User> members) { this.members = members; }
// public void setTasks(LinkedList<Task> tasks) { this.tasks = tasks; }
//Other methods
//Add to Collection
public void addTask(Task task){
if (task.getID() == 0)
task.setID(getNextTaskID());
tasks.add(task);
}
public void addMember(User user) { members.add(user); }
//Remove from Collection
public void removeTask(Task task) { tasks.remove(task); }
// public void removeMember(User user) { members.remove(user); }
public int getNextTaskID()
{
int max = 0;
for(Task task:tasks){
if(task!=null)
max=task.getID()>=max?task.getID():max;
}
return max+1;
}
public Task getTaskByID(int taskID){
for(Task task:tasks){
if(task.getID()==taskID){
return task;
}
}
return null;
}
// public LinkedList<Task> getTaskByMemberEmail(TeamMember member){
// LinkedList<Task> taskList=new LinkedList();
// for(Task task:tasks){
// if(task.getOwner().equalsIgnoreCase(member.getEmail()))
// taskList.add(task);
// return taskList;
// public int compareTo(Project p)
// return this.title.compareToIgnoreCase(p.title);
<<<<<<< HEAD
public int compareTo(String p){
return this.title.compareToIgnoreCase(p);
}
=======
// public int compareTo(String p)
// return this.title.compareToIgnoreCase(p);
>>>> f43cccbc8b9cfdf60cb242613cfc0b0e36530721
@Override
public int compareTo(Project p)
{
int retVal = this.startDate.compareTo(p.startDate);
if(retVal != 0) return retVal;
else{return this.id - p.getID();}
}
private void setID(){
int max=0;
for(Project project:TaskSystem.projectList){
if(project!=null)
max=project.getID()>=max?project.getID():max;
}
this.id=max+1;
}
public String[] toStringArray()
{
LinkedList<String> attrs = new LinkedList<>();
attrs.add(Integer.toString(id));
attrs.add(owner.getEmail());
attrs.add(title);
attrs.add(simpleDate.format(startDate));
attrs.add(simpleDate.format(endDate));
attrs.add(status.name());
for (Task t : tasks) {
attrs.add((Integer.toString(t.getID())));
attrs.add(t.getOwner());
attrs.add(t.getTitle());
attrs.add(Integer.toString(t.getProjectID()));
attrs.add(simpleDate.format(t.getStartDate()));
attrs.add(simpleDate.format(t.getEndDate()));
attrs.add(t.getStatus().name());
}
return attrs.toArray(new String[attrs.size()]);
}
@Override
public boolean equals(Object obj){
if(obj instanceof Project){
Project project=(Project) obj;
return project.title.compareToIgnoreCase(this.title)==0;
}
return false;
}
@Override
public int hashCode() {
int hash = 7;
hash = 73 * hash + Objects.hashCode(this.title);
return hash;
}
@Override
public String toString() {
String p = String.format("%-30s%-30s%-30s", "PROJECT:" + title,"START DATE:" + simpleDate.format(startDate),"END DATE:" + simpleDate.format(endDate));
return(p);
}
}
|
package bento.runtime;
import bento.lang.*;
import java.lang.reflect.Array;
import java.util.*;
public class Context {
/** Value to pass to setErrorThreshhold to redirect everything. */
public final static int EVERYTHING = 0;
/** Value to pass to setErrorThreshhold to redirect all warnings and errors. */
public final static int WARNINGS = 1;
/**
* Value to pass to setErrorThreshhold to ignore warnings and redirect all
* errors, including ignorable ones such as undefined instances.
*/
public final static int IGNORABLE_ERRORS = 2;
/**
* Value to pass to setErrorThreshhold to ignore warnings and ignorable errors
* and redirect all functional and fatal errors.
*/
public final static int FUNCTIONAL_ERRORS = 3;
/** Value to pass to setErrorThreshhold to ignore everything except for fatal errors. */
public final static int FATAL_ERRORS = 4;
private final static int MAX_POINTER_CHAIN_LENGTH = 10;
private final static int DEFAULT_MAX_CONTEXT_SIZE = 250;
private final static void vlog(String str) {
SiteBuilder.vlog(str);
}
/** Anything bigger than this will be treated as runaway recursion. The default value
* is DEFAULT_MAX_CONTEXT_SIZE.
**/
private static int maxSize = DEFAULT_MAX_CONTEXT_SIZE;
/** Set the maximum size for any context. The maximum number of levels of nesting
* may be slightly less than this number, since some constructions require temporary
* pushing of additional definitions onto the stack during instantiation.
*/
public static void setGlobalMaxSize(int max) {
maxSize = max;
}
/** A static class instantiated once per context tree capable of generating id
* values which are globally unique within a context tree (a root context and
* all contexts copied and cloned from it).
*
* State id's are nonnegative integers (along with the special value -1 for
* an empty context), meaning there are about 2 billion unique states. The
* id generator will roll over safely when it hits the limit and continue
* to generate nonnegative id's, but those id's are no longer absolutely
* guaranteed to be unique.
*
* To minimize the possibility of nonunique states, the rollover logic skips
* low id values, so that id values up to 1000 <i>are</i> guaranteed to remain
* unique.
*/
private static class StateFactory {
/** The value to which the state wraps around to. Global and persistent state
* values will most likely have low values, so the wrap around value should
* be well above zero.
*/
private final static int WRAP_AROUND_STATE = 1001;
private int state = -1;
public StateFactory() {}
public int nextState() {
++state;
if (state < 0) {
// wrap arround
state = WRAP_AROUND_STATE;
}
return state;
}
public int lastState() { return state; }
}
/** Dereferences the passed definition if necessary to return the proper
* definition to push on the context.
* @throws Redirection
*/
private Definition getContextDefinition(Definition definition) {
Definition contextDef = null;
// first resolve element references to element definitions,
// which are handled below
if (definition instanceof ElementReference) {
try {
Definition elementDef = ((ElementReference) definition).getElementDefinition(this);
if (elementDef != null) {
definition = elementDef;
}
} catch (Redirection r) {
throw new IllegalStateException("Redirection on attempt to get element definition: " + r);
}
}
if (definition instanceof DefinitionFlavor) {
contextDef = ((DefinitionFlavor) definition).def;
} else if (definition instanceof TypeDefinition) {
contextDef = ((TypeDefinition) definition).def;
//} else if (definition instanceof ElementReference) {
// // array and table references defer to their collections for context.
// contextDef = ((ElementReference) definition).getCollectionDefinition();
} else if (definition instanceof ElementDefinition) {
Object element = ((ElementDefinition) definition).getElement(this);
if (element instanceof Definition) {
contextDef = getContextDefinition((Definition) element);
} else if (element instanceof Instantiation) {
Instantiation instance = (Instantiation) element;
contextDef = getContextDefinition(instance.getDefinition(this));
}
}
if (contextDef != null) {
return contextDef;
} else {
// anything else has to be a named definition
return definition;
}
}
public static String makeGlobalKey(String fullName) {
return fullName;
}
/** Takes a cache key and strips off modifiers indicating arguments or loop index. */
public static String baseKey(String key) {
// argument modifier
int ix = key.indexOf('(');
if (ix > 0) {
key = key.substring(0, ix);
} else {
// loop modifier
ix = key.indexOf('
if (ix > 0) {
key = key.substring(0, ix);
}
}
return key;
}
private static int instanceCount = 0;
public static int getNumContextsCreated() {
return instanceCount;
}
private static int numClonedContexts = 0;
public static int getNumClonedContexts() {
return numClonedContexts;
}
// Context properties
private Context rootContext;
private StateFactory stateFactory;
private Entry rootEntry = null;
private Entry topEntry = null;
private Entry popLimit = null;
private Definition definingDef = null;
private NamedDefinition instantiatedDef = null;
private Map<String, Object> cache = null;
private Map<String, Pointer> keepMap = null;
private Map<String, Map<String,Object>> siteCaches = null;
private Map<String, Object> globalCache = null;
private Session session = null;
private int stateCount;
private int size = 0;
private int errorThreshhold = EVERYTHING;
private Stack<Entry> unpushedEntries = null;
// only root entries have nonull values for abandonedEntries
private Entry abandonedEntries = null;
// debugging interface
private BentoDebugger debugger = null;
/** Constructs a context beginning with the specified definition */
public Context(Definition def) throws Redirection {
this(def, null, null);
}
/** Constructs a context beginning with the specified definition, parameters
* and arguments.
*/
private Context(Definition def, ParameterList params, ArgumentList args) throws Redirection {
instanceCount++;
rootContext = this;
stateFactory = new StateFactory();
stateCount = stateFactory.lastState();
cache = newHashMap(Object.class);
keepMap = newHashMap(Pointer.class);
siteCaches = newHashMapOfMaps(Object.class);
globalCache = newHashMap(Object.class);
unpushedEntries = new Stack<Entry>();
if (def != null) {
try {
push(def, params, args, true);
} catch (Redirection r) {
vlog("Error creating context: " + r.getMessage());
throw r;
}
}
popLimit = topEntry;
}
/** Constructs a new context with the specified root entry.
* @throws Redirection
*/
public Context(Entry rootEntry) throws Redirection {
// initialize according to root entry
instanceCount++;
rootContext = this;
stateFactory = new StateFactory();
stateCount = stateFactory.lastState();
cache = newHashMap(Object.class);
keepMap = newHashMap(Pointer.class);
siteCaches = newHashMapOfMaps(Object.class);
globalCache = newHashMap(Object.class);
unpushedEntries = new Stack<Entry>();
push(newEntry(rootEntry, true));
popLimit = topEntry;
}
/** Constructs a context which is a copy of the passed context.
*/
public Context(Context context, boolean clearCache) {
instanceCount++;
copy(context, clearCache);
}
public Context.Entry getRootEntry() {
return rootEntry;
}
public int getErrorThreshhold() {
return errorThreshhold;
}
public void setErrorThreshhold(int threshhold) {
errorThreshhold = threshhold;
}
public BentoDebugger getDebugger() {
return debugger;
}
public void setDebugger(BentoDebugger debugger) {
this.debugger = debugger;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public Map<String, Object> getCache() {
return cache;
}
public Map<String, Pointer> getKeepMap() {
return keepMap;
}
public Map<String, Object> getSiteCache(String name) {
return siteCaches.get(name);
}
public Map<String, Object> getGlobalCache(String name) {
return globalCache;
}
void addKeeps(Definition def) throws Redirection {
if (def != null && def instanceof NamedDefinition) {
List<KeepStatement> keeps = ((NamedDefinition) def).getKeeps();
if (keeps != null) {
Iterator<KeepStatement> it = keeps.iterator();
while (it.hasNext()) {
KeepStatement k = it.next();
try {
keep(k);
} catch (Redirection r) {
vlog("Error in keep statement: " + r.getMessage());
throw r;
}
}
}
List<InsertStatement> inserts = ((NamedDefinition) def).getInserts();
if (inserts != null) {
Iterator<InsertStatement> it = inserts.iterator();
while (it.hasNext()) {
InsertStatement i = it.next();
try {
insert(i);
} catch (Redirection r) {
vlog("Error in insert statement: " + r.getMessage());
throw r;
}
}
}
}
}
@SuppressWarnings("unchecked")
private void keep(KeepStatement k) throws Redirection {
Map<String, Object> table = null;
Instantiation instance = k.getTableInstance();
// the current container entry; this is the entry corresponding to the code
// block containing the instantiation being constructed.
Entry containerEntry = null;
Map<String, Object> containerTable = null;
String containerKey = null;
boolean inContainer = k.isInContainer(this);
if (inContainer) {
// back up to the new frame entry
for (Entry entry = topEntry; entry.getPrevious() != null; entry = entry.getPrevious()) {
if (entry.superdef == null) {
containerEntry = entry.getPrevious();
containerTable = containerEntry.getKeepCache();
break;
}
}
table = containerTable;
} else if (instance == null) {
table = topEntry.getKeepCache();
} else {
NamedDefinition def = (NamedDefinition) instance.getDefinition(this);
if (def instanceof CollectionDefinition) {
CollectionDefinition collectionDef = (CollectionDefinition) def; // ((TableDefinition) def).initCollection(this);
CollectionInstance collection = collectionDef.getCollectionInstance(this, instance.getArguments(), instance.getIndexes());
if (collectionDef.isTable()) {
table = (Map<String, Object>) collection.getCollectionObject();
} else {
table = new MappedArray(collection.getCollectionObject(), this);
}
} else {
Object tableObject = instance.getData(this);
if (tableObject == null || tableObject.equals(NullValue.NULL_VALUE)) {
throw new Redirection(Redirection.STANDARD_ERROR, "error in keep: table " + instance.getName() + " not found");
}
if (tableObject instanceof AbstractNode) {
def.initNode((AbstractNode) tableObject);
}
if (tableObject instanceof Map<?,?>) {
table = (Map<String, Object>) tableObject;
} else if (tableObject instanceof List || tableObject.getClass().isArray()) {
table = new MappedArray(tableObject, this);
} else if (tableObject instanceof CollectionInstance) {
Object obj = ((CollectionInstance) tableObject).getCollectionObject();
if (obj instanceof Map<?,?>) {
table = (Map<String, Object>) obj;
} else {
table = new MappedArray(obj, this);
}
} else if (tableObject instanceof CollectionDefinition) {
CollectionInstance collection = ((CollectionDefinition) tableObject).getCollectionInstance(this, instance.getArguments(), instance.getIndexes());
if (((CollectionDefinition) tableObject).isTable()) {
table = (Map<String, Object>) collection.getCollectionObject();
} else {
table = new MappedArray(collection.getCollectionObject(), this);
}
}
}
}
if (table != null) {
ResolvedInstance[] resolvedInstances = k.getResolvedInstances(this);
Name asName = k.getAsName(this);
Name byName = k.getByName();
String key = null;
boolean asthis = false;
if (asName != null) {
key = asName.getName();
if (key == Name.THIS) {
key = topEntry.def.getName();
asthis = true;
}
} else if (byName != null) {
NameNode keepName = k.getDefName();
Definition owner = getDefiningDef();
KeepHolder keepHolder = new KeepHolder(keepName, owner, resolvedInstances, (NameNode) byName, table, k.isPersist(), inContainer, asthis);
topEntry.addDynamicKeep(keepHolder);
return;
}
containerKey = (asthis ? key : topEntry.def.getName() + (key == null ? "." : "." + key));
topEntry.addKeep(resolvedInstances, key, table, containerKey, containerTable, k.isPersist(), keepMap, cache);
}
}
private void setKeepsFromEntry(Entry entry) {
topEntry.copyKeeps(entry);
}
private void addKeepsFromEntry(Entry entry) {
topEntry.addKeeps(entry);
}
private void insert(InsertStatement i) throws Redirection {
topEntry.addInsert(i.getInsertedType(), i.getTargetType(), i.getInsertionPoint());
}
private void setInsertsFromEntry(Entry entry) {
topEntry.copyInserts(entry);
}
public Type getInsertedAbove(Type t) {
Entry entry = topEntry;
while (entry != null && t.equals(entry.def.getType())) {
entry = entry.link;
}
if (entry != null && entry.insertAboveMap != null) {
return (Type) entry.insertAboveMap.get(t.getName());
}
return null;
}
public Type getInsertedBelow(Type st, Type t) {
Entry entry = topEntry;
Definition topDef = topEntry.def;
while (entry != null && topDef.equals(entry.def)) {
entry = entry.link;
}
if (entry != null && entry.insertBelowMap != null) {
return (Type) entry.insertBelowMap.get(st.getName());
}
return null;
}
/** Looks through the context for the immediate subdefinition of the superdefinition at the
* top of the stack.
*/
private synchronized NamedDefinition getSubdefinition() {
// if there is no superdef in the top context entry, then there is
// no subdefinition
if (topEntry.superdef == null) {
return null;
}
int numUnpushes = 0;
Definition superdef = topEntry.superdef;
try {
while (topEntry != null) {
Definition subdef = (topEntry.superdef != null ? topEntry.superdef : topEntry.def);
NamedDefinition sd = subdef.getSuperDefinition(this);
if (sd != null && sd.includes(superdef)) {
return (NamedDefinition) subdef;
}
if (topEntry.link == null) {
break;
}
unpush();
numUnpushes++;
}
} finally {
while (numUnpushes > 0) {
repush();
numUnpushes
}
}
return null;
}
private Object constructSuper(NamedDefinition def, ArgumentList args, NamedDefinition instantiatedDef) throws Redirection {
return constructSuper(def, args, instantiatedDef, null);
}
private Object constructSuper(NamedDefinition def, ArgumentList args, NamedDefinition instantiatedDef, LinkedList<Definition> nextList) throws Redirection {
Object data = null;
boolean pushed = false;
boolean hasMore = (nextList != null && nextList.size() > 0);
if (!hasMore) {
ParameterList params = def.getParamsForArgs(args, this, false);
push(instantiatedDef, def, params, args);
pushed = true;
}
try {
List<Construction> constructions = def.getConstructions(this);
int numConstructions = (constructions == null ? 0 : constructions.size());
NamedDefinition superDef = def.getSuperDefinition(this);
if (!hasMore && superDef != null && (superDef.hasSub(this) || numConstructions == 0)) {
Type st = def.getSuper(this);
ArgumentList superArgs = (st != null ? st.getArguments(this) : null);
NamedDefinition superFlavor = (NamedDefinition) superDef.getDefinitionForArgs(superArgs, this);
data = constructSuper(superFlavor, superArgs, instantiatedDef);
} else {
if (hasMore) {
Definition nextDef = nextList.removeFirst();
constructions = nextDef.getConstructions(this);
numConstructions = (constructions == null ? 0 : constructions.size());
}
if (numConstructions == 1) {
Construction object = constructions.get(0);
if (object instanceof SubStatement) {
NamedDefinition sub = (NamedDefinition) peek().def;
data = constructSub(sub, instantiatedDef);
} else if (object instanceof SuperStatement) {
Type st = def.getSuper(this);
ArgumentList superArgs = (st != null ? st.getArguments(this) : null);
NamedDefinition superFlavor = (NamedDefinition) superDef.getDefinitionForArgs(superArgs, this);
data = constructSuper(superFlavor, superArgs, instantiatedDef);
} else if (object instanceof NextStatement) {
data = constructSuper(def, args, instantiatedDef, nextList);
} else if (object instanceof RedirectStatement) {
RedirectStatement redir = (RedirectStatement) object;
throw redir.getRedirection(this);
} else if (object instanceof Value) {
data = object;
} else if (object instanceof ValueGenerator) {
data = ((ValueGenerator) object).getData(this);
} else {
data = object.getData(this);
}
if (data instanceof Value) {
data = ((Value) data).getValue();
} else if (data instanceof AbstractNode) {
instantiatedDef.initNode((AbstractNode) data);
}
} else if (numConstructions > 1) {
Iterator<Construction> it = constructions.iterator();
while (it.hasNext()) {
Construction chunk = it.next();
if (chunk == null) {
continue;
} else if (chunk instanceof RedirectStatement) {
RedirectStatement redir = (RedirectStatement) chunk;
throw redir.getRedirection(this);
} else {
Object chunkData = null;
if (chunk instanceof SubStatement) {
NamedDefinition sub = getSubdefinition();
Object subData = (sub == null ? null : constructSub(sub, instantiatedDef));
if (subData != null) {
if (subData instanceof Value) {
chunkData = ((Value) subData).getValue();
} else if (subData instanceof ValueGenerator) {
chunkData = ((ValueGenerator) subData).getValue(this);
} else {
chunkData = subData;
}
}
} else if (chunk instanceof SuperStatement) {
Type st = def.getSuper(this);
ArgumentList superArgs = (st != null ? st.getArguments(this) : null);
NamedDefinition superFlavor = (NamedDefinition) superDef.getDefinitionForArgs(superArgs, this);
Object superData = constructSuper(superFlavor, superArgs, instantiatedDef);
if (superData != null) {
if (superData instanceof Value) {
chunkData = ((Value) superData).getValue();
} else if (superData instanceof ValueGenerator) {
chunkData = ((ValueGenerator) superData).getValue(this);
} else {
chunkData = superData;
}
}
} else if (chunk instanceof NextStatement) {
chunkData = constructSuper(def, args, instantiatedDef, nextList);
} else {
chunkData = chunk.getData(this);
if (chunkData != null && chunkData instanceof Value) {
chunkData = ((Value) chunkData).getValue();
}
}
if (chunkData != null) {
if (data == null) {
data = chunkData;
} else {
data = PrimitiveValue.getStringFor(data) + chunkData;
}
}
}
}
}
}
} finally {
if (pushed) {
pop();
}
}
return data;
}
public Object constructSub(NamedDefinition def, NamedDefinition instantiatedDef) throws Redirection {
Object data = getLocalData("sub", null, null); // getData(null, "sub", null, null, null);
if (data != null) {
return data;
}
LinkedList<Definition> nextList = null;
// call the form of getSuperDefinition that does not take
// a context parameter, because we want the multidefinition
// if there is one.
Definition superDef = def.getSuperDefinition();
if (superDef != null && superDef.hasNext(this)) {
nextList = superDef.getNextList(this);
}
if (nextList != null && nextList.size() > 0) {
Definition nextDef = nextList.removeFirst();
data = constructSub(nextDef, instantiatedDef, nextList);
} else {
try {
unpush();
data = constructSub(def, instantiatedDef, null);
} finally {
repush();
}
}
if (data == null) {
data = NullValue.NULL_VALUE;
}
putData(def, null, null, "sub", data);
return data;
}
private Object constructSub(Definition def, NamedDefinition instantiatedDef, LinkedList<Definition> nextList) throws Redirection {
Object data = null;
List<Construction> constructions = def.getConstructions(this);
boolean hasMoreNext = (nextList != null && nextList.size() > 0);
if (constructions == null || constructions.size() == 0) {
NamedDefinition sub = getSubdefinition();
data = (sub == null ? null : constructSub(sub, instantiatedDef));
} else {
if (def.equals(instantiatedDef)) {
data = construct(constructions);
} else {
int n = constructions.size();
if (n == 1) {
Construction object = constructions.get(0);
if (object instanceof NextStatement) {
if (hasMoreNext) {
Definition nextDef = nextList.removeFirst();
data = constructSub(nextDef, instantiatedDef, nextList);
} else {
NamedDefinition sub = getSubdefinition();
if (sub == null) {
data = null;
} else {
try {
unpush();
data = constructSub(sub, instantiatedDef, null);
} finally {
repush();
}
}
}
} else if (object instanceof SubStatement) {
NamedDefinition sub = getSubdefinition();
data = (sub == null ? null : constructSub(sub, instantiatedDef));
} else if (object instanceof SuperStatement) {
Definition superDef = def.getSuperDefinition(this);
if (superDef == null) {
if (errorThreshhold <= Context.IGNORABLE_ERRORS) {
throw new Redirection(Redirection.STANDARD_ERROR, "Undefined superdefinition reference in " + def.getFullName());
} else {
data = null;
}
} else {
Type st = def.getSuper(this);
ArgumentList superArgs = (st != null ? st.getArguments(this) : null);
NamedDefinition superFlavor = (NamedDefinition) superDef.getDefinitionForArgs(superArgs, this);
data = constructSuper(superFlavor, superArgs, instantiatedDef);
}
} else if (object instanceof RedirectStatement) {
RedirectStatement redir = (RedirectStatement) object;
throw redir.getRedirection(this);
} else if (object instanceof Value) {
data = object;
} else if (object instanceof ValueGenerator) {
data = ((ValueGenerator) object).getData(this);
} else {
data = object.getData(this);
}
if (data instanceof Value) {
data = ((Value) data).getValue();
} else if (data instanceof AbstractNode) {
instantiatedDef.initNode((AbstractNode) data);
}
} else if (n > 1) {
Iterator<Construction> it = constructions.iterator();
while (it.hasNext()) {
Construction chunk = it.next();
if (chunk == null) {
continue;
} else if (chunk instanceof RedirectStatement) {
RedirectStatement redir = (RedirectStatement) chunk;
throw redir.getRedirection(this);
} else {
Object chunkData = null;
if (chunk instanceof NextStatement) {
Object subData = null;
if (hasMoreNext) {
Definition nextDef = nextList.removeFirst();
subData = constructSub(nextDef, instantiatedDef, nextList);
} else {
NamedDefinition sub = getSubdefinition();
if (sub == null) {
subData = null;
} else {
try {
unpush();
subData = constructSub(sub, instantiatedDef, null);
} finally {
repush();
}
}
}
if (subData != null) {
if (subData instanceof Value) {
chunkData = ((Value) subData).getValue();
} else if (subData instanceof ValueGenerator) {
chunkData = ((ValueGenerator) subData).getValue(this);
} else {
chunkData = subData;
}
}
} else if (chunk instanceof SubStatement) {
NamedDefinition sub = getSubdefinition();
Object subData = (sub == null ? null : constructSub(sub, instantiatedDef));
if (subData != null) {
if (subData instanceof Value) {
chunkData = ((Value) subData).getValue();
} else if (subData instanceof ValueGenerator) {
chunkData = ((ValueGenerator) subData).getValue(this);
} else {
chunkData = subData;
}
}
} else if (chunk instanceof SuperStatement) {
Definition superDef = def.getSuperDefinition(this);
if (superDef == null) {
if (errorThreshhold <= Context.IGNORABLE_ERRORS) {
throw new Redirection(Redirection.STANDARD_ERROR, "Undefined superdefinition reference in " + def.getFullName());
} else {
chunkData = null;
}
} else {
Type st = def.getSuper(this);
ArgumentList superArgs = (st != null ? st.getArguments(this) : null);
NamedDefinition superFlavor = (NamedDefinition) superDef.getDefinitionForArgs(superArgs, this);
Object superData = constructSuper(superFlavor, superArgs, instantiatedDef);
if (superData != null) {
if (superData instanceof Value) {
chunkData = ((Value) superData).getValue();
} else if (superData instanceof ValueGenerator) {
chunkData = ((ValueGenerator) superData).getValue(this);
} else {
chunkData = superData;
}
}
}
} else {
chunkData = chunk.getData(this);
if (chunkData != null && chunkData instanceof Value) {
chunkData = ((Value) chunkData).getValue();
}
}
if (chunkData != null) {
if (data == null) {
data = chunkData;
} else {
data = PrimitiveValue.getStringFor(data) + chunkData;
}
}
}
}
}
}
}
return data;
}
public Object construct(Definition definition, ArgumentList args) throws Redirection {
Object data = null;
boolean pushedSuperDef = false;
boolean pushedParamDef = false;
boolean pushedContext = false;
int pushedParams = 0;
Block catchBlock = (definition instanceof AnonymousDefinition ? ((AnonymousDefinition) definition).getCatchBlock() : null);
NamedDefinition oldInstantiatedDef = instantiatedDef;
if (definition instanceof NamedDefinition) {
instantiatedDef = (NamedDefinition) definition;
}
ParameterList params = null;
// determine if this defines a namespace and therefore a new context level.
// No need to push external definitions, because external names are
// resolved externally
if (!definition.isAnonymous() && !definition.isExternal()) {
if (definition.getName().equals("height_for_proto")) {
System.out.println("ctx 902: " + definition.getName());
}
// get the arguments and parameters, if any, to push on the
// context stack with the definition
params = definition.getParamsForArgs(args, this);
push(definition, params, args, true);
pushedContext = true;
}
try {
List<Construction> constructions = definition.getConstructions(this);
boolean constructed = false;
NamedDefinition superDef = definition.getSuperDefinition(this);
Type st = definition.getSuper(this);
if (!constructed && superDef != null && definition.getName() != Name.SUB) {
// check to see if this is an alias, and the alias definition extends or equals the
// superdefinition, in which case we shouldn't bother constructing the superdef here,
// it will get constructed when the alias is constructed
Definition aliasDef = null;
if (definition.isAliasInContext(this)) {
Instantiation aliasInstance = definition.getAliasInstanceInContext(this);
if (aliasInstance != null) {
if (definition.isParamAlias()) {
aliasInstance = aliasInstance.getUltimateInstance(this);
}
aliasDef = aliasInstance.getDefinition(this, definition);
//if (aliasDef != null) {
// return construct(aliasDef, aliasInstance.getArguments());
}
}
AbstractNode contents = definition.getContents();
Definition constructedDef = null;
if (contents instanceof Construction) {
Type constructedType = ((Construction) contents).getType(this, definition);
if (constructedType != null) {
constructedDef = constructedType.getDefinition();
}
}
if ((aliasDef == null || !aliasDef.equalsOrExtends(superDef))
&& (constructedDef == null || !constructedDef.equalsOrExtends(superDef))) {
ArgumentList superArgs = (st != null ? st.getArguments(this) : null);
NamedDefinition superFlavor = (NamedDefinition) superDef.getDefinitionForArgs(superArgs, this);
if (superFlavor != null && (superFlavor.hasSub(this) || (constructions == null || constructions.size() == 0))) {
NamedDefinition ndef = (NamedDefinition) peek().def;
data = constructSuper(superFlavor, superArgs, ndef);
constructed = true;
}
}
}
// not handled by one of the above cases
if (!constructed) {
if (definition.isAlias()) {
Construction construction = constructions.get(0);
if (construction instanceof Value) {
data = construction;
} else if (construction instanceof ValueGenerator) {
// no this isn't right
// if (construction instanceof Instantiation) {
// Instantiation instance = (Instantiation) construction;
// ArgumentList instanceArgs = instance.getArguments();
// if (instanceArgs != null) {
// if (args == null || instanceArgs.size() != args.size()) {
// construction = new Instantiation(instance, args, instance.getIndexes());
data = ((ValueGenerator) construction).getData(this);
} else {
data = construction.getData(this);
}
} else {
data = construct(constructions);
}
}
if (data instanceof Value) {
data = ((Value) data).getValue();
} else if (data instanceof AbstractNode) {
instantiatedDef.initNode((AbstractNode) data);
}
return data;
} catch (Redirection r) {
if (catchBlock != null) {
String location = r.getLocation();
String catchIdentifier = catchBlock.getCatchIdentifier();
while (catchIdentifier != null && catchIdentifier.length() > 0) {
if (catchIdentifier.equals(location)) {
return catchBlock.getData(this);
} else {
catchBlock = catchBlock.getCatchBlock();
if (catchBlock == null) {
throw r;
}
catchIdentifier = catchBlock.getCatchIdentifier();
}
}
return catchBlock.getData(this);
} else {
throw r;
}
} catch (Throwable t) {
if (catchBlock != null && catchBlock.getCatchIdentifier() == null) {
return catchBlock.getData(this);
} else {
String className = t.getClass().getName();
String message = t.getMessage();
if (message == null) {
message = className;
} else {
message = className + ": " + message;
}
t.printStackTrace();
throw new Redirection(Redirection.STANDARD_ERROR, message);
}
} finally {
if (pushedParams > 0) {
for (int i = 0; i < pushedParams; i++) {
popParam();
}
} else if (pushedContext) {
pop();
}
if (pushedSuperDef) {
pop();
}
if (pushedParamDef) {
pop();
}
instantiatedDef = oldInstantiatedDef;
}
}
public Object construct(List<Construction> constructions) throws Redirection {
Object data = null;
if (constructions != null) {
StringBuffer sb = null;
int n = constructions.size();
for (int i = 0; i < n; i++) {
Construction object = constructions.get(i);
if (object instanceof RedirectStatement) {
RedirectStatement redir = (RedirectStatement) object;
throw redir.getRedirection(this);
} else if (data == null) {
if (object instanceof SubStatement) {
NamedDefinition sub = getSubdefinition();
data = (sub == null ? null : constructSub(sub, instantiatedDef));
} else if (object instanceof SuperStatement) {
Definition def = peek().def;
NamedDefinition superDef = def.getSuperDefinition();
if (superDef == null) {
if (errorThreshhold <= Context.IGNORABLE_ERRORS) {
throw new Redirection(Redirection.STANDARD_ERROR, "Undefined superdefinition reference in " + def.getFullName());
} else {
data = null;
}
} else {
LinkedList<Definition> nextList = null;
if (superDef.hasNext(this)) {
nextList = superDef.getNextList(this);
}
// get the specific definition for this context
superDef = def.getSuperDefinition(this);
if (superDef == null) {
if (errorThreshhold <= Context.IGNORABLE_ERRORS) {
throw new Redirection(Redirection.STANDARD_ERROR, "Undefined superdefinition reference in " + def.getFullName());
} else {
data = null;
}
} else {
Type st = def.getSuper(this);
ArgumentList superArgs = (st != null ? st.getArguments(this) : null);
NamedDefinition superFlavor = (NamedDefinition) superDef.getDefinitionForArgs(superArgs, this);
data = constructSuper(superFlavor, superArgs, instantiatedDef, nextList);
}
}
} else if (object instanceof Value) {
data = object;
} else if (object instanceof Chunk) {
data = object.getData(this);
} else if (object instanceof ValueGenerator) {
data = ((ValueGenerator) object).getData(this);
} else {
data = object;
}
if (data instanceof Value) {
data = ((Value) data).getValue();
} else if (data instanceof AbstractNode) {
if (instantiatedDef != null) {
instantiatedDef.initNode((AbstractNode) data);
} else {
vlog("Null instantiatedDef in constructions for " + peek().def.getFullName());
}
}
} else {
String str = null;
if (object instanceof SubStatement) {
NamedDefinition sub = getSubdefinition();
if (sub != null) {
Object obj = constructSub(sub, instantiatedDef);
if (obj != null && !obj.equals(NullValue.NULL_VALUE)) {
str = obj.toString();
}
}
} else if (object instanceof SuperStatement) {
Definition def = peek().def;
NamedDefinition superDef = def.getSuperDefinition();
if (superDef == null) {
if (errorThreshhold <= Context.IGNORABLE_ERRORS) {
throw new Redirection(Redirection.STANDARD_ERROR, "Undefined superdefinition reference in " + def.getFullName());
} else {
str = null;
}
} else {
LinkedList<Definition> nextList = null;
if (superDef.hasNext(this)) {
nextList = superDef.getNextList(this);
}
// get the specific definition for this context
superDef = def.getSuperDefinition(this);
if (superDef == null) {
if (errorThreshhold <= Context.IGNORABLE_ERRORS) {
throw new Redirection(Redirection.STANDARD_ERROR, "Undefined superdefinition reference in " + def.getFullName());
} else {
str = null;
}
} else {
Type st = def.getSuper(this);
ArgumentList superArgs = (st != null ? st.getArguments(this) : null);
NamedDefinition superFlavor = (NamedDefinition) superDef.getDefinitionForArgs(superArgs, this);
Object obj = constructSuper(superFlavor, superArgs, instantiatedDef, nextList);
if (obj != null && !obj.equals(NullValue.NULL_VALUE)) {
str = obj.toString();
}
}
}
} else if (object instanceof Value) {
if (!object.equals(NullValue.NULL_VALUE)) {
str = ((Value) object).getString();
}
} else if (object instanceof Chunk) {
str = ((Chunk) object).getText(this);
} else if (object instanceof ValueGenerator) {
str = ((ValueGenerator) object).getValue(this).getString();
} else if (object != null) {
str = object.toString();
}
if (str != null && str.length() > 0) {
if (sb == null) {
sb = new StringBuffer(PrimitiveValue.getStringFor(data));
data = sb;
}
sb.append(str);
}
}
}
if (sb != null && data == sb) {
data = sb.toString();
}
}
return data;
}
private boolean addingDynamicKeeps = false;
@SuppressWarnings("unchecked")
synchronized private List<String>[] addDynamicKeeps(String name, ArgumentList args) throws Redirection {
if (addingDynamicKeeps) {
return null;
}
List<String> allAddedKeeps[] = (List<String>[]) new List[size];
int numUnpushes = 0;
int i = 0;
try {
addingDynamicKeeps = true;
while (topEntry != null) {
List<String> addedKeeps = null;
if (topEntry.dynamicKeeps != null) {
Iterator<KeepHolder> it = topEntry.dynamicKeeps.iterator();
Context clonedContext = this;
while (it.hasNext()) {
KeepHolder kh = it.next();
NameNode keepName = kh.keepName;
Definition keyOwner = kh.owner;
if (keepName.getName().equals(name)) {
if (addedKeeps == null) {
addedKeeps = new ArrayList<String>(4);
}
addedKeeps.add(name);
if (clonedContext == null) {
clonedContext = clone(false);
}
Definition keepDef = keyOwner.getChildDefinition(kh.keepName, clonedContext);
Object keyObj = null;
if (keepDef != null && keepDef.hasChildDefinition(kh.byName.getName())) {
// temporarily restore the stack in case the definition has to access
// parameters that have been unpushed; however, keep track with numUnpushes
// so as to not throw off the finally clause should there be an
// exception or redirection;
int rememberUnpushes = numUnpushes;
for (int j = 0; j < rememberUnpushes; j++) {
clonedContext.repush();
numUnpushes
}
ParameterList params = keepDef.getParamsForArgs(args, clonedContext);
try {
clonedContext.push(keepDef, params, args, false);
keyObj = keepDef.getChildData(kh.byName, null, clonedContext, args);
} finally {
clonedContext.pop();
}
for (int j = 0; j < rememberUnpushes; j++) {
clonedContext.unpush();
numUnpushes++;
}
} else {
keyObj = clonedContext.getData(null, kh.byName.getName(), args, null);
if (keyObj == null) {
keyObj = keyOwner.getChildData(kh.byName, null, clonedContext, args);
}
}
if (keyObj == null || keyObj.equals(NullValue.NULL_VALUE)) {
Instantiation keyInstance = new Instantiation(kh.byName, topEntry.def);
keyObj = keyInstance.getData(clonedContext);
if (keyObj == null || keyObj.equals(NullValue.NULL_VALUE)) {
throw new Redirection(Redirection.STANDARD_ERROR, "error in keep by directive: key is null");
}
}
String key = (keyObj instanceof Value ? ((Value) keyObj).getString() : keyObj.toString());
Entry containerEntry = null;
Map<String, Object> containerTable = null;
String containerKey = null;
if (kh.inContainer) {
// back up to the new frame entry
for (Entry e = topEntry; e.getPrevious() != null; e = e.getPrevious()) {
if (e.superdef == null) {
containerEntry = e.getPrevious();
containerTable = containerEntry.getCache();
break;
}
}
if (containerEntry != null) {
containerKey = (kh.asThis ? key : topEntry.def.getName() + (key == null ? "." : "." + key));
containerEntry.addKeep(kh.resolvedInstances, containerKey, containerTable, null, null, kh.persist, keepMap, cache);
}
} else {
topEntry.addKeep(kh.resolvedInstances, keyObj, kh.table, containerKey, containerTable, kh.persist, keepMap, cache);
}
}
}
}
allAddedKeeps[i++] = addedKeeps;
if (topEntry.link == null) {
break;
}
numUnpushes++;
unpush();
}
} finally {
while (numUnpushes > 0) {
repush();
numUnpushes
}
addingDynamicKeeps = false;
}
return allAddedKeeps;
}
synchronized private void removeDynamicKeeps(List<String>[] allAddedKeeps) {
Iterator<Entry> entryIt = iterator();
int i = 0;
while (entryIt.hasNext() && i < allAddedKeeps.length) {
Entry entry = entryIt.next();
try {
List<String> addedKeeps = allAddedKeeps[i];
if (addedKeeps != null) {
Iterator<String> it = addedKeeps.iterator();
while (it.hasNext()) {
String name = it.next();
entry.removeKeep(name);
}
}
} finally {
i++;
}
}
}
synchronized private void updateDynamicKeeps(String name, ArgumentList args) throws Redirection {
if (addingDynamicKeeps) {
return;
}
addingDynamicKeeps = true;
int numUnpushes = 0;
int i = 0;
try {
while (topEntry != null) {
if (topEntry.dynamicKeeps != null) {
Iterator<KeepHolder> it = topEntry.dynamicKeeps.iterator();
Context clonedContext = this;
while (it.hasNext()) {
KeepHolder kh = it.next();
NameNode keepName = kh.keepName;
Definition keyOwner = kh.owner;
if (keepName.getName().equals(name)) {
if (clonedContext == null) {
clonedContext = clone(false);
}
Definition keepDef = keyOwner.getChildDefinition(kh.keepName, clonedContext);
Object keyObj = null;
if (keepDef != null && keepDef.hasChildDefinition(kh.byName.getName())) {
// temporarily restore the stack in case the definition has to access
// parameters that have been unpushed; however, keep track with numUnpushes
// so as to not throw off the finally clause should there be an
// exception or redirection;
int rememberUnpushes = numUnpushes;
for (int j = 0; j < rememberUnpushes; j++) {
clonedContext.repush();
numUnpushes
}
ParameterList params = keepDef.getParamsForArgs(args, clonedContext);
try {
clonedContext.push(keepDef, params, args, false);
keyObj = keepDef.getChildData(kh.byName, null, clonedContext, args);
} finally {
clonedContext.pop();
}
for (int j = 0; j < rememberUnpushes; j++) {
clonedContext.unpush();
numUnpushes++;
}
} else {
keyObj = clonedContext.getData(null, kh.byName.getName(), args, null);
if (keyObj == null) {
keyObj = keyOwner.getChildData(kh.byName, null, clonedContext, args);
}
}
if (keyObj == null || keyObj.equals(NullValue.NULL_VALUE)) {
Instantiation keyInstance = new Instantiation(kh.byName, topEntry.def);
keyObj = keyInstance.getData(clonedContext);
if (keyObj == null || keyObj.equals(NullValue.NULL_VALUE)) {
throw new Redirection(Redirection.STANDARD_ERROR, "error in keep by directive: key is null");
}
}
String key = (keyObj instanceof Value ? ((Value) keyObj).getString() : keyObj.toString());
Entry containerEntry = null;
Map<String, Object> containerTable = null;
String containerKey = null;
if (kh.inContainer) {
// back up to the new frame entry
for (Entry e = topEntry; e.getPrevious() != null; e = e.getPrevious()) {
if (e.superdef == null) {
containerEntry = e.getPrevious();
containerTable = containerEntry.getCache();
break;
}
}
if (containerEntry != null) {
containerKey = (kh.asThis ? key : topEntry.def.getName() + (key == null ? "." : "." + key));
containerEntry.addKeep(kh.resolvedInstances, containerKey, containerTable, null, null, kh.persist, keepMap, cache);
}
} else {
topEntry.addKeep(kh.resolvedInstances, keyObj, kh.table, containerKey, containerTable, kh.persist, keepMap, cache);
}
}
}
}
if (topEntry.link == null) {
break;
}
numUnpushes++;
unpush();
}
} finally {
while (numUnpushes > 0) {
repush();
numUnpushes
}
addingDynamicKeeps = false;
}
}
/** Returns any cached data for a definition with the specified name
* in the current frame of the current context, or null if there is none.
*/
public Object getLocalData(String name, ArgumentList args, List<Index> indexes) throws Redirection {
return getData(null, name, args, indexes, true);
}
/** Returns any cached data for a definition with the specified name
* in the current context, or null if there is none.
*/
public Object getData(Definition def, String name, ArgumentList args, List<Index> indexes) throws Redirection {
return getData(def, name, args, indexes, false);
}
synchronized private Object getData(Definition def, String name, ArgumentList args, List<Index> indexes, boolean local) throws Redirection {
if (name == null || name.length() == 0) {
return null;
}
String fullName = (def == null ? name : def.getFullNameInContext(this));
Object data = null;
if (topEntry != null) {
//List<String>[] keeps = addDynamicKeeps(name, args);
updateDynamicKeeps(name, args);
// use indexes as part of the key otherwise a cached element may be confused with a cached array
String key = addIndexesToKey(name, indexes);
data = topEntry.get(key, fullName, args, local);
//if (keeps != null) {
// removeDynamicKeeps(keeps);
}
if (data == null) {
// TODO: modify fullName to match name if name is multipart
// use indexes as part of the key otherwise a cached element may be confused with a cached array
String key = addIndexesToKey(fullName, indexes);
data = getContextData(key);
}
return data;
}
/** Modify the name used to cache a value with indexes, to discriminate
* cached collections from cached elements.
*/
private String addIndexesToKey(String key, List<Index> indexes) {
if (indexes != null && indexes.size() > 0) {
Iterator<Index> it = indexes.iterator();
while (it.hasNext()) {
key = key + it.next().getModifierString(this);
}
}
return key;
}
/** Returns data cached in the context via a keep statement.
*/
public Object getContextData(String name) throws Redirection {
return getContextData(name, false);
}
public Holder getContextHolder(String name) throws Redirection {
return (Holder) getContextData(name, true);
}
private Object getContextData(String name, boolean getHolder) throws Redirection {
if (name == null || cache == null || keepMap == null) {
return null;
}
Object data = null;
Holder holder = null;
String key = name;
if (keepMap != null && keepMap.get(key) != null) {
Pointer p = keepMap.get(key);
if (!p.persist) {
return null;
}
// Problem: the cache map stored in the pointer might no longer be
// valid, depending on its scope and what has happened since the pointer
// was created.
// So, this is what we have to do: Instead of storing the map
// directly, we store the def name of the entry where it's locally
// cached and the key it's cached under.
Map<String, Object> keepTable = p.cache;
data = keepTable.get(p.getKey());
if (data instanceof Pointer) {
int i = 0;
do {
p = (Pointer) data;
data = p.cache.get(p.getKey());
if (data instanceof Holder) {
holder = (Holder) data;
data = (holder.data == AbstractNode.UNINSTANTIATED ? null : holder.data);
} else {
holder = null;
}
i++;
if (i >= MAX_POINTER_CHAIN_LENGTH) {
throw new IndexOutOfBoundsException("Pointer chain in cache exceeds limit");
}
} while (data instanceof Pointer);
} else if (data instanceof Holder) {
holder = (Holder) data;
data = (holder.data == AbstractNode.UNINSTANTIATED ? null : holder.data);
}
}
return getHolder ? holder : data;
}
/** Returns the definition associated with cached data which is the same or the
* equivalent of the specified definition in the current context, or null if there is none.
*/
public Definition getCachedDefinition(Definition def, ArgumentList args) throws Redirection {
String name = def.getName();
String fullName = def.getFullNameInContext(this);
Definition defInCache = getDefinition(name, fullName, args);
if (defInCache == null) {
Definition defOwner = def.getOwner();
int numUnpushes = 0;
try {
for (Definition topDef = topEntry.def; topDef != defOwner && size() > 1; topDef = topEntry.def) {
unpush();
numUnpushes++;
}
if (numUnpushes > 0) {
defInCache = getDefinition(name, fullName, args);
}
} catch (Throwable t) {
String message = "Unable to find definition in cache for array " + name + ": " + t.toString();
vlog(message);
} finally {
while (numUnpushes
repush();
}
}
}
return defInCache;
}
/** Returns the cached definition holder associated with the specified definition in the current context,
* or null if there is none.
*/
public Holder getCachedHolderForDef(Definition def, ArgumentList args, List<Index> indexes) throws Redirection {
String name = def.getName();
String fullName = def.getFullNameInContext(this);
Holder holder = getDefHolder(name, fullName, args, indexes, false);
if (holder == null) {
Definition defOwner = def.getOwner();
int numUnpushes = 0;
try {
for (Definition topDef = topEntry.def; topDef != defOwner && size() > 1; topDef = topEntry.def) {
unpush();
numUnpushes++;
}
if (numUnpushes > 0) {
holder = getDefHolder(name, fullName, args, indexes, false);
}
} catch (Throwable t) {
String message = "Unable to find holder in cache for array " + name + ": " + t.toString();
vlog(message);
} finally {
while (numUnpushes
repush();
}
}
}
return holder;
}
/** Returns the definition associated with cached data for a specified name
* in the current context, or null if there is none.
*/
public Definition getDefinition(String name, String fullName, ArgumentList args) throws Redirection {
if (topEntry == null || name == null || name.length() == 0) {
return null;
}
//List keeps = addDynamicKeeps(name, args);
Definition def = topEntry.getDefinition(name, makeGlobalKey(fullName), args);
//removeDynamicKeeps(keeps);
return def;
}
/** Returns a Holder containing the definition and arguments associated with cached data for a
* specified name in the current context, or null if there is none.
*/
synchronized public Holder getDefHolder(String name, String fullName, ArgumentList args, List<Index> indexes, boolean local) throws Redirection {
if (topEntry == null || name == null || name.length() == 0) {
return null;
}
// use indexes as part of the key otherwise a cached element may be confused with a cached array
String key = addIndexesToKey(name, indexes);
//List<String>[] keeps = addDynamicKeeps(key, args);
updateDynamicKeeps(key, args);
Holder holder = topEntry.getDefHolder(key, makeGlobalKey(fullName), args, local);
//if (keeps != null) {
// removeDynamicKeeps(keeps);
if (holder == null) {
holder = getContextHolder(name);
}
// if this is an identity, then use the definition of the passed argument, if available,
// else the superdefinition instead so children etc. resolve to it
if (holder != null && holder.nominalDef != null && holder.nominalDef.isIdentity()) {
Construction arg = (args != null && args.size() > 0 ? args.get(0) : null);
if (arg != null && arg instanceof Instantiation) {
Instantiation argInstance = ((Instantiation) arg).getUltimateInstance(this);
Definition argDef = argInstance.getDefinition(this);
if (argDef != null && !argDef.getType().isPrimitive()) {
holder.def = argDef;
holder.args = argInstance.getArguments();
}
}
}
return holder;
}
public void putDefinition(Definition def, String name, ArgumentList args, List<Index> indexes) throws Redirection {
putData(def, args, indexes, name, null); //AbstractNode.UNINSTANTIATED);
}
/** Caches data associated with the specified name
* in the current context.
*/
public void putData(Definition def, ArgumentList args, List<Index> indexes, String name, Object data) throws Redirection {
putData(def, args, def, args, indexes, name, data, null);
}
/** Caches data associated with the specified name
* in the current context.
*/
synchronized public void putData(Definition nominalDef, ArgumentList nominalArgs, Definition def, ArgumentList args, List<Index> indexes, String name, Object data, ResolvedInstance resolvedInstance) throws Redirection {
if (topEntry != null && name != null && name.length() > 0) {
int maxCacheLevels = getMaxCacheLevels(nominalDef);
//List<String>[] keeps = addDynamicKeeps(name, args);
updateDynamicKeeps(name, args);
// use indexes as part of the key otherwise a cached element may be confused with a cached array
String key = addIndexesToKey(name, indexes);
topEntry.put(key, nominalDef, nominalArgs, def, args, this, data, resolvedInstance, maxCacheLevels);
//if (keeps != null) {
// removeDynamicKeeps(keeps);
}
}
/** Determine how far down the context stack to go looking to see if a value should
* be cached, whether by a keep statement or because the definition resides at
* that level.
*/
private int getMaxCacheLevels(Definition def) {
int levels = 0;
if (def == null) {
return -1;
}
ComplexDefinition scopeOwner = getComplexOwner(def);
Context.Entry entry = topEntry;
Definition entryDef = entry.def;
boolean reachedScope = (scopeOwner == null || scopeOwner.equals(entryDef) || scopeOwner.isSubDefinition(entryDef));
while (true) {
levels++;
entry = entry.link;
if (entry == null) {
// may have been obtained by reflection or some other out-of-scope mechanism; don't try to
// cache beyond local level
if (!reachedScope) {
levels = 0;
}
break;
}
if (reachedScope) {
if (!entry.def.equals(entryDef)) {
break;
}
} else {
entryDef = (NamedDefinition) entry.def;
reachedScope = (scopeOwner.equals(entryDef) ||
scopeOwner.isSubDefinition(entryDef) ||
(scopeOwner instanceof Site &&
(entry.hasSiteCacheEntryFor(def) || entry.isAdopted(scopeOwner.getNameNode()))));
}
}
return levels;
}
private static ComplexDefinition getComplexOwner(Definition def) {
Definition owner = def.getOwner();
while (owner != null) {
if (owner instanceof ComplexDefinition) {
return (ComplexDefinition) owner;
}
owner = owner.getOwner();
}
return null;
}
/** Checks to see if a name corresponds to a parameter, and if so returns
* the parameter type, otherwise null.
*/
public Type getParameterType(NameNode node, boolean inContainer) {
if (topEntry == null) {
return null;
}
Type paramType = null;
if (inContainer) {
synchronized (this) {
int i = 0;
try {
while (topEntry != null) {
paramType = getParameterType(node, false);
if (paramType != null || topEntry.getPrevious() == null) {
break;
}
unpush();
i++;
}
} finally {
while (i > 0) {
repush();
i
}
}
}
} else if (node.numParts() > 1) {
try {
Definition paramDef = getParameterDefinition(node, false);
if (paramDef != null) {
paramType = paramDef.getType();
}
} catch (Redirection r) {
;
}
} else {
String name = node.getName();
int numParams = topEntry.params.size();
for (int i = numParams - 1; i >= 0; i
DefParameter param = topEntry.params.get(i);
String paramName = param.getName();
if (name.equals(paramName)) {
paramType = param.getType();
}
}
}
// Warning: this might not work on multidimensional arrays that have fewer
// indexes than dimenstions
if (paramType != null && paramType.isCollection() && node.hasIndexes()) {
Definition def = paramType.getDefinition();
if (def instanceof CollectionDefinition) {
paramType = ((CollectionDefinition) def).getElementType();
}
}
return paramType;
}
/** Returns true if a parameter of the specified name is present at the top of the
* context stack.
*/
public boolean paramIsPresent(NameNode nameNode) {
if (topEntry != null) {
return topEntry.paramIsPresent(nameNode, true);
} else {
return false;
}
}
/** Returns true if this is the instantiation of a child of a parameter at the
* top of the context stack.
*/
public boolean isParameterChildDefinition(NameNode node) {
if (node == null) {
return false;
}
String name = node.getName();
if (topEntry == null) {
return false;
}
int numParams = topEntry.params.size();
for (int i = numParams - 1; i >= 0; i
DefParameter param = topEntry.params.get(i);
String paramName = param.getName();
if (name.startsWith(paramName + '.')) {
return true;
}
}
return false;
}
public Object getArgumentForParameter(NameNode name, boolean checkForChild, boolean inContainer) throws Redirection {
if (topEntry == null || topEntry == rootEntry) {
return null;
}
Entry entry = topEntry;
if (inContainer) {
while (!entry.paramIsPresent(name, true)) {
if (entry.link == null || entry.link == rootEntry) {
break;
}
entry = entry.link;
}
}
String checkName = name.getName();
ArgumentList args = entry.args;
int numArgs = args.size();
ParameterList params = entry.params;
int numParams = params.size();
DefParameter param = null;
Construction arg = null;
int i;
int n = (numParams > numArgs ? numArgs : numParams);
for (i = n - 1; i >= 0; i
param = params.get(i);
String paramName = param.getName();
if ((!checkForChild && checkName.equals(paramName)) || (checkForChild && checkName.startsWith(paramName + '.'))) {
arg = args.get(i);
break;
}
}
if (arg != null && entry.args.isDynamic()) {
ArgumentList argHolder = new ArgumentList(true);
argHolder.add(arg);
return argHolder;
} else {
return arg;
}
}
public Object getParameterInstance(NameNode name, boolean checkForChild, boolean inContainer, Definition argOwner) throws Redirection {
Entry entry = topEntry;
int numUnpushes = 0;
while (!entry.def.equalsOrExtends(argOwner)) {
if (entry.link == null || entry.link == rootEntry) {
numUnpushes = 0;
break;
}
numUnpushes++;
entry = entry.link;
}
try {
for (int i = 0; i < numUnpushes; i++) {
unpush();
}
return getParameterInstance(name, checkForChild, inContainer);
} finally {
while (numUnpushes
repush();
}
}
}
/** Checks to see if a name corresponds to a parameter, and if so returns the instance
* or, if the instantiate flag is true, instantiates it and returns the generated data.
*/
public Object getParameterInstance(NameNode name, boolean checkForChild, boolean inContainer) throws Redirection {
// if (checkForChild) {
// return getParameter(name, inContainer, Object.class);
if (topEntry == null || topEntry == rootEntry) {
return null;
}
Entry entry = topEntry;
int numUnpushes = 0;
if (inContainer) {
while (!entry.paramIsPresent(name, false)) {
if (entry.link == null || entry.link == rootEntry) {
numUnpushes = 0;
break;
}
numUnpushes++;
entry = entry.link;
}
}
String checkName = name.getName();
ArgumentList args = entry.args;
int numArgs = args.size();
ParameterList params = entry.params;
int numParams = params.size();
DefParameter param = null;
Object arg = null;
int i;
int n = (numParams > numArgs ? numArgs : numParams);
for (i = n - 1; i >= 0; i
param = params.get(i);
String paramName = param.getName();
if ((!checkForChild && checkName.equals(paramName)) || (checkForChild && checkName.startsWith(paramName + '.'))) {
arg = args.get(i);
break;
}
}
if (arg == null || arg == ArgumentList.MISSING_ARG) {
return null;
} else {
try {
Object data = null;
for (i = 0; i < numUnpushes; i++) {
unpush();
}
Context resolutionContext = (arg instanceof ResolvedInstance ? ((ResolvedInstance) arg).getResolutionContext() : this);
if (checkForChild) {
// the child consists of everything past the first dot, which is the
// same as a complex name consisting of every node in the name
// except for the first
List<Index> indexes = ((NameNode) name.getChild(0)).getIndexes();
ComplexName childName = new ComplexName(name, 1, name.getNumChildren());
data = instantiateParameterChild(childName, param, arg, indexes);
} else {
data = instantiateParameter(param, arg, name);
}
return data;
} finally {
while (numUnpushes
repush();
}
}
}
}
private Object instantiateParameter(DefParameter param, Object arg, NameNode argName) throws Redirection {
Object data = null;
ArgumentList argArgs = argName.getArguments();
List<Index> indexes = argName.getIndexes();
int numUnpushes = 0;
boolean pushedOwner = false;
if (arg instanceof AbstractNode) {
Definition argOwner = ((AbstractNode) arg).getOwner();
Entry entry = topEntry;
while (!entry.def.equalsOrExtends(argOwner)) {
if (entry.link == null || entry.link == rootEntry) {
numUnpushes = (size > 1 && !param.isInFor() ? 1 : 0);
break;
}
numUnpushes++;
entry = entry.link;
}
}
numUnpushes = Math.max((size > 1 && !param.isInFor() ? 1 : 0), numUnpushes);
if (arg instanceof Instantiation) {
Instantiation argInstance = (Instantiation) arg;
boolean inContainer = argInstance.isContainerParameter(this);
boolean isParam = argInstance.isParameterKind();
BentoNode argRef = argInstance.getReference();
Definition argDef = null;
// handle parameters which reference parameters in their containers
if (argRef instanceof NameNode && isParam) {
for (int i = 0; i < numUnpushes; i++) {
unpush();
}
Context resolutionContext = (arg instanceof ResolvedInstance ? ((ResolvedInstance) arg).getResolutionContext() : this);
try {
argDef = argInstance.getDefinition(this);
data = resolutionContext.getParameterInstance((NameNode) argRef, argInstance.isParamChild, inContainer);
if (argDef != null) {
String key = argInstance.getName();
// too expensive for a large loop
//if (argInstance.isForParameter()) {
// key = key + addLoopModifier();
putData(argDef, argArgs, argDef, argArgs, indexes, key, data, null);
}
} finally {
for (int i = 0; i < numUnpushes; i++) {
repush();
}
}
if (data != null) {
if (indexes != null) {
data = dereference(data, indexes);
}
return data;
} else {
return NullValue.NULL_VALUE;
}
}
}
Definition argDef = null;
boolean unpoppedArgDef = false;
try {
if (arg instanceof Definition) {
if (arg instanceof ElementDefinition) {
Object element = ((ElementDefinition) arg).getElement();
if (element instanceof Definition) {
argDef = (Definition) element;
} else if (element instanceof Instantiation) {
Instantiation instance = (Instantiation) element;
arg = instance;
argDef = instance.getDefinition(this);
if (argDef != null && argArgs == null) {
argArgs = instance.getArguments();
if (instance.isSuper() && argArgs == null) {
argArgs = topEntry.args;
}
}
} else {
if (element instanceof Value) {
data = ((Value) element).getValue();
} else if (element instanceof Chunk) {
data = ((Chunk) element).getData(this);
} else if (element instanceof ValueGenerator) {
data = ((ValueGenerator) element).getData(this);
} else {
data = element;
//throw new Redirection(Redirection.STANDARD_ERROR, "unrecognized element class: " + element.getClass().getName());
}
arg = element;
}
} else { // if (arg instanceof CollectionDefinition) {
argDef = (Definition) arg;
}
for (int i = 0; i < numUnpushes; i++) {
unpush();
}
} else {
for (int i = 0; i < numUnpushes; i++) {
unpush();
}
try {
if (data == null) {
if (arg instanceof Instantiation) {
if (argArgs != null || indexes != null) {
for (int i = 0; i < numUnpushes; i++) {
repush();
}
if (indexes != null) {
indexes = instantiateIndexes(indexes);
}
if (argArgs != null) {
argArgs = resolveArguments(argArgs);
}
for (int i = 0; i < numUnpushes; i++) {
unpush();
}
}
if (arg instanceof ResolvedInstance) {
ResolvedInstance ri = (ResolvedInstance) arg;
if (argArgs != null && argArgs.size() > 0) {
ri.setArguments(argArgs);
}
data = ri.getData(ri.getResolutionContext());
} else {
Instantiation instance = (Instantiation) arg;
if (instance.isSuper() && argArgs == null) {
argArgs = topEntry.args;
}
if (argArgs != null) {
if (indexes == null || instance.getIndexes() == null) {
instance = new Instantiation(instance, argArgs, indexes);
indexes = null;
} else {
instance = new Instantiation(instance, argArgs, instance.getIndexes());
}
}
data = instance.getData(this);
}
} else if (arg instanceof PrimitiveValue) {
data = arg; //((PrimitiveValue) arg).getValue();
} else if (arg instanceof Expression) {
data = ((ValueGenerator) arg).getData(this);
} else if (arg instanceof Chunk) {
argDef = param.getDefinitionFor(this, (Chunk) arg);
// there must be a better way to avoid this, but for now...
if (argDef == null && numUnpushes > 0) {
for (int i = 0; i < numUnpushes; i++) {
repush();
}
numUnpushes = 0;
argDef = param.getDefinitionFor(this, (Chunk) arg);
}
if (argDef != null && arg instanceof Instantiation) {
Instantiation instance = (Instantiation) arg;
argArgs = instance.getArguments();
if (instance.isSuper() && argArgs == null) {
argArgs = topEntry.args;
}
}
} else if (arg instanceof ValueGenerator) {
data = ((ValueGenerator) arg).getData(this);
} else {
data = arg;
}
if (data != null) {
// if the name is indexed, and the argument is raw data, then get
// the appropriate item in the collection. In such a case, the data
// must be of the appropriate type for the indexes.
if (indexes != null) {
data = dereference(data, indexes);
}
} else {
data = NullValue.NULL_VALUE;
}
}
} finally {
;
}
}
if (argDef != null) {
// this is to partly handle definitions returned from out of context, e.g. the
// ones returned by descendants_of_type
if (arg instanceof Definition) {
Definition argOwner = ((AbstractNode) arg).getOwner();
if (!topEntry.def.equalsOrExtends(argOwner)) {
push(argOwner, null, null, true);
pushedOwner = true;
}
}
if (!(argDef.isFormalParam())) {
unpop(argDef, argDef.getParamsForArgs(argArgs, this, false), argArgs);
unpoppedArgDef = true;
}
// if the name has one or more indexes, and the argument definition is a
// collection definition, get the appropriate element in the collection.
if (argDef instanceof CollectionDefinition && indexes != null) {
CollectionDefinition collectionDef = (CollectionDefinition) argDef;
argDef = collectionDef.getElementReference(this, argArgs, indexes);
}
data = constructDef(argDef, argArgs, indexes);
}
} finally {
if (unpoppedArgDef) {
repop();
}
if (pushedOwner) {
pop();
}
for (int i = 0; i < numUnpushes; i++) {
repush();
}
}
return data;
}
private List<Index> instantiateIndexes(List<Index> indexes) throws Redirection {
if (indexes == null || indexes.size() == 0) {
return indexes;
}
List<Index> instantiatedIndexes = new ArrayList<Index>(indexes.size());
Iterator<Index> it = indexes.iterator();
while (it.hasNext()) {
Index index = it.next();
Index instantiatedIndex = index.instantiateIndex(this);
instantiatedIndexes.add(instantiatedIndex);
}
return instantiatedIndexes;
}
private List<Index> resolveIndexes(List<Index> indexes) throws Redirection {
if (indexes == null || indexes.size() == 0) {
return indexes;
}
List<Index> resolvedIndexes = new ArrayList<Index>(indexes.size());
Iterator<Index> it = indexes.iterator();
while (it.hasNext()) {
Index index = it.next();
Index resolvedIndex = index.resolveIndex(this);
resolvedIndexes.add(resolvedIndex);
}
return resolvedIndexes;
}
private ArgumentList resolveArguments(ArgumentList args) throws Redirection {
if (args == null || args.size() == 0) {
return args;
}
ArgumentList resolvedArgs = args;
Context sharedContext = null;
for (int i = 0; i < args.size(); i++) {
Construction arg = args.get(i);
if (arg instanceof Instantiation && !(arg instanceof ResolvedInstance)) {
Instantiation argInstance = (Instantiation) arg;
if (resolvedArgs == args) {
resolvedArgs = new ArgumentList(args);
}
ResolvedInstance ri = new ResolvedInstance(argInstance, this, false);
resolvedArgs.set(i, ri);
}
}
return resolvedArgs;
}
private Object instantiateParameterChild(ComplexName childName, DefParameter param, Object arg, List<Index> indexes) throws Redirection {
//if ("status".equals(childName.getName()))
if (arg instanceof Value) {
Object val = ((Value) arg).getValue();
if (val instanceof BentoObjectWrapper) {
arg = val;
}
}
Object data = null;
Instantiation instance = (arg instanceof Instantiation ? (Instantiation) arg : null);
int numUnpushes = 0;
if (arg instanceof AbstractNode) {
Definition argOwner = ((AbstractNode) arg).getOwner();
Definition argOwnerOwner = (argOwner != null ? argOwner.getOwner() : null);
Entry entry = topEntry;
while (!entry.def.equalsOrExtends(argOwner) && !entry.def.equalsOrExtends(argOwnerOwner)) {
if (entry.link == null || entry.link == rootEntry) {
numUnpushes = 0;
break;
}
numUnpushes++;
entry = entry.link;
}
}
Context fallbackContext = this;
Definition argDef = null;
numUnpushes = Math.max((size > 1 && !param.isInFor() ? 1 : 0), numUnpushes);
try {
for (int i = 0; i < numUnpushes; i++) {
unpush();
}
if (arg instanceof Definition) {
if (arg instanceof ElementDefinition) {
Object contents = ((ElementDefinition) arg).getContents();
if (contents instanceof Definition) {
argDef = (Definition) contents;
} else if (contents instanceof Instantiation) {
instance = (Instantiation) contents;
arg = instance;
argDef = instance.getDefinition(this);
if (instance instanceof ResolvedInstance) {
fallbackContext = ((ResolvedInstance) instance).getResolutionContext();
}
} else {
argDef = (Definition) arg;
arg = contents;
}
} else {
argDef = (Definition) arg;
}
} else if (arg instanceof BentoObjectWrapper) {
BentoObjectWrapper wrapper = (BentoObjectWrapper) arg;
// TODO: this doesn't handle children of children
data = wrapper.getChildData(childName.getName());
} else {
if (instance != null && instance.isParameterKind()) {
Context resolutionContext = this;
while (instance.isParameterKind()) {
if (instance instanceof ResolvedInstance) {
resolutionContext = ((ResolvedInstance) instance).getResolutionContext();
}
String checkName = instance.getName();
NameNode instanceName = instance.getReferenceName();
Entry entry = resolutionContext.topEntry;
if (instance.isContainerParameter(resolutionContext)) {
while (entry != null) {
if (entry.paramIsPresent(instanceName, true)) {
break;
}
entry = entry.link;
}
if (entry == null) {
return null;
}
}
ArgumentList args = entry.args;
int numArgs = args.size();
ParameterList params = entry.params;
int numParams = params.size();
DefParameter p = null;
Object a = null;
int i;
int n = (numParams > numArgs ? numArgs : numParams);
for (i = n - 1; i >= 0; i
p = params.get(i);
String paramName = p.getName();
if (checkName.equals(paramName)) {
a = args.get(i);
break;
}
}
if (a == null) {
break;
}
if (a instanceof Value) {
Object o = ((Value) a).getValue();
a = o;
}
if (a instanceof Definition) {
if (a instanceof NamedDefinition && p.getType().isTypeOf("definition")) {
argDef = new AliasedDefinition((NamedDefinition) a, instance.getReferenceName());
} else {
argDef = (Definition) a;
}
break;
} else if (!(a instanceof Instantiation)) {
break;
}
instance = (Instantiation) a;
arg = a;
param = p;
if (!p.isInFor()) {
unpush();
numUnpushes++;
}
}
if (instance.isParameterChild()) {
NameNode compName = new ComplexName(instance.getReferenceName(), childName);
data = resolutionContext.getParameter(compName, instance.isContainerParameter(resolutionContext), Object.class);
// trying to avoid multiple instantiation attempts, so commented this out.
//if (data == null || data == NullValue.NULL_VALUE) {
// data = getParameter(compName, instance.isContainerParameter(this), Object.class);
}
}
if (data == null && argDef == null) {
if (arg instanceof Chunk) {
argDef = param.getDefinitionFor(this, (Chunk) arg);
if (arg instanceof ResolvedInstance) {
fallbackContext = ((ResolvedInstance) arg).getResolutionContext();
}
} else if (arg instanceof Map<?,?> && arg != null) {
String nm = childName.getName();
if (nm.equals("keys")) {
Set<?> keySet = ((Map<?,?>) arg).keySet();
List<String> keys = new ArrayList<String>(keySet.size());
Iterator<?> it = keySet.iterator();
while (it.hasNext()) {
keys.add(it.next().toString());
}
data = keys;
} else {
data = ((Map<?,?>) arg).get(childName.getName());
}
} else {
data = arg;
}
}
}
if (data != null) {
// if the name is indexed, and the argument is raw data, then get
// the appropriate item in the collection. In such a case, the data
// must be of the appropriate type for the indexes.
if (indexes != null) {
data = dereference(data, indexes);
}
return data;
}
} finally {
// un-unpush if necessary
for (int i = 0; i < numUnpushes; i++) {
repush();
}
}
if (argDef != null) {
ArgumentList args = (instance != null ? instance.getArguments() : null);
List<Index> argIndexes = (instance != null ? instance.getIndexes() : null);
if (argDef.isIdentity() && (instance == null || !(instance instanceof ResolvedInstance))) {
Holder holder = getDefHolder(argDef.getName(), argDef.getFullNameInContext(this), args, argIndexes, false);
if (holder != null && holder.def != null && !holder.def.isIdentity()) {
argDef = holder.def;
args = holder.args;
}
}
argDef = initDef(argDef, args, indexes);
// The following line replaces the commented out section following it. The commented
// out section in some cases tries twice to instantiate the child, first with this
// context and second with the fallbackContext, in cases where the argument resolves
// to a ResolvedInstance, in which case the fallbackContext gets the value of
// the ResolvedInstance's resolution context. The problem with this is that often
// the null return value is intentional, and not caused by being unable to resolve
// the child reference. So, now we are trying something different. We will use the
// ResolvedInstance's resolution context first and only, when it exists. Since
// fallbackContext is initialized to this, we can achieve this by simply using
// falllbackContext (no longer aptly named), and not falling back to anything.
data = fallbackContext.instantiateArgChild(childName, param.getType(), argDef, args, null);
// // commented out to fix Array Element Child Array test, because of
// // a reference to a loop parameter.
// // for (int i = 0; i < numUnpushes; i++) {
// // unpush();
// data = instantiateArgChild(childName, param.getType(), argDef, args, null);
// // for (int i = 0; i < numUnpushes; i++) {
// // repush();
// if ((data == null || data == NullValue.NULL_VALUE) && fallbackContext != this) {
// data = fallbackContext.instantiateArgChild(childName, param.getType(), argDef, args, null);
}
return data;
}
private Object instantiateArgChild(ComplexName name, Type paramType, Definition def, ArgumentList args, List<Index> indexes) throws Redirection {
int n = name.numParts();
NameNode childName = name.getFirstPart();
int numPushes = 0;
try {
// Keep track of intermediate definitions during alias dereferencing
// by pushing them onto the context stack in case their parameters are
// referenced in the child being instantiated. Ensure however that
// the original definition remains on top
for (int i = 0; i < n - 1; i++) {
if (def == null) {
break;
}
ParameterList params = def.getParamsForArgs(args, this);
Definition childDef = null;
if (def.isExternal()) {
push(def, params, args, false);
numPushes++;
childDef = def.getChildDefinition(childName, childName.getArguments(), childName.getIndexes(), null, this, null);
} else {
push(def, params, args, false);
numPushes++;
childDef = def.getChildDefinition(childName, childName.getArguments(), childName.getIndexes(), null, this, null);
//pop();
//numPushes--;
}
numPushes += pushSupersAndAliases(def, args, childDef);
def = childDef;
if (def != null && childName != null) {
args = childName.getArguments();
def = initDef(def, childName.getArguments(), childName.getIndexes());
}
childName = (NameNode) name.getChild(i + 1);
}
return _instantiateArgChild(childName, paramType, def, args, indexes);
} finally {
while (numPushes
pop();
}
}
}
public int pushSupersAndAliases(Definition def, ArgumentList args, Definition childDef) throws Redirection {
// track back through superdefinitions and aliases to push intermediate definitions
if (childDef != null /* && !isSpecialDefinition(childDef) */ ) {
// find the complex owner of the child
Definition childOwner = childDef.getOwner();
while (childOwner != null && !(childOwner instanceof ComplexDefinition)) {
childOwner = childOwner.getOwner();
}
if (childOwner == null) {
throw new Redirection(Redirection.STANDARD_ERROR, "Improperly initialized definition tree");
}
return pushSupersAndAliases((ComplexDefinition) childOwner, def, args);
} else {
return 0;
}
}
public int pushSupersAndAliases(ComplexDefinition owner, Definition def, ArgumentList args) throws Redirection {
Definition instantiatedDef = getContextDefinition(def);
int numPushes = 0;
ParameterList params = def.getParamsForArgs(args, this);
Definition superdef = null;
while (!def.equals(owner)) {
push(instantiatedDef, params, args, false);
numPushes++;
Type st = def.getSuper(this);
superdef = def.getSuperDefinition(this);
// this doesn't completely work, because it misses
// superclasses of intermediate aliases. To really
// handle this right, we need a flag for getChildDefinition
// which prevents it from restoring the context, so
// that none of the pushing here would be necessary.
// Instead we would use a clone of the context, which
// we could just throw away when we're done.
if (def.isAliasInContext(this)) {
Definition aliasDef = def;
int numAliasPushes = 0;
ArgumentList aliasArgs = args;
ParameterList aliasParams = def.getParamsForArgs(args, this);
while (aliasDef != null && aliasDef.isAliasInContext(this)) {
push(instantiatedDef, aliasParams, aliasArgs, false);
numAliasPushes++;
Instantiation aliasInstance = aliasDef.getAliasInstanceInContext(this);
aliasDef = (Definition) aliasInstance.getDefinition(this); // lookup(this, false);
aliasArgs = aliasInstance.getArguments(); // getUltimateInstance(this).getArguments();
if (aliasDef != null) {
aliasParams = aliasDef.getParamsForArgs(aliasArgs, this);
}
}
if (aliasDef != null && aliasDef.equals(owner)) {
def = aliasDef;
args = aliasArgs;
params = aliasParams;
numPushes += numAliasPushes;
continue;
} else {
while (numAliasPushes
pop();
}
}
}
if (st == null || superdef == null) {
break;
}
def = superdef;
args = st.getArguments(this);
params = def.getParamsForArgs(args, this);
}
if (superdef != null) {
push(instantiatedDef, superdef, params, args);
numPushes++;
}
return numPushes;
}
synchronized private Object _instantiateArgChild(NameNode childName, Type paramType, Definition argDef, ArgumentList argArgs, List<Index> argIndexes) throws Redirection {
Object data = null;
boolean unpopped = false;
int numPushes = 0;
int numUnpushes = 0;
// initialization dynamic objects such as collections initialized with
// comprehensions or external methods
if (argDef instanceof DynamicObject) {
argDef = (Definition) ((DynamicObject) argDef).initForContext(this, argArgs, argIndexes);
}
try {
while (argDef.isAliasInContext(this)) {
ParameterList params = argDef.getParamsForArgs(argArgs, this);
push(argDef, params, argArgs, false);
numPushes++;
Instantiation aliasInstance = argDef.getAliasInstanceInContext(this); //.getUltimateInstance(this);
Definition newDef = (Definition) aliasInstance.getDefinition(this); // lookup(this, false);
if (newDef == null) {
pop();
numPushes
break;
} else {
argDef = newDef;
}
argArgs = aliasInstance.getArguments();
}
if (argDef != null) {
if (argDef instanceof ElementReference) {
unpush();
numUnpushes++;
argDef = ((ElementReference) argDef).getElementDefinition(this);
repush();
numUnpushes
if (argDef == null) {
return null;
}
}
// if it's a NamedDefinition, but not an external definition, push the
// definition of the parameter onto the context in order to properly resolve
// any of its children which may be instantiated
if (argDef instanceof NamedDefinition) { // && !argDef.isExternal()) {
// unpop the stack since the child's arguments have to be
// resolved where they are, not up at the level of its parent's
// referenced parameter.
push(argDef, argDef.getParamsForArgs(argArgs, this, false), argArgs);
numPushes++;
}
data = argDef.getChildData(childName, paramType, this, argArgs);
}
} finally {
while (numPushes
pop();
}
while (numUnpushes
repush();
}
}
return data;
}
public Object getDescendant(Definition parentDef, ArgumentList args, NameNode name, boolean generate, Object parentObj) throws Redirection {
Definition def = parentDef;
// if this is a reference to a collection element, forward to its definition
if (def instanceof ElementReference) {
Definition elementDef = ((ElementReference) def).getElementDefinition(this);
if (elementDef instanceof ElementDefinition) {
// might have to fix the args and parentArgs here
return ((ElementDefinition) elementDef).getChild(name, args, null, null, this, generate, true, parentObj, null);
}
}
Definition childDef = null;
NameNode childName = name.getFirstPart();
ArgumentList childArgs = childName.getArguments();
boolean dynamicChild = (childArgs != null && childArgs.isDynamic());
List<Index> childIndexes = childName.getIndexes();
int numPushes = 0;
ComplexName restOfName = null;
int numNameParts = name.numParts();
if (numNameParts > 1) {
restOfName = new ComplexName(name, 1, numNameParts);
}
// if parentObj is a BentoObjectWrapper and we are generating data, delegate to the object
if (generate && !dynamicChild && numNameParts == 1 && parentObj != null && parentObj instanceof BentoObjectWrapper) {
BentoObjectWrapper obj = (BentoObjectWrapper) parentObj;
//return obj.getChildData(name);
}
try {
// Keep track of intermediate definitions during alias dereferencing
// by pushing them onto the context stack in case their parameters are
// referenced in the child being instantiated. Look for cached
// definitions and arguments
if (args == null && !(def instanceof AliasedDefinition)) {
String nm = def.getName();
String fullNm = def.getFullNameInContext(this);
Holder holder = getDefHolder(nm, fullNm, null, null, false);
if (holder != null && holder.nominalDef != null && holder.nominalDef.getDurability() != Definition.DYNAMIC && !((BentoNode) holder.nominalDef).isDynamic()) {
def = holder.nominalDef;
args = holder.nominalArgs;
}
}
ParameterList params = def.getParamsForArgs(args, this);
if (!def.isExternal() && (!def.isCollection() || parentObj == null)) {
boolean newFrame = !topEntry.def.equalsOrExtends(def);
push(def, params, args, newFrame);
numPushes++;
Definition superDef = def.getSuperDefinition(this);
while (def.isAliasInContext(this) && !def.isCollection()) {
Instantiation aliasInstance = def.getAliasInstanceInContext(this);
if (def.isParamAlias() && aliasInstance != null) {
aliasInstance = aliasInstance.getUltimateInstance(this);
}
if (aliasInstance == null) {
break;
}
NameNode aliasName = aliasInstance.getReferenceName();
if (aliasName.isComplex()) {
numPushes += pushParts(aliasInstance);
}
ArgumentList aliasArgs = aliasInstance.getArguments();
List<Index> aliasIndexes = aliasInstance.getIndexes();
Definition aliasDef = aliasInstance.getDefinition(this, def);
if (aliasDef == null) {
break;
}
// we are only interested in aliases in the same hierarchy
if (superDef != null && !aliasDef.equalsOrExtends(superDef)) {
break;
}
def = aliasDef;
args = aliasArgs;
if (args == null && aliasIndexes == null) {
String nm = aliasInstance.getName();
String fullNm = parentDef.getFullNameInContext(this) + "." + nm;
Holder holder = getDefHolder(nm, fullNm, null, null, false);
if (holder != null && holder.nominalDef != null && holder.nominalDef.getDurability() != Definition.DYNAMIC && !((BentoNode) holder.nominalDef).isDynamic()) {
def = holder.nominalDef;
args = holder.nominalArgs;
if (generate && holder.data != null && holder.data instanceof BentoObjectWrapper && numNameParts == 1) {
BentoObjectWrapper obj = (BentoObjectWrapper) holder.data;
return obj.getChildData(childName);
}
}
}
params = def.getParamsForArgs(args, this);
push(def, params, args, false); //true);
numPushes++;
}
}
//if (childIndexes == null) {
String nm = childName.getName();
String fullNm = parentDef.getFullNameInContext(this) + "." + nm;
Holder holder = getDefHolder(nm, fullNm, childArgs, childIndexes, false);
if (holder != null) {
Definition nominalDef = holder.nominalDef;
if (nominalDef != null && !nominalDef.isCollection() && nominalDef.getDurability() != Definition.DYNAMIC) {
if (nominalDef.isIdentity()) {
childDef = holder.def;
if (childArgs == null) {
childArgs = holder.args;
}
} else {
childDef = nominalDef;
if (childArgs == null) {
childArgs = holder.nominalArgs;
}
}
if (childDef != null && childDef.getDurability() == Definition.DYNAMIC) {
dynamicChild = true;
}
if (generate && !dynamicChild) {
if (holder.data != null && !holder.data.equals(NullValue.NULL_VALUE)) {
if (numNameParts == 1) {
return holder.data;
} else if (holder.data instanceof BentoObjectWrapper) {
BentoObjectWrapper obj = (BentoObjectWrapper) holder.data;
return obj.getChildData(restOfName);
}
} else if (holder.resolvedInstance != null) {
ResolvedInstance ri = holder.resolvedInstance;
if (numNameParts == 1) {
Object data = ri.getData(this, childDef);
if (data != null && !data.equals(NullValue.NULL_VALUE)) {
return data;
}
}
}
}
}
}
if (childDef == null) {
return def.getChild(name, name.getArguments(), name.getIndexes(), args, this, generate, true, parentObj, null);
}
// if parentObj is a BentoObjectWrapper and we are generating data, delegate to the object
if (generate && childDef.getDurability() != Definition.DYNAMIC && !dynamicChild && numNameParts == 1 && parentObj != null && parentObj instanceof BentoObjectWrapper) {
BentoObjectWrapper obj = (BentoObjectWrapper) parentObj;
return obj.getChildData(name);
}
DefinitionInstance childDefInstance = null;
if (childDef != null) {
if (generate && childName != null) {
childDef = initDef(childDef, childArgs, childName.getIndexes());
}
if (restOfName != null) {
if (generate) {
return getDescendant(childDef, childArgs, restOfName, generate, parentObj);
} else {
childDefInstance = (DefinitionInstance) getDescendant(childDef, childArgs, restOfName, generate, parentObj);
}
}
}
if (!generate) {
if (childDefInstance != null) {
return childDefInstance;
} else if (childDef != null) {
return childDef.getDefInstance(childArgs, childIndexes);
} else {
return null;
}
}
if (childDefInstance != null) {
childDef = childDefInstance.def;
}
if (childDef == null) {
return AbstractNode.UNDEFINED;
} else {
return childDef.instantiate(childArgs, childName.getIndexes(), this);
}
} finally {
while (numPushes
pop();
}
}
}
public Definition dereference(Definition def, ArgumentList args, List<Index> indexes) throws Redirection {
if (indexes != null) {
CollectionDefinition collectionDef = null;
if (def instanceof CollectionDefinition) {
collectionDef = (CollectionDefinition) def;
}
Definition checkDef = def;
ArgumentList checkArgs = args;
while (collectionDef == null && checkDef != null) {
int numAliasPushes = 0;
ParameterList aliasParams = checkDef.getParamsForArgs(checkArgs, this);
try {
Instantiation checkInstance = null;
while (checkDef != null && checkDef.isAliasInContext(this)) {
checkInstance = checkDef.getAliasInstanceInContext(this);
checkArgs = checkInstance.getArguments(); // getUltimateInstance(this).getArguments();
aliasParams = (checkDef != null ? checkDef.getParamsForArgs(checkArgs, this) : null);
push(checkDef, aliasParams, checkArgs, false);
numAliasPushes++;
checkDef = (Definition) checkInstance.getDefinition(this); // lookup(context, false);
}
if (checkDef != null) {
if (checkDef instanceof CollectionDefinition) {
collectionDef = (CollectionDefinition) checkDef;
return collectionDef.getElementReference(this, args, indexes);
} else if (!(checkDef instanceof IndexedMethodDefinition)) {
ResolvedInstance instance = new ResolvedInstance(checkDef, this, checkArgs, null);
return new IndexedInstanceReference(instance, indexes);
} else {
checkDef = null;
}
}
} finally {
while (numAliasPushes
pop();
}
}
}
if (collectionDef != null) {
def = collectionDef.getElementReference(this, args, indexes);
}
}
return def;
}
public Definition initDef(Definition def, ArgumentList args, List<Index> indexes) throws Redirection {
if (def instanceof ExternalDefinition) {
def = ((ExternalDefinition) def).getDefForContext(this, args);
}
// return dereference(def, args, indexes);
// if the reference has one or more indexes, and the definition is a
// collection definition, get the appropriate element in the collection.
// Note: this fails when there is an index on an aliased collection definition
if (indexes != null && indexes.size() > 0 && def.isCollection()) {
CollectionDefinition collectionDef = def.getCollectionDefinition(this, args);
if (collectionDef != null) {
indexes = resolveIndexes(indexes);
def = collectionDef.getElementReference(this, args, indexes);
} else {
def = null;
}
}
return def;
}
public Object dereference(Object data, List<Index> indexes) throws Redirection {
// dereference collections represented as values
if (data instanceof Value) {
data = ((Value) data).getValue();
if (data == null) {
return null;
}
}
// dereference collections represented as BentoArray objects
if (data instanceof BentoArray) {
data = ((BentoArray) data).getArrayObject();
}
Iterator<Index> it = indexes.iterator();
while (it.hasNext() && data != null) {
Index index = it.next();
data = getElement(data, index);
}
return data;
}
private Object getElement(Object collection, Index index) throws Redirection {
Object data = null;
// this occurs with anonymous collections in the input
if (collection instanceof CollectionDefinition) {
collection = ((CollectionDefinition) collection).getCollectionInstance(this, null, null);
}
if (collection instanceof CollectionInstance) {
collection = ((CollectionInstance) collection).getCollectionObject();
}
if (collection instanceof Value) {
collection = ((Value) collection).getValue();
} else if (collection instanceof ValueGenerator) {
collection = ((ValueGenerator) collection).getData(this);
}
boolean isArray = collection.getClass().isArray();
boolean isList = (collection instanceof List<?>);
if (index instanceof TableIndex) {
String key = index.getIndexValue(this).getString();
if (isArray || isList) {
// NOTE: the following is the comment accompanying the related logic
// in the method getElement in ArrayDefinition:
// retrieve the element which matches the index key value. There
// are two ways an element can match the key:
// -- if the element is a definition which owns a child named "key"
// compare its instantiated string value to the index key
// -- if the element doesn't have such a "key" field, compare the
// string value of the element itself to the index key.
// The logic below is operating on an instantiated array, so it contains
// instantiated elements, and as a result the element definitions are
// not available. Therefore only the second of the two methods
// described above can be implemented.
// This inconsistency between the logic here and in ArrayDefinition
// is a bug and needs to be corrected, preferably by finding a way to
// put the logic in one place.
if (key == null) {
return null;
}
int size = (isArray ? Array.getLength(collection) : ((List<?>) collection).size());
int ix = -1;
for (int i = 0; i < size; i++) {
Object element = (isArray ? Array.get(collection, i) : ((List<?>) collection).get(i));
try {
String elementKey;
if (element instanceof String) {
elementKey = (String) element;
} else if (element instanceof Value) {
elementKey = ((Value) element).getString();
} else if (element instanceof Chunk) {
elementKey = ((Chunk) element).getText(this);
} else if (element instanceof ValueGenerator) {
elementKey = ((ValueGenerator) element).getString(this);
} else {
elementKey = element.toString();
}
if (key.equals(elementKey)) {
ix = i;
break;
}
} catch (Redirection r) {
// don't redirect, we're only checking
continue;
}
}
data = new PrimitiveValue(ix);
} else if (collection instanceof Map<?,?>) {
data = ((Map<?,?>) collection).get(key);
}
} else { // must be an ArrayIndex
int i = index.getIndexValue(this).getInt();
if (collection.getClass().isArray()) {
data = Array.get(collection, i);
} else if (collection instanceof List<?>) {
data = ((List<?>) collection).get(i);
} else if (collection instanceof Map<?,?>) {
Object[] keys = ((Map<?,?>) collection).keySet().toArray();
Arrays.sort(keys);
data = ((Map<?,?>) collection).get(keys[i]);
}
}
while (data instanceof Holder) {
data = ((Holder) data).data;
}
if (data instanceof ElementDefinition) {
data = ((ElementDefinition) data).getElement();
}
return data;
}
public Object constructDef(Definition definition, ArgumentList args, List<Index> indexes) throws Redirection {
// initialization expressions
if (definition instanceof DynamicObject) {
definition = (Definition) ((DynamicObject) definition).initForContext(this, args, indexes);
}
Logger.logInstantiation(this, definition);
if (definition instanceof CollectionDefinition) {
CollectionInstance collection = ((CollectionDefinition) definition).getCollectionInstance(this, args, indexes);
return collection.getCollectionObject();
} else {
return construct(definition, args);
}
}
/** Checks to see if a name corresponds to a parameter, and if so returns
* the definition associated with it (i.e., the argument passed as the
* parameter's value).
*/
public Definition getParameterDefinition(NameNode name, boolean inContainer) throws Redirection {
return (Definition) getParameter(name, inContainer, Definition.class);
}
public Entry getParameterEntry(NameNode name, boolean inContainer) throws Redirection {
return (Entry) getParameter(name, inContainer, Entry.class);
}
public Object getParameter(NameNode name, boolean inContainer, Class<?> returnClass) throws Redirection {
if (topEntry == null) {
return null;
}
Entry entry = topEntry;
if (inContainer) {
Object paramObj = null;
synchronized (this) {
int i = 0;
try {
//unpush();
while (topEntry != null) {
paramObj = getParameter(name, false, returnClass);
if (paramObj != null || topEntry.getPrevious() == null) {
break;
}
unpush();
i++;
}
} finally {
while (i > 0) {
repush();
i
}
}
}
return paramObj;
}
boolean checkForChild = (name.numParts() > 1);
String checkName = name.getName();
ArgumentList args = entry.args;
int numArgs = args.size();
ParameterList params = entry.params;
int numParams = params.size();
ArgumentList argArgs = null;
ParameterList argParams = null;
Object arg = null;
int n = (numParams > numArgs ? numArgs : numParams);
boolean mustUnpush = false;
DefParameter param = null;
Type paramType = null;
int i;
for (i = n - 1; i >= 0; i
param = params.get(i);
String paramName = param.getName();
if ((!checkForChild && checkName.equals(paramName)) || (checkForChild && checkName.startsWith(paramName + '.'))) {
arg = args.get(i);
break;
}
}
if (arg == null) {
return null;
}
Definition argDef = null;
// for loop arguments are in the same context, not the next higher context
if (!param.isInFor() && size > 1) {
mustUnpush = true;
unpush();
}
int numPushes = 0;
Instantiation argInstance = null;
try {
if (arg instanceof Definition) {
argDef = (Definition) arg;
} else if (arg != ArgumentList.MISSING_ARG) {
argDef = param.getDefinitionFor(this, arg);
if (arg instanceof Instantiation && argDef != null) {
argInstance = (Instantiation) arg;
argArgs = argInstance.getArguments();
if (argInstance.isSuper() && argArgs == null) {
argArgs = topEntry.args;
}
argParams = argDef.getParamsForArgs(argArgs, this);
//numPushes += pushParts(argInstance);
}
}
if (argDef == null) {
return null;
}
push(argDef, argParams, argArgs);
numPushes++;
paramType = param.getType();
Definition lastDef = null;
// don't dereference global definitions, or we might miss a globally cached value
while (!(arg instanceof ResolvedInstance) && argDef != lastDef && !argDef.isGlobal() && argDef.isAliasInContext(this)) {
lastDef = argDef;
NameNode alias = argDef.isParamAlias() ? argDef.getParamAlias() : argDef.getAliasInContext(this);
if (alias == null) {
break;
}
ArgumentList aliasArgs = alias.getArguments();
Instantiation aliasInstance = argDef.getAliasInstanceInContext(this);
if (aliasInstance == null) {
break;
}
numPushes += pushParts(aliasInstance);
Context.Entry aliasEntry = getParameterEntry(alias, aliasInstance.isContainerParameter(this));
if (aliasEntry == null) {
List<Index> aliasIndexes = alias.getIndexes();
for (Definition owner = argDef.getOwner(); owner != null; owner = owner.getOwner()) {
owner = getSubdefinitionInContext(owner);
Definition aliasDef = owner.getChildDefinition(alias, aliasArgs, aliasIndexes, args, this, null);
if (aliasDef != null) {
argDef = aliasDef;
argArgs = aliasArgs;
argParams = argDef.getParamsForArgs(argArgs, this);
push(argDef, argParams, argArgs);
numPushes++;
break;
}
}
} else {
argDef = aliasEntry.def;
argArgs = aliasEntry.args;
argParams = aliasEntry.params;
push(aliasEntry);
numPushes++;
}
}
// dereference the argument definition if the reference includes indexes
NameNode paramNameNode = (checkForChild ? (NameNode) name.getChild(0) : name);
ArgumentList paramArgs = paramNameNode.getArguments();
List<Index> paramIndexes = paramNameNode.getIndexes();
if ((paramArgs != null && paramArgs.size() > 0) || (paramIndexes != null && paramIndexes.size() > 0)) {
Context argContext = this;
if (mustUnpush) {
argContext = clone(false);
Entry clonedEntry = newEntry(unpushedEntries.peek(), true);
argContext.push(clonedEntry);
}
argDef = argContext.initDef(argDef, paramArgs, paramIndexes);
}
// if this is a child of a parameter, resolve it.
if (checkForChild && argDef != null) {
// the child consists of everything past the first dot, which is the
// same as a complex name consisting of every node in the name
// except for the first
ComplexName childName = new ComplexName(name, 1, name.getNumChildren());
// see if the argument definition has a child definition by that name
ArgumentList childArgs = childName.getArguments();
Definition childDef = argDef.getChildDefinition(childName, childArgs, childName.getIndexes(), args, this, null);
// if not, then look for an aliased external definition
if (childDef == null) {
if (argDef.isAlias()) {
NameNode aliasName = argDef.getAlias();
childName = new ComplexName(aliasName, childName);
NamedDefinition ndef = (NamedDefinition) peek().def;
childDef = ExternalDefinition.createForName(ndef, childName, param.getType(), argDef.getAccess(), argDef.getDurability(), this);
}
// if that didn't work, look for a special definition child
if (childDef == null) {
if (paramType != null && paramType.getName().equals("definition")) {
childDef = ((AnonymousDefinition) argDef).getDefinitionChild(childName, this, args);
}
}
} else {
childDef = childDef.getUltimateDefinition(this);
}
argDef = childDef;
if (arg instanceof Value && ((Value) arg).getValueClass().equals(BentoObjectWrapper.class)) {
BentoObjectWrapper wrapper = (BentoObjectWrapper) ((Value) arg).getValue();
Context argContext = wrapper.context;
argDef = new BoundDefinition(argDef, argContext);
}
}
if (returnClass == Entry.class) {
if (argDef == null) {
return null;
} else {
return newEntry(argDef, argDef, argParams, argArgs);
}
} else if (returnClass == Definition.class) {
return argDef;
} else {
Object data = (argDef == null ? null : construct(argDef, argArgs));
if (data == null) {
return NullValue.NULL_VALUE;
} else {
return data;
}
}
} finally {
// restore the stack
while (numPushes
pop();
}
if (mustUnpush) {
repush();
}
}
}
public Definition getSubdefinitionInContext(Definition def) {
Definition subdef = def;
for (Entry entry = topEntry; entry != null; entry = entry.link) {
if (entry.def.equalsOrExtends(def)) {
subdef = entry.def;
break;
}
}
return subdef;
}
/** Returns a copy of the passed argument list with any arguments that
* reference parameters in this context replaced by the arguments referenced
* by those parameters. If no arguments reference parameters, the original
* argument list is returned.
*/
public ArgumentList getUltimateArgs(ArgumentList args) throws Redirection {
if (args == null) {
return null;
}
ArgumentList newArgs = null;
Iterator<Construction> it = args.iterator();
int n = 0;
while (it.hasNext()) {
Construction arg = it.next();
if (arg instanceof Instantiation) {
Instantiation argInstance = (Instantiation) arg;
if (argInstance.isParameterKind()) {
if (newArgs == null) {
newArgs = new ArgumentList(args);
}
Construction newArg = null;
Object obj = getArgumentForParameter(argInstance.getReferenceName(), argInstance.isParameterChild(), argInstance.isContainerParameter(this));
if (obj != null) {
if (obj instanceof ArgumentList) {
ArgumentList argHolder = (ArgumentList) obj;
newArg = argHolder.get(0);
if (argHolder.isDynamic()) {
newArgs.setDynamic(true);
}
} else {
newArg = (Construction) obj;
}
newArgs.set(n, newArg);
}
}
}
n++;
}
if (newArgs != null) {
return newArgs;
} else {
return args;
}
}
public int pushParts(Instantiation instance) throws Redirection {
if (instance != null) {
NameNode nameNode = instance.getReferenceName();
if (nameNode != null) {
if (nameNode.isComplex()) {
Context resolutionContext = this;
//if (instance instanceof ResolvedInstance) {
// resolutionContext = ((ResolvedInstance) instance).getResolutionContext();
int num = nameNode.numParts();
return resolutionContext.pushParts(nameNode, num - 1, instance.getOwner());
}
}
}
return 0;
}
public int pushParts(NameNode nameNode, int numParts, Definition owner) throws Redirection {
int numPushes = 0;
try {
for (int part = 0; part < numParts; part++) {
NameNode partName = nameNode.getPart(part);
Definition partDef = null;
List<Index> partIndexes = partName.getIndexes();
ArgumentList partArgs = partName.getArguments();
if (partIndexes == null || partIndexes.size() == 0) {
String nm = partName.getName();
String fullNm = owner.getFullNameInContext(this) + "." + nm;
Holder holder = getDefHolder(nm, fullNm, partArgs, partIndexes, false);
if (holder != null) {
Definition nominalDef = holder.nominalDef;
if (nominalDef != null && !nominalDef.isCollection() && nominalDef.getDurability() != Definition.DYNAMIC) {
if (nominalDef.isIdentity()) {
partDef = holder.def;
if (partArgs == null) {
partArgs = holder.args;
}
} else {
partDef = nominalDef;
if (partArgs == null) {
partArgs = holder.nominalArgs;
}
}
}
}
}
Instantiation partInstance = new Instantiation(partName, owner);
partInstance.setKind(getParameterKind(partName.getName()));
if (partDef == null) {
partDef = partInstance.getDefinition(this);
if (partDef == null) {
break;
}
}
if (partInstance.isParameterKind()) {
Entry partEntry = getParameterEntry(partInstance.getReferenceName(), partInstance.isContainerParameter(this));
push(partEntry);
} else {
ParameterList partParams = partDef.getParamsForArgs(partArgs, this, false);
push(partDef, partParams, partArgs, false);
}
numPushes++;
while (partDef.isAliasInContext(this) && !partDef.isIdentity()) {
partInstance = partDef.getAliasInstanceInContext(this);
if (partInstance == null) {
break;
}
if (partInstance.isParameterKind()) {
Entry partEntry = getParameterEntry(partInstance.getReferenceName(), partInstance.isContainerParameter(this));
if (partEntry == null) {
break;
}
partDef = partEntry.def;
if (partDef == null) {
break;
}
push(partEntry);
} else {
partDef = partInstance.getDefinition(this);
if (partDef == null) {
break;
}
partArgs = partInstance.getArguments();
ParameterList partParams = partDef.getParamsForArgs(partArgs, this);
push(partDef, partParams, partArgs, false);
}
numPushes++;
}
}
} finally {
;
}
return numPushes;
}
public int getParameterKind(String name) {
int kind = Instantiation.UNRESOLVED;
boolean isChild = (name.indexOf('.') > 0);
DefParameter param = topEntry.getParam(name);
if (param != null) {
if (param.isInFor()) {
return (isChild ? Instantiation.FOR_PARAMETER_CHILD : Instantiation.FOR_PARAMETER);
} else {
return (isChild ? Instantiation.PARAMETER_CHILD : Instantiation.PARAMETER);
}
}
for (Entry entry = topEntry.getPrevious(); entry != null; entry = entry.getPrevious()) {
param = entry.getParam(name);
if (param != null) {
return (isChild ? Instantiation.CONTAINER_PARAMETER_CHILD : Instantiation.CONTAINER_PARAMETER);
}
}
return kind;
}
public int size() {
return size;
}
public void push(Definition def, ParameterList params, ArgumentList args) throws Redirection {
Definition contextDef = getContextDefinition(def);
Entry entry = newEntry(contextDef, contextDef, params, args);
push(entry);
}
public void push(Definition def, ParameterList params, ArgumentList args, boolean newFrame) throws Redirection {
Definition contextDef = getContextDefinition(def);
Definition superdef = (newFrame ? null : contextDef);
Entry entry = newEntry(contextDef, superdef, params, args);
push(entry);
}
public void push(Definition instantiatedDef, Definition superdef, ParameterList params, ArgumentList args) throws Redirection {
Entry entry = newEntry(getContextDefinition(instantiatedDef), getContextDefinition(superdef), params, args);
push(entry);
}
private void push(Entry entry) throws Redirection {
boolean newFrame = (entry.superdef == null);
boolean newScope = (entry.def != entry.superdef);
if (entry.def instanceof Site) {
// if we are pushing a site, share the cache from the
// root entry
if (rootEntry != null && !entry.equals(rootEntry)) {
entry.cache = rootEntry.cache;
}
} else {
Site entrySite = entry.def.getSite();
if (entrySite != null && !(entrySite instanceof Core) && topEntry != null) {
Site currentSite = topEntry.def.getSite();
if (!entrySite.equals(currentSite)) {
Map<String, Object> siteCache = siteCaches.get(entrySite.getName());
if (siteCache == null) {
siteCache = newHashMap(Object.class);
siteCaches.put(entrySite.getName(), siteCache);
}
entry.setSiteCache(siteCache);
}
}
}
stateCount = stateFactory.nextState();
entry.setState(stateCount);
_push(entry);
if (entry.def instanceof NamedDefinition) {
definingDef = entry.def;
// add keep and cache directives to this entry's list.
NamedDefinition scopedef = (NamedDefinition) ((entry.superdef == null && entry.def instanceof NamedDefinition) ? entry.def : entry.superdef);
Entry prev = entry.link;
if (!newFrame && prev != null) {
if (sharesKeeps(entry, prev, true)) {
setKeepsFromEntry(prev);
setInsertsFromEntry(prev);
} else {
List<KeepStatement> keeps = scopedef.getKeeps();
if (keeps != null) {
Iterator<KeepStatement> it = keeps.iterator();
while (it.hasNext()) {
KeepStatement k = it.next();
try {
keep(k);
} catch (Redirection r) {
vlog("Error in keep statement: " + r.getMessage());
throw r;
}
}
String keepCacheKey = scopedef.getName() + ".keep";
String globalKeepCacheKey = makeGlobalKey(scopedef.getFullNameInContext(this)) + ".keep";
while (prev != null) {
Object keepCache = prev.get(keepCacheKey, globalKeepCacheKey, null, true);
if (keepCache != null) {
topEntry.addKeepCache((Map<String, Object>) keepCache);
break;
}
prev = prev.link;
}
}
}
} else if (newScope) {
List<KeepStatement> keeps = scopedef.getKeeps();
if (keeps != null) {
Iterator<KeepStatement> it = keeps.iterator();
while (it.hasNext()) {
KeepStatement k = it.next();
try {
keep(k);
} catch (Redirection r) {
vlog("Error in keep statement: " + r.getMessage());
throw r;
}
}
}
// Don't cache the keep map if the def owning the keeps is dynamic or the current instantiation
// of the owning def is dynamic.
// Not sure if entry.args is right -- maybe should be the args for the entry where
// scopedef shows up (assuming scopedef is right -- maybe should be entry.def)
if (scopedef.getDurability() != Definition.DYNAMIC && (entry.args == null || !entry.args.isDynamic())) {
String keepCacheKey = scopedef.getName() + ".keep";
String globalKeepCacheKey = makeGlobalKey(scopedef.getFullNameInContext(this)) + ".keep";
while (prev != null) {
Object keepCache = prev.get(keepCacheKey, globalKeepCacheKey, null, true);
if (keepCache != null) {
topEntry.addKeepCache((Map<String, Object>) keepCache);
break;
}
prev = prev.link;
}
}
List<InsertStatement> inserts = scopedef.getInserts();
if (inserts != null) {
Iterator<InsertStatement> it = inserts.iterator();
while (it.hasNext()) {
InsertStatement i = it.next();
try {
insert(i);
} catch (Redirection r) {
vlog("Error in insert statement: " + r.getMessage());
throw r;
}
}
}
}
}
}
private NamedDefinition dealias(NamedDefinition def) {
while (def != null && (def.isIdentity() || def.isAlias())) {
// if this is an identity, look for the definition of the passed instance.
// Look directly in the top entry rather than calling getDefinition, which in
// some cases would cause infinite regression
if (def.isIdentity()) {
Holder holder = peek().getDefHolder(def.getName(), makeGlobalKey(def.getFullNameInContext(this)), null, false);
if (holder != null && !def.equals(holder.def)) {
def = (NamedDefinition) holder.def;
} else {
break;
}
} else if (def.isAlias()) {
Instantiation aliasInstance = def.getAliasInstance();
Definition aliasDef = aliasInstance.getDefinition(this, def);
if (aliasDef == null) {
break;
}
def = (NamedDefinition) aliasDef;
}
}
return def;
}
private boolean sharesKeeps(Entry entry, Entry prev, boolean forward) {
boolean shares = false;
if (forward && prev.def.equals(entry.def) && (prev.superdef == null || entry.superdef == null || prev.superdef.equalsOrExtends(entry.superdef) || entry.superdef.equalsOrExtends(prev.superdef))) {
shares = true;
} else if (!forward && prev.def.isAlias()) {
Definition prevSuperdef = prev.def.getSuperDefinition();
Definition thisSuperdef = entry.def.getSuperDefinition();
if (prevSuperdef != null && thisSuperdef != null && (prevSuperdef.equalsOrExtends(thisSuperdef) || thisSuperdef.equalsOrExtends(prevSuperdef))) {
shares = true;
}
}
return shares;
}
private synchronized void _push(Entry entry) {
if (entry.def == null) {
throw new NullPointerException("attempt to push null definition on context");
}
if (size >= maxSize) {
throw new RuntimeException("blown context");
} else if (size == 200) {
System.err.println("**** context exceeding 200 ****");
} else if (size == 100) {
System.err.println("**** context exceeding 100 ****");
} else if (size == 50) {
System.err.println("**** context exceeding 50 ****");
}
size++;
//System.out.println("ctx " + Integer.toHexString(hashCode()) + " size ^" + size);
if (rootEntry == null) {
if (entry.getPrevious() != null) {
entry = newEntry(entry, true);
}
setRootEntry(entry);
} else {
if (entry.getPrevious() != topEntry) {
if (entry.getPrevious() != null) {
entry = newEntry(entry, true);
}
entry.setPrevious(topEntry);
}
}
setTop(entry);
int calcSize = 0;
Entry e = topEntry;
while (e != null) {
calcSize++;
e = e.link;
}
if (calcSize != size) {
System.out.println("Ctx 3761 context size incorrect (stored size = " + size + ", real size = " + calcSize + ")" );
}
}
private void setRootEntry(Entry entry) {
rootEntry = entry;
Site site = entry.def.getSite();
List<Name> adoptedSites = site.getAdoptedSiteList();
if (adoptedSites != null) {
Iterator<Name> it = adoptedSites.iterator();
while (it.hasNext()) {
Name adoptedSite = it.next();
Map<String, Object> adoptedSiteCache = siteCaches.get(adoptedSite.getName());
if (adoptedSiteCache == null) {
adoptedSiteCache = newHashMap(Object.class);
siteCaches.put(adoptedSite.getName(), adoptedSiteCache);
}
}
rootEntry.setSiteCacheMap(siteCaches, adoptedSites);
}
}
public synchronized void pop() {
Entry entry = _pop();
if (topEntry != null) {
stateCount = topEntry.getState();
definingDef = topEntry.def;
if (sharesKeeps(entry, topEntry, false)) {
addKeepsFromEntry(entry);
}
} else {
stateCount = -1;
definingDef = null;
}
oldEntry(entry);
}
private Entry _pop() {
if (size > 0) {
if (topEntry == popLimit) {
vlog("popping context beyond popLimit");
throw new IndexOutOfBoundsException("Illegal pop attempt; can only pop entries pushed after this copy was made.");
}
Entry entry = topEntry;
setTop(entry.getPrevious());
size
int calcSize = 0;
Entry e = topEntry;
while (e != null) {
calcSize++;
e = e.link;
}
if (calcSize != size) {
System.out.println("Ctx 3796 context size incorrect (stored size = " + size + ", real size = " + calcSize + ")" );
}
//System.out.println("ctx " + Integer.toHexString(hashCode()) + " size v" + size);
return entry;
} else {
return null;
}
}
public synchronized Entry unpush() {
if (size <= 1) {
throw new IndexOutOfBoundsException("Attempt to unpush root entry in context");
}
Entry entry = _pop();
unpushedEntries.push(entry);
return entry;
}
public synchronized void repush() {
if (unpushedEntries == null) {
System.out.println("Null!!! ctx 3608");
}
Entry entry = unpushedEntries.pop();
// by pre-setting the link to topEntry, we avoid the logic in _push that clones
// the entry being pushed
entry.setPrevious(topEntry);
_push(entry);
}
public synchronized void unpop(Definition def, ParameterList params, ArgumentList args) {
Definition contextDef = getContextDefinition(def);
_push(newEntry(contextDef, contextDef, params, args));
}
public synchronized void unpop(Entry entry) {
_push(entry);
}
public synchronized Entry repop() {
Entry entry = _pop();
return entry;
}
public Entry peek() {
return topEntry;
}
public Definition getDefiningDef() {
return definingDef;
}
public void pushParam(DefParameter param, Construction arg) throws Redirection {
if (size >= maxSize) {
throw new RuntimeException("blown context");
} else if (size < 1) {
throw new NoSuchElementException("Cannot push a parameter onto an empty context");
}
Entry entry = topEntry;
if (entry.params == null || entry.params.size() == 0) {
entry.params = new ParameterList(newArrayList(1, DefParameter.class));
} else if (entry.params.size() == entry.origParamsSize) {
entry.params = new ParameterList(newArrayList(entry.params));
} else {
entry = newEntry(entry, true);
push(entry);
}
if (entry.args == null || entry.args.size() == 0) {
entry.args = new ArgumentList(newArrayList(1, Construction.class));
} else if (entry.args.size() == entry.origArgsSize) {
entry.args = new ArgumentList(newArrayList(entry.args));
}
entry.params.add(param);
entry.args.add(arg);
}
public void popParam() {
Entry entry = topEntry;
int n = entry.params.size();
if (n > entry.origParamsSize + 1) {
pop();
} else if (n > 0) {
entry.params.remove(n - 1);
// this entry may have started with fewer args than params
entry.args.remove(entry.args.size() - 1);
}
}
/** Advances the current loop index to a new unique integer value, i.e. a value
* not used by any other pass in this loop or any other loop in the same context,
* and returns this value.
*
* @throws NullPointerException if the context is uninitialized.
*/
public int nextLoopIndex() {
topEntry.advanceLoopIndex();
return topEntry.getLoopIndex();
}
public void resetLoopIndex() {
topEntry.resetLoopIndex();
}
public int getLoopIndex() {
if (topEntry != null) {
return topEntry.getLoopIndex();
}
return -1;
}
public void setLoopIndex(int index) {
if (topEntry != null) {
topEntry.setLoopIndex(index);
}
}
public ArgumentList getArguments() {
if (topEntry != null) {
return topEntry.args;
}
return null;
}
public ParameterList getParameters() {
if (topEntry != null) {
return topEntry.params;
}
return null;
}
public Iterator<Entry> iterator() {
return new ContextIterator();
}
public boolean equals(Object obj) {
if (obj instanceof Context) {
Context other = (Context) obj;
return (rootContext == other.rootContext && stateCount == other.stateCount && getLoopIndex() == other.getLoopIndex());
} else if (obj instanceof ContextMarker) {
ContextMarker marker = (ContextMarker) obj;
return (rootContext == marker.rootContext && stateCount == marker.stateCount && getLoopIndex() == marker.loopIndex);
} else {
return false;
}
}
public boolean equalsOrPrecedes(Object obj) {
if (obj instanceof Context) {
Context context = (Context) obj;
if (rootContext == context.rootContext) {
if (stateCount == context.stateCount && getLoopIndex() <= context.getLoopIndex()) {
return true;
} else if (stateCount < context.stateCount) {
Iterator<Entry> it = context.iterator();
while (it.hasNext()) {
Entry entry = (Entry) it.next();
if (entry.equals(topEntry)) {
return true;
}
}
}
}
} else if (obj instanceof ContextMarker) {
ContextMarker marker = (ContextMarker) obj;
if (rootContext == marker.rootContext) {
if (stateCount == marker.stateCount && getLoopIndex() <= marker.loopIndex) {
return true;
} else if (stateCount < marker.stateCount) {
return true;
}
}
}
return false;
}
public boolean isCompatible(Context context) {
if (context != null && rootContext == context.rootContext) {
if (stateCount == context.stateCount) {
return true;
} else if (stateCount < context.stateCount) {
if (topEntry != null) {
Iterator<Entry> it = context.iterator();
while (it.hasNext()) {
Entry entry = it.next();
if (entry.equals(topEntry)) {
return true;
}
}
}
} else if (context.topEntry != null) {
Iterator<Entry> it = iterator();
while (it.hasNext()) {
Entry entry = it.next();
if (entry.equals(context.topEntry)) {
return true;
}
}
}
}
return false;
}
public void clear() {
unpushedEntries = new Stack<Entry>();
setTop(null);
definingDef = null;
instantiatedDef = null;
popLimit = null;
cache = null;
size = 0;
errorThreshhold = EVERYTHING;
// careful -- these are dangerous to leave null for long
rootContext = null;
rootEntry = null;
}
private void setTop(Entry entry) {
if (topEntry != null) {
topEntry.decRefCount();
}
topEntry = entry;
if (topEntry != null) {
topEntry.incRefCount();
}
}
/** Makes this context a copy of the passed context. */
synchronized private void copy(Context context, boolean clearCache) {
clear();
int calcSize = 0;
Entry e = context.topEntry;
while (e != null) {
calcSize++;
e = e.link;
}
if (calcSize != context.size) {
System.out.println("Ctx 4031 context size incorrect (stored size = " + context.size + ", real size = " + calcSize + ")" );
}
// copy the root
rootContext = context.rootContext;
definingDef = context.definingDef;
instantiatedDef = context.instantiatedDef;
// this is a copy, so don't pop past the current top
popLimit = topEntry;
// copy the global state variables
stateCount = context.stateCount;
stateFactory = context.stateFactory;
size = context.size;
errorThreshhold = context.errorThreshhold;
// copy the session
session = context.session;
// // deep copy the unpushed entries, so the context and its copy
// // can unpush separately
// Entry toEntry = null;
// for (Entry fromEntry = context.unpushedEntries; fromEntry != null; fromEntry = fromEntry.link) {
// if (toEntry == null) {
// toEntry = newEntry(fromEntry, true);
// unpushedEntries = toEntry;
// } else {
// toEntry.link = newEntry(fromEntry, true);
// toEntry = toEntry.link;
keepMap = context.keepMap;
// just one global cache
globalCache = context.globalCache;
if (!clearCache) {
rootEntry = context.rootEntry;
// share the cache
cache = context.cache;
siteCaches = context.siteCaches;
if (context.topEntry != null) {
if (context.topEntry == context.rootEntry) {
setRootEntry(newEntry(context.rootEntry, true));
setTop(rootEntry);
} else {
// clone the top entry only. This assumes that entries from the root
// up to just below the top will not be modified in the new context,
// because those entries are shared with the original context.
setTop(newEntry(context.topEntry, true));
topEntry.setPrevious(context.topEntry.getPrevious());
}
}
} else {
cache = newHashMap(Object.class);
siteCaches = newHashMapOfMaps(Object.class);
setRootEntry(newEntry(context.rootEntry, false));
setTop(rootEntry);
}
calcSize = 0;
e = topEntry;
while (e != null) {
calcSize++;
e = e.link;
}
if (calcSize != size) {
System.out.println("Ctx 4114 context size incorrect (stored size = " + size + ", real size = " + calcSize + ")" );
}
}
public int hashCode() {
int n = (rootEntry == null ? 0 : (rootEntry.hashCode() << 16) + stateCount);
return n;
}
public String toString() {
return dump("\n");
}
public String toHTML() {
return "<pre>" + Utils.htmlEncode(toString()) + "</pre>";
}
private String dump(String newline) {
String str = "context #" + hashCode() + " $" + stateCount + newline;
str = str + " top> " + topEntry.toString() + newline;
for (Context.Entry entry = topEntry.link; entry != null; entry = entry.link) {
str = str + " -> " + entry.toString() + newline;
}
return str;
}
public Object getMarker(Object obj) {
if (obj == null) {
return new ContextMarker(this);
} else {
mark(obj);
return obj;
}
}
public Object getMarker() {
return new ContextMarker(this);
}
public void mark(Object obj) {
if (obj instanceof ContextMarker) {
synchronized (obj) {
ContextMarker marker = (ContextMarker) obj;
marker.rootContext = rootContext;
marker.stateCount = stateCount;
marker.loopIndex = getLoopIndex();
}
} else {
throw new IllegalArgumentException("attempt to mark a strange object");
}
}
public Object clone() {
Context context = new Context(this, false);
numClonedContexts++;
return context;
}
public Context clone(boolean clearCache) {
Context context = new Context(this, clearCache);
numClonedContexts++;
return context;
}
private static Object getCachedData(Map<String, Object> cache, String key) {
Object data = null;
data = cache.get(key);
if (data == null) {
int ix = key.indexOf('.');
if (ix > 0) {
String firstKey = key.substring(0, ix);
String restOfKey = key.substring(ix + 1);
Object obj = cache.get(firstKey);
if (obj != null && obj instanceof Holder) {
Holder holder = (Holder) obj;
if (holder.data != null && holder.data instanceof Map<?,?>) {
data = getCachedData((Map<String, Object>) holder.data, restOfKey);
}
}
if (data == null) {
String keepCacheKey = firstKey + ".keep";
Map<String, Object> keepCache = (Map<String, Object>) cache.get(keepCacheKey);
if (keepCache != null) {
data = getCachedData(keepCache, restOfKey);
}
}
}
}
return data;
}
static class KeepHolder {
public NameNode keepName;
public Definition owner;
public ResolvedInstance[] resolvedInstances;
public NameNode byName;
public Map<String, Object> table;
public boolean persist;
public boolean inContainer;
public boolean asThis;
KeepHolder(NameNode keepName, Definition owner, ResolvedInstance[] resolvedInstances, NameNode byName, Map<String, Object> table, boolean persist, boolean inContainer, boolean asThis) {
this.keepName = keepName;
this.owner = owner;
this.resolvedInstances = resolvedInstances;
this.byName = byName;
this.table = table;
this.persist = persist;
this.inContainer = inContainer;
this.asThis = asThis;
}
Definition[] getDefinitions() {
int numDefs = resolvedInstances.length;
Definition[] defs = new Definition[numDefs];
for (int i = 0; i < numDefs; i++) {
defs[i] = resolvedInstances[i].getDefinition();
}
return defs;
}
}
static class Pointer {
ResolvedInstance ri;
ResolvedInstance riAs;
Object key;
Map<String, Object> cache;
boolean persist;
public Pointer(ResolvedInstance ri, Object key, Map<String, Object> cache, boolean persist) {
this(ri, ri, key, cache, persist);
}
public Pointer(ResolvedInstance ri, ResolvedInstance riAs, Object key, Map<String, Object> cache, boolean persist) {
this.ri = ri;
this.riAs = riAs;
this.key = key;
this.cache = cache;
this.persist = persist;
}
public String getKey() {
if (key instanceof Value) {
return ((Value) key).getString();
} else {
return key.toString();
}
}
public String toString() {
return toString("");
}
public String toString(String prefix) {
StringBuffer sb = new StringBuffer(prefix);
prefix += " ";
sb.append("===> ");
sb.append(key == null ? "(null)" : key);
sb.append(": ");
if (cache != null) {
Object obj = cache.get(key);
if (obj != null) {
if (obj instanceof AbstractNode) {
sb.append("\n");
sb.append(((AbstractNode) obj).toString(prefix));
} else if (obj instanceof Pointer) {
sb.append("\n");
sb.append(((Pointer) obj).toString(prefix));
} else {
sb.append(obj.toString());
}
} else {
sb.append("(null)");
}
}
return sb.toString();
}
}
private static int hashMapsCreated = 0;
public static int getNumHashMapsCreated() {
return hashMapsCreated;
}
public static <E> HashMap<String, E> newHashMap(Class<E> c) {
hashMapsCreated++;
return new HashMap<String, E>();
}
public static <E> HashMap<String, E> newHashMap(Map<String, E> map) {
hashMapsCreated++;
return new HashMap<String, E>(map);
}
public static <E> HashMap<String, Map<String,E>> newHashMapOfMaps(Class<E> c) {
hashMapsCreated++;
return new HashMap<String, Map<String, E>>();
}
private static int arrayListsCreated = 0;
private static long totalListSize = 0L;
public static int getNumArrayListsCreated() {
return arrayListsCreated;
}
public static long getTotalListSize() {
return totalListSize;
}
public static <E> ArrayList<E> newArrayList(int size, Class<E> c) {
arrayListsCreated++;
totalListSize += size;
return new ArrayList<E>(size);
}
public static <E> ArrayList<E> newArrayList(int size, List<E> list) {
arrayListsCreated++;
totalListSize += size;
return new ArrayList<E>(size);
}
public static <E> ArrayList<E> newArrayList(List<E> list) {
arrayListsCreated++;
totalListSize += list.size();
return new ArrayList<E>(list);
}
protected static int entriesCreated = 0;
public static int getNumEntriesCreated() {
return entriesCreated;
}
protected static int entriesCloned = 0;
public static int getNumEntriesCloned() {
return entriesCloned;
}
public Entry newEntry(Definition def, Definition superdef, ParameterList params, ArgumentList args) {
Map<String, Object> entryCache = null;
if (def instanceof Site) {
entryCache = siteCaches.get(def.getName());
if (entryCache == null) {
entryCache = newHashMap(Object.class);
siteCaches.put(def.getName(), entryCache);
}
}
// ENTRY REUSE HAS BEEN DISABLED FOR NOW
// getAbandonedEntry will always return null
Entry entry = getAbandonedEntry();
if (entry != null) {
entry.init(def, superdef, params, args, entryCache, globalCache);
} else {
entry = new Entry(def, superdef, params, args, entryCache, globalCache);
}
return entry;
}
public Entry newEntry(Entry copyEntry, boolean copyCache) {
// ENTRY REUSE HAS BEEN DISABLED FOR NOW
// getAbandonedEntry will always return null
Entry entry = getAbandonedEntry();
if (entry != null) {
entry.copy(copyEntry, copyCache);
} else {
entry = new Entry(copyEntry, copyCache);
}
return entry;
}
private void oldEntry(Entry entry) {
// recycle if the refCount has dropped to zero, unless it's the top of the
// unpushedEntries stack, which may have a refCount of 0 but should
// definitely not be abandoned.
synchronized (entry) {
if (entry.refCount == 0 && !unpushedEntries.contains(entry)) {
entry.clear();
addAbandonedEntry(entry);
} else {
//vlog(" !!! popped an entry with ref count of " + entry.refCount);
}
}
}
// DISABLE ENTRY REUSE FOR NOW
// see addAbandonedEntry
private Entry getAbandonedEntry() {
Entry entry = rootContext.abandonedEntries;
if (entry != null) {
synchronized (rootContext.abandonedEntries) {
Entry next = entry.getPrevious();
entry.setPrevious(null);
rootContext.abandonedEntries = next;
}
}
return entry;
}
// DISABLE ENTRY REUSE FOR NOW
// by disabling this function
private void addAbandonedEntry(Entry entry) {
//entry.setPrevious(rootContext.abandonedEntries);
//rootContext.abandonedEntries = entry;
}
public static class Entry {
public Definition def;
public Definition superdef;
public ParameterList params;
public ArgumentList args;
public Map<String, Pointer> keepMap = null;
public List<KeepHolder> dynamicKeeps = null;
public Map<String, Type> insertAboveMap = null;
public Map<String, Type> insertBelowMap = null;
protected Entry link = null;
int refCount = 0; // number of links by other entries to this one
private int contextState = -1;
private int loopIx = -1;
protected int origParamsSize;
protected int origArgsSize;
private StateFactory loopIndexFactory;
// Only one copy of a context entry gets to write to the cache; other copies have
// read-only access.
private Map<String, Object> cache = null;
private Map<String, Object> readOnlyCache = null;
private Map<String, Object> globalCache = null;
// Objects that are persisted through keep directives are cached here
private Map<String, Object> keepCache = null;
private Map<String, Object> siteCache = null;
private Map<String, Map<String, Object>> siteCacheMap = null;
private List<Name> adoptedSites = null;
protected Entry(Definition def, Definition superdef, ParameterList params, ArgumentList args, Map<String, Object> cache, Map<String, Object> globalCache) {
entriesCreated++;
this.def = def;
this.superdef = superdef;
this.params = (params != null ? (ParameterList) params.clone() : new ParameterList(newArrayList(0, DefParameter.class)));
this.args = (args != null ? (ArgumentList) args.clone() : new ArgumentList(newArrayList(0, Construction.class)));
origParamsSize = this.params.size();
origArgsSize = this.args.size();
// fill out the argument list with nulls if it's shorter than the parameter list
while (origArgsSize < origParamsSize) {
this.args.add(ArgumentList.MISSING_ARG);
origArgsSize++;
}
loopIndexFactory = new StateFactory();
this.cache = cache;
this.siteCache = cache;
this.globalCache = globalCache;
}
protected Entry(Entry entry, boolean copyCache) {
entriesCreated++;
entriesCloned++;
def = entry.def;
superdef = entry.superdef;
params = (entry.params != null ? (ParameterList) entry.params.clone() : new ParameterList(newArrayList(0, DefParameter.class)));
args = (entry.args != null ? (ArgumentList) entry.args.clone() : new ArgumentList(newArrayList(0, Construction.class)));
// don't clone the link to avoid duplicating references. If the
// clone needs to point somewhere, it has to be done explicitly.
contextState = entry.contextState;
loopIx = entry.loopIx;
loopIndexFactory = entry.loopIndexFactory;
origParamsSize = entry.origParamsSize;
origArgsSize = entry.origArgsSize;
// the keep map and global cache are always shared
keepMap = entry.keepMap;
globalCache = entry.globalCache;
// make shallow copy of cache if copyCache flag is true, otherwise they
// will be null;
if (copyCache) {
// for now, no read only cache, let everybody write (yikes!)
//entry.readOnlyCache = (cache != null ? cache : readOnlyCache);
cache = entry.getCache();
keepCache = entry.getKeepCache();
siteCache = entry.siteCache;
siteCacheMap = entry.siteCacheMap;
adoptedSites = entry.adoptedSites;
dynamicKeeps = entry.dynamicKeeps;
}
}
void init(Definition def, Definition superdef, ParameterList params, ArgumentList args, Map<String, Object> cache, Map<String, Object> globalCache) {
this.def = def;
this.superdef = superdef;
this.params = (params != null ? (ParameterList) params.clone() : new ParameterList(newArrayList(0, DefParameter.class)));
this.args = (args != null ? (ArgumentList) args.clone() : new ArgumentList(newArrayList(0, Construction.class)));
origParamsSize = this.params.size();
origArgsSize = this.args.size();
// fill out the argument list with nulls if it's shorter than the parameter list
while (origArgsSize < origParamsSize) {
this.args.add(ArgumentList.MISSING_ARG);
origArgsSize++;
}
this.cache = cache;
this.globalCache = globalCache;
this.keepCache = null;
this.siteCache = cache;
this.siteCacheMap = null;
}
void copy(Entry entry, boolean copyCache) {
if (refCount > 0) {
throw new RuntimeException("Attempt to copy over entry with non-zero refCount");
}
def = entry.def;
superdef = entry.superdef;
if (params != null) {
params.clear();
if (entry.params != null) {
params.addAll(entry.params);
}
} else {
params = (entry.params != null ? (ParameterList) entry.params.clone() : new ParameterList(newArrayList(0, DefParameter.class)));
}
if (args != null) {
args.clear();
if (entry.args != null) {
args.addAll(entry.args);
}
} else {
args = (entry.args != null ? (ArgumentList) entry.args.clone() : new ArgumentList(newArrayList(0, Construction.class)));
}
contextState = entry.contextState;
loopIx = entry.loopIx;
loopIndexFactory = entry.loopIndexFactory;
origParamsSize = entry.origParamsSize;
origArgsSize = entry.origArgsSize;
// for now, let everybody write (yikes!)
//entry.readOnlyCache = (cache != null ? cache : readOnlyCache);
if (copyCache) {
copyKeeps(entry);
} else {
cache = null;
keepCache = null;
siteCache = null;
// keepMap and globalCache are shared everywhere
keepMap = entry.keepMap;
globalCache = entry.globalCache;
}
}
void copyKeeps(Entry entry) {
// Calling getCache allocates the cache if it doesn't exist; this is
// wasteful if the cache never gets used, but it guarantees that if the
// cache is used, it's the same cache for every entry that wants to use
// the same cache.
// To eliminate the waste, we could wait till the cache is allocated,
// then backfill previous entries as appropriate. For now, we do the
// allocation on the first copy, trading greater waste for less risk.
cache = entry.getCache();
keepCache = entry.keepCache;
siteCache = entry.siteCache;
siteCacheMap = entry.siteCacheMap;
adoptedSites = entry.adoptedSites;
keepMap = entry.keepMap;
globalCache = entry.globalCache;
dynamicKeeps = entry.dynamicKeeps;
}
void addKeeps(Entry entry) {
if (cache != null) {
if (entry.cache != null && entry.cache != cache) {
synchronized (cache) {
cache.putAll(entry.cache);
}
}
} else {
cache = entry.cache;
}
if (keepCache != null) {
if (entry.keepCache != null && entry.keepCache != keepCache) {
synchronized (keepCache) {
keepCache.putAll(entry.keepCache);
}
}
} else {
keepCache = entry.keepCache;
}
if (siteCache != null) {
if (entry.siteCache != null && entry.siteCache != siteCache) {
synchronized (siteCache) {
siteCache.putAll(entry.siteCache);
}
}
} else {
siteCache = entry.siteCache;
}
if (siteCacheMap != null) {
if (entry.siteCacheMap != null && entry.siteCacheMap != siteCacheMap) {
synchronized (siteCacheMap) {
siteCacheMap.putAll(entry.siteCacheMap);
}
}
} else {
siteCacheMap = entry.siteCacheMap;
}
if (adoptedSites != null) {
if (entry.adoptedSites != null && entry.adoptedSites != adoptedSites) {
synchronized (adoptedSites) {
adoptedSites.addAll(entry.adoptedSites);
}
}
} else {
adoptedSites = entry.adoptedSites;
}
if (keepMap != null) {
if (entry.keepMap != null && entry.keepMap != keepMap) {
synchronized (keepMap) {
keepMap.putAll(entry.keepMap);
}
}
} else {
keepMap = entry.keepMap;
}
if (globalCache != null) {
if (entry.globalCache != null && entry.globalCache != globalCache) {
synchronized (globalCache) {
globalCache.putAll(entry.globalCache);
}
}
} else {
globalCache = entry.globalCache;
}
}
void copyInserts(Entry entry) {
insertAboveMap = entry.insertAboveMap;
}
public void clear() {
if (refCount > 0) {
throw new RuntimeException("Attempt to clear entry with non-zero refCount");
}
def = null;
superdef = null;
if (params != null) {
params.clear();
}
if (args != null) {
args.clear();
}
setPrevious(null);
origParamsSize = 0;
origArgsSize = 0;
keepMap = null;
insertAboveMap = null;
cache = null;
readOnlyCache = null;
globalCache = null;
keepCache = null;
siteCache = null;
siteCacheMap = null;
adoptedSites = null;
}
public void addInsert(Type insertedType, Type targetType, int insertionPoint) {
switch (insertionPoint) {
case InsertStatement.ABOVE:
if (insertAboveMap == null) {
insertAboveMap = new HashMap<String, Type>();
}
insertAboveMap.put(targetType.getName(), insertedType);
break;
case InsertStatement.BELOW:
if (insertBelowMap == null) {
insertBelowMap = new HashMap<String, Type>();
}
insertBelowMap.put(targetType.getName(), insertedType);
break;
}
}
public void addDynamicKeep(KeepHolder keepHolder) {
if (dynamicKeeps == null) {
dynamicKeeps = new ArrayList<KeepHolder>(4);
}
if (!dynamicKeeps.contains(keepHolder)) {
dynamicKeeps.add(keepHolder);
}
}
public void addKeep(ResolvedInstance[] resolvedInstances, Object keyObj, Map<String, Object> table, String containerKey, Map<String, Object> containerTable, boolean persist, Map<String, Pointer> contextKeepMap, Map<String, Object> contextCache) {
boolean inContainer = (containerTable != null);
if (def.isGlobal()) {
contextCache = globalCache;
}
if (keepMap == null) {
keepMap = newHashMap(Pointer.class);
}
synchronized (keepMap) {
int numInstances = resolvedInstances.length;
String key = (keyObj == null ? null : (keyObj instanceof Value ? ((Value) keyObj).getString() : keyObj.toString()));
if (key != null) {
if (!key.endsWith(".")) {
ResolvedInstance riAs = resolvedInstances[numInstances - 1];
for (int i = 0; i < numInstances; i++) {
if (resolvedInstances[i] != null) {
Pointer p = new Pointer(resolvedInstances[i], riAs, keyObj, table, persist);
String keepKey = (inContainer ? key : resolvedInstances[i].getName());
keepMap.put(keepKey, p);
String contextKey = def.getFullName() + '.' + keepKey;
contextKey = contextKey.substring(contextKey.indexOf('.') + 1);
Pointer contextp = new Pointer(resolvedInstances[i], riAs, contextKey, contextCache, persist);
contextKeepMap.put(contextKey, contextp);
}
}
} else {
for (int i = 0; i < numInstances; i++) {
if (resolvedInstances[i] != null) {
String name = resolvedInstances[i].getName();
String keepKey = key + name;
Pointer p = new Pointer(resolvedInstances[i], keepKey, table, persist);
keepMap.put(keepKey, p);
if (inContainer) {
p = new Pointer(resolvedInstances[i], keepKey, containerTable, persist);
keepMap.put(containerKey + name, p);
}
String contextKey = def.getFullName() + '.' + keepKey;
contextKey = contextKey.substring(contextKey.indexOf('.') + 1);
Pointer contextp = new Pointer(resolvedInstances[i], contextKey, contextCache, persist);
contextKeepMap.put(contextKey, contextp);
}
}
}
} else {
for (int i = 0; i < numInstances; i++) {
if (resolvedInstances[i] != null) {
String name = resolvedInstances[i].getName();
Pointer p = new Pointer(resolvedInstances[i], name, table, persist);
keepMap.put(name, p);
if (inContainer) {
p = new Pointer(resolvedInstances[i], containerKey + name, containerTable, persist);
keepMap.put("+" + name, p);
}
String contextKey = def.getFullName() + '.' + name;
contextKey = contextKey.substring(contextKey.indexOf('.') + 1);
Pointer contextp = new Pointer(resolvedInstances[i], contextKey, contextCache, persist);
contextKeepMap.put(contextKey, contextp);
}
}
}
}
}
public void removeKeep(String name) {
synchronized (keepMap) {
keepMap.remove(name);
}
}
/** Returns true if a parameter of the specified name is present in this entry. */
public boolean paramIsPresent(NameNode nameNode, boolean checkForArg) {
boolean isPresent = false;
String name = nameNode.getName();
int n = name.indexOf('.');
if (n > 0) {
name = name.substring(0, n);
}
int numParams = params.size();
for (int i = 0; i < numParams; i++) {
DefParameter param = params.get(i);
if (name.equals(param.getName()) && (!checkForArg || args.get(i) != ArgumentList.MISSING_ARG)) {
isPresent = true;
break;
}
}
return isPresent;
}
/** Return the parameter by a given name, or null if there isn't one. */
public DefParameter getParam(String name) {
int n = name.indexOf('.');
if (n > 0) {
name = name.substring(0, n);
}
int numParams = params.size();
for (int i = 0; i < numParams; i++) {
DefParameter param = params.get(i);
if (name.equals(param.getName()) && args.get(i) != ArgumentList.MISSING_ARG) {
return param;
}
}
return null;
}
public Object get(String key, String globalKey, ArgumentList args, boolean local) {
return get(key, globalKey, args, false, local);
}
public Definition getDefinition(String key, String globalKey, ArgumentList args) {
Holder holder = (Holder) get(key, globalKey, args, true, false);
if (holder != null) {
return holder.def;
} else {
return null;
}
}
public Holder getDefHolder(String key, String globalKey, ArgumentList args, boolean local) {
return (Holder) get(key, globalKey, args, true, local);
}
private Object get(String key, String globalKey, ArgumentList args, boolean getDefHolder, boolean local) {
Holder holder = null;
Map<String, Object> c = (cache != null ? cache : readOnlyCache);
if (globalCache != null && globalKey != null && globalCache.get(globalKey) != null) {
c = globalCache;
}
if (c == null && siteCache == null && siteCacheMap == null && (keepMap == null || keepMap.get(key) == null)) {
if (this.def == null) {
return null;
}
if (!local && link != null && !this.def.hasChildDefinition(key) && !NameNode.isSpecialName(key)) {
return link.get(key, globalKey, args, getDefHolder, false);
} else {
return null;
}
}
Object data = null;
Definition def = null;
ResolvedInstance ri = null;
// If there is a keep entry here but no value was retrieved from the cache above
// then it means the value has not been instantiated yet in this context. If
// this is not a keep statement, or there is no value for this key in the
// out-of-context cache, or if the key is accompanied by a non-null modifier,
// return null rather than continue the search up the context chain in order to
// force instantiation and avoid bypassing the designated cache.
if (data == null && keepMap != null && keepMap.get(key) != null) {
Pointer p = keepMap.get(key);
if (!p.persist) {
return null;
}
ri = p.ri;
Map<String, Object> keepTable = p.cache;
data = keepTable.get(p.getKey());
if (data instanceof Pointer) {
int i = 0;
do {
p = (Pointer) data;
data = p.cache.get(p.getKey());
if (data instanceof Holder) {
holder = (Holder) data;
data = (holder.data == AbstractNode.UNINSTANTIATED ? null : holder.data);
def = holder.def;
args = holder.args;
ri = holder.resolvedInstance;
}
i++;
if (i >= MAX_POINTER_CHAIN_LENGTH) {
throw new IndexOutOfBoundsException("Pointer chain in cache exceeds limit");
}
} while (data instanceof Pointer);
} else if (data instanceof Holder) {
holder = (Holder) data;
data = (holder.data == AbstractNode.UNINSTANTIATED ? null : holder.data);
def = p.riAs.getDefinition();
args = holder.args;
ri = holder.resolvedInstance;
} else if (data instanceof ElementDefinition) {
def = (Definition) data;
data = ((ElementDefinition) data).getElement();
data = AbstractNode.getObjectValue(null, data);
}
}
if (data == null && !local && (siteCache != null || siteCacheMap != null)) {
if (siteCache != null) {
data = siteCache.get(key);
} else {
Iterator<Name> it = adoptedSites.iterator();
while (it.hasNext()) {
NameNode adoptedSiteName = (NameNode) it.next();
Map<String, Object> adoptedSiteCache = (Map<String, Object>) siteCacheMap.get(adoptedSiteName.getName());
data = adoptedSiteCache.get(key);
if (data != null) {
break;
}
}
}
if (data != null) {
if (data instanceof Holder) {
holder = (Holder) data;
data = (holder.data == AbstractNode.UNINSTANTIATED ? null : holder.data);
def = holder.def;
args = holder.args;
ri = holder.resolvedInstance;
} else if (data instanceof Pointer) {
def = ((Pointer) data).riAs.getDefinition();
// strip off modifier if present
key = baseKey(((Pointer) data).getKey());
}
String loopModifier = getLoopModifier();
if (loopModifier != null) {
if (data instanceof Pointer && ((Pointer) data).cache == siteCache) {
data = siteCache.get(key + loopModifier);
}
}
if (data != null) {
// to prevent an infinite loop arising from a circular list
// of pointers, abort after reaching a maximum
int i = 0;
if (data instanceof Pointer) {
do {
Pointer p = (Pointer) data;
data = p.cache.get(p.getKey());
if (data instanceof Holder) {
holder = (Holder) data;
data = (holder.data == AbstractNode.UNINSTANTIATED ? null : holder.data);
def = holder.def;
args = holder.args;
ri = holder.resolvedInstance;
}
i++;
if (i >= MAX_POINTER_CHAIN_LENGTH) {
throw new IndexOutOfBoundsException("Pointer chain in cache exceeds limit");
}
} while (data instanceof Pointer);
} else if (data instanceof Holder) {
holder = (Holder) data;
data = (holder.data == AbstractNode.UNINSTANTIATED ? null : holder.data);
def = holder.def;
args = holder.args;
ri = holder.resolvedInstance;
}
}
}
}
if (data == null && c != null) {
String ckey = (c == globalCache ? globalKey : key);
data = getCachedData(c, ckey);
if (data != null) {
if (data instanceof ElementDefinition) {
def = (Definition) data;
data = ((ElementDefinition) def).getElement();
} else if (data instanceof Holder) {
holder = (Holder) data;
data = (holder.data == AbstractNode.UNINSTANTIATED ? null : holder.data);
def = holder.def;
args = holder.args;
ri = holder.resolvedInstance;
} else if (data instanceof Pointer) {
def = ((Pointer) data).riAs.getDefinition();
ckey = baseKey(((Pointer) data).getKey());
}
String loopModifier = getLoopModifier();
if (loopModifier != null) {
if (data instanceof Pointer && ((Pointer) data).cache == c) {
data = c.get(ckey + loopModifier);
}
}
}
if (data != null) {
// to prevent an infinite loop arising from a circular list
// of pointers, abort after reaching a maximum
int i = 0;
if (data instanceof Pointer) {
do {
Pointer p = (Pointer) data;
data = p.cache.get(p.getKey());
if (data instanceof Holder) {
holder = (Holder) data;
data = (holder.data == AbstractNode.UNINSTANTIATED ? null : holder.data);
def = holder.def;
args = holder.args;
ri = holder.resolvedInstance;
}
i++;
if (i >= MAX_POINTER_CHAIN_LENGTH) {
throw new IndexOutOfBoundsException("Pointer chain in cache exceeds limit");
}
} while (data instanceof Pointer);
} else if (data instanceof Holder) {
holder = (Holder) data;
data = (holder.data == AbstractNode.UNINSTANTIATED ? null : holder.data);
def = holder.def;
args = holder.args;
ri = holder.resolvedInstance;
}
}
}
// continue up the context chain
if (data == null && (def == null || !getDefHolder) && !local && link != null && !this.def.hasChildDefinition(key) && !NameNode.isSpecialName(key)) {
return link.get(key, globalKey, args, getDefHolder, false);
}
// return either the definition or the data, depending on the passed flag
if (getDefHolder) {
if (holder == null) {
if (def == null && ri != null) {
def = ri.getDefinition();
}
// if def is null, this might be an entry resulting from an "as" clause
// in a keep statement, so look in the keep table for an entry.
if (def == null && keepMap != null && keepMap.get(key) != null) {
Pointer p = keepMap.get(key);
def = p.riAs.getDefinition();
}
if (def != null) {
Definition nominalDef = def;
ArgumentList nominalArgs = args;
holder = new Holder(nominalDef, nominalArgs, def, args, null, data, ri);
} else if (data != null) {
holder = new Holder(null, null, null, null, null, data, null);
}
}
return holder;
} else {
return data;
}
}
/** If the current cache contains a Pointer under the specified key, stores the
* data in the cache pointed to by the Pointer; otherwise stores the data in the
* current cache. Then traverses back up the context tree, storing the data in
* any other context level where data for that key is explicitly stored (i.e. the
* cache contains a Pointer for that key, or the entry definition is the owner or
* a subdefinition of the owner of a child whose name is the key).
*
* If the definition parameter is non-null, the data and the definition are
* wrapped in a Holder, which is cached.
*/
public void put(String key, Definition nominalDef, ArgumentList nominalArgs, Definition def, ArgumentList args, Context context, Object data, ResolvedInstance resolvedInstance, int maxLevels) {
Holder holder = new Holder(nominalDef, nominalArgs, def, args, context, data, resolvedInstance);
put(key, holder, context, maxLevels);
}
private void put(String key, Holder holder, Context context, int maxLevels) {
boolean kept = false;
Definition def = holder.def;
Definition nominalDef = holder.nominalDef;
Map<String, Object> localCache = getCache();
synchronized (localCache) {
if (localPut(localCache, key, holder)) {
kept = true;
}
}
if (nominalDef != null) {
if (nominalDef.isGlobal() && nominalDef.getName().equals(key)) {
if (globalCache != null) {
synchronized (globalCache) {
String globalKey = makeGlobalKey(nominalDef.getFullNameInContext(context));
localPut(globalCache, globalKey, holder);
}
}
}
if (nominalDef.getOwner() instanceof Site) {
Map<String, Object> siteCache = getSiteCache(nominalDef);
if (siteCache != null) {
synchronized (siteCache) {
localPut(siteCache, key, holder);
}
}
}
}
//if (contextPut(key, holder, context)) {
// kept = true;
// if this is an identity, copy the keep cache (if any) from the real
// def to the nominal def
// this seems to catch too wide a net, and doesn't seem to be needed anyway
// if (def != null && !key.equals(def.getName())) {
// String keepCacheKey = def.getName() + ".keep";
// Object keepCache = localCache.get(keepCacheKey);
// if (keepCache != null) {
// localCache.put(key + ".keep", keepCache);
int access = (nominalDef != null ? nominalDef.getAccess() : Definition.LOCAL_ACCESS);
if (link != null && access != Definition.LOCAL_ACCESS) {
String ownerName = this.def.getName();
if (ownerName != null && nominalDef != null && !nominalDef.isFormalParam()) {
// should this be def or nominalDef?
Definition defOwner = nominalDef.getOwner();
for (Entry nextEntry = link; nextEntry != null; nextEntry = nextEntry.link) {
if (nextEntry.def.equalsOrExtends(defOwner)) {
// get the subbest subclass
do {
defOwner = nextEntry.def;
nextEntry = nextEntry.link;
} while (nextEntry != null && nextEntry.def.equalsOrExtends(defOwner));
break;
}
}
for (String k = key; defOwner != null && k.indexOf('.') > 0; k = k.substring(k.indexOf('.') + 1)) {
defOwner = defOwner.getOwner();
}
if (defOwner != null && defOwner.getDurability() != Definition.DYNAMIC && this.def.equalsOrExtends(defOwner)) {
Definition defOwnerOwner = defOwner.getOwner();
Entry entry = link;
while (entry != null) {
if (entry.def.equalsOrExtends(defOwnerOwner)) {
break;
}
entry = entry.link;
}
if (entry != null) {
Map<String, Object> ownerCache = entry.getCache();
synchronized (ownerCache) {
entry.localPut(ownerCache, ownerName + "." + key, holder);
}
}
}
}
// keep directives intercept cache updates
if (maxLevels > 0) maxLevels
if (!kept && maxLevels != 0) {
if (this.def.hasChildDefinition(key)) {
KeepStatement keep = this.def.getKeep(key);
if (keep == null || !(keep.isInContainer() || keep.getTableInstance() != null /* || this.def.equals(link.def) */ )) {
return;
}
}
link.checkForPut(key, holder, context, maxLevels);
}
}
}
private Entry getContainerEntry(Definition def) {
if (def != null) {
Entry entry = this;
while (entry != null) {
if (!entry.def.equalsOrExtends(def)) {
break;
}
entry = entry.link;
}
return entry;
}
return null;
}
private Entry getOwnerContainerEntry(Definition def) {
if (def != null) {
Definition ownerDef = def.getOwner();
if (ownerDef != null) {
Entry entry = this;
while (entry != null) {
if (entry.def.equalsOrExtends(ownerDef)) {
break;
}
entry = entry.link;
}
return entry;
}
}
return null;
}
public boolean localPut(Map<String, Object> cache, String key, Holder holder) {
boolean kept = false;
boolean persist = false;
Pointer p = null;
Object oldData = cache.get(key);
// if this is the first entry, set up any required pointers for keep tables
// and modifiers, save the data and return
if (oldData == null || (oldData instanceof Holder && (((Holder) oldData).data == AbstractNode.UNINSTANTIATED || ((Holder) oldData).data == null))) {
Object newData;
newData = holder;
//if (def != null) {
// newData = new Holder(def, args, context, data);
//} else {
// newData = data;
if (keepMap != null) {
p = keepMap.get(key);
if (p != null) {
// first check for a pointer to the container. If there is one it will have
// the same key but prepended with a "+"
Pointer pContainer = keepMap.get("+" + key);
if (pContainer != null) {
Map<String, Object> containerTable = pContainer.cache;
containerTable.put(pContainer.getKey(), newData);
}
persist = p.persist;
Map<String, Object> keepTable = p.cache;
if (keepTable != cache || !key.equals(p.getKey())) {
synchronized (keepTable) {
p = new Pointer(p.ri, p.riAs, p.getKey(), keepTable, persist);
// two scenarios: keep as and cached identity. With keep as, we want the
// pointer def; with cached identity, we want the holder def. We can tell
// cached identities because the def and nominalDef in the holder are different.
Definition newDef;
if (holder.def != null && !holder.def.equals(holder.nominalDef)) {
newDef = holder.def;
} else {
newDef = p.riAs.getDefinition();
}
ArgumentList newArgs = (newDef == holder.def ? holder.args : null);
Holder newHolder = new Holder(holder.nominalDef, holder.nominalArgs, newDef, newArgs, null, holder.data, holder.resolvedInstance);
keepTable.put(p.getKey(), newHolder);
newData = p;
}
}
kept = true;
}
}
cache.put(key, newData);
} else {
// There is an existing entry. See if it's a modifier
if (oldData instanceof Pointer) {
p = (Pointer) oldData;
persist = p.persist;
Map<String, Object> keepTable = p.cache;
if (keepTable != cache || !key.equals(p.getKey())) {
p = new Pointer(p.ri, p.riAs, p.getKey(), keepTable, persist);
// two scenarios: keep as and cached identity. With keep as, we want the
// pointer def; with cached identity, we want the holder def. We can tell
// cached identities either from the definition's identity flag or because
// the def and nominalDef in the holder are different.
Definition newDef = (!holder.def.equals(holder.nominalDef) || holder.def.isIdentity() ? holder.def : p.riAs.getDefinition());
ArgumentList newArgs = (newDef == holder.def ? holder.args : null);
holder = new Holder(holder.nominalDef, holder.nominalArgs, newDef, newArgs, null, holder.data, holder.resolvedInstance);
kept = true;
}
}
// Follow the pointer chain to update the data
Map<String, Object> nextCache = cache;
String nextKey = key;
Object nextData = oldData;
while (nextData != null && nextData instanceof Pointer) {
p = (Pointer) nextData;
nextCache = p.cache;
nextKey = p.getKey();
nextData = nextCache.get(nextKey);
}
synchronized (nextCache) {
//if (def != null) {
// data = new Holder(def, args, context, data);
nextCache.put(nextKey, holder);
}
// Finally look for a container cache pointer. nextKey at this point
// should have the unmodified, unaliased version of the key
p = (Pointer) cache.get("+" + nextKey);
if (p != null) {
nextCache = p.cache;
nextKey = p.getKey();
synchronized (nextCache) {
nextCache.put(nextKey, holder);
}
}
}
return kept;
}
public boolean contextPut(String key, Holder holder, Context context) {
boolean kept = false;
boolean persist = false;
// repeat the above logic for the context cache, if necessary
Map<String, Pointer> contextKeepMap = context.getKeepMap();
String contextKey = key;
if (holder.nominalDef != null) {
String fullName = holder.nominalDef.getFullName();
if (fullName != null) {
// this sort of solves the problem of multipart keys
if (fullName.endsWith(key)) {
contextKey = fullName;
} else {
int ix = fullName.lastIndexOf('.');
if (ix > 0) {
contextKey = fullName.substring(0, ix + 1) + key;
}
}
}
}
// context caching logic goes as follows:
// -- unlike local caching, context caching only happens when explicitly
// specified by a keep statement.
// -- so look for a keep statement for the context key, determined above.
// A keep statement implies that a keep map exists, and a context exists,
// and a Pointer object is stored in the keep map under the key
if (contextKeepMap != null && contextKey != null) {
Pointer contextp = contextKeepMap.get(contextKey);
if (contextp != null) {
Map<String, Object> contextCache = context.getCache();
persist = contextp.persist;
Object oldContextData = contextp.cache.get(contextKey);
if (oldContextData == null) {
Object newContextData;
newContextData = holder;
//if (def != null) {
// newContextData = new Holder(def, args, context, data);
//} else {
// newContextData = data;
if (contextp.cache != contextCache || !contextp.getKey().equals(contextKey)) {
contextp = new Pointer(contextp.ri, contextp.riAs, contextp.getKey(), contextCache, persist);
contextp.cache.put(contextp.getKey(), newContextData);
newContextData = contextp;
}
contextCache.put(contextKey, newContextData);
} else {
// There is an existing entry. See if it's a modifier
if (oldContextData instanceof Pointer) {
contextp = (Pointer) oldContextData;
persist = contextp.persist;
if (contextp.cache == contextCache) { // it's a modifier or cache alias
String pkey = contextp.getKey();
if (contextKey.equals(baseKey(pkey)) && !pkey.equals(contextKey)) { // it's a modifier but not the same modifier
// move the chain data to the new spot
synchronized (contextCache) {
oldContextData = contextCache.get(pkey);
contextCache.put(pkey, null);
contextp = new Pointer(contextp.ri, contextp.riAs, contextKey + addLoopModifier(), contextCache, persist);
contextCache.put(contextp.getKey(), oldContextData);
contextCache.put(contextKey, contextp);
oldContextData = contextp;
}
}
} else { // it's a table in a keep directive
kept = true;
}
}
// Follow the pointer chain to update the data
Map<String, Object> nextCache = contextCache;
String nextKey = contextKey;
Object nextData = oldContextData;
while (nextData != null && nextData instanceof Pointer) {
Pointer nextp = (Pointer) nextData;
nextCache = nextp.cache;
nextKey = nextp.getKey();
nextData = nextCache.get(nextKey);
}
synchronized (nextCache) {
nextCache.put(nextKey, holder);
}
}
}
}
return kept;
}
private void checkForPut(String key, Holder holder, Context context, int maxLevels) {
if ((cache != null && cache.get(key) != null) ||
(keepMap != null && keepMap.get(key) != null) ||
hasSiteCache(def) ||
this.def.hasChildDefinition(key)) {
put(key, holder, context, maxLevels);
} else {
if (maxLevels > 0) maxLevels
if (link != null && maxLevels != 0) {
link.checkForPut(key, holder, context, maxLevels);
}
}
}
boolean hasSiteCacheEntryFor(Definition def) {
if (def != null) {
String key = def.getName();
if (siteCache != null) {
if (siteCache.get(key) != null) {
return true;
}
}
if (siteCacheMap != null) {
Definition defOwner = def.getOwner();
if (defOwner instanceof Site) {
String defSiteName = defOwner.getName();
Map<String, Object> cache = (Map<String, Object>) siteCacheMap.get(defSiteName);
if (cache != null) {
if (cache.get(key) != null) {
return true;
}
}
}
}
}
return false;
}
private boolean hasSiteCache(Definition def) {
if (siteCache != null) {
return true;
}
if (siteCacheMap != null && def != null) {
Definition defOwner = def.getOwner();
if (defOwner instanceof Site) {
String defSiteName = defOwner.getName();
Iterator<Name> it = adoptedSites.iterator();
while (it.hasNext()) {
NameNode siteName = (NameNode) it.next();
if (siteName.getName().equals(defSiteName)) {
return true;
}
}
}
}
return false;
}
boolean isAdopted(Name name) {
if (adoptedSites != null) {
return adoptedSites.contains(name);
} else {
return false;
}
}
private String getLoopModifier() {
int loopIx = getLoopIndex();
if (loopIx >= 0) {
return "#" + String.valueOf(loopIx);
} else {
return null;
}
}
private String addLoopModifier() {
int loopIx = getLoopIndex();
if (loopIx >= 0) {
return '#' + String.valueOf(loopIx);
} else {
return "";
}
}
Map<String, Object> getCache() {
if (cache == null) {
if (readOnlyCache != null) {
//throw new UnsupportedOperationException("this context entry does not have write access to the cache");
}
cache = newHashMap(Object.class);
}
return cache;
}
Map<String, Object> getKeepCache() {
if (keepMap == null) {
keepMap = newHashMap(Pointer.class);
}
if ("piece_serializer".equals(def.getName())) {
System.out.println("Ctx 5541");
}
if (keepCache == null) {
// cache the keep cache in the owner entry in the context
Entry containerEntry = getOwnerContainerEntry(def);
if (containerEntry != null) {
String key = def.getName() + ".keep";
Map<String, Object> containerCache = containerEntry.getCache();
synchronized (containerCache) {
keepCache = (Map<String, Object>) containerCache.get(key);
if (keepCache == null) {
keepCache = newHashMap(Object.class);
if (def.getDurability() != Definition.DYNAMIC) {
containerCache.put(key, keepCache);
}
keepCache.put("from", keepMap);
} else {
vlog(" ---)> retrieving keep cache for " + def.getName() + " from " + containerEntry.def.getName());
}
}
} else {
keepCache = newHashMap(Object.class);
}
} else {
// make sure the keep cache is cached in the owner entry
// in the context
Entry containerEntry = getOwnerContainerEntry(def);
if (containerEntry != null) {
String key = def.getName() + ".keep";
Map<String, Object> containerCache = containerEntry.getCache();
Map<String, Object> containerKeepCache = (Map<String, Object>) containerCache.get(key);
if (containerKeepCache == null) {
keepCache.put("from", keepMap);
if (def.getDurability() != Definition.DYNAMIC) {
containerCache.put(key, keepCache);
}
}
}
}
return keepCache;
}
void addKeepCache(Map<String, Object> cache) {
if (keepCache == null) {
keepCache = newHashMap(Object.class);
}
Set<Map.Entry<String, Object>> entrySet = cache.entrySet();
Iterator<Map.Entry<String, Object>> it = entrySet.iterator();
while (it.hasNext()) {
Map.Entry<String, Object> entry = it.next();
String key = entry.getKey();
if (!key.equals("from")) {
keepCache.put(entry.getKey(), entry.getValue());
}
}
if (keepMap == null) {
keepMap = newHashMap(Pointer.class);
keepCache.put("from", keepMap);
}
Map<String, Pointer> map = (Map<String, Pointer>) cache.get("from");
if (map != null) {
keepMap.putAll(map);
}
}
public boolean equals(Object obj) {
if (obj instanceof Entry) {
Entry entry = (Entry) obj;
if (def.equals(entry.def) && args.equals(entry.args)) {
if (superdef == null) {
return (entry.superdef == null);
} else {
return superdef.equals(entry.superdef);
}
}
}
return false;
}
public boolean covers(Definition def) {
if (def.equals(this.def) || def.equals(superdef)) {
return true;
} else {
return def.equalsOrExtends(this.def.getSuperDefinition());
}
}
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(def.getName());
sb.append(" <");
if (superdef != null) {
sb.append(superdef.getName());
}
sb.append("> A:");
if (args != null && args.size() > 0) {
sb.append(args.toString());
} else {
sb.append("()");
}
sb.append(" P:");
if (params != null && params.size() > 0) {
sb.append(params.toString());
} else {
sb.append("()");
}
if (loopIx > -1) {
sb.append("@" + loopIx);
}
return sb.toString();
}
int getState() {
return contextState;
}
void setState(int state) {
contextState = state;
}
int getLoopIndex() {
return loopIx;
}
void setLoopIndex(int ix) {
loopIx = ix;
}
void advanceLoopIndex() {
loopIx = loopIndexFactory.nextState();
}
void resetLoopIndex() {
loopIx = -1;
}
public boolean isInLoop() {
return loopIx != -1;
}
public Entry getPrevious() {
return link;
}
void setPrevious(Entry entry) {
// decrement the ref count in the old link
if (link != null) {
link.refCount
}
link = entry;
if (link != null) {
link.refCount++;
}
}
void incRefCount() {
refCount++;
}
void decRefCount() {
refCount
}
Map<String, Object> getSiteCache(Definition def) {
if (siteCache != null) {
return siteCache;
} else if (siteCacheMap != null) {
Site site = def.getSite();
if (site != null) {
return siteCacheMap.get(site.getName());
}
}
return null;
}
void setSiteCache(Map<String, Object> siteCache) {
this.siteCache = siteCache;
}
void setSiteCacheMap(Map<String, Map<String, Object>> siteCacheMap, List<Name> adoptedSites) {
this.siteCacheMap = siteCacheMap;
this.adoptedSites = adoptedSites;
}
}
class ContextIterator implements Iterator<Entry> {
private Entry nextEntry;
public ContextIterator() {
nextEntry = topEntry;
}
public boolean hasNext() {
return (nextEntry != null);
}
public Entry next() {
if (nextEntry == null) {
throw new NoSuchElementException();
}
Entry entry = nextEntry;
nextEntry = nextEntry.getPrevious();
return entry;
}
public void remove() {
throw new UnsupportedOperationException("ReverseIterator does not support remove");
}
}
}
class ContextMarker {
Context rootContext = null;
int stateCount = -1;
int loopIndex = -1;
public ContextMarker() {}
public ContextMarker(Context context) {
context.mark(this);
}
public boolean equals(Object object) {
if (object instanceof ContextMarker) {
ContextMarker marker = (ContextMarker) object;
if (loopIndex >= 0) {
SiteBuilder.vlog("comparing context marker loop indices: " + loopIndex + " to " + marker.loopIndex);
}
return (marker.rootContext == rootContext && marker.stateCount == stateCount && marker.loopIndex == loopIndex);
} else {
return object.equals(this);
}
}
public int hashCode() {
int n = (rootContext.getRootEntry().hashCode() << 16) + stateCount;
return n;
}
}
|
package org.skyve.impl.generate;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.skyve.domain.Bean;
import org.skyve.impl.metadata.model.document.DocumentImpl;
import org.skyve.impl.metadata.repository.AbstractRepository;
import org.skyve.impl.metadata.repository.LocalDesignRepository;
import org.skyve.impl.metadata.repository.view.Actions;
import org.skyve.impl.metadata.repository.view.ViewMetaData;
import org.skyve.impl.metadata.view.ActionImpl;
import org.skyve.impl.metadata.view.ViewImpl;
import org.skyve.impl.metadata.view.WidgetReference;
import org.skyve.impl.metadata.view.container.Tab;
import org.skyve.impl.metadata.view.container.TabPane;
import org.skyve.impl.metadata.view.container.form.Form;
import org.skyve.impl.metadata.view.container.form.FormColumn;
import org.skyve.impl.metadata.view.container.form.FormItem;
import org.skyve.impl.metadata.view.container.form.FormRow;
import org.skyve.impl.metadata.view.widget.bound.input.DefaultWidget;
import org.skyve.impl.metadata.view.widget.bound.input.ListMembership;
import org.skyve.impl.metadata.view.widget.bound.input.LookupDescription;
import org.skyve.impl.metadata.view.widget.bound.tabular.AbstractDataWidget;
import org.skyve.impl.metadata.view.widget.bound.tabular.DataGrid;
import org.skyve.impl.metadata.view.widget.bound.tabular.DataGridBoundColumn;
import org.skyve.impl.util.UtilImpl;
import org.skyve.impl.util.XMLMetaData;
import org.skyve.metadata.MetaData;
import org.skyve.metadata.MetaDataException;
import org.skyve.metadata.controller.ImplicitActionName;
import org.skyve.metadata.customer.Customer;
import org.skyve.metadata.model.Attribute;
import org.skyve.metadata.model.Extends;
import org.skyve.metadata.model.document.Collection;
import org.skyve.metadata.model.document.Collection.CollectionType;
import org.skyve.metadata.model.document.Document;
import org.skyve.metadata.model.document.DomainType;
import org.skyve.metadata.model.document.Inverse;
import org.skyve.metadata.module.Module;
import org.skyve.metadata.module.query.QueryDefinition;
import org.skyve.metadata.view.Action;
import org.skyve.metadata.view.View.ViewType;
import org.skyve.util.Binder;
import org.skyve.util.Binder.TargetMetaData;
public class ViewGenerator {
private static final Integer THIRTY = new Integer(30);
private static final Integer SIXTY = new Integer(60);
private static final Integer FOUR = new Integer(4);
private static final Integer TWELVE = new Integer(12);
private ViewGenerator() {
// do nothing
}
public static ViewImpl generate(Customer customer, Document document, String viewName) {
ViewImpl result = null;
Module module = customer.getModule(document.getOwningModuleName());
if (ViewType.list.toString().equals(viewName)) {
QueryDefinition defaultQuery = module.getDocumentDefaultQuery(customer, document.getName());
result = generateListView(customer, document, defaultQuery, null);
}
else if (ViewType.edit.toString().equals(viewName)) {
result = generateEditView(customer, module, document);
}
else {
throw new IllegalArgumentException("ViewGenerator : Cannot generate a view of type " + viewName);
}
return result;
}
@SuppressWarnings("unused")
public static ViewImpl generateListView(Customer customer, Document document, QueryDefinition query, String description) {
ViewImpl result = new ViewImpl();
result.setName(ViewType.list.toString());
StringBuilder title = new StringBuilder(64);
String finalDescription = description;
if (finalDescription == null) {
finalDescription = document.getDescription();
}
if (finalDescription == null) {
finalDescription = document.getPluralAlias();
}
if (finalDescription != null) {
title.append(finalDescription);
}
result.setTitle(title.toString());
ActionImpl action = new ActionImpl();
action.setImplicitName(ImplicitActionName.DEFAULTS);
result.putAction(action);
/*
* Table table = generateTable(customer, document, null, query);
* result.getContained().add(table);
* String modelName = model.getName();
*
* String documentName = modelName; if (model instanceof Selection) { documentName = ((Selection) model).getDocumentName();
* }
*/
return result;
}
private static class Detail {
String title;
MetaData widget;
}
private static ViewImpl generateEditView(Customer customer, Module module, Document document) {
ViewImpl result = new ViewImpl();
result.setName(ViewType.edit.toString());
result.setTitle(document.getSingularAlias());
ActionImpl action = new ActionImpl();
action.setImplicitName(ImplicitActionName.DEFAULTS);
result.putAction(action);
AbstractRepository repository = AbstractRepository.get();
// Add any actions that have privileges
for (String actionName : ((DocumentImpl) document).getDefinedActionNames()) {
action = new ActionImpl();
try {
repository.getServerSideAction(customer, document, actionName, false);
}
catch (Exception e) {
try {
repository.getUploadAction(customer, document, actionName, false);
action.setImplicitName(ImplicitActionName.Upload);
}
catch (Exception e1) {
try {
repository.getDownloadAction(customer, document, actionName, false);
action.setImplicitName(ImplicitActionName.Download);
}
catch (Exception e2) {
try {
repository.getBizExportAction(customer, document, actionName, false);
action.setImplicitName(ImplicitActionName.BizExport);
}
catch (Exception e3) {
try {
repository.getBizImportAction(customer, document, actionName, false);
action.setImplicitName(ImplicitActionName.BizImport);
}
catch (Exception e4) {
throw new MetaDataException(actionName + " cannot be found");
}
}
}
}
}
action.setResourceName(actionName);
action.setDisplayName(actionName);
result.putAction(action);
}
Form form = new Form();
form.setBorder(Boolean.TRUE);
form.setPercentageWidth(SIXTY);
form.setResponsiveWidth(TWELVE);
FormColumn column = new FormColumn();
column.setPercentageWidth(THIRTY);
column.setResponsiveWidth(FOUR);
form.getColumns().add(column);
form.getColumns().add(new FormColumn());
List<Detail> details = new ArrayList<>();
processAttributes(customer, module, document, form, details);
// make a tabbed view if more than 1 detail widget or there is 1 detail widget and more than 5 form fields
int numberOfDetailWidgets = details.size();
if ((numberOfDetailWidgets > 1) ||
((numberOfDetailWidgets == 1) && (form.getRows().size() > 5))) {
TabPane tabPane = new TabPane();
Tab tab = null;
if (! form.getRows().isEmpty()) {
tab = new Tab();
tab.setTitle("General");
tab.getContained().add(form);
tabPane.getTabs().add(tab);
}
for (Detail detail : details) {
tab = new Tab();
tab.setTitle(detail.title);
MetaData detailWidget = detail.widget;
if (detailWidget instanceof AbstractDataWidget) {
AbstractDataWidget adw = (AbstractDataWidget) detailWidget;
adw.setTitle(null);
}
tab.getContained().add(detailWidget);
tabPane.getTabs().add(tab);
}
result.getContained().add(tabPane);
}
else {
if (! form.getRows().isEmpty()) {
result.getContained().add(form);
}
for (Detail detail : details) {
result.getContained().add(detail.widget);
}
}
return result;
}
private static void processAttributes(Customer customer,
Module module,
Document document,
Form form,
List<Detail> details) {
Extends inherits = document.getExtends();
if (inherits != null) {
Document baseDocument = module.getDocument(customer, inherits.getDocumentName());
processAttributes(customer, module, baseDocument, form, details);
}
for (Attribute attribute : document.getAttributes()) {
if (! attribute.isDeprecated()) {
String attributeName = attribute.getName();
if (attribute instanceof Collection) {
Collection collection = (Collection) attribute;
Document detailDocument = module.getDocument(customer, collection.getDocumentName());
List<String> propertyNames = new ArrayList<>();
populatePropertyNames(customer, module, detailDocument, propertyNames);
if (collection.getDomainType() == null) {
@SuppressWarnings("synthetic-access")
Detail detail = new Detail();
detail.title = attribute.getDisplayName();
detail.widget = generateDataGrid(collection.getType(),
customer,
module,
detailDocument,
attributeName,
propertyNames);
details.add(detail);
}
else {
@SuppressWarnings("synthetic-access")
Detail detail = new Detail();
detail.title = attribute.getDisplayName();
ListMembership membership = new ListMembership();
membership.setBinding(attribute.getName());
membership.setCandidatesHeading("Candidates");
membership.setMembersHeading("Members");
detail.widget = membership;
details.add(detail);
}
}
else if (attribute instanceof Inverse) {
Inverse inverse = (Inverse) attribute;
Document detailDocument = module.getDocument(customer, inverse.getDocumentName());
List<String> propertyNames = new ArrayList<>();
populatePropertyNames(customer, module, detailDocument, propertyNames);
@SuppressWarnings("synthetic-access")
Detail detail = new Detail();
detail.title = attribute.getDisplayName();
detail.widget = generateDataGrid(CollectionType.composition,
customer,
module,
detailDocument,
attributeName,
propertyNames);
details.add(detail);
}
else { // field or association
FormItem item = new FormItem();
DefaultWidget widget = new DefaultWidget();
widget.setBinding(attributeName);
item.setWidget(widget);
FormRow row = new FormRow();
row.getItems().add(item);
form.getRows().add(row);
}
}
}
}
private static void populatePropertyNames(Customer customer,
Module module,
Document document,
List<String> propertyNames) {
Extends inherits = document.getExtends();
if (inherits != null) {
String inheritedDocumentName = inherits.getDocumentName();
Document inheritedDocument = module.getDocument(customer, inheritedDocumentName);
populatePropertyNames(customer, module, inheritedDocument, propertyNames);
}
for (Attribute detailAttribute : document.getAttributes()) {
if ((! (detailAttribute instanceof Collection)) && (! (detailAttribute instanceof Inverse)) && // only scalars
(! detailAttribute.getName().equals(Bean.BIZ_KEY))) {
propertyNames.add(detailAttribute.getName());
}
}
}
private static DataGrid generateDataGrid(CollectionType collectionType,
Customer customer,
Module module,
Document document,
String dataGridBinding,
List<String> propertyNames) {
DataGrid result = new DataGrid();
if (dataGridBinding != null) {
result.setBinding(dataGridBinding);
result.setTitle(document.getPluralAlias());
}
if (CollectionType.aggregation.equals(collectionType)) {
DataGridBoundColumn column = new DataGridBoundColumn();
column.setBinding(null); // no column binding
LookupDescription lookup = new LookupDescription();
lookup.setDescriptionBinding(Bean.BIZ_KEY);
WidgetReference lookupRef = new WidgetReference();
lookupRef.setWidget(lookup);
column.setInputWidget(lookupRef);
result.getColumns().add(column);
}
else {
for (String propertyName : propertyNames) {
TargetMetaData target = Binder.getMetaDataForBinding(customer, module, document, propertyName);
Attribute attribute = target.getAttribute();
DataGridBoundColumn column = new DataGridBoundColumn();
DomainType domainType = attribute.getDomainType();
if (DomainType.dynamic.equals(domainType)) {
column.setBinding(Binder.createCompoundBinding(propertyName, Bean.BIZ_KEY));
column.setEditable(Boolean.FALSE);
}
else {
column.setBinding(propertyName);
}
result.getColumns().add(column);
}
}
if (result.getColumns().isEmpty()) {
DataGridBoundColumn column = new DataGridBoundColumn();
column.setBinding(Bean.BIZ_KEY);
column.setEditable(Boolean.FALSE);
result.getColumns().add(column);
}
return result;
}
public static String generateEditViewXML(Customer customer,
Document document,
boolean customerOverridden,
boolean uxuiOverridden) {
ViewImpl view = generate(customer, document, ViewType.edit.toString());
ViewMetaData repositoryView = new ViewMetaData();
repositoryView.setName(ViewType.edit.toString());
repositoryView.setTitle(view.getTitle());
repositoryView.getContained().addAll(view.getContained());
Actions actions = new Actions();
for (Action action : view.getActions()) {
actions.getActions().add(((ActionImpl) action).toRepositoryAction());
}
repositoryView.setActions(actions);
return XMLMetaData.marshalView(repositoryView, customerOverridden, uxuiOverridden);
}
public static void main(String[] args) throws Exception {
String srcPath = null;
String customerName = null;
String moduleName = null;
String documentName = null;
String uxui = null;
boolean customerOverridden = false;
boolean validArgs = true;
if (args.length >= 5) {
srcPath = args[0];
customerName = args[1];
moduleName = args[2];
documentName = args[3];
customerOverridden = Boolean.parseBoolean(args[4]);
if (args.length == 6) {
uxui = args[5];
}
if (args.length > 6) {
validArgs = false;
}
}
else {
validArgs = false;
}
if (! validArgs) {
System.err.println("Usage: org.skyve.impl.generate.ViewGenerator sourcePath (usually \"src/skyve/\") customerName moduleName documentName customerOverridden (boolean) uxui (optional)");
System.exit(1);
}
AbstractRepository.set(new LocalDesignRepository());
AbstractRepository repository = AbstractRepository.get();
Customer customer = repository.getCustomer(customerName);
// If the module and/or document was not specified, we will just generate all edit views.
if (StringUtils.isBlank(moduleName) || StringUtils.isBlank(documentName)) {
for (Module module : customer.getModules()) {
for (Map.Entry<String, Module.DocumentRef> entry : module.getDocumentRefs().entrySet()) {
Module.DocumentRef documentRef = entry.getValue();
if (documentRef.getOwningModuleName().equals(module.getName())) {
Document document = module.getDocument(customer, entry.getKey());
try {
writeEditView(srcPath, module, document, customer, customerOverridden, uxui);
} catch (Exception e) {
UtilImpl.LOGGER.warning(String.format("Failed to generate edit view for %s.%s, %s.",
module.getName(), document.getName(), e.getMessage()));
}
}
}
}
} else {
Module module = repository.getModule(customer, moduleName);
Document document = repository.getDocument(customer, module, documentName);
writeEditView(srcPath, module, document, customer, customerOverridden, uxui);
}
}
private static void writeEditView(String srcPath, Module module, Document document, Customer customer,
boolean customerOverridden,
String uxui) throws IOException {
StringBuilder filePath = new StringBuilder(64);
filePath.append(srcPath);
if (customerOverridden) {
filePath.append("customers/").append(customer.getName()).append("/modules/");
}
else {
filePath.append("modules/");
}
filePath.append(module.getName()).append('/').append(document.getName()).append("/views/");
if (uxui != null) {
filePath.append(uxui).append('/');
}
File file = new File(filePath.toString());
file.mkdirs();
filePath.append("generatedEdit.xml");
file = new File(filePath.toString());
UtilImpl.LOGGER.info("Output is written to " + file.getCanonicalPath());
try (PrintWriter out = new PrintWriter(file)) {
out.println(generateEditViewXML(customer, document, customerOverridden, uxui != null));
out.flush();
}
}
}
|
package gov.nih.nci.nbia.restUtil;
import java.util.List;
public class CollectionUtil {
private long created;
List<String> authorizedCollections;
public long getCreated() {
return created;
}
public void setCreated(long created) {
this.created = created;
}
public List<String> getAuthorizedCollections() {
return authorizedCollections;
}
public void setAuthorizedCollections(List<String> authorizedCollections) {
this.authorizedCollections = authorizedCollections;
}
}
|
package io.scif.util;
import io.scif.FormatException;
import io.scif.ImageMetadata;
import io.scif.Metadata;
import io.scif.Plane;
import io.scif.Reader;
import io.scif.Writer;
import io.scif.common.ReflectException;
import io.scif.common.ReflectedUniverse;
import io.scif.io.RandomAccessInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Vector;
import net.imglib2.meta.Axes;
import net.imglib2.meta.AxisType;
import net.imglib2.meta.CalibratedAxis;
import net.imglib2.meta.axis.DefaultLinearAxis;
import net.imglib2.meta.axis.LinearAxis;
/**
* A collection of constants and utility methods applicable for all cycles of
* image processing within SCIFIO.
*/
public final class FormatTools {
// -- Constants --
public static final String[] COMPRESSION_SUFFIXES = { "bz2", "gz" };
// -- Constants - Thumbnail dimensions --
/** Default height and width for thumbnails. */
public static final int THUMBNAIL_DIMENSION = 128;
// -- Constants - pixel types --
/** Identifies the <i>INT8</i> data type used to store pixel values. */
public static final int INT8 = 0;
/** Identifies the <i>UINT8</i> data type used to store pixel values. */
public static final int UINT8 = 1;
/** Identifies the <i>INT16</i> data type used to store pixel values. */
public static final int INT16 = 2;
/** Identifies the <i>UINT16</i> data type used to store pixel values. */
public static final int UINT16 = 3;
/** Identifies the <i>INT32</i> data type used to store pixel values. */
public static final int INT32 = 4;
/** Identifies the <i>UINT32</i> data type used to store pixel values. */
public static final int UINT32 = 5;
/** Identifies the <i>FLOAT</i> data type used to store pixel values. */
public static final int FLOAT = 6;
/** Identifies the <i>DOUBLE</i> data type used to store pixel values. */
public static final int DOUBLE = 7;
/** Human readable pixel type. */
private static final String[] pixelTypes = makePixelTypes();
static String[] makePixelTypes() {
final String[] pixelTypes = new String[8];
pixelTypes[INT8] = "int8";
pixelTypes[UINT8] = "uint8";
pixelTypes[INT16] = "int16";
pixelTypes[UINT16] = "uint16";
pixelTypes[INT32] = "int32";
pixelTypes[UINT32] = "uint32";
pixelTypes[FLOAT] = "float";
pixelTypes[DOUBLE] = "double";
return pixelTypes;
}
// -- Constants - miscellaneous --
/** File grouping options. */
public static final int MUST_GROUP = 0;
public static final int CAN_GROUP = 1;
public static final int CANNOT_GROUP = 2;
/** Patterns to be used when constructing a pattern for output filenames. */
public static final String SERIES_NUM = "%s";
public static final String SERIES_NAME = "%n";
public static final String CHANNEL_NUM = "%c";
public static final String CHANNEL_NAME = "%w";
public static final String Z_NUM = "%z";
public static final String T_NUM = "%t";
public static final String TIMESTAMP = "%A";
// -- Constants - domains --
/** Identifies the high content screening domain. */
public static final String HCS_DOMAIN = "High-Content Screening (HCS)";
/** Identifies the light microscopy domain. */
public static final String LM_DOMAIN = "Light Microscopy";
/** Identifies the electron microscopy domain. */
public static final String EM_DOMAIN = "Electron Microscopy (EM)";
/** Identifies the scanning probe microscopy domain. */
public static final String SPM_DOMAIN = "Scanning Probe Microscopy (SPM)";
/** Identifies the scanning electron microscopy domain. */
public static final String SEM_DOMAIN = "Scanning Electron Microscopy (SEM)";
/** Identifies the fluorescence-lifetime domain. */
public static final String FLIM_DOMAIN = "Fluorescence-Lifetime Imaging";
/** Identifies the medical imaging domain. */
public static final String MEDICAL_DOMAIN = "Medical Imaging";
/** Identifies the histology domain. */
public static final String HISTOLOGY_DOMAIN = "Histology";
/** Identifies the gel and blot imaging domain. */
public static final String GEL_DOMAIN = "Gel/Blot Imaging";
/** Identifies the astronomy domain. */
public static final String ASTRONOMY_DOMAIN = "Astronomy";
/**
* Identifies the graphics domain. This includes formats used exclusively by
* analysis software.
*/
public static final String GRAPHICS_DOMAIN = "Graphics";
/** Identifies an unknown domain. */
public static final String UNKNOWN_DOMAIN = "Unknown";
/** List of non-graphics domains. */
public static final String[] NON_GRAPHICS_DOMAINS =
new String[] { LM_DOMAIN, EM_DOMAIN, SPM_DOMAIN, SEM_DOMAIN, FLIM_DOMAIN,
MEDICAL_DOMAIN, HISTOLOGY_DOMAIN, GEL_DOMAIN, ASTRONOMY_DOMAIN,
HCS_DOMAIN, UNKNOWN_DOMAIN };
/** List of non-HCS domains. */
public static final String[] NON_HCS_DOMAINS = new String[] { LM_DOMAIN,
EM_DOMAIN, SPM_DOMAIN, SEM_DOMAIN, FLIM_DOMAIN, MEDICAL_DOMAIN,
HISTOLOGY_DOMAIN, GEL_DOMAIN, ASTRONOMY_DOMAIN, UNKNOWN_DOMAIN };
/**
* List of domains that do not require special handling. Domains that require
* special handling are {@link #GRAPHICS_DOMAIN} and {@link #HCS_DOMAIN}.
*/
public static final String[] NON_SPECIAL_DOMAINS = new String[] { LM_DOMAIN,
EM_DOMAIN, SPM_DOMAIN, SEM_DOMAIN, FLIM_DOMAIN, MEDICAL_DOMAIN,
HISTOLOGY_DOMAIN, GEL_DOMAIN, ASTRONOMY_DOMAIN, UNKNOWN_DOMAIN };
/** List of all supported domains. */
public static final String[] ALL_DOMAINS = new String[] { HCS_DOMAIN,
LM_DOMAIN, EM_DOMAIN, SPM_DOMAIN, SEM_DOMAIN, FLIM_DOMAIN, MEDICAL_DOMAIN,
HISTOLOGY_DOMAIN, GEL_DOMAIN, ASTRONOMY_DOMAIN, GRAPHICS_DOMAIN,
UNKNOWN_DOMAIN };
// -- Constructor --
private FormatTools() {
// NB: Prevent instantiation of utility class.
}
// Utility methods -- dimensional positions --
/**
* Wraps the provided AxisType in a CalibratedAxis with calibration = 1.0um.
*/
public static CalibratedAxis createAxis(final AxisType axisType) {
return new DefaultLinearAxis(axisType, "um");
}
/**
* Creates an array, wrapping all provided AxisTypes as CalibratedAxis with
* calibration = 1.0um.
*/
public static CalibratedAxis[] createAxes(final AxisType... axisTypes) {
final CalibratedAxis[] axes = new CalibratedAxis[axisTypes.length];
for (int i = 0; i < axisTypes.length; i++) {
axes[i] = createAxis(axisTypes[i]);
}
return axes;
}
/**
* Applies the given scale value, and an origin of 0.0, to each
* {@link LinearAxis} in the provided Metadata.
*/
public static void calibrate(final Metadata m, final int imageIndex,
final double[] scale)
{
calibrate(m, imageIndex, scale, new double[scale.length]);
}
/**
* Applies the given scale and origin values to each {@link LinearAxis} in the
* provided Metadata.
*/
public static void calibrate(final Metadata m, final int imageIndex,
final double[] scale, final double[] origin)
{
int i = 0;
for (final CalibratedAxis axis : m.get(imageIndex).getAxes()) {
if (i >= scale.length || i >= origin.length) continue;
calibrate(axis, scale[i], origin[i]);
i++;
}
}
/**
* Applies the given scale and origin to the provided CalibratedAxis, if it is
* a {@link LinearAxis}.
*/
public static void calibrate(final CalibratedAxis axis, final double scale,
final double origin)
{
if (axis instanceof LinearAxis) {
((LinearAxis) axis).setScale(scale);
((LinearAxis) axis).setOrigin(origin);
}
}
/**
* Gets the average scale over the specified axis of the given image metadata.
*
* @return the average scale over the axis's values, or 1.0 if the desired
* axis is null.
*/
public static double getScale(final Metadata m, final int imageIndex,
final AxisType axisType)
{
final CalibratedAxis axis = m.get(imageIndex).getAxis(axisType);
if (axis == null) return 1.0;
final long axisLength = m.get(imageIndex).getAxisLength(axis);
return axis.averageScale(0, axisLength - 1);
}
/**
* Computes a unique N-D position corresponding to the given rasterized index
* value.
*
* @param imageIndex image index within dataset
* @param planeIndex rasterized plane index to convert to axis indices
* @param reader reader used to open the dataset
* @return position along each dimensional axis
*/
public static long[] rasterToPosition(final int imageIndex,
final long planeIndex, final Reader reader)
{
return rasterToPosition(imageIndex, planeIndex, reader.getMetadata());
}
/**
* Computes a unique N-D position corresponding to the given rasterized index
* value.
*
* @param imageIndex image index within dataset
* @param planeIndex rasterized plane index to convert to axis indices
* @param m metadata describing the dataset
* @return position along each dimensional axis
*/
public static long[] rasterToPosition(final int imageIndex,
final long planeIndex, final Metadata m)
{
final long[] axisLengths = m.get(imageIndex).getAxesLengthsNonPlanar();
return rasterToPosition(axisLengths, planeIndex);
}
/**
* Computes a unique N-D position corresponding to the given rasterized index
* value.
*
* @param lengths the maximum value at each positional dimension
* @param raster rasterized index value
* @return position along each dimensional axis
*/
public static long[]
rasterToPosition(final long[] lengths, final long raster)
{
return rasterToPosition(lengths, raster, new long[lengths.length]);
}
/**
* Computes a unique N-D position corresponding to the given rasterized index
* value.
*
* @param lengths the maximum value at each positional dimension
* @param raster rasterized index value
* @param pos preallocated position array to populate with the result
* @return position along each dimensional axis
*/
public static long[] rasterToPosition(final long[] lengths, long raster,
final long[] pos)
{
long offset = 1;
for (int i = 0; i < pos.length; i++) {
final long offset1 = offset * lengths[i];
final long q = i < pos.length - 1 ? raster % offset1 : raster;
pos[i] = q / offset;
raster -= q;
offset = offset1;
}
return pos;
}
/**
* Computes the next plane index for a given position, using the current min
* and max planar values. Also updates the position array appropriately.
*
* @param imageIndex image index within dataset
* @param r reader used to open the dataset
* @param pos current position in each dimension
* @param offsets offsets in each dimension (potentially cropped)
* @param cropLengths effective lengths in each dimension (potentially
* cropped)
* @return the next plane index, or -1 if the position extends beyond the
* given min/max
*/
public static long nextPlaneIndex(int imageIndex, Reader r, long[] pos,
long[] offsets, long[] cropLengths)
{
return nextPlaneIndex(imageIndex, r.getMetadata(), pos, offsets,
cropLengths);
}
/**
* Computes the next plane index for a given position, using the current min
* and max planar values. Also updates the position array appropriately.
*
* @param imageIndex image index within dataset
* @param m metadata describing the dataset
* @param pos current position in each dimension
* @param offsets offsets in each dimension (potentially cropped)
* @param cropLengths effective lengths in each dimension (potentially
* cropped)
* @return the next plane index, or -1 if the position extends beyond the
* given min/max
*/
public static long nextPlaneIndex(int imageIndex, Metadata m, long[] pos,
long[] offsets, long[] cropLengths)
{
return nextPlaneIndex(m.get(imageIndex).getAxesLengthsNonPlanar(), pos,
offsets, cropLengths);
}
/**
* Computes the next plane index for a given position, using the current min
* and max planar values. Also updates the position array appropriately.
*
* @param lengths actual dimension lengths
* @param pos current position in each dimension
* @param offsets offsets in each dimension (potentially cropped)
* @param cropLengths effective lengths in each dimension (potentially
* cropped)
* @return the next plane index, or -1 if the position extends beyond the
* given min/max
*/
public static long nextPlaneIndex(long[] lengths, long[] pos, long[] offsets,
long[] cropLengths)
{
boolean updated = false;
// loop over each index of the position to see if we can update it
for (int i = 0; i < pos.length && !updated; i++) {
if (pos[i] < offsets[i]) break;
// Check if the next index is valid for this position
if (pos[i] + 1 < offsets[i] + cropLengths[i]) {
// if so, make the update
pos[i]++;
updated = true;
}
else {
// if not, reset this position and try to update the next position
pos[i] = offsets[i];
}
}
if (updated) {
// Next position is valid. Return its raster
return FormatTools.positionToRaster(lengths, pos);
}
// Next position is not valid
return -1;
}
/**
* Computes a unique 1-D index corresponding to the given multidimensional
* position.
*
* @param imageIndex image index within dataset
* @param reader reader used to open the dataset
* @param planeIndices position along each dimensional axis
* @return rasterized index value
*/
public static long positionToRaster(final int imageIndex,
final Reader reader, final long[] planeIndices)
{
return positionToRaster(imageIndex, reader.getMetadata(), planeIndices);
}
/**
* Computes a unique 1-D index corresponding to the given multidimensional
* position.
*
* @param imageIndex image index within dataset
* @param m metadata describing the dataset
* @param planeIndices position along each dimensional axis
* @return rasterized index value
*/
public static long positionToRaster(final int imageIndex, final Metadata m,
final long[] planeIndices)
{
final long[] planeSizes = m.get(imageIndex).getAxesLengthsNonPlanar();
return positionToRaster(planeSizes, planeIndices);
}
/**
* Computes a unique 1-D index corresponding to the given multidimensional
* position.
*
* @param lengths the maximum value for each positional dimension
* @param pos position along each dimensional axis
* @return rasterized index value
*/
public static long positionToRaster(final long[] lengths, final long[] pos) {
long offset = 1;
long raster = 0l;
for (int i = 0; i < pos.length; i++) {
raster += offset * pos[i];
offset *= lengths[i];
}
return raster;
}
/**
* Computes the number of raster values for a positional array with the given
* lengths.
*/
public static long getRasterLength(final long[] lengths) {
long len = 1;
for (int i = 0; i < lengths.length; i++)
len *= lengths[i];
return len;
}
// -- Utility methods - sanity checking
public static void assertId(final Object id, final boolean notNull,
final int depth)
{
String msg = null;
if (id == null && notNull) {
msg = "Current file should not be null; call setId(String) first";
}
else if (id != null && !notNull) {
msg =
"Current file should be null, but is '" + id + "'; call close() first";
}
if (msg == null) return;
final StackTraceElement[] ste = new Exception().getStackTrace();
String header;
if (depth > 0 && ste.length > depth) {
String c = ste[depth].getClassName();
if (c.startsWith("io.scif.")) {
c = c.substring(c.lastIndexOf(".") + 1);
}
header = c + "." + ste[depth].getMethodName() + ": ";
}
else header = "";
throw new IllegalStateException(header + msg);
}
public static void assertStream(final RandomAccessInputStream stream,
final boolean notNull, final int depth)
{
String msg = null;
if (stream == null && notNull) {
msg = "Current file should not be null; call setId(String) first";
}
else if (stream != null && !notNull) {
msg =
"Current file should be null, but is '" + stream +
"'; call close() first";
}
if (msg == null) return;
final StackTraceElement[] ste = new Exception().getStackTrace();
String header;
if (depth > 0 && ste.length > depth) {
String c = ste[depth].getClassName();
if (c.startsWith("io.scif.")) {
c = c.substring(c.lastIndexOf(".") + 1);
}
header = c + "." + ste[depth].getMethodName() + ": ";
}
else header = "";
throw new IllegalStateException(header + msg);
}
/**
* As {@link #checkPlaneForWriting} but also asserts that the Metadata has a
* non-null source attached. If no exception is throwin, these parameters are
* suitable for reading.
*/
public static void checkPlaneForReading(final Metadata m,
final int imageIndex, final long planeIndex, final int bufLength,
final long[] planeMin, final long[] planeMax) throws FormatException
{
assertId(m.getSource(), true, 2);
checkPlaneForWriting(m, imageIndex, planeIndex, bufLength, planeMin,
planeMax);
}
/**
* Convenience method for checking that the plane number, tile size and buffer
* sizes are all valid for the given Metadata. If 'bufLength' is less than 0,
* then the buffer length check is not performed. If no exception is thrown,
* these parameters are suitable for writing.
*/
public static void checkPlaneForWriting(final Metadata m,
final int imageIndex, final long planeIndex, final int bufLength,
final long[] planeMin, final long[] planeMax) throws FormatException
{
checkPlaneNumber(m, imageIndex, planeIndex);
checkTileSize(m, planeMin, planeMax, imageIndex);
if (bufLength >= 0) checkBufferSize(m, bufLength, planeMax, imageIndex);
}
/** Checks that the given plane number is valid for the given reader. */
public static void checkPlaneNumber(final Metadata m, final int imageIndex,
final long planeIndex) throws FormatException
{
final long imageCount = m.get(imageIndex).getPlaneCount();
if (planeIndex < 0 || planeIndex >= imageCount) {
throw new FormatException("Invalid plane number: " + planeIndex + " (" +
/* TODO series=" +
r.getMetadata().getSeries() + ", */"planeCount=" + planeIndex + ")");
}
}
/** Checks that the given tile size is valid for the given reader. */
public static void checkTileSize(final Metadata m, final long[] planeMin,
final long[] planeMax, final int imageIndex) throws FormatException
{
List<CalibratedAxis> axes = m.get(imageIndex).getAxesPlanar();
for (int i = 0; i < axes.size(); i++) {
final long start = planeMin[i];
final long end = planeMax[i];
final long length = m.get(imageIndex).getAxisLength(axes.get(i));
if (start < 0 || end < 0 || (start + end) > length) throw new FormatException(
"Invalid planar size: start=" + start + ", end=" + end +
", length in metadata=" + length);
}
}
/**
* Checks that the given buffer length is long enough to hold planes of the
* specified image index, using the provided Reader.
*/
public static void checkBufferSize(final int imageIndex, final Metadata m,
final int len) throws FormatException
{
checkBufferSize(m, len, m.get(imageIndex).getAxesLengthsPlanar(),
imageIndex);
}
/**
* Checks that the given buffer size is large enough to hold an image with the
* given planar lengths.
*
* @throws FormatException if the buffer is too small
*/
public static void checkBufferSize(final Metadata m, final int len,
final long[] planeLengths, final int imageIndex) throws FormatException
{
final long size =
getPlaneSize(m, new long[planeLengths.length], planeLengths, imageIndex);
if (size > len) {
throw new FormatException("Buffer too small (got " + len + ", expected " +
size + ").");
}
}
/**
* Returns true if the given RandomAccessInputStream conatins at least 'len'
* bytes.
*/
public static boolean validStream(final RandomAccessInputStream stream,
final int len, final boolean littleEndian) throws IOException
{
stream.seek(0);
stream.order(littleEndian);
return stream.length() >= len;
}
/** Returns the size in bytes of a single plane read by the given Reader. */
public static long getPlaneSize(final Reader r, final int imageIndex) {
return getPlaneSize(r.getMetadata(), imageIndex);
}
/** Returns the size in bytes of a tile defined by the given Metadata. */
public static long getPlaneSize(final Metadata m, final int imageIndex) {
return m.get(imageIndex).getPlaneSize();
}
/** Returns the size in bytes of a w * h tile. */
public static long getPlaneSize(final Metadata m, final int width,
final int height, int imageIndex)
{
ImageMetadata iMeta = m.get(imageIndex);
long[] planeMin = new long[iMeta.getPlanarAxisCount()];
long[] planeMax = new long[iMeta.getPlanarAxisCount()];
for (int i = 0; i < planeMax.length; i++) {
AxisType type = iMeta.getAxis(i).type();
if (type == Axes.X) {
planeMax[i] = width;
}
else if (type == Axes.Y) {
planeMax[i] = height;
}
else {
planeMax[i] = iMeta.getAxisLength(type);
}
}
return getPlaneSize(m, planeMin, planeMax, imageIndex);
}
/** Returns the size in bytes of a plane with the given minima and maxima. */
public static long getPlaneSize(final Metadata m, final long[] planeMin,
final long[] planeMax, final int imageIndex)
{
if (planeMin.length != planeMax.length) throw new IllegalArgumentException(
"Plane min array size: " + planeMin.length +
" does not match plane max array size: " + planeMax.length);
long length = m.get(imageIndex).getBitsPerPixel() / 8;
for (int i = 0; i < planeMin.length; i++) {
length *= planeMax[i] - planeMin[i];
}
return length;
}
// -- Utility methods - pixel types --
/**
* Takes a string value and maps it to one of the pixel type enumerations.
*
* @param pixelTypeAsString the pixel type as a string.
* @return type enumeration value for use with class constants.
*/
public static int pixelTypeFromString(final String pixelTypeAsString) {
final String lowercaseTypeAsString = pixelTypeAsString.toLowerCase();
for (int i = 0; i < pixelTypes.length; i++) {
if (pixelTypes[i].equals(lowercaseTypeAsString)) return i;
}
throw new IllegalArgumentException("Unknown type: '" + pixelTypeAsString +
"'");
}
/**
* Takes a pixel type value and gets a corresponding string representation.
*
* @param pixelType the pixel type.
* @return string value for human-readable output.
*/
public static String getPixelTypeString(final int pixelType) {
if (pixelType < 0 || pixelType >= pixelTypes.length) {
throw new IllegalArgumentException("Unknown pixel type: " + pixelType);
}
return pixelTypes[pixelType];
}
/**
* Retrieves how many bytes per pixel the current plane or section has.
*
* @param pixelType the pixel type as retrieved from
* @return the number of bytes per pixel.
* @see io.scif.ImageMetadata#getPixelType()
*/
public static int getBytesPerPixel(final int pixelType) {
switch (pixelType) {
case INT8:
case UINT8:
return 1;
case INT16:
case UINT16:
return 2;
case INT32:
case UINT32:
case FLOAT:
return 4;
case DOUBLE:
return 8;
}
throw new IllegalArgumentException("Unknown pixel type: " + pixelType);
}
/**
* Retrieves how many bytes per pixel the current plane or section has.
*
* @param pixelType the pixel type as retrieved from
* {@link io.scif.ImageMetadata#getPixelType()}.
* @return the number of bytes per pixel.
* @see io.scif.ImageMetadata#getPixelType()
*/
public static int getBitsPerPixel(final int pixelType) {
return 8 * FormatTools.getBytesPerPixel(pixelType);
}
/**
* Retrieves the number of bytes per pixel in the current plane.
*
* @param pixelType the pixel type, as a String.
* @return the number of bytes per pixel.
* @see #pixelTypeFromString(String)
* @see #getBytesPerPixel(int)
*/
public static int getBytesPerPixel(final String pixelType) {
return getBytesPerPixel(pixelTypeFromString(pixelType));
}
/**
* Determines whether the given pixel type is floating point or integer.
*
* @param pixelType the pixel type as retrieved from
* {@link io.scif.ImageMetadata#getPixelType()}.
* @return true if the pixel type is floating point.
* @see io.scif.ImageMetadata#getPixelType()
*/
public static boolean isFloatingPoint(final int pixelType) {
switch (pixelType) {
case INT8:
case UINT8:
case INT16:
case UINT16:
case INT32:
case UINT32:
return false;
case FLOAT:
case DOUBLE:
return true;
}
throw new IllegalArgumentException("Unknown pixel type: " + pixelType);
}
/**
* Determines whether the given pixel type is signed or unsigned.
*
* @param pixelType the pixel type as retrieved from
* {@link io.scif.ImageMetadata#getPixelType()}.
* @return true if the pixel type is signed.
* @see io.scif.ImageMetadata#getPixelType()
*/
public static boolean isSigned(final int pixelType) {
switch (pixelType) {
case INT8:
case INT16:
case INT32:
case FLOAT:
case DOUBLE:
return true;
case UINT8:
case UINT16:
case UINT32:
return false;
}
throw new IllegalArgumentException("Unknown pixel type: " + pixelType);
}
/**
* Returns an appropriate pixel type given the number of bytes per pixel.
*
* @param bytes number of bytes per pixel.
* @param signed whether or not the pixel type should be signed.
* @param fp whether or not these are floating point pixels.
*/
public static int pixelTypeFromBytes(final int bytes, final boolean signed,
final boolean fp) throws FormatException
{
switch (bytes) {
case 1:
return signed ? INT8 : UINT8;
case 2:
return signed ? INT16 : UINT16;
case 4:
return fp ? FLOAT : signed ? INT32 : UINT32;
case 8:
return DOUBLE;
default:
throw new FormatException("Unsupported byte depth: " + bytes);
}
}
// -- Utility methods -- export
/**
* @throws FormatException Never actually thrown.
* @throws IOException Never actually thrown.
*/
public static String getFilename(final int imageIndex, final int image,
final Reader r, final String pattern) throws FormatException, IOException
{
String filename =
pattern.replaceAll(SERIES_NUM, String.valueOf(imageIndex));
String imageName = r.getCurrentFile();
if (imageName == null) imageName = "Image#" + imageIndex;
imageName = imageName.replaceAll("/", "_");
imageName = imageName.replaceAll("\\\\", "_");
filename = filename.replaceAll(SERIES_NAME, imageName);
final long[] coordinates =
FormatTools.rasterToPosition(imageIndex, image, r);
filename = filename.replaceAll(Z_NUM, String.valueOf(coordinates[0]));
filename = filename.replaceAll(T_NUM, String.valueOf(coordinates[2]));
filename = filename.replaceAll(CHANNEL_NUM, String.valueOf(coordinates[1]));
String channelName = String.valueOf(coordinates[1]);
channelName = channelName.replaceAll("/", "_");
channelName = channelName.replaceAll("\\\\", "_");
filename = filename.replaceAll(CHANNEL_NAME, channelName);
/*
//TODO check for date
String date = retrieve.getImageAcquisitionDate(imageIndex).getValue();
long stamp = 0;
if (retrieve.getPlaneCount(imageIndex) > image) {
Double deltaT = retrieve.getPlaneDeltaT(imageIndex, image);
if (deltaT != null) {
stamp = (long) (deltaT * 1000);
}
}
stamp += DateTools.getTime(date, DateTools.ISO8601_FORMAT);
date = DateTools.convertDate(stamp, (int) DateTools.UNIX_EPOCH);
filename = filename.replaceAll(TIMESTAMP, date);
*/
return filename;
}
/**
* @throws FormatException
* @throws IOException
*/
public static String[] getFilenames(final String pattern, final Reader r)
throws FormatException, IOException
{
final Vector<String> filenames = new Vector<String>();
String filename = null;
for (int series = 0; series < r.getImageCount(); series++) {
for (int image = 0; image < r.getImageCount(); image++) {
filename = getFilename(series, image, r, pattern);
if (!filenames.contains(filename)) filenames.add(filename);
}
}
return filenames.toArray(new String[0]);
}
/**
* @throws FormatException
* @throws IOException
*/
public static int getImagesPerFile(final String pattern, final Reader r)
throws FormatException, IOException
{
final String[] filenames = getFilenames(pattern, r);
int totalPlanes = 0;
for (int series = 0; series < r.getImageCount(); series++) {
totalPlanes += r.getMetadata().get(series).getPlaneCount();
}
return totalPlanes / filenames.length;
}
// -- Utility methods -- other
/**
* Default implementation for {@link Reader#openThumbPlane(int, long)}. At the
* moment, it uses {@link java.awt.image.BufferedImage} objects to resize
* thumbnails, so it is not safe for use in headless contexts. In the future,
* we may reimplement the image scaling logic purely with byte arrays, but
* handling every case would be substantial effort, so doing so is currently a
* low priority item.
*/
public static byte[] openThumbBytes(final Reader reader,
final int imageIndex, final long planeIndex) throws FormatException,
IOException
{
// NB: Dependency on AWT here is unfortunate, but very difficult to
// eliminate in general. We use reflection to limit class loading
// problems with AWT on Mac OS X.
final ReflectedUniverse r = new ReflectedUniverse(reader.log());
byte[][] bytes = null;
try {
r.exec("import io.scif.gui.AWTImageTools");
final long planeSize = getPlaneSize(reader, imageIndex);
Plane plane = null;
if (planeSize < 0) {
final Metadata m = reader.getMetadata();
final long[] planeMax = m.get(imageIndex).getAxesLengthsPlanar();
final long[] planeMin = new long[planeMax.length];
final int xIndex = m.get(imageIndex).getAxisIndex(Axes.X);
final int yIndex = m.get(imageIndex).getAxisIndex(Axes.Y);
final long width = m.get(imageIndex).getThumbSizeX() * 4;
final long height = m.get(imageIndex).getThumbSizeY() * 4;
planeMin[xIndex] =
(m.get(imageIndex).getAxisLength(Axes.X) - width) / 2;
planeMin[yIndex] =
(m.get(imageIndex).getAxisLength(Axes.Y) - height) / 2;
planeMax[xIndex] = width;
planeMax[yIndex] = height;
plane = reader.openPlane(imageIndex, planeIndex, planeMin, planeMax);
}
else {
plane = reader.openPlane(imageIndex, planeIndex);
}
r.setVar("plane", plane);
r.setVar("reader", reader);
r.setVar("sizeX", reader.getMetadata().get(imageIndex).getAxisLength(
Axes.X));
r.setVar("sizeY", reader.getMetadata().get(imageIndex).getAxisLength(
Axes.Y));
r.setVar("thumbSizeX", reader.getMetadata().get(imageIndex)
.getThumbSizeX());
r.setVar("thumbSizeY", reader.getMetadata().get(imageIndex)
.getThumbSizeY());
r.setVar("little", reader.getMetadata().get(imageIndex).isLittleEndian());
r.setVar("imageIndex", imageIndex);
r.exec("thumb = AWTImageTools.openThumbImage(plane, reader, imageIndex, sizeX, sizeY,"
+ " thumbSizeX, thumbSizeY, false)");
bytes = (byte[][]) r.exec("AWTImageTools.getPixelBytes(thumb, little)");
}
catch (final ReflectException exc) {
throw new FormatException(exc);
}
if (bytes.length == 1) return bytes[0];
final long rgbChannelCount =
reader.getMetadata().get(imageIndex).getAxisLength(Axes.CHANNEL);
final byte[] rtn = new byte[(int) rgbChannelCount * bytes[0].length];
if (!(reader.getMetadata().get(imageIndex).getInterleavedAxisCount() > 0)) {
for (int i = 0; i < rgbChannelCount; i++) {
System
.arraycopy(bytes[i], 0, rtn, bytes[0].length * i, bytes[i].length);
}
}
else {
final int bpp =
FormatTools.getBytesPerPixel(reader.getMetadata().get(imageIndex)
.getPixelType());
for (int i = 0; i < bytes[0].length / bpp; i += bpp) {
for (int j = 0; j < rgbChannelCount; j++) {
System.arraycopy(bytes[j], i, rtn, (int) (i * rgbChannelCount) + j *
bpp, bpp);
}
}
}
return rtn;
}
// -- Conversion convenience methods --
/**
* Convenience method for writing all of the images and metadata obtained from
* the specified Reader into the specified Writer.
*
* @param input the pre-initialized Reader used for reading data.
* @param output the uninitialized Writer used for writing data.
* @param outputFile the full path name of the output file to be created.
* @throws FormatException if there is a general problem reading from or
* writing to one of the files.
* @throws IOException if there is an I/O-related error.
*/
public static void convert(final Reader input, final Writer output,
final String outputFile) throws FormatException, IOException
{
Plane p = null;
for (int i = 0; i < input.getImageCount(); i++) {
for (int j = 0; j < input.getPlaneCount(i); j++) {
p = input.openPlane(i, j);
output.savePlane(i, j, p);
}
}
input.close();
output.close();
}
public static long[] defaultMinMax(final int pixelType) {
long min = 0, max = 0;
switch (pixelType) {
case INT8:
min = Byte.MIN_VALUE;
max = Byte.MAX_VALUE;
break;
case INT16:
min = Short.MIN_VALUE;
max = Short.MAX_VALUE;
break;
case INT32:
case FLOAT:
case DOUBLE:
min = Integer.MIN_VALUE;
max = Integer.MAX_VALUE;
break;
case UINT8:
min = 0;
max = (long) Math.pow(2, 8) - 1;
break;
case UINT16:
min = 0;
max = (long) Math.pow(2, 16) - 1;
break;
case UINT32:
min = 0;
max = (long) Math.pow(2, 32) - 1;
break;
default:
throw new IllegalArgumentException("Invalid pixel type");
}
final long[] values = { min, max };
return values;
}
/** Performs suffix matching for the given filename. */
public static boolean checkSuffix(final String name, final String suffix) {
return checkSuffix(name, new String[] { suffix });
}
/** Performs suffix matching for the given filename. */
public static boolean
checkSuffix(final String name, final String[] suffixList)
{
final String lname = name.toLowerCase();
for (int i = 0; i < suffixList.length; i++) {
final String s = "." + suffixList[i];
if (lname.endsWith(s)) return true;
for (int j = 0; j < COMPRESSION_SUFFIXES.length; j++) {
if (lname.endsWith(s + "." + COMPRESSION_SUFFIXES[j])) return true;
}
}
return false;
}
}
|
package custom.mondrian.xmla.handler;
import mondrian.olap.*;
import mondrian.util.Composite;
import org.olap4j.OlapConnection;
import org.olap4j.OlapException;
import org.olap4j.impl.ArrayNamedListImpl;
import org.olap4j.impl.Olap4jUtil;
import org.olap4j.mdx.IdentifierNode;
import org.olap4j.mdx.IdentifierSegment;
import org.olap4j.mdx.ParseTreeNode;
import org.olap4j.mdx.ParseTreeWriter;
import org.olap4j.metadata.*;
import org.olap4j.metadata.Cube;
import org.olap4j.metadata.Dimension;
import org.olap4j.metadata.Hierarchy;
import org.olap4j.metadata.Level;
import org.olap4j.metadata.Member;
import org.olap4j.metadata.Member.TreeOp;
import org.olap4j.metadata.NamedSet;
import org.olap4j.metadata.Property;
import org.olap4j.metadata.Schema;
import org.olap4j.metadata.XmlaConstants;
import custom.mondrian.xmla.exception.XmlaException;
import custom.mondrian.xmla.request.XmlaRequest;
import custom.mondrian.xmla.response.XmlaResponse;
import custom.mondrian.xmla.writer.SaxWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.*;
import java.sql.SQLException;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;
import static mondrian.olap.Util.filter;
import static custom.mondrian.xmla.handler.XmlaConstants.*;
import static custom.mondrian.xmla.handler.CustomXmlaHandler.getExtra;
/**
* <code>RowsetDefinition</code> defines a rowset, including the columns it
* should contain.
*
* <p>
* See "XML for Analysis Rowsets", page 38 of the XML for Analysis
* Specification, version 1.1.
*
* @author jhyde
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public enum RowsetDefinition {
DISCOVER_DATASOURCES(0, "Returns a list of XML for Analysis data sources available on the " + "server or Web Service.", new Column[] { DiscoverDatasourcesRowset.DataSourceName,
DiscoverDatasourcesRowset.DataSourceDescription, DiscoverDatasourcesRowset.URL, DiscoverDatasourcesRowset.DataSourceInfo, DiscoverDatasourcesRowset.ProviderName,
DiscoverDatasourcesRowset.ProviderType, DiscoverDatasourcesRowset.AuthenticationMode, },
// XMLA does not specify a sort order, but olap4j does.
new Column[] { DiscoverDatasourcesRowset.DataSourceName, }) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new DiscoverDatasourcesRowset(request, handler);
}
},
/**
* Note that SQL Server also returns the data-mining columns.
*
*
* restrictions
*
* Not supported
*/
DISCOVER_SCHEMA_ROWSETS(2, "Returns the names, values, and other information of all supported " + "RequestType enumeration values.", new Column[] {
DiscoverSchemaRowsetsRowset.SchemaName, DiscoverSchemaRowsetsRowset.SchemaGuid, DiscoverSchemaRowsetsRowset.Restrictions, DiscoverSchemaRowsetsRowset.Description,
DiscoverSchemaRowsetsRowset.RestrictionsMask, }, null /* not sorted */) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new DiscoverSchemaRowsetsRowset(request, handler);
}
protected void writeRowsetXmlSchemaRowDef(SaxWriter writer) {
writer.startElement("xsd:complexType", "name", "row");
writer.startElement("xsd:sequence");
for (Column column : columnDefinitions) {
final String name = XmlaUtil.ElementNameEncoder.INSTANCE.encode(column.name);
if (column == DiscoverSchemaRowsetsRowset.Restrictions) {
writer.startElement("xsd:element", "sql:field", column.name, "name", name, "minOccurs", 0, "maxOccurs", "unbounded");
writer.startElement("xsd:complexType");
writer.startElement("xsd:sequence");
writer.element("xsd:element", "name", "Name", "type", "xsd:string", "sql:field", "Name");
writer.element("xsd:element", "name", "Type", "type", "xsd:string", "sql:field", "Type");
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
writer.endElement(); // xsd:element
} else {
final String xsdType = column.type.columnType;
Object[] attrs;
if (column.nullable) {
if (column.unbounded) {
attrs = new Object[] { "sql:field", column.name, "name", name, "type", xsdType, "minOccurs", 0, "maxOccurs", "unbounded" };
} else {
attrs = new Object[] { "sql:field", column.name, "name", name, "type", xsdType, "minOccurs", 0 };
}
} else {
if (column.unbounded) {
attrs = new Object[] { "sql:field", column.name, "name", name, "type", xsdType, "maxOccurs", "unbounded" };
} else {
attrs = new Object[] { "sql:field", column.name, "name", name, "type", xsdType };
}
}
writer.element("xsd:element", attrs);
}
}
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
}
},
/**
*
*
*
* restrictions
*
* Not supported
*/
DISCOVER_PROPERTIES(1, "Returns a list of information and values about the requested " + "properties that are supported by the specified data source " + "provider.",
new Column[] { DiscoverPropertiesRowset.PropertyName, DiscoverPropertiesRowset.PropertyDescription, DiscoverPropertiesRowset.PropertyType,
DiscoverPropertiesRowset.PropertyAccessType, DiscoverPropertiesRowset.IsRequired, DiscoverPropertiesRowset.Value, }, null /*
* not
* sorted
*/) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new DiscoverPropertiesRowset(request, handler);
}
},
/**
*
*
*
* restrictions
*
* Not supported
*/
DISCOVER_LITERALS(5, "Returns information about literals supported by the provider.", new Column[] { DiscoverLiteralsRowset.LiteralName, DiscoverLiteralsRowset.LiteralValue,
DiscoverLiteralsRowset.LiteralInvalidChars, DiscoverLiteralsRowset.LiteralInvalidStartingChars, DiscoverLiteralsRowset.LiteralMaxLength,
// DiscoverLiteralsRowset.LiteralNameEnumValue, // used by SSAS 12
}, null /* not sorted */) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new DiscoverLiteralsRowset(request, handler);
}
},
/**
*
*
*
* restrictions
*
* Not supported
*/
DISCOVER_INSTANCES(15, "",
new Column[] { DiscoverInstancesRowset.InstanceName}, null /* not sorted */) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new DiscoverLiteralsRowset(request, handler);
}
},
/**
*
*
*
* restrictions
*
* Not supported
*/
DBSCHEMA_CATALOGS(6, "Identifies the physical attributes associated with catalogs " + "accessible from the provider.", new Column[] { DbschemaCatalogsRowset.CatalogName,
DbschemaCatalogsRowset.Description, DbschemaCatalogsRowset.Roles, DbschemaCatalogsRowset.DateModified, }, new Column[] { DbschemaCatalogsRowset.CatalogName, }) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new DbschemaCatalogsRowset(request, handler);
}
},
/**
*
*
*
* restrictions
*
* Not supported COLUMN_OLAP_TYPE
*/
DBSCHEMA_COLUMNS(7, null, new Column[] { DbschemaColumnsRowset.TableCatalog, DbschemaColumnsRowset.TableSchema, DbschemaColumnsRowset.TableName,
DbschemaColumnsRowset.ColumnName, DbschemaColumnsRowset.OrdinalPosition, DbschemaColumnsRowset.ColumnHasDefault, DbschemaColumnsRowset.ColumnFlags,
DbschemaColumnsRowset.IsNullable, DbschemaColumnsRowset.DataType, DbschemaColumnsRowset.CharacterMaximumLength, DbschemaColumnsRowset.CharacterOctetLength,
DbschemaColumnsRowset.NumericPrecision, DbschemaColumnsRowset.NumericScale, }, new Column[] { DbschemaColumnsRowset.TableCatalog, DbschemaColumnsRowset.TableSchema,
DbschemaColumnsRowset.TableName, }) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new DbschemaColumnsRowset(request, handler);
}
},
/**
*
*
*
* restrictions
*
* Not supported
*/
DBSCHEMA_PROVIDER_TYPES(8, null, new Column[] { DbschemaProviderTypesRowset.TypeName, DbschemaProviderTypesRowset.DataType, DbschemaProviderTypesRowset.ColumnSize,
DbschemaProviderTypesRowset.LiteralPrefix, DbschemaProviderTypesRowset.LiteralSuffix, DbschemaProviderTypesRowset.IsNullable,
DbschemaProviderTypesRowset.CaseSensitive, DbschemaProviderTypesRowset.Searchable, DbschemaProviderTypesRowset.UnsignedAttribute,
DbschemaProviderTypesRowset.FixedPrecScale, DbschemaProviderTypesRowset.AutoUniqueValue, DbschemaProviderTypesRowset.IsLong, DbschemaProviderTypesRowset.BestMatch, },
new Column[] { DbschemaProviderTypesRowset.DataType, }) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new DbschemaProviderTypesRowset(request, handler);
}
},
// DBSCHEMA_SCHEMATA(
// 8, null,
// new Column[] {
// DbschemaSchemataRowset.CatalogName,
// DbschemaSchemataRowset.SchemaName,
// DbschemaSchemataRowset.SchemaOwner,
// new Column[] {
// DbschemaSchemataRowset.CatalogName,
// DbschemaSchemataRowset.SchemaName,
// DbschemaSchemataRowset.SchemaOwner,
// public Rowset getRowset(XmlaRequest request, XmlaHandler handler) {
// return new DbschemaSchemataRowset(request, handler);
DBSCHEMA_TABLES(9, null, new Column[] { DbschemaTablesRowset.TableCatalog, DbschemaTablesRowset.TableSchema, DbschemaTablesRowset.TableName, DbschemaTablesRowset.TableType,
DbschemaTablesRowset.TableGuid, DbschemaTablesRowset.Description, DbschemaTablesRowset.TablePropId, DbschemaTablesRowset.DateCreated,
DbschemaTablesRowset.DateModified, DbschemaTablesRowset.TableOlapType, }, new Column[] { DbschemaTablesRowset.TableType, DbschemaTablesRowset.TableCatalog,
DbschemaTablesRowset.TableSchema, DbschemaTablesRowset.TableName, DbschemaTablesRowset.TableOlapType,
}) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new DbschemaTablesRowset(request, handler);
}
},
// DBSCHEMA_TABLES_INFO(
// 10, null,
// new Column[] {
// DbschemaTablesInfoRowset.TableCatalog,
// DbschemaTablesInfoRowset.TableSchema,
// DbschemaTablesInfoRowset.TableName,
// DbschemaTablesInfoRowset.TableType,
// DbschemaTablesInfoRowset.TableGuid,
// DbschemaTablesInfoRowset.Bookmarks,
// DbschemaTablesInfoRowset.BookmarkType,
// DbschemaTablesInfoRowset.BookmarkDataType,
// DbschemaTablesInfoRowset.BookmarkMaximumLength,
// DbschemaTablesInfoRowset.BookmarkInformation,
// DbschemaTablesInfoRowset.TableVersion,
// DbschemaTablesInfoRowset.Cardinality,
// DbschemaTablesInfoRowset.Description,
// DbschemaTablesInfoRowset.TablePropId,
// null /* cannot find doc -- presume unsorted */)
// public Rowset getRowset(XmlaRequest request, XmlaHandler handler) {
// return new DbschemaTablesInfoRowset(request, handler);
MDSCHEMA_ACTIONS(11, null, new Column[] { MdschemaActionsRowset.CatalogName, MdschemaActionsRowset.SchemaName, MdschemaActionsRowset.CubeName, MdschemaActionsRowset.ActionName,
MdschemaActionsRowset.ActionType, MdschemaActionsRowset.Coordinate, MdschemaActionsRowset.CoordinateType, MdschemaActionsRowset.Invocation, }, new Column[] {
// Spec says sort on CATALOG_NAME, SCHEMA_NAME, CUBE_NAME,
// ACTION_NAME.
MdschemaActionsRowset.CatalogName, MdschemaActionsRowset.SchemaName, MdschemaActionsRowset.CubeName, MdschemaActionsRowset.ActionName,
MdschemaActionsRowset.ActionType, MdschemaActionsRowset.Invocation, }) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new MdschemaActionsRowset(request, handler);
}
},
MDSCHEMA_CUBES(12, null, new Column[] { MdschemaCubesRowset.CatalogName, MdschemaCubesRowset.SchemaName, MdschemaCubesRowset.CubeName, MdschemaCubesRowset.CubeType,
MdschemaCubesRowset.CubeGuid, MdschemaCubesRowset.CreatedOn, MdschemaCubesRowset.LastSchemaUpdate, MdschemaCubesRowset.SchemaUpdatedBy,
MdschemaCubesRowset.LastDataUpdate, MdschemaCubesRowset.DataUpdatedBy, MdschemaCubesRowset.IsDrillthroughEnabled, MdschemaCubesRowset.IsWriteEnabled,
MdschemaCubesRowset.IsLinkable, MdschemaCubesRowset.IsSqlEnabled, MdschemaCubesRowset.CubeCaption, MdschemaCubesRowset.BaseCubeName, MdschemaCubesRowset.CubeSource,
MdschemaCubesRowset.PreferedQueryPatterns, MdschemaCubesRowset.Description, MdschemaCubesRowset.Dimensions, MdschemaCubesRowset.Sets, MdschemaCubesRowset.Measures },
new Column[] { MdschemaCubesRowset.CatalogName, MdschemaCubesRowset.SchemaName, MdschemaCubesRowset.CubeName, MdschemaCubesRowset.BaseCubeName,
MdschemaCubesRowset.CubeSource, MdschemaCubesRowset.PreferedQueryPatterns, }) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new MdschemaCubesRowset(request, handler);
}
},
MDSCHEMA_DIMENSIONS(13, null, new Column[] { MdschemaDimensionsRowset.CatalogName, MdschemaDimensionsRowset.SchemaName, MdschemaDimensionsRowset.CubeName,
MdschemaDimensionsRowset.DimensionName, MdschemaDimensionsRowset.DimensionUniqueName, MdschemaDimensionsRowset.DimensionGuid,
MdschemaDimensionsRowset.DimensionCaption, MdschemaDimensionsRowset.DimensionOrdinal, MdschemaDimensionsRowset.DimensionType,
MdschemaDimensionsRowset.DimensionCardinality, MdschemaDimensionsRowset.DefaultHierarchy, MdschemaDimensionsRowset.Description, MdschemaDimensionsRowset.IsVirtual,
MdschemaDimensionsRowset.IsReadWrite, MdschemaDimensionsRowset.DimensionUniqueSettings, MdschemaDimensionsRowset.DimensionMasterUniqueName,
MdschemaDimensionsRowset.DimensionVisibility, MdschemaDimensionsRowset.Hierarchies, MdschemaDimensionsRowset.CubeSource,
}, new Column[] { MdschemaDimensionsRowset.CatalogName, MdschemaDimensionsRowset.SchemaName, MdschemaDimensionsRowset.CubeName, MdschemaDimensionsRowset.DimensionName,
MdschemaDimensionsRowset.CubeSource, }) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new MdschemaDimensionsRowset(request, handler);
}
},
MDSCHEMA_FUNCTIONS(14, null, new Column[] { MdschemaFunctionsRowset.FunctionName, MdschemaFunctionsRowset.Description, MdschemaFunctionsRowset.ParameterList,
MdschemaFunctionsRowset.ReturnType, MdschemaFunctionsRowset.Origin, MdschemaFunctionsRowset.InterfaceName, MdschemaFunctionsRowset.LibraryName,
MdschemaFunctionsRowset.Caption, }, new Column[] { MdschemaFunctionsRowset.LibraryName, MdschemaFunctionsRowset.InterfaceName, MdschemaFunctionsRowset.FunctionName,
MdschemaFunctionsRowset.Origin, }) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new MdschemaFunctionsRowset(request, handler);
}
},
MDSCHEMA_HIERARCHIES(15, null, new Column[] { MdschemaHierarchiesRowset.CatalogName, MdschemaHierarchiesRowset.SchemaName, MdschemaHierarchiesRowset.CubeName,
MdschemaHierarchiesRowset.DimensionUniqueName, MdschemaHierarchiesRowset.HierarchyName, MdschemaHierarchiesRowset.HierarchyUniqueName,
MdschemaHierarchiesRowset.HierarchyGuid, MdschemaHierarchiesRowset.HierarchyCaption, MdschemaHierarchiesRowset.DimensionType,
MdschemaHierarchiesRowset.HierarchyCardinality, MdschemaHierarchiesRowset.DefaultMember, MdschemaHierarchiesRowset.AllMember, MdschemaHierarchiesRowset.Description,
MdschemaHierarchiesRowset.Structure, MdschemaHierarchiesRowset.IsVirtual, MdschemaHierarchiesRowset.IsReadWrite, MdschemaHierarchiesRowset.DimensionUniqueSettings,
MdschemaHierarchiesRowset.DimensionMasterUniqueName,
MdschemaHierarchiesRowset.DimensionIsVisible, MdschemaHierarchiesRowset.HierarchyOrdinal,
MdschemaHierarchiesRowset.DimensionIsShared, MdschemaHierarchiesRowset.HierarchyIsVisible,
MdschemaHierarchiesRowset.HierarchyVisibility,MdschemaHierarchiesRowset.CubeSource,
MdschemaHierarchiesRowset.HierarchyOrigin, MdschemaHierarchiesRowset.HierarchyDisplayFolder, MdschemaHierarchiesRowset.InstanceSelection, MdschemaHierarchiesRowset.GroupingBehaviors,
MdschemaHierarchiesRowset.StructureType, }, new Column[] { MdschemaHierarchiesRowset.CatalogName, MdschemaHierarchiesRowset.SchemaName,
MdschemaHierarchiesRowset.CubeName, MdschemaHierarchiesRowset.DimensionUniqueName, MdschemaHierarchiesRowset.HierarchyName,
MdschemaHierarchiesRowset.HierarchyVisibility,MdschemaHierarchiesRowset.CubeSource}) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new MdschemaHierarchiesRowset(request, handler);
}
},
MDSCHEMA_LEVELS(16, null, new Column[] { MdschemaLevelsRowset.CatalogName, MdschemaLevelsRowset.SchemaName, MdschemaLevelsRowset.CubeName,
MdschemaLevelsRowset.DimensionUniqueName, MdschemaLevelsRowset.HierarchyUniqueName, MdschemaLevelsRowset.LevelName, MdschemaLevelsRowset.LevelUniqueName,
MdschemaLevelsRowset.LevelGuid, MdschemaLevelsRowset.LevelCaption, MdschemaLevelsRowset.LevelNumber, MdschemaLevelsRowset.LevelCardinality,
MdschemaLevelsRowset.LevelType, MdschemaLevelsRowset.CustomRollupSettings, MdschemaLevelsRowset.LevelUniqueSettings, MdschemaLevelsRowset.LevelIsVisible,
MdschemaLevelsRowset.Description,
MdschemaLevelsRowset.LevelDbtype,
MdschemaLevelsRowset.LevelKeyCardinality,
MdschemaLevelsRowset.LevelOrigin,
MdschemaLevelsRowset.LevelNameSqlColumnName,
MdschemaLevelsRowset.LevelKeySqlColumnName,
MdschemaLevelsRowset.LevelUniqueNameSqlColumnName,
MdschemaLevelsRowset.LevelAttributeHierarchyName,
MdschemaLevelsRowset.LevelOrderingProperty
}, new Column[] { MdschemaLevelsRowset.CatalogName, MdschemaLevelsRowset.SchemaName, MdschemaLevelsRowset.CubeName, MdschemaLevelsRowset.DimensionUniqueName,
MdschemaLevelsRowset.HierarchyUniqueName, MdschemaLevelsRowset.LevelNumber,
// MdschemaLevelsRowset.LevelDbtype,
// MdschemaLevelsRowset.LevelKeyCardinality,
// MdschemaLevelsRowset.LevelOrigin,
}) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new MdschemaLevelsRowset(request, handler);
}
},
MDSCHEMA_MEASURES(17, null, new Column[] {
MdschemaMeasuresRowset.CatalogName,
MdschemaMeasuresRowset.SchemaName,
MdschemaMeasuresRowset.CubeName,
MdschemaMeasuresRowset.MeasureName,
MdschemaMeasuresRowset.MeasureUniqueName,
MdschemaMeasuresRowset.MeasureCaption,
MdschemaMeasuresRowset.MeasureGuid,
MdschemaMeasuresRowset.MeasureAggregator,
MdschemaMeasuresRowset.DataType,
MdschemaMeasuresRowset.NumericPrecision,
MdschemaMeasuresRowset.NumericScale,
MdschemaMeasuresRowset.MeasureUnits,
MdschemaMeasuresRowset.Description,
MdschemaMeasuresRowset.Expression,
MdschemaMeasuresRowset.MeasureIsVisible,
MdschemaMeasuresRowset.LevelsList,
MdschemaMeasuresRowset.MeasureNameSql,
MdschemaMeasuresRowset.MeasureUnqualifiedCaption,
MdschemaMeasuresRowset.MeasureGroupName,
MdschemaMeasuresRowset.MeasureDisplayFolder,
MdschemaMeasuresRowset.FormatString,
MdschemaMeasuresRowset.CubeSource,
MdschemaMeasuresRowset.MeasureVisibility,
},
new Column[] { MdschemaMeasuresRowset.CatalogName, MdschemaMeasuresRowset.SchemaName, MdschemaMeasuresRowset.CubeName, MdschemaMeasuresRowset.MeasureName,
MdschemaMeasuresRowset.NumericScale, MdschemaMeasuresRowset.MeasureIsVisible, MdschemaMeasuresRowset.MeasureNameSql, MdschemaMeasuresRowset.MeasureGroupName,
MdschemaMeasuresRowset.CubeSource, MdschemaMeasuresRowset.MeasureVisibility }) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new MdschemaMeasuresRowset(request, handler);
}
},
MDSCHEMA_MEMBERS(18, null, new Column[] { MdschemaMembersRowset.CatalogName, MdschemaMembersRowset.SchemaName, MdschemaMembersRowset.CubeName,
MdschemaMembersRowset.DimensionUniqueName, MdschemaMembersRowset.HierarchyUniqueName, MdschemaMembersRowset.LevelUniqueName, MdschemaMembersRowset.LevelNumber,
MdschemaMembersRowset.MemberOrdinal, MdschemaMembersRowset.MemberName, MdschemaMembersRowset.MemberUniqueName, MdschemaMembersRowset.MemberType,
MdschemaMembersRowset.MemberGuid, MdschemaMembersRowset.MemberCaption, MdschemaMembersRowset.ChildrenCardinality, MdschemaMembersRowset.ParentLevel,
MdschemaMembersRowset.ParentUniqueName, MdschemaMembersRowset.ParentCount, MdschemaMembersRowset.TreeOp_, MdschemaMembersRowset.CubeSource,
MdschemaMembersRowset.Depth, MdschemaMembersRowset.MemberKey, MdschemaMembersRowset.IsPlaceHolderMember, MdschemaMembersRowset.IsDatamember, }, new Column[] {
MdschemaMembersRowset.CatalogName, MdschemaMembersRowset.SchemaName, MdschemaMembersRowset.CubeName, MdschemaMembersRowset.DimensionUniqueName,
MdschemaMembersRowset.HierarchyUniqueName, MdschemaMembersRowset.LevelUniqueName, MdschemaMembersRowset.LevelNumber, MdschemaMembersRowset.MemberOrdinal,
MdschemaMembersRowset.IsPlaceHolderMember, MdschemaMembersRowset.IsDatamember, }) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new MdschemaMembersRowset(request, handler);
}
},
MDSCHEMA_PROPERTIES(19, null, new Column[] {
MdschemaPropertiesRowset.CatalogName,
MdschemaPropertiesRowset.SchemaName,
MdschemaPropertiesRowset.CubeName,
MdschemaPropertiesRowset.DimensionUniqueName,
MdschemaPropertiesRowset.HierarchyUniqueName,
MdschemaPropertiesRowset.LevelUniqueName,
MdschemaPropertiesRowset.MemberUniqueName,
MdschemaPropertiesRowset.PropertyName,
MdschemaPropertiesRowset.PropertyType,
MdschemaPropertiesRowset.PropertyContentType,
MdschemaPropertiesRowset.PropertyOrigin, //PROPERTY_ORIGIN
MdschemaPropertiesRowset.CubeSource,
MdschemaPropertiesRowset.PropertyVisibility,
MdschemaPropertiesRowset.PropertyIsVisible,
MdschemaPropertiesRowset.Description,
MdschemaPropertiesRowset.PropertyCaption,
MdschemaPropertiesRowset.DataType,
MdschemaPropertiesRowset.CharacterMaximumLength, //CHARACTER_MAXIMUM_LENGTH
MdschemaPropertiesRowset.CharacterOctetLength,//CHARACTER_OCTET_LENGTH
MdschemaPropertiesRowset.NumericPrecision,//NUMERIC_PRECISION
MdschemaPropertiesRowset.NumericScale,//NUMERIC_SCALE
MdschemaPropertiesRowset.SqlColumnName, //SQL_COLUMN_NAME
MdschemaPropertiesRowset.Language,
MdschemaPropertiesRowset.PropertyAttributeHierarchyName,
//MdschemaPropertiesRowset.CubeSource,
MdschemaPropertiesRowset.PropertyCardinality,
MdschemaPropertiesRowset.MimeType,
}, null /* not sorted */) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new MdschemaPropertiesRowset(request, handler);
}
},
MDSCHEMA_SETS(20, null, new Column[] {
MdschemaSetsRowset.CatalogName,
MdschemaSetsRowset.SchemaName,
MdschemaSetsRowset.CubeName,
MdschemaSetsRowset.SetName,
MdschemaSetsRowset.Scope,
MdschemaSetsRowset.Description,
MdschemaSetsRowset.Expression,
MdschemaSetsRowset.Dimensions,
MdschemaSetsRowset.SetDisplayFolder,
MdschemaSetsRowset.SetEvaluationContext},
new Column[] {
MdschemaSetsRowset.CatalogName,
MdschemaSetsRowset.SchemaName,
MdschemaSetsRowset.CubeName, }) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new MdschemaSetsRowset(request, handler);
}
},
MDSCHEMA_KPIS(20, null, new Column[] {
MdschemaKpisRowset.CatalogName,
MdschemaKpisRowset.SchemaName,
MdschemaKpisRowset.CubeName,
MdschemaKpisRowset.KpiName,
MdschemaKpisRowset.CubeSource,
MdschemaKpisRowset.Scope},
new Column[] {
MdschemaKpisRowset.CatalogName,
MdschemaKpisRowset.SchemaName,
MdschemaKpisRowset.CubeName,
MdschemaKpisRowset.KpiName,
MdschemaKpisRowset.CubeSource,
MdschemaKpisRowset.Scope }) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new MdschemaSetsRowset(request, handler);
}
},
MDSCHEMA_MEASUREGROUPS(20, null, new Column[] {
MdschemaMeasureGroupRowset.CatalogName,
MdschemaMeasureGroupRowset.SchemaName,
MdschemaMeasureGroupRowset.CubeName,
MdschemaMeasureGroupRowset.MeasureGroupName,
MdschemaMeasureGroupRowset.Description,
MdschemaMeasureGroupRowset.IsWriteEnabled,
MdschemaMeasureGroupRowset.MeasureGroupCaption},
new Column[] {
MdschemaMeasureGroupRowset.CatalogName,
MdschemaMeasureGroupRowset.SchemaName,
MdschemaMeasureGroupRowset.CubeName, }) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new MdschemaMeasureGroupRowset(request, handler);
}
},
MDSCHEMA_MEASUREGROUP_DIMENSIONS(20, null, new Column[] {
MdschemaMeasureGroupDimensionRowset.CatalogName,
MdschemaMeasureGroupDimensionRowset.SchemaName,
MdschemaMeasureGroupDimensionRowset.CubeName,
MdschemaMeasureGroupDimensionRowset.MeasureGroupName,
MdschemaMeasureGroupDimensionRowset.MeasureGroupCardinality,
MdschemaMeasureGroupDimensionRowset.DimensionUniqueName,
MdschemaMeasureGroupDimensionRowset.DimensionCardinality,
MdschemaMeasureGroupDimensionRowset.DimensionIsVisible,
MdschemaMeasureGroupDimensionRowset.DimensionISFactDimension,
MdschemaMeasureGroupDimensionRowset.DimensionPath,
MdschemaMeasureGroupDimensionRowset.DimensionGranularity,},
new Column[] {
MdschemaMeasureGroupDimensionRowset.CatalogName,
MdschemaMeasureGroupDimensionRowset.SchemaName,
MdschemaMeasureGroupDimensionRowset.CubeName,
MdschemaMeasureGroupDimensionRowset.MeasureGroupName,
MdschemaMeasureGroupDimensionRowset.MeasureGroupCardinality,
MdschemaMeasureGroupDimensionRowset.DimensionUniqueName,
MdschemaMeasureGroupDimensionRowset.DimensionCardinality,
MdschemaMeasureGroupDimensionRowset.DimensionIsVisible,
MdschemaMeasureGroupDimensionRowset.DimensionISFactDimension,
MdschemaMeasureGroupDimensionRowset.DimensionPath,
MdschemaMeasureGroupDimensionRowset.DimensionGranularity, }) {
public Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler) {
return new MdschemaMeasureGroupDimensionRowset(request, handler);
}
};
transient final Column[] columnDefinitions;
transient final Column[] sortColumnDefinitions;
/**
* Date the schema was last modified.
*
* <p>
* TODO: currently schema grammar does not support modify date so we return
* just some date for now.
*/
private static final String dateModified = "2005-01-25T17:35:32";
private final String description;
static final String UUID_PATTERN = "[0-9a-zA-Z]{8}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{4}-[0-9a-zA-Z]{12}";
/**
* Creates a rowset definition.
*
* @param ordinal
* Rowset ordinal, per OLE DB for OLAP
* @param description
* Description
* @param columnDefinitions
* List of column definitions
* @param sortColumnDefinitions
* List of column definitions to sort on,
*/
RowsetDefinition(int ordinal, String description, Column[] columnDefinitions, Column[] sortColumnDefinitions) {
Util.discard(ordinal);
this.description = description;
this.columnDefinitions = columnDefinitions;
this.sortColumnDefinitions = sortColumnDefinitions;
}
public abstract Rowset getRowset(XmlaRequest request, CustomXmlaHandler handler);
public Column lookupColumn(String name) {
for (Column columnDefinition : columnDefinitions) {
if (columnDefinition.name.equals(name)) {
return columnDefinition;
}
}
return null;
}
/**
* Returns a comparator with which to sort rows of this rowset definition.
* The sort order is defined by the {@link #sortColumnDefinitions} field. If
* the rowset is not sorted, returns null.
*/
Comparator<Rowset.Row> getComparator() {
if (sortColumnDefinitions == null) {
return null;
}
return new Comparator<Rowset.Row>() {
public int compare(Rowset.Row row1, Rowset.Row row2) {
// A faster implementation is welcome.
for (Column sortColumn : sortColumnDefinitions) {
Comparable val1 = (Comparable) row1.get(sortColumn.name);
Comparable val2 = (Comparable) row2.get(sortColumn.name);
if ((val1 == null) && (val2 == null)) {
// columns can be optional, compare next column
continue;
} else if (val1 == null) {
return -1;
} else if (val2 == null) {
return 1;
} else if (val1 instanceof String && val2 instanceof String) {
int v = ((String) val1).compareToIgnoreCase((String) val2);
// if equal (= 0), compare next column
if (v != 0) {
return v;
}
} else {
int v = val1.compareTo(val2);
// if equal (= 0), compare next column
if (v != 0) {
return v;
}
}
}
return 0;
}
};
}
/**
* Generates an XML schema description to the writer. This is broken into
* top, Row definition and bottom so that on a case by case basis a
* RowsetDefinition can redefine the Row definition output. The default
* assumes a flat set of elements, but for example, SchemaRowsets has a
* element with child elements.
*
* @param writer
* SAX writer
* @see CustomXmlaHandler#writeDatasetXmlSchema(SaxWriter,
* mondrian.xmla.XmlaHandler.SetType)
*/
void writeRowsetXmlSchema(SaxWriter writer) {
writeRowsetXmlSchemaTop(writer);
writeRowsetXmlSchemaRowDef(writer);
writeRowsetXmlSchemaBottom(writer);
}
protected void writeRowsetXmlSchemaTop(SaxWriter writer) {
writer.startElement("xsd:schema", "xmlns:sql", "urn:schemas-microsoft-com:xml-sql", "targetNamespace",
NS_XMLA_ROWSET, "elementFormDefault", "qualified");
writer.startElement("xsd:element", "name", "root");
writer.startElement("xsd:complexType");
writer.startElement("xsd:sequence","minOccurs",0,"maxOccurs","unbounded");
writer.element("xsd:element", "name", "row", "type", "row");
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
writer.endElement(); // xsd:element
// MS SQL includes this in its schema section even thought
// its not need for most queries.
writer.startElement("xsd:simpleType", "name", "uuid");
writer.startElement("xsd:restriction", "base", "xsd:string");
writer.element("xsd:pattern", "value", UUID_PATTERN);
writer.endElement(); // xsd:restriction
writer.endElement(); // xsd:simpleType
}
protected void writeRowsetXmlSchemaRowDef(SaxWriter writer) {
Map<String, Object[]> tmpMap = new HashMap<String, Object[]>();
List<Object[]> tmpList = new ArrayList<Object[]>();
for (Column column : columnDefinitions) {
final String name = XmlaUtil.ElementNameEncoder.INSTANCE.encode(column.name);
final String xsdType = column.type.columnType;
Object[] attrs;
if (column.nullable) {
if (column.unbounded) {
attrs = new Object[] { "sql:field", column.name, "name", name, "type", xsdType, "minOccurs", 0, "maxOccurs", "unbounded" };
} else {
attrs = new Object[] { "sql:field", column.name, "name", name, "type", xsdType, "minOccurs", 0 };
}
} else {
if (column.unbounded) {
attrs = new Object[] { "sql:field", column.name, "name", name, "type", xsdType, "maxOccurs", "unbounded" };
} else {
attrs = new Object[] { "sql:field", column.name, "name", name, "type", xsdType };
}
}
tmpMap.put(column.name, attrs);
tmpList.add(attrs);
}
//This's the right order of elements under complex type
final String[] nameList = {"CATALOG_NAME","SCHEMA_NAME","CUBE_NAME","DIMENSION_UNIQUE_NAME","HIERARCHY_UNIQUE_NAME","LEVEL_UNIQUE_NAME","MEMBER_UNIQUE_NAME","PROPERTY_TYPE","PROPERTY_NAME","PROPERTY_CAPTION",
"DATA_TYPE","CHARACTER_MAXIMUM_LENGTH","CHARACTER_OCTET_LENGTH","NUMERIC_PRECISION","NUMERIC_SCALE","DESCRIPTION","PROPERTY_CONTENT_TYPE","SQL_COLUMN_NAME","LANGUAGE","PROPERTY_ORIGIN","PROPERTY_ATTRIBUTE_HIERARCHY_NAME",
"PROPERTY_CARDINALITY","MIME_TYPE","PROPERTY_IS_VISIBLE"};
boolean isMdschemaProperties = false;
for(String s: nameList){
isMdschemaProperties = true;
if (!tmpMap.containsKey(s)){
isMdschemaProperties = false;
break;
}
}
writer.startElement("xsd:complexType", "name", "row");
writer.startElement("xsd:sequence");
if(isMdschemaProperties){
for(String s: nameList){
writer.element("xsd:element", (Object[])(tmpMap.get(s)));
}
}
else {
for(Object o: tmpList){
writer.element("xsd:element", (Object[])o);
}
}
writer.endElement(); // xsd:sequence
writer.endElement(); // xsd:complexType
}
protected void writeRowsetXmlSchemaBottom(SaxWriter writer) {
writer.endElement(); // xsd:schema
}
enum Type {
String("xsd:string"), StringArray("xsd:string"), Array("xsd:string"), Enumeration("xsd:string"), EnumerationArray("xsd:string"), EnumString("xsd:string"), Boolean(
"xsd:boolean"), StringSometimesArray("xsd:string"), Integer("xsd:int"), UnsignedInteger("xsd:unsignedInt"), DateTime("xsd:dateTime"), Rowset(null), Short(
"xsd:short"), UUID("uuid"), UnsignedShort("xsd:unsignedShort"), Long("xsd:long"), UnsignedLong("xsd:unsignedLong");
public final String columnType;
Type(String columnType) {
this.columnType = columnType;
}
boolean isEnum() {
return this == Enumeration || this == EnumerationArray || this == EnumString;
}
String getName() {
return this == String ? "string" : name();
}
}
private static XmlaConstants.DBType getDBTypeFromProperty(Property prop) {
switch (prop.getDatatype()) {
case STRING:
return XmlaConstants.DBType.WSTR;
case INTEGER:
case UNSIGNED_INTEGER:
case DOUBLE:
return XmlaConstants.DBType.R8;
case BOOLEAN:
return XmlaConstants.DBType.BOOL;
default:
return XmlaConstants.DBType.WSTR;
}
}
static class Column {
/**
* This is used as the true value for the restriction parameter.
*/
static final boolean RESTRICTION = true;
/**
* This is used as the false value for the restriction parameter.
*/
static final boolean NOT_RESTRICTION = false;
/**
* This is used as the false value for the nullable parameter.
*/
static final boolean REQUIRED = false;
/**
* This is used as the true value for the nullable parameter.
*/
static final boolean OPTIONAL = true;
/**
* This is used as the false value for the unbounded parameter.
*/
static final boolean ONE_MAX = false;
/**
* This is used as the true value for the unbounded parameter.
*/
static final boolean UNBOUNDED = true;
final String name;
final Type type;
final Enumeration enumeration;
final String description;
final boolean restriction;
final boolean nullable;
final boolean unbounded;
/**
* Creates a column.
*
* @param name
* Name of column
* @param type
* A {@link mondrian.xmla.RowsetDefinition.Type} value
* @param enumeratedType
* Must be specified for enumeration or array of enumerations
* @param description
* Description of column
* @param restriction
* Whether column can be used as a filter on its rowset
* @param nullable
* Whether column can contain null values
* @pre type != null
* @pre (type == Type.Enumeration || type == Type.EnumerationArray || type
* == Type.EnumString) == (enumeratedType != null)
* @pre description == null || description.indexOf('\r') == -1
*/
Column(String name, Type type, Enumeration enumeratedType, boolean restriction, boolean nullable, String description) {
this(name, type, enumeratedType, restriction, nullable, ONE_MAX, description);
}
Column(String name, Type type, Enumeration enumeratedType, boolean restriction, boolean nullable, boolean unbounded, String description) {
assert type != null;
assert (type == Type.Enumeration || type == Type.EnumerationArray || type == Type.EnumString) == (enumeratedType != null);
// Line endings must be UNIX style (LF) not Windows style (LF+CR).
// Thus the client will receive the same XML, regardless
// of the server O/S.
assert description == null || description.indexOf('\r') == -1;
this.name = name;
this.type = type;
this.enumeration = enumeratedType;
this.description = description;
this.restriction = restriction;
this.nullable = nullable;
this.unbounded = unbounded;
}
/**
* Retrieves a value of this column from a row. The base implementation
* uses reflection to call an accessor method; a derived class may provide
* a different implementation.
*
* @param row
* Row
*/
protected Object get(Object row) {
return getFromAccessor(row);
}
/**
* Retrieves the value of this column "MyColumn" from a field called
* "myColumn".
*
* @param row
* Current row
* @return Value of given this property of the given row
*/
protected final Object getFromField(Object row) {
try {
String javaFieldName = name.substring(0, 1).toLowerCase() + name.substring(1);
Field field = row.getClass().getField(javaFieldName);
return field.get(row);
} catch (NoSuchFieldException e) {
throw Util.newInternal(e, "Error while accessing rowset column " + name);
} catch (SecurityException e) {
throw Util.newInternal(e, "Error while accessing rowset column " + name);
} catch (IllegalAccessException e) {
throw Util.newInternal(e, "Error while accessing rowset column " + name);
}
}
/**
* Retrieves the value of this column "MyColumn" by calling a method
* called "getMyColumn()".
*
* @param row
* Current row
* @return Value of given this property of the given row
*/
protected final Object getFromAccessor(Object row) {
try {
String javaMethodName = "get" + name;
Method method = row.getClass().getMethod(javaMethodName);
return method.invoke(row);
} catch (SecurityException e) {
throw Util.newInternal(e, "Error while accessing rowset column " + name);
} catch (IllegalAccessException e) {
throw Util.newInternal(e, "Error while accessing rowset column " + name);
} catch (NoSuchMethodException e) {
throw Util.newInternal(e, "Error while accessing rowset column " + name);
} catch (InvocationTargetException e) {
throw Util.newInternal(e, "Error while accessing rowset column " + name);
}
}
public String getColumnType() {
if (type.isEnum()) {
return enumeration.type.columnType;
}
return type.columnType;
}
}
// From this point on, just rowset classess.
static class DiscoverSchemaRowsetsRowset extends Rowset {
private static final Column SchemaName = new Column("SchemaName", Type.StringArray, null, Column.RESTRICTION, Column.REQUIRED,
"The name of the schema/request. This returns the values in " + "the RequestTypes enumeration, plus any additional types "
+ "supported by the provider. The provider defines rowset " + "structures for the additional types");
private static final Column SchemaGuid = new Column("SchemaGuid", Type.UUID, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "The GUID of the schema.");
private static final Column Restrictions = new Column("Restrictions", Type.Array, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"An array of the restrictions suppoted by provider. An example " + "follows this table.");
private static final Column Description = new Column("Description", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A localizable description of the schema");
private static final Column RestrictionsMask = new Column("RestrictionsMask", Type.UnsignedLong, null, Column.NOT_RESTRICTION,
// Column.REQUIRED,
Column.OPTIONAL,
"The lowest N bits set to 1, where N is the number of restrictions.");
private List restrictedSchemas = null;
public DiscoverSchemaRowsetsRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(DISCOVER_SCHEMA_ROWSETS, request, handler);
if(request.getRestrictions() != null && request.getRestrictions().size() > 0){
Map restrictions = request.getRestrictions();
restrictedSchemas =(List<String>) restrictions.get("SchemaName");
}
}
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException {
RowsetDefinition[] rowsetDefinitions = RowsetDefinition.class.getEnumConstants().clone();
Arrays.sort(rowsetDefinitions, new Comparator<RowsetDefinition>() {
public int compare(RowsetDefinition o1, RowsetDefinition o2) {
return o1.name().compareTo(o2.name());
}
});
for (RowsetDefinition rowsetDefinition : rowsetDefinitions) {
if(restrictedSchemas== null || (restrictedSchemas !=null && restrictedSchemas.contains(rowsetDefinition.name()))){
Row row = new Row();
row.set(SchemaName.name, rowsetDefinition.name());
row.set(SchemaGuid.name, UUID.fromString(getSchemGuid(rowsetDefinition)));
row.set(Restrictions.name, getRestrictions(rowsetDefinition));
row.set(RestrictionsMask.name, getRestrictionsMask(rowsetDefinition));
addRow(row, rows);
}
}
}
private List<XmlElement> getRestrictions(RowsetDefinition rowsetDefinition) {
List<XmlElement> restrictionList = new ArrayList<XmlElement>();
final Column[] columns = rowsetDefinition.columnDefinitions;
for (Column column : columns) {
if (column.restriction) {
restrictionList.add(new XmlElement(Restrictions.name, null, new XmlElement[] { new XmlElement("Name", null, column.name),
new XmlElement("Type", null, column.getColumnType()) }));
}
}
return restrictionList;
}
private String getRestrictionsMask(RowsetDefinition rowsetDefinition) {
if (rowsetDefinition.equals(DBSCHEMA_CATALOGS))
return "1";
if (rowsetDefinition.equals(DBSCHEMA_TABLES))
return "31";
if (rowsetDefinition.equals(DBSCHEMA_COLUMNS))
return "31";
if (rowsetDefinition.equals(DBSCHEMA_PROVIDER_TYPES))
return "3";
if (rowsetDefinition.equals(DISCOVER_DATASOURCES))
return "31";
if (rowsetDefinition.equals(DISCOVER_LITERALS))
return "1";
if (rowsetDefinition.equals(DISCOVER_PROPERTIES))
return "1";
if (rowsetDefinition.equals(DISCOVER_SCHEMA_ROWSETS))
return "1";
if (rowsetDefinition.equals(MDSCHEMA_ACTIONS))
return "511";
if (rowsetDefinition.equals(MDSCHEMA_CUBES))
return "31";
if (rowsetDefinition.equals(MDSCHEMA_DIMENSIONS))
return "127";
if (rowsetDefinition.equals(MDSCHEMA_FUNCTIONS))
return "15";
if (rowsetDefinition.equals(MDSCHEMA_HIERARCHIES))
return "511";
if (rowsetDefinition.equals(MDSCHEMA_LEVELS))
return "1023";
if (rowsetDefinition.equals(MDSCHEMA_MEASURES))
return "255";
if (rowsetDefinition.equals(MDSCHEMA_MEMBERS))
return "16383";
if (rowsetDefinition.equals(MDSCHEMA_PROPERTIES))
return "8191";
if (rowsetDefinition.equals(MDSCHEMA_SETS))
return "255";
if (rowsetDefinition.equals(MDSCHEMA_MEASUREGROUPS))
return "15";
if (rowsetDefinition.equals(MDSCHEMA_MEASUREGROUP_DIMENSIONS))
return "63";
if (rowsetDefinition.equals(DISCOVER_INSTANCES))
return "1";
if (rowsetDefinition.equals(MDSCHEMA_KPIS))
return "63";
throw new IllegalArgumentException("illegal rowset input");
}
private String getSchemGuid(RowsetDefinition rowsetDefinition) {
if (rowsetDefinition.equals(DBSCHEMA_CATALOGS))
return "c8b52211-5cf3-11ce-ade5-00aa0044773d";
if (rowsetDefinition.equals(DBSCHEMA_TABLES))
return "c8b52229-5cf3-11ce-ade5-00aa0044773d";
if (rowsetDefinition.equals(DBSCHEMA_COLUMNS))
return "c8b52214-5cf3-11ce-ade5-00aa0044773d";
if (rowsetDefinition.equals(DBSCHEMA_PROVIDER_TYPES))
return "c8b5222c-5cf3-11ce-ade5-00aa0044773d";
if (rowsetDefinition.equals(DISCOVER_DATASOURCES))
return "06c03d41-f66d-49f3-b1b8-987f7af4cf18";
if (rowsetDefinition.equals(DISCOVER_LITERALS))
return "c3ef5ecb-0a07-4665-a140-b075722dbdc2";
if (rowsetDefinition.equals(DISCOVER_PROPERTIES))
return "4b40adfb-8b09-4758-97bb-636e8ae97bcf";
if (rowsetDefinition.equals(DISCOVER_SCHEMA_ROWSETS))
return "eea0302b-7922-4992-8991-0e605d0e5593";
if (rowsetDefinition.equals(MDSCHEMA_ACTIONS))
return "a07ccd08-8148-11d0-87bb-00c04fc33942";
if (rowsetDefinition.equals(MDSCHEMA_CUBES))
return "c8b522d8-5cf3-11ce-ade5-00aa0044773d";
if (rowsetDefinition.equals(MDSCHEMA_DIMENSIONS))
return "c8b522d9-5cf3-11ce-ade5-00aa0044773d";
if (rowsetDefinition.equals(MDSCHEMA_FUNCTIONS))
return "a07ccd07-8148-11d0-87bb-00c04fc33942";
if (rowsetDefinition.equals(MDSCHEMA_HIERARCHIES))
return "c8b522da-5cf3-11ce-ade5-00aa0044773d";
if (rowsetDefinition.equals(MDSCHEMA_LEVELS))
return "c8b522db-5cf3-11ce-ade5-00aa0044773d";
if (rowsetDefinition.equals(MDSCHEMA_MEASURES))
return "c8b522dc-5cf3-11ce-ade5-00aa0044773d";
if (rowsetDefinition.equals(MDSCHEMA_MEMBERS))
return "c8b522de-5cf3-11ce-ade5-00aa0044773d";
if (rowsetDefinition.equals(MDSCHEMA_PROPERTIES))
return "c8b522dd-5cf3-11ce-ade5-00aa0044773d";
if (rowsetDefinition.equals(MDSCHEMA_SETS))
return "a07ccd0b-8148-11d0-87bb-00c04fc33942";
if (rowsetDefinition.equals(MDSCHEMA_MEASUREGROUPS))
return "e1625ebf-fa96-42fd-bea6-db90adafd96b";
if (rowsetDefinition.equals(MDSCHEMA_MEASUREGROUP_DIMENSIONS))
return "a07ccd33-8148-11d0-87bb-00c04fc33942";
if (rowsetDefinition.equals(DISCOVER_INSTANCES))
return "20518699-2474-4C15-9885-0E947EC7A7E3";
if (rowsetDefinition.equals(MDSCHEMA_KPIS))
return "2AE44109-ED3D-4842-B16F-B694D1CB0E3F";
throw new IllegalArgumentException("illegal rowset input");
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
}
public String getDescription() {
return description;
}
static class DiscoverPropertiesRowset extends Rowset {
private final Util.Functor1<Boolean, PropertyDefinition> propNameCond;
DiscoverPropertiesRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(DISCOVER_PROPERTIES, request, handler);
propNameCond = makeCondition(PROPDEF_NAME_GETTER, PropertyName);
}
private static final Column PropertyName = new Column("PropertyName", Type.StringSometimesArray, null, Column.RESTRICTION, Column.REQUIRED, "The name of the property.");
private static final Column PropertyDescription = new Column("PropertyDescription", Type.String, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"A localizable text description of the property.");
private static final Column PropertyType = new Column("PropertyType", Type.String, null, Column.NOT_RESTRICTION, Column.REQUIRED, "The XML data type of the property.");
private static final Column PropertyAccessType = new Column("PropertyAccessType", Type.EnumString, Enumeration.ACCESS, Column.NOT_RESTRICTION, Column.REQUIRED,
"Access for the property. The value can be Read, Write, or " + "ReadWrite.");
private static final Column IsRequired = new Column("IsRequired", Type.Boolean, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"True if a property is required, false if it is not required.");
private static final Column Value = new Column("Value", Type.String, null, Column.NOT_RESTRICTION, Column.REQUIRED, "The current value of the property.");
protected boolean needConnection() {
return false;
}
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException {
for (PropertyDefinition propertyDefinition : PropertyDefinition.class.getEnumConstants()) {
if (!propNameCond.apply(propertyDefinition)) {
continue;
}
Row row = new Row();
row.set(PropertyName.name, propertyDefinition.name());
row.set(PropertyDescription.name, propertyDefinition.description);
row.set(PropertyType.name, propertyDefinition.type.getName());
row.set(PropertyAccessType.name, propertyDefinition.access);
row.set(IsRequired.name, false);
row.set(Value.name, propertyDefinition.value);
addRow(row, rows);
}
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
}
static class DiscoverInstancesRowset extends Rowset {
DiscoverInstancesRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(DISCOVER_INSTANCES, request, handler);
}
private static final Column InstanceName = new Column("INSTANCE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
"The name of the literal described in the row.\n" + "Example: DBLITERAL_LIKE_PERCENT");
@Override
protected void populateImpl(XmlaResponse response, OlapConnection connection, List rows) throws XmlaException, SQLException {
}
}
static class DiscoverLiteralsRowset extends Rowset {
DiscoverLiteralsRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(DISCOVER_LITERALS, request, handler);
}
// contains data
public static Map<String, List<String>> fillLiteralSchema() {
Map<String, List<String>> data = new HashMap<String, List<String>>();
List row;
row = new ArrayList();
row.addAll(Arrays.asList("", ".", "0123456789", "24", "2"));
data.put("CATALOG_NAME", row);
row.clear();
row.add(Arrays.asList(".", "", "", "1", "3"));
data.put("CATALOG_SEPARATOR", row);
row.clear();
row.clear();
row.add(Arrays.asList("", "\'\"[]", "0123456789", "255", "5"));
data.put("COLUMN_ALIAS", row);
row.clear();
row.add(Arrays.asList("", ".", "0123456789", "14", "6"));
data.put("COLUMN_NAME", row);
row.clear();
row.add(Arrays.asList("", "\'\"[]", "0123456789", "255", "7"));
data.put("CORRELATION_NAME", row);
row.clear();
row.add(Arrays.asList("", ".", "0123456789", "255", "14"));
data.put("PROCEDURE_NAME", row);
row.clear();
row.add(Arrays.asList("", ".", "0123456789", "24", "17"));
data.put("TABLE_NAME", row);
row.clear();
row.add(Arrays.asList("", "", "", "0", "18"));
data.put("TEXT_COMMAND", row);
row.clear();
row.add(Arrays.asList("", "", "", "0", "19"));
data.put("USER_NAME", row);
row.clear();
row.add(Arrays.asList("[", "", "", "1", "15"));
data.put("QUOTE_PREFIX", row);
row.clear();
row.add(Arrays.asList("", ".", "0123456789", "24", "21"));
data.put("CUBE_NAME", row);
row.clear();
row.add(Arrays.asList("", ".", "0123456789", "14", "22"));
data.put("DIMENSION_NAME", row);
row.clear();
row.add(Arrays.asList("", ".", "0123456789", "10", "23"));
data.put("HIERARCHY_NAME", row);
row.clear();
row.add(Arrays.asList("", ".", "0123456789", "255", "24"));
data.put("LEVEL_NAME", row);
row.clear();
row.add(Arrays.asList("", ".", "0123456789", "255", "25"));
data.put("MEMBER_NAME", row);
row.clear();
row.add(Arrays.asList("", ".", "0123456789", "255", "26"));
data.put("PROPERTY_NAME", row);
row.clear();
row.add(Arrays.asList("]", "", "", "1", "28"));
data.put("QUOTE_SUFFIX", row);
row.clear();
row.add(Arrays.asList("", ".", "0123456789", "24", "16"));
data.put("SCHEMA_NAME", row);
row.clear();
row.add(Arrays.asList(".", "", "", "1", "27"));
data.put("SCHEMA_SEPARATOR", row);
return data;
}
public static List getColumnNamese() {
String[] names = new String[6];
names[0] = LiteralName.name;
names[1] = LiteralValue.name;
names[2] = LiteralInvalidChars.name;
names[3] = LiteralInvalidStartingChars.name;
names[4] = LiteralMaxLength.name;
names[5] = LiteralNameEnumValue.name;
return Arrays.asList(names);
}
private static final Column LiteralName = new Column("LiteralName", Type.StringSometimesArray, null, Column.RESTRICTION, Column.REQUIRED,
"The name of the literal described in the row.\n" + "Example: DBLITERAL_LIKE_PERCENT");
private static final Column LiteralValue = new Column("LiteralValue", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Contains the actual literal value.\n"
+ "Example, if LiteralName is DBLITERAL_LIKE_PERCENT and the " + "percent character (%) is used to match zero or more characters "
+ "in a LIKE clause, this column's value would be \"%\".");
private static final Column LiteralInvalidChars = new Column("LiteralInvalidChars", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The characters, in the literal, that are not valid.\n" + "For example, if table names can contain anything other than a "
+ "numeric character, this string would be \"0123456789\".");
private static final Column LiteralInvalidStartingChars = new Column("LiteralInvalidStartingChars", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The characters that are not valid as the first character of the " + "literal. If the literal can start with any valid character, " + "this is null.");
private static final Column LiteralMaxLength = new Column("LiteralMaxLength", Type.Integer, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The maximum number of characters in the literal. If there is no " + "maximum or the maximum is unknown, the value is ?1.");
private static final Column LiteralNameEnumValue = new Column("LiteralNameEnumValue", Type.Integer, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"");
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException {
populate(XmlaConstants.Literal.class, rows, new Comparator<XmlaConstants.Literal>() {
public int compare(XmlaConstants.Literal o1, XmlaConstants.Literal o2) {
return o1.name().compareTo(o2.name());
}
});
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
}
static class DbschemaCatalogsRowset extends Rowset {
DbschemaCatalogsRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(DBSCHEMA_CATALOGS, request, handler);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "Catalog name. Cannot be NULL.");
private static final Column Description = new Column("DESCRIPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Human-readable description of the catalog.");
private static final Column Roles = new Column("ROLES", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A comma delimited list of roles to which the current user " + "belongs. An asterisk (*) is included as a role if the "
+ "current user is a server or database administrator. " + "Username is appended to ROLES if one of the roles uses " + "dynamic security.");
private static final Column DateModified = new Column("DATE_MODIFIED", Type.DateTime, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The date that the catalog was last modified.");
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException, SQLException {
Iterable<Catalog> catalogsItr = catIter(connection);
for (Catalog catalog : catalogsItr) {
for (@SuppressWarnings("unused") Schema m : catalog.getSchemas()) {
Row row = new Row();
row.set(CatalogName.name, catalog.getName());
row.set(Description.name, "No description available");
addRow(row, rows);
}
}
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
}
static class DbschemaColumnsRowset extends Rowset {
private final Util.Functor1<Boolean, Catalog> tableCatalogCond;
private final Util.Functor1<Boolean, Cube> tableNameCond;
private final Util.Functor1<Boolean, String> columnNameCond;
DbschemaColumnsRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(DBSCHEMA_COLUMNS, request, handler);
tableCatalogCond = makeCondition(CATALOG_NAME_GETTER, TableCatalog);
tableNameCond = makeCondition(ELEMENT_NAME_GETTER, TableName);
columnNameCond = makeCondition(ColumnName);
}
private static final Column TableCatalog = new Column("TABLE_CATALOG", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "The name of the Database.");
private static final Column TableSchema = new Column("TABLE_SCHEMA", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, null);
private static final Column TableName = new Column("TABLE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "The name of the cube.");
private static final Column ColumnName = new Column("COLUMN_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "The name of the attribute hierarchy or measure.");
private static final Column OrdinalPosition = new Column("ORDINAL_POSITION", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"The position of the column, beginning with 1.");
private static final Column ColumnHasDefault = new Column("COLUMN_HAS_DEFAULT", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Not supported.");
/*
* A bitmask indicating the information stored in DBCOLUMNFLAGS in OLE DB.
* 1 = Bookmark 2 = Fixed length 4 = Nullable 8 = Row versioning 16 =
* Updateable column
*
* And, of course, MS SQL Server sometimes has the value of 80!!
*/
private static final Column ColumnFlags = new Column("COLUMN_FLAGS", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"A DBCOLUMNFLAGS bitmask indicating column properties.");
private static final Column IsNullable = new Column("IS_NULLABLE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.REQUIRED, "Always returns false.");
private static final Column DataType = new Column("DATA_TYPE", Type.UnsignedShort, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"The data type of the column. Returns a string for dimension " + "columns and a variant for measures.");
private static final Column NumericPrecision = new Column("NUMERIC_PRECISION", Type.UnsignedShort, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The maximum precision of the column for numeric data types " + "other than DBTYPE_VARNUMERIC.");
private static final Column CharacterMaximumLength = new Column("CHARACTER_MAXIMUM_LENGTH", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The maximum possible length of a value within the column.");
private static final Column CharacterOctetLength = new Column("CHARACTER_OCTET_LENGTH", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The maximum possible length of a value within the column, in " + "bytes, for character or binary columns.");
private static final Column NumericScale = new Column("NUMERIC_SCALE", Type.Short, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The number of digits to the right of the decimal point for " + "DBTYPE_DECIMAL, DBTYPE_NUMERIC, DBTYPE_VARNUMERIC. " + "Otherwise, this is NULL.");
private final static Long restrictionsMask = 31L;
private final static String schemaCuid = "c8b52214-5cf3-11ce-ade5-00aa0044773d";
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException, OlapException {
for (Catalog catalog : catIter(connection, catNameCond(), tableCatalogCond)) {
// By definition, mondrian catalogs have only one
// schema. It is safe to use get(0)
final Schema schema = catalog.getSchemas().get(0);
final boolean emitInvisibleMembers = XmlaUtil.shouldEmitInvisibleMembers(request);
int ordinalPosition = 1;
Row row;
for (Cube cube : filter(sortedCubes(schema), tableNameCond)) {
for (Dimension dimension : cube.getDimensions()) {
for (Hierarchy hierarchy : dimension.getHierarchies()) {
ordinalPosition = populateHierarchy(cube, hierarchy, ordinalPosition, rows);
}
}
List<Measure> rms = cube.getMeasures();
for (int k = 1; k < rms.size(); k++) {
Measure member = rms.get(k);
// null == true for regular cubes
// virtual cubes do not set the visible property
// on its measures so it might be null.
Boolean visible = (Boolean) member.getPropertyValue(Property.StandardMemberProperty.$visible);
if (visible == null) {
visible = true;
}
if (!emitInvisibleMembers && !visible) {
continue;
}
String memberName = member.getName();
final String columnName = "Measures:" + memberName;
if (!columnNameCond.apply(columnName)) {
continue;
}
row = new Row();
row.set(TableCatalog.name, catalog.getName());
row.set(TableName.name, cube.getName());
row.set(ColumnName.name, columnName);
row.set(OrdinalPosition.name, ordinalPosition++);
row.set(ColumnHasDefault.name, false);
row.set(ColumnFlags.name, 0);
row.set(IsNullable.name, false);
// here is where one tries to determine the
// type of the column - since these are all
// Measures, aggregate Measures??, maybe they
// are all numeric? (or currency)
row.set(DataType.name, XmlaConstants.DBType.R8.xmlaOrdinal());
// 16/255 seems to be what MS SQL Server
// always returns.
row.set(NumericPrecision.name, 16);
row.set(NumericScale.name, 255);
addRow(row, rows);
}
}
}
}
private int populateHierarchy(Cube cube, Hierarchy hierarchy, int ordinalPosition, List<Row> rows) {
String schemaName = cube.getSchema().getName();
String cubeName = cube.getName();
String hierarchyName = hierarchy.getName();
if (hierarchy.hasAll()) {
Row row = new Row();
row.set(TableCatalog.name, schemaName);
row.set(TableName.name, cubeName);
row.set(ColumnName.name, hierarchyName + ":(All)!NAME");
row.set(OrdinalPosition.name, ordinalPosition++);
row.set(ColumnHasDefault.name, false);
row.set(ColumnFlags.name, 0);
row.set(IsNullable.name, false);
// names are always WSTR
row.set(DataType.name, XmlaConstants.DBType.WSTR.xmlaOrdinal());
row.set(CharacterMaximumLength.name, 0);
row.set(CharacterOctetLength.name, 0);
addRow(row, rows);
row = new Row();
row.set(TableCatalog.name, schemaName);
row.set(TableName.name, cubeName);
row.set(ColumnName.name, hierarchyName + ":(All)!UNIQUE_NAME");
row.set(OrdinalPosition.name, ordinalPosition++);
row.set(ColumnHasDefault.name, false);
row.set(ColumnFlags.name, 0);
row.set(IsNullable.name, false);
// names are always WSTR
row.set(DataType.name, XmlaConstants.DBType.WSTR.xmlaOrdinal());
row.set(CharacterMaximumLength.name, 0);
row.set(CharacterOctetLength.name, 0);
addRow(row, rows);
}
for (Level level : hierarchy.getLevels()) {
ordinalPosition = populateLevel(cube, hierarchy, level, ordinalPosition, rows);
}
return ordinalPosition;
}
private int populateLevel(Cube cube, Hierarchy hierarchy, Level level, int ordinalPosition, List<Row> rows) {
String schemaName = cube.getSchema().getName();
String cubeName = cube.getName();
String hierarchyName = hierarchy.getName();
String levelName = level.getName();
Row row = new Row();
row.set(TableCatalog.name, schemaName);
row.set(TableName.name, cubeName);
row.set(ColumnName.name, hierarchyName + ':' + levelName + "!NAME");
row.set(OrdinalPosition.name, ordinalPosition++);
row.set(ColumnHasDefault.name, false);
row.set(ColumnFlags.name, 0);
row.set(IsNullable.name, false);
// names are always WSTR
row.set(DataType.name, XmlaConstants.DBType.WSTR.xmlaOrdinal());
row.set(CharacterMaximumLength.name, 0);
row.set(CharacterOctetLength.name, 0);
addRow(row, rows);
row = new Row();
row.set(TableCatalog.name, schemaName);
row.set(TableName.name, cubeName);
row.set(ColumnName.name, hierarchyName + ':' + levelName + "!UNIQUE_NAME");
row.set(OrdinalPosition.name, ordinalPosition++);
row.set(ColumnHasDefault.name, false);
row.set(ColumnFlags.name, 0);
row.set(IsNullable.name, false);
// names are always WSTR
row.set(DataType.name, XmlaConstants.DBType.WSTR.xmlaOrdinal());
row.set(CharacterMaximumLength.name, 0);
row.set(CharacterOctetLength.name, 0);
addRow(row, rows);
NamedList<Property> props = level.getProperties();
for (Property prop : props) {
String propName = prop.getName();
row = new Row();
row.set(TableCatalog.name, schemaName);
row.set(TableName.name, cubeName);
row.set(ColumnName.name, hierarchyName + ':' + levelName + '!' + propName);
row.set(OrdinalPosition.name, ordinalPosition++);
row.set(ColumnHasDefault.name, false);
row.set(ColumnFlags.name, 0);
row.set(IsNullable.name, false);
XmlaConstants.DBType dbType = getDBTypeFromProperty(prop);
row.set(DataType.name, dbType.xmlaOrdinal());
switch (prop.getDatatype()) {
case STRING:
row.set(CharacterMaximumLength.name, 0);
row.set(CharacterOctetLength.name, 0);
break;
case INTEGER:
case UNSIGNED_INTEGER:
case DOUBLE:
// 16/255 seems to be what MS SQL Server
// always returns.
row.set(NumericPrecision.name, 16);
row.set(NumericScale.name, 255);
break;
case BOOLEAN:
row.set(NumericPrecision.name, 255);
row.set(NumericScale.name, 255);
break;
default:
//what type is it really, its
// not a string
row.set(CharacterMaximumLength.name, 0);
row.set(CharacterOctetLength.name, 0);
break;
}
addRow(row, rows);
}
return ordinalPosition;
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
public static Long getRestrictionsmask() {
return restrictionsMask;
}
public static String getSchemacuid() {
return schemaCuid;
}
}
static class DbschemaProviderTypesRowset extends Rowset {
private final Util.Functor1<Boolean, Integer> dataTypeCond;
DbschemaProviderTypesRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(DBSCHEMA_PROVIDER_TYPES, request, handler);
dataTypeCond = makeCondition(DataType);
}
/*
* DATA_TYPE DBTYPE_UI2 BEST_MATCH DBTYPE_BOOL Column(String name, Type
* type, Enumeration enumeratedType, boolean restriction, boolean
* nullable, String description)
*/
/*
* These are the columns returned by SQL Server.
*/
private static final Column TypeName = new Column("TYPE_NAME", Type.String, null, Column.NOT_RESTRICTION, Column.REQUIRED, "The provider-specific data type name.");
private static final Column DataType = new Column("DATA_TYPE", Type.UnsignedShort, null, Column.RESTRICTION, Column.REQUIRED, "The indicator of the data type.");
private static final Column ColumnSize = new Column("COLUMN_SIZE", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"The length of a non-numeric column. If the data type is " + "numeric, this is the upper bound on the maximum precision " + "of the data type.");
private static final Column LiteralPrefix = new Column("LITERAL_PREFIX", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The character or characters used to prefix a literal of this " + "type in a text command.");
private static final Column LiteralSuffix = new Column("LITERAL_SUFFIX", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The character or characters used to suffix a literal of this " + "type in a text command.");
private static final Column IsNullable = new Column("IS_NULLABLE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A Boolean that indicates whether the data type is nullable. " + "NULL-- indicates that it is not known whether the data type " + "is nullable.");
private static final Column CaseSensitive = new Column("CASE_SENSITIVE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A Boolean that indicates whether the data type is a " + "characters type and case-sensitive.");
private static final Column Searchable = new Column("SEARCHABLE", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"An integer indicating how the data type can be used in " + "searches if the provider supports ICommandText; otherwise, " + "NULL.");
private static final Column UnsignedAttribute = new Column("UNSIGNED_ATTRIBUTE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A Boolean that indicates whether the data type is unsigned.");
private static final Column FixedPrecScale = new Column("FIXED_PREC_SCALE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A Boolean that indicates whether the data type has a fixed " + "precision and scale.");
private static final Column AutoUniqueValue = new Column("AUTO_UNIQUE_VALUE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A Boolean that indicates whether the data type is " + "autoincrementing.");
private static final Column IsLong = new Column("IS_LONG", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A Boolean that indicates whether the data type is a binary " + "large object (BLOB) and has very long data.");
private static final Column BestMatch = new Column("BEST_MATCH", Type.Boolean, null, Column.RESTRICTION, Column.OPTIONAL,
"A Boolean that indicates whether the data type is a best " + "match.");
@Override
protected boolean needConnection() {
return false;
}
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException {
// Identifies the (base) data types supported by the data provider.
Row row;
Integer dt = XmlaConstants.DBType.I4.xmlaOrdinal();
if (dataTypeCond.apply(dt)) {
row = new Row();
row.set(TypeName.name, XmlaConstants.DBType.I4.userName);
row.set(DataType.name, dt);
row.set(ColumnSize.name, 8);
row.set(IsNullable.name, true);
row.set(Searchable.name, null);
row.set(UnsignedAttribute.name, false);
row.set(FixedPrecScale.name, false);
row.set(AutoUniqueValue.name, false);
row.set(IsLong.name, false);
row.set(BestMatch.name, true);
addRow(row, rows);
}
dt = XmlaConstants.DBType.R8.xmlaOrdinal();
if (dataTypeCond.apply(dt)) {
row = new Row();
row.set(TypeName.name, XmlaConstants.DBType.R8.userName);
row.set(DataType.name, dt);
row.set(ColumnSize.name, 16);
row.set(IsNullable.name, true);
row.set(Searchable.name, null);
row.set(UnsignedAttribute.name, false);
row.set(FixedPrecScale.name, false);
row.set(AutoUniqueValue.name, false);
row.set(IsLong.name, false);
row.set(BestMatch.name, true);
addRow(row, rows);
}
dt = XmlaConstants.DBType.CY.xmlaOrdinal();
if (dataTypeCond.apply(dt)) {
row = new Row();
row.set(TypeName.name, XmlaConstants.DBType.CY.userName);
row.set(DataType.name, dt);
row.set(ColumnSize.name, 8);
row.set(IsNullable.name, true);
row.set(Searchable.name, null);
row.set(UnsignedAttribute.name, false);
row.set(FixedPrecScale.name, false);
row.set(AutoUniqueValue.name, false);
row.set(IsLong.name, false);
row.set(BestMatch.name, true);
addRow(row, rows);
}
// BOOL
dt = XmlaConstants.DBType.BOOL.xmlaOrdinal();
if (dataTypeCond.apply(dt)) {
row = new Row();
row.set(TypeName.name, XmlaConstants.DBType.BOOL.userName);
row.set(DataType.name, dt);
row.set(ColumnSize.name, 1);
row.set(IsNullable.name, true);
row.set(Searchable.name, null);
row.set(UnsignedAttribute.name, false);
row.set(FixedPrecScale.name, false);
row.set(AutoUniqueValue.name, false);
row.set(IsLong.name, false);
row.set(BestMatch.name, true);
addRow(row, rows);
}
dt = XmlaConstants.DBType.I8.xmlaOrdinal();
if (dataTypeCond.apply(dt)) {
row = new Row();
row.set(TypeName.name, XmlaConstants.DBType.I8.userName);
row.set(DataType.name, dt);
row.set(ColumnSize.name, 16);
row.set(IsNullable.name, true);
row.set(Searchable.name, null);
row.set(UnsignedAttribute.name, false);
row.set(FixedPrecScale.name, false);
row.set(AutoUniqueValue.name, false);
row.set(IsLong.name, false);
row.set(BestMatch.name, true);
addRow(row, rows);
}
// WSTR
dt = XmlaConstants.DBType.WSTR.xmlaOrdinal();
if (dataTypeCond.apply(dt)) {
row = new Row();
row.set(TypeName.name, XmlaConstants.DBType.WSTR.userName);
row.set(DataType.name, dt);
// how big are the string columns in the db
row.set(ColumnSize.name, 255);
row.set(LiteralPrefix.name, "\"");
row.set(LiteralSuffix.name, "\"");
row.set(IsNullable.name, true);
row.set(CaseSensitive.name, false);
row.set(Searchable.name, null);
row.set(FixedPrecScale.name, false);
row.set(AutoUniqueValue.name, false);
row.set(IsLong.name, false);
row.set(BestMatch.name, true);
addRow(row, rows);
}
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
}
static class DbschemaTablesRowset extends Rowset {
private final Util.Functor1<Boolean, Catalog> tableCatalogCond;
private final Util.Functor1<Boolean, Cube> tableNameCond;
private final Util.Functor1<Boolean, String> tableTypeCond;
DbschemaTablesRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(DBSCHEMA_TABLES, request, handler);
tableCatalogCond = makeCondition(CATALOG_NAME_GETTER, TableCatalog);
tableNameCond = makeCondition(ELEMENT_NAME_GETTER, TableName);
tableTypeCond = makeCondition(TableType);
}
private static final Column TableCatalog = new Column("TABLE_CATALOG", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
"The name of the catalog to which this object belongs.");
private static final Column TableSchema = new Column("TABLE_SCHEMA", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the cube to which this object belongs.");
private static final Column TableName = new Column("TABLE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "The name of the object, if TABLE_TYPE is TABLE.");
private static final Column TableType = new Column("TABLE_TYPE", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
"The type of the table. TABLE indicates the object is a " + "measure group. SYSTEM TABLE indicates the object is a " + "dimension.");
private static final Column TableGuid = new Column("TABLE_GUID", Type.UUID, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Not supported.");
private static final Column Description = new Column("DESCRIPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "A human-readable description of the object.");
private static final Column TablePropId = new Column("TABLE_PROPID", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Not supported.");
private static final Column DateCreated = new Column("DATE_CREATED", Type.DateTime, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Not supported.");
private static final Column DateModified = new Column("DATE_MODIFIED", Type.DateTime, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "The date the object was last modified.");
private static final Column TableOlapType = new Column("TABLE_OLAP_TYPE", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
"The OLAP type of the object. MEASURE_GROUP indicates the " + "object is a measure group. CUBE_DIMENSION indicated the " + "object is a dimension.");
private final static Long restrictionsMask = 31L;
private final static String schemaCuid = "c8b52229-5cf3-11ce-ade5-00aa0044773d";
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException, OlapException {
for (Catalog catalog : catIter(connection, catNameCond(), tableCatalogCond)) {
// By definition, mondrian catalogs have only one
// schema. It is safe to use get(0)
final Schema schema = catalog.getSchemas().get(0);
Row row;
for (Cube cube : filter(sortedCubes(schema), tableNameCond)) {
String desc = cube.getDescription();
if (desc == null) {
desc = catalog.getName() + " - " + cube.getName() + " Cube";
}
if (tableTypeCond.apply("TABLE")) {
row = new Row();
row.set(TableCatalog.name, catalog.getName());
row.set(TableName.name, cube.getName());
row.set(TableSchema.name, cube.getName());
row.set(TableType.name, "TABLE");
row.set(Description.name, desc);
row.set(TableOlapType.name, "MEASURE_GROUP");
row.set(DateModified.name, dateModified);
addRow(row, rows);
}
if (tableTypeCond.apply("SYSTEM TABLE")) {
for (Dimension dimension : cube.getDimensions()) {
if (dimension.getDimensionType() == Dimension.Type.MEASURE) {
continue;
}
for (Hierarchy hierarchy : dimension.getHierarchies()) {
populateHierarchy(cube, hierarchy, rows);
}
}
}
}
}
}
private void populateHierarchy(Cube cube, Hierarchy hierarchy, List<Row> rows) {
for (Level level : hierarchy.getLevels()) {
populateLevel(cube, hierarchy, level, rows);
}
}
private void populateLevel(Cube cube, Hierarchy hierarchy, Level level, List<Row> rows) {
String schemaName = cube.getSchema().getName();
String cubeName = cube.getName();
String hierarchyName = getHierarchyName(hierarchy);
String levelName = level.getName();
String tableName = cubeName + ':' + hierarchyName + ':' + levelName;
String desc = level.getDescription();
if (desc == null) {
desc = schemaName + " - " + cubeName + " Cube - " + hierarchyName + " Hierarchy - " + levelName + " Level";
}
Row row = new Row();
row.set(TableCatalog.name, schemaName);
row.set(TableSchema.name, cubeName);
row.set(TableName.name, tableName);
row.set(TableType.name, "SYSTEM TABLE");
row.set(Description.name, desc);
row.set(TableOlapType.name, "CUBE_DIMENSION");
row.set(DateModified.name, dateModified);
addRow(row, rows);
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
public static Long getRestrictionsmask() {
return restrictionsMask;
}
public static String getSchemacuid() {
return schemaCuid;
}
}
static class MdschemaActionsRowset extends Rowset {
MdschemaActionsRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(MDSCHEMA_ACTIONS, request, handler);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the catalog to which this action belongs.");
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the schema to which this action belongs.");
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "The name of the cube to which this action belongs.");
private static final Column ActionName = new Column("ACTION_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "The name of the action.");
private static final Column ActionType = new Column("ACTION_TYPE", Type.Integer, null, Column.RESTRICTION, Column.REQUIRED, "The name of the action.");
private static final Column Invocation = new Column("INVOCATION", Type.Integer, null, Column.RESTRICTION, Column.REQUIRED,
"Information about how to invoke the action: 1 - Indicates a regular action used during normal");
private static final Column Coordinate = new Column("COORDINATE", Type.String, null, Column.RESTRICTION, Column.REQUIRED, null);
private static final Column CoordinateType = new Column("COORDINATE_TYPE", Type.Integer, null, Column.RESTRICTION, Column.REQUIRED, null);
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException {
// mondrian doesn't support actions. It's not an error to ask for
// them, there just aren't any
}
}
public static class MdschemaCubesRowset extends Rowset {
private final Util.Functor1<Boolean, Catalog> catalogNameCond;
private final Util.Functor1<Boolean, Schema> schemaNameCond;
private final Util.Functor1<Boolean, Cube> cubeNameCond;
MdschemaCubesRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(MDSCHEMA_CUBES, request, handler);
catalogNameCond = makeCondition(CATALOG_NAME_GETTER, CatalogName);
schemaNameCond = makeCondition(SCHEMA_NAME_GETTER, SchemaName);
cubeNameCond = makeCondition(ELEMENT_NAME_GETTER, CubeName);
}
public static final String MD_CUBTYPE_CUBE = "CUBE";
public static final String MD_CUBTYPE_VIRTUAL_CUBE = "VIRTUAL CUBE";
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the catalog to which this cube belongs.");
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the schema to which this cube belongs.");
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "Name of the cube.");
private static final Column CubeType = new Column("CUBE_TYPE", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "Cube type.");
private static final Column CubeGuid = new Column("CUBE_GUID", Type.UUID, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Cube type.");
private static final Column CreatedOn = new Column("CREATED_ON", Type.DateTime, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Date and time of cube creation.");
private static final Column LastSchemaUpdate = new Column("LAST_SCHEMA_UPDATE", Type.DateTime, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"Date and time of last schema update.");
private static final Column SchemaUpdatedBy = new Column("SCHEMA_UPDATED_BY", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"User ID of the person who last updated the schema.");
private static final Column LastDataUpdate = new Column("LAST_DATA_UPDATE", Type.DateTime, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"Date and time of last data update.");
private static final Column DataUpdatedBy = new Column("DATA_UPDATED_BY", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"User ID of the person who last updated the data.");
private static final Column IsDrillthroughEnabled = new Column("IS_DRILLTHROUGH_ENABLED", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"Describes whether DRILLTHROUGH can be performed on the " + "members of a cube");
private static final Column IsWriteEnabled = new Column("IS_WRITE_ENABLED", Type.Boolean, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"Describes whether a cube is write-enabled");
private static final Column IsLinkable = new Column("IS_LINKABLE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"Describes whether a cube can be used in a linked cube");
private static final Column IsSqlEnabled = new Column("IS_SQL_ENABLED", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"Describes whether or not SQL can be used on the cube");
private static final Column CubeCaption = new Column("CUBE_CAPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "The caption of the cube.");
private static final Column BaseCubeName = new Column("BASE_CUBE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
"The name of the source cube if this cube is a perspective cube");
private static final Column CubeSource = new Column("CUBE_SOURCE", Type.UnsignedShort, null, Column.RESTRICTION, Column.REQUIRED,
"A bitmask with one of these valid values: 0x01-Cube 0x02-Dimension");
private static final Column PreferedQueryPatterns = new Column("PREFERRED_QUERY_PATTERNS", Type.UnsignedShort, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"describes query pattern client applications can utilize for higher performance");
private static final Column Description = new Column("DESCRIPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A user-friendly description of the dimension.");
private static final Column Dimensions = new Column("DIMENSIONS", Type.Rowset, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Dimensions in this cube.");
private static final Column Sets = new Column("SETS", Type.Rowset, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Sets in this cube.");
private static final Column Measures = new Column("MEASURES", Type.Rowset, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Measures in this cube.");
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException, SQLException {
for (Catalog catalog : catIter(connection, catNameCond(), catalogNameCond)) {
for (Schema schema : filter(catalog.getSchemas(), schemaNameCond)) {
for (Cube cube : filter(sortedCubes(schema), cubeNameCond)) {
String desc = cube.getDescription();
if (desc == null) {
desc = catalog.getName() + " Schema - " + cube.getName() + " Cube";
}
Row row = new Row();
row.set(CatalogName.name, catalog.getName());
row.set(CubeName.name, cube.getName());
final CustomXmlaHandler.XmlaExtra extra = getExtra(connection);
row.set(CubeType.name, extra.getCubeType(cube));
row.set(IsDrillthroughEnabled.name, true);
row.set(IsWriteEnabled.name, false);
row.set(IsLinkable.name, true);
row.set(IsSqlEnabled.name, true);
row.set(CubeCaption.name, cube.getCaption());
row.set(Description.name, desc);
Format formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String formattedDate = formatter.format(extra.getSchemaLoadDate(schema));
row.set(LastSchemaUpdate.name, formattedDate);
row.set(LastDataUpdate.name, formattedDate);
if (deep) {
row.set(Dimensions.name,
new MdschemaDimensionsRowset(wrapRequest(request, Olap4jUtil.mapOf(MdschemaDimensionsRowset.CatalogName, catalog.getName(),
MdschemaDimensionsRowset.SchemaName, schema.getName(), MdschemaDimensionsRowset.CubeName, cube.getName())), handler));
row.set(Sets.name,
new MdschemaSetsRowset(wrapRequest(request, Olap4jUtil.mapOf(MdschemaSetsRowset.CatalogName, catalog.getName(), MdschemaSetsRowset.SchemaName,
schema.getName(), MdschemaSetsRowset.CubeName, cube.getName())), handler));
row.set(Measures.name,
new MdschemaMeasuresRowset(wrapRequest(request, Olap4jUtil.mapOf(MdschemaMeasuresRowset.CatalogName, catalog.getName(),
MdschemaMeasuresRowset.SchemaName, schema.getName(), MdschemaMeasuresRowset.CubeName, cube.getName())), handler));
}
row.set(CubeSource.name, "1");
// row.set(BaseCubeName.name, cube.getName());
row.set(PreferedQueryPatterns.name, 0);
addRow(row, rows);
}
}
}
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
}
static class MdschemaDimensionsRowset extends Rowset {
private final Util.Functor1<Boolean, Catalog> catalogNameCond;
private final Util.Functor1<Boolean, Schema> schemaNameCond;
private final Util.Functor1<Boolean, Cube> cubeNameCond;
private final Util.Functor1<Boolean, Dimension> dimensionUnameCond;
private final Util.Functor1<Boolean, Dimension> dimensionNameCond;
MdschemaDimensionsRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(MDSCHEMA_DIMENSIONS, request, handler);
catalogNameCond = makeCondition(CATALOG_NAME_GETTER, CatalogName);
schemaNameCond = makeCondition(SCHEMA_NAME_GETTER, SchemaName);
cubeNameCond = makeCondition(ELEMENT_NAME_GETTER, CubeName);
dimensionUnameCond = makeCondition(ELEMENT_UNAME_GETTER, DimensionUniqueName);
dimensionNameCond = makeCondition(ELEMENT_NAME_GETTER, DimensionName);
}
public static final int MD_DIMTYPE_OTHER = 3;
public static final int MD_DIMTYPE_MEASURE = 2;
public static final int MD_DIMTYPE_TIME = 1;
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "The name of the database.");
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "Not supported.");
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "The name of the cube.");
private static final Column DimensionName = new Column("DIMENSION_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "The name of the dimension.");
private static final Column DimensionUniqueName = new Column("DIMENSION_UNIQUE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
"The unique name of the dimension.");
private static final Column DimensionGuid = new Column("DIMENSION_GUID", Type.UUID, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Not supported.");
private static final Column DimensionCaption = new Column("DIMENSION_CAPTION", Type.String, null, Column.NOT_RESTRICTION, Column.REQUIRED, "The caption of the dimension.");
private static final Column DimensionOrdinal = new Column("DIMENSION_ORDINAL", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"The position of the dimension within the cube.");
/*
* SQL Server returns values: MD_DIMTYPE_TIME (1) MD_DIMTYPE_MEASURE (2)
* MD_DIMTYPE_OTHER (3)
*/
private static final Column DimensionType = new Column("DIMENSION_TYPE", Type.Short, null, Column.NOT_RESTRICTION, Column.REQUIRED, "The type of the dimension.");
private static final Column DimensionCardinality = new Column("DIMENSION_CARDINALITY", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"The number of members in the key attribute.");
private static final Column DefaultHierarchy = new Column("DEFAULT_HIERARCHY", Type.String, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"A hierarchy from the dimension. Preserved for backwards " + "compatibility.");
private static final Column Description = new Column("DESCRIPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A user-friendly description of the dimension.");
private static final Column IsVirtual = new Column("IS_VIRTUAL", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Always FALSE.");
private static final Column IsReadWrite = new Column("IS_READWRITE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A Boolean that indicates whether the dimension is " + "write-enabled.");
/*
* SQL Server returns values: 0 or 1
*/
private static final Column DimensionUniqueSettings = new Column("DIMENSION_UNIQUE_SETTINGS", Type.Integer, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A bitmap that specifies which columns contain unique values " + "if the dimension contains only members with unique names.");
private static final Column DimensionMasterUniqueName = new Column("DIMENSION_MASTER_NAME", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Always NULL.");
private static final Column DimensionVisibility = new Column("DIMENSION_VISIBILITY", Type.UnsignedInteger, null, Column.RESTRICTION, Column.REQUIRED, "Always TRUE.");
private static final Column Hierarchies = new Column("HIERARCHIES", Type.Rowset, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Hierarchies in this dimension.");
private static final Column CubeSource = new Column("CUBE_SOURCE", Type.UnsignedShort, null, Column.RESTRICTION, Column.OPTIONAL,
"A bitmask with one of these valid values:0x01 - Cube 0x02 - Dimension");
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException, SQLException {
for (Catalog catalog : catIter(connection, catNameCond(), catalogNameCond)) {
populateCatalog(connection, catalog, rows);
}
}
protected void populateCatalog(OlapConnection connection, Catalog catalog, List<Row> rows) throws XmlaException, SQLException {
for (Schema schema : filter(catalog.getSchemas(), schemaNameCond)) {
for (Cube cube : filteredCubes(schema, cubeNameCond)) {
populateCube(connection, catalog, cube, rows);
}
}
}
protected void populateCube(OlapConnection connection, Catalog catalog, Cube cube, List<Row> rows) throws XmlaException, SQLException {
for (Dimension dimension : filter(cube.getDimensions(), dimensionNameCond, dimensionUnameCond)) {
populateDimension(connection, catalog, cube, dimension, rows);
}
}
protected void populateDimension(OlapConnection connection, Catalog catalog, Cube cube, Dimension dimension, List<Row> rows) throws XmlaException, SQLException {
String desc = dimension.getDescription();
if (desc == null) {
desc = cube.getName() + " Cube - " + dimension.getName() + " Dimension";
}
Row row = new Row();
row.set(CatalogName.name, catalog.getName());
row.set(SchemaName.name, cube.getSchema().getName());
row.set(CubeName.name, cube.getName());
row.set(DimensionName.name, dimension.getName());
// row.set(DimensionMasterUniqueName.name, dimension.getName());
row.set(DimensionUniqueName.name, dimension.getUniqueName());
row.set(DimensionCaption.name, dimension.getCaption());
row.set(DimensionOrdinal.name, cube.getDimensions().indexOf(dimension));
row.set(DimensionType.name, getDimensionType(dimension));
// Is this the number of primaryKey members there are??
// According to microsoft this is:
// "The number of members in the key attribute."
// There may be a better way of doing this but
// this is what I came up with. Note that I need to
// add '1' to the number inorder for it to match
// match what microsoft SQL Server is producing.
// The '1' might have to do with whether or not the
// hierarchy has a 'all' member or not - don't know yet.
// large data set total for Orders cube 0m42.923s
Hierarchy firstHierarchy = dimension.getHierarchies().get(0);
NamedList<Level> levels = firstHierarchy.getLevels();
Level lastLevel = levels.get(levels.size() - 1);
/*
* if override config setting is set if approxRowCount has a value use
* it else do default
*/
// Added by TWI to returned cached row numbers
int n = getExtra(connection).getLevelCardinality(lastLevel);
row.set(DimensionCardinality.name, n + 1);
row.set(DefaultHierarchy.name, dimension.getUniqueName());
row.set(Description.name, desc);
row.set(IsVirtual.name, false);
// SQL Server always returns false
row.set(IsReadWrite.name, false);
row.set(DimensionUniqueSettings.name, 0);
row.set(DimensionMasterUniqueName.name, dimension.getName());
row.set(DimensionVisibility.name, dimension.isVisible() ? 1:0);
if (deep) {
row.set(Hierarchies.name,
new MdschemaHierarchiesRowset(wrapRequest(request, Olap4jUtil.mapOf(MdschemaHierarchiesRowset.CatalogName, catalog.getName(),
MdschemaHierarchiesRowset.SchemaName, cube.getSchema().getName(), MdschemaHierarchiesRowset.CubeName, cube.getName(),
MdschemaHierarchiesRowset.DimensionUniqueName, dimension.getUniqueName())), handler));
}
addRow(row, rows);
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
}
static int getDimensionType(Dimension dim) throws OlapException {
switch (dim.getDimensionType()) {
case MEASURE:
return MdschemaDimensionsRowset.MD_DIMTYPE_MEASURE;
case TIME:
return MdschemaDimensionsRowset.MD_DIMTYPE_TIME;
default:
return MdschemaDimensionsRowset.MD_DIMTYPE_OTHER;
}
}
public static class MdschemaFunctionsRowset extends Rowset {
public enum VarType {
Empty("Uninitialized (default)"), Null("Contains no valid data"), Integer("Integer subtype"), Long("Long subtype"), Single("Single subtype"), Double("Double subtype"), Currency(
"Currency subtype"), Date("Date subtype"), String("String subtype"), Object("Object subtype"), Error("Error subtype"), Boolean("Boolean subtype"), Variant(
"Variant subtype"), DataObject("DataObject subtype"), Decimal("Decimal subtype"), Byte("Byte subtype"), Array("Array subtype");
public static VarType forCategory(int category) {
switch (category) {
case Category.Unknown:
// expression == unknown ???
// case Category.Expression:
return Empty;
case Category.Array:
return Array;
case Category.Dimension:
case Category.Hierarchy:
case Category.Level:
case Category.Member:
case Category.Set:
case Category.Tuple:
case Category.Cube:
case Category.Value:
return Variant;
case Category.Logical:
return Boolean;
case Category.Numeric:
return Double;
case Category.String:
case Category.Symbol:
case Category.Constant:
return String;
case Category.DateTime:
return Date;
case Category.Integer:
case Category.Mask:
return Integer;
}
// NOTE: this should never happen
return Empty;
}
VarType(String description) {
Util.discard(description);
}
}
private final Util.Functor1<Boolean, String> functionNameCond;
MdschemaFunctionsRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(MDSCHEMA_FUNCTIONS, request, handler);
functionNameCond = makeCondition(FunctionName);
}
private static final Column FunctionName = new Column("FUNCTION_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "The name of the function.");
private static final Column Description = new Column("DESCRIPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "A description of the function.");
private static final Column ParameterList = new Column("PARAMETER_LIST", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "A comma delimited list of parameters.");
private static final Column ReturnType = new Column("RETURN_TYPE", Type.Integer, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"The VARTYPE of the return data type of the function.");
private static final Column Origin = new Column("ORIGIN", Type.Integer, null, Column.RESTRICTION, Column.REQUIRED,
"The origin of the function: 1 for MDX functions. 2 for " + "user-defined functions.");
private static final Column InterfaceName = new Column("INTERFACE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
"The name of the interface for user-defined functions");
private static final Column LibraryName = new Column("LIBRARY_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the type library for user-defined functions. " + "NULL for MDX functions.");
private static final Column Caption = new Column("CAPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "The display caption for the function.");
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException, SQLException {
final CustomXmlaHandler.XmlaExtra extra = getExtra(connection);
for (Catalog catalog : catIter(connection, catNameCond())) {
// By definition, mondrian catalogs have only one
// schema. It is safe to use get(0)
final Schema schema = catalog.getSchemas().get(0);
List<CustomXmlaHandler.XmlaExtra.FunctionDefinition> funDefs = new ArrayList<CustomXmlaHandler.XmlaExtra.FunctionDefinition>();
// olap4j does not support describing functions. Call an
// auxiliary method.
extra.getSchemaFunctionList(funDefs, schema, functionNameCond);
for (CustomXmlaHandler.XmlaExtra.FunctionDefinition funDef : funDefs) {
Row row = new Row();
row.set(FunctionName.name, funDef.functionName);
row.set(Description.name, funDef.description);
row.set(ParameterList.name, funDef.parameterList);
row.set(ReturnType.name, funDef.returnType);
row.set(Origin.name, funDef.origin);
// row.set(LibraryName.name, "");
row.set(InterfaceName.name, funDef.interfaceName);
row.set(Caption.name, funDef.caption);
addRow(row, rows);
}
}
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
}
static class MdschemaHierarchiesRowset extends Rowset {
private final Util.Functor1<Boolean, Catalog> catalogCond;
private final Util.Functor1<Boolean, Schema> schemaNameCond;
private final Util.Functor1<Boolean, Cube> cubeNameCond;
private final Util.Functor1<Boolean, Dimension> dimensionUnameCond;
private final Util.Functor1<Boolean, Hierarchy> hierarchyUnameCond;
private final Util.Functor1<Boolean, Hierarchy> hierarchyNameCond;
MdschemaHierarchiesRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(MDSCHEMA_HIERARCHIES, request, handler);
// if (((DefaultXmlaRequest)request).getRequestItemName() != null && ((DefaultXmlaRequest)request).getRequestItemName().equals("MDSCHEMA_HIERARCHIES")){
// if(getRestriction("CUBE_NAME")== null){
// putRestriction("CUBE_NAME", Arrays.asList(handler.currentCube));
catalogCond = makeCondition(CATALOG_NAME_GETTER, CatalogName);
schemaNameCond = makeCondition(SCHEMA_NAME_GETTER, SchemaName);
cubeNameCond = makeCondition(ELEMENT_NAME_GETTER, CubeName);
dimensionUnameCond = makeCondition(ELEMENT_UNAME_GETTER, DimensionUniqueName);
hierarchyUnameCond = makeCondition(ELEMENT_UNAME_GETTER, HierarchyUniqueName);
hierarchyNameCond = makeCondition(ELEMENT_NAME_GETTER, HierarchyName);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the catalog to which this hierarchy belongs.");
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "Not supported");
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the cube to which this hierarchy belongs.");
private static final Column CubeSource = new Column("CUBE_SOURCE", Type.UnsignedInteger, null, Column.RESTRICTION, Column.OPTIONAL,
"");
private static final Column DimensionUniqueName = new Column("DIMENSION_UNIQUE_NAME", Type.String, null, Column.OPTIONAL, Column.OPTIONAL,
"The unique name of the dimension to which this hierarchy " + "belongs.");
private static final Column DimensionMasterUniqueName = new Column("DIMENSION_MASTER_UNIQUE_NAME", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The unique name of the dimension to which this hierarchy " + "belongs.");
private static final Column HierarchyName = new Column("HIERARCHY_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the hierarchy. Blank if there is only a single " + "hierarchy in the dimension.");
private static final Column HierarchyUniqueName = new Column("HIERARCHY_UNIQUE_NAME", Type.String, null, Column.OPTIONAL, Column.OPTIONAL,
"The unique name of the hierarchy.");
private static final Column HierarchyGuid = new Column("HIERARCHY_GUID", Type.UUID, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Hierarchy GUID.");
private static final Column HierarchyCaption = new Column("HIERARCHY_CAPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A label or a caption associated with the hierarchy.");
private static final Column DimensionType = new Column("DIMENSION_TYPE", Type.Short, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "The type of the dimension.");
private static final Column HierarchyCardinality = new Column("HIERARCHY_CARDINALITY", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The number of members in the hierarchy.");
private static final Column DefaultMember = new Column("DEFAULT_MEMBER", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "The default member for this hierarchy.");
private static final Column AllMember = new Column("ALL_MEMBER", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The member at the highest level of rollup in the hierarchy.");
private static final Column Description = new Column("DESCRIPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A human-readable description of the hierarchy. NULL if no " + "description exists.");
private static final Column Structure = new Column("STRUCTURE", Type.Short, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "The structure of the hierarchy.");
private static final Column IsVirtual = new Column("IS_VIRTUAL", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Always returns False.");
private static final Column IsReadWrite = new Column("IS_READWRITE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A Boolean that indicates whether the Write Back to dimension " + "column is enabled.");
private static final Column HierarchyUniqueSettings = new Column("HIERARCHY_UNIQUE_SETTINGS", Type.Integer, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"Always returns MDDIMENSIONS_MEMBER_KEY_UNIQUE (1).");
private static final Column DimensionIsVisible = new Column("DIMENSION_IS_VISIBLE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A Boolean that indicates whether the parent dimension is visible.");
private static final Column HierarchyIsVisible = new Column("HIERARCHY_IS_VISIBLE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A Boolean that indicates whether the hieararchy is visible.");
private static final Column HierarchyVisibility = new Column("HIERARCHY_VISIBILITY", Type.UnsignedShort, null, Column.RESTRICTION, Column.OPTIONAL,
"");
private static final Column HierarchyOrdinal = new Column("HIERARCHY_ORDINAL", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The ordinal number of the hierarchy across all hierarchies of " + "the cube.");
private static final Column DimensionIsShared = new Column("DIMENSION_IS_SHARED", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Always returns true.");
private static final Column Levels = new Column("LEVELS", Type.Rowset, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Levels in this hierarchy.");
private static final Column DimensionUniqueSettings = new Column("DIMENSION_UNIQUE_SETTINGS", Type.Integer, null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column HierarchyOrigin = new Column("HIERARCHY_ORIGIN", Type.UnsignedShort, null, Column.RESTRICTION, Column.OPTIONAL, "Levels in this hierarchy.");
private static final Column HierarchyDisplayFolder = new Column("HIERARCHY_DISPLAY_FOLDER", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
/*
* NOTE: This is non-standard, where did it come from?
*/
// private static final Column ParentChild = new Column("PARENT_CHILD", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Is hierarchy a parent.");
private static final Column InstanceSelection = new Column("INSTANCE_SELECTION", Type.UnsignedShort, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
private static final Column StructureType = new Column("STRUCTURE_TYPE", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
private static final Column GroupingBehaviors = new Column("GROUPING_BEHAVIOR", Type.UnsignedShort, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException, SQLException {
// if(visualModeEnable)
// return;
for (Catalog catalog : catIter(connection, catNameCond(), catalogCond)) {
populateCatalog(connection, catalog, rows);
}
}
protected void populateCatalog(OlapConnection connection, Catalog catalog, List<Row> rows) throws XmlaException, SQLException {
for (Schema schema : filter(catalog.getSchemas(), schemaNameCond)) {
for (Cube cube : filteredCubes(schema, cubeNameCond)) {
if(cube instanceof SharedDimensionHolderCube){
continue;
}
populateCube(connection, catalog, cube, rows);
}
}
}
protected void populateCube(OlapConnection connection, Catalog catalog, Cube cube, List<Row> rows) throws XmlaException, SQLException {
int ordinal = 0;
for (Dimension dimension : cube.getDimensions()) {
// Must increment ordinal for all dimensions but
// only output some of them.
boolean genOutput = dimensionUnameCond.apply(dimension);
if (genOutput) {
populateDimension(connection, catalog, cube, dimension, ordinal, rows);
}
ordinal += dimension.getHierarchies().size();
}
}
protected void populateDimension(OlapConnection connection, Catalog catalog, Cube cube, Dimension dimension, int ordinal, List<Row> rows) throws XmlaException, SQLException {
final NamedList<Hierarchy> hierarchies = dimension.getHierarchies();
for (Hierarchy hierarchy : filter(hierarchies, hierarchyNameCond, hierarchyUnameCond)) {
populateHierarchy(connection, catalog, cube, dimension, hierarchy,
ordinal + hierarchies.indexOf(hierarchy), rows);
}
}
protected void populateHierarchy(OlapConnection connection, Catalog catalog, Cube cube, Dimension dimension, Hierarchy hierarchy,
// Level level,
int ordinal, List<Row> rows) throws XmlaException, SQLException {
final CustomXmlaHandler.XmlaExtra extra = getExtra(connection);
String desc = hierarchy.getDescription();
if (desc == null) {
desc = cube.getName() + " Cube - " + getHierarchyName(hierarchy) + " Hierarchy";
}
Row row = new Row();
row.set(CatalogName.name, catalog.getName());
// row.set(SchemaName.name, cube.getSchema().getName());
row.set(CubeName.name, cube.getName());
row.set(DimensionUniqueName.name, dimension.getUniqueName());
row.set(HierarchyName.name, hierarchy.getName());
row.set(HierarchyUniqueName.name, hierarchy.getUniqueName());
// row.set(HierarchyGuid.name, "");
row.set(HierarchyCaption.name, hierarchy.getCaption());
row.set(DimensionType.name, getDimensionType(dimension));
// The number of members in the hierarchy. Because
// of the presence of multiple hierarchies, this number
// might not be the same as DIMENSION_CARDINALITY. This
// value can be an approximation of the real
// cardinality. Consumers should not assume that this
// value is accurate.
int cardinality = extra.getHierarchyCardinality(hierarchy);
row.set(HierarchyCardinality.name, cardinality);
row.set(DefaultMember.name, hierarchy.getDefaultMember().getUniqueName());
if (hierarchy.hasAll()) {
row.set(AllMember.name, hierarchy.getRootMembers().get(0).getUniqueName());
}
row.set(Description.name, desc);
// only support:
// MD_STRUCTURE_FULLYBALANCED (0)
// MD_STRUCTURE_RAGGEDBALANCED (1)
row.set(Structure.name, extra.getHierarchyStructure(hierarchy));
row.set(IsVirtual.name, false);
row.set(IsReadWrite.name, false);
// NOTE that SQL Server returns '0'
row.set(HierarchyUniqueSettings.name, 0);
row.set(DimensionUniqueSettings.name, 1);
row.set(DimensionIsVisible.name, dimension.isVisible());
row.set(HierarchyIsVisible.name, hierarchy.isVisible());
row.set(HierarchyOrdinal.name, ordinal);
// always true
row.set(DimensionIsShared.name, true);
// row.set(ParentChild.name, extra.isHierarchyParentChild(hierarchy));
if (deep) {
row.set(Levels.name,
new MdschemaLevelsRowset(wrapRequest(request, Olap4jUtil.mapOf(MdschemaLevelsRowset.CatalogName, catalog.getName(), MdschemaLevelsRowset.SchemaName, cube
.getSchema().getName(), MdschemaLevelsRowset.CubeName, cube.getName(), MdschemaLevelsRowset.DimensionUniqueName, dimension.getUniqueName(),
MdschemaLevelsRowset.HierarchyUniqueName, hierarchy.getUniqueName())), handler));
}
// row.set(InstanceSelection.name, 1);
row.set(HierarchyDisplayFolder.name, "");
row.set(GroupingBehaviors.name, 1);
row.set(HierarchyOrigin.name, 1);
row.set(StructureType.name, "Natural");
addRow(row, rows);
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
}
static class DiscoverDatasourcesRowset extends Rowset {
private static final Column DataSourceName = new Column("DataSourceName", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
"The name of the data source, such as FoodMart 2000.");
private static final Column DataSourceDescription = new Column("DataSourceDescription", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A description of the data source, as entered by the " + "publisher.");
private static final Column URL = new Column("URL", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "The unique path that shows where to invoke the XML for "
+ "Analysis methods for that data source.");
private static final Column DataSourceInfo = new Column("DataSourceInfo", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A string containing any additional information required to " + "connect to the data source. This can include the Initial "
+ "Catalog property or other information for the provider.\n" + "Example: \"Provider=MSOLAP;Data Source=Local;\"");
private static final Column ProviderName = new Column("ProviderName", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the provider behind the data source.\n" + "Example: \"MSDASQL\"");
private static final Column ProviderType = new Column("ProviderType", Type.EnumerationArray, Enumeration.PROVIDER_TYPE, Column.RESTRICTION, Column.REQUIRED,
Column.UNBOUNDED, "The types of data supported by the provider. May include one " + "or more of the following types. Example follows this " + "table.\n"
+ "TDP: tabular data provider.\n" + "MDP: multidimensional data provider.\n" + "DMP: data mining provider. A DMP provider implements the "
+ "OLE DB for Data Mining specification.");
private static final Column AuthenticationMode = new Column("AuthenticationMode", Type.EnumString, Enumeration.AUTHENTICATION_MODE, Column.RESTRICTION, Column.REQUIRED,
"Specification of what type of security mode the data source " + "uses. Values can be one of the following:\n"
+ "Unauthenticated: no user ID or password needs to be sent.\n" + "Authenticated: User ID and Password must be included in the "
+ "information required for the connection.\n" + "Integrated: the data source uses the underlying security to "
+ "determine authorization, such as Integrated Security " + "provided by Microsoft Internet Information Services (IIS).");
DiscoverDatasourcesRowset(RowsetDefinition definition, XmlaRequest request, CustomXmlaHandler handler) {
super(definition, request, handler);
}
public DiscoverDatasourcesRowset(XmlaRequest request, CustomXmlaHandler handler) {
this(DISCOVER_DATASOURCES,request,handler);
}
private static final Column[] columns = { DataSourceName, DataSourceDescription, URL, DataSourceInfo, ProviderName, ProviderType, AuthenticationMode, };
@Override
protected void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException, SQLException {
if (needConnection()) {
final CustomXmlaHandler.XmlaExtra extra = getExtra(connection);
for (Map<String, Object> ds : extra.getDataSources(connection)) {
Row row = new Row();
for (Column column : columns) {
Object val = ds.get(column.name);
row.set(column.name, val);
}
addRow(row, rows);
}
} else {
// using pre-configured discover datasources response
Row row = new Row();
Map<String, Object> map = this.handler.connectionFactory.getPreConfiguredDiscoverDatasourcesResponse();
for (Column column : columns) {
row.set(column.name, map.get(column.name));
}
addRow(row, rows);
}
}
@Override
protected boolean needConnection() {
// If the olap connection factory has a pre configured response,
// we don't need to connect to find metadata. This is good.
return this.handler.connectionFactory.getPreConfiguredDiscoverDatasourcesResponse() == null;
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
}
static class MdschemaLevelsRowset extends Rowset {
private final Util.Functor1<Boolean, Catalog> catalogCond;
private final Util.Functor1<Boolean, Schema> schemaNameCond;
private final Util.Functor1<Boolean, Cube> cubeNameCond;
private final Util.Functor1<Boolean, Dimension> dimensionUnameCond;
private final Util.Functor1<Boolean, Hierarchy> hierarchyUnameCond;
private final Util.Functor1<Boolean, Level> levelUnameCond;
private final Util.Functor1<Boolean, Level> levelNameCond;
MdschemaLevelsRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(MDSCHEMA_LEVELS, request, handler);
catalogCond = makeCondition(CATALOG_NAME_GETTER, CatalogName);
schemaNameCond = makeCondition(SCHEMA_NAME_GETTER, SchemaName);
cubeNameCond = makeCondition(ELEMENT_NAME_GETTER, CubeName);
dimensionUnameCond = makeCondition(ELEMENT_UNAME_GETTER, DimensionUniqueName);
hierarchyUnameCond = makeCondition(ELEMENT_UNAME_GETTER, HierarchyUniqueName);
levelUnameCond = makeCondition(ELEMENT_UNAME_GETTER, LevelUniqueName);
levelNameCond = makeCondition(ELEMENT_NAME_GETTER, LevelName);
}
public static final int MDLEVEL_TYPE_UNKNOWN = 0x0000;
public static final int MDLEVEL_TYPE_REGULAR = 0x0000;
public static final int MDLEVEL_TYPE_ALL = 0x0001;
public static final int MDLEVEL_TYPE_CALCULATED = 0x0002;
public static final int MDLEVEL_TYPE_TIME = 0x0004;
public static final int MDLEVEL_TYPE_RESERVED1 = 0x0008;
public static final int MDLEVEL_TYPE_TIME_YEARS = 0x0014;
public static final int MDLEVEL_TYPE_TIME_HALF_YEAR = 0x0024;
public static final int MDLEVEL_TYPE_TIME_QUARTERS = 0x0044;
public static final int MDLEVEL_TYPE_TIME_MONTHS = 0x0084;
public static final int MDLEVEL_TYPE_TIME_WEEKS = 0x0104;
public static final int MDLEVEL_TYPE_TIME_DAYS = 0x0204;
public static final int MDLEVEL_TYPE_TIME_HOURS = 0x0304;
public static final int MDLEVEL_TYPE_TIME_MINUTES = 0x0404;
public static final int MDLEVEL_TYPE_TIME_SECONDS = 0x0804;
public static final int MDLEVEL_TYPE_TIME_UNDEFINED = 0x1004;
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the catalog to which this level belongs.");
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the schema to which this level belongs.");
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "The name of the cube to which this level belongs.");
private static final Column DimensionUniqueName = new Column("DIMENSION_UNIQUE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
"The unique name of the dimension to which this level " + "belongs.");
private static final Column HierarchyUniqueName = new Column("HIERARCHY_UNIQUE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
"The unique name of the hierarchy.");
private static final Column LevelName = new Column("LEVEL_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "The name of the level.");
private static final Column LevelUniqueName = new Column("LEVEL_UNIQUE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
"The properly escaped unique name of the level.");
private static final Column LevelGuid = new Column("LEVEL_GUID", Type.UUID, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Level GUID.");
private static final Column LevelCaption = new Column("LEVEL_CAPTION", Type.String, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"A label or caption associated with the hierarchy.");
private static final Column LevelNumber = new Column("LEVEL_NUMBER", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"The distance of the level from the root of the hierarchy. " + "Root level is zero (0).");
private static final Column LevelCardinality = new Column("LEVEL_CARDINALITY", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"The number of members in the level. This value can be an " + "approximation of the real cardinality.");
private static final Column LevelType = new Column("LEVEL_TYPE", Type.Integer, null, Column.NOT_RESTRICTION, Column.REQUIRED, "Type of the level");
private static final Column CustomRollupSettings = new Column("CUSTOM_ROLLUP_SETTINGS", Type.Integer, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"A bitmap that specifies the custom rollup options.");
private static final Column LevelUniqueSettings = new Column("LEVEL_UNIQUE_SETTINGS", Type.Integer, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"A bitmap that specifies which columns contain unique values, " + "if the level only has members with unique names or keys.");
private static final Column LevelIsVisible = new Column("LEVEL_IS_VISIBLE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"A Boolean that indicates whether the level is visible.");
private static final Column Description = new Column("DESCRIPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A human-readable description of the level. NULL if no " + "description exists.");
private static final Column LevelKeyCardinality = new Column("LEVEL_KEY_CARDINALITY", Type.Short, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
private static final Column LevelOrigin = new Column("LEVEL_ORIGIN", Type.Short, null, Column.RESTRICTION, Column.OPTIONAL, "");
private static final Column LevelDbtype = new Column("LEVEL_DBTYPE", Type.Integer, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
private static final Column LevelOrderingProperty = new Column("LEVEL_ORDERING_PROPERTY", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
private static final Column LevelNameSqlColumnName = new Column("LEVEL_NAME_SQL_COLUMN_NAME", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
private static final Column LevelKeySqlColumnName = new Column("LEVEL_KEY_SQL_COLUMN_NAME", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
private static final Column LevelUniqueNameSqlColumnName = new Column("LEVEL_UNIQUE_NAME_SQL_COLUMN_NAME", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
private static final Column LevelAttributeHierarchyName = new Column("LEVEL_ATTRIBUTE_HIERARCHY_NAME", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException, SQLException {
for (Catalog catalog : catIter(connection, catNameCond(), catalogCond)) {
populateCatalog(connection, catalog, rows);
}
}
protected void populateCatalog(OlapConnection connection, Catalog catalog, List<Row> rows) throws XmlaException, SQLException {
for (Schema schema : filter(catalog.getSchemas(), schemaNameCond)) {
for (Cube cube : filteredCubes(schema, cubeNameCond)) {
populateCube(connection, catalog, cube, rows);
}
}
}
protected void populateCube(OlapConnection connection, Catalog catalog, Cube cube, List<Row> rows) throws XmlaException, SQLException {
for (Dimension dimension : filter(cube.getDimensions(), dimensionUnameCond)) {
populateDimension(connection, catalog, cube, dimension, rows);
}
}
protected void populateDimension(OlapConnection connection, Catalog catalog, Cube cube, Dimension dimension, List<Row> rows) throws XmlaException, SQLException {
for (Hierarchy hierarchy : filter(dimension.getHierarchies(), hierarchyUnameCond)) {
populateHierarchy(connection, catalog, cube, hierarchy, rows);
}
}
protected void populateHierarchy(OlapConnection connection, Catalog catalog, Cube cube, Hierarchy hierarchy, List<Row> rows) throws XmlaException, SQLException {
for (Level level : filter(hierarchy.getLevels(), levelUnameCond, levelNameCond)) {
outputLevel(connection, catalog, cube, hierarchy, level, rows);
}
}
/**
* Outputs a level.
*
* @param catalog
* Catalog name
* @param cube
* Cube definition
* @param hierarchy
* Hierarchy
* @param level
* Level
* @param rows
* List of rows to output to
* @return whether the level is visible
* @throws XmlaException
* If error occurs
*/
protected boolean outputLevel(OlapConnection connection, Catalog catalog, Cube cube, Hierarchy hierarchy, Level level, List<Row> rows) throws XmlaException, SQLException {
final CustomXmlaHandler.XmlaExtra extra = getExtra(connection);
String desc = level.getDescription();
if (desc == null) {
desc = cube.getName() + " Cube - " + getHierarchyName(hierarchy) + " Hierarchy - " + level.getName() + " Level";
}
Row row = new Row();
row.set(CatalogName.name, catalog.getName());
row.set(SchemaName.name, cube.getSchema().getName());
row.set(CubeName.name, cube.getName());
row.set(DimensionUniqueName.name, hierarchy.getDimension().getUniqueName());
row.set(HierarchyUniqueName.name, hierarchy.getUniqueName());
row.set(LevelName.name, level.getName());
row.set(LevelUniqueName.name, level.getUniqueName());
row.set(LevelCaption.name, level.getCaption());
row.set(LevelNumber.name, level.getDepth());
// Get level cardinality
// According to microsoft this is:
// "The number of members in the level."
int n = extra.getLevelCardinality(level);
row.set(LevelCardinality.name, n);
row.set(LevelType.name, getLevelType(level));
row.set(CustomRollupSettings.name, 0);
int uniqueSettings = 0;
if (level.getLevelType() == Level.Type.ALL) {
uniqueSettings |= 2;
}
if (extra.isLevelUnique(level)) {
uniqueSettings |= 1;
}
row.set(LevelUniqueSettings.name, uniqueSettings);
row.set(LevelIsVisible.name, level.isVisible());
row.set(LevelOrderingProperty.name, level.getName());
row.set(Description.name, desc);
row.set(LevelDbtype.name, 3);
row.set(LevelKeyCardinality.name, 1);
row.set(LevelOrigin.name, 2);
if(!level.getName().equalsIgnoreCase("(All)")){
String tmpName = level.getUniqueName();
String str = tmpName.substring(1);
tmpName = "[$".concat(str);
row.set(LevelNameSqlColumnName.name, "NAME("+tmpName+")");
row.set(LevelKeySqlColumnName.name, "KEY(" + tmpName+")");
row.set(LevelUniqueNameSqlColumnName.name, "(UNIQUENAME(" +tmpName + ")");
row.set(LevelAttributeHierarchyName.name, level.getName());
}
addRow(row, rows);
return true;
}
private int getLevelType(Level lev) {
int ret = 0;
switch (lev.getLevelType()) {
case ALL:
ret |= MDLEVEL_TYPE_ALL;
break;
case REGULAR:
ret |= MDLEVEL_TYPE_REGULAR;
break;
case TIME_YEARS:
ret |= MDLEVEL_TYPE_TIME_YEARS;
break;
case TIME_HALF_YEAR:
ret |= MDLEVEL_TYPE_TIME_HALF_YEAR;
break;
case TIME_QUARTERS:
ret |= MDLEVEL_TYPE_TIME_QUARTERS;
break;
case TIME_MONTHS:
ret |= MDLEVEL_TYPE_TIME_MONTHS;
break;
case TIME_WEEKS:
ret |= MDLEVEL_TYPE_TIME_WEEKS;
break;
case TIME_DAYS:
ret |= MDLEVEL_TYPE_TIME_DAYS;
break;
case TIME_HOURS:
ret |= MDLEVEL_TYPE_TIME_HOURS;
break;
case TIME_MINUTES:
ret |= MDLEVEL_TYPE_TIME_MINUTES;
break;
case TIME_SECONDS:
ret |= MDLEVEL_TYPE_TIME_SECONDS;
break;
case TIME_UNDEFINED:
ret |= MDLEVEL_TYPE_TIME_UNDEFINED;
break;
default:
ret |= MDLEVEL_TYPE_UNKNOWN;
}
return ret;
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
}
public static class MdschemaMeasuresRowset extends Rowset {
public static final int MDMEASURE_AGGR_UNKNOWN = 0;
public static final int MDMEASURE_AGGR_SUM = 1;
public static final int MDMEASURE_AGGR_COUNT = 2;
public static final int MDMEASURE_AGGR_MIN = 3;
public static final int MDMEASURE_AGGR_MAX = 4;
public static final int MDMEASURE_AGGR_AVG = 5;
public static final int MDMEASURE_AGGR_VAR = 6;
public static final int MDMEASURE_AGGR_STD = 7;
public static final int MDMEASURE_AGGR_CALCULATED = 127;
private final Util.Functor1<Boolean, Catalog> catalogCond;
private final Util.Functor1<Boolean, Schema> schemaNameCond;
private final Util.Functor1<Boolean, Cube> cubeNameCond;
private final Util.Functor1<Boolean, Measure> measureUnameCond;
private final Util.Functor1<Boolean, Measure> measureNameCond;
MdschemaMeasuresRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(MDSCHEMA_MEASURES, request, handler);
catalogCond = makeCondition(CATALOG_NAME_GETTER, CatalogName);
schemaNameCond = makeCondition(SCHEMA_NAME_GETTER, SchemaName);
cubeNameCond = makeCondition(ELEMENT_NAME_GETTER, CubeName);
measureNameCond = makeCondition(ELEMENT_NAME_GETTER, MeasureName);
measureUnameCond = makeCondition(ELEMENT_UNAME_GETTER, MeasureUniqueName);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the catalog to which this measure belongs.");
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the schema to which this measure belongs.");
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "The name of the cube to which this measure belongs.");
private static final Column CubeSource = new Column("CUBE_SOURCE", Type.UnsignedShort, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A bitmask with one of the following valid values: Cube, Dimension");
private static final Column MeasureName = new Column("MEASURE_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "The name of the measure.");
private static final Column MeasureUniqueName = new Column("MEASURE_UNIQUE_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "The Unique name of the measure.");
private static final Column MeasureNameSql = new Column("MEASURE_NAME_SQL_COLUMN_NAME", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The Unique name of the measure.");
private static final Column MeasureCaption = new Column("MEASURE_CAPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A label or caption associated with the measure.");
private static final Column MeasureGuid = new Column("MEASURE_GUID", Type.UUID, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Measure GUID.");
private static final Column MeasureAggregator = new Column("MEASURE_AGGREGATOR", Type.Integer, null, Column.NOT_RESTRICTION, Column.REQUIRED, "How a measure was derived.");
private static final Column DataType = new Column("DATA_TYPE", Type.UnsignedShort, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Data type of the measure.");
private static final Column NumericPrecision = new Column("NUMERIC_PRECISION", Type.UnsignedShort, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The maximum precision of the column for numeric data types " + "other than DBTYPE_VARNUMERIC.");
private static final Column MeasureIsVisible = new Column("MEASURE_IS_VISIBLE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A Boolean that always returns True. If the measure is not " + "visible, it will not be included in the schema rowset.");
private static final Column MeasureVisibility = new Column("MEASURE_VISIBILITY", Type.UnsignedShort, null, Column.RESTRICTION, Column.OPTIONAL,
"A Boolean that always returns True. If the measure is not " + "visible, it will not be included in the schema rowset.");
private static final Column LevelsList = new Column("LEVELS_LIST", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A string that always returns NULL. EXCEPT that SQL Server " + "returns non-null values!!!");
private static final Column MeasureUnqualifiedCaption = new Column("MEASURE_UNQUALIFIED_CAPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"");
private static final Column Expression = new Column("EXPRESSION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"");
private static final Column Description = new Column("DESCRIPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A human-readable description of the measure.");
private static final Column FormatString = new Column("DEFAULT_FORMAT_STRING", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The default format string for the measure.");
private static final Column NumericScale = new Column("NUMERIC_SCALE", Type.Short, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"The number of digits to the right of the decimal point for " + "DBTYPE_DECIMAL, DBTYPE_NUMERIC, DBTYPE_VARNUMERIC. " + "Otherwise, this is NULL.");
private static final Column MeasureUnits = new Column("MEASURE_UNITS", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"");
private static final Column MeasureGroupName = new Column("MEASUREGROUP_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "");
private static final Column MeasureDisplayFolder = new Column("MEASURE_DISPLAY_FOLDER", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException, SQLException {
for (Catalog catalog : catIter(connection, catNameCond(), catalogCond)) {
populateCatalog(connection, catalog, rows);
}
}
protected void populateCatalog(OlapConnection connection, Catalog catalog, List<Row> rows) throws XmlaException, SQLException {
// SQL Server actually includes the LEVELS_LIST row
StringBuilder buf = new StringBuilder(100);
for (Schema schema : filter(catalog.getSchemas(), schemaNameCond)) {
for (Cube cube : filteredCubes(schema, cubeNameCond)) {
buf.setLength(0);
int j = 0;
for (Dimension dimension : cube.getDimensions()) {
if (dimension.getDimensionType() == Dimension.Type.MEASURE) {
continue;
}
for (Hierarchy hierarchy : dimension.getHierarchies()) {
NamedList<Level> levels = hierarchy.getLevels();
Level lastLevel = levels.get(levels.size() - 1);
if (j++ > 0) {
buf.append(',');
}
buf.append(lastLevel.getUniqueName());
}
}
String levelListStr = buf.toString();
List<Member> calcMembers = new ArrayList<Member>();
for (Measure measure : filter(cube.getMeasures(), measureNameCond, measureUnameCond)) {
if (measure.isCalculated()) {
// Output calculated measures after stored
// measures.
calcMembers.add(measure);
} else {
populateMember(connection, catalog, measure, cube, levelListStr, rows);
}
}
for (Member member : calcMembers) {
populateMember(connection, catalog, member, cube, null, rows);
}
}
}
}
private void populateMember(OlapConnection connection, Catalog catalog, Member member, Cube cube, String levelListStr, List<Row> rows) throws SQLException {
Boolean visible = (Boolean) member.getPropertyValue(Property.StandardMemberProperty.$visible);
if (visible == null) {
visible = true;
}
if (!visible && !XmlaUtil.shouldEmitInvisibleMembers(request)) {
return;
}
String desc = member.getDescription();
if (desc == null) {
desc = cube.getName() + " Cube - " + member.getName() + " Member";
}
String formatString = (String) member.getPropertyValue(Property.StandardCellProperty.FORMAT_STRING);
if(formatString == null)
formatString = "
Row row = new Row();
row.set(CatalogName.name, catalog.getName());
row.set(CubeName.name, cube.getName());
row.set(MeasureName.name, member.getName());
row.set(MeasureUniqueName.name, member.getUniqueName());
row.set(MeasureUnqualifiedCaption.name, member.getUniqueName());
row.set(MeasureCaption.name, member.getCaption());
// row.set(MeasureGuid.name, "");
final CustomXmlaHandler.XmlaExtra extra = getExtra(connection);
row.set(MeasureAggregator.name, extra.getMeasureAggregator(member));
// DATA_TYPE DBType best guess is string
XmlaConstants.DBType dbType = XmlaConstants.DBType.WSTR;
String datatype = (String) member.getPropertyValue(Property.StandardCellProperty.DATATYPE);
String precision ="16";
if (datatype != null) {
if (datatype.equals("Integer")) {
dbType = XmlaConstants.DBType.I4;
precision = "10";
} else if (datatype.equals("Numeric")) {
dbType = XmlaConstants.DBType.R8;
precision = "16";
} else {
dbType = XmlaConstants.DBType.WSTR;
precision = null;
}
}
row.set(DataType.name, dbType.xmlaOrdinal());
row.set(NumericPrecision.name, precision);
row.set(NumericScale.name, -1);
row.set(MeasureIsVisible.name, true);
row.set(MeasureNameSql.name, member.getName());
// row.set(MeasureGroupName.name, member.getCaption());
// row.set(MeasureGroupName.name, "");
row.set(Description.name, desc);
row.set(MeasureDisplayFolder.name,"");
row.set(FormatString.name, formatString);
addRow(row, rows);
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
}
@SuppressWarnings("unused")
static class MdschemaMembersRowset extends Rowset {
private final Util.Functor1<Boolean, Catalog> catalogCond;
private final Util.Functor1<Boolean, Schema> schemaNameCond;
private final Util.Functor1<Boolean, Cube> cubeNameCond;
private final Util.Functor1<Boolean, Dimension> dimensionUnameCond;
private final Util.Functor1<Boolean, Hierarchy> hierarchyUnameCond;
private final Util.Functor1<Boolean, Member> memberNameCond;
private final Util.Functor1<Boolean, Member> memberUnameCond;
private final Util.Functor1<Boolean, Member> memberTypeCond;
MdschemaMembersRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(MDSCHEMA_MEMBERS, request, handler);
catalogCond = makeCondition(CATALOG_NAME_GETTER, CatalogName);
schemaNameCond = makeCondition(SCHEMA_NAME_GETTER, SchemaName);
cubeNameCond = makeCondition(ELEMENT_NAME_GETTER, CubeName);
dimensionUnameCond = makeCondition(ELEMENT_UNAME_GETTER, DimensionUniqueName);
hierarchyUnameCond = makeCondition(ELEMENT_UNAME_GETTER, HierarchyUniqueName);
memberNameCond = makeCondition(ELEMENT_NAME_GETTER, MemberName);
memberUnameCond = makeCondition(ELEMENT_UNAME_GETTER, MemberUniqueName);
memberTypeCond = makeCondition(MEMBER_TYPE_GETTER, MemberType);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the catalog to which this member belongs.");
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the schema to which this member belongs.");
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "Name of the cube to which this member belongs.");
private static final Column DimensionUniqueName = new Column("DIMENSION_UNIQUE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
"Unique name of the dimension to which this member belongs.");
private static final Column HierarchyUniqueName = new Column("HIERARCHY_UNIQUE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
"Unique name of the hierarchy. If the member belongs to more " + "than one hierarchy, there is one row for each hierarchy to " + "which it belongs.");
private static final Column LevelUniqueName = new Column("LEVEL_UNIQUE_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
" Unique name of the level to which the member belongs.");
private static final Column LevelNumber = new Column("LEVEL_NUMBER", Type.UnsignedInteger, null, Column.RESTRICTION, Column.REQUIRED,
"The distance of the member from the root of the hierarchy.");
private static final Column MemberOrdinal = new Column("MEMBER_ORDINAL", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"Ordinal number of the member. Sort rank of the member when " + "members of this dimension are sorted in their natural sort "
+ "order. If providers do not have the concept of natural " + "ordering, this should be the rank when sorted by " + "MEMBER_NAME.");
private static final Column MemberName = new Column("MEMBER_NAME", Type.String, null, Column.RESTRICTION, Column.REQUIRED, "Name of the member.");
private static final Column MemberUniqueName = new Column("MEMBER_UNIQUE_NAME", Type.StringSometimesArray, null, Column.RESTRICTION, Column.REQUIRED,
" Unique name of the member.");
private static final Column MemberType = new Column("MEMBER_TYPE", Type.Integer, null, Column.RESTRICTION, Column.REQUIRED, "Type of the member.");
private static final Column MemberGuid = new Column("MEMBER_GUID", Type.UUID, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Memeber GUID.");
private static final Column MemberCaption = new Column("MEMBER_CAPTION", Type.String, null, Column.RESTRICTION, Column.REQUIRED,
"A label or caption associated with the member.");
private static final Column ChildrenCardinality = new Column("CHILDREN_CARDINALITY", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"Number of children that the member has.");
private static final Column ParentLevel = new Column("PARENT_LEVEL", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"The distance of the member's parent from the root level of " + "the hierarchy.");
private static final Column ParentUniqueName = new Column("PARENT_UNIQUE_NAME", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"Unique name of the member's parent.");
private static final Column ParentCount = new Column("PARENT_COUNT", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"Number of parents that this member has.");
private static final Column TreeOp_ = new Column("TREE_OP", Type.Enumeration, Enumeration.TREE_OP, Column.RESTRICTION, Column.OPTIONAL, "Tree Operation");
private static final Column CubeSource = new Column("CUBE_SOURCE", Type.UnsignedShort, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A bitmask with one of the following valid values: Cube, Dimension");
/* Mondrian specified member properties. */
private static final Column Depth = new Column("DEPTH", Type.Integer, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "depth");
private static final Column MemberKey = new Column("MEMBER_KEY", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
private static final Column IsPlaceHolderMember = new Column("IS_PLACEHOLDERMEMBER", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
private static final Column IsDatamember = new Column("IS_DATAMEMBER", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException, SQLException {
for (Catalog catalog : catIter(connection, catNameCond(), catalogCond)) {
populateCatalog(connection, catalog, rows);
}
}
protected void populateCatalog(OlapConnection connection, Catalog catalog, List<Row> rows) throws XmlaException, SQLException {
for (Schema schema : filter(catalog.getSchemas(), schemaNameCond)) {
for (Cube cube : filteredCubes(schema, cubeNameCond)) {
if (isRestricted(MemberUniqueName)) {
outputUniqueMemberName(connection, catalog, cube, rows);
} else {
populateCube(connection, catalog, cube, rows);
}
}
}
}
protected void populateCube(OlapConnection connection, Catalog catalog, Cube cube, List<Row> rows) throws XmlaException, SQLException {
if (isRestricted(LevelUniqueName)) {
// Note: If the LEVEL_UNIQUE_NAME has been specified, then
// the dimension and hierarchy are specified implicitly.
String levelUniqueName = getRestrictionValueAsString(LevelUniqueName);
if (levelUniqueName == null) {
// The query specified two or more unique names
// which means that nothing will match.
return;
}
Level level = lookupLevel(cube, levelUniqueName);
if (level != null) {
// Get members of this level, without access control, but
// including calculated members.
List<Member> members = level.getMembers();
outputMembers(connection, members, catalog, cube, rows);
}
} else {
for (Dimension dimension : filter(cube.getDimensions(), dimensionUnameCond)) {
populateDimension(connection, catalog, cube, dimension, rows);
}
}
}
protected void populateDimension(OlapConnection connection, Catalog catalog, Cube cube, Dimension dimension, List<Row> rows) throws XmlaException, SQLException {
for (Hierarchy hierarchy : filter(dimension.getHierarchies(), hierarchyUnameCond)) {
populateHierarchy(connection, catalog, cube, hierarchy, rows);
}
}
protected void populateHierarchy(OlapConnection connection, Catalog catalog, Cube cube, Hierarchy hierarchy, List<Row> rows) throws XmlaException, SQLException {
if (isRestricted(LevelNumber)) {
int levelNumber = getRestrictionValueAsInt(LevelNumber);
if (levelNumber == -1) {
LOGGER.warn("RowsetDefinition.populateHierarchy: " + "LevelNumber invalid");
return;
}
NamedList<Level> levels = hierarchy.getLevels();
if (levelNumber >= levels.size()) {
LOGGER.warn("RowsetDefinition.populateHierarchy: " + "LevelNumber (" + levelNumber + ") is greater than number of levels (" + levels.size() + ") for hierarchy \""
+ hierarchy.getUniqueName() + "\"");
return;
}
Level level = levels.get(levelNumber);
List<Member> members = level.getMembers();
outputMembers(connection, members, catalog, cube, rows);
} else {
// At this point we get ALL of the members associated with
// the Hierarchy (rather than getting them one at a time).
// The value returned is not used at this point but they are
// now cached in the SchemaReader.
for (Level level : hierarchy.getLevels()) {
outputMembers(connection, level.getMembers(), catalog, cube, rows);
}
}
}
/**
* Returns whether a value contains all of the bits in a mask.
*/
private static boolean mask(int value, int mask) {
return (value & mask) == mask;
}
/**
* Adds a member to a result list and, depending upon the
* <code>treeOp</code> parameter, other relatives of the member. This
* method recursively invokes itself to walk up, down, or across the
* hierarchy.
*/
private void populateMember(OlapConnection connection, Catalog catalog, Cube cube, Member member, int treeOp, List<Row> rows) throws SQLException {
// Visit node itself.
if (mask(treeOp, TreeOp.SELF.xmlaOrdinal())) {
outputMember(connection, member, catalog, cube, rows);
}
// Visit node's siblings (not including itself).
if (mask(treeOp, TreeOp.SIBLINGS.xmlaOrdinal())) {
final List<Member> siblings;
final Member parent = member.getParentMember();
if (parent == null) {
siblings = member.getHierarchy().getRootMembers();
} else {
siblings = Olap4jUtil.cast(parent.getChildMembers());
}
for (Member sibling : siblings) {
if (sibling.equals(member)) {
continue;
}
populateMember(connection, catalog, cube, sibling, TreeOp.SELF.xmlaOrdinal(), rows);
}
}
// Visit node's descendants or its immediate children, but not both.
if (mask(treeOp, TreeOp.DESCENDANTS.xmlaOrdinal())) {
for (Member child : member.getChildMembers()) {
populateMember(connection, catalog, cube, child, TreeOp.SELF.xmlaOrdinal() | TreeOp.DESCENDANTS.xmlaOrdinal(), rows);
}
} else if (mask(treeOp, TreeOp.CHILDREN.xmlaOrdinal())) {
for (Member child : member.getChildMembers()) {
populateMember(connection, catalog, cube, child, TreeOp.SELF.xmlaOrdinal(), rows);
}
}
// Visit node's ancestors or its immediate parent, but not both.
if (mask(treeOp, TreeOp.ANCESTORS.xmlaOrdinal())) {
final Member parent = member.getParentMember();
if (parent != null) {
populateMember(connection, catalog, cube, parent, TreeOp.SELF.xmlaOrdinal() | TreeOp.ANCESTORS.xmlaOrdinal(), rows);
}
} else if (mask(treeOp, TreeOp.PARENT.xmlaOrdinal())) {
final Member parent = member.getParentMember();
if (parent != null) {
populateMember(connection, catalog, cube, parent, TreeOp.SELF.xmlaOrdinal(), rows);
}
}
}
protected ArrayList<Column> pruneRestrictions(ArrayList<Column> list) {
// If they've restricted TreeOp, we don't want to literally filter
// the result on TreeOp (because it's not an output column) or
// on MemberUniqueName (because TreeOp will have caused us to
// generate other members than the one asked for).
if (list.contains(TreeOp_)) {
list.remove(TreeOp_);
list.remove(MemberUniqueName);
}
return list;
}
private void outputMembers(OlapConnection connection, List<Member> members, final Catalog catalog, Cube cube, List<Row> rows) throws SQLException {
for (Member member : members) {
outputMember(connection, member, catalog, cube, rows);
}
}
private void outputUniqueMemberName(final OlapConnection connection, final Catalog catalog, Cube cube, List<Row> rows) throws SQLException {
final Object unameRestrictions = restrictions.get(MemberUniqueName.name);
List<String> list;
if (unameRestrictions instanceof String) {
list = Collections.singletonList((String) unameRestrictions);
} else {
list = (List<String>) unameRestrictions;
}
for (String memberUniqueName : list) {
final IdentifierNode identifierNode = IdentifierNode.parseIdentifier(memberUniqueName);
Member member = cube.lookupMember(identifierNode.getSegmentList());
if (member == null) {
return;
}
if (isRestricted(TreeOp_)) {
int treeOp = getRestrictionValueAsInt(TreeOp_);
if (treeOp == -1) {
return;
}
populateMember(connection, catalog, cube, member, treeOp, rows);
} else {
outputMember(connection, member, catalog, cube, rows);
}
}
}
private void outputMember(OlapConnection connection, Member member, final Catalog catalog, Cube cube, List<Row> rows) throws SQLException {
if (!memberNameCond.apply(member)) {
return;
}
if (!memberTypeCond.apply(member)) {
return;
}
getExtra(connection).checkMemberOrdinal(member);
// Check whether the member is visible, otherwise do not dump.
Boolean visible = (Boolean) member.getPropertyValue(Property.StandardMemberProperty.$visible);
if (visible == null) {
visible = true;
}
if (!visible && !XmlaUtil.shouldEmitInvisibleMembers(request)) {
return;
}
final Level level = member.getLevel();
final Hierarchy hierarchy = level.getHierarchy();
final Dimension dimension = hierarchy.getDimension();
int adjustedLevelDepth = level.getDepth();
Row row = new Row();
row.set(CatalogName.name, catalog.getName());
row.set(SchemaName.name, cube.getSchema().getName());
row.set(CubeName.name, cube.getName());
row.set(DimensionUniqueName.name, dimension.getUniqueName());
row.set(HierarchyUniqueName.name, hierarchy.getUniqueName());
row.set(LevelUniqueName.name, level.getUniqueName());
row.set(LevelNumber.name, adjustedLevelDepth);
row.set(MemberOrdinal.name, member.getOrdinal());
row.set(MemberName.name, member.getName());
row.set(MemberUniqueName.name, member.getUniqueName());
row.set(MemberType.name, member.getMemberType().ordinal());
// row.set(MemberGuid.name, "");
row.set(MemberCaption.name, member.getCaption());
row.set(ChildrenCardinality.name, member.getPropertyValue(Property.StandardMemberProperty.CHILDREN_CARDINALITY));
row.set(ChildrenCardinality.name, 100);
if (adjustedLevelDepth == 0) {
row.set(ParentLevel.name, 0);
} else {
row.set(ParentLevel.name, adjustedLevelDepth - 1);
final Member parentMember = member.getParentMember();
if (parentMember != null) {
row.set(ParentUniqueName.name, parentMember.getUniqueName());
}
}
row.set(ParentCount.name, member.getParentMember() == null ? 0 : 1);
row.set(Depth.name, member.getDepth());
row.set(MemberKey.name, member.getCaption());// Member_Key =
// Member_Caption?
row.set(IsPlaceHolderMember.name, false);
row.set(IsDatamember.name, false);
addRow(row, rows);
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
}
static class MdschemaSetsRowset extends Rowset {
private final Util.Functor1<Boolean, Catalog> catalogCond;
private final Util.Functor1<Boolean, Schema> schemaNameCond;
private final Util.Functor1<Boolean, Cube> cubeNameCond;
private final Util.Functor1<Boolean, NamedSet> setUnameCond;
private static final String GLOBAL_SCOPE = "1";
MdschemaSetsRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(MDSCHEMA_SETS, request, handler);
catalogCond = makeCondition(CATALOG_NAME_GETTER, CatalogName);
schemaNameCond = makeCondition(SCHEMA_NAME_GETTER, SchemaName);
cubeNameCond = makeCondition(ELEMENT_NAME_GETTER, CubeName);
setUnameCond = makeCondition(ELEMENT_UNAME_GETTER, SetName);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, true, true, null);
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, true, true, null);
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, true, true, null);
private static final Column SetName = new Column("SET_NAME", Type.String, null, true, true, null);
private static final Column Scope = new Column("SCOPE", Type.Integer, null, true, true, null);
private static final Column Description = new Column("DESCRIPTION", Type.String, null, false, true, "A human-readable description of the measure.");
private static final Column Expression = new Column("EXPRESSION", Type.String, null, false, true, "");
private static final Column Dimensions = new Column("DIMENSIONS", Type.String, null, false, true, "");
private static final Column SetCaption = new Column("SET_CAPTION", Type.String, null, true, true, null);
private static final Column SetDisplayFolder = new Column("SET_DISPLAY_FOLDER", Type.String, null, false, true, "");
private static final Column SetEvaluationContext = new Column("SET_EVALUATION_CONTEXT", Type.Integer, null, false, true, "");
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException, OlapException {
for (Catalog catalog : catIter(connection, catNameCond(), catalogCond)) {
processCatalog(connection, catalog, rows);
}
}
private void processCatalog(OlapConnection connection, Catalog catalog, List<Row> rows) throws OlapException {
for (Schema schema : filter(catalog.getSchemas(), schemaNameCond)) {
for (Cube cube : filter(sortedCubes(schema), cubeNameCond)) {
populateNamedSets(cube, catalog, rows);
}
}
}
private void populateNamedSets(Cube cube, Catalog catalog, List<Row> rows) {
for (NamedSet namedSet : filter(cube.getSets(), setUnameCond)) {
Row row = new Row();
Writer writer = new StringWriter();
ParseTreeWriter parseTreeWriter = new ParseTreeWriter(writer);
ParseTreeNode node = namedSet.getExpression();
node.unparse(parseTreeWriter);
//String expression = writer.toString();
// expression = expression.substring(1, expression.toCharArray().length - 1);
final String expression = "[Product].[Category].&[1]";
row.set(CatalogName.name, catalog.getName());
// row.set(SchemaName.name, cube.getSchema().getName());
row.set(CubeName.name, cube.getName());
row.set(SetName.name, namedSet.getUniqueName().substring(1, namedSet.getUniqueName().length() -1));
row.set(Scope.name, GLOBAL_SCOPE);
row.set(Description.name, namedSet.getDescription());
row.set(Expression.name, expression);
row.set(Dimensions.name, "[Store].[USA].[CA]");
row.set(SetCaption.name, namedSet.getCaption());
row.set(SetDisplayFolder.name, "");
row.set(SetEvaluationContext.name, 2);
addRow(row, rows);
}
}
}
static class MdschemaKpisRowset extends Rowset {
MdschemaKpisRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(MDSCHEMA_KPIS, request, handler);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "");
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "");
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "");
private static final Column KpiName = new Column("KPI_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "");
private static final Column CubeSource = new Column("CUBE_SOURCE", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "");
private static final Column Scope = new Column("SCOPE", Type.Integer, null, Column.RESTRICTION, Column.OPTIONAL, "");
@Override
protected void populateImpl(XmlaResponse response, OlapConnection connection, List rows) throws XmlaException, SQLException {
}
}
static class MdschemaMeasureGroupRowset extends Rowset {
MdschemaMeasureGroupRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(MDSCHEMA_MEASUREGROUPS, request, handler);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, true, true, null);
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, true, true, null);
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, true, false, null);
private static final Column MeasureGroupName = new Column("MEASUREGROUP_NAME", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
private static final Column Description = new Column("DESCRIPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A human-readable description of the measure.");
private static final Column IsWriteEnabled = new Column("IS_WRITE_ENABLED", Type.Boolean, null, Column.RESTRICTION, Column.OPTIONAL,
"The unique name of the dimension.");
private static final Column MeasureGroupCaption = new Column("MEASUREGROUP_CAPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
@Override
protected void populateImpl(XmlaResponse response, OlapConnection connection, List rows) throws XmlaException, SQLException {
}
}
static class MdschemaMeasureGroupDimensionRowset extends Rowset {
MdschemaMeasureGroupDimensionRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(MDSCHEMA_MEASUREGROUP_DIMENSIONS, request, handler);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, true, true, null);
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, true, true, null);
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, true, false, null);
private static final Column MeasureGroupName = new Column("MEASUREGROUP_NAME", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
private static final Column MeasureGroupCardinality = new Column("MEASUREGROUP_CARDINALITY", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
private static final Column DimensionUniqueName = new Column("DIMENSION_UNIQUE_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The unique name of the dimension.");
private static final Column DimensionCardinality = new Column("DIMENSION_CARDINALITY", Type.UnsignedInteger, null, Column.NOT_RESTRICTION, Column.REQUIRED,
"The number of members in the key attribute.");
private static final Column DimensionIsVisible = new Column("DIMENSION_IS_VISIBLE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Always TRUE.");
private static final Column DimensionISFactDimension = new Column("DIMENSION_IS_FACT_DIMENSION", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Always TRUE.");
private static final Column DimensionPath = new Column("DIMENSION_PATH", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Always TRUE.");
private static final Column DimensionGranularity = new Column("DIMENSION_GRANULARITY", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Always TRUE.");
@Override
protected void populateImpl(XmlaResponse response, OlapConnection connection, List rows) throws XmlaException, SQLException {
// TODO Auto-generated method stub
}
}
@SuppressWarnings("unused")
static class MdschemaPropertiesRowset extends Rowset {
private Util.Functor1<Boolean, Catalog> catalogCond;
private Util.Functor1<Boolean, Schema> schemaNameCond;
private Util.Functor1<Boolean, Cube> cubeNameCond;
private Util.Functor1<Boolean, Dimension> dimensionUnameCond;
private Util.Functor1<Boolean, Hierarchy> hierarchyUnameCond;
private Util.Functor1<Boolean, Property> propertyNameCond;
private Util.Functor1<Boolean, Level> levelNameCond;
MdschemaPropertiesRowset(XmlaRequest request, CustomXmlaHandler handler) {
super(MDSCHEMA_PROPERTIES, request, handler);
catalogCond = makeCondition(CATALOG_NAME_GETTER, CatalogName);
schemaNameCond = makeCondition(SCHEMA_NAME_GETTER, SchemaName);
cubeNameCond = makeCondition(ELEMENT_NAME_GETTER, CubeName);
dimensionUnameCond = makeCondition(ELEMENT_UNAME_GETTER, DimensionUniqueName);
hierarchyUnameCond = makeCondition(ELEMENT_UNAME_GETTER, HierarchyUniqueName);
levelNameCond = makeCondition(ELEMENT_NAME_GETTER,LevelUniqueName);
propertyNameCond = makeCondition(ELEMENT_NAME_GETTER, PropertyName);
}
private static final Column CatalogName = new Column("CATALOG_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "The name of the database.");
private static final Column SchemaName = new Column("SCHEMA_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The name of the schema to which this property belongs.");
private static final Column CubeName = new Column("CUBE_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "The name of the cube.");
private static final Column DimensionUniqueName = new Column("DIMENSION_UNIQUE_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The unique name of the dimension.");
private static Column HierarchyUniqueName = new Column("HIERARCHY_UNIQUE_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The unique name of the hierarchy.");
private static final Column LevelUniqueName = new Column("LEVEL_UNIQUE_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The unique name of the level to which this property belongs.");
// According to MS this should not be nullable
private static final Column MemberUniqueName = new Column("MEMBER_UNIQUE_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL,
"The unique name of the member to which the property belongs.");
private static final Column PropertyName = new Column("PROPERTY_NAME", Type.String, null, Column.RESTRICTION, Column.OPTIONAL, "Name of the property.");
private static final Column PropertyType = new Column("PROPERTY_TYPE", Type.Short, null, Column.RESTRICTION, Column.OPTIONAL,
"A bitmap that specifies the type of the property");
private static final Column PropertyCaption = new Column("PROPERTY_CAPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A label or caption associated with the property, used " + "primarily for display purposes.");
private static final Column DataType = new Column("DATA_TYPE", Type.UnsignedShort, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "Data type of the property.");
private static final Column NumericPrecission = new Column("NUMERIC_PRECISION", Type.UnsignedShort, null, Column.RESTRICTION, Column.OPTIONAL, "Data type of the property.");
private static final Column PropertyContentType = new Column("PROPERTY_CONTENT_TYPE", Type.Short, null, Column.RESTRICTION, Column.OPTIONAL, "The type of the property.");
private static final Column PropertyOrigin = new Column("PROPERTY_ORIGIN", Type.UnsignedShort, null, Column.RESTRICTION, Column.OPTIONAL, "The type of the property.");
private static final Column PropertyAttributeHierarchyName = new Column("PROPERTY_ATTRIBUTE_HIERARCHY_NAME", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, ".");
private static final Column PropertyCardinality = new Column("PROPERTY_CARDINALITY", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL, ".");
private static final Column Description = new Column("DESCRIPTION", Type.String, null, Column.NOT_RESTRICTION, Column.OPTIONAL,
"A human-readable description of the measure.");
private static final Column PropertyIsVisible = new Column("PROPERTY_IS_VISIBLE", Type.Boolean, null, Column.NOT_RESTRICTION, Column.OPTIONAL, "");
private static final Column PropertyVisibility = new Column("PROPERTY_VISIBILITY", Type.Boolean, null, Column.RESTRICTION, Column.OPTIONAL, "");
private static final Column LevelOrderingProperty = new Column("LEVEL_ORDERING_PROPERTY", Type.String,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column LevelDbtype = new Column("LEVEL_DBTYPE", Type.Integer,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column LevelNameSqlColumnName = new Column("LEVEL_NAME_SQL_COLUMN_NAME", Type.String,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column LevelKeySqlColumnName = new Column("LEVEL_KEY_SQL_COLUMN_NAME", Type.String,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column LevelUniqueNameSqlColumnName = new Column("LEVEL_UNIQUE_NAME_SQL_COLUMN_NAME", Type.String,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column LevelAttributeHierarchyName = new Column("LEVEL_ATTRIBUTE_HIERARCHY_NAME", Type.String,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column LevelKeyCardinality = new Column("LEVEL_KEY_CARDINALITY", Type.UnsignedShort,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column LevelOrign = new Column("LEVEL_ORIGIN", Type.UnsignedShort,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column CubeSource = new Column("CUBE_SOURCE", Type.UnsignedShort,null, Column.RESTRICTION, Column.OPTIONAL,"");
private static final Column CharacterMaximumLength = new Column("CHARACTER_MAXIMUM_LENGTH", Type.UnsignedInteger,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column CharacterOctetLength = new Column("CHARACTER_OCTET_LENGTH", Type.UnsignedInteger,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column NumericPrecision = new Column("NUMERIC_PRECISION", Type.UnsignedShort,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column NumericScale = new Column("NUMERIC_SCALE", Type.UnsignedShort,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column SqlColumnName = new Column("SQL_COLUMN_NAME", Type.String,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column Language = new Column("LANGUAGE", Type.UnsignedShort,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
private static final Column MimeType = new Column("MIME_TYPE", Type.String,null, Column.NOT_RESTRICTION, Column.OPTIONAL,"");
protected boolean needConnection() {
return false;
}
public void populateImpl(XmlaResponse response, OlapConnection connection, List<Row> rows) throws XmlaException, SQLException {
// Default PROPERTY_TYPE is MDPROP_MEMBER.
final List<String> list = (List<String>) restrictions.get(PropertyType.name);
Set<Property.TypeFlag> typeFlags;
if (list == null) {
typeFlags = Olap4jUtil.enumSetOf(Property.TypeFlag.MEMBER);
} else {
typeFlags = Property.TypeFlag.getDictionary().forMask(Integer.valueOf(list.get(0)));
}
for (Property.TypeFlag typeFlag : typeFlags) {
switch (typeFlag) {
case MEMBER:
populateMember(rows);
break;
case CELL:
populateCell(rows);
break;
case SYSTEM:
case BLOB:
default:
break;
}
}
}
private void populateCell(List<Row> rows) {
List<Row> tmpRow = new ArrayList<Row>(12);
for(int i=0;i<12;i++){
tmpRow.add(new Row());
}
for (Property.StandardCellProperty property : Property.StandardCellProperty.values()) {
if(property.name().equals("VALUE")|| property.name().equals("FORMAT_STRING")||property.name().equals("BACK_COLOR")||property.name().equals("FORE_COLOR")||
property.name().equals("FONT_NAME")||property.name().equals("FONT_SIZE")||property.name().equals("FONT_FLAGS")
||property.name().equals("LANGUAGE")||property.name().equals("CELL_ORDINAL") || property.name().equals("FORMATTED_VALUE")
|| property.name().equals("ACTION_TYPE")||property.name().equals("UPDATEABLE")){
Row row = new Row();
row.set(PropertyType.name, Property.TypeFlag.getDictionary().toMask(property.getType()));
row.set(PropertyName.name, property.name());
row.set(PropertyCaption.name, property.getCaption());
if(property.name().equals("BACK_COLOR")){
row.set(DataType.name, 19);
}
else if(property.name().equals("FORE_COLOR")){
row.set(DataType.name, 19);
}
else if(property.name().equals("ACTION_TYPE")){
row.set(DataType.name, 19);
}
else if(property.name().equals("FONT_SIZE")){
row.set(DataType.name, 18);
}
else if(property.name().equals("FONT_FLAGS")){
row.set(DataType.name, 3);
}else{
row.set(DataType.name, property.getDatatype().xmlaOrdinal());
}
// row.set(PropertyOrigin.name, "6");
// row.set(PropertyIsVisible.name, true);
if(property.name().equals("VALUE"))
tmpRow.set(0, row);
else if(property.name().equals("FORMAT_STRING"))
tmpRow.set(1, row);
else if(property.name().equals("BACK_COLOR"))
tmpRow.set(2, row);
else if(property.name().equals("FORE_COLOR"))
tmpRow.set(3, row);
else if(property.name().equals("FONT_NAME"))
tmpRow.set(4, row);
else if(property.name().equals("FONT_SIZE"))
tmpRow.set(5, row);
else if(property.name().equals("FONT_FLAGS"))
tmpRow.set(6, row);
else if(property.name().equals("LANGUAGE"))
tmpRow.set(7, row);
else if(property.name().equals("CELL_ORDINAL"))
tmpRow.set(8, row);
else if(property.name().equals("FORMATTED_VALUE"))
tmpRow.set(9, row);
else if(property.name().equals("ACTION_TYPE"))
tmpRow.set(10, row);
else if(property.name().equals("UPDATEABLE"))
tmpRow.set(11, row);
}
}
for(Row r: tmpRow){
addRow(r, rows);
}
}
private void populateMember(List<Row> rows) throws SQLException {
OlapConnection connection = handler.getConnection(request, Collections.<String, String> emptyMap());
for (Catalog catalog : catIter(connection, catNameCond(), catalogCond)) {
populateCatalog(catalog, rows);
}
}
protected void populateCatalog(Catalog catalog, List<Row> rows) throws XmlaException, SQLException {
for (Schema schema : filter(catalog.getSchemas(), schemaNameCond)) {
for (Cube cube : filteredCubes(schema, cubeNameCond)) {
populateCube(catalog, cube, rows);
}
}
}
protected void populateCube(Catalog catalog, Cube cube, List<Row> rows) throws XmlaException, SQLException {
if (cube instanceof SharedDimensionHolderCube) {
return;
}
if (isRestricted(LevelUniqueName)) {
// Note: If the LEVEL_UNIQUE_NAME has been specified, then
// the dimension and hierarchy are specified implicitly.
String levelUniqueName = getRestrictionValueAsString(LevelUniqueName);
if (levelUniqueName == null) {
// The query specified two or more unique names
// which means that nothing will match.
return;
}
Level level = lookupLevel(cube, levelUniqueName);
if(!levelUniqueName.contains("].[") && levelUniqueName.startsWith("[") && levelUniqueName.endsWith("]")){
hierarchyUnameCond = makeCondition(ELEMENT_UNAME_GETTER, HierarchyUniqueName);
for (Dimension dimension : filter(cube.getDimensions(), dimensionUnameCond)) {
populateDimension(catalog, cube, dimension, rows);
}
return;
}
else if (level == null) {
return;
}
populateLevel(catalog, cube, level, rows);
} else {
for (Dimension dimension : filter(cube.getDimensions(), dimensionUnameCond)) {
populateDimension(catalog, cube, dimension, rows);
}
}
}
private void populateDimension(Catalog catalog, Cube cube, Dimension dimension, List<Row> rows) throws SQLException {
for (Hierarchy hierarchy : filter(dimension.getHierarchies(), hierarchyUnameCond)) {
populateHierarchy(catalog, cube, hierarchy, rows);
}
}
private void populateHierarchy(Catalog catalog, Cube cube, Hierarchy hierarchy, List<Row> rows) throws SQLException {
for (Level level : hierarchy.getLevels()) {
populateLevel(catalog, cube, level, rows);
}
}
private void populateLevel(Catalog catalog, Cube cube, Level level, List<Row> rows) throws SQLException {
final CustomXmlaHandler.XmlaExtra extra = getExtra(catalog.getMetaData().getConnection());
for (Property property : filter(extra.getLevelProperties(level), propertyNameCond)) {
if (extra.isPropertyInternal(property)) {
continue;
}
outputProperty(property, catalog, cube, level, rows);
}
}
private void outputProperty(Property property, Catalog catalog, Cube cube, Level level, List<Row> rows) {
Hierarchy hierarchy = level.getHierarchy();
Dimension dimension = hierarchy.getDimension();
String propertyName = property.getName();
Row row = new Row();
row.set(CatalogName.name, catalog.getName());
row.set(CubeName.name, cube.getName());
row.set(DimensionUniqueName.name, dimension.getUniqueName());
row.set(HierarchyUniqueName.name, hierarchy.getUniqueName());
row.set(LevelUniqueName.name, level.getUniqueName());
row.set(PropertyName.name, propertyName);
row.set(PropertyCaption.name, property.getCaption());
// Only member properties now
row.set(PropertyType.name, 1);
row.set(PropertyContentType.name, Property.ContentType.REGULAR.xmlaOrdinal());
XmlaConstants.DBType dbType = getDBTypeFromProperty(property);
row.set(DataType.name, 0);
row.set(PropertyOrigin.name, 1);
String desc = cube.getName() + " Cube - " + getHierarchyName(hierarchy) + " Hierarchy - " + level.getName() + " Level - " + property.getName() + " Property";
row.set(Description.name, desc);
row.set(PropertyCardinality.name, "MANY");
row.set(PropertyAttributeHierarchyName.name, propertyName);
row.set(PropertyIsVisible.name, true);
addRow(row, rows);
}
protected void setProperty(PropertyDefinition propertyDef, String value) {
switch (propertyDef) {
case Content:
break;
default:
super.setProperty(propertyDef, value);
}
}
}
public static final Util.Functor1<String, Catalog> CATALOG_NAME_GETTER = new Util.Functor1<String, Catalog>() {
public String apply(Catalog catalog) {
return catalog.getName();
}
};
public static final Util.Functor1<String, Schema> SCHEMA_NAME_GETTER = new Util.Functor1<String, Schema>() {
public String apply(Schema schema) {
return schema.getName();
}
};
public static final Util.Functor1<String, MetadataElement> ELEMENT_NAME_GETTER = new Util.Functor1<String, MetadataElement>() {
public String apply(MetadataElement element) {
return element.getName();
}
};
public static final Util.Functor1<String, MetadataElement> ELEMENT_UNAME_GETTER = new Util.Functor1<String, MetadataElement>() {
public String apply(MetadataElement element) {
return element.getUniqueName();
}
};
public static final Util.Functor1<Member.Type, Member> MEMBER_TYPE_GETTER = new Util.Functor1<Member.Type, Member>() {
public Member.Type apply(Member member) {
return member.getMemberType();
}
};
public static final Util.Functor1<String, PropertyDefinition> PROPDEF_NAME_GETTER = new Util.Functor1<String, PropertyDefinition>() {
public String apply(PropertyDefinition property) {
return property.name();
}
};
static void serialize(StringBuilder buf, Collection<String> strings) {
int k = 0;
for (String name : Util.sort(strings)) {
if (k++ > 0) {
buf.append(',');
}
buf.append(name);
}
}
private static Level lookupLevel(Cube cube, String levelUniqueName) {
for (Dimension dimension : cube.getDimensions()) {
for (Hierarchy hierarchy : dimension.getHierarchies()) {
for (Level level : hierarchy.getLevels()) {
if (level.getUniqueName().equals(levelUniqueName)) {
return level;
}
}
}
}
return null;
}
static Iterable<Cube> sortedCubes(Schema schema) throws OlapException {
return Util.sort(schema.getCubes(), new Comparator<Cube>() {
public int compare(Cube o1, Cube o2) {
return o1.getName().compareTo(o2.getName());
}
});
}
static Iterable<Cube> filteredCubes(final Schema schema, Util.Functor1<Boolean, Cube> cubeNameCond) throws OlapException {
final Iterable<Cube> iterable = filter(sortedCubes(schema), cubeNameCond);
if (!cubeNameCond.apply(new SharedDimensionHolderCube(schema))) {
return iterable;
}
return Composite.of(Collections.singletonList(new SharedDimensionHolderCube(schema)), iterable);
}
private static String getHierarchyName(Hierarchy hierarchy) {
String hierarchyName = hierarchy.getName();
if (MondrianProperties.instance().SsasCompatibleNaming.get() && !hierarchyName.equals(hierarchy.getDimension().getName())) {
hierarchyName = hierarchy.getDimension().getName() + "." + hierarchyName;
}
return hierarchyName;
}
private static XmlaRequest wrapRequest(XmlaRequest request, Map<Column, String> map) {
final Map<String, Object> restrictionsMap = new HashMap<String, Object>(request.getRestrictions());
for (Map.Entry<Column, String> entry : map.entrySet()) {
restrictionsMap.put(entry.getKey().name, Collections.singletonList(entry.getValue()));
}
return new DelegatingXmlaRequest(request) {
@Override
public Map<String, Object> getRestrictions() {
return restrictionsMap;
}
};
}
/**
* Returns an iterator over the catalogs in a connection, setting the
* connection's catalog to each successful catalog in turn.
*
* @param connection
* Connection
* @param conds
* Zero or more conditions to be applied to catalogs
* @return Iterator over catalogs
*/
public static Iterable<Catalog> catIter(final OlapConnection connection, final Util.Functor1<Boolean, Catalog>... conds) {
return new Iterable<Catalog>() {
public Iterator<Catalog> iterator() {
try {
return new Iterator<Catalog>() {
final Iterator<Catalog> catalogIter = Util.filter(connection.getOlapCatalogs(), conds).iterator();
public boolean hasNext() {
return catalogIter.hasNext();
}
public Catalog next() {
Catalog catalog = catalogIter.next();
try {
connection.setCatalog(catalog.getName());
} catch (SQLException e) {
throw new RuntimeException(e);
}
return catalog;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
} catch (OlapException e) {
throw new RuntimeException("Failed to obtain a list of catalogs form the connection object.", e);
}
}
};
}
public static Iterable<Catalog> catIter(final OlapConnection connection) {
return new Iterable<Catalog>() {
public Iterator<Catalog> iterator() {
try {
return new Iterator<Catalog>() {
final Iterator<Catalog> catalogIter = Util.filter(connection.getOlapCatalogs()).iterator();
public boolean hasNext() {
return catalogIter.hasNext();
}
public Catalog next() {
Catalog catalog = catalogIter.next();
try {
connection.setCatalog(catalog.getName());
} catch (SQLException e) {
throw new RuntimeException(e);
}
return catalog;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
} catch (OlapException e) {
throw new RuntimeException("Failed to obtain a list of catalogs form the connection object.", e);
}
}
};
}
private static class DelegatingXmlaRequest implements XmlaRequest {
protected final XmlaRequest request;
public DelegatingXmlaRequest(XmlaRequest request) {
this.request = request;
}
public XmlaConstants.Method getMethod() {
return request.getMethod();
}
public Map<String, String> getProperties() {
return request.getProperties();
}
public Map<String, Object> getRestrictions() {
return request.getRestrictions();
}
public String getStatement() {
return request.getStatement();
}
public String getRoleName() {
return request.getRoleName();
}
public String getRequestType() {
return request.getRequestType();
}
public boolean isDrillThrough() {
return request.isDrillThrough();
}
public String getUsername() {
return request.getUsername();
}
public String getPassword() {
return request.getPassword();
}
public String getSessionId() {
return request.getSessionId();
}
}
/**
* Dummy implementation of {@link Cube} that holds all shared dimensions in a
* given schema. Less error-prone than requiring all generator code to cope
* with a null Cube.
*/
private static class SharedDimensionHolderCube implements Cube {
private final Schema schema;
public SharedDimensionHolderCube(Schema schema) {
this.schema = schema;
}
public Schema getSchema() {
return schema;
}
public NamedList<Dimension> getDimensions() {
try {
return schema.getSharedDimensions();
} catch (OlapException e) {
throw new RuntimeException(e);
}
}
public NamedList<Hierarchy> getHierarchies() {
final NamedList<Hierarchy> hierarchyList = new ArrayNamedListImpl<Hierarchy>() {
private static final long serialVersionUID = -5177781397505125769L;
public String getName(Object hierarchy) {
return ((Hierarchy) hierarchy).getName();
}
};
for (Dimension dimension : getDimensions()) {
hierarchyList.addAll(dimension.getHierarchies());
}
return hierarchyList;
}
public List<Measure> getMeasures() {
return Collections.emptyList();
}
public NamedList<NamedSet> getSets() {
throw new UnsupportedOperationException();
}
public Collection<Locale> getSupportedLocales() {
throw new UnsupportedOperationException();
}
public Member lookupMember(List<IdentifierSegment> identifierSegments) throws org.olap4j.OlapException {
throw new UnsupportedOperationException();
}
public List<Member> lookupMembers(Set<Member.TreeOp> treeOps, List<IdentifierSegment> identifierSegments) throws org.olap4j.OlapException {
throw new UnsupportedOperationException();
}
public boolean isDrillThroughEnabled() {
return false;
}
public String getName() {
return "";
}
public String getUniqueName() {
return "";
}
public String getCaption() {
return "";
}
public String getDescription() {
return "";
}
public boolean isVisible() {
return false;
}
}
}
// End RowsetDefinition.java
|
package de.lmu.ifi.dbs.elki.database;
import de.lmu.ifi.dbs.elki.data.DatabaseObject;
import de.lmu.ifi.dbs.elki.data.NumberVector;
import de.lmu.ifi.dbs.elki.utilities.ClassGenericsUtil;
import de.lmu.ifi.dbs.elki.utilities.ExceptionMessages;
import de.lmu.ifi.dbs.elki.utilities.UnableToComplyException;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.AbstractParameterizable;
import de.lmu.ifi.dbs.elki.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.elki.utilities.pairs.Pair;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/**
* Provides a mapping for associations based on a Hashtable and functions to get
* the next usable ID for insertion, making IDs reusable after deletion of the
* entry.
*
* @author Arthur Zimek
* @param <O> the type of DatabaseObject as element of the database
*/
public abstract class AbstractDatabase<O extends DatabaseObject> extends AbstractParameterizable implements Database<O> {
/**
* Map to hold global associations.
*/
private final Associations globalAssociations;
/**
* Map to hold association maps.
*/
private final AssociationMaps associations;
/**
* Counter to provide a new Integer id.
*/
private int counter;
/**
* Provides a list of reusable ids.
*/
private List<Integer> reusableIDs;
/**
* Map to hold the objects of the database.
*/
private Map<Integer, O> content;
/**
* Holds the listener of this database.
*/
protected List<DatabaseListener> listenerList = new ArrayList<DatabaseListener>();
/**
* Provides an abstract database including a mapping for associations based on
* a Hashtable and functions to get the next usable ID for insertion, making
* IDs reusable after deletion of the entry. Make sure to delete any
* associations when deleting an entry (e.g. by calling
* {@link #deleteAssociations(Integer) deleteAssociations(id)}).
*/
protected AbstractDatabase() {
super();
content = new Hashtable<Integer, O>();
associations = new AssociationMaps();
globalAssociations = new Associations();
counter = 0;
reusableIDs = new ArrayList<Integer>();
}
public void insert(List<Pair<O, Associations>> objectsAndAssociationsList) throws UnableToComplyException {
for(Pair<O, Associations> objectAndAssociations : objectsAndAssociationsList) {
insert(objectAndAssociations);
}
}
/**
* @throws UnableToComplyException if database reached limit of storage
* capacity
*/
public Integer insert(Pair<O, Associations> objectAndAssociations) throws UnableToComplyException {
O object = objectAndAssociations.getFirst();
// insert object
Integer id = setNewID(object);
content.put(id, object);
// insert associations
Associations associations = objectAndAssociations.getSecond();
setAssociations(id, associations);
// notify listeners
fireObjectInserted(id);
return id;
}
public void delete(O object) {
for(Integer id : content.keySet()) {
if(content.get(id).equals(object)) {
delete(id);
}
}
}
public O delete(Integer id) {
O object = content.remove(id);
restoreID(id);
deleteAssociations(id);
// notify listeners
fireObjectRemoved(id);
return object;
}
public final int size() {
return content.size();
}
public final O get(Integer id) {
return content.get(id);
}
/**
* Returns an iterator iterating over all keys of the database.
*
* @return an iterator iterating over all keys of the database
*/
public final Iterator<Integer> iterator() {
return content.keySet().iterator();
}
public <T> void associate(final AssociationID<T> associationID, final Integer objectID, final T association) {
try {
associationID.getType().cast(association);
}
catch(ClassCastException e) {
throw new IllegalArgumentException("Expected class: " + associationID.getType() + ", found " + association.getClass());
}
if(!associations.containsKey(associationID)) {
associations.put(associationID, new Hashtable<Integer, T>());
}
associations.get(associationID).put(objectID, association);
}
/**
* Associates a global association in a certain relation to the database.
*
* @param associationID the id of the association, respectively the name of
* the relation
* @param association the association to be associated with the database
* @throws ClassCastException if the association cannot be cast as the class
* that is specified by the associationID
*/
public <T> void associateGlobally(AssociationID<T> associationID, T association) throws ClassCastException {
try {
associationID.getType().cast(association);
}
catch(ClassCastException e) {
throw new IllegalArgumentException("Expected class: " + associationID.getType() + ", found " + association.getClass());
}
globalAssociations.put(associationID, association);
}
public <T> T getAssociation(final AssociationID<T> associationID, final Integer objectID) {
if(associations.containsKey(associationID)) {
return associations.get(associationID).get(objectID);
}
else {
return null;
}
}
/**
* Returns the global association specified by the given associationID.
*
* @param associationID the id of the association, respectively the name of
* the relation
* @return Object the association or null, if there is no association with the
* specified associationID
*/
public <T> T getGlobalAssociation(AssociationID<T> associationID) {
return globalAssociations.get(associationID);
}
/**
* Provides a new id for the specified database object suitable as key for a
* new insertion and sets this id in the specified database object.
*
* @param object the object for which a new id should be provided
* @return a new id suitable as key for a new insertion
* @throws UnableToComplyException if the database has reached the limit and,
* therefore, new insertions are not possible
*/
protected Integer setNewID(O object) throws UnableToComplyException {
if(object.getID() != null) {
if(content.containsKey(object.getID())) {
throw new UnableToComplyException("ID " + object.getID() + " is already in use!");
}
return object.getID();
}
if(content.size() == Integer.MAX_VALUE) {
throw new UnableToComplyException("Database reached limit of storage.");
}
else {
Integer id;
if(reusableIDs.size() != 0) {
id = reusableIDs.remove(0);
}
else {
if(counter == Integer.MAX_VALUE) {
throw new UnableToComplyException("Database reached limit of storage.");
}
else {
counter++;
while(content.containsKey(counter)) {
if(counter == Integer.MAX_VALUE) {
throw new UnableToComplyException("Database reached limit of storage.");
}
counter++;
}
id = counter;
}
}
object.setID(id);
return id;
}
}
/**
* Makes the given id reusable for new insertion operations.
*
* @param id the id to become reusable
*/
protected void restoreID(final Integer id) {
{
reusableIDs.add(id);
}
}
/**
* Deletes associations for the given id if there are any.
*
* @param id id of which all associations are to be deleted
*/
protected void deleteAssociations(final Integer id) {
for(AssociationID<?> a : associations.keySet()) {
associations.get(a).remove(id);
}
}
/**
* Returns all associations for a given ID.
*
* @param id the id for which the associations are to be returned
* @return all associations for a given ID
*/
public Associations getAssociations(final Integer id) {
Associations idAssociations = new Associations();
for(AssociationID<?> associationID : associations.keySet()) {
if(associations.get(associationID).containsKey(id)) {
idAssociations.putUnchecked(associationID, associations.get(associationID).get(id));
}
}
return idAssociations;
}
/**
* Sets the specified association to the specified id.
*
* @param id the id which is to associate with specified associations
* @param idAssociations the associations to be associated with the specified
* id
*/
@SuppressWarnings("unchecked")
protected void setAssociations(final Integer id, final Associations idAssociations) {
for(AssociationID<?> associationID : idAssociations.keySet()) {
AssociationID<Object> aID = (AssociationID<Object>) associationID;
associate(aID, id, idAssociations.get(aID));
}
}
public Map<Integer, Database<O>> partition(Map<Integer, List<Integer>> partitions) throws UnableToComplyException {
return partition(partitions, null, null);
}
public Map<Integer, Database<O>> partition(Map<Integer, List<Integer>> partitions, Class<? extends Database<O>> dbClass, List<String> dbParameters) throws UnableToComplyException {
if(dbClass == null) {
dbClass = ClassGenericsUtil.uglyCrossCast(this.getClass(), Database.class);
dbParameters = getParameters();
}
Map<Integer, Database<O>> databases = new Hashtable<Integer, Database<O>>();
for(Integer partitionID : partitions.keySet()) {
List<Pair<O, Associations>> objectAndAssociationsList = new ArrayList<Pair<O, Associations>>();
List<Integer> ids = partitions.get(partitionID);
for(Integer id : ids) {
O object = get(id);
Associations associations = getAssociations(id);
objectAndAssociationsList.add(new Pair<O, Associations>(object, associations));
}
Database<O> database;
try {
database = ClassGenericsUtil.instantiateGenerics(Database.class, dbClass.getName());
database.setParameters(dbParameters);
database.insert(objectAndAssociationsList);
databases.put(partitionID, database);
}
catch(ParameterException e) {
throw new UnableToComplyException(e);
}
}
return databases;
}
/**
* Checks whether an association is set for every id in the database.
*
* @param associationID an association id to be checked
* @return true, if the association is set for every id in the database, false
* otherwise
*/
public boolean isSetForAllObjects(AssociationID<?> associationID) {
for(Iterator<Integer> dbIter = this.iterator(); dbIter.hasNext();) {
Integer id = dbIter.next();
if(this.getAssociation(associationID, id) == null)
return false;
}
return true;
}
/**
* Checks whether an association is set for at least one id in the database.
*
* @param associationID an association id to be checked
* @return true, if the association is set for every id in the database, false
* otherwise
*/
public boolean isSet(AssociationID<?> associationID) {
for(Iterator<Integer> dbIter = this.iterator(); dbIter.hasNext();) {
Integer id = dbIter.next();
if(this.getAssociation(associationID, id) != null)
return true;
}
return false;
}
public boolean isSetGlobally(AssociationID<?> associationID) {
return this.getGlobalAssociation(associationID) != null;
}
public final Set<Integer> randomSample(int k, long seed) {
if(k < 0 || k > this.size()) {
throw new IllegalArgumentException("Illegal value for size of random sample: " + k);
}
Set<Integer> sample = new HashSet<Integer>(k);
List<Integer> ids = getIDs();
Random random = new Random(seed);
while(sample.size() < k) {
sample.add(ids.get(random.nextInt(ids.size())));
}
return sample;
}
/**
* Returns a list of all ids currently in use in the database.
*
* The list is not affected of any changes made to the database in the future nor vice versa.
*
* @see de.lmu.ifi.dbs.elki.database.Database#getIDs()
*/
public List<Integer> getIDs() {
List<Integer> ids = new ArrayList<Integer>(this.size());
for(Integer id : this) {
ids.add(id);
}
return ids;
}
public int dimensionality() throws UnsupportedOperationException {
Iterator<Integer> iter = this.iterator();
if(iter.hasNext()) {
O entry = this.get(iter.next());
if(NumberVector.class.isInstance(entry)) {
return ((NumberVector<?, ?>) entry).getDimensionality();
}
else {
throw new UnsupportedOperationException("Database entries are not implementing interface " + NumberVector.class.getName() + ".");
}
}
else {
throw new UnsupportedOperationException(ExceptionMessages.DATABASE_EMPTY);
}
}
/**
* Helper method to extract the list of database objects from the specified
* list of objects and their associations.
*
* @param objectAndAssociationsList the list of objects and their associations
* @return the list of database objects
*/
protected List<O> getObjects(List<Pair<O, Associations>> objectAndAssociationsList) {
List<O> objects = new ArrayList<O>(objectAndAssociationsList.size());
for(Pair<O, Associations> objectAndAssociations : objectAndAssociationsList) {
objects.add(objectAndAssociations.getFirst());
}
return objects;
}
/**
* Adds a listener for the <code>DatabaseEvent</code> posted after the
* database changes.
*
* @param l the listener to add
* @see #removeDatabaseListener
*/
public void addDatabaseListener(DatabaseListener l) {
listenerList.add(l);
}
/**
* Removes a listener previously added with <code>addTreeModelListener</code>.
*
* @param l the listener to remove
* @see #addDatabaseListener
*/
public void removeDatabaseListener(DatabaseListener l) {
listenerList.remove(l);
}
/**
* Notifies all listeners that have registered interest for notification on
* this event type.
*
* @param objectIDs the ids of the database objects that have been removed
*/
protected void fireObjectsChanged(List<Integer> objectIDs) {
if(listenerList.isEmpty())
return;
DatabaseEvent e = new DatabaseEvent(this, objectIDs);
for(DatabaseListener listener : listenerList) {
listener.objectsChanged(e);
}
}
/**
* Notifies all listeners that have registered interest for notification on
* this event type.
*
* @param objectIDs the ids of the database objects that have been removed
*/
protected void fireObjectsInserted(List<Integer> objectIDs) {
if(listenerList.isEmpty())
return;
DatabaseEvent e = new DatabaseEvent(this, objectIDs);
for(DatabaseListener listener : listenerList) {
listener.objectsInserted(e);
}
}
/**
* Notifies all listeners that have registered interest for notification on
* this event type.
*
* @param objectID the ids of the database object that has been removed
*/
protected void fireObjectInserted(Integer objectID) {
List<Integer> objectIDs = new ArrayList<Integer>();
objectIDs.add(objectID);
fireObjectsInserted(objectIDs);
}
/**
* Notifies all listeners that have registered interest for notification on
* this event type.
*
* @param objectIDs the ids of the database objects that have been removed
*/
protected void fireObjectsRemoved(List<Integer> objectIDs) {
if(listenerList.isEmpty())
return;
DatabaseEvent e = new DatabaseEvent(this, objectIDs);
for(DatabaseListener listener : listenerList) {
listener.objectsRemoved(e);
}
}
/**
* Notifies all listeners that have registered interest for notification on
* this event type.
*
* @param objectID the id of the database object that has been removed
*/
protected void fireObjectRemoved(Integer objectID) {
List<Integer> objectIDs = new ArrayList<Integer>();
objectIDs.add(objectID);
fireObjectsRemoved(objectIDs);
}
@Override
public String getName() {
return "database";
}
}
|
package edu.wustl.cab2b.client.ui.query;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import junit.framework.TestCase;
import edu.common.dynamicextensions.domain.DomainObjectFactory;
import edu.common.dynamicextensions.domaininterface.AssociationInterface;
import edu.common.dynamicextensions.domaininterface.AttributeInterface;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.common.dynamicextensions.domaininterface.RoleInterface;
import edu.wustl.cab2b.client.ui.util.ClientConstants;
import edu.wustl.cab2b.common.queryengine.result.IQueryResult;
import edu.wustl.cab2b.common.queryengine.result.IRecord;
import edu.wustl.cab2b.common.queryengine.result.QueryResultFactory;
import edu.wustl.common.querysuite.metadata.associations.IAssociation;
import edu.wustl.common.querysuite.metadata.associations.impl.InterModelAssociation;
import edu.wustl.common.querysuite.metadata.associations.impl.IntraModelAssociation;
import edu.wustl.common.querysuite.metadata.path.Path;
import edu.wustl.common.querysuite.queryobject.LogicalOperator;
import edu.wustl.common.querysuite.queryobject.RelationalOperator;
/**
* @author Chandrakant Talele
*/
public class UtilityTest extends TestCase {
DomainObjectFactory fact = DomainObjectFactory.getInstance();
RelationalOperator[] arr = { RelationalOperator.Equals, RelationalOperator.NotEquals, RelationalOperator.Between, RelationalOperator.IsNull, RelationalOperator.IsNotNull, RelationalOperator.LessThan, RelationalOperator.LessThanOrEquals, RelationalOperator.GreaterThan, RelationalOperator.GreaterThanOrEquals, RelationalOperator.In, RelationalOperator.Contains, RelationalOperator.StartsWith, RelationalOperator.EndsWith, RelationalOperator.NotIn };
String[] res = { "Equals", "Not Equals", "Between", "Is Null", "Is Not Null", "Less than", "Less than or Equal to", "Greater than", "Greater than or Equal to", "In", "Contains", "Starts With", "Ends With", "Not In" };
public void testGetRoleNameForIntraModel() {
String name = "someName";
RoleInterface role = fact.createRole();
role.setName(name);
AssociationInterface association = fact.createAssociation();
association.setTargetRole(role);
IntraModelAssociation intraModelAssociation = new IntraModelAssociation(association);
assertEquals(name, Utility.getRoleName(intraModelAssociation));
}
public void testGetRoleNameForInterModel() {
String srcName = "srcName";
String tgtName = "tgtName";
AttributeInterface src = fact.createStringAttribute();
src.setName(srcName);
AttributeInterface tgt = fact.createStringAttribute();
tgt.setName(tgtName);
InterModelAssociation a = new InterModelAssociation(src, tgt);
assertEquals(srcName + " = " + tgtName, Utility.getRoleName(a));
}
public void testGetRecordNumNoRecords() {
IQueryResult queryResult = QueryResultFactory.createResult(fact.createEntity());
assertEquals(0, Utility.getRecordNum(queryResult));
}
public void testGetRecordNum() {
int size = 4;
int urls = 3;
IQueryResult queryResult = QueryResultFactory.createResult(fact.createEntity());
List<IRecord> list = new ArrayList<IRecord>(size);
for (int i = 0; i < size; i++) {
list.add(QueryResultFactory.createRecord(new HashSet<AttributeInterface>(), null));
}
for (int i = 0; i < urls; i++) {
queryResult.addRecords("URL" + i, list);
}
assertEquals(size * urls, Utility.getRecordNum(queryResult));
}
public void testGetPathDisplayString() {
EntityInterface source = fact.createEntity();
source.setName("sourceEntity");
EntityInterface target = fact.createEntity();
target.setName("targetEntity");
AssociationInterface association = fact.createAssociation();
association.setTargetEntity(target);
IntraModelAssociation intraModelAssociation = new IntraModelAssociation(association);
List<IAssociation> list = new ArrayList<IAssociation>();
list.add(intraModelAssociation);
Path path = new Path(source, target, list);
String str = Utility.getPathDisplayString(path);
assertEquals("<HTML><B>Path</B>:sourceEntity<B>----></B>targetEntity<HTML>", str);
}
public void testGetPathDisplayStringTwoAssociations() {
EntityInterface source = fact.createEntity();
source.setName("sourceEntity");
EntityInterface target = fact.createEntity();
target.setName("targetEntity");
EntityInterface inter = fact.createEntity();
inter.setName("inter");
AssociationInterface association1 = fact.createAssociation();
association1.setTargetEntity(inter);
AssociationInterface association2 = fact.createAssociation();
association2.setTargetEntity(target);
IntraModelAssociation intraModelAssociation1 = new IntraModelAssociation(association1);
IntraModelAssociation intraModelAssociation2 = new IntraModelAssociation(association2);
List<IAssociation> list = new ArrayList<IAssociation>();
list.add(intraModelAssociation1);
list.add(intraModelAssociation2);
Path path = new Path(source, target, list);
String str = Utility.getPathDisplayString(path);
assertEquals("<HTML><B>Path</B>:sourceEntity<B>
}
public void testGetLogicalOperatorOR() {
assertEquals(LogicalOperator.Or, Utility.getLogicalOperator(ClientConstants.OPERATOR_OR));
}
public void testGetLogicalOperatorAND() {
assertEquals(LogicalOperator.And, Utility.getLogicalOperator(ClientConstants.OPERATOR_AND));
}
public void testDisplayStringForRelationalOperator() {
assertEquals(arr.length, res.length);
for (int i = 0; i < arr.length; i++) {
String str = Utility.displayStringForRelationalOperator(arr[i]);
assertEquals(res[i], str);
}
}
public void testGetRelationalOperator() {
for (int i = 0; i < arr.length; i++) {
RelationalOperator opr = Utility.getRelationalOperator(res[i]);
assertEquals(arr[i], opr);
}
}
}
|
package dr.inference.mcmc;
import dr.inference.loggers.Logger;
import dr.inference.loggers.MCLogger;
import dr.inference.markovchain.MarkovChain;
import dr.inference.markovchain.MarkovChainListener;
import dr.inference.model.Model;
import dr.inference.model.PathLikelihood;
import dr.inference.operators.CombinedOperatorSchedule;
import dr.inference.operators.OperatorAnalysisPrinter;
import dr.inference.operators.OperatorSchedule;
import dr.inference.prior.Prior;
import dr.util.Identifiable;
import dr.xml.*;
import org.apache.commons.math.MathException;
import org.apache.commons.math.distribution.BetaDistributionImpl;
/**
* An MCMC analysis that estimates parameters of a probabilistic model.
*
* @author Andrew Rambaut
* @author Alex Alekseyenko
* @version $Id: MCMC.java,v 1.41 2005/07/11 14:06:25 rambaut Exp $
*/
public class MarginalLikelihoodEstimator implements Runnable, Identifiable {
public MarginalLikelihoodEstimator(String id, int chainLength, int burninLength, int pathSteps,
// boolean linear, boolean lacing,
PathScheme scheme,
PathLikelihood pathLikelihood,
OperatorSchedule schedule,
MCLogger logger) {
this.id = id;
this.chainLength = chainLength;
this.pathSteps = pathSteps;
this.scheme = scheme;
this.schedule = schedule;
// deprecated
// this.linear = (scheme == PathScheme.LINEAR);
// this.lacing = false; // Was not such a good idea
this.burninLength = burninLength;
MCMCCriterion criterion = new MCMCCriterion();
pathDelta = 1.0 / pathSteps;
pathParameter = 1.0;
this.pathLikelihood = pathLikelihood;
pathLikelihood.setPathParameter(pathParameter);
mc = new MarkovChain(Prior.UNIFORM_PRIOR, pathLikelihood, schedule, criterion, 0, 0, true);
this.logger = logger;
}
private void setDefaultBurnin() {
if (burninLength == -1) {
burnin = (int) (0.1 * chainLength);
} else {
burnin = burninLength;
}
}
public void integrate(Integrator scheme) {
setDefaultBurnin();
mc.setCurrentLength(burnin);
scheme.init();
for (pathParameter = scheme.nextPathParameter(); pathParameter >= 0; pathParameter = scheme.nextPathParameter()) {
pathLikelihood.setPathParameter(pathParameter);
reportIteration(pathParameter, chainLength, burnin);
long cl = mc.getCurrentLength();
mc.setCurrentLength(0);
mc.runChain(burnin, false);
mc.setCurrentLength(cl);
mc.runChain(chainLength, false);
(new OperatorAnalysisPrinter(schedule)).showOperatorAnalysis(System.out);
((CombinedOperatorSchedule) schedule).reset();
}
}
public abstract class Integrator {
protected int step;
protected int pathSteps;
protected Integrator(int pathSteps) {
this.pathSteps = pathSteps;
}
public void init() {
step = 0;
}
abstract double nextPathParameter();
}
public class LinearIntegrator extends Integrator {
public LinearIntegrator(int pathSteps) {
super(pathSteps);
}
double nextPathParameter() {
if (step > pathSteps)
return -1;
double pathParameter = 1.0 - step / (pathSteps - 1);
step = step + 1;
return pathParameter;
}
}
public class SigmoidIntegrator extends Integrator {
private double alpha;
public SigmoidIntegrator(double alpha, int pathSteps) {
super(pathSteps);
this.alpha = alpha;
}
double nextPathParameter() {
if (step == 0) {
step++;
return 1.0;
} else if (step == pathSteps) {
step++;
return 0.0;
} else if (step > pathSteps) {
return -1.0;
} else {
double xvalue = ((pathSteps - step)/((double)pathSteps)) - 0.5;
step++;
return Math.exp(alpha*xvalue)/(Math.exp(alpha*xvalue) + Math.exp(-alpha*xvalue));
}
}
}
public class BetaQuantileIntegrator extends Integrator {
private double alpha;
public BetaQuantileIntegrator(double alpha, int pathSteps) {
super(pathSteps);
this.alpha = alpha;
}
double nextPathParameter() {
if (step > pathSteps)
return -1;
double result = Math.pow((pathSteps - step)/((double)pathSteps), 1.0/alpha);
step++;
return result;
}
}
public class BetaIntegrator extends Integrator {
private BetaDistributionImpl betaDistribution;
public BetaIntegrator(double alpha, double beta, int pathSteps) {
super(pathSteps);
this.betaDistribution = new BetaDistributionImpl(alpha, beta);
}
double nextPathParameter() {
if (step > pathSteps)
return -1;
if (step == 0) {
step += 1;
return 1.0;
} else if (step + 1 < pathSteps) {
double ratio = (double) step / (double) (pathSteps - 1);
try {
step += 1;
return 1.0 - betaDistribution.inverseCumulativeProbability(ratio);
} catch (MathException e) {
e.printStackTrace();
}
}
step += 1;
return 0.0;
}
}
public class GeometricIntegrator extends Integrator {
public GeometricIntegrator(int pathSteps) {
super(pathSteps);
}
double nextPathParameter() {
if (step > pathSteps) {
return -1;
}
if (step == pathSteps) { //pathSteps instead of pathSteps - 1
step += 1;
return 0;
}
step += 1;
return Math.pow(2, -(step - 1));
}
}
/*public void linearIntegration() {
setDefaultBurnin();
mc.setCurrentLength(0);
for (int step = 0; step < pathSteps; step++) {
pathLikelihood.setPathParameter(pathParameter);
reportIteration(pathParameter, chainLength, burnin);
//mc.runChain(chainLength + burnin, false, 0);
mc.runChain(chainLength + burnin, false);
pathParameter -= pathDelta;
}
pathLikelihood.setPathParameter(0.0);
reportIteration(pathParameter, chainLength, burnin);
//mc.runChain(chainLength + burnin, false, 0);
mc.runChain(chainLength + burnin, false);
}*/
/*public void betaIntegration(double alpha, double beta) {
setDefaultBurnin();
mc.setCurrentLength(0);
BetaDistributionImpl betaDistribution = new BetaDistributionImpl(alpha, beta);
for (int step = 0; step < pathSteps; step++) {
if (step == 0) {
pathParameter = 1.0;
} else if (step + 1 < pathSteps) {
double ratio = (double) step / (double) (pathSteps - 1);
try {
pathParameter = 1.0 - betaDistribution.inverseCumulativeProbability(ratio);
} catch (MathException e) {
e.printStackTrace();
}
} else {
pathParameter = 0.0;
}
pathLikelihood.setPathParameter(pathParameter);
reportIteration(pathParameter, chainLength, burnin);
//mc.runChain(chainLength + burnin, false, 0);
mc.runChain(chainLength + burnin, false);
(new OperatorAnalysisPrinter(schedule)).showOperatorAnalysis(System.out);
((CombinedOperatorSchedule) schedule).reset();
}
}*/
private void reportIteration(double pathParameter, long chainLength, long burnin) {
System.out.println("Attempting theta = " + pathParameter + " for " + chainLength + " iterations + " + burnin + " burnin.");
}
public void run() {
logger.startLogging();
mc.addMarkovChainListener(chainListener);
switch (scheme) {
case LINEAR:
integrate(new LinearIntegrator(pathSteps));
break;
case GEOMETRIC:
integrate(new GeometricIntegrator(pathSteps));
break;
case ONE_SIDED_BETA:
integrate(new BetaIntegrator(1.0, betaFactor, pathSteps));
break;
case BETA:
integrate(new BetaIntegrator(alphaFactor, betaFactor, pathSteps));
break;
case BETA_QUANTILE:
integrate(new BetaQuantileIntegrator(alphaFactor, pathSteps));
break;
case SIGMOID:
integrate(new SigmoidIntegrator(alphaFactor, pathSteps));
break;
default:
throw new RuntimeException("Illegal path scheme");
}
mc.removeMarkovChainListener(chainListener);
}
private final MarkovChainListener chainListener = new MarkovChainListener() {
// for receiving messages from subordinate MarkovChain
/**
* Called to update the current model keepEvery states.
*/
public void currentState(long state, Model currentModel) {
currentState = state;
if (currentState >= burnin) {
logger.log(state);
}
}
/**
* Called when a new new best posterior state is found.
*/
public void bestState(long state, Model bestModel) {
currentState = state;
}
/**
* cleans up when the chain finishes (possibly early).
*/
public void finished(long chainLength) {
currentState = chainLength;
(new OperatorAnalysisPrinter(schedule)).showOperatorAnalysis(System.out);
// logger.log(currentState);
logger.stopLogging();
}
};
/**
* @return the current state of the MCMC analysis.
*/
public boolean getSpawnable() {
return spawnable;
}
private boolean spawnable = true;
public void setSpawnable(boolean spawnable) {
this.spawnable = spawnable;
}
public void setAlphaFactor(double alpha) {
alphaFactor = alpha;
}
public void setBetaFactor(double beta) {
betaFactor = beta;
}
public double getAlphaFactor() {
return alphaFactor;
}
public double getBetaFactor() {
return betaFactor;
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return MARGINAL_LIKELIHOOD_ESTIMATOR;
}
/**
* @return a tree object based on the XML element it was passed.
*/
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
PathLikelihood pathLikelihood = (PathLikelihood) xo.getChild(PathLikelihood.class);
MCLogger logger = (MCLogger) xo.getChild(MCLogger.class);
int chainLength = xo.getIntegerAttribute(CHAIN_LENGTH);
int pathSteps = xo.getIntegerAttribute(PATH_STEPS);
int burninLength = -1;
if (xo.hasAttribute(BURNIN)) {
burninLength = xo.getIntegerAttribute(BURNIN);
}
int prerunLength = -1;
if (xo.hasAttribute(PRERUN)) {
prerunLength = xo.getIntegerAttribute(PRERUN);
}
// deprecated
boolean linear = xo.getAttribute(LINEAR, true);
// boolean lacing = xo.getAttribute(LACING,false);
PathScheme scheme;
if (linear) {
scheme = PathScheme.LINEAR;
} else {
scheme = PathScheme.GEOMETRIC;
}
// new approach
if (xo.hasAttribute(PATH_SCHEME)) { // change to: getAttribute once deprecated approach removed
scheme = PathScheme.parseFromString(xo.getAttribute(PATH_SCHEME, PathScheme.LINEAR.getText()));
}
for (int i = 0; i < xo.getChildCount(); i++) {
Object child = xo.getChild(i);
if (child instanceof Logger) {
}
}
CombinedOperatorSchedule os = new CombinedOperatorSchedule();
XMLObject mcmcXML = xo.getChild(MCMC);
for (int i = 0; i < mcmcXML.getChildCount(); ++i) {
if (mcmcXML.getChild(i) instanceof MCMC) {
MCMC mcmc = (MCMC) mcmcXML.getChild(i);
if (prerunLength > 0) {
java.util.logging.Logger.getLogger("dr.inference").info("Path Sampling Marginal Likelihood Estimator:\n\tEquilibrating chain " + mcmc.getId() + " for " + prerunLength + " iterations.");
for (Logger log : mcmc.getLoggers()) { // Stop the loggers, so nothing gets written to normal output
log.stopLogging();
}
mcmc.getMarkovChain().runChain(prerunLength, false);
}
os.addOperatorSchedule(mcmc.getOperatorSchedule());
}
}
if (os.getScheduleCount() == 0) {
System.err.println("Error: no mcmc objects provided in construction. Bayes Factor estimation will likely fail.");
}
MarginalLikelihoodEstimator mle = new MarginalLikelihoodEstimator(MARGINAL_LIKELIHOOD_ESTIMATOR, chainLength,
burninLength, pathSteps, scheme, pathLikelihood, os, logger);
if (!xo.getAttribute(SPAWN, true))
mle.setSpawnable(false);
if (xo.hasAttribute(ALPHA)) {
mle.setAlphaFactor(xo.getAttribute(ALPHA, 0.5));
}
if (xo.hasAttribute(BETA)) {
mle.setBetaFactor(xo.getAttribute(BETA, 0.5));
}
String alphaBetaText = "(";
if (scheme == PathScheme.ONE_SIDED_BETA) {
alphaBetaText += "1," + mle.getBetaFactor() + ")";
} else if (scheme == PathScheme.BETA) {
alphaBetaText += mle.getAlphaFactor() + "," + mle.getBetaFactor() + ")";
} else if (scheme == PathScheme.BETA_QUANTILE) {
alphaBetaText += mle.getAlphaFactor() + ")";
} else if (scheme == PathScheme.SIGMOID) {
alphaBetaText += mle.getAlphaFactor() + ")";
}
java.util.logging.Logger.getLogger("dr.inference").info("\nCreating the Marginal Likelihood Estimator chain:" +
"\n chainLength=" + chainLength +
"\n pathSteps=" + pathSteps +
"\n pathScheme=" + scheme.getText() + alphaBetaText +
"\n If you use these results, please cite:" +
"\n Guy Baele, Philippe Lemey, Trevor Bedford, Andrew Rambaut, Marc A. Suchard, and Alexander V. Alekseyenko." +
"\n 2012. Improving the accuracy of demographic and molecular clock model comparison while accommodating " +
"\n phylogenetic uncertainty. Mol. Biol. Evol. (in press).");
return mle;
}
/**
* this markov chain does most of the work.
*/
private final MarkovChain mc;
private OperatorSchedule schedule;
private String id = null;
private long currentState;
private final long chainLength;
private long burnin;
private final long burninLength;
private int pathSteps;
// private final boolean linear;
// private final boolean lacing;
private final PathScheme scheme;
private double alphaFactor = 0.5;
private double betaFactor = 0.5;
private final double pathDelta;
private double pathParameter;
private final MCLogger logger;
private final PathLikelihood pathLikelihood;
public static final String MARGINAL_LIKELIHOOD_ESTIMATOR = "marginalLikelihoodEstimator";
public static final String CHAIN_LENGTH = "chainLength";
public static final String PATH_STEPS = "pathSteps";
public static final String LINEAR = "linear";
public static final String LACING = "lacing";
public static final String SPAWN = "spawn";
public static final String BURNIN = "burnin";
public static final String MCMC = "samplers";
public static final String PATH_SCHEME = "pathScheme";
public static final String ALPHA = "alpha";
public static final String BETA = "beta";
public static final String PRERUN = "prerun";
}
|
package dr.inference.model;
import dr.util.NumberFormatter;
import dr.xml.*;
import java.util.ArrayList;
import java.util.List;
/**
* A likelihood function which is simply the product of a set of likelihood functions.
*
* @author Alexei Drummond
* @author Andrew Rambaut
* @version $Id: CompoundLikelihood.java,v 1.19 2005/05/25 09:14:36 rambaut Exp $
*/
public class ThreadedCompoundLikelihood implements Likelihood {
public static final String THREADED_COMPOUND_LIKELIHOOD = "threadedCompoundLikelihood";
public ThreadedCompoundLikelihood() {
}
public void addLikelihood(Likelihood likelihood) {
if (!likelihoods.contains(likelihood)) {
likelihoods.add(likelihood);
if (likelihood.getModel() != null) {
compoundModel.addModel(likelihood.getModel());
}
likelihoodCallers.add(new LikelihoodCaller(likelihood));
}
}
public int getLikelihoodCount() {
return likelihoods.size();
}
public final Likelihood getLikelihood(int i) {
return likelihoods.get(i);
}
// Likelihood IMPLEMENTATION
public Model getModel() {
return compoundModel;
}
public double getLogLikelihood() {
double logLikelihood = 0.0;
if (threads == null) {
// first call so setup a thread for each likelihood...
threads = new LikelihoodThread[likelihoodCallers.size()];
for (int i = 0; i < threads.length; i++) {
// and start them running...
threads[i] = new LikelihoodThread();
threads[i].start();
}
}
for (int i = 0; i < threads.length; i++) {
// set the caller which will be called in each thread
threads[i].setCaller(likelihoodCallers.get(i));
}
for (LikelihoodThread thread : threads) {
// now wait for the results to be set...
Double result = thread.getResult();
while (result == null) {
result = thread.getResult();
}
logLikelihood += result;
}
return logLikelihood;
}
public void makeDirty() {
for (Likelihood likelihood : likelihoods) {
likelihood.makeDirty();
}
}
public String getDiagnosis() {
String message = "";
boolean first = true;
for (Likelihood lik : likelihoods) {
if (!first) {
message += ", ";
} else {
first = false;
}
String id = lik.getId();
if (id == null || id.trim().length() == 0) {
String[] parts = lik.getClass().getName().split("\\.");
id = parts[parts.length - 1];
}
message += id + "=";
if (lik instanceof ThreadedCompoundLikelihood) {
String d = ((ThreadedCompoundLikelihood) lik).getDiagnosis();
if (d != null && d.length() > 0) {
message += "(" + d + ")";
}
} else {
if (lik.getLogLikelihood() == Double.NEGATIVE_INFINITY) {
message += "-Inf";
} else if (Double.isNaN(lik.getLogLikelihood())) {
message += "NaN";
} else {
NumberFormatter nf = new NumberFormatter(6);
message += nf.formatDecimal(lik.getLogLikelihood(), 4);
}
}
}
return message;
}
public String toString() {
return Double.toString(getLogLikelihood());
}
// Loggable IMPLEMENTATION
/**
* @return the log columns.
*/
public dr.inference.loggers.LogColumn[] getColumns() {
return new dr.inference.loggers.LogColumn[]{
new LikelihoodColumn(getId())
};
}
private class LikelihoodColumn extends dr.inference.loggers.NumberColumn {
public LikelihoodColumn(String label) {
super(label);
}
public double getDoubleValue() {
return getLogLikelihood();
}
}
// Identifiable IMPLEMENTATION
private String id = null;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public String getParserName() {
return THREADED_COMPOUND_LIKELIHOOD;
}
public String[] getParserNames() {
return new String[]{getParserName()};
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
ThreadedCompoundLikelihood compoundLikelihood = new ThreadedCompoundLikelihood();
for (int i = 0; i < xo.getChildCount(); i++) {
if (xo.getChild(i) instanceof Likelihood) {
compoundLikelihood.addLikelihood((Likelihood) xo.getChild(i));
} else {
Object rogueElement = xo.getChild(i);
throw new XMLParseException("An element (" + rogueElement + ") which is not a likelihood has been added to a " + THREADED_COMPOUND_LIKELIHOOD + " element");
}
}
return compoundLikelihood;
}
/**
* Main run loop
*/
public void run() {
while (true) {
if (caller != null) {
synchronized (result) {
result = caller.call();
resultAvailable = true;
caller = null;
}
}
}
}
public Double getResult() {
if (resultAvailable) {
resultAvailable = false;
return result;
}
return null;
}
private LikelihoodCaller caller = null;
private Double result = Double.NaN;
private boolean resultAvailable = false;
}
}
|
package edu.dynamic.dynamiz.controller;
import static org.junit.Assert.*;
import org.junit.Test;
import edu.dynamic.dynamiz.structure.ErrorFeedback;
import edu.dynamic.dynamiz.structure.Feedback;
import edu.dynamic.dynamiz.structure.SuccessFeedback;
import edu.dynamic.dynamiz.structure.ToDoItem;
public class ControllerTest {
@Test
public void testExecuteCommand() throws Exception{
Feedback feedback;
Controller controller = new Controller();
//Adds a ToDoItem
feedback = controller.executeCommand("add Buy newspaper");
assertEquals("add", feedback.getCommandType());
assertEquals("add Buy newspaper", feedback.getOriginalCommand());
//Adds an event
feedback = controller.executeCommand("add Meeting priority 2 from 7/10/2014 to 8/10/2014");
feedback = controller.executeCommand("add CS2103T Tutorial from 8/10/2014 13:00 to 8/10/2014 14:00");
feedback = controller.executeCommand("add A from 1/1/2000 13:00 to 2/1/2000 14:00");
//Deletes and item
//feedback = controller.executeCommand("delete A2");
//assertEquals("delete", feedback.getCommandType());
//assertEquals("delete A2", feedback.getOriginalCommand());
//Updates an event
//Date currently cannot be parsed.
feedback = controller.executeCommand("update A1 on 27/9/2014 17:30");
assertEquals("update", feedback.getCommandType());
//assertEquals("update A1 from 27/9/2014 17:30", feedback.getOriginalCommand());
feedback = controller.executeCommand("update A1 to 27/9/2014 20:00");
assertEquals("update", feedback.getCommandType());
assertEquals("update A1 to 27/9/2014 20:00", feedback.getOriginalCommand());
//Adds a deadline to ToDoItem.
feedback = controller.executeCommand("update A4 by 6/10/2014");
assertTrue(feedback instanceof SuccessFeedback);
//Item does not get changed due to error.
feedback= controller.executeCommand("update A4 Go shopping");
assertTrue(feedback instanceof SuccessFeedback);
//Tests program's handling of invalid options.
feedback = controller.executeCommand("update A4 from to");
assertFalse(feedback instanceof SuccessFeedback);
//System.out.println(((SuccessFeedback)feedback).getAffectedItems()[0]);
//System.out.println(((SuccessFeedback)feedback).getAffectedItems()[1]);
//Lists the items in storage
feedback = controller.executeCommand("list");
assertEquals("list", feedback.getCommandType());
ToDoItem[] list = ((SuccessFeedback)feedback).getAffectedItems();
for(ToDoItem item: list){
System.out.println(item);
}
System.out.println();
feedback = controller.executeCommand("search CS");
list = ((SuccessFeedback)feedback).getAffectedItems();
for(ToDoItem item: list){
System.out.println(item);
}
System.out.println();
//Erroneous test case. To be dealt with in later stages.
//feedback = controller.executeCommand("add");
//Output is wrong. Parsing of the following command not yet supported.
feedback = controller.executeCommand("list -s");
assertTrue(feedback instanceof SuccessFeedback);
list = ((SuccessFeedback)feedback).getAffectedItems();
for(ToDoItem item: list){
System.out.println(item);
}
System.out.println();
}
}
|
package edu.kit.informatik.literatur_system;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Various utility functions
* @author JoseNote
* @version %I%, %G%
*/
public class Utilities {
/**
* Concatenates multiple generic collections into one list.
* Doesn't remove repeated elements.
* @param <T> TODO add doc
* @param collections TODO add doc
* @return TODO add doc
*/
@SafeVarargs
public static <T> List<T> concatenatedList(
Collection<T>... collections) {
return Arrays.stream(collections)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
/**
* Joins multiple primitive type objects into a space separated string
* @param values TODO add doc
* @return TODO add doc
*/
public static String listing(
final Object... values) {
return Stream.of(values).map(String::valueOf).collect(Collectors.joining(" "));
}
/**
* TODO add doc
* @param type TODO add doc
* @param args TODO add doc
* @return TODO add doc
*/
public static IllegalArgumentException noSuch(
final Class<?> type, final Object... args) {
//TODO improve message
return new IllegalArgumentException(Stream.of(args).map(String::valueOf)
.collect(Collectors.joining(", ", "No such " + type.getSimpleName() + ": ", "")));
}
/**
* TODO add doc
* @param type TODO add doc
* @param args TODO add doc
* @return TODO add doc
*/
public static IllegalArgumentException alreadyExist(
final Class<?> type, final Object... args) {
//TODO improve message
return new IllegalArgumentException(Stream.of(args).map(String::valueOf)
.collect(Collectors.joining(", ", "exist already " + type.getSimpleName() + ": ", "")));
}
}
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* the project. */
package edu.wpi.first.wpilibj.templates;
import edu.wpi.first.wpilibj.DigitalInput;
import edu.wpi.first.wpilibj.DriverStation;
import edu.wpi.first.wpilibj.DriverStationLCD;
import edu.wpi.first.wpilibj.IterativeRobot;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.Joystick;
//import edu.wpi.first.wpilibj.Relay;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Timer;
import java.io.* ;
import java.lang.StringBuffer;
/**
* The VM is configured to automatically run this class, and to call the
* functions corresponding to each mode, as described in the IterativeRobot
* documentation. If you change the name of this class or the package after
* creating this project, you must also update the manifest file in the resource
* directory.
*/
public class RobotTemplate extends IterativeRobot {
public void printMsg(String message) {
userMessages.println(DriverStationLCD.Line.kMain6, 1, message );
userMessages.updateLCD();
}
RobotDrive drivetrain;
//Relay spikeA;
Joystick leftStick;
Joystick rightStick;
//public String controlScheme = "twostick";
int leftStickX, leftStickY;
DriverStationLCD userMessages;
String controlScheme = "twostick";
Timer timer;
DigitalInput switchA, switchB;
Jaguar launcher;
double voltage;
//DriverStation driverStation = new DriverStation();
/**
* This function is run when the robot is first started up and should be
* used for any initialization code.
*/
public void robotInit() {
//Instantialize objects for RobotTemplate
//driverStation = new DriverStation();
rightStick = new Joystick(1);
leftStick = new Joystick(2);
userMessages = DriverStationLCD.getInstance();
//2-Wheel tank drive
//spikeA = new Relay(1);
drivetrain = new RobotDrive(1,2);
launcher = new Jaguar(5);
/*pistonUp = new Solenoid(1);
pistonDown = new Solenoid(2);
sol3 = new Solenoid(3);
sol4 = new Solenoid(4);
sol5 = new Solenoid(5);*/
//4-Wheel tank drive
//Motors must be set in the following order:
//LeftFront=1; LeftRear=2; RightFront=3; RightRear=4;
//drivetrain = new RobotDrive(1,2,3,4);
//drivetrain.tankDrive(leftStick, rightStick);
/*pistonDown.set(true);
pistonUp.set(true);*/
switchA = new DigitalInput(1);
switchB = new DigitalInput(2);//remember to check port
}
/**
* This function is called periodically during autonomous
*/
public void autonomousInit() {
voltage = DriverStation.getInstance().getBatteryVoltage();
drivetrain.setSafetyEnabled(false);
if (switchA.get() && switchB.get()) {
printMsg("Moving Forward");
drivetrain.setLeftRightMotorOutputs(0.5, 0.5);
Timer.delay(1);
drivetrain.stopMotor();
}
else if (!switchA.get() && !switchB.get()) {
printMsg("Moving backward");
drivetrain.setLeftRightMotorOutputs(-0.5, -0.5);
Timer.delay(1);
drivetrain.stopMotor();
}
else if (switchA.get() && !switchB.get()) {
printMsg("turning");
drivetrain.setLeftRightMotorOutputs(0.5, -0.5);
Timer.delay(1);
drivetrain.stopMotor();
}
else if (!switchA.get() && switchB.get()) {
printMsg("turning");
drivetrain.setLeftRightMotorOutputs(-0.5, 0.5);
Timer.delay(1);
drivetrain.stopMotor();
}
else {
printMsg("Switch not detected");
//Timer.delay(15); not necessary, see below
}
//teleopInit(); driver station will do this automatically
/*drivetrain.setLeftRightMotorOutputs(1.0, 1.0);
Timer.delay(1000);
drivetrain.setLeftRightMotorOutputs(-1.0, 1.0);
Timer.delay(500);
drivetrain.setLeftRightMotorOutputs(1.0, 1.0);
Timer.delay(1000);
drivetrain.setLeftRightMotorOutputs(0, 0);
*/
}
public void telopInit() {
//drivetrain.setSafetyEnabled(true);
//drivetrain.tankDrive(leftStick.getY(), rightStick.getY());
//compressorA.start();
printMsg("Teleop started.");
}
/**
* This function is called periodically during operator control
*/
public void teleopPeriodic() {
/*if(switchA.get()){//if switch isn't tripped
printMsg("Moving motor.");
//victor.set(0.5); //start motor
}
else{
printMsg("Motor stopped");
//victor.set(0); //stop motor
}*/
//getWatchdog().setEnabled(true);
double rightMag;
rightMag = rightStick.getX();
String rightMag2 = String.valueOf(rightMag);
double leftMag;
leftMag = leftStick.getX();
String leftMag2 = String.valueOf(leftMag);
String someMags = new StringBuffer().append(rightMag2).append(" ").append(leftMag2).toString();
printMsg(someMags);
while(isEnabled() && isOperatorControl()) {
drivetrain.tankDrive(leftStick, rightStick);
}
//Pneumatics test code
if (leftStick.getTrigger()) {
launcher.set(-1);
}
else {
//don't set to 0 to avoid conflicts with right stick
}
if (rightStick.getTrigger()) {
launcher.set(1);
}
else {
launcher.set(0);
}
//Switch between "onestick" and "twostick" control schemes
if (leftStick.getRawButton(6)) {
controlScheme = "twostick";
}
if (leftStick.getRawButton(7)) {
controlScheme = "onestick";
}
if (controlScheme.equals("twostick")) {
drivetrain.tankDrive(rightStick, leftStick);
printMsg("Tankdrive activated.");
}
else if (controlScheme.equals("onestick")) {
drivetrain.arcadeDrive(leftStick);
printMsg("Arcade drive activated.");
}
if(switchA.get()){//if switch isn't tripped
printMsg("Moving motor.");
//victor.set(0.5); //start motor
}
else{
printMsg("Motor stopped");
//victor.set(0); //stop motor
}
//Rotate in-place left and right, respectively
if (leftStick.getRawButton(8)) {
drivetrain.setLeftRightMotorOutputs(-1.0, 1.0);
printMsg("Rotating counterclockwise in place.");
}
if (leftStick.getRawButton(9)) {
drivetrain.setLeftRightMotorOutputs(1.0, -1.0);
printMsg("Rotating clockwise in place.");
}
//userMessages.println(DriverStationLCD.Line.kMain6, 1, "This is a test" );
userMessages.updateLCD();
}
/*public void disabledInit() {
}*/
}
|
package engine.game.eventobserver;
import java.util.ArrayList;
import java.util.List;
import engine.Collision;
import engine.CollisionSide;
import engine.Entity;
/**
* Part of the Observable Design Pattern for detecting if collisions occur
* between Entities. Collisions that are detected are stored as a Collision in a
* list of Collisions.
*
* @author Kyle Finke
* @author Matthew Barbano
*
*/
public class CollisionObservable extends EventObservable {
private List<Collision> collisions = new ArrayList<>();
public CollisionObservable() {
super();
}
private boolean isCollision(Entity first, Entity second) {
if (first.getMinX() + first.getWidth() < second.getMinX()
|| second.getMinX() + second.getWidth() < first.getWidth()
|| first.getMinY() + first.getHeight() < second.getMinY()
|| second.getMinY() + second.getHeight() < first.getMinY()) {
return false;
}
return true;
}
private CollisionSide collisionSide(Entity entityOne, Entity entityTwo) {
if (isHorizontalCollision(entityOne, entityTwo)) {
if (entityOne.getMinX() < entityTwo.getMinX()) {
return CollisionSide.RIGHT;
}
return CollisionSide.LEFT;
}
if (entityOne.getMinY() < entityTwo.getMinY()) {
return CollisionSide.TOP;
}
return CollisionSide.BOTTOM;
}
private boolean isHorizontalCollision(Entity entityOne, Entity entityTwo) {
return getIntersectionHeight(entityOne, entityTwo) > getIntersectionWidth(entityOne, entityTwo);
}
private double getIntersectionWidth(Entity entityOne, Entity entityTwo) {
if (entityOne.getMaxX() < entityTwo.getMaxX()) {
if (entityOne.getMinX() < entityTwo.getMinX()) {
return entityOne.getMaxX() - entityTwo.getMinX();
}
return entityOne.getWidth();
}
return entityTwo.getMaxX() - entityOne.getMinX();
}
private double getIntersectionHeight(Entity entityOne, Entity entityTwo) {
if (entityOne.getMaxY() < entityTwo.getMaxY()) {
if (entityOne.getMinY() < entityTwo.getMinY()) {
return entityOne.getMaxY() - entityTwo.getMinY();
}
return entityOne.getHeight();
}
return entityTwo.getMaxY() - entityOne.getMinY();
}
/**
* Checks all entities in the current level for collisions. If a Collision
* is detected, it is added to a list of Collisions.
*/
@Override
public void updateObservers() {
for (Entity first : getObservers()) {
for (Entity second : getObservers()) {
if (first != second && isCollision(first, second)) {
collisions.add(new Collision(first, second, collisionSide(first, second)));
}
}
}
}
/**
*
* @return list of collisions that occurred between observed Entities
*/
public List<Collision> getCollisions() {
return collisions;
}
}
|
package explorviz.visualization.timeshift;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONString;
public class TimeShiftJS {
public static native void init() /*-{
var firstDataDone = false;
var dataPointPixelRatio = 17;
var panning = false;
var dataBegin = 0;
var dataEnd = 0;
Date.prototype.ddhhmmss = function() {
var weekday = new Array(7);
weekday[0] = "Su";
weekday[1] = "Mo";
weekday[2] = "Tu";
weekday[3] = "We";
weekday[4] = "Th";
weekday[5] = "Fr";
weekday[6] = "Sa";
var n = weekday[this.getDay()];
var hh = this.getHours().toString();
var mm = this.getMinutes().toString();
var ss = this.getSeconds().toString();
return n + " " + (hh[1] ? hh : "0" + hh[0]) + ":" + (mm[1] ? mm : "0" + mm[0]) + ":"
+ (ss[1] ? ss : "0" + ss[0]);
};
var timeshiftChartDiv = $wnd.jQuery("#timeshiftChartDiv");
//$doc.getElementById('timeshiftChartDiv').style.height = '100px';
//$doc.getElementById('timeshiftChartDiv').style.width = '500px';
var dataSet = [ {
data : [],
label : "Method Calls",
color : '#058DC7'
} ];
var options = {
series : {
lines : {
show : true,
fill : true,
fillColor : "rgba(86, 137, 191, 0.8)"
},
points : {
show : true,
radius : 2
},
downsample : {
threshold : 0
// 0 disables downsampling for this series.
},
shadowSize : 0,
highlightColor: "rgba(255, 0, 0, 0.8)"
},
axisLabels : {
show : true
},
legend : {
show : false
},
grid : {
hoverable : true,
clickable : true
},
xaxis : {
axisLabel: "Time",
mode : "time",
timezone : "browser"
},
yaxis : {
position: 'left',
axisLabel: 'Method Calls',
tickFormatter: function(x) {return x >= 1000 ? (x/1000)+"k": x;},
ticks : 1,
tickDecimals : 0,
zoomRange : false
},
zoom : {
interactive : true
},
pan : {
interactive : true,
cursor: "default",
frameRate: 60
}
};
var plot = $wnd.$.plot(timeshiftChartDiv, dataSet, options);
function addTooltipDiv() {
$wnd.jQuery("<div id='timeshiftTooltip'></div>").css({
position : "absolute",
display : "none",
border : "1px solid #fdd",
padding : "2px",
"background-color" : "#fee",
opacity : 0.80
}).appendTo("#timeshiftChartDiv");
}
addTooltipDiv();
$wnd.jQuery("#timeshiftChartDiv").bind("dblclick", onDblclick);
$wnd.jQuery("#timeshiftChartDiv").bind("plotzoom", onZoom);
$wnd.jQuery("#timeshiftChartDiv").bind("plothover", onHover);
$wnd.jQuery("#timeshiftChartDiv").bind("plotclick", onPointSelection);
$wnd.jQuery("#timeshiftChartDiv").bind("plotpan", onPanning);
$wnd.jQuery("#timeshiftChartDiv").bind("mouseup", onPanningEnd);
//Due to no difference between panning and click events, we need to differentiate.
function onPanningEnd() {
setTimeout(function() {
panning = false;
}
, 100);
}
function onPanning() {
panning = true;
}
function onPointSelection(event, pos, item) {
if (item && !panning) {
plot.unhighlight();
plot.highlight(item.series, item.datapoint);
@explorviz.visualization.landscapeexchange.LandscapeExchangeManager::stopAutomaticExchange(Ljava/lang/String;)(item.datapoint[0].toString());
@explorviz.visualization.interaction.Usertracking::trackFetchedSpecifcLandscape(Ljava/lang/String;)(item.datapoint[0].toString());
@explorviz.visualization.landscapeexchange.LandscapeExchangeManager::fetchSpecificLandscape(Ljava/lang/String;)(item.datapoint[0].toString());
}
}
function onDblclick() {
options.xaxis.min = dataSet[0].data[0][0];
options.xaxis.max = dataSet[0].data[dataSet[0].data.length - 1][0];
var innerWidth = $wnd.innerWidth;
options.series.downsample.threshold = parseInt(innerWidth / dataPointPixelRatio);
redraw();
}
function onHover(event, pos, item) {
if (item) {
var x = item.datapoint[0];
var y = item.datapoint[1];
// view-div offset
var offset = $wnd.jQuery("#view").offset().top;
// timechart-div offset
offset += $wnd.jQuery("#timeshiftChartDiv").position().top;
showTooltip(item.pageX + 15, (item.pageY - offset), "Method Calls: " + y);
} else {
$wnd.jQuery("#timeshiftTooltip").hide();
}
}
function onZoom() {
//console.log("zooming");
}
function showTooltip(x, y, contents) {
$wnd.jQuery("#timeshiftTooltip").html(contents).css({
top : y,
left : x
}).fadeIn(200);
}
function setDatapointsAndOptions(convertedValues, convDataLength) {
var innerWidth = $wnd.innerWidth;
var dataSetLength = dataSet[0].data.length;
var numberOfPointsToShow = parseInt(innerWidth / dataPointPixelRatio);
dataBegin = dataSetLength - numberOfPointsToShow <= 0 ?
0 : (dataSetLength - numberOfPointsToShow) ;
dataEnd = dataSetLength-1;
var newXMin = dataSet[0].data[dataBegin][0];
var newXMax = dataSet[0].data[dataEnd][0];
var oldXMin = firstDataDone ? dataSet[0].data[0][0] : newXMin;
var newYMax = Math.max.apply(Math, convertedValues.map(function(o) {
return o[1];
}));
if (!firstDataDone)
firstDataDone = true
options.xaxis.min = newXMin;
options.xaxis.max = newXMax;
options.xaxis.panRange = [ oldXMin, dataSet[0].data[dataSetLength-1][0] ];
options.yaxis.panRange = [ 0, newYMax ];
options.yaxis.max = newYMax;
options.series.downsample.threshold = 0;
}
function redraw() {
if(!panning) {
console.log(dataSet);
plot = $wnd.$.plot(timeshiftChartDiv, dataSet, options);
addTooltipDiv();
}
}
$wnd.jQuery.fn.updateTimeshiftChart = function(data) {
var values = data[0].values;
var newElemObj = values[values.length - 1];
var newElem = [newElemObj.x, newElemObj.y];
dataSet[0].data.push(newElem);
var dataLength = dataSet[0].data.length;
if(dataLength > 0) {
setDatapointsAndOptions(dataSet[0].data, dataLength);
redraw();
}
}
}-*/;
public static void updateTimeshiftChart(final Map<Long, Long> data) {
final JavaScriptObject jsObj = convertToJSHashMap(data);
nativeUpdateTimeshiftChart(jsObj);
}
private static JavaScriptObject convertToJSHashMap(final Map<Long, Long> data) {
final JSONObject obj = new JSONObject();
for (final Entry<Long, Long> entry : data.entrySet()) {
obj.put(entry.getKey().toString(), new JSONString(entry.getValue().toString()));
}
final JavaScriptObject jsObj = obj.getJavaScriptObject();
return jsObj;
}
public static native void nativeUpdateTimeshiftChart(JavaScriptObject jsObj) /*-{
var keys = Object.keys(jsObj);
var series1 = [];
keys.forEach(function(entry) {
series1.push({
x : Number(entry),
y : Number(jsObj[entry])
});
});
$wnd.jQuery(this).updateTimeshiftChart([ {
key : "Timeseries",
values : series1,
color : "#366eff",
area : true
} ]);
}-*/;
}
|
package net.sf.farrago.query;
import openjava.mop.*;
import openjava.ptree.*;
import org.eigenbase.rex.*;
import org.eigenbase.rel.*;
import org.eigenbase.relopt.*;
import org.eigenbase.reltype.*;
import org.eigenbase.oj.rel.*;
import org.eigenbase.oj.util.*;
import org.eigenbase.runtime.*;
import net.sf.farrago.runtime.*;
/**
* FarragoJavaUdxRel is the implementation for a {@link
* TableFunctionRel} which invokes a Java UDX (user-defined transformation).
*
* @author John V. Sichi
* @version $Id$
*/
public class FarragoJavaUdxRel extends TableFunctionRelBase
implements JavaRel
{
private final String serverMofId;
/**
* Creates a <code>FarragoJavaUdxRel</code>.
*
* @param cluster {@link RelOptCluster} this relational expression
* belongs to
*
* @param rexCall function invocation expression
*
* @param rowType row type produced by function
*
* @param serverMofId MOFID of data server to associate with this UDX
* invocation, or null for none
*
* @param inputs 0 or more relational inputs
*/
public FarragoJavaUdxRel(
RelOptCluster cluster, RexNode rexCall, RelDataType rowType,
String serverMofId, RelNode [] inputs)
{
super(
cluster,
new RelTraitSet(CallingConvention.ITERATOR),
rexCall,
rowType,
inputs);
this.serverMofId = serverMofId;
}
/**
* Creates a <code>FarragoJavaUdxRel</code> with no relational
* inputs.
*
* @param cluster {@link RelOptCluster} this relational expression
* belongs to
*
* @param rexCall function invocation expression
*
* @param rowType row type produced by function
*
* @param serverMofId MOFID of data server to associate with this UDX
* invocation, or null for none
*/
public FarragoJavaUdxRel(
RelOptCluster cluster, RexNode rexCall, RelDataType rowType,
String serverMofId)
{
this(cluster, rexCall, rowType, serverMofId, RelNode.emptyArray);
}
// implement RelNode
public Object clone()
{
FarragoJavaUdxRel clone = new FarragoJavaUdxRel(
getCluster(),
getCall(),
getRowType(),
serverMofId,
RelOptUtil.clone(inputs));
clone.inheritTraitsFrom(this);
return clone;
}
// implement RelNode
public RelOptCost computeSelfCost(RelOptPlanner planner)
{
// TODO jvs 8-Jan-2006: get estimate from user or history
return planner.makeTinyCost();
}
// override TableFunctionRelBase
public void explain(RelOptPlanWriter pw)
{
if (serverMofId == null) {
super.explain(pw);
return;
}
// NOTE jvs 7-Mar-2006: including the serverMofId means
// we can't use EXPLAIN PLAN in diff-based testing because
// the MOFID isn't deterministic.
pw.explain(
this,
new String [] { "invocation", "serverMofId" },
new Object [] { serverMofId } );
}
// implement JavaRel
public ParseTree implement(JavaRelImplementor implementor)
{
final RelDataType outputRowType = getRowType();
OJClass outputRowClass = OJUtil.typeToOJClass(
outputRowType,
implementor.getTypeFactory());
// Translate relational inputs to ResultSet expressions.
final Expression [] childExprs = new Expression[inputs.length];
for (int i = 0; i < inputs.length; ++i) {
childExprs[i] =
implementor.visitJavaChild(this, i, (JavaRel) inputs[i]);
OJClass rowClass = OJUtil.typeToOJClass(
inputs[i].getRowType(), getCluster().getTypeFactory());
Expression typeLookupCall = generateTypeLookupCall(
implementor,
inputs[i]);
ExpressionList resultSetParams = new ExpressionList();
resultSetParams.add(childExprs[i]);
resultSetParams.add(new ClassLiteral(rowClass));
resultSetParams.add(typeLookupCall);
resultSetParams.add(Literal.constantNull());
childExprs[i] = new AllocationExpression(
OJUtil.typeNameForClass(FarragoTupleIterResultSet.class),
resultSetParams);
}
// Rebind RexInputRefs accordingly.
final JavaRexBuilder rexBuilder =
(JavaRexBuilder) implementor.getRexBuilder();
RexShuttle shuttle = new RexShuttle()
{
public RexNode visitInputRef(RexInputRef inputRef)
{
return rexBuilder.makeJava(
getCluster().getEnv(),
childExprs[inputRef.getIndex()]);
}
};
RexNode rewrittenCall = getCall().accept(shuttle);
MemberDeclarationList memberList = new MemberDeclarationList();
StatementList executeMethodBody = new StatementList();
// Set up server MOFID context while generating method call
// so that it will be available to the UDX at runtime in case
// it needs to call back to the foreign data server.
FarragoRelImplementor farragoImplementor =
(FarragoRelImplementor) implementor;
farragoImplementor.setServerMofId(serverMofId);
implementor.translateViaStatements(
this,
rewrittenCall,
executeMethodBody,
memberList);
farragoImplementor.setServerMofId(null);
MemberDeclaration executeMethodDecl =
new MethodDeclaration(new ModifierList(ModifierList.PROTECTED),
TypeName.forOJClass(OJSystem.VOID), "executeUdx",
new ParameterList(), null, executeMethodBody);
memberList.add(executeMethodDecl);
Expression typeLookupCall = generateTypeLookupCall(
implementor,
this);
Expression iteratorExp =
new AllocationExpression(
OJUtil.typeNameForClass(FarragoJavaUdxIterator.class),
new ExpressionList(
implementor.getConnectionVariable(),
new ClassLiteral(TypeName.forOJClass(outputRowClass)),
typeLookupCall),
memberList);
// TODO jvs 23-Feb-2006: get rid of adapter and write
// a new TupleIter implementation so that we can take
// advantage of the closeAllocation call.
Expression tupleIterExp = new AllocationExpression(
OJUtil.typeNameForClass(RestartableIteratorTupleIter.class),
new ExpressionList(
iteratorExp));
return tupleIterExp;
}
/**
* Stores the row type for a relational expression in the PreparingStmt,
* and generates a call which will retrieve it from the executable context
* at runtime. The literal string key used is based on the relational
* expression id.
*/
private Expression generateTypeLookupCall(
JavaRelImplementor implementor,
RelNode relNode)
{
String resultSetName = "ResultSet:" + relNode.getId();
FarragoPreparingStmt preparingStmt =
((FarragoRelImplementor) implementor).getPreparingStmt();
preparingStmt.mapResultSetType(
resultSetName,
relNode.getRowType());
MethodCall typeLookupCall =
new MethodCall(
implementor.getConnectionVariable(),
"getRowTypeForResultSet",
new ExpressionList(
Literal.makeLiteral(resultSetName)));
return typeLookupCall;
}
}
// End FarragoJavaUdxRel.java
|
import com.docusign.esign.api.*;
import com.docusign.esign.client.*;
import com.docusign.esign.model.*;
import com.docusign.esign.client.auth.OAuth;
import com.docusign.esign.client.auth.OAuth.UserInfo;
import java.io.File;
//import java.awt.Desktop;
import org.joda.time.DateTime;
import org.junit.*;
import org.junit.runners.MethodSorters;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.migcomponents.migbase64.Base64;
import javax.ws.rs.core.UriBuilderException;
/**
*
* @author majid.mallis
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SdkUnitTests {
private static final String UserName = System.getProperty("USER_NAME");
private static final String UserId = System.getProperty("USER_ID");
private static final String IntegratorKey = System.getProperty("INTEGRATOR_KEY_JWT");
private static final String IntegratorKeyImplicit = System.getProperty("INTEGRATOR_KEY_IMPLICIT");
//private static final String ClientSecret = System.getProperty("CLIENT_SECRET");
private static final String RedirectURI = System.getProperty("REDIRECT_URI");
private static final String BaseUrl = "https://demo.docusign.net/restapi";
//private static final String OAuthBaseUrl = "account-d.docusign.com";
private static final byte[] privateKeyBytes = System.getProperty("PRIVATE_KEY").getBytes();
private static final String brandLogoFullPath = System.getProperty("user.dir") + "/src/test/docs/DS.png";
private static final String SignTest1File = "/src/test/docs/SignTest1.pdf";
private static final String TemplateId = System.getProperty("TEMPLATE_ID");
private static final String BrandId = System.getProperty("BRAND_ID");
private String[] envelopeIds = new String[0];
// JUnit 4.12 runs test cases in parallel, so the envelope ID needs to be initiated as well.
// private JSON json = new JSON();
public SdkUnitTests() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
if (envelopeIds.length == 0) {
envelopeIds = getLastTenEnvelopeIds();
}
}
@After
public void tearDown() {
}
// The methods must be annotated with annotation @Test. For example:
@Test
public void JWTLoginTest() {
System.out.println("\nJWTLoginTest:\n" + "===========================================");
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
scopes.add(OAuth.Scope_IMPERSONATION);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void AuthorizationCodeLoginTest() {
System.out.println("\nAuthorizationCodeLoginTest:\n" + "===========================================");
ApiClient apiClient = new ApiClient(BaseUrl);
try {
// after successful login you should compare the value of URI decoded "state" query param
// with the one you create here; they should match.
String randomState = "*^.$DGj*)+}Jk";
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
// get DocuSign OAuth authorization url
URI oauthLoginUrl = apiClient.getAuthorizationUri(IntegratorKey, scopes, RedirectURI, OAuth.CODE, randomState);
// open DocuSign OAuth login in the browser
//Desktop.getDesktop().browse(oauthLoginUrl);
// IMPORTANT: after the login, DocuSign will send back a fresh
// authorization code as a query param of the redirect URI.
// You should set up a route that handles the redirect call to get
// that code and pass it to token endpoint as shown in the next
// lines:
/*String code = "<once_you_get_the_oauth_code_put_it_here>";
OAuth.OAuthToken oAuthToken = apiClient.generateAccessToken(IntegratorKey, ClientSecret, code);
Assert.assertNotSame(null, oAuthToken);
Assert.assertNotNull(oAuthToken.getAccessToken());
Assert.assertTrue(oAuthToken.getExpiresIn() > 0L);
System.out.println("OAuthToken: " + oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);*/
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void ImplicitLoginTest() {
System.out.println("\nImplicitLoginTest:\n" + "===========================================");
ApiClient apiClient = new ApiClient(BaseUrl);
try {
// after successful login you should compare the value of URI decoded "state" query param
// with the one you create here; they should match.
String randomState = "*^.$DGj*)+}Jk";
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
// get DocuSign OAuth authorization url
URI oAuthLoginUri = apiClient.getAuthorizationUri(IntegratorKeyImplicit, scopes, RedirectURI, OAuth.TOKEN, randomState);
// open DocuSign OAuth login in the browser
//Desktop.getDesktop().browse(oAuthLoginUri);
// IMPORTANT: after the login, DocuSign will send back a new
// access token in the hash fragment of the redirect URI.
// You should set up a client-side handler that handles window.location change to get
// that token and pass it to the ApiClient object as shown in the next
// lines:
//String token = "<once_you_get_the_oauth_token_put_it_here>";
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
/*apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(token);
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);*/
} catch (UriBuilderException ex) {
System.out.println("UriBuilderException: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void RequestASignatureTest() {
System.out.println("\nRequestASignatureTest:\n" + "===========================================");
byte[] fileBytes = null;
try {
// String currentDir = new java.io.File(".").getCononicalPath();
String currentDir = System.getProperty("user.dir");
Path path = Paths.get(currentDir + SignTest1File);
fileBytes = Files.readAllBytes(path);
} catch (IOException ioExcp) {
Assert.assertEquals(null, ioExcp);
}
// create an envelope to be signed
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.setEmailSubject("Please Sign my Java SDK Envelope");
envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");
// add a document to the envelope
Document doc = new Document();
String base64Doc = Base64.encodeToString(fileBytes, false);
doc.setDocumentBase64(base64Doc);
doc.setName("TestFile.pdf");
doc.setDocumentId("1");
List<Document> docs = new ArrayList<Document>();
docs.add(doc);
envDef.setDocuments(docs);
// Add a recipient to sign the document
Signer signer = new Signer();
signer.setEmail(UserName);
signer.setName("Pat Developer");
signer.setRecipientId("1");
// Create a SignHere tab somewhere on the document for the signer to
// sign
SignHere signHere = new SignHere();
signHere.setDocumentId("1");
signHere.setPageNumber("1");
signHere.setRecipientId("1");
signHere.setXPosition("100");
signHere.setYPosition("100");
signHere.setScaleValue("0.5");
List<SignHere> signHereTabs = new ArrayList<SignHere>();
signHereTabs.add(signHere);
Tabs tabs = new Tabs();
tabs.setSignHereTabs(signHereTabs);
signer.setTabs(tabs);
// Above causes issue
envDef.setRecipients(new Recipients());
envDef.getRecipients().setSigners(new ArrayList<Signer>());
envDef.getRecipients().getSigners().add(signer);
// send the envelope (otherwise it will be "created" in the Draft folder
envDef.setStatus("sent");
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);
Assert.assertNotNull(envelopeSummary);
Assert.assertNotNull(envelopeSummary.getEnvelopeId());
Assert.assertEquals("sent", envelopeSummary.getStatus());
System.out.println("EnvelopeSummary: " + envelopeSummary);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void RequestSignatureFromTemplate() {
System.out.println("\nRequestSignatureFromTemplate:\n" + "===========================================");
String templateRoleName = "Needs to sign";
// create an envelope to be signed
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.setEmailSubject("Please Sign my Java SDK Envelope");
envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");
/// assign template information including ID and role(s)
envDef.setTemplateId(TemplateId);
// create a template role with a valid templateId and roleName and
// assign signer info
TemplateRole tRole = new TemplateRole();
tRole.setRoleName(templateRoleName);
tRole.setName("Pat Developer");
tRole.setEmail(UserName);
// create a list of template roles and add our newly created role
List<TemplateRole> templateRolesList = new ArrayList<TemplateRole>();
templateRolesList.add(tRole);
// assign template role(s) to the envelope
envDef.setTemplateRoles(templateRolesList);
// send the envelope by setting |status| to "sent". To save as a draft
// set to "created"
envDef.setStatus("sent");
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);
Assert.assertNotNull(envelopeSummary);
Assert.assertNotNull(envelopeSummary.getEnvelopeId());
Assert.assertEquals("sent", envelopeSummary.getStatus());
System.out.println("EnvelopeSummary: " + envelopeSummary);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void EmbeddedSigningTest() {
System.out.println("\nEmbeddedSigningTest:\n" + "===========================================");
byte[] fileBytes = null;
try {
// String currentDir = new java.io.File(".").getCononicalPath();
String currentDir = System.getProperty("user.dir");
Path path = Paths.get(currentDir + SignTest1File);
fileBytes = Files.readAllBytes(path);
} catch (IOException ioExcp) {
Assert.assertEquals(null, ioExcp);
}
// create an envelope to be signed
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.setEmailSubject("Please Sign my Java SDK Envelope (Embedded Signer)");
envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");
// add a document to the envelope
Document doc = new Document();
String base64Doc = Base64.encodeToString(fileBytes, false);
doc.setDocumentBase64(base64Doc);
doc.setName("TestFile.pdf");
doc.setDocumentId("1");
List<Document> docs = new ArrayList<Document>();
docs.add(doc);
envDef.setDocuments(docs);
// Add a recipient to sign the document
Signer signer = new Signer();
signer.setEmail(UserName);
String name = "Pat Developer";
signer.setName(name);
signer.setRecipientId("1");
// this value represents the client's unique identifier for the signer
String clientUserId = "2939";
signer.setClientUserId(clientUserId);
// Create a SignHere tab somewhere on the document for the signer to
// sign
SignHere signHere = new SignHere();
signHere.setDocumentId("1");
signHere.setPageNumber("1");
signHere.setRecipientId("1");
signHere.setXPosition("100");
signHere.setYPosition("100");
signHere.setScaleValue("0.5");
List<SignHere> signHereTabs = new ArrayList<SignHere>();
signHereTabs.add(signHere);
Tabs tabs = new Tabs();
tabs.setSignHereTabs(signHereTabs);
signer.setTabs(tabs);
// Above causes issue
envDef.setRecipients(new Recipients());
envDef.getRecipients().setSigners(new ArrayList<Signer>());
envDef.getRecipients().getSigners().add(signer);
// send the envelope (otherwise it will be "created" in the Draft folder
envDef.setStatus("sent");
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);
Assert.assertNotNull(envelopeSummary);
Assert.assertNotNull(envelopeSummary.getEnvelopeId());
System.out.println("EnvelopeSummary: " + envelopeSummary);
String returnUrl = "http:
RecipientViewRequest recipientView = new RecipientViewRequest();
recipientView.setReturnUrl(returnUrl);
recipientView.setClientUserId(clientUserId);
recipientView.setAuthenticationMethod("email");
recipientView.setUserName(name);
recipientView.setEmail(UserName);
ViewUrl viewUrl = envelopesApi.createRecipientView(accountId, envelopeSummary.getEnvelopeId(), recipientView);
Assert.assertNotNull(viewUrl);
Assert.assertNotNull(viewUrl.getUrl());
//Desktop.getDesktop().browse(URI.create(viewUrl.getUrl()));
// This Url should work in an Iframe or browser to allow signing
System.out.println("ViewUrl is " + viewUrl);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void CreateTemplateTest() {
System.out.println("\nCreateTemplateTest:\n" + "===========================================");
byte[] fileBytes = null;
File f;
try {
// String currentDir = new java.io.File(".").getCononicalPath();
String currentDir = System.getProperty("user.dir");
Path path = Paths.get(currentDir + SignTest1File);
fileBytes = Files.readAllBytes(path);
f = new File(path.toString());
Assert.assertTrue(f.length() > 0);
} catch (IOException ioExcp) {
Assert.assertEquals(null, ioExcp);
}
// create an envelope to be signed
EnvelopeTemplate templateDef = new EnvelopeTemplate();
templateDef.setEmailSubject("Please Sign my Java SDK Envelope");
templateDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");
// add a document to the envelope
Document doc = new Document();
String base64Doc = Base64.encodeToString(fileBytes, false);
doc.setDocumentBase64(base64Doc);
doc.setName("TestFile.pdf");
doc.setDocumentId("1");
List<Document> docs = new ArrayList<Document>();
docs.add(doc);
templateDef.setDocuments(docs);
// Add a recipient to sign the document
Signer signer = new Signer();
signer.setRoleName("Signer1");
signer.setRecipientId("1");
// Create a SignHere tab somewhere on the document for the signer to
// sign
SignHere signHere = new SignHere();
signHere.setDocumentId("1");
signHere.setPageNumber("1");
signHere.setRecipientId("1");
signHere.setXPosition("100");
signHere.setYPosition("100");
signHere.setScaleValue("0.5");
List<SignHere> signHereTabs = new ArrayList<SignHere>();
signHereTabs.add(signHere);
Tabs tabs = new Tabs();
tabs.setSignHereTabs(signHereTabs);
signer.setTabs(tabs);
templateDef.setRecipients(new Recipients());
templateDef.getRecipients().setSigners(new ArrayList<Signer>());
templateDef.getRecipients().getSigners().add(signer);
templateDef.setName("myTemplate");
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
TemplatesApi templatesApi = new TemplatesApi();
TemplateSummary templateSummary = templatesApi.createTemplate(accountId, templateDef);
Assert.assertNotNull(templateSummary);
System.out.println("TemplateSummary: " + templateSummary);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void DownLoadEnvelopeDocumentsTest() {
System.out.println("\nDownLoadEnvelopeDocumentsTest:\n" + "===========================================");
byte[] fileBytes = null;
try {
// String currentDir = new java.io.File(".").getCononicalPath();
String currentDir = System.getProperty("user.dir");
Path path = Paths.get(currentDir + SignTest1File);
fileBytes = Files.readAllBytes(path);
} catch (IOException ioExcp) {
Assert.assertEquals(null, ioExcp);
}
// create an envelope to be signed
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.setEmailSubject("Please Sign my Java SDK Envelope");
envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");
// add a document to the envelope
Document doc = new Document();
String base64Doc = Base64.encodeToString(fileBytes, false);
doc.setDocumentBase64(base64Doc);
doc.setName("TestFile.pdf");
doc.setDocumentId("1");
List<Document> docs = new ArrayList<Document>();
docs.add(doc);
envDef.setDocuments(docs);
// Add a recipient to sign the document
Signer signer = new Signer();
signer.setEmail(UserName);
String name = "Pat Developer";
signer.setName(name);
signer.setRecipientId("1");
// this value represents the client's unique identifier for the signer
String clientUserId = "2939";
signer.setClientUserId(clientUserId);
// Create a SignHere tab somewhere on the document for the signer to
// sign
Text text = new Text();
text.setDocumentId("1");
text.setPageNumber("1");
text.setRecipientId("1");
text.setXPosition("100");
text.setYPosition("100");
List<Text> textTabs = new ArrayList<Text>();
textTabs.add(text);
Tabs tabs = new Tabs();
tabs.setTextTabs(textTabs);
signer.setTabs(tabs);
// Above causes issue
envDef.setRecipients(new Recipients());
envDef.getRecipients().setSigners(new ArrayList<Signer>());
envDef.getRecipients().getSigners().add(signer);
// send the envelope (otherwise it will be "created" in the Draft folder
envDef.setStatus("sent");
//String currentDir = System.getProperty("user.dir");
try {
ApiClient apiClient = new ApiClient();
apiClient.setBasePath(BaseUrl);
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);
Assert.assertNotNull(envelopeSummary);
Assert.assertNotNull(envelopeSummary.getEnvelopeId());
System.out.println("EnvelopeSummary: " + envelopeSummary);
byte[] pdfBytes = envelopesApi.getDocument(accountId, envelopeSummary.getEnvelopeId(), "combined");
Assert.assertTrue(pdfBytes.length > 0);
/*
* try {
*
* File pdfFile = File.createTempFile("ds_", "pdf", null);
* FileOutputStream fos = new FileOutputStream(pdfFile);
* fos.write(pdfBytes);
*
* // show the PDF Desktop.getDesktop().open(pdfFile);
*
*
* } catch (Exception ex) {
* Assert.fail("Could not create pdf File");
*
* }
*/
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void ListDocumentsTest() {
System.out.println("\nListDocumentsTest:\n" + "===========================================");
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeDocumentsResult docsList = envelopesApi.listDocuments(accountId, envelopeIds[0]);
Assert.assertNotNull(docsList);
Assert.assertEquals(envelopeIds[0], docsList.getEnvelopeId());
System.out.println("EnvelopeDocumentsResult: " + docsList);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void ResendEnvelopeTest() {
System.out.println("\nResendEnvelopeTest:\n" + "===========================================");
byte[] fileBytes = null;
try {
// String currentDir = new java.io.File(".").getCononicalPath();
String currentDir = System.getProperty("user.dir");
Path path = Paths.get(currentDir + SignTest1File);
fileBytes = Files.readAllBytes(path);
} catch (IOException ioExcp) {
Assert.assertEquals(null, ioExcp);
}
// create an envelope to be signed
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.setEmailSubject("Please Sign my Java SDK Envelope");
envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");
// add a document to the envelope
Document doc = new Document();
String base64Doc = Base64.encodeToString(fileBytes, false);
doc.setDocumentBase64(base64Doc);
doc.setName("TestFile.pdf");
doc.setDocumentId("1");
List<Document> docs = new ArrayList<Document>();
docs.add(doc);
envDef.setDocuments(docs);
// Add a recipient to sign the document
Signer signer = new Signer();
signer.setEmail(UserName);
String name = "Pat Developer";
signer.setName(name);
signer.setRecipientId("1");
// this value represents the client's unique identifier for the signer
String clientUserId = "2939";
signer.setClientUserId(clientUserId);
// Create a SignHere tab somewhere on the document for the signer to
// sign
SignHere signHere = new SignHere();
signHere.setDocumentId("1");
signHere.setPageNumber("1");
signHere.setRecipientId("1");
signHere.setXPosition("100");
signHere.setYPosition("100");
signHere.setScaleValue("0.5");
List<SignHere> signHereTabs = new ArrayList<SignHere>();
signHereTabs.add(signHere);
Tabs tabs = new Tabs();
tabs.setSignHereTabs(signHereTabs);
signer.setTabs(tabs);
// Above causes issue
Recipients recipients = new Recipients();
recipients.setSigners(new ArrayList<Signer>());
recipients.getSigners().add(signer);
envDef.setRecipients(recipients);
envDef.setStatus("sent");
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);
Assert.assertNotNull(envelopeSummary);
Assert.assertNotNull(envelopeSummary.getEnvelopeId());
System.out.println("EnvelopeSummary: " + envelopeSummary);
EnvelopesApi.UpdateRecipientsOptions updateRecipientsOptions = envelopesApi.new UpdateRecipientsOptions();
updateRecipientsOptions.setResendEnvelope("true");
RecipientsUpdateSummary recipientsUpdateSummary = envelopesApi.updateRecipients(accountId,
envelopeSummary.getEnvelopeId(), recipients, updateRecipientsOptions);
Assert.assertNotNull(recipientsUpdateSummary);
Assert.assertTrue(recipientsUpdateSummary.getRecipientUpdateResults().size() > 0);
System.out.println("RecipientsUpdateSummary: " + recipientsUpdateSummary);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void GetDiagnosticLogsTest() {
System.out.println("\nGetDiagnosticLogsTest:\n" + "===========================================");
byte[] fileBytes = null;
try {
// String currentDir = new java.io.File(".").getCononicalPath();
String currentDir = System.getProperty("user.dir");
Path path = Paths.get(currentDir + SignTest1File);
fileBytes = Files.readAllBytes(path);
} catch (IOException ioExcp) {
Assert.assertEquals(null, ioExcp);
}
// create an envelope to be signed
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.setEmailSubject("Please Sign my Java SDK Envelope");
envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");
// add a document to the envelope
Document doc = new Document();
String base64Doc = Base64.encodeToString(fileBytes, false);
doc.setDocumentBase64(base64Doc);
doc.setName("TestFile.pdf");
doc.setDocumentId("1");
List<Document> docs = new ArrayList<Document>();
docs.add(doc);
envDef.setDocuments(docs);
// Add a recipient to sign the document
Signer signer = new Signer();
signer.setEmail(UserName);
String name = "Pat Developer";
signer.setName(name);
signer.setRecipientId("1");
// this value represents the client's unique identifier for the signer
String clientUserId = "2939";
signer.setClientUserId(clientUserId);
// Create a SignHere tab somewhere on the document for the signer to
// sign
SignHere signHere = new SignHere();
signHere.setDocumentId("1");
signHere.setPageNumber("1");
signHere.setRecipientId("1");
signHere.setXPosition("100");
signHere.setYPosition("100");
signHere.setScaleValue("0.5");
List<SignHere> signHereTabs = new ArrayList<SignHere>();
signHereTabs.add(signHere);
Tabs tabs = new Tabs();
tabs.setSignHereTabs(signHereTabs);
signer.setTabs(tabs);
// Above causes issue
envDef.setRecipients(new Recipients());
envDef.getRecipients().setSigners(new ArrayList<Signer>());
envDef.getRecipients().getSigners().add(signer);
// send the envelope (otherwise it will be "created" in the Draft folder
envDef.setStatus("sent");
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);
Assert.assertNotNull(envelopeSummary);
Assert.assertNotNull(envelopeSummary.getEnvelopeId());
System.out.println("EnvelopeSummary: " + envelopeSummary);
byte[] pdfBytes = envelopesApi.getDocument(accountId, envelopeSummary.getEnvelopeId(), "combined");
Assert.assertTrue(pdfBytes.length > 0);
/*
* try {
*
* File pdfFile = File.createTempFile("ds_", "pdf", null);
* FileOutputStream fos = new FileOutputStream(pdfFile);
* fos.write(pdfBytes);
*
* // show the PDF Desktop.getDesktop().open(pdfFile);
*
*
* } catch (Exception ex) {
* Assert.fail("Could not create pdf File");
*
* }
*/
DiagnosticsApi diagApi = new DiagnosticsApi();
ApiRequestLogsResult logsList = diagApi.listRequestLogs();
String requestLogId = logsList.getApiRequestLogs().get(0).getRequestLogId();
byte[] diagBytes = diagApi.getRequestLog(requestLogId);
Assert.assertTrue(diagBytes.length > 0);
/*
* try {
*
* File diagFile = File.createTempFile("ds_", "txt", null);
* FileOutputStream fos = new FileOutputStream(diagFile);
* fos.write(diagBytes);
*
* // show the PDF Desktop.getDesktop().open(diagFile);
*
*
* } catch (Exception ex) {
* Assert.fail("Could not create diag log File");
*
* }
*/
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void ListStatusChangesTest() {
System.out.println("\nListStatusChangesTest:\n" + "===========================================");
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
EnvelopesApi envelopesApi = new EnvelopesApi();
String envelopeIdsStr = StringUtil.join(envelopeIds, ",");
// set a filter for the envelopes we want returned using the envelopeIds property in the query parameter
EnvelopesApi.ListStatusChangesOptions listStatusChangesOptions = envelopesApi.new ListStatusChangesOptions();
listStatusChangesOptions.setEnvelopeIds(envelopeIdsStr);
EnvelopesInformation envelopesInformation = envelopesApi.listStatusChanges(accountId, listStatusChangesOptions);
Assert.assertNotNull(envelopesInformation);
Assert.assertNotNull(envelopesInformation.getEnvelopes().get(0));
Assert.assertNotNull(envelopesInformation.getEnvelopes().get(0).getEnvelopeId());
Assert.assertNotNull(envelopesInformation.getEnvelopes().get(0).getStatus());
System.out.println("EnvelopesInformation: " + envelopesInformation);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void ListStatusTest() {
System.out.println("\nListStatusTest:\n" + "===========================================");
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
EnvelopesApi envelopesApi = new EnvelopesApi();
// set a filter for the envelopes we want returned using the envelopeIds property in the body
EnvelopeIdsRequest envelopeIdsRequest = new EnvelopeIdsRequest();
envelopeIdsRequest.setEnvelopeIds(Arrays.asList(envelopeIds));
EnvelopesApi.ListStatusOptions listStatusOptions = envelopesApi.new ListStatusOptions();
listStatusOptions.setEnvelopeIds("request_body");
EnvelopesInformation envelopesInformation = envelopesApi.listStatus(accountId, envelopeIdsRequest, listStatusOptions);
Assert.assertNotNull(envelopesInformation);
Assert.assertNotNull(envelopesInformation.getEnvelopes().get(0));
Assert.assertNotNull(envelopesInformation.getEnvelopes().get(0).getEnvelopeId());
Assert.assertNotNull(envelopesInformation.getEnvelopes().get(0).getStatus());
System.out.println("EnvelopesInformation: " + envelopesInformation);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void UpdateBulkRecipientsTest() {
System.out.println("\nUpdateBulkRecipientsTest:\n" + "===========================================");
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
String templateRoleName = "Needs to sign";
// create an envelope to be signed
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.setEmailSubject("Please Sign my Java SDK Envelope");
envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");
/// assign template information including ID and role(s)
envDef.setTemplateId(TemplateId);
// create a template role with a valid templateId and roleName and
// assign signer info
TemplateRole tRole = new TemplateRole();
tRole.setRoleName(templateRoleName);
tRole.setName("Pat Developer");
tRole.setEmail("pat.developer@mailinator.com");
// create a list of template roles and add our newly created role
List<TemplateRole> templateRolesList = new ArrayList<TemplateRole>();
templateRolesList.add(tRole);
// assign template role(s) to the envelope
envDef.setTemplateRoles(templateRolesList);
// save as a draft
envDef.setStatus("created");
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);
BulkEnvelopesApi bulkEnvelopesApi = new BulkEnvelopesApi();
BulkRecipientsRequest bulkRecipientsRequest = new BulkRecipientsRequest();
BulkRecipient bulkRecipient1 = new BulkRecipient();
bulkRecipient1.setName("John Doe");
bulkRecipient1.setEmail("john.doe@mailinator.com");
BulkRecipient bulkRecipient2 = new BulkRecipient();
bulkRecipient2.setName("Jane Doe");
bulkRecipient2.setEmail("jane.doe@mailinator.com");
bulkRecipientsRequest.addBulkRecipientsItem(bulkRecipient1);
bulkRecipientsRequest.addBulkRecipientsItem(bulkRecipient2);
BulkRecipientsSummaryResponse bulkRecipientsSummaryResponse = bulkEnvelopesApi.updateRecipients(accountId, envelopeSummary.getEnvelopeId(), "1", bulkRecipientsRequest);
Assert.assertNotNull(bulkRecipientsSummaryResponse);
System.out.println("BulkRecipientsSummaryResponse: " + bulkRecipientsSummaryResponse);
// finally bulk send to all recipients
Envelope env = new Envelope();
env.setStatus("sent");
envelopesApi.update(accountId, envelopeSummary.getEnvelopeId(), env);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void UpdateChunkedUpload() {
System.out.println("\nUpdateChunkedUpload:\n" + "===========================================");
byte[] fileBytes = null;
try {
// String currentDir = new java.io.File(".").getCononicalPath();
String currentDir = System.getProperty("user.dir");
Path path = Paths.get(currentDir + SignTest1File);
fileBytes = Files.readAllBytes(path);
} catch (IOException ioExcp) {
Assert.assertEquals(null, ioExcp);
}
// create an envelope to be signed
EnvelopeDefinition envDef = new EnvelopeDefinition();
envDef.setEmailSubject("Please Sign my Java SDK Envelope");
envDef.setEmailBlurb("Hello, Please sign my Java SDK Envelope.");
// add a document to the envelope
Document doc = new Document();
//String base64Doc = Base64.encodeToString(fileBytes, false);
//doc.setDocumentBase64(base64Doc);
doc.setName("TestFile.pdf");
doc.setDocumentId("1");
List<Document> docs = new ArrayList<Document>();
docs.add(doc);
envDef.setDocuments(docs);
// Add a recipient to sign the document
Signer signer = new Signer();
signer.setEmail(UserName);
signer.setName("Pat Developer");
signer.setRecipientId("1");
// Create a SignHere tab somewhere on the document for the signer to
// sign
SignHere signHere = new SignHere();
signHere.setDocumentId("1");
signHere.setPageNumber("1");
signHere.setRecipientId("1");
signHere.setXPosition("100");
signHere.setYPosition("100");
signHere.setScaleValue("0.5");
List<SignHere> signHereTabs = new ArrayList<SignHere>();
signHereTabs.add(signHere);
Tabs tabs = new Tabs();
tabs.setSignHereTabs(signHereTabs);
signer.setTabs(tabs);
// Above causes issue
envDef.setRecipients(new Recipients());
envDef.getRecipients().setSigners(new ArrayList<Signer>());
envDef.getRecipients().getSigners().add(signer);
// send the envelope (otherwise it will be "created" in the Draft folder
envDef.setStatus("sent");
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
EnvelopesApi envelopesApi = new EnvelopesApi();
// upload 2 chunks
ChunkedUploadRequest chunkedUploadRequest1 = new ChunkedUploadRequest();
chunkedUploadRequest1.setData(Base64.encodeToString(Arrays.copyOfRange(fileBytes, 0, fileBytes.length / 2), false));
ChunkedUploadResponse chunkedUploadResponse1 = envelopesApi.createChunkedUpload(accountId, chunkedUploadRequest1);
final String chunkedUploadId = chunkedUploadResponse1.getChunkedUploadId();
final String chunkedUploadUri = chunkedUploadResponse1.getChunkedUploadUri();
ChunkedUploadRequest chunkedUploadRequest2 = new ChunkedUploadRequest();
chunkedUploadRequest2.setData(Base64.encodeToString(Arrays.copyOfRange(fileBytes, fileBytes.length / 2, fileBytes.length), false));
envelopesApi.updateChunkedUploadPart(accountId, chunkedUploadId, "1", chunkedUploadRequest2);
ChunkedUploadResponse updateChunkedUploadResponse = envelopesApi.updateChunkedUpload(accountId, chunkedUploadId);
//refer to the chuck
envDef.getDocuments().get(0).setRemoteUrl(chunkedUploadUri);
EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);
System.out.println("UpdateChunkedUploadResponse: " + updateChunkedUploadResponse);
Assert.assertNotNull(envelopeSummary);
Assert.assertNotNull(envelopeSummary.getEnvelopeId());
Assert.assertEquals("sent", envelopeSummary.getStatus());
System.out.println("EnvelopeSummary: " + envelopeSummary);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
@Test
public void UpdateBrandLogoByTypeTest() {
System.out.println("\nUpdateBrandLogoByTypeTest:\n" + "===========================================");
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
System.out.println("UserInfo: " + userInfo);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
byte[] brandLogoBytes = null;
try {
brandLogoBytes = Files.readAllBytes(Paths.get(brandLogoFullPath));
} catch (IOException ioExcp) {
Assert.assertEquals(null, ioExcp);
}
if (brandLogoBytes == null) return;
AccountsApi accountsApi = new AccountsApi();
accountsApi.updateBrandLogoByType(accountId, BrandId, "primary", brandLogoBytes);
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
Assert.fail("Exception: " + e.getLocalizedMessage());
}
}
private String[] getLastTenEnvelopeIds() {
String [] envelopeIds = new String[0];
ApiClient apiClient = new ApiClient(BaseUrl);
//String currentDir = System.getProperty("user.dir");
try {
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
java.util.List<String> scopes = new ArrayList<String>();
scopes.add(OAuth.Scope_SIGNATURE);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
Assert.assertNotSame(null, oAuthToken);
// now that the API client has an OAuth token, let's use it in all
// DocuSign APIs
apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());
Assert.assertNotSame(null, userInfo);
Assert.assertNotNull(userInfo.getAccounts());
Assert.assertTrue(userInfo.getAccounts().size() > 0);
// parse first account's baseUrl
// below code required for production, no effect in demo (same
// domain)
apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
Configuration.setDefaultApiClient(apiClient);
String accountId = userInfo.getAccounts().get(0).getAccountId();
// This example gets statuses of all envelopes in your account going back 1 full month...
DateTime fromDate = new DateTime();
fromDate = fromDate.minusDays(30);
String fromDateStr = fromDate.toString("yyyy-MM-dd");
// set a filter for the envelopes we want returned using the fromDate and count properties
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopesApi.ListStatusChangesOptions listStatusChangesOptions = envelopesApi.new ListStatusChangesOptions();
listStatusChangesOptions.setCount("10");
listStatusChangesOptions.setFromDate(fromDateStr);
// |EnvelopesApi| contains methods related to envelopes and envelope recipients
EnvelopesInformation envelopesInformation = envelopesApi.listStatusChanges(accountId, listStatusChangesOptions);
Assert.assertNotNull(envelopesInformation);
Assert.assertNotNull(envelopesInformation.getEnvelopes().get(0));
Assert.assertNotNull(envelopesInformation.getEnvelopes().get(0).getEnvelopeId());
Assert.assertNotNull(envelopesInformation.getEnvelopes().get(0).getStatus());
List<Envelope> envelopes = envelopesInformation.getEnvelopes();
envelopeIds = new String[envelopes.size()];
for (int i = 0; i < envelopes.size(); i++){
envelopeIds[i] = envelopes.get(i).getEnvelopeId();
}
} catch (ApiException ex) {
Assert.fail("Exception: " + ex);
} catch (Exception e) {
e.printStackTrace();
Assert.fail("Exception: " + e.getLocalizedMessage());
}
return envelopeIds;
}
}
|
package org.opencms.gwt.client.ui.contextmenu;
import org.opencms.gwt.client.CmsCoreProvider;
import org.opencms.gwt.client.rpc.CmsRpcAction;
import org.opencms.gwt.shared.CmsContextMenuEntryBean;
import org.opencms.util.CmsUUID;
import com.google.gwt.user.client.Window;
/**
* Provides a method to open the workplace.<p>
*
* @since 8.0.0
*/
public final class CmsShowWorkplace implements I_CmsHasContextMenuCommand {
/**
* Hidden utility class constructor.<p>
*/
private CmsShowWorkplace() {
// nothing to do
}
/**
* Returns the context menu command according to
* {@link org.opencms.gwt.client.ui.contextmenu.I_CmsHasContextMenuCommand}.<p>
*
* @return the context menu command
*/
public static I_CmsContextMenuCommand getContextMenuCommand() {
return new I_CmsContextMenuCommand() {
public void execute(CmsUUID structureId, I_CmsContextMenuHandler handler, CmsContextMenuEntryBean bean) {
openWorkplace(structureId);
}
public String getCommandIconClass() {
return org.opencms.gwt.client.ui.css.I_CmsImageBundle.INSTANCE.contextMenuIcons().workplace();
}
};
}
/**
* Opens the workplace.<p>
*
* @param structureId the structure id of the resource for which the workplace should be opened
*/
protected static void openWorkplace(final CmsUUID structureId) {
CmsRpcAction<String> callback = new CmsRpcAction<String>() {
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()
*/
@Override
public void execute() {
CmsCoreProvider.getService().getWorkplaceLink(structureId, this);
}
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object)
*/
@Override
protected void onResponse(String result) {
int width = Window.getClientWidth();
int height = Window.getClientHeight();
int left = Window.getScrollLeft();
int top = Window.getScrollTop();
openWorkplace(result, width, height, left, top);
}
};
callback.execute();
}
/**
* Opens the workplace.<p>
*
* @param path the workplace path to open
* @param winWidth the width of the window
* @param winHeight the height of the window
* @param winLeft the left space of the window
* @param winTop the top space of the window
*/
protected static native void openWorkplace(String path, int winWidth, int winHeight, int winLeft, int winTop) /*-{
if ($wnd.opener && $wnd.opener != self) {
$wnd.opener.location.href = path;
$wnd.opener.focus();
} else {
var openerStr = 'width='
+ winWidth
+ ',height='
+ winHeight
+ ',left='
+ winLeft
+ ',top='
+ winTop
+ ',scrollbars=no,location=no,toolbar=no,menubar=no,directories=no,status=yes,resizable=yes';
var deWindow = $wnd.open(path, "DirectEditWorkplace", openerStr);
if (deWindow) {
deWindow.focus();
}
}
}-*/;
}
|
package hex;
import static org.junit.Assert.assertEquals;
import hex.glm.*;
import hex.glm.GLMParams.Family;
import java.io.File;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;
import org.junit.Test;
import water.*;
import water.deploy.Node;
import water.deploy.NodeVM;
import water.fvec.*;
public class GLMTest2 extends TestUtil {
@Test public void testGaussianRegression() throws InterruptedException, ExecutionException{
Key raw = Key.make("gaussian_test_data_raw");
Key parsed = Key.make("gaussian_test_data_parsed");
Key modelKey = Key.make("gaussian_test");
GLMModel model = null;
try {
// make data so that the expected coefficients is icept = col[0] = 1.0
FVecTest.makeByteVec(raw, "x,y\n0,0\n1,0.1\n2,0.2\n3,0.3\n4,0.4\n5,0.5\n6,0.6\n7,0.7\n8,0.8\n9,0.9");
Frame fr = ParseDataset2.parse(parsed, new Key[]{raw});
new GLM2("GLM test of gaussian(linear) regression.",modelKey,fr,false,Family.gaussian, Family.gaussian.defaultLink,0,0).run(null).get();
model = DKV.get(modelKey).get();
HashMap<String, Double> coefs = model.coefficients();
assertEquals(0.0,coefs.get("Intercept"),1e-4);
assertEquals(0.1,coefs.get("x"),1e-4);
}finally{
UKV.remove(raw);
UKV.remove(parsed);
if(model != null)model.delete();
}
}
/**
* Test Poisson regression on simple and small synthetic dataset.
* Equation is: y = exp(x+1);
*/
@Test public void testPoissonRegression() throws InterruptedException, ExecutionException {
Key raw = Key.make("poisson_test_data_raw");
Key parsed = Key.make("poisson_test_data_parsed");
Key modelKey = Key.make("poisson_test");
GLMModel model = null;
try {
// make data so that the expected coefficients is icept = col[0] = 1.0
FVecTest.makeByteVec(raw, "x,y\n0,2\n1,4\n2,8\n3,16\n4,32\n5,64\n6,128\n7,256");
Frame fr = ParseDataset2.parse(parsed, new Key[]{raw});
new GLM2("GLM test of poisson regression.",modelKey,fr,false,Family.poisson, Family.poisson.defaultLink,0,0).run(null).get();
model = DKV.get(modelKey).get();
for(double c:model.beta())assertEquals(Math.log(2),c,1e-4);
//new byte []{1,2,3,4,5,6,7,8, 9, 10,11,12,13,14},
// new byte []{0,1,2,3,1,4,9,18,23,31,20,25,37,45});
model.delete();
UKV.remove(raw);
FVecTest.makeByteVec(raw, "x,y\n1,0\n2,1\n3,2\n4,3\n5,1\n6,4\n7,9\n8,18\n9,23\n10,31\n11,20\n12,25\n13,37\n14,45\n");
fr = ParseDataset2.parse(parsed, new Key[]{raw});
new GLM2("GLM test of poisson regression(2).",modelKey,fr,false,Family.poisson, Family.poisson.defaultLink,0,0).run(null).get();
model = DKV.get(modelKey).get();
assertEquals(0.3396,model.beta()[1],1e-4);
assertEquals(0.2565,model.beta()[0],1e-4);
}finally{
UKV.remove(raw);
UKV.remove(parsed);
if(model != null)model.delete();
}
}
/**
* Test Gamma regression on simple and small synthetic dataset.
* Equation is: y = 1/(x+1);
* @throws ExecutionException
* @throws InterruptedException
*/
@Test public void testGammaRegression() throws InterruptedException, ExecutionException {
Key raw = Key.make("gamma_test_data_raw");
Key parsed = Key.make("gamma_test_data_parsed");
Key modelKey = Key.make("gamma_test");
GLMModel model = null;
try {
// make data so that the expected coefficients is icept = col[0] = 1.0
FVecTest.makeByteVec(raw, "x,y\n0,1\n1,0.5\n2,0.3333333\n3,0.25\n4,0.2\n5,0.1666667\n6,0.1428571\n7,0.125");
Frame fr = ParseDataset2.parse(parsed, new Key[]{raw});
// /public GLM2(String desc, Key dest, Frame src, Family family, Link link, double alpha, double lambda) {
double [] vals = new double[] {1.0,1.0};
//public GLM2(String desc, Key dest, Frame src, Family family, Link link, double alpha, double lambda) {
new GLM2("GLM test of gamma regression.",modelKey,fr,false,Family.gamma, Family.gamma.defaultLink,0,0).run(null).get();
model = DKV.get(modelKey).get();
for(double c:model.beta())assertEquals(1.0, c,1e-4);
}finally{
UKV.remove(raw);
UKV.remove(parsed);
if(model != null)model.delete();
}
}
//simple tweedie test
@Test public void testTweedieRegression() throws InterruptedException, ExecutionException{
Key raw = Key.make("gaussian_test_data_raw");
Key parsed = Key.make("gaussian_test_data_parsed");
Key modelKey = Key.make("gaussian_test");
GLMModel model = null;
try {
// make data so that the expected coefficients is icept = col[0] = 1.0
FVecTest.makeByteVec(raw, "x,y\n0,0\n1,0.1\n2,0.2\n3,0.3\n4,0.4\n5,0.5\n6,0.6\n7,0.7\n8,0.8\n9,0.9\n0,0\n1,0\n2,0\n3,0\n4,0\n5,0\n6,0\n7,0\n8,0\n9,0");
Frame fr = ParseDataset2.parse(parsed, new Key[]{raw});
double [] powers = new double [] {1.5,1.1,1.9};
double [] intercepts = new double []{3.643,1.318,9.154};
double [] xs = new double []{-0.260,-0.0284,-0.853};
for(int i = 0; i < powers.length; ++i){
new GLM2("GLM test of gaussian(linear) regression.",modelKey,fr,false,Family.tweedie, Family.tweedie.defaultLink,0,0).setTweedieVarPower(powers[i]).run(null).get();
model = DKV.get(modelKey).get();
HashMap<String, Double> coefs = model.coefficients();
assertEquals(intercepts[i],coefs.get("Intercept"),1e-3);
assertEquals(xs[i],coefs.get("x"),1e-3);
model.delete();
model = null;
}
}finally{
UKV.remove(raw);
UKV.remove(parsed);
if(model != null)model.delete();
}
}
/**
* Simple test for poisson, gamma and gaussian families (no regularization, test both lsm solvers).
* Basically tries to predict horse power based on other parameters of the cars in the dataset.
* Compare against the results from standard R glm implementation.
* @throws ExecutionException
* @throws InterruptedException
*/
@Test public void testCars() throws InterruptedException, ExecutionException{
Key parsed = Key.make("cars_parsed");
Key modelKey = Key.make("cars_model");
GLMModel model = null;
try{
String [] ignores = new String[]{"name"};
String response = "power (hp)";
Frame fr = getFrameForFile(parsed, "smalldata/cars.csv", ignores, response);
new GLM2("GLM test on cars.",modelKey,fr,true,Family.poisson,Family.poisson.defaultLink,0,0).run(null).get();
model = DKV.get(modelKey).get();
HashMap<String,Double> coefs = model.coefficients();
String [] cfs1 = new String[]{"Intercept","economy (mpg)", "cylinders", "displacement (cc)", "weight (lb)", "0-60 mph (s)", "year"};
double [] vls1 = new double []{4.9504805,-0.0095859,-0.0063046,0.0004392,0.0001762,-0.0469810,0.0002891};
for(int i = 0; i < cfs1.length; ++i)
assertEquals(vls1[i], coefs.get(cfs1[i]),1e-4);
// test gamma
double [] vls2 = new double []{8.992e-03,1.818e-04,-1.125e-04,1.505e-06,-1.284e-06,4.510e-04,-7.254e-05};
model.delete();
new GLM2("GLM test on cars.",modelKey,fr,true,Family.gamma,Family.gamma.defaultLink,0,0).run(null).get();
model = DKV.get(modelKey).get();
coefs = model.coefficients();
for(int i = 0; i < cfs1.length; ++i)
assertEquals(vls2[i], coefs.get(cfs1[i]),1e-4);
model.delete();
// test gaussian
double [] vls3 = new double []{166.95862,-0.00531,-2.46690,0.12635,0.02159,-4.66995,-0.85724};
new GLM2("GLM test on cars.",modelKey,fr,true,Family.gaussian,Family.gaussian.defaultLink,0,0).run(null).get();
model = DKV.get(modelKey).get();
coefs = model.coefficients();
for(int i = 0; i < cfs1.length; ++i)
assertEquals(vls3[i], coefs.get(cfs1[i]),1e-4);
} finally {
UKV.remove(parsed);
if(model != null)model.delete();
}
}
/**
* Simple test for binomial family (no regularization, test both lsm solvers).
* Runs the classical prostate, using dataset with race replaced by categoricals (probably as it's supposed to be?), in any case,
* it gets to test correct processing of categoricals.
*
* Compare against the results from standard R glm implementation.
* @throws ExecutionException
* @throws InterruptedException
*/
@Test public void testProstate() throws InterruptedException, ExecutionException{
Key parsed = Key.make("prostate_parsed");
Key modelKey = Key.make("prostate_model");
GLMModel model = null;
File f = TestUtil.find_test_file("smalldata/glm_test/prostate_cat_replaced.csv");
Frame fr = getFrameForFile(parsed, "smalldata/glm_test/prostate_cat_replaced.csv", new String[]{"ID"}, "CAPSULE");
try{
// R results
// Coefficients:
// (Intercept) ID AGE RACER2 RACER3 DPROS DCAPS PSA VOL GLEASON
// -8.894088 0.001588 -0.009589 0.231777 -0.459937 0.556231 0.556395 0.027854 -0.011355 1.010179
String [] cfs1 = new String [] {"Intercept","AGE", "RACE.R2","RACE.R3", "DPROS", "DCAPS", "PSA", "VOL", "GLEASON"};
double [] vals = new double [] {-8.14867, -0.01368, 0.32337, -0.38028, 0.55964, 0.49548, 0.02794, -0.01104, 0.97704};
new GLM2("GLM test on prostate.",modelKey,fr,false,Family.binomial,Family.binomial.defaultLink,0,0).run(null).get();
model = DKV.get(modelKey).get();
HashMap<String, Double> coefs = model.coefficients();
for(int i = 0; i < cfs1.length; ++i)
assertEquals(vals[i], coefs.get(cfs1[i]),1e-4);
GLMValidation val = model.validation();
assertEquals(512.3, val.nullDeviance(),1e-1);
assertEquals(378.3, val.residualDeviance(),1e-1);
assertEquals(396.3, val.aic(),1e-1);
} finally {
UKV.remove(parsed);
if(model != null)model.delete();
}
}
private static Frame getFrameForFile(Key outputKey, String path,String [] ignores, String response){
File f = TestUtil.find_test_file(path);
Key k = NFSFileVec.make(f);
try{
Frame fr = ParseDataset2.parse(outputKey, new Key[]{k});
if(ignores != null)
for(String s:ignores) UKV.remove(fr.remove(s)._key);
// put the response to the end
fr.add(response, fr.remove(response));
return GLMTask.adaptFrame(fr);
}finally{
UKV.remove(k);
}
}
public static void main(String [] args) throws Exception{
System.out.println("Running ParserTest2");
final int nnodes = 1;
for( int i = 1; i < nnodes; i++ ) {
Node n = new NodeVM(args);
n.inheritIO();
n.start();
}
H2O.waitForCloudSize(nnodes);
System.out.println("Running...");
new GLMTest2().testGaussianRegression();
new GLMTest2().testPoissonRegression();
new GLMTest2().testGammaRegression();
new GLMTest2().testTweedieRegression();
new GLMTest2().testProstate();
new GLMTest2().testCars();
System.out.println("DONE!");
}
}
|
package com.opencms.workplace;
import org.opencms.file.CmsGroup;
import org.opencms.file.CmsObject;
import org.opencms.file.CmsUser;
import org.opencms.i18n.CmsEncoder;
import org.opencms.main.CmsException;
import org.opencms.main.CmsLog;
import org.opencms.util.CmsDateUtil;
import org.opencms.workflow.CmsTask;
import org.opencms.workflow.CmsTaskService;
import com.opencms.core.I_CmsSession;
import com.opencms.legacy.CmsXmlTemplateLoader;
import com.opencms.template.A_CmsXmlContent;
import java.text.DateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.Vector;
public class CmsTaskContentDialogPriority extends CmsWorkplaceDefault {
/**
* Constant for generating user javascriptlist
*/
private final static String C_ALL_ROLES = "___all";
/**
* Constant for generating user javascriptlist
*/
private static String C_ROLE = null;
/**
* Constant for generating user javascriptlist
*/
private static String C_ROLE_1 = null;
/**
* Constant for generating user javascriptlist
*/
private static String C_ROLE_2 = null;
/**
* Constant for generating user javascriptlist
*/
private static String C_USER_1 = null;
/**
* Constant for generating user javascriptlist
*/
private static String C_USER_2 = null;
/**
* Constant for generating user javascriptlist
*/
private static String C_USER_3 = null;
/**
* Constant for generating user javascriptlist
*/
private static String C_USER_4 = null;
/**
* Constant for generating user javascriptlist
*/
private static String C_USER_5 = null;
/**
* Gets the content of a defined section in a given template file and its subtemplates
* with the given parameters.
*
* @see #getContent(CmsObject, String, String, Hashtable, String)
* @param cms CmsObject Object for accessing system resources.
* @param templateFile Filename of the template file.
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
*/
public byte[] getContent(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) throws CmsException {
if(CmsLog.getLog(this).isDebugEnabled() && C_DEBUG) {
CmsLog.getLog(this).debug("Getting content of element " + ((elementName==null)?"<root>":elementName));
CmsLog.getLog(this).debug("Template file is: " + templateFile);
CmsLog.getLog(this).debug("Selected template section is: " + ((templateSelector==null)?"<default>":templateSelector));
}
String taskName = "";
String taskDescription = "";
String due = "";
String paraAcceptation = "";
String paraAll = "";
String paraCompletion = "";
String paraDelivery = "";
String userIdxString = "";
String groupIdxString = "";
I_CmsSession session = CmsXmlTemplateLoader.getSession(cms.getRequestContext(), true);
CmsXmlWpTemplateFile xmlTemplateDocument = (CmsXmlWpTemplateFile)getOwnTemplateFile(cms,
templateFile, elementName, parameters, templateSelector);
// are the constants read from the cms already?
if(C_ROLE == null) {
// declare the constants
initConstants(xmlTemplateDocument);
}
try {
String taskidstr = (String)parameters.get("taskid");
int taskid;
if(taskidstr == null || taskidstr == "") {
Integer sessionTaskid = (Integer)session.getValue("taskid");
taskid = sessionTaskid.intValue();
}
else {
Integer taskidInt = new Integer(taskidstr);
taskid = taskidInt.intValue();
session.putValue("taskid", taskidInt);
}
CmsTaskService taskService = cms.getTaskService();
CmsTask task = taskService.readTask(taskid);
taskName = task.getName();
taskDescription = CmsTaskAction.getDescription(cms, task.getId());
paraAcceptation = taskService.getTaskPar(task.getId(), CmsWorkplaceDefault.C_TASKPARA_ACCEPTATION);
paraAll = taskService.getTaskPar(task.getId(), CmsWorkplaceDefault.C_TASKPARA_ALL);
paraCompletion = taskService.getTaskPar(task.getId(), CmsWorkplaceDefault.C_TASKPARA_COMPLETION);
paraDelivery = taskService.getTaskPar(task.getId(), CmsWorkplaceDefault.C_TASKPARA_DELIVERY);
// we have to creagte a date in german date format, otherwise the redisplay in the dialogs does
// not work correctly.
due = CmsDateUtil.getDate(new Date(task.getTimeOut().getTime()), DateFormat.MEDIUM, new Locale("de"));
// preselect the old user and role in the dialog for forwarding and resurrection
// compute the indices of the user and role
String username = taskService.readAgent(task).getName();
String groupname = taskService.readGroup(task).getName();
int userindex = 0;
int groupindex = 0;
List groups = cms.getGroups();
List users = cms.getUsersOfGroup(groupname);
int n = 0;
for(int z = 0;z < groups.size();z++) {
CmsGroup group = (CmsGroup)groups.get(z);
if(group.getRole()) {
n++;
if(group.getName().equals(groupname)) {
groupindex = n;
}
}
}
for(int z = 0;z < users.size();z++) {
if(((CmsUser)users.get(z)).getName().equals(username)) {
userindex = z + 1;
}
}
userIdxString = (new Integer(userindex)).toString();
groupIdxString = (new Integer(groupindex)).toString();
}
catch(Exception exc) {
// unexpected exception - ignoring
}
xmlTemplateDocument.setData("task", CmsEncoder.escape(taskName,
cms.getRequestContext().getEncoding()));
xmlTemplateDocument.setData("description", CmsEncoder.escape(taskDescription,
cms.getRequestContext().getEncoding()));
xmlTemplateDocument.setData("due", due);
xmlTemplateDocument.setData(CmsWorkplaceDefault.C_TASKPARA_ACCEPTATION, paraAcceptation);
xmlTemplateDocument.setData(CmsWorkplaceDefault.C_TASKPARA_ALL, paraAll);
xmlTemplateDocument.setData(CmsWorkplaceDefault.C_TASKPARA_COMPLETION, paraCompletion);
xmlTemplateDocument.setData(CmsWorkplaceDefault.C_TASKPARA_DELIVERY, paraDelivery);
xmlTemplateDocument.setData("groupindex", groupIdxString);
xmlTemplateDocument.setData("userindex", userIdxString);
// Now load the template file and start the processing
return startProcessing(cms, xmlTemplateDocument, elementName, parameters, templateSelector);
}
/**
* Gets all priorities, that are defined for a project.
* <P>
* The given vectors <code>names</code> and <code>values</code> will
* be filled with the appropriate information to be used for building
* a select box.
*
* @param cms CmsObject Object for accessing system resources.
* @param names Vector to be filled with the appropriate values in this method.
* @param values Vector to be filled with the appropriate values in this method.
* @param parameters Hashtable containing all user parameters <em>(not used here)</em>.
* @return Index representing the current value in the vectors.
* @throws CmsException
*/
public Integer getPriority(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values,
Hashtable parameters) throws CmsException {
// get session for current taskid
I_CmsSession session = CmsXmlTemplateLoader.getSession(cms.getRequestContext(), true);
// read current task for priority-level
CmsTask task = cms.getTaskService().readTask(((Integer)session.getValue("taskid")).intValue());
// add names for priority
names.addElement(lang.getLanguageValue("task.label.prioritylevel.high"));
names.addElement(lang.getLanguageValue("task.label.prioritylevel.middle"));
names.addElement(lang.getLanguageValue("task.label.prioritylevel.low"));
// add values for priority
values.addElement(org.opencms.workflow.CmsTaskService.TASK_PRIORITY_HIGH + "");
values.addElement(CmsTaskService.TASK_PRIORITY_NORMAL + "");
values.addElement(org.opencms.workflow.CmsTaskService.TASK_PRIORITY_LOW + "");
// return the current priority
return new Integer(task.getPriority() - 1);
}
/**
* Gets all groups, that may work for a project.
* <P>
* The given vectors <code>names</code> and <code>values</code> will
* be filled with the appropriate information to be used for building
* a select box.
*
* @param cms CmsObject Object for accessing system resources.
* @param names Vector to be filled with the appropriate values in this method.
* @param values Vector to be filled with the appropriate values in this method.
* @param parameters Hashtable containing all user parameters <em>(not used here)</em>.
* @return Index representing the current value in the vectors.
* @throws CmsException
*/
public Integer getTeams(CmsObject cms, CmsXmlLanguageFile lang, Vector names, Vector values,
Hashtable parameters) throws CmsException {
// get all groups
List groups = cms.getGroups();
CmsGroup group;
names.addElement(lang.getLanguageValue("task.label.emptyrole"));
values.addElement(lang.getLanguageValue("task.label.emptyrole"));
// fill the names and values
for(int z = 0;z < groups.size();z++) {
group = (CmsGroup)groups.get(z);
// is the group a role?
if(group.getRole()) {
String name = group.getName();
names.addElement(name);
values.addElement(name);
}
}
names.addElement(lang.getLanguageValue("task.label.allroles"));
values.addElement(C_ALL_ROLES);
// no current group, set index to -1
return new Integer(-1);
}
/**
* @param cms CmsObject Object for accessing system resources.
* @param tagcontent Unused in this special case of a user method. Can be ignored.
* @param doc Reference to the A_CmsXmlContent object of the initiating XLM document <em>(not used here)</em>.
* @param userObj Hashtable with parameters <em>(not used here)</em>.
* @return String with the pics URL.
* @throws CmsException
*/
public Object getUsers(CmsObject cms, String tagcontent, A_CmsXmlContent doc,
Object userObj) throws CmsException {
StringBuffer retValue = new StringBuffer();
retValue.append(C_ROLE);
// get the language for choose-user
String chooseUser = (new CmsXmlLanguageFile(cms)).getLanguageValue("task.label.emptyuser");
// get all groups
List groups = cms.getGroups();
for(int n = 0;n < groups.size();n++) {
if(((CmsGroup)groups.get(n)).getRole()) {
String groupname = ((CmsGroup)groups.get(n)).getName();
// get users of this group
List users = cms.getUsersOfGroup(groupname);
// create entry for role
retValue.append(C_ROLE_1 + groupname + C_ROLE_2);
retValue.append(C_USER_1 + groupname + C_USER_2 + 0 + C_USER_3 + chooseUser + C_USER_4 + C_USER_5);
for(int m = 0;m < users.size();m++) {
CmsUser user = (CmsUser)users.get(m);
// create entry for user
retValue.append(C_USER_1 + groupname + C_USER_2 + (m + 1) + C_USER_3
+ user.getName() + C_USER_4 + user.getName() + C_USER_5);
}
}
}
// generate output for all users
retValue.append(C_ROLE_1 + C_ALL_ROLES + C_ROLE_2);
retValue.append(C_USER_1 + C_ALL_ROLES + C_USER_2 + 0 + C_USER_3 + chooseUser + C_USER_4 + C_USER_5);
List users = cms.getUsers();
for(int m = 0;m < users.size();m++) {
CmsUser user = (CmsUser)users.get(m);
// create entry for user
retValue.append(C_USER_1 + C_ALL_ROLES + C_USER_2 + (m + 1) + C_USER_3
+ user.getName() + C_USER_4 + user.getName() + C_USER_5);
}
return retValue.toString();
}
/**
* This method initializes all constants, that are needed for genrating this pages.
*
* @param document The xml-document to get the constant content from.
*/
private void initConstants(CmsXmlWpTemplateFile document) {
try {
// exists the needed datablocks?
if(document.hasData("role")) {
// YES: initialize the constants
C_ROLE = document.getDataValue("role");
C_ROLE_1 = document.getDataValue("role_1");
C_ROLE_2 = document.getDataValue("role_2");
C_USER_1 = document.getDataValue("user_1");
C_USER_2 = document.getDataValue("user_2");
C_USER_3 = document.getDataValue("user_3");
C_USER_4 = document.getDataValue("user_4");
C_USER_5 = document.getDataValue("user_5");
}
}
catch(CmsException exc) {
if(CmsLog.getLog(this).isWarnEnabled() ) {
CmsLog.getLog(this).warn("Couldn't get xml datablocks for CmsTaskNew", exc);
}
}
}
/**
* Indicates if the results of this class are cacheable.
*
* @param cms CmsObject Object for accessing system resources
* @param templateFile Filename of the template file
* @param elementName Element name of this template in our parent template.
* @param parameters Hashtable with all template class parameters.
* @param templateSelector template section that should be processed.
* @return <EM>true</EM> if cacheable, <EM>false</EM> otherwise.
*/
public boolean isCacheable(CmsObject cms, String templateFile, String elementName,
Hashtable parameters, String templateSelector) {
return false;
}
}
|
package com.sunshineapps.riftexample;
import static com.oculusvr.capi.OvrLibrary.ovrDistortionCaps.ovrDistortionCap_Chromatic;
import static com.oculusvr.capi.OvrLibrary.ovrDistortionCaps.ovrDistortionCap_TimeWarp;
import static com.oculusvr.capi.OvrLibrary.ovrDistortionCaps.ovrDistortionCap_Vignette;
import static com.oculusvr.capi.OvrLibrary.ovrEyeType.ovrEye_Count;
import static com.oculusvr.capi.OvrLibrary.ovrEyeType.ovrEye_Left;
import static com.oculusvr.capi.OvrLibrary.ovrEyeType.ovrEye_Right;
import static com.oculusvr.capi.OvrLibrary.ovrTrackingCaps.ovrTrackingCap_MagYawCorrection;
import static com.oculusvr.capi.OvrLibrary.ovrTrackingCaps.ovrTrackingCap_Orientation;
import static com.oculusvr.capi.OvrLibrary.ovrTrackingCaps.ovrTrackingCap_Position;
import static org.lwjgl.glfw.Callbacks.errorCallbackPrint;
import static org.lwjgl.glfw.GLFW.GLFW_CURSOR;
import static org.lwjgl.glfw.GLFW.GLFW_CURSOR_NORMAL;
import static org.lwjgl.glfw.GLFW.GLFW_KEY_ESCAPE;
import static org.lwjgl.glfw.GLFW.GLFW_KEY_R;
import static org.lwjgl.glfw.GLFW.GLFW_RELEASE;
import static org.lwjgl.glfw.GLFW.glfwCreateWindow;
import static org.lwjgl.glfw.GLFW.glfwDestroyWindow;
import static org.lwjgl.glfw.GLFW.glfwInit;
import static org.lwjgl.glfw.GLFW.glfwMakeContextCurrent;
import static org.lwjgl.glfw.GLFW.glfwPollEvents;
import static org.lwjgl.glfw.GLFW.glfwSetErrorCallback;
import static org.lwjgl.glfw.GLFW.glfwSetInputMode;
import static org.lwjgl.glfw.GLFW.glfwSetKeyCallback;
import static org.lwjgl.glfw.GLFW.glfwSetWindowShouldClose;
import static org.lwjgl.glfw.GLFW.glfwShowWindow;
import static org.lwjgl.glfw.GLFW.glfwTerminate;
import static org.lwjgl.glfw.GLFW.glfwWindowShouldClose;
import static org.lwjgl.opengl.GL11.GL_AMBIENT;
import static org.lwjgl.opengl.GL11.GL_CCW;
import static org.lwjgl.opengl.GL11.GL_COLOR_ARRAY;
import static org.lwjgl.opengl.GL11.GL_COLOR_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.GL_COLOR_MATERIAL;
import static org.lwjgl.opengl.GL11.GL_CULL_FACE;
import static org.lwjgl.opengl.GL11.GL_DECAL;
import static org.lwjgl.opengl.GL11.GL_DEPTH_BUFFER_BIT;
import static org.lwjgl.opengl.GL11.GL_DIFFUSE;
import static org.lwjgl.opengl.GL11.GL_FALSE;
import static org.lwjgl.opengl.GL11.GL_LIGHT0;
import static org.lwjgl.opengl.GL11.GL_LIGHTING;
import static org.lwjgl.opengl.GL11.GL_MODELVIEW;
import static org.lwjgl.opengl.GL11.GL_NORMAL_ARRAY;
import static org.lwjgl.opengl.GL11.GL_POSITION;
import static org.lwjgl.opengl.GL11.GL_PROJECTION;
import static org.lwjgl.opengl.GL11.GL_QUADS;
import static org.lwjgl.opengl.GL11.GL_SPECULAR;
import static org.lwjgl.opengl.GL11.GL_SPOT_CUTOFF;
import static org.lwjgl.opengl.GL11.GL_TEXTURE_2D;
import static org.lwjgl.opengl.GL11.GL_TEXTURE_COORD_ARRAY;
import static org.lwjgl.opengl.GL11.GL_TEXTURE_ENV;
import static org.lwjgl.opengl.GL11.GL_TEXTURE_ENV_MODE;
import static org.lwjgl.opengl.GL11.GL_TRUE;
import static org.lwjgl.opengl.GL11.GL_VERTEX_ARRAY;
import static org.lwjgl.opengl.GL11.glBegin;
import static org.lwjgl.opengl.GL11.glBindTexture;
import static org.lwjgl.opengl.GL11.glClear;
import static org.lwjgl.opengl.GL11.glClearColor;
import static org.lwjgl.opengl.GL11.glColor4f;
import static org.lwjgl.opengl.GL11.glDisable;
import static org.lwjgl.opengl.GL11.glEnable;
import static org.lwjgl.opengl.GL11.glEnableClientState;
import static org.lwjgl.opengl.GL11.glEnd;
import static org.lwjgl.opengl.GL11.glFrontFace;
import static org.lwjgl.opengl.GL11.glLightf;
import static org.lwjgl.opengl.GL11.glLightfv;
import static org.lwjgl.opengl.GL11.glLoadIdentity;
import static org.lwjgl.opengl.GL11.glLoadMatrixf;
import static org.lwjgl.opengl.GL11.glMatrixMode;
import static org.lwjgl.opengl.GL11.glNormal3f;
import static org.lwjgl.opengl.GL11.glTexCoord2f;
import static org.lwjgl.opengl.GL11.glTexEnvf;
import static org.lwjgl.opengl.GL11.glTranslatef;
import static org.lwjgl.opengl.GL11.glVertex3f;
import static org.lwjgl.system.MemoryUtil.NULL;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.lwjgl.BufferUtils;
import org.lwjgl.PointerBuffer;
import org.lwjgl.Sys;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWKeyCallback;
import org.lwjgl.glfw.GLFWvidmode;
import org.lwjgl.opengl.ARBFramebufferObject;
import org.lwjgl.opengl.GLContext;
import org.saintandreas.math.Matrix4f;
import org.saintandreas.math.Quaternion;
import org.saintandreas.math.Vector3f;
import com.oculusvr.capi.EyeRenderDesc;
import com.oculusvr.capi.FovPort;
import com.oculusvr.capi.GLTexture;
import com.oculusvr.capi.GLTextureData;
import com.oculusvr.capi.Hmd;
import com.oculusvr.capi.OvrLibrary;
import com.oculusvr.capi.OvrMatrix4f;
import com.oculusvr.capi.OvrQuaternionf;
import com.oculusvr.capi.OvrRecti;
import com.oculusvr.capi.OvrSizei;
import com.oculusvr.capi.OvrVector2i;
import com.oculusvr.capi.OvrVector3f;
import com.oculusvr.capi.Posef;
import com.oculusvr.capi.RenderAPIConfig;
import com.oculusvr.capi.TextureHeader;
import com.sunshineapps.riftexample.thirdparty.FrameBuffer;
import com.sunshineapps.riftexample.thirdparty.MatrixStack;
import com.sunshineapps.riftexample.thirdparty.Texture;
import com.sunshineapps.riftexample.thirdparty.TextureLoader;
public final class RiftClient0440 {
private final boolean useDebugHMD = true;
private final int RIFT_MONITOR = 1; //This needs to be set manually since we cant detect which is the rift currently. try 0 or 1
private long window;
private long riftMonitorId;
private final int riftWidth = 1920; //DK2
private final int riftHeight = 1080; //DK2
private GLFWErrorCallback errorfun;
private GLFWKeyCallback keyfun;
//OpenGL
private final FloatBuffer projectionDFB[];
private final FloatBuffer modelviewDFB;
private FrameBuffer eyeDFB[];
// private FixedTexture cheq;
private Texture floorTexture;
private Texture wallTexture;
private Texture ceilingTexture;
private float roomSize = 6.0f;
private float roomHeight = 2.6f*2;
// Rift Specific
private Hmd hmd;
private int frameCount = -1;
private final OvrVector3f eyeOffsets[] = (OvrVector3f[]) new OvrVector3f().toArray(2);
private final OvrRecti[] eyeRenderViewport = (OvrRecti[]) new OvrRecti().toArray(2);
private final Posef poses[] = (Posef[]) new Posef().toArray(2);
private final GLTexture eyeTextures[] = (GLTexture[]) new GLTexture().toArray(2);
private final FovPort fovPorts[] = (FovPort[]) new FovPort().toArray(2);
private final Matrix4f projections[] = new Matrix4f[2];
private float ipd = OvrLibrary.OVR_DEFAULT_IPD;
private float eyeHeight = OvrLibrary.OVR_DEFAULT_EYE_HEIGHT;
// Scene
private Matrix4f player;
//FPS
private final int fpsReportingPeriodSeconds = 5;
private final ScheduledExecutorService fpsCounter = Executors.newSingleThreadScheduledExecutor();
private final AtomicInteger frames = new AtomicInteger(0);
private final AtomicInteger fps = new AtomicInteger(0);
Runnable fpsJob = new Runnable() {
public void run() {
int frameCount = frames.getAndSet(0);
fps.set(frameCount/fpsReportingPeriodSeconds);
frames.addAndGet(frameCount-(fps.get()*fpsReportingPeriodSeconds));
System.out.println(frameCount+" frames in "+fpsReportingPeriodSeconds+"s. "+fps.get()+"fps");
}
};
public RiftClient0440() {
System.out.println("RiftClient0440()");
modelviewDFB = ByteBuffer.allocateDirect(4*4*4).order(ByteOrder.nativeOrder()).asFloatBuffer();
projectionDFB = new FloatBuffer[2];
for (int eye = 0; eye < 2; ++eye) {
projectionDFB[eye] = ByteBuffer.allocateDirect(4*4*4).order(ByteOrder.nativeOrder()).asFloatBuffer();
}
}
public boolean findRift() {
PointerBuffer monitors = GLFW.glfwGetMonitors();
IntBuffer modeCount = BufferUtils.createIntBuffer(1);
for (int i = 0; i < monitors.limit(); i++) {
long monitorId = monitors.get(i);
System.out.println("monitor: " + monitorId);
ByteBuffer modes = GLFW.glfwGetVideoModes(monitorId, modeCount);
System.out.println("mode count=" + modeCount.get(0));
for (int j = 0; j < modeCount.get(0); j++) {
modes.position(j * GLFWvidmode.SIZEOF);
int width = GLFWvidmode.width(modes);
int height = GLFWvidmode.height(modes);
// System.out.println(width + "," + height + "," + monitorId);
if (width == riftWidth && height == riftHeight) {
System.out.println("found dimensions match: " + width + "," + height + "," + monitorId);
riftMonitorId = monitorId;
if (i == RIFT_MONITOR) {
return true;
}
}
}
System.out.println("
}
return (riftMonitorId != 0);
}
private void recenterView() {
Vector3f center = Vector3f.UNIT_Y.mult(eyeHeight);
// Vector3f eye = new Vector3f(0, eyeHeight, ipd * 10.0f); //jherico
Vector3f eye = new Vector3f(ipd * 5.0f, eyeHeight, 0.0f);
player = Matrix4f.lookat(eye, center, Vector3f.UNIT_Y).invert();
// worldToCamera = Matrix4f.lookat(eye, center, Vector3f.UNIT_Y);
hmd.recenterPose();
}
//Z- is into the screen
public final void drawPlaneFloor() {
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
float tileSize = 1.0f; // if same then there are two tiles per square
glBegin(GL_QUADS);
{
glNormal3f(0f, 1f, 0f);
glColor4f(1f, 1f, 1f, 1f);
glTexCoord2f(0f, 0f);
glVertex3f(-roomSize, 0f, roomSize);
glTexCoord2f(tileSize, 0f);
glVertex3f(roomSize, 0f, roomSize);
glTexCoord2f(tileSize, tileSize);
glVertex3f(roomSize, 0f, -roomSize);
glTexCoord2f(0f, tileSize);
glVertex3f(-roomSize, 0f, -roomSize);
}
glEnd();
}
public final void drawPlaneCeiling() {
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
float tileSize = 1.0f; // if same then there are two tiles per square
glBegin(GL_QUADS);
{
glNormal3f(0f, -1f, 0f);
glColor4f(1f, 1f, 1f, 1f);
glTexCoord2f(0f, 0f);
glVertex3f(-roomSize, 0f, roomSize);
glTexCoord2f(0f, tileSize);
glVertex3f(-roomSize, 0f, -roomSize);
glTexCoord2f(tileSize, tileSize);
glVertex3f(roomSize, 0f, -roomSize);
glTexCoord2f(tileSize, 0f);
glVertex3f(roomSize, 0f, roomSize);
}
glEnd();
}
//Z- is into the screen
public final void drawPlaneWallLeft() { //appears in front
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
float tileSize = 1.0f;
glBegin(GL_QUADS);
{
glNormal3f(1f, 0f, 0f);
glColor4f(1f, 1f, 1f, 1f);
glTexCoord2f(tileSize*6, 0f);
glVertex3f(-roomSize, 0f, roomSize);
glTexCoord2f(0f, 0f);
glVertex3f(-roomSize, 0f, -roomSize);
glTexCoord2f(0f, tileSize);
glVertex3f(-roomSize, roomHeight, -roomSize);
glTexCoord2f(tileSize*6, tileSize);
glVertex3f(-roomSize, roomHeight, roomSize);
}
glEnd();
}
//Z- is into the screen
public final void drawPlaneWallFront() { //appears to right
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
float tileSize = 1.0f;
glBegin(GL_QUADS);
{
glNormal3f(0f, 0f, 1f);
glColor4f(1f, 1f, 1f, 1f);
glTexCoord2f(tileSize*6, 0f);
glVertex3f(-roomSize, 0f, -roomSize);
glTexCoord2f(0f, 0f);
glVertex3f(roomSize, 0f, -roomSize);
glTexCoord2f(0f, tileSize);
glVertex3f(roomSize, roomHeight, -roomSize);
glTexCoord2f(tileSize*6, tileSize);
glVertex3f(-roomSize, roomHeight, -roomSize);
}
glEnd();
}
public final void drawPlaneWallRight() { //appears behind
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
float tileSize = 1.0f;
glBegin(GL_QUADS);
{
glNormal3f(-1f, 0f, 0f);
glColor4f(1f, 1f, 1f, 1f);
glTexCoord2f(tileSize*6, 0f);
glVertex3f(roomSize, 0f, -roomSize);
glTexCoord2f(0f, 0f);
glVertex3f(roomSize, 0f, roomSize);
glTexCoord2f(0f, tileSize);
glVertex3f(roomSize, roomHeight, roomSize);
glTexCoord2f(tileSize*6, tileSize);
glVertex3f(roomSize, roomHeight, -roomSize);
}
glEnd();
}
public final void drawPlaneWallBack() { //appears
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
float tileSize = 1.0f;
glBegin(GL_QUADS);
{
glNormal3f(0f, 0f, -1f);
glColor4f(1f, 1f, 1f, 1f);
glTexCoord2f(tileSize*6, 0f);
glVertex3f(roomSize, 0f, roomSize);
glTexCoord2f(0f, 0f);
glVertex3f(-roomSize, 0f, roomSize);
glTexCoord2f(0f, tileSize);
glVertex3f(-roomSize, roomHeight, roomSize);
glTexCoord2f(tileSize*6, tileSize);
glVertex3f(roomSize, roomHeight, roomSize);
}
glEnd();
}
public void run() {
System.out.println(""+System.getProperty("java.version"));
// step 1 - hmd init
System.out.println("step 1 - hmd init");
Hmd.initialize();
try {
Thread.sleep(400);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
// step 2 - hmd create
System.out.println("step 2 - hmd create");
hmd = Hmd.create(0); // assume 1 device at index 0
if (hmd == null) {
System.out.println("null hmd");
hmd = Hmd.createDebug(OvrLibrary.ovrHmdType.ovrHmd_DK2);
if (!useDebugHMD) {
return;
}
}
// step 3 - hmd size queries
System.out.println("step 3 - hmd sizes");
OvrSizei resolution = hmd.Resolution;
System.out.println("resolution= " + resolution.w + "x" + resolution.h);
OvrSizei recommendedTex0Size = hmd.getFovTextureSize(ovrEye_Left, hmd.DefaultEyeFov[ovrEye_Left], 1.0f);
OvrSizei recommendedTex1Size = hmd.getFovTextureSize(ovrEye_Right, hmd.DefaultEyeFov[ovrEye_Right], 1.0f);
System.out.println("left= " + recommendedTex0Size.w + "x" + recommendedTex0Size.h);
System.out.println("right= " + recommendedTex1Size.w + "x" + recommendedTex1Size.h);
int displayW = recommendedTex0Size.w + recommendedTex1Size.w;
int displayH = Math.max(recommendedTex0Size.h, recommendedTex1Size.h);
OvrSizei renderTargetEyeSize = new OvrSizei(displayW / 2, displayH); //single eye
System.out.println("using eye size " + renderTargetEyeSize.w + "x" + renderTargetEyeSize.h);
eyeRenderViewport[ovrEye_Left].Pos = new OvrVector2i(0, 0);
eyeRenderViewport[ovrEye_Left].Size = renderTargetEyeSize;
eyeRenderViewport[ovrEye_Right].Pos = eyeRenderViewport[ovrEye_Left].Pos;
eyeRenderViewport[ovrEye_Right].Size = renderTargetEyeSize;
eyeTextures[ovrEye_Left].ogl = new GLTextureData(new TextureHeader(renderTargetEyeSize, eyeRenderViewport[ovrEye_Left]));
eyeTextures[ovrEye_Right].ogl = new GLTextureData(new TextureHeader(renderTargetEyeSize, eyeRenderViewport[ovrEye_Right]));
// step 4 - tracking
System.out.println("step 4 - tracking");
if (hmd.configureTracking(ovrTrackingCap_Orientation | ovrTrackingCap_MagYawCorrection | ovrTrackingCap_Position, 0) == 0) {
throw new IllegalStateException("Unable to start the sensor");
}
// step 5 - FOV
System.out.println("step 5 - FOV");
for (int eye = 0; eye < ovrEye_Count; ++eye) {
fovPorts[eye] = hmd.DefaultEyeFov[eye];
projections[eye] = toMatrix4f(Hmd.getPerspectiveProjection(fovPorts[eye], 0.1f, 1000000f, true));
}
// step 6 - player params
System.out.println("step 6 - player params");
ipd = hmd.getFloat(OvrLibrary.OVR_KEY_IPD, ipd);
eyeHeight = hmd.getFloat(OvrLibrary.OVR_KEY_EYE_HEIGHT, eyeHeight);
recenterView();
System.out.println("eyeheight=" + eyeHeight + " ipd=" + ipd);
System.out.println("Hello LWJGL " + Sys.getVersion() + "!");
try {
init();
loop();
glfwDestroyWindow(window);
} finally {
glfwTerminate();
fpsCounter.shutdown();
keyfun.release();
errorfun.release();
}
}
private void init() {
// step 7 - opengl window
System.out.println("step 7 - window");
errorfun = errorCallbackPrint(System.err);
glfwSetErrorCallback(errorfun);
if (glfwInit() != GL_TRUE) {
throw new IllegalStateException("Unable to initialize GLFW");
}
// glfwDefaultWindowHints(); //not needed
if (findRift()) {
window = glfwCreateWindow(riftWidth, riftHeight, "Hello World!", riftMonitorId, NULL); //where is this text used?
System.out.println("found rift and using it " + riftMonitorId);
} else {
window = glfwCreateWindow(riftWidth, riftHeight, "Hello World!", NULL, NULL);
System.out.println("use rift debug mode");
}
if (window == NULL) {
throw new RuntimeException("Failed to create the GLFW window");
}
keyfun = new GLFWKeyCallback() {
@Override
public void invoke(long window, int key, int scancode, int action, int mods) {
if ( action != GLFW_RELEASE) {
return;
}
switch (key) {
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GL_TRUE);
break;
case GLFW_KEY_R:
recenterView();
break;
}
}
};
glfwSetKeyCallback(window, keyfun);
glfwMakeContextCurrent(window);
// glfwSwapInterval(1); //not needed?
glfwShowWindow(window);
// glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED); //only after display create?
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL); //only after display create?
//glfwSetInputMode(id, GLFW_CURSOR, GLFW_CURSOR_HIDDEN); //hide mouse
GLContext.createFromCurrent();
glClearColor(.42f, .67f, .87f, 1f);
glEnable(GL_CULL_FACE);
glFrontFace(GL_CCW);
// Lighting
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glEnable(GL_COLOR_MATERIAL);
FloatBuffer lightPos = ByteBuffer.allocateDirect(4*4).order(ByteOrder.nativeOrder()).asFloatBuffer();
lightPos.put(new float[]{0.5f, 0.0f, 1.0f, 0.0001f});
lightPos.rewind();
FloatBuffer noAmbient = ByteBuffer.allocateDirect(4*4).order(ByteOrder.nativeOrder()).asFloatBuffer();
noAmbient.put(new float[]{0.2f, 0.2f, 0.2f, 1.0f});
noAmbient.rewind();
FloatBuffer diffuse = ByteBuffer.allocateDirect(4*4).order(ByteOrder.nativeOrder()).asFloatBuffer();
diffuse.put(new float[]{1.0f, 1.0f, 1.0f, 1.0f});
diffuse.rewind();
FloatBuffer spec = ByteBuffer.allocateDirect(4*4).order(ByteOrder.nativeOrder()).asFloatBuffer();
spec.put(new float[]{1.0f, 1.0f, 1.0f, 1.0f});
spec.rewind();
glLightfv(GL_LIGHT0, GL_AMBIENT, noAmbient);
glLightfv(GL_LIGHT0, GL_SPECULAR, spec);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse);
glLightfv(GL_LIGHT0, GL_POSITION, lightPos);
glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 45.0f);
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_NORMAL_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
RenderAPIConfig rc = new RenderAPIConfig();
rc.Header.BackBufferSize = hmd.Resolution;
rc.Header.Multisample = 1;
int distortionCaps = ovrDistortionCap_Chromatic | ovrDistortionCap_TimeWarp | ovrDistortionCap_Vignette;
EyeRenderDesc eyeRenderDescs[] = hmd.configureRendering(rc, distortionCaps, fovPorts);
for (int eye = 0; eye < 2; ++eye) {
eyeOffsets[eye].x = eyeRenderDescs[eye].HmdToEyeViewOffset.x;
eyeOffsets[eye].y = eyeRenderDescs[eye].HmdToEyeViewOffset.y;
eyeOffsets[eye].z = eyeRenderDescs[eye].HmdToEyeViewOffset.z;
}
eyeDFB = new FrameBuffer[2];
eyeDFB[ovrEye_Left] = new FrameBuffer(eyeRenderViewport[ovrEye_Left].Size.w, eyeRenderViewport[ovrEye_Left].Size.h);
eyeDFB[ovrEye_Right] = new FrameBuffer(eyeRenderViewport[ovrEye_Right].Size.w, eyeRenderViewport[ovrEye_Right].Size.h);
eyeTextures[ovrEye_Left].ogl.TexId = eyeDFB[ovrEye_Left].getTexture().id;
eyeTextures[ovrEye_Right].ogl.TexId = eyeDFB[ovrEye_Right].getTexture().id;
// scene prep
TextureLoader loader = new TextureLoader();
try {
floorTexture = loader.getTexture("floor512512.png");
wallTexture = loader.getTexture("panel512512.png");
ceilingTexture = loader.getTexture("ceiling512512.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// does not work for some reason
// glEnable(GL_TEXTURE_2D);
// cheq = new FixedTexture(BuiltinTexture.tex_checker);
// glDisable(GL_TEXTURE_2D);
// glBindTexture(GL_TEXTURE_2D, 0);
// initial matrix stuff
glMatrixMode(GL_PROJECTION);
for (int eye = 0; eye < ovrEye_Count; ++eye) {
MatrixStack.PROJECTION.set(projections[eye]);
glMatrixMode(GL_PROJECTION);
MatrixStack.PROJECTION.top().fillFloatBuffer(projectionDFB[eye], true);
projectionDFB[eye].rewind();
glLoadMatrixf(projectionDFB[eye]);
}
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
recenterView();
MatrixStack.MODELVIEW.set(player.invert());
modelviewDFB.clear();
MatrixStack.MODELVIEW.top().fillFloatBuffer(modelviewDFB, true);
modelviewDFB.rewind();
glLoadMatrixf(modelviewDFB);
//fps
fpsCounter.scheduleAtFixedRate(fpsJob, 0, fpsReportingPeriodSeconds, TimeUnit.SECONDS);
}
private void loop() {
// step 8 - animator loop
System.out.println("step 8 - animator loop");
while (glfwWindowShouldClose(window) == GL_FALSE) {
hmd.beginFrameTiming(++frameCount);
Posef eyePoses[] = hmd.getEyePoses(frameCount, eyeOffsets);
for (int eyeIndex = 0; eyeIndex < ovrEye_Count; eyeIndex++) {
int eye = hmd.EyeRenderOrder[eyeIndex];
Posef pose = eyePoses[eye];
poses[eye].Orientation = pose.Orientation;
poses[eye].Position = pose.Position;
eyeDFB[eye].activate();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(projectionDFB[eye]);
glMatrixMode(GL_MODELVIEW);
MatrixStack mv = MatrixStack.MODELVIEW;
mv.push();
{
mv.preTranslate(toVector3f(poses[eye].Position).mult(-1));
mv.preRotate(toQuaternion(poses[eye].Orientation).inverse());
mv.translate(new Vector3f(0, eyeHeight, 0));
modelviewDFB.clear();
MatrixStack.MODELVIEW.top().fillFloatBuffer(modelviewDFB, true);
modelviewDFB.rewind();
glLoadMatrixf(modelviewDFB);
// tiles on floor
glEnable(GL_TEXTURE_2D);
// glBindTexture(GL_TEXTURE_2D, cheq.getId());
floorTexture.bind();
glTranslatef(0.0f, -eyeHeight, 0.0f);
drawPlaneFloor();
floorTexture.unbind();
wallTexture.bind();
drawPlaneWallLeft();
drawPlaneWallFront();
drawPlaneWallRight();
drawPlaneWallBack();
wallTexture.unbind();
ceilingTexture.bind();
glTranslatef(0.0f, roomHeight, 0.0f);
drawPlaneCeiling();
glTranslatef(0.0f, -roomHeight, 0.0f);
ceilingTexture.unbind();
glTranslatef(0.0f, eyeHeight, 0.0f);
glDisable(GL_TEXTURE_2D);
}
mv.pop();
}
ARBFramebufferObject.glBindFramebuffer(ARBFramebufferObject.GL_FRAMEBUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_TEXTURE_2D);
glfwPollEvents();
frames.incrementAndGet();
hmd.endFrame(poses, eyeTextures);
}
}
public Vector3f toVector3f(OvrVector3f v) {
return new Vector3f(v.x, v.y, v.z);
}
public Quaternion toQuaternion(OvrQuaternionf q) {
return new Quaternion(q.x, q.y, q.z, q.w);
}
public Matrix4f toMatrix4f(OvrMatrix4f m) {
return new org.saintandreas.math.Matrix4f(m.M).transpose();
}
public static void main(String[] args) {
new RiftClient0440().run();
}
}
|
package com.malhartech.demos.ads;
import com.malhartech.api.DAG;
import com.malhartech.dag.ApplicationFactory;
import com.malhartech.lib.io.ConsoleOutputOperator;
import com.malhartech.lib.io.HttpOutputOperator;
import com.malhartech.lib.math.Margin;
import com.malhartech.lib.math.Quotient;
import com.malhartech.lib.math.Sum;
import com.malhartech.lib.stream.StreamMerger;
import com.malhartech.lib.testbench.EventClassifier;
import com.malhartech.lib.testbench.EventGenerator;
import com.malhartech.lib.testbench.FilteredEventClassifier;
import com.malhartech.lib.testbench.ThroughputCounter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.apache.hadoop.conf.Configuration;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Example of application configuration in Java using {@link com.malhartech.stram.conf.NewDAGBuilder}.<p>
*/
public class Application implements ApplicationFactory
{
public static final String P_generatorVTuplesBlast = Application.class.getName() + ".generatorVTuplesBlast";
public static final String P_generatorMaxWindowsCount = Application.class.getName() + ".generatorMaxWindowsCount";
public static final String P_allInline = Application.class.getName() + ".allInline";
public static final String P_enableHdfs = Application.class.getName() + ".enableHdfs";
// adjust these depending on execution mode (junit, cli-local, cluster)
private int generatorVTuplesBlast = 1000;
private int generatorMaxWindowsCount = 100;
private int generatorWindowCount = 1;
private boolean allInline = true;
public void setUnitTestMode()
{
generatorVTuplesBlast = 10;
generatorWindowCount = 5;
generatorMaxWindowsCount = 20;
}
public void setLocalMode()
{
generatorVTuplesBlast = 1000; // keep this number low to not distort window boundaries
//generatorVTuplesBlast = 500000;
generatorWindowCount = 5;
//generatorMaxWindowsCount = 50;
generatorMaxWindowsCount = 1000;
}
private void configure(Configuration conf)
{
if (LAUNCHMODE_YARN.equals(conf.get(DAG.STRAM_LAUNCH_MODE))) {
setLocalMode();
// settings only affect distributed mode
conf.setIfUnset(DAG.STRAM_CONTAINER_MEMORY_MB, "2048");
conf.setIfUnset(DAG.STRAM_MASTER_MEMORY_MB, "1024");
conf.setIfUnset(DAG.STRAM_MAX_CONTAINERS, "1");
}
else if (LAUNCHMODE_LOCAL.equals(conf.get(DAG.STRAM_LAUNCH_MODE))) {
setLocalMode();
}
this.generatorVTuplesBlast = conf.getInt(P_generatorVTuplesBlast, this.generatorVTuplesBlast);
this.generatorMaxWindowsCount = conf.getInt(P_generatorMaxWindowsCount, this.generatorMaxWindowsCount);
this.allInline = conf.getBoolean(P_allInline, this.allInline);
}
/**
* Map properties from application to operator scope
*
* @param dag
* @param op
*/
public static Map<String, String> getOperatorInstanceProperties(Configuration appConf, Class<?> appClass, String operatorId)
{
String keyPrefix = appClass.getName() + "." + operatorId + ".";
Map<String, String> values = appConf.getValByRegex(keyPrefix + "*");
Map<String, String> properties = new HashMap<String, String>(values.size());
for (Map.Entry<String, String> e: values.entrySet()) {
properties.put(e.getKey().replace(keyPrefix, ""), e.getValue());
}
return properties;
}
private Operator getConsoleOperatorInstance(DAG b, String name)
{
// output to HTTP server when specified in environment setting
Operator ret;
String serverAddr = System.getenv("MALHAR_AJAXSERVER_ADDRESS");
if (serverAddr != null) {
HttpOutputOperator oper = b.addOperator(name, HttpOutputOperator.class);
URI u = null;
try {
u = new URI("http://" + serverAddr + "/channel/" + name);
}
catch (URISyntaxException ex) {
Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
}
oper.setResourceURL(u);
ret = oper;
}
else {
ConsoleOutputOperator oper = b.addOperator(name, ConsoleOutputOperator.class);
oper.setStringFormat(name + ": %s");
ret = oper;
}
return ret;
}
private HttpOutputOperator<HashMap<String,Number>> getHttpOutputNumberOperator(DAG b, String name)
{
// output to HTTP server when specified in environment setting
String serverAddr = System.getenv("MALHAR_AJAXSERVER_ADDRESS");
HttpOutputOperator<HashMap<String,Number>> oper = b.addOperator(name, new HttpOutputOperator<HashMap<String,Number>>());
URI u = null;
try {
u = new URI("http://" + serverAddr + "/channel/" + name);
}
catch (URISyntaxException ex) {
Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
}
oper.setResourceURL(u);
return oper;
}
private ConsoleOutputOperator<HashMap<String,Number>> getConsoleNumberOperator(DAG b, String name)
{
// output to HTTP server when specified in environment setting
ConsoleOutputOperator<HashMap<String,Number>> oper = b.addOperator(name, new ConsoleOutputOperator<HashMap<String,Number>>());
oper.setStringFormat(name + ": %s");
return oper;
}
private ConsoleOutputOperator<HashMap<String,Double>> getConsoleDoubleOperator(DAG b, String name)
{
// output to HTTP server when specified in environment setting
ConsoleOutputOperator<HashMap<String,Double>> oper = b.addOperator(name, new ConsoleOutputOperator<HashMap<String,Double>>());
oper.setStringFormat(name + ": %s");
return oper;
}
/*
private DAG.InputPort getViewsToHdfsOperatorInstance(DAG dag, String operatorName)
{
Map<String, String> props = getOperatorInstanceProperties(dag.getConf(), this.getClass(), operatorName);
OperatorInstance o = dag.addOperator(operatorName, HdfsOutputModule.class);
o.setProperty(HdfsOutputModule.KEY_APPEND, "false");
o.setProperty(HdfsOutputModule.KEY_FILEPATH, "file:///tmp/adsdemo/views-%(moduleId)-part%(partIndex)");
for (Map.Entry<String, String> e: props.entrySet()) {
o.setProperty(e.getKey(), e.getValue());
}
return o.getInput(HdfsOutputModule.INPUT);
}
*/
public Operator getSumOperator(String name, DAG b, String debug)
{
return b.addOperator(name, Sum.class);
}
public Operator getStreamMerger(String name, DAG b)
{
return b.addOperator(name, StreamMerger.class);
}
public Operator getThroughputCounter(String name, DAG b)
{
ThroughputCounter oper = b.addOperator(name, ThroughputCounter.class);
oper.setRollingWindowCount(5);
return oper;
}
public Operator getMarginOperator(String name, DAG b)
{
Margin oper = b.addOperator(name, Margin.class);
oper.setPercent(true);
return oper;
}
public Operator getQuotientOperator(String name, DAG b)
{
Quotient oper = b.addOperator(name, Quotient.class);
oper.setMult_by(100);
oper.setDokey(true);
return oper;
}
public Operator getPageViewGenOperator(String name, DAG b)
{
EventGenerator oper = b.addOperator(name, EventGenerator.class);
oper.setKeys("home,finance,sports,mail");
// Paying $2.15,$3,$1.75,$.6 for 1000 views respectively
oper.setValues("0.00215,0.003,0.00175,0.0006");
oper.setWeights("25,25,25,25");
oper.setTuplesBlast(this.generatorVTuplesBlast);
oper.setMaxcountofwindows(generatorMaxWindowsCount);
oper.setRollingWindowCount(this.generatorWindowCount);
return oper;
}
public Operator getAdViewsStampOperator(String name, DAG b)
{
EventClassifier oper = b.addOperator(name, EventClassifier.class);
HashMap<String, Double> kmap = new HashMap<String, Double>();
kmap.put("sprint", 0.0);
kmap.put("etrace", 0.0);
kmap.put("nike", 0.0);
oper.setKeyMap(kmap);
return oper;
}
public Operator getInsertClicksOperator(String name, DAG b)
{
FilteredEventClassifier<Double> oper = b.addOperator(name, new FilteredEventClassifier<Double>());
HashMap<String, Double> kmap = new HashMap<String, Double>();
// Getting $1,$5,$4 per click respectively
kmap.put("sprint", 1.0);
kmap.put("etrade", 5.0);
kmap.put("nike", 4.0);
HashMap<String, ArrayList<Integer>> wmap = new HashMap<String, ArrayList<Integer>>();
ArrayList<Integer> alist = new ArrayList<Integer>(3);
alist.add(60);
alist.add(10);
alist.add(30);
wmap.put("home", alist);
alist = new ArrayList<Integer>(3);
alist.add(10);
alist.add(75);
alist.add(15);
wmap.put("finance", alist);
alist = new ArrayList<Integer>(3);
alist.add(10);
alist.add(10);
alist.add(80);
wmap.put("sports", alist);
alist.add(50);
alist.add(15);
alist.add(35);
wmap.put("mail", alist);
oper.setKeyWeights(wmap);
oper.setPassFilter(40);
oper.setTotalFilter(1000);
return oper;
}
@Override
public DAG getApplication(Configuration conf)
{
configure(conf);
DAG dag = new DAG();
Operator viewGen = getPageViewGenOperator("viewGen", dag);
Operator adviews = getAdViewsStampOperator("adviews", dag);
Operator insertclicks = getInsertClicksOperator("insertclicks", dag);
Operator viewAggregate = getSumOperator("viewAggr", dag, "");
Operator clickAggregate = getSumOperator("clickAggr", dag, "");
Operator ctr = getQuotientOperator("ctr", dag);
Operator cost = getSumOperator("cost", dag, "");
Operator revenue = getSumOperator("rev", dag, "");
Operator margin = getMarginOperator("margin", dag);
Operator merge = getStreamMerger("countmerge", dag);
Operator tuple_counter = getThroughputCounter("tuple_counter", dag);
dag.addStream("views", viewGen.getOutput(EventGenerator.OPORT_DATA), adviews.getInput(EventClassifier.IPORT_IN_DATA)).setInline(true);
StreamDecl viewsAggStream = dag.addStream("viewsaggregate", adviews.getOutput(EventClassifier.OPORT_OUT_DATA), insertclicks.getInput(FilteredEventClassifier.IPORT_IN_DATA),
viewAggregate.getInput(Sum.IPORT_DATA)).setInline(true);
/*
if (conf.getBoolean(P_enableHdfs, false)) {
DAG.InputPort viewsToHdfs = getViewsToHdfsOperatorInstance(dag, "viewsToHdfs");
viewsAggStream.addSink(viewsToHdfs);
}
*/
dag.addStream("clicksaggregate", insertclicks.filter, clickAggregate.data).setInline(true);
dag.addStream("clicksaggregate", insertclicks.getOutput(FilteredEventClassifier.OPORT_OUT_DATA), clickAggregate.getInput(Sum.IPORT_DATA)).setInline(true);
dag.addStream("adviewsdata", viewAggregate.getOutput(Sum.OPORT_SUM), cost.getInput(Sum.IPORT_DATA));
dag.addStream("clicksdata", clickAggregate.getOutput(Sum.OPORT_SUM), revenue.getInput(Sum.IPORT_DATA));
dag.addStream("viewtuplecount", viewAggregate.getOutput(Sum.OPORT_COUNT), ctr.getInput(Quotient.IPORT_DENOMINATOR), merge.getInput(StreamMerger.IPORT_IN_DATA1));
dag.addStream("clicktuplecount", clickAggregate.getOutput(Sum.OPORT_COUNT), ctr.getInput(Quotient.IPORT_NUMERATOR), merge.getInput(StreamMerger.IPORT_IN_DATA2));
dag.addStream("total count", merge.getOutput(StreamMerger.OPORT_OUT_DATA), tuple_counter.getInput(ThroughputCounter.IPORT_DATA));
Operator revconsole = getConsoleOperatorInstance(dag, "revConsole");
Operator costconsole = getConsoleOperatorInstance(dag, "costConsole");
Operator marginconsole = getConsoleOperatorInstance(dag, "marginConsole");
Operator ctrconsole = getConsoleOperatorInstance(dag, "ctrConsole");
Operator viewcountconsole = getConsoleOperatorInstance(dag, "viewCountConsole");
dag.addStream("revenuedata", revenue.getOutput(Sum.OPORT_SUM), margin.getInput(Margin.IPORT_DENOMINATOR), revconsole.getInput(ConsoleOutputOperator.INPUT)).setInline(allInline);
dag.addStream("costdata", cost.getOutput(Sum.OPORT_SUM), margin.getInput(Margin.IPORT_NUMERATOR), costconsole.getInput(ConsoleOutputOperator.INPUT)).setInline(allInline);
dag.addStream("margindata", margin.getOutput(Margin.OPORT_MARGIN), marginconsole.getInput(ConsoleOutputOperator.INPUT)).setInline(allInline);
dag.addStream("ctrdata", ctr.getOutput(Quotient.OPORT_QUOTIENT), ctrconsole.getInput(ConsoleOutputOperator.INPUT)).setInline(allInline);
dag.addStream("tuplecount", tuple_counter.getOutput(ThroughputCounter.OPORT_COUNT), viewcountconsole.getInput(ConsoleOutputOperator.INPUT)).setInline(allInline);
String serverAddr = System.getenv("MALHAR_AJAXSERVER_ADDRESS");
if (serverAddr == null) {
ConsoleOutputOperator<HashMap<String, Double>> revconsole = getConsoleDoubleOperator(dag, "revConsole");
ConsoleOutputOperator<HashMap<String, Double>> costconsole = getConsoleDoubleOperator(dag, "costConsole");
ConsoleOutputOperator<HashMap<String, Double>> marginconsole = getConsoleDoubleOperator(dag, "marginConsole");
ConsoleOutputOperator<HashMap<String, Double>> ctrconsole = getConsoleDoubleOperator(dag, "ctrConsole");
ConsoleOutputOperator<HashMap<String, Number>> viewcountconsole = getConsoleNumberOperator(dag, "viewCountConsole");
dag.addStream("revenuedata", revenue.sum, margin.denominator, revconsole.input).setInline(allInline);
dag.addStream("costdata", cost.sum, margin.numerator, costconsole.input).setInline(allInline);
dag.addStream("margindata", margin.margin, marginconsole.input).setInline(allInline);
dag.addStream("ctrdata", ctr.quotient, ctrconsole.input).setInline(allInline);
dag.addStream("tuplecount", tuple_counter.count, viewcountconsole.input).setInline(allInline);
}
else {
HttpOutputOperator<HashMap<String, Double>> revhttp = getHttpOutputDoubleOperator(dag, "revConsole");
HttpOutputOperator<HashMap<String, Double>> costhttp = getHttpOutputDoubleOperator(dag, "costConsole");
HttpOutputOperator<HashMap<String, Double>> marginhttp = getHttpOutputDoubleOperator(dag, "marginConsole");
HttpOutputOperator<HashMap<String, Double>> ctrhttp = getHttpOutputDoubleOperator(dag, "ctrConsole");
HttpOutputOperator<HashMap<String, Number>> viewcounthttp = getHttpOutputNumberOperator(dag, "viewCountConsole");
dag.addStream("revenuedata", revenue.sum, margin.denominator, revhttp.input).setInline(allInline);
dag.addStream("costdata", cost.sum, margin.numerator, costhttp.input).setInline(allInline);
dag.addStream("margindata", margin.margin, marginhttp.input).setInline(allInline);
dag.addStream("ctrdata", ctr.quotient, ctrhttp.input).setInline(allInline);
dag.addStream("tuplecount", tuple_counter.count, viewcounthttp.input).setInline(allInline);
}
return dag;
}
}
|
package org.cru.godtools.migration;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.ccci.util.xml.XmlDocumentSearchUtilities;
import org.cru.godtools.domain.languages.Language;
import org.cru.godtools.domain.languages.LanguageCode;
import org.cru.godtools.domain.languages.LanguageService;
import org.cru.godtools.domain.packages.Package;
import org.cru.godtools.domain.packages.PackageService;
import org.cru.godtools.domain.packages.PackageStructure;
import org.cru.godtools.domain.packages.PackageStructureService;
import org.cru.godtools.domain.packages.Page;
import org.cru.godtools.domain.packages.PageStructure;
import org.cru.godtools.domain.packages.PageStructureService;
import org.cru.godtools.domain.packages.TranslationElementService;
import org.cru.godtools.domain.translations.Translation;
import org.cru.godtools.domain.translations.TranslationService;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/**
* Encapsulates logic for a package directory. (e.g: "/Packages/kgp")
*
* - build a Package
* - build a list of Languages a Package is translated into
* - build a list of Icons represented by a Package
*/
public class PackageDirectory
{
public static final String DIRECTORY_BASE = "/Packages-dir/";
private String packageCode;
private PackageService packageService;
private LanguageService languageService;
private TranslationService translationService;
private TranslationElementService translationElementService;
private PackageStructureService packageStructureService;
private PageStructureService pageStructureService;
public PackageDirectory(String packageCode)
{
this.packageCode = packageCode;
}
public PackageDirectory(String packageCode, PackageService packageService, LanguageService languageService, TranslationService translationService, TranslationElementService translationElementService, PackageStructureService packageStructureService, PageStructureService pageStructureService)
{
this.packageCode = packageCode;
this.packageService = packageService;
this.languageService = languageService;
this.translationService = translationService;
this.translationElementService = translationElementService;
this.packageStructureService = packageStructureService;
this.pageStructureService = pageStructureService;
}
public Package buildPackage() throws Exception
{
File directory = getDirectory();
for(File nextFile : directory.listFiles())
{
if(nextFile.isFile() && nextFile.getName().equalsIgnoreCase("en.xml"))
{
Package gtPackage = new Package();
gtPackage.setId(UUID.randomUUID());
gtPackage.setName(getPackageName(getPackageDescriptorXml(nextFile)));
gtPackage.setCode(packageCode);
return gtPackage;
}
}
throw new RuntimeException("unable to build package for packageCode: " + packageCode);
}
/**
* Returns a list of all the languages represented in this package directory.
*
* @return
* @throws Exception
*/
public List<Language> buildLanguages() throws Exception
{
List<Language> languages = Lists.newArrayList();
File directory = getDirectory();
for(File nextFile : directory.listFiles())
{
if(nextFile.isFile() && nextFile.getName().endsWith(".xml"))
{
PackageDescriptorFile packageDescriptorFile = new PackageDescriptorFile(nextFile);
Language language = new Language();
language.setId(UUID.randomUUID());
language.setCode(packageDescriptorFile.getLanguageCode());
language.setLocale(packageDescriptorFile.getLocaleCode());
language.setSubculture(packageDescriptorFile.getSubculture());
languages.add(language);
}
}
return languages;
}
public Document getPackageDescriptorXml(Language language) throws IOException, SAXException, ParserConfigurationException
{
String path = DIRECTORY_BASE + packageCode + "/";
path += language.getCode();
if(!Strings.isNullOrEmpty(language.getLocale())) path = path + "-" + language.getLocale();
if(!Strings.isNullOrEmpty(language.getSubculture())) path = path + "-" + language.getSubculture();
path += ".xml";
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
return builder.parse(this.getClass().getResourceAsStream(path));
}
public ImageDirectory getSharedImageDirectory() throws URISyntaxException, FileNotFoundException
{
File thisDirectory = getDirectory();
for(File possibleSharedDirectory : thisDirectory.listFiles())
{
if(possibleSharedDirectory.isDirectory() && possibleSharedDirectory.getName().equals("shared"))
{
return new ImageDirectory(possibleSharedDirectory);
}
}
throw new FileNotFoundException("no shared images directory found");
}
public ImageDirectory getIconDirectory() throws URISyntaxException, FileNotFoundException
{
File thisDirectory = getDirectory();
for(File possibleSharedDirectory : thisDirectory.listFiles())
{
if(possibleSharedDirectory.isDirectory() && possibleSharedDirectory.getName().equals("icons"))
{
return new ImageDirectory(possibleSharedDirectory);
}
}
throw new FileNotFoundException("no shared images directory found");
}
public void savePackageStructures() throws Exception
{
Package gtPackage = packageService.selectByCode(packageCode);
PackageStructure englishPackageStructure = getEnglishPackageStructure(gtPackage);
for(Translation translation : translationService.selectByPackageId(gtPackage.getId()))
{
PackageStructure translatedPackageStructure = getTranslatedPackageStructure(gtPackage, translation);
TranslatableElements translatableElements = new TranslatableElements(englishPackageStructure.getXmlContent(),
translatedPackageStructure.getXmlContent(),
packageCode + ".xml",
translation.getId());
saveTranslatedName(translation, translatedPackageStructure);
translatableElements.save(translationElementService);
}
packageStructureService.insert(englishPackageStructure);
}
private void saveTranslatedName(Translation translation, PackageStructure translatedPackageStructure)
{
List<Element> packageNameElementList = XmlDocumentSearchUtilities.findElements(translatedPackageStructure.getXmlContent(), "packagename");
// there should be exactly one, if there are zero oh well.. if there are more.. idk
if(packageNameElementList.size() == 1)
{
translation.setTranslatedName(packageNameElementList.get(0).getTextContent());
translationService.update(translation);
}
}
private PackageStructure getEnglishPackageStructure(Package gtPackage) throws IOException, SAXException, ParserConfigurationException
{
PackageStructure englishPackageStructure = new PackageStructure();
englishPackageStructure.setId(UUID.randomUUID());
englishPackageStructure.setPackageId(gtPackage.getId());
englishPackageStructure.setXmlContent(getPackageDescriptorXml(languageService.selectByLanguageCode(new LanguageCode("en"))));
englishPackageStructure.setVersionNumber(1);
return englishPackageStructure;
}
private PackageStructure getTranslatedPackageStructure(Package gtPackage, Translation translation) throws IOException, SAXException, ParserConfigurationException
{
PackageStructure translatedPackageStructure = new PackageStructure();
translatedPackageStructure.setId(UUID.randomUUID());
translatedPackageStructure.setPackageId(gtPackage.getId());
translatedPackageStructure.setXmlContent(getPackageDescriptorXml(languageService.selectLanguageById(translation.getLanguageId())));
translatedPackageStructure.setVersionNumber(1);
return translatedPackageStructure;
}
/**
* Save a PageStructure for each page in each Translation of a GodTools Package.
*/
public void savePageStructures()
{
// load the package out
Package gtPackage = packageService.selectByCode(packageCode);
Map<UUID, Iterator<Page>> translationPageDirectoryIteratorMap = Maps.newHashMap();
// load the translations we know about
for(Translation translation : translationService.selectByPackageId(gtPackage.getId()))
{
Language languageRepresentedByTranslation = languageService.selectLanguageById(translation.getLanguageId());
// for each translation, load up all the pages from the filesystem and associate an iterator of those pages to the translationId
translationPageDirectoryIteratorMap.put(translation.getId(), new PageDirectory(packageCode, languageRepresentedByTranslation.getPath()).buildPages().iterator());
}
// hold a reference to the base English page directory
List<Page> baseEnglishPages = new PageDirectory(packageCode, "en").buildPages();
// loop through each translation ID
for(UUID translationId : translationPageDirectoryIteratorMap.keySet())
{
// take the iterator for the pages on the translation and loop through the pages
Iterator<Page> i = translationPageDirectoryIteratorMap.get(translationId);
Iterator<Page> baseIterator = baseEnglishPages.iterator();
for( ; i.hasNext();)
{
Page translatedPage = i.next();
// each page gets its own PageStructure
PageStructure pageStructure = new PageStructure();
// initialize the fields we can with data we know
pageStructure.setId(UUID.randomUUID());
pageStructure.setXmlContent(translatedPage.getXmlContent());
pageStructure.setFilename(translatedPage.getFilename());
pageStructure.setTranslationId(translationId);
pageStructureService.insert(pageStructure);
TranslatableElements translatableElements = new TranslatableElements(baseIterator.next().getXmlContent(),
translatedPage.getXmlContent(),
translatedPage.getFilename(),
translationId,
pageStructure.getId());
translatableElements.save(translationElementService);
pageStructureService.update(pageStructure);
}
}
}
private File getDirectory() throws URISyntaxException
{
URL packageFolderUrl = this.getClass().getResource(DIRECTORY_BASE + packageCode);
return new File(packageFolderUrl.toURI());
}
private Document getPackageDescriptorXml(File packageDescriptor) throws ParserConfigurationException, IOException, SAXException
{
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
return builder.parse(packageDescriptor);
}
private String getPackageName(Document packageDescriptorXml)
{
NodeList nodes = packageDescriptorXml.getElementsByTagName("packagename");
for(int i = 0; i < nodes.getLength(); i++)
{
if(!Strings.isNullOrEmpty(nodes.item(i).getTextContent()))
{
return nodes.item(i).getTextContent();
}
}
return null;
}
}
|
package org.devdom.tracker.model.dto;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name = "dev_dom_user")
@XmlRootElement
public class FacebookMember implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "uid")
private String uid;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "pic")
private String pic;
public FacebookMember() {
}
/**
* Definir una nueva instancia desde el constructor
* @param uid
* @param firstName
* @param lastName
* @param pic
*/
public FacebookMember(String uid /*Id de Facebook*/, String firstName, String lastName, String pic){
this.uid = uid;
this.firstName = firstName;
this.lastName = lastName;
this.pic = pic;
}
/**
* @return Facebook Id
*/
public String getId() {
return getUid();
}
/**
* @param id
*/
public void setId(String id) {
this.setUid(id);
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the uid
*/
public String getUid() {
return uid;
}
/**
* @param uid the uid to set
*/
public void setUid(String uid) {
this.uid = uid;
}
/**
* @return the pic
*/
public String getPic() {
return pic;
}
/**
* @param pic the pic to set
*/
public void setPic(String pic) {
this.pic = pic;
}
}
|
package tk.ultimatedev.jailplusplus.task;
public class UnjailTask implements Runnable {
@Override
public void run() {
// TODO: Update this task
/*
List<Prisoner> prisoners = Prisoner.getAllPrisoners();
for (Prisoner prisoner : prisoners) {
if (Bukkit.getPlayer(prisoner.getPlayer()) != null) {
if (prisoner.getExpiryTime().getTime() < System.currentTimeMillis()) {
Prisoner.removePrisoner(prisoner.getId());
if (prisoner.getX() == -1 && prisoner.getY() == -1 && prisoner.getZ() == -1) {
Bukkit.getPlayer(prisoner.getPlayer()).teleport(Cell.getCell(prisoner.getCell()).getJail().getCuboid().getWorld().getSpawnLocation());
} else {
Bukkit.getPlayer(prisoner.getPlayer()).teleport(new Location(Bukkit.getWorld(prisoner.getWorld()), (double) prisoner.getX(), (double) prisoner.getY(), (double) prisoner.getZ()));
}
Messenger.sendMessage(Bukkit.getPlayer(prisoner.getPlayer()), "You have served your sentence, and you are now unjailed!");
}
}
}
*/
}
}
|
package com.vimeo.networking;
@SuppressWarnings("unused")
public final class Vimeo {
public static final String VIMEO_BASE_URL_STRING = "https://api.vimeo.com/";
public static final String API_VERSION = "3.4.1";
// Global Constants
public static final int NOT_FOUND = -1;
// Grant Types
public static final String CODE_GRANT_PATH = "/oauth/authorize";
public static final String CODE_GRANT_RESPONSE_TYPE = "code";
public static final String CODE_GRANT_STATE = "state";
public static final String CODE_GRANT_TYPE = "authorization_code";
public static final String DEVICE_GRANT_TYPE = "device_grant";
public static final String FACEBOOK_GRANT_TYPE = "facebook";
public static final String GOOGLE_GRANT_TYPE = "google";
public static final String PASSWORD_GRANT_TYPE = "password";
public static final String CLIENT_CREDENTIALS_GRANT_TYPE = "client_credentials";
public static final String OAUTH_ONE_GRANT_TYPE = "vimeo_oauth1";
// Endpoints
public static final String ENDPOINT_ME = "me";
public static final String ENDPOINT_RECOMMENDATIONS = "/recommendations";
public static final String ENDPOINT_TERMS_OF_SERVICE = "documents/termsofservice";
public static final String ENDPOINT_PRIVACY_POLICY = "documents/privacy";
public static final String ENDPOINT_PAYMENT_ADDENDUM = "documents/paymentaddendum";
// Parameters
public static final String PARAMETER_REDIRECT_URI = "redirect_uri";
public static final String PARAMETER_RESPONSE_TYPE = "response_type";
public static final String PARAMETER_STATE = "state";
public static final String PARAMETER_SCOPE = "scope";
public static final String PARAMETER_TOKEN = "token";
public static final String PARAMETER_ID_TOKEN = "id_token";
public static final String PARAMETER_CLIENT_ID = "client_id";
public static final String PARAMETER_USERS_NAME = "name";
public static final String PARAMETER_EMAIL = "email";
public static final String PARAMETER_PASSWORD = "password";
public static final String PARAMETER_USERS_LOCATION = "location";
public static final String PARAMETER_USERS_BIO = "bio";
public static final String PARAMETER_MARKETING_OPT_IN = "marketing_opt_in";
public static final String PARAMETER_VIDEO_VIEW = "view";
public static final String PARAMETER_VIDEO_COMMENTS = "comments";
public static final String PARAMETER_VIDEO_EMBED = "embed";
public static final String PARAMETER_VIDEO_DOWNLOAD = "download";
public static final String PARAMETER_VIDEO_ADD = "add";
public static final String PARAMETER_VIDEO_NAME = "name";
public static final String PARAMETER_VIDEO_DESCRIPTION = "description";
public static final String PARAMETER_VIDEO_PRIVACY = "privacy";
public static final String PARAMETER_VIDEO_PASSWORD = "password";
public static final String PARAMETER_COMMENT_TEXT_BODY = "text";
public static final String PARAMETER_ACTIVE = "active";
// Header Parameters
public static final String HEADER_CACHE_CONTROL = "Cache-Control";
public static final String HEADER_USER_AGENT = "User-Agent";
public static final String HEADER_ACCEPT = "Accept";
public static final String HEADER_ACCEPT_LANGUAGE = "Accept-Language";
// Header Values
public static final String HEADER_CACHE_PUBLIC = "public";
// Video Analytics Parameters
public static final String PARAMETER_SESSION_ID = "session_id";
public static final String PARAMETER_SESSION_TIME = "session_time";
public static final String PARAMETER_VUID = "vuid";
public static final String PARAMETER_LOCALE = "locale";
public static final String PARAMETER_EXIT_WATCHED_TIME = "exit_watched_time_code";
public static final String PARAMETER_FURTHEST_WATCHED_TIME = "furthest_watched_time_code";
public static final String PARAMETER_PROGRESS = "progress";
public static final String PARAMETER_EVENTS = "events";
public static final String PARAMETER_EVENT_TYPE = "type";
public static final String PARAMETER_EVENT_TYPE_WATER_LATER = "watchlater";
public static final String PARAMETER_EVENT_TYPE_LIKE = "like";
public static final String PARAMETER_EVENT_ACTION = "action";
public static final String PARAMETER_EVENT_ACTION_ADDED = "added";
public static final String PARAMETER_EVENT_ACTION_REMOVED = "removed";
// GET and Sorting Parameters
public static final String PARAMETER_GET_PAGE_SIZE = "per_page";
public static final String PARAMETER_GET_QUERY = "query";
public static final String PARAMETER_GET_SORT = "sort";
public static final String PARAMETER_GET_DIRECTION = "direction";
public static final String PARAMETER_GET_FIELD_FILTER = "fields";
public static final String PARAMETER_GET_CONTAINER_FIELD_FILTER = "container_fields";
public static final String PARAMETER_GET_LENGTH_MIN_DURATION = "min_duration";
public static final String PARAMETER_GET_LENGTH_MAX_DURATION = "max_duration";
public static final String PARAMETER_GET_FILTER = "filter";
public static final String PARAMETER_GET_UPLOAD_DATE_FILTER = "filter_upload_date";
public static final String PARAMETER_GET_NOTIFICATION_TYPES_FILTER = "filter_notification_types";
public static final String PARAMETER_PATCH_LATEST_NOTIFICATION_URI = "latest_notification_uri";
// Sorting (sort) Values
public static final String SORT_DEFAULT = "default";
public static final String SORT_RELEVANCE = "relevant";
public static final String SORT_POPULAR = "popularity";
public static final String SORT_DATE = "date";
public static final String SORT_PURCHASE_TIME = "purchase_time";
public static final String SORT_FOLLOWERS = "followers";
public static final String SORT_ALPHABETICAL = "alphabetical";
public static final String SORT_MANUAL = "manual";
public static final String SORT_DURATION = "duration";
public static final String SORT_LAST_USER_ACTION_EVENT_DATE = "last_user_action_event_date";
public static final String SORT_PLAYS = "plays";
public static final String SORT_LIKES = "likes";
public static final String SORT_MODIFIED_TIME = "modified_time";
public static final String SORT_COMMENTS = "comments";
// Sort Direction Values
public static final String SORT_DIRECTION_ASCENDING = "asc";
public static final String SORT_DIRECTION_DESCENDING = "desc";
// Filter (filter) Values
public static final String FILTER_RELATED = "related";
public static final String FILTER_UPLOAD = "upload_date";
public static final String FILTER_VIEWABLE = "viewable";
public static final String FILTER_PLAYABLE = "playable";
public static final String FILTER_TRENDING = "trending";
public static final String FILTER_TVOD_RENTALS = "rented";
public static final String FILTER_TVOD_SUBSCRIPTIONS = "subscription";
public static final String FILTER_TVOD_PURCHASES = "purchased";
public static final String FILTER_NOTIFICATION_TYPES = "notification_types";
// Filter Upload Date Values
public static final String FILTER_UPLOAD_DATE_TODAY = "day";
public static final String FILTER_UPLOAD_DATE_WEEK = "week";
public static final String FILTER_UPLOAD_DATE_MONTH = "month";
public static final String FILTER_UPLOAD_DATE_YEAR = "year";
public static final String PAGE_SIZE_MAX = "100";
public static final String OPTIONS_POST = "POST";
// Fields (for invalid params)
public static final String FIELD_NAME = "name";
public static final String FIELD_EMAIL = "email";
public static final String FIELD_PASSWORD = "password";
public static final String FIELD_TOKEN = "token";
public static final String FIELD_USERNAME = "username";
public enum RefineLength {
ANY,
UNDER_FIVE_MINUTES,
OVER_FIVE_MINUTES
}
public enum RefineSort {
DEFAULT(SORT_DEFAULT),
RELEVANCE(SORT_RELEVANCE),
POPULARITY(SORT_POPULAR),
RECENT(SORT_DATE),
// Channels
FOLLOWERS(SORT_FOLLOWERS),
// Users
AZ(SORT_DIRECTION_ASCENDING),
ZA(SORT_DIRECTION_DESCENDING);
private String mText;
RefineSort(String text) {
this.mText = text;
}
public String getText() {
return this.mText;
}
public static RefineSort fromString(String text) {
if (text != null) {
for (RefineSort b : RefineSort.values()) {
if (text.equalsIgnoreCase(b.mText)) {
return b;
}
}
}
throw new IllegalArgumentException("No constant with mText " + text + " found");
}
}
public enum RefineUploadDate {
ANYTIME(""),
TODAY(FILTER_UPLOAD_DATE_TODAY),
THIS_WEEK(FILTER_UPLOAD_DATE_WEEK),
THIS_MONTH(FILTER_UPLOAD_DATE_MONTH),
THIS_YEAR(FILTER_UPLOAD_DATE_YEAR);
private String mText;
RefineUploadDate(String text) {
this.mText = text;
}
public String getText() {
return this.mText;
}
public static RefineUploadDate fromString(String text) {
if (text != null) {
for (RefineUploadDate b : RefineUploadDate.values()) {
if (text.equalsIgnoreCase(b.mText)) {
return b;
}
}
}
throw new IllegalArgumentException("No constant with mText " + text + " found");
}
}
public enum LogLevel {
// 0 1 2 3
VERBOSE, DEBUG, ERROR, NONE
}
private Vimeo() {
}
}
|
package com.wonderpush.sdk;
import org.json.JSONException;
import org.json.JSONObject;
class JSONSync {
interface ResponseHandler {
void onSuccess();
void onFailure();
}
interface Callbacks {
void save(JSONObject state);
void schedulePatchCall();
void serverPatchInstallation(JSONObject diff, ResponseHandler handler);
}
private static final String SAVED_STATE_FIELD__SYNC_STATE_VERSION = "_syncStateVersion";
private static final int SAVED_STATE_STATE_VERSION_1 = 1;
private static final String SAVED_STATE_FIELD_SDK_STATE = "sdkState";
private static final String SAVED_STATE_FIELD_SERVER_STATE = "serverState";
private static final String SAVED_STATE_FIELD_PUT_ACCUMULATOR = "putAccumulator";
private static final String SAVED_STATE_FIELD_INFLIGHT_DIFF = "inflightDiff";
private static final String SAVED_STATE_FIELD_INFLIGHT_PUT_ACCUMULATOR = "inflightPutAccumulator";
private static final String SAVED_STATE_FIELD_SCHEDULED_PATCH_CALL = "scheduledPatchCall";
private static final String SAVED_STATE_FIELD_INFLIGHT_PATCH_CALL = "inflightPatchCall";
private Callbacks callbacks;
private JSONObject sdkState;
private JSONObject serverState;
private JSONObject putAccumulator;
private JSONObject inflightDiff;
private JSONObject inflightPutAccumulator;
private boolean scheduledPatchCall;
private boolean inflightPatchCall;
JSONSync(Callbacks callbacks) {
this(callbacks, null, null, null, null, null, false, false);
}
private static JSONObject _initDiffServerAndSdkState(JSONObject serverState, JSONObject sdkState) {
if (serverState == null) serverState = new JSONObject();
if (sdkState == null) sdkState = new JSONObject();
JSONObject diff;
try {
diff = JSONUtil.diff(serverState, sdkState);
} catch (JSONException ex) {
WonderPush.logError("Error while diffing serverState " + serverState + " with sdkState " + sdkState + ". Falling back to full sdkState", ex);
try {
diff = JSONUtil.deepCopy(sdkState);
} catch (JSONException ex2) {
WonderPush.logError("Error while cloning sdkState " + sdkState + ". Falling back to empty diff", ex2);
diff = new JSONObject();
}
}
return diff;
}
static JSONSync fromSdkStateAndServerState(Callbacks callbacks, JSONObject sdkState, JSONObject serverState) {
return new JSONSync(callbacks, sdkState, serverState, _initDiffServerAndSdkState(serverState, sdkState), null, null, true /*schedule a patch call*/, false);
}
static JSONSync fromSavedState(Callbacks callbacks, JSONObject savedState) throws JSONException {
if (savedState == null) savedState = new JSONObject();
int version = savedState.has(SAVED_STATE_FIELD_SDK_STATE) ? savedState.getInt(SAVED_STATE_FIELD__SYNC_STATE_VERSION) : SAVED_STATE_STATE_VERSION_1;
return new JSONSync(
callbacks,
savedState.has(SAVED_STATE_FIELD_SDK_STATE) ? savedState.getJSONObject(SAVED_STATE_FIELD_SDK_STATE) : null,
savedState.has(SAVED_STATE_FIELD_SERVER_STATE) ? savedState.getJSONObject(SAVED_STATE_FIELD_SERVER_STATE) : null,
savedState.has(SAVED_STATE_FIELD_PUT_ACCUMULATOR) ? savedState.getJSONObject(SAVED_STATE_FIELD_PUT_ACCUMULATOR) : null,
savedState.has(SAVED_STATE_FIELD_INFLIGHT_DIFF) ? savedState.getJSONObject(SAVED_STATE_FIELD_INFLIGHT_DIFF) : null,
savedState.has(SAVED_STATE_FIELD_INFLIGHT_PUT_ACCUMULATOR) ? savedState.getJSONObject(SAVED_STATE_FIELD_INFLIGHT_PUT_ACCUMULATOR) : null,
savedState.has(SAVED_STATE_FIELD_SCHEDULED_PATCH_CALL) ? savedState.getBoolean(SAVED_STATE_FIELD_SCHEDULED_PATCH_CALL) : true,
savedState.has(SAVED_STATE_FIELD_INFLIGHT_PATCH_CALL) ? savedState.getBoolean(SAVED_STATE_FIELD_INFLIGHT_PATCH_CALL) : false
);
}
JSONSync(Callbacks callbacks, JSONObject sdkState, JSONObject serverState, JSONObject putAccumulator, JSONObject inflightDiff, JSONObject inflightPutAccumulator, boolean scheduledPatchCall, boolean inflightPatchCall) {
if (callbacks == null) throw new NullPointerException("callbacks cannot be null");
if (sdkState == null) sdkState = new JSONObject();
if (serverState == null) serverState = new JSONObject();
if (putAccumulator == null) putAccumulator = new JSONObject();
if (inflightDiff == null) inflightDiff = new JSONObject();
if (inflightPutAccumulator == null) inflightPutAccumulator = new JSONObject();
try {
JSONUtil.stripNulls(sdkState);
} catch (JSONException ex) {
WonderPush.logError("Unexpected JSON error while removing null fields on sdkState", ex);
}
try {
JSONUtil.stripNulls(serverState);
} catch (JSONException ex) {
WonderPush.logError("Unexpected JSON error while removing null fields on serverState", ex);
}
this.callbacks = callbacks;
this.sdkState = sdkState;
this.serverState = serverState;
this.putAccumulator = putAccumulator;
this.inflightDiff = inflightDiff;
this.inflightPutAccumulator = inflightPutAccumulator;
this.scheduledPatchCall = scheduledPatchCall;
this.inflightPatchCall = inflightPatchCall;
if (this.inflightPatchCall) {
callPatch_onFailure();
}
}
public synchronized JSONObject getSdkState() throws JSONException {
return JSONUtil.deepCopy(sdkState);
}
private synchronized void save() {
try {
JSONObject state = new JSONObject();
state.put(SAVED_STATE_FIELD__SYNC_STATE_VERSION, SAVED_STATE_STATE_VERSION_1);
state.put(SAVED_STATE_FIELD_SDK_STATE, sdkState);
state.put(SAVED_STATE_FIELD_SERVER_STATE, serverState);
state.put(SAVED_STATE_FIELD_PUT_ACCUMULATOR, putAccumulator);
state.put(SAVED_STATE_FIELD_INFLIGHT_DIFF, inflightDiff);
state.put(SAVED_STATE_FIELD_INFLIGHT_PUT_ACCUMULATOR, inflightPutAccumulator);
state.put(SAVED_STATE_FIELD_SCHEDULED_PATCH_CALL, scheduledPatchCall);
state.put(SAVED_STATE_FIELD_INFLIGHT_PATCH_CALL, inflightPatchCall);
callbacks.save(state);
} catch (JSONException ex) {
WonderPush.logError("Failed to build state object for saving installation custom for " + this, ex);
}
}
public synchronized void put(JSONObject diff) throws JSONException {
if (diff == null) diff = new JSONObject();
JSONUtil.merge(sdkState, diff);
JSONUtil.merge(putAccumulator, diff, false);
schedulePatchCallAndSave();
}
public synchronized void receiveServerState(JSONObject srvState) throws JSONException {
if (srvState == null) srvState = new JSONObject();
serverState = JSONUtil.deepCopy(srvState);
JSONUtil.stripNulls(serverState);
schedulePatchCallAndSave();
}
public synchronized void receiveState(JSONObject receivedState, boolean resetSdkState) throws JSONException {
if (receivedState == null) receivedState = new JSONObject();
serverState = JSONUtil.deepCopy(receivedState);
JSONUtil.stripNulls(serverState);
sdkState = JSONUtil.deepCopy(serverState);
if (resetSdkState) {
putAccumulator = new JSONObject();
} else {
JSONUtil.merge(sdkState, putAccumulator);
JSONUtil.merge(sdkState, inflightDiff);
}
schedulePatchCallAndSave();
}
public synchronized void receiveDiff(JSONObject diff) throws JSONException {
if (diff == null) diff = new JSONObject();
// The diff is already server-side, by contract
JSONUtil.merge(serverState, diff);
put(diff);
}
private synchronized void schedulePatchCallAndSave() {
scheduledPatchCall = true;
save();
callbacks.schedulePatchCall();
}
synchronized boolean hasScheduledPatchCall() {
return scheduledPatchCall;
}
synchronized boolean hasInflightPatchCall() {
return inflightPatchCall;
}
synchronized boolean performScheduledPatchCall() {
if (scheduledPatchCall) {
callPatch();
return true;
}
return false;
}
private synchronized void callPatch() {
if (inflightPatchCall) {
if (!scheduledPatchCall) {
WonderPush.logDebug("Server PATCH call already inflight, scheduling a new one");
schedulePatchCallAndSave();
} else {
WonderPush.logDebug("Server PATCH call already inflight, and already scheduled");
}
save();
return;
}
scheduledPatchCall = false;
try {
inflightDiff = JSONUtil.diff(serverState, sdkState);
} catch (JSONException ex) {
WonderPush.logError("Failed to diff server state and sdk state to send installation custom diff", ex);
inflightDiff = new JSONObject();
}
if (inflightDiff.length() == 0) {
WonderPush.logDebug("No diff to send to server");
save();
return;
}
inflightPatchCall = true;
try {
inflightPutAccumulator = JSONUtil.deepCopy(putAccumulator);
} catch (JSONException e) {
inflightPutAccumulator = putAccumulator;
}
putAccumulator = new JSONObject();
save();
callbacks.serverPatchInstallation(inflightDiff, new ResponseHandler() {
@Override
public void onSuccess() {
callPatch_onSuccess();
}
@Override
public void onFailure() {
callPatch_onFailure();
}
});
}
private synchronized void callPatch_onSuccess() {
inflightPatchCall = false;
inflightPutAccumulator = new JSONObject();
try {
JSONUtil.merge(serverState, inflightDiff);
inflightDiff = new JSONObject();
} catch (JSONException ex) {
WonderPush.logError("Failed to copy putAccumulator", ex);
}
save();
}
private synchronized void callPatch_onFailure() {
inflightPatchCall = false;
try {
JSONUtil.merge(inflightPutAccumulator, putAccumulator, false);
} catch (JSONException ex) {
WonderPush.logError("Failed to merge putAccumulator into oldPutAccumulator", ex);
}
putAccumulator = inflightPutAccumulator;
inflightPutAccumulator = new JSONObject();
schedulePatchCallAndSave();
}
@Override
public synchronized String toString() {
return "JSONSync"
+ "{sdkState:" + sdkState
+ ",serverState:" + serverState
+ ",putAccumulator:" + putAccumulator
+ ",inflightDiff:" + inflightDiff
+ ",inflightPutAccumulator:" + inflightPutAccumulator
+ ",scheduledPatchCall:" + scheduledPatchCall
+ ",inflightPatchCall:" + inflightPatchCall
+ "}";
}
}
|
package org.objectweb.proactive.core.util.log;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.objectweb.proactive.core.Constants;
import org.objectweb.proactive.core.config.PAProperties;
import org.objectweb.proactive.core.config.ProActiveConfiguration;
/**
* @author Arnaud Contes
*
* This class stores all logger used in ProActive. It provides an easy way
* to create and to retrieve a logger.
*/
public class ProActiveLogger extends Logger {
static {
if (System.getProperty("log4j.configuration") == null) {
// if logger is not defined create default logger with level info that logs
// on the console
File f = new File(System.getProperty("user.home") + File.separator + Constants.USER_CONFIG_DIR +
File.separator + ProActiveConfiguration.PROACTIVE_LOG_PROPERTIES_FILE);
if (f.exists()) {
try {
InputStream in = new FileInputStream(f);
// testing the availability of the file
Properties p = new Properties();
p.load(in);
PropertyConfigurator.configure(p);
System.setProperty("log4j.configuration", f.toURI().toString());
} catch (Exception e) {
System.err.println("the user's log4j configuration file (" + f.getAbsolutePath() +
") exits but is not accessible, fallbacking on the default configuration");
InputStream in = PAProperties.class.getResourceAsStream("proactive-log4j");
// testing the availability of the file
Properties p = new Properties();
try {
p.load(in);
PropertyConfigurator.configure(p);
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else {
InputStream in = PAProperties.class.getResourceAsStream("proactive-log4j");
// testing the availability of the file
Properties p = new Properties();
try {
p.load(in);
PropertyConfigurator.configure(p);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
private static ProActiveLoggerFactory myFactory = new ProActiveLoggerFactory();
/**
Just calls the parent constructor.
*/
protected ProActiveLogger(String name) {
super(name);
}
/**
This method overrides {@link Logger#getLogger} by supplying
its own factory type as a parameter.
*/
public static Logger getLogger(String name) {
return Logger.getLogger(name, myFactory);
}
/**
* Get corresponding stack trace as string
* @param e A Throwable
* @return The output of printStackTrace is returned as a String
*/
public static String getStackTraceAsString(Throwable e) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
return stringWriter.toString();
}
}
|
package org.voovan.tools.serialize;
import org.voovan.tools.TProperties;
import org.voovan.tools.exception.SerializeException;
import org.voovan.tools.log.Logger;
import org.voovan.tools.reflect.TReflect;
import org.voovan.tools.security.THash;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class TSerialize {
public static Serialize SERIALIZE;
static {
String serializeType = TProperties.getString("framework", "SerializeType").trim();
if("JSON".equalsIgnoreCase(serializeType.trim())){
serializeType = "org.voovan.tools.serialize.DefaultJSONSerialize";
} else if("JDK".equalsIgnoreCase(serializeType.trim())){
serializeType = "org.voovan.tools.serialize.DefaultJDKSerialize";
} else if("ProtoStuff".equalsIgnoreCase(serializeType.trim())){
serializeType = "org.voovan.tools.serialize.ProtoStuffSerialize";
} else if(serializeType == null){
serializeType = "org.voovan.tools.serialize.DefaultJDKSerialize";
}
try {
Class serializeClazz = Class.forName(serializeType);
TReflect.isImpByInterface(serializeClazz, Serialize.class);
SERIALIZE = (Serialize) TReflect.newInstance(serializeClazz);
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
Logger.simple("[SYSTEM] serialize type: " + serializeType);
}
/**
*
* @param object
* @return
*/
public static byte[] serialize(Object object) {
return object == null ? null : SERIALIZE.serialize(object);
}
/**
*
* @param bytes
* @return
*/
public static Object unserialize(byte[] bytes){
return bytes == null ? null : SERIALIZE.unserialize(bytes);
}
static ConcurrentHashMap<Class, Integer> CLASS_AND_HASH = new ConcurrentHashMap<Class, Integer>();
static ConcurrentHashMap<Integer, Class> HASH_AND_CLASS = new ConcurrentHashMap<Integer, Class>();
/**
* Class
* @param clazz
*/
public static void register(Class clazz){
int hashcode = THash.HashFNV1(clazz.getName());
register(hashcode, clazz);
}
/**
* Class
* @param code
* @param clazz
*/
public static void register(Integer code, Class clazz){
if(HASH_AND_CLASS.contains(code)) {
throw new RuntimeException("simple name is exists");
}
if(CLASS_AND_HASH.containsKey(clazz) || HASH_AND_CLASS.containsKey(code)) {
throw new SerializeException("TSerialize.registerClassWithSimpleName failed, because class or simplename is registerd");
} else {
CLASS_AND_HASH.put(clazz, code);
HASH_AND_CLASS.put(code, clazz);
}
}
static {
CLASS_AND_HASH.put(int.class, THash.HashFNV1(Integer.class.getName()));
CLASS_AND_HASH.put(Integer.class, THash.HashFNV1(Integer.class.getName()));
CLASS_AND_HASH.put(byte.class, THash.HashFNV1(Byte.class.getName()));
CLASS_AND_HASH.put(Byte.class, THash.HashFNV1(Byte.class.getName()));
CLASS_AND_HASH.put(short.class, THash.HashFNV1(Short.class.getName()));
CLASS_AND_HASH.put(Short.class, THash.HashFNV1(Short.class.getName()));
CLASS_AND_HASH.put(long.class, THash.HashFNV1(Long.class.getName()));
CLASS_AND_HASH.put(Long.class, THash.HashFNV1(Long.class.getName()));
CLASS_AND_HASH.put(float.class, THash.HashFNV1(Float.class.getName()));
CLASS_AND_HASH.put(Float.class, THash.HashFNV1(Float.class.getName()));
CLASS_AND_HASH.put(double.class, THash.HashFNV1(Double.class.getName()));
CLASS_AND_HASH.put(Double.class, THash.HashFNV1(Double.class.getName()));
CLASS_AND_HASH.put(char.class, THash.HashFNV1(Character.class.getName()));
CLASS_AND_HASH.put(Character.class, THash.HashFNV1(Character.class.getName()));
CLASS_AND_HASH.put(boolean.class, THash.HashFNV1(Boolean.class.getName()));
CLASS_AND_HASH.put(Boolean.class, THash.HashFNV1(Boolean.class.getName()));
CLASS_AND_HASH.put(String.class, THash.HashFNV1(String.class.getName()));
CLASS_AND_HASH.put(byte[].class, THash.HashFNV1(byte[].class.getName()));
for(Map.Entry<Class, Integer> entry : CLASS_AND_HASH.entrySet()) {
if(!entry.getKey().isPrimitive()) {
HASH_AND_CLASS.put(entry.getValue(), entry.getKey());
}
}
}
protected static Integer getHashByClass(Class clazz){
Integer hashcode = CLASS_AND_HASH.get(clazz);
if(hashcode == null) {
register(clazz);
}
return hashcode;
}
protected static Class getClassByHash(Integer hashcode) throws ClassNotFoundException {
Class clazz = HASH_AND_CLASS.get(hashcode);
if(clazz == null) {
return null;
}
return clazz;
}
}
|
package org.mskcc.cbio.cgds.util;
import org.mskcc.cbio.cgds.dao.DaoCancerStudy;
import org.mskcc.cbio.cgds.dao.DaoException;
import org.mskcc.cbio.cgds.dao.DaoGeneOptimized;
import org.mskcc.cbio.cgds.dao.MySQLbulkLoader;
import org.mskcc.cbio.cgds.model.CancerStudy;
import org.mskcc.cbio.cgds.model.CanonicalGene;
import org.mskcc.cbio.cgds.model.MutSig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.*;
import java.util.List;
import java.util.Properties;
import static org.mskcc.cbio.cgds.dao.DaoMutSig.addMutSig;
/*
* Reads and loads a MutSig file.
* Requires a "properties" file for the Cancer Study associated with the MutSig file.
* @author Lennart Bastian
* @author Gideon Dresdner
*
*/
public class MutSigReader {
public static final int HIGH_Q_VALUE = -1;
private static Log log = LogFactory.getLog(MutSigReader.class);
// look up the internalId for a cancer_study_identifier from a properties file
/**
* Look up CancerStudy Id, internal databse record
* @param props Properties file
* @return CancerStudyId
* @throws IOException
* @throws DaoException
*/
public static int getInternalId(File props) throws IOException, DaoException
{
Properties properties = new Properties();
properties.load(new FileInputStream(props));
String cancerStudyIdentifier = properties.getProperty("cancer_study_identifier");
if (cancerStudyIdentifier == null) {
throw new IllegalArgumentException("cancer_study_identifier is not specified.");
}
CancerStudy cancerStudy = DaoCancerStudy.getCancerStudyByStableId(cancerStudyIdentifier);
if (cancerStudy == null) {
throw new DaoException("no CancerStudy associated with \""
+ cancerStudyIdentifier + "\" cancer_study_identifier");
}
return cancerStudy.getInternalId();
}
/**
* Adds MutSigs to CDGS database.
* @param internalId CancerStudy database record
* @param mutSigFile MutSigFile
* @param pMonitor pMonitor
* @return number of MutSig records loaded
* @throws IOException
* @throws DaoException
*/
public static int loadMutSig(int internalId, File mutSigFile, ProgressMonitor pMonitor) throws IOException, DaoException {
int loadedMutSigs = 0;
MySQLbulkLoader.bulkLoadOff();
FileReader reader = new FileReader(mutSigFile);
BufferedReader buf = new BufferedReader(reader);
// parse field names of a mutsig data file
int rankField = -1;
int hugoField = -1;
int BasesCoveredField = -1;
int numMutationsField = -1;
int PvalField = -1;
int QvalField = -1;
String head = buf.readLine();
String[] names = head.split("\t");
int len = names.length;
for (int i = 0; i < len ; i++)
{
if (names[i].equals("rank")) {
rankField = i;
}
if (names[i].equalsIgnoreCase("gene")) {
hugoField = i;
}
if (names[i].equals("N")) {
BasesCoveredField = i;
}
if (names[i].equals("n")) {
numMutationsField = i;
}
if (names[i].equalsIgnoreCase("p")) {
PvalField = i;
}
if (names[i].equalsIgnoreCase("q") || names[i].equalsIgnoreCase("q\n")) {
QvalField = i;
}
}
// end parse Column names
// check to see if all fields are filled
if (rankField == -1
|| hugoField == -1
|| BasesCoveredField == -1
|| numMutationsField == -1
|| PvalField == -1
|| QvalField == -1) {
throw new IOException("one or more of the fields [rank, hugoGeneSymbol, number of bases covered (N), " +
"number of mutations (n), p-value, q-value] are undefined");
}
// parse data
String line = buf.readLine();
while (line != null) {
if (pMonitor != null) {
pMonitor.incrementCurValue();
ConsoleUtil.showProgress(pMonitor);
}
DaoGeneOptimized daoGene = DaoGeneOptimized.getInstance();
String[] parts = line.split("\t");
// -- load parameters for new MutSig object --
int rank = Integer.parseInt(parts[rankField]);
String hugoGeneSymbol = parts[hugoField];
int numBasesCovered = Integer.parseInt(parts[BasesCoveredField]);
int numMutations = Integer.parseInt(parts[numMutationsField]);
// ignoring '<' sign
float pValue = Float.valueOf(parts[PvalField].replace("<", ""));
float qValue = Float.valueOf(parts[QvalField].replace("<", ""));
// Ignore everything with high q-value,
// specified by Ethan
if (qValue >= 0.1) {
line = buf.readLine();
continue;
}
List<CanonicalGene> genes;
genes = daoGene.guessGene(hugoGeneSymbol);
// there should only be one EntrezId for any given HugoGeneSymbol
CanonicalGene gene;
if (genes.size() == 0) {
if (log.isWarnEnabled()) {
log.warn("Cannot find CanonicalGene for HugoGeneSymbol: " + hugoGeneSymbol
+ ". Set EntrezId = 0");
}
gene = new CanonicalGene(0, hugoGeneSymbol);
}
else if (genes.size() > 1 && log.isWarnEnabled()) {
log.warn("Found more than one CanonicalGenes for HugoGeneSymbol: " + hugoGeneSymbol
+ ". Chose the first one by default");
gene = genes.get(0);
}
else { // there is one and only one EntrezId for a given HUGO symbol
gene = genes.get(0);
}
// -- end load parameters for new MutSig object --
MutSig mutSig = new MutSig(internalId, gene, rank, numBasesCovered, numMutations, pValue, qValue);
loadedMutSigs += addMutSig(mutSig);
line = buf.readLine();
}
return loadedMutSigs;
}
}
|
package arez.processor;
import com.squareup.javapoet.AnnotationSpec;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.CodeBlock;
import com.squareup.javapoet.FieldSpec;
import com.squareup.javapoet.MethodSpec;
import com.squareup.javapoet.ParameterSpec;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import com.squareup.javapoet.TypeSpec;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.NestingKind;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.ExecutableType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
import static arez.processor.ProcessorUtil.*;
/**
* The class that represents the parsed state of ArezComponent annotated class.
*/
@SuppressWarnings( "Duplicates" )
final class ComponentDescriptor
{
enum InjectMode
{
NONE,
CONSUME,
PROVIDE
}
private static final Pattern OBSERVABLE_REF_PATTERN = Pattern.compile( "^get([A-Z].*)ObservableValue$" );
private static final Pattern COMPUTABLE_VALUE_REF_PATTERN = Pattern.compile( "^get([A-Z].*)ComputableValue$" );
private static final Pattern OBSERVER_REF_PATTERN = Pattern.compile( "^get([A-Z].*)Observer$" );
private static final Pattern SETTER_PATTERN = Pattern.compile( "^set([A-Z].*)$" );
private static final Pattern GETTER_PATTERN = Pattern.compile( "^get([A-Z].*)$" );
private static final Pattern ID_GETTER_PATTERN = Pattern.compile( "^get([A-Z].*)Id$" );
private static final Pattern RAW_ID_GETTER_PATTERN = Pattern.compile( "^(.*)Id$" );
private static final Pattern ISSER_PATTERN = Pattern.compile( "^is([A-Z].*)$" );
private static final List<String> OBJECT_METHODS =
Arrays.asList( "hashCode", "equals", "clone", "toString", "finalize", "getClass", "wait", "notifyAll", "notify" );
private static final List<String> AREZ_SPECIAL_METHODS =
Arrays.asList( "observe", "dispose", "isDisposed", "getArezId" );
@Nullable
private List<TypeElement> _repositoryExtensions;
/**
* Flag controlling whether dagger module is created for repository.
*/
private String _repositoryDaggerConfig = "AUTODETECT";
/**
* Flag controlling whether Inject annotation is added to repository constructor.
*/
private String _repositoryInjectMode = "AUTODETECT";
@Nonnull
private final SourceVersion _sourceVersion;
@Nonnull
private final Elements _elements;
@Nonnull
private final Types _typeUtils;
@Nonnull
private final String _type;
private final boolean _nameIncludesId;
private final boolean _allowEmpty;
/**
* Flag indicating that there is a @Generated annotation on arez.
* In this scenario we are a little more forgiving with our errors as otherwise the generating tool would need to
* have a deep understanding of the component model to generate the code which may be too demanding for downstream
* generators.
*/
private final boolean _generated;
private final boolean _observable;
private final boolean _disposeTrackable;
private final boolean _disposeOnDeactivate;
@Nonnull
private final InjectMode _injectMode;
private final boolean _dagger;
private final boolean _generatesFactoryToInject;
/**
* Is there any @Inject annotated fields or methods? If so we need to do a dance when generating Dagger support.
*/
private final boolean _nonConstructorInjections;
/**
* Annotation that indicates whether equals/hashCode should be implemented. See arez.annotations.ArezComponent.requireEquals()
*/
private final boolean _requireEquals;
/**
* Flag indicating whether generated component should implement arez.component.Verifiable.
*/
private final boolean _verify;
/**
* Scope annotation that is declared on component and should be transferred to injection providers.
*/
private final AnnotationMirror _scopeAnnotation;
private final boolean _deferSchedule;
private final boolean _generateToString;
private boolean _idRequired;
@Nonnull
private final PackageElement _packageElement;
@Nonnull
private final TypeElement _element;
@Nullable
private ExecutableElement _postConstruct;
@Nullable
private ExecutableElement _componentId;
@Nullable
private ExecutableElement _componentIdRef;
@Nullable
private ExecutableType _componentIdMethodType;
@Nullable
private ExecutableElement _componentRef;
@Nullable
private ExecutableElement _contextRef;
@Nullable
private ExecutableElement _componentTypeNameRef;
@Nullable
private ExecutableElement _componentNameRef;
@Nullable
private ExecutableElement _preDispose;
@Nullable
private ExecutableElement _postDispose;
private final Map<String, CandidateMethod> _observerRefs = new LinkedHashMap<>();
private final Map<String, ObservableDescriptor> _observables = new LinkedHashMap<>();
private final Collection<ObservableDescriptor> _roObservables =
Collections.unmodifiableCollection( _observables.values() );
private final Map<String, ActionDescriptor> _actions = new LinkedHashMap<>();
private final Collection<ActionDescriptor> _roActions =
Collections.unmodifiableCollection( _actions.values() );
private final Map<String, MemoizeDescriptor> _memoizes = new LinkedHashMap<>();
private final Collection<MemoizeDescriptor> _roMemoizes =
Collections.unmodifiableCollection( _memoizes.values() );
private final Map<String, ObserveDescriptor> _observes = new LinkedHashMap<>();
private final Collection<ObserveDescriptor> _roObserves =
Collections.unmodifiableCollection( _observes.values() );
private final Map<Element, DependencyDescriptor> _dependencies = new LinkedHashMap<>();
private final Collection<DependencyDescriptor> _roDependencies =
Collections.unmodifiableCollection( _dependencies.values() );
private final Map<Element, CascadeDisposableDescriptor> _cascadeDisposes = new LinkedHashMap<>();
private final Collection<CascadeDisposableDescriptor> _roCascadeDisposes =
Collections.unmodifiableCollection( _cascadeDisposes.values() );
private final Map<String, ReferenceDescriptor> _references = new LinkedHashMap<>();
private final Collection<ReferenceDescriptor> _roReferences =
Collections.unmodifiableCollection( _references.values() );
private final Map<String, InverseDescriptor> _inverses = new LinkedHashMap<>();
private final Collection<InverseDescriptor> _roInverses =
Collections.unmodifiableCollection( _inverses.values() );
ComponentDescriptor( @Nonnull final SourceVersion sourceVersion,
@Nonnull final Elements elements,
@Nonnull final Types typeUtils,
@Nonnull final String type,
final boolean nameIncludesId,
final boolean allowEmpty,
final boolean generated,
final boolean observable,
final boolean disposeTrackable,
final boolean disposeOnDeactivate,
@Nonnull final String injectMode,
final boolean dagger,
final boolean generatesFactoryToInject,
final boolean nonConstructorInjections,
final boolean requireEquals,
final boolean verify,
@Nullable final AnnotationMirror scopeAnnotation,
final boolean deferSchedule,
final boolean generateToString,
@Nonnull final PackageElement packageElement,
@Nonnull final TypeElement element )
{
_sourceVersion = Objects.requireNonNull( sourceVersion );
_elements = Objects.requireNonNull( elements );
_typeUtils = Objects.requireNonNull( typeUtils );
_type = Objects.requireNonNull( type );
_nameIncludesId = nameIncludesId;
_allowEmpty = allowEmpty;
_generated = generated;
_observable = observable;
_disposeTrackable = disposeTrackable;
_disposeOnDeactivate = disposeOnDeactivate;
_injectMode = InjectMode.valueOf( injectMode );
_dagger = dagger;
_generatesFactoryToInject = generatesFactoryToInject;
_nonConstructorInjections = nonConstructorInjections;
_requireEquals = requireEquals;
_verify = verify;
_scopeAnnotation = scopeAnnotation;
_deferSchedule = deferSchedule;
_generateToString = generateToString;
_packageElement = Objects.requireNonNull( packageElement );
_element = Objects.requireNonNull( element );
}
@Nonnull
SourceVersion getSourceVersion()
{
return _sourceVersion;
}
@Nonnull
Elements getElements()
{
return _elements;
}
@Nonnull
ClassName getClassName()
{
return ClassName.get( getElement() );
}
@Nonnull
Types getTypeUtils()
{
return _typeUtils;
}
private boolean hasDeprecatedElements()
{
return isDeprecated( _postConstruct ) ||
isDeprecated( _componentId ) ||
isDeprecated( _componentRef ) ||
isDeprecated( _contextRef ) ||
isDeprecated( _componentTypeNameRef ) ||
isDeprecated( _componentNameRef ) ||
isDeprecated( _preDispose ) ||
isDeprecated( _postDispose ) ||
_roObservables.stream().anyMatch( e -> ( e.hasSetter() && isDeprecated( e.getSetter() ) ) ||
( e.hasGetter() && isDeprecated( e.getGetter() ) ) ) ||
_roMemoizes.stream().anyMatch( e -> ( e.hasMemoize() && isDeprecated( e.getMethod() ) ) ||
isDeprecated( e.getOnActivate() ) ||
isDeprecated( e.getOnDeactivate() ) ||
isDeprecated( e.getOnStale() ) ) ||
_observerRefs.values().stream().anyMatch( e -> isDeprecated( e.getMethod() ) ) ||
_roDependencies.stream().anyMatch( e -> ( e.isMethodDependency() && isDeprecated( e.getMethod() ) ) ||
( !e.isMethodDependency() && isDeprecated( e.getField() ) ) ) ||
_roActions.stream().anyMatch( e -> isDeprecated( e.getAction() ) ) ||
_roObserves.stream().anyMatch( e -> ( e.hasObserve() && isDeprecated( e.getObserve() ) ) ||
( e.hasOnDepsChange() && isDeprecated( e.getOnDepsChange() ) ) );
}
void setIdRequired( final boolean idRequired )
{
_idRequired = idRequired;
}
boolean shouldVerify()
{
return _verify;
}
boolean isDisposeTrackable()
{
return _disposeTrackable;
}
private boolean isDeprecated( @Nullable final Element element )
{
return null != element && null != element.getAnnotation( Deprecated.class );
}
@Nonnull
private DeclaredType asDeclaredType()
{
return (DeclaredType) _element.asType();
}
@Nonnull
TypeElement getElement()
{
return _element;
}
@Nonnull
String getType()
{
return _type;
}
@Nonnull
private ReferenceDescriptor findOrCreateReference( @Nonnull final String name )
{
return _references.computeIfAbsent( name, n -> new ReferenceDescriptor( this, name ) );
}
@Nonnull
private ObservableDescriptor findOrCreateObservable( @Nonnull final String name )
{
return _observables.computeIfAbsent( name, ObservableDescriptor::new );
}
@Nonnull
private ObserveDescriptor findOrCreateObserve( @Nonnull final String name )
{
return _observes.computeIfAbsent( name, n -> new ObserveDescriptor( this, n ) );
}
@Nonnull
private ObservableDescriptor addObservable( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVABLE_ANNOTATION_CLASSNAME, method );
final String declaredName = getAnnotationParameter( annotation, "name" );
final boolean expectSetter = getAnnotationParameter( annotation, "expectSetter" );
final boolean readOutsideTransaction = getAnnotationParameter( annotation, "readOutsideTransaction" );
final boolean writeOutsideTransaction = getAnnotationParameter( annotation, "writeOutsideTransaction" );
final boolean setterAlwaysMutates = getAnnotationParameter( annotation, "setterAlwaysMutates" );
final Boolean requireInitializer = isInitializerRequired( method );
final TypeMirror returnType = method.getReturnType();
final String methodName = method.getSimpleName().toString();
String name;
final boolean setter;
if ( TypeKind.VOID == returnType.getKind() )
{
setter = true;
//Should be a setter
if ( 1 != method.getParameters().size() )
{
throw new ArezProcessorException( "@Observable target should be a setter or getter", method );
}
name = ProcessorUtil.deriveName( method, SETTER_PATTERN, declaredName );
if ( null == name )
{
name = methodName;
}
}
else
{
setter = false;
//Must be a getter
if ( 0 != method.getParameters().size() )
{
throw new ArezProcessorException( "@Observable target should be a setter or getter", method );
}
name = getPropertyAccessorName( method, declaredName );
}
// Override name if supplied by user
if ( !ProcessorUtil.isSentinelName( declaredName ) )
{
name = declaredName;
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@Observable target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@Observable target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
}
checkNameUnique( name, method, Constants.OBSERVABLE_ANNOTATION_CLASSNAME );
if ( setter && !expectSetter )
{
throw new ArezProcessorException( "Method annotated with @Observable is a setter but defines " +
"expectSetter = false for observable named " + name, method );
}
final ObservableDescriptor observable = findOrCreateObservable( name );
if ( readOutsideTransaction )
{
observable.setReadOutsideTransaction( true );
}
if ( writeOutsideTransaction )
{
observable.setWriteOutsideTransaction( true );
}
if ( !setterAlwaysMutates )
{
observable.setSetterAlwaysMutates( false );
}
if ( !expectSetter )
{
observable.setExpectSetter( false );
}
if ( !observable.expectSetter() )
{
if ( observable.hasSetter() )
{
throw new ArezProcessorException( "Method annotated with @Observable defines expectSetter = false but a " +
"setter exists named " + observable.getSetter().getSimpleName() +
"for observable named " + name, method );
}
}
if ( setter )
{
if ( observable.hasSetter() )
{
throw new ArezProcessorException( "Method annotated with @Observable defines duplicate setter for " +
"observable named " + name, method );
}
if ( !observable.expectSetter() )
{
throw new ArezProcessorException( "Method annotated with @Observable defines expectSetter = false but a " +
"setter exists for observable named " + name, method );
}
observable.setSetter( method, methodType );
}
else
{
if ( observable.hasGetter() )
{
throw new ArezProcessorException( "Method annotated with @Observable defines duplicate getter for " +
"observable named " + name, method );
}
observable.setGetter( method, methodType );
}
if ( null != requireInitializer )
{
if ( !method.getModifiers().contains( Modifier.ABSTRACT ) )
{
throw new ArezProcessorException( "@Observable target set initializer parameter to ENABLED but " +
"method is not abstract.", method );
}
final Boolean existing = observable.getInitializer();
if ( null == existing )
{
observable.setInitializer( requireInitializer );
}
else if ( existing != requireInitializer )
{
throw new ArezProcessorException( "@Observable target set initializer parameter to value that differs from " +
"the paired observable method.", method );
}
}
return observable;
}
private void addObservableValueRef( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVABLE_VALUE_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeAbstract( Constants.OBSERVABLE_VALUE_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotHaveAnyParameters( Constants.OBSERVABLE_VALUE_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.OBSERVABLE_VALUE_REF_ANNOTATION_CLASSNAME, method );
final TypeMirror returnType = methodType.getReturnType();
if ( TypeKind.DECLARED != returnType.getKind() ||
!toRawType( returnType ).toString().equals( "arez.ObservableValue" ) )
{
throw new ArezProcessorException( "Method annotated with @ObservableValueRef must return an instance of " +
"arez.ObservableValue", method );
}
final String declaredName = getAnnotationParameter( annotation, "name" );
final String name;
if ( ProcessorUtil.isSentinelName( declaredName ) )
{
name = ProcessorUtil.deriveName( method, OBSERVABLE_REF_PATTERN, declaredName );
if ( null == name )
{
throw new ArezProcessorException( "Method annotated with @ObservableValueRef should specify name or be " +
"named according to the convention get[Name]ObservableValue", method );
}
}
else
{
name = declaredName;
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@ObservableValueRef target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@ObservableValueRef target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
}
final ObservableDescriptor observable = findOrCreateObservable( name );
if ( observable.hasRefMethod() )
{
throw new ArezProcessorException( "Method annotated with @ObservableValueRef defines duplicate ref " +
"accessor for observable named " + name, method );
}
observable.setRefMethod( method, methodType );
}
@Nonnull
private TypeName toRawType( @Nonnull final TypeMirror type )
{
final TypeName typeName = TypeName.get( type );
if ( typeName instanceof ParameterizedTypeName )
{
return ( (ParameterizedTypeName) typeName ).rawType;
}
else
{
return typeName;
}
}
private void addAction( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
MethodChecks.mustBeWrappable( getElement(), Constants.ACTION_ANNOTATION_CLASSNAME, method );
final String name = deriveActionName( method, annotation );
checkNameUnique( name, method, Constants.ACTION_ANNOTATION_CLASSNAME );
final boolean mutation = getAnnotationParameter( annotation, "mutation" );
final boolean requireNewTransaction = getAnnotationParameter( annotation, "requireNewTransaction" );
final boolean reportParameters = getAnnotationParameter( annotation, "reportParameters" );
final boolean reportResult = getAnnotationParameter( annotation, "reportResult" );
final boolean verifyRequired = getAnnotationParameter( annotation, "verifyRequired" );
final ActionDescriptor action =
new ActionDescriptor( name,
requireNewTransaction,
mutation,
verifyRequired,
reportParameters,
reportResult,
method,
methodType );
_actions.put( action.getName(), action );
}
@Nonnull
private String deriveActionName( @Nonnull final ExecutableElement method, @Nonnull final AnnotationMirror annotation )
throws ArezProcessorException
{
final String name = getAnnotationParameter( annotation, "name" );
if ( ProcessorUtil.isSentinelName( name ) )
{
return method.getSimpleName().toString();
}
else
{
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@Action target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@Action target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
return name;
}
}
private void addObserve( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
final String name = deriveObserveName( method, annotation );
checkNameUnique( name, method, Constants.OBSERVE_ANNOTATION_CLASSNAME );
final boolean mutation = getAnnotationParameter( annotation, "mutation" );
final boolean observeLowerPriorityDependencies =
getAnnotationParameter( annotation, "observeLowerPriorityDependencies" );
final boolean nestedActionsAllowed = getAnnotationParameter( annotation, "nestedActionsAllowed" );
final VariableElement priority = getAnnotationParameter( annotation, "priority" );
final boolean reportParameters = getAnnotationParameter( annotation, "reportParameters" );
final boolean reportResult = getAnnotationParameter( annotation, "reportResult" );
final VariableElement executor = getAnnotationParameter( annotation, "executor" );
final VariableElement depType = getAnnotationParameter( annotation, "depType" );
findOrCreateObserve( name ).setObserveMethod( mutation,
priority.getSimpleName().toString(),
executor.getSimpleName().toString().equals( "INTERNAL" ),
reportParameters,
reportResult,
depType.getSimpleName().toString(),
observeLowerPriorityDependencies,
nestedActionsAllowed,
method,
methodType );
}
@Nonnull
private String deriveObserveName( @Nonnull final ExecutableElement method,
@Nonnull final AnnotationMirror annotation )
throws ArezProcessorException
{
final String name = getAnnotationParameter( annotation, "name" );
if ( ProcessorUtil.isSentinelName( name ) )
{
return method.getSimpleName().toString();
}
else
{
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@Observe target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@Observe target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
return name;
}
}
private void addOnDepsChange( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
final String name =
deriveHookName( method,
ObserveDescriptor.ON_DEPS_CHANGE_PATTERN,
"DepsChange",
getAnnotationParameter( annotation, "name" ) );
findOrCreateObserve( name ).setOnDepsChange( method );
}
private void addObserverRef( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(), Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeAbstract( Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotHaveAnyParameters( Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.OBSERVER_REF_ANNOTATION_CLASSNAME, method );
final TypeMirror returnType = method.getReturnType();
if ( TypeKind.DECLARED != returnType.getKind() ||
!returnType.toString().equals( "arez.Observer" ) )
{
throw new ArezProcessorException( "Method annotated with @ObserverRef must return an instance of " +
"arez.Observer", method );
}
final String declaredName = getAnnotationParameter( annotation, "name" );
final String name;
if ( ProcessorUtil.isSentinelName( declaredName ) )
{
name = ProcessorUtil.deriveName( method, OBSERVER_REF_PATTERN, declaredName );
if ( null == name )
{
throw new ArezProcessorException( "Method annotated with @ObserverRef should specify name or be " +
"named according to the convention get[Name]Observer", method );
}
}
else
{
name = declaredName;
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@ObserverRef target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@ObserverRef target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
}
if ( _observerRefs.containsKey( name ) )
{
throw new ArezProcessorException( "Method annotated with @ObserverRef defines duplicate ref accessor for " +
"observer named " + name, method );
}
_observerRefs.put( name, new CandidateMethod( method, methodType ) );
}
@Nonnull
private MemoizeDescriptor findOrCreateMemoize( @Nonnull final String name )
{
return _memoizes.computeIfAbsent( name, n -> new MemoizeDescriptor( this, n ) );
}
private void addMemoize( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
final String name = deriveMemoizeName( method, annotation );
checkNameUnique( name, method, Constants.MEMOIZE_ANNOTATION_CLASSNAME );
final boolean keepAlive = getAnnotationParameter( annotation, "keepAlive" );
final boolean reportResult = getAnnotationParameter( annotation, "reportResult" );
final boolean observeLowerPriorityDependencies =
getAnnotationParameter( annotation, "observeLowerPriorityDependencies" );
final VariableElement priority = getAnnotationParameter( annotation, "priority" );
final VariableElement depType = getAnnotationParameter( annotation, "depType" );
final String depTypeAsString = depType.getSimpleName().toString();
findOrCreateMemoize( name ).setMemoize( method,
methodType,
keepAlive,
priority.getSimpleName().toString(),
reportResult,
observeLowerPriorityDependencies,
depTypeAsString );
}
private void addComputableValueRef( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(), Constants.COMPUTABLE_VALUE_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeAbstract( Constants.COMPUTABLE_VALUE_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.COMPUTABLE_VALUE_REF_ANNOTATION_CLASSNAME, method );
final TypeMirror returnType = methodType.getReturnType();
if ( TypeKind.DECLARED != returnType.getKind() ||
!toRawType( returnType ).toString().equals( "arez.ComputableValue" ) )
{
throw new ArezProcessorException( "Method annotated with @ComputableValueRef must return an instance of " +
"arez.ComputableValue", method );
}
final String declaredName = getAnnotationParameter( annotation, "name" );
final String name;
if ( ProcessorUtil.isSentinelName( declaredName ) )
{
name = ProcessorUtil.deriveName( method, COMPUTABLE_VALUE_REF_PATTERN, declaredName );
if ( null == name )
{
throw new ArezProcessorException( "Method annotated with @ComputableValueRef should specify name or be " +
"named according to the convention get[Name]ComputableValue", method );
}
}
else
{
name = declaredName;
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@ComputableValueRef target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@ComputableValueRef target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
}
findOrCreateMemoize( name ).setRefMethod( method, methodType );
}
@Nonnull
private String deriveMemoizeName( @Nonnull final ExecutableElement method,
@Nonnull final AnnotationMirror annotation )
throws ArezProcessorException
{
final String name = getAnnotationParameter( annotation, "name" );
if ( ProcessorUtil.isSentinelName( name ) )
{
return getPropertyAccessorName( method, name );
}
else
{
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@Memoize target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@Memoize target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
return name;
}
}
private void addOnActivate( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
final String name = deriveHookName( method,
MemoizeDescriptor.ON_ACTIVATE_PATTERN,
"Activate",
getAnnotationParameter( annotation, "name" ) );
findOrCreateMemoize( name ).setOnActivate( method );
}
private void addOnDeactivate( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
final String name =
deriveHookName( method,
MemoizeDescriptor.ON_DEACTIVATE_PATTERN,
"Deactivate",
getAnnotationParameter( annotation, "name" ) );
findOrCreateMemoize( name ).setOnDeactivate( method );
}
private void addOnStale( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
final String name =
deriveHookName( method,
MemoizeDescriptor.ON_STALE_PATTERN,
"Stale",
getAnnotationParameter( annotation, "name" ) );
findOrCreateMemoize( name ).setOnStale( method );
}
@Nonnull
private String deriveHookName( @Nonnull final ExecutableElement method,
@Nonnull final Pattern pattern,
@Nonnull final String type,
@Nonnull final String name )
throws ArezProcessorException
{
final String value = ProcessorUtil.deriveName( method, pattern, name );
if ( null == value )
{
throw new ArezProcessorException( "Unable to derive name for @On" + type + " as does not match " +
"on[Name]" + type + " pattern. Please specify name.", method );
}
else if ( !SourceVersion.isIdentifier( value ) )
{
throw new ArezProcessorException( "@On" + type + " target specified an invalid name '" + value + "'. The " +
"name must be a valid java identifier.", _element );
}
else if ( SourceVersion.isKeyword( value ) )
{
throw new ArezProcessorException( "@On" + type + " target specified an invalid name '" + value + "'. The " +
"name must not be a java keyword.", _element );
}
else
{
return value;
}
}
private void setContextRef( @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(), Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeAbstract( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotHaveAnyParameters( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustReturnAValue( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.CONTEXT_REF_ANNOTATION_CLASSNAME, method );
final TypeMirror returnType = method.getReturnType();
if ( TypeKind.DECLARED != returnType.getKind() ||
!returnType.toString().equals( "arez.ArezContext" ) )
{
throw new ArezProcessorException( "Method annotated with @ContextRef must return an instance of " +
"arez.ArezContext", method );
}
if ( null != _contextRef )
{
throw new ArezProcessorException( "@ContextRef target duplicates existing method named " +
_contextRef.getSimpleName(), method );
}
else
{
_contextRef = Objects.requireNonNull( method );
}
}
boolean hasComponentIdRefMethod()
{
return null != _componentIdRef;
}
private void setComponentIdRef( @Nonnull final ExecutableElement method )
{
MethodChecks.mustBeOverridable( getElement(), Constants.COMPONENT_ID_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeAbstract( Constants.COMPONENT_ID_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_ID_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustReturnAValue( Constants.COMPONENT_ID_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_ID_REF_ANNOTATION_CLASSNAME, method );
if ( null != _componentIdRef )
{
throw new ArezProcessorException( "@ComponentIdRef target duplicates existing method named " +
_componentIdRef.getSimpleName(), method );
}
else
{
_componentIdRef = Objects.requireNonNull( method );
}
}
private void setComponentRef( @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(), Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeAbstract( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustReturnAValue( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_REF_ANNOTATION_CLASSNAME, method );
final TypeMirror returnType = method.getReturnType();
if ( TypeKind.DECLARED != returnType.getKind() ||
!returnType.toString().equals( "arez.Component" ) )
{
throw new ArezProcessorException( "Method annotated with @ComponentRef must return an instance of " +
"arez.Component", method );
}
if ( null != _componentRef )
{
throw new ArezProcessorException( "@ComponentRef target duplicates existing method named " +
_componentRef.getSimpleName(), method );
}
else
{
_componentRef = Objects.requireNonNull( method );
}
}
boolean hasComponentIdMethod()
{
return null != _componentId;
}
private void setComponentId( @Nonnull final ExecutableElement componentId,
@Nonnull final ExecutableType componentIdMethodType )
throws ArezProcessorException
{
MethodChecks.mustNotBeAbstract( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId );
MethodChecks.mustBeSubclassCallable( getElement(), Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId );
MethodChecks.mustBeFinal( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId );
MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId );
MethodChecks.mustReturnAValue( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId );
MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_ID_ANNOTATION_CLASSNAME, componentId );
if ( null != _componentId )
{
throw new ArezProcessorException( "@ComponentId target duplicates existing method named " +
_componentId.getSimpleName(), componentId );
}
else
{
_componentId = Objects.requireNonNull( componentId );
_componentIdMethodType = componentIdMethodType;
}
}
private void setComponentTypeNameRef( @Nonnull final ExecutableElement componentTypeName )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(),
Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME,
componentTypeName );
MethodChecks.mustBeAbstract( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName );
MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName );
MethodChecks.mustReturnAValue( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName );
MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME, componentTypeName );
final TypeMirror returnType = componentTypeName.getReturnType();
if ( !( TypeKind.DECLARED == returnType.getKind() &&
returnType.toString().equals( String.class.getName() ) ) )
{
throw new ArezProcessorException( "@ComponentTypeNameRef target must return a String", componentTypeName );
}
if ( null != _componentTypeNameRef )
{
throw new ArezProcessorException( "@ComponentTypeNameRef target duplicates existing method named " +
_componentTypeNameRef.getSimpleName(), componentTypeName );
}
else
{
_componentTypeNameRef = Objects.requireNonNull( componentTypeName );
}
}
private void setComponentNameRef( @Nonnull final ExecutableElement componentName )
throws ArezProcessorException
{
MethodChecks.mustBeOverridable( getElement(), Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName );
MethodChecks.mustBeAbstract( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName );
MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName );
MethodChecks.mustReturnAValue( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName );
MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME, componentName );
if ( null != _componentNameRef )
{
throw new ArezProcessorException( "@ComponentNameRef target duplicates existing method named " +
_componentNameRef.getSimpleName(), componentName );
}
else
{
_componentNameRef = Objects.requireNonNull( componentName );
}
}
@Nullable
ExecutableElement getPostConstruct()
{
return _postConstruct;
}
void setPostConstruct( @Nonnull final ExecutableElement postConstruct )
throws ArezProcessorException
{
MethodChecks.mustBeLifecycleHook( getElement(), Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME, postConstruct );
if ( null != _postConstruct )
{
throw new ArezProcessorException( "@PostConstruct target duplicates existing method named " +
_postConstruct.getSimpleName(), postConstruct );
}
else
{
_postConstruct = postConstruct;
}
}
private void setPreDispose( @Nonnull final ExecutableElement preDispose )
throws ArezProcessorException
{
MethodChecks.mustBeLifecycleHook( getElement(), Constants.PRE_DISPOSE_ANNOTATION_CLASSNAME, preDispose );
if ( null != _preDispose )
{
throw new ArezProcessorException( "@PreDispose target duplicates existing method named " +
_preDispose.getSimpleName(), preDispose );
}
else
{
_preDispose = preDispose;
}
}
private void setPostDispose( @Nonnull final ExecutableElement postDispose )
throws ArezProcessorException
{
MethodChecks.mustBeLifecycleHook( getElement(), Constants.POST_DISPOSE_ANNOTATION_CLASSNAME, postDispose );
if ( null != _postDispose )
{
throw new ArezProcessorException( "@PostDispose target duplicates existing method named " +
_postDispose.getSimpleName(), postDispose );
}
else
{
_postDispose = postDispose;
}
}
@Nonnull
Collection<ObservableDescriptor> getObservables()
{
return _roObservables;
}
void validate()
throws ArezProcessorException
{
_roObservables.forEach( ObservableDescriptor::validate );
_roMemoizes.forEach( MemoizeDescriptor::validate );
_roObserves.forEach( ObserveDescriptor::validate );
_roDependencies.forEach( DependencyDescriptor::validate );
_roReferences.forEach( ReferenceDescriptor::validate );
_roInverses.forEach( InverseDescriptor::validate );
final boolean hasReactiveElements =
_roObservables.isEmpty() &&
_roActions.isEmpty() &&
_roMemoizes.isEmpty() &&
_roDependencies.isEmpty() &&
_roCascadeDisposes.isEmpty() &&
_roReferences.isEmpty() &&
_roInverses.isEmpty() &&
_roObserves.isEmpty();
if ( !_allowEmpty && hasReactiveElements )
{
throw new ArezProcessorException( "@ArezComponent target has no methods annotated with @Action, " +
"@CascadeDispose, @Memoize, @Observable, @Inverse, " +
"@Reference, @ComponentDependency or @Observe", _element );
}
else if ( _allowEmpty && !hasReactiveElements && !_generated )
{
throw new ArezProcessorException( "@ArezComponent target has specified allowEmpty = true but has methods " +
"annotated with @Action, @CascadeDispose, @Memoize, @Observable, @Inverse, " +
"@Reference, @ComponentDependency or @Observe", _element );
}
if ( _deferSchedule && !requiresSchedule() )
{
throw new ArezProcessorException( "@ArezComponent target has specified the deferSchedule = true " +
"annotation parameter but has no methods annotated with @Observe, " +
"@ComponentDependency or @Memoize(keepAlive=true)", _element );
}
if ( null != _componentIdRef &&
null != _componentId &&
!_typeUtils.isSameType( _componentId.getReturnType(), _componentIdRef.getReturnType() ) )
{
throw new ArezProcessorException( "@ComponentIdRef target has a return type " + _componentIdRef.getReturnType() +
" and a @ComponentId annotated method with a return type " +
_componentIdRef.getReturnType() + ". The types must match.", _element );
}
else if ( null != _componentIdRef &&
null == _componentId &&
!_typeUtils.isSameType( _typeUtils.getPrimitiveType( TypeKind.INT ), _componentIdRef.getReturnType() ) )
{
throw new ArezProcessorException( "@ComponentIdRef target has a return type " + _componentIdRef.getReturnType() +
" but no @ComponentId annotated method. The type is expected to be of " +
"type int.", _element );
}
else if ( InjectMode.NONE != _injectMode )
{
for ( final ExecutableElement constructor : getConstructors( getElement() ) )
{
// The annotation processor engine can not distinguish between a "default constructor"
// synthesized by the compiler and one written by a user that has the same signature.
// So our check just skips scenarios where the constructor could be synthetic.
if ( constructor.getModifiers().contains( Modifier.PUBLIC ) &&
!( constructor.getParameters().isEmpty() && constructor.getThrownTypes().isEmpty() ) )
{
throw new ArezProcessorException( "@ArezComponent target has a public constructor but the inject parameter " +
"does not resolve to NONE. Public constructors are not necessary when " +
"the instantiation of the component is managed by the injection framework.",
constructor );
}
}
if ( InjectMode.PROVIDE == _injectMode &&
_dagger &&
!getElement().getModifiers().contains( Modifier.PUBLIC ) )
{
throw new ArezProcessorException( "@ArezComponent target is not public but is configured as inject = PROVIDE " +
"using the dagger injection framework. Due to constraints within the " +
"dagger framework the type needs to made public.",
getElement() );
}
}
}
private boolean requiresSchedule()
{
return _roObserves.stream().anyMatch( ObserveDescriptor::isInternalExecutor ) ||
!_roDependencies.isEmpty() ||
_memoizes.values().stream().anyMatch( MemoizeDescriptor::isKeepAlive );
}
private void checkNameUnique( @Nonnull final String name,
@Nonnull final ExecutableElement sourceMethod,
@Nonnull final String sourceAnnotationName )
throws ArezProcessorException
{
final ActionDescriptor action = _actions.get( name );
if ( null != action )
{
throw toException( name,
sourceAnnotationName,
sourceMethod,
Constants.ACTION_ANNOTATION_CLASSNAME,
action.getAction() );
}
final MemoizeDescriptor memoize = _memoizes.get( name );
if ( null != memoize && memoize.hasMemoize() )
{
throw toException( name,
sourceAnnotationName,
sourceMethod,
Constants.MEMOIZE_ANNOTATION_CLASSNAME,
memoize.getMethod() );
}
// Observe have pairs so let the caller determine whether a duplicate occurs in that scenario
if ( !sourceAnnotationName.equals( Constants.OBSERVE_ANNOTATION_CLASSNAME ) )
{
final ObserveDescriptor observed = _observes.get( name );
if ( null != observed )
{
throw toException( name,
sourceAnnotationName,
sourceMethod,
Constants.OBSERVE_ANNOTATION_CLASSNAME,
observed.getObserve() );
}
}
// Observables have pairs so let the caller determine whether a duplicate occurs in that scenario
if ( !sourceAnnotationName.equals( Constants.OBSERVABLE_ANNOTATION_CLASSNAME ) )
{
final ObservableDescriptor observable = _observables.get( name );
if ( null != observable )
{
throw toException( name,
sourceAnnotationName,
sourceMethod,
Constants.OBSERVABLE_ANNOTATION_CLASSNAME,
observable.getDefiner() );
}
}
}
@Nonnull
private ArezProcessorException toException( @Nonnull final String name,
@Nonnull final String sourceAnnotationName,
@Nonnull final ExecutableElement sourceMethod,
@Nonnull final String targetAnnotationName,
@Nonnull final ExecutableElement targetElement )
{
return new ArezProcessorException( "Method annotated with @" + ProcessorUtil.toSimpleName( sourceAnnotationName ) +
" specified name " + name + " that duplicates @" +
ProcessorUtil.toSimpleName( targetAnnotationName ) + " defined by method " +
targetElement.getSimpleName(), sourceMethod );
}
void analyzeCandidateMethods( @Nonnull final List<ExecutableElement> methods,
@Nonnull final Types typeUtils )
throws ArezProcessorException
{
for ( final ExecutableElement method : methods )
{
final String methodName = method.getSimpleName().toString();
if ( AREZ_SPECIAL_METHODS.contains( methodName ) && method.getParameters().isEmpty() )
{
throw new ArezProcessorException( "Method defined on a class annotated by @ArezComponent uses a name " +
"reserved by Arez", method );
}
else if ( methodName.startsWith( Generator.FIELD_PREFIX ) ||
methodName.startsWith( Generator.OBSERVABLE_DATA_FIELD_PREFIX ) ||
methodName.startsWith( Generator.REFERENCE_FIELD_PREFIX ) ||
methodName.startsWith( Generator.FRAMEWORK_PREFIX ) )
{
throw new ArezProcessorException( "Method defined on a class annotated by @ArezComponent uses a name " +
"with a prefix reserved by Arez", method );
}
}
final Map<String, CandidateMethod> getters = new HashMap<>();
final Map<String, CandidateMethod> setters = new HashMap<>();
final Map<String, CandidateMethod> observes = new HashMap<>();
final Map<String, CandidateMethod> onDepsChanges = new HashMap<>();
for ( final ExecutableElement method : methods )
{
final ExecutableType methodType =
(ExecutableType) typeUtils.asMemberOf( (DeclaredType) _element.asType(), method );
if ( !analyzeMethod( method, methodType ) )
{
/*
* If we get here the method was not annotated so we can try to detect if it is a
* candidate arez method in case some arez annotations are implied via naming conventions.
*/
if ( method.getModifiers().contains( Modifier.STATIC ) )
{
continue;
}
final CandidateMethod candidateMethod = new CandidateMethod( method, methodType );
final boolean voidReturn = method.getReturnType().getKind() == TypeKind.VOID;
final int parameterCount = method.getParameters().size();
String name;
if ( !method.getModifiers().contains( Modifier.FINAL ) )
{
name = ProcessorUtil.deriveName( method, SETTER_PATTERN, ProcessorUtil.SENTINEL_NAME );
if ( voidReturn && 1 == parameterCount && null != name )
{
setters.put( name, candidateMethod );
continue;
}
name = ProcessorUtil.deriveName( method, ISSER_PATTERN, ProcessorUtil.SENTINEL_NAME );
if ( !voidReturn && 0 == parameterCount && null != name )
{
getters.put( name, candidateMethod );
continue;
}
name = ProcessorUtil.deriveName( method, GETTER_PATTERN, ProcessorUtil.SENTINEL_NAME );
if ( !voidReturn && 0 == parameterCount && null != name )
{
getters.put( name, candidateMethod );
continue;
}
}
name =
ProcessorUtil.deriveName( method, ObserveDescriptor.ON_DEPS_CHANGE_PATTERN, ProcessorUtil.SENTINEL_NAME );
if ( voidReturn && 0 == parameterCount && null != name )
{
onDepsChanges.put( name, candidateMethod );
continue;
}
final String methodName = method.getSimpleName().toString();
if ( !OBJECT_METHODS.contains( methodName ) )
{
observes.put( methodName, candidateMethod );
}
}
}
linkUnAnnotatedObservables( getters, setters );
linkUnAnnotatedObserves( observes, onDepsChanges );
linkObserverRefs();
linkDependencies( getters.values() );
autodetectObservableInitializers();
/*
* ALl of the maps will have called remove() for all matching candidates.
* Thus any left are the non-arez methods.
*/
ensureNoAbstractMethods( getters.values() );
ensureNoAbstractMethods( setters.values() );
ensureNoAbstractMethods( observes.values() );
ensureNoAbstractMethods( onDepsChanges.values() );
processCascadeDisposeFields();
processComponentDependencyFields();
}
private void processComponentDependencyFields()
{
ProcessorUtil.getFieldElements( _element )
.stream()
.filter( f -> null !=
ProcessorUtil.findAnnotationByType( f, Constants.COMPONENT_DEPENDENCY_ANNOTATION_CLASSNAME ) )
.forEach( this::processComponentDependencyField );
}
private void processComponentDependencyField( @Nonnull final VariableElement field )
{
verifyNoDuplicateAnnotations( field );
MethodChecks.mustBeSubclassCallable( _element, Constants.COMPONENT_DEPENDENCY_ANNOTATION_CLASSNAME, field );
addDependency( field );
}
private void processCascadeDisposeFields()
{
ProcessorUtil.getFieldElements( _element )
.stream()
.filter( f -> null != ProcessorUtil.findAnnotationByType( f, Constants.CASCADE_DISPOSE_ANNOTATION_CLASSNAME ) )
.forEach( this::processCascadeDisposeField );
}
private void processCascadeDisposeField( @Nonnull final VariableElement field )
{
verifyNoDuplicateAnnotations( field );
MethodChecks.mustBeSubclassCallable( _element, Constants.CASCADE_DISPOSE_ANNOTATION_CLASSNAME, field );
mustBeCascadeDisposeTypeCompatible( field );
_cascadeDisposes.put( field, new CascadeDisposableDescriptor( field ) );
}
private void mustBeCascadeDisposeTypeCompatible( @Nonnull final VariableElement field )
{
final TypeElement disposable = _elements.getTypeElement( Constants.DISPOSABLE_CLASSNAME );
assert null != disposable;
final TypeMirror typeMirror = field.asType();
if ( !_typeUtils.isAssignable( typeMirror, disposable.asType() ) )
{
final TypeElement typeElement = (TypeElement) _typeUtils.asElement( typeMirror );
final AnnotationMirror value =
null != typeElement ?
ProcessorUtil.findAnnotationByType( typeElement, Constants.COMPONENT_ANNOTATION_CLASSNAME ) :
null;
if ( null == value || !ProcessorUtil.isDisposableTrackableRequired( _elements, typeElement ) )
{
//The type of the field must implement {@link arez.Disposable} or must be annotated by {@link ArezComponent}
throw new ArezProcessorException( "@CascadeDispose target must be assignable to " +
Constants.DISPOSABLE_CLASSNAME + " or a type annotated with @ArezComponent",
field );
}
}
}
private void addCascadeDisposeMethod( @Nonnull final ExecutableElement method )
{
MethodChecks.mustNotBeAbstract( Constants.CASCADE_DISPOSE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotHaveAnyParameters( Constants.CASCADE_DISPOSE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.CASCADE_DISPOSE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeSubclassCallable( _element, Constants.CASCADE_DISPOSE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeFinal( Constants.CASCADE_DISPOSE_ANNOTATION_CLASSNAME, method );
mustBeCascadeDisposeTypeCompatible( method );
_cascadeDisposes.put( method, new CascadeDisposableDescriptor( method ) );
}
private void mustBeCascadeDisposeTypeCompatible( @Nonnull final ExecutableElement method )
{
final TypeElement disposable = _elements.getTypeElement( Constants.DISPOSABLE_CLASSNAME );
assert null != disposable;
final TypeMirror typeMirror = method.getReturnType();
if ( !_typeUtils.isAssignable( typeMirror, disposable.asType() ) )
{
final TypeElement typeElement = (TypeElement) _typeUtils.asElement( typeMirror );
final AnnotationMirror value =
null != typeElement ?
ProcessorUtil.findAnnotationByType( typeElement, Constants.COMPONENT_ANNOTATION_CLASSNAME ) :
null;
if ( null == value || !ProcessorUtil.isDisposableTrackableRequired( _elements, typeElement ) )
{
//The type of the field must implement {@link arez.Disposable} or must be annotated by {@link ArezComponent}
throw new ArezProcessorException( "@CascadeDispose target must return a type assignable to " +
Constants.DISPOSABLE_CLASSNAME + " or a type annotated with @ArezComponent",
method );
}
}
}
private void autodetectObservableInitializers()
{
for ( final ObservableDescriptor observable : getObservables() )
{
if ( null == observable.getInitializer() && observable.hasGetter() )
{
if ( observable.hasSetter() )
{
final boolean initializer =
autodetectInitializer( observable.getGetter() ) && autodetectInitializer( observable.getSetter() );
observable.setInitializer( initializer );
}
else
{
final boolean initializer = autodetectInitializer( observable.getGetter() );
observable.setInitializer( initializer );
}
}
}
}
private void linkDependencies( @Nonnull final Collection<CandidateMethod> candidates )
{
_roObservables
.stream()
.filter( ObservableDescriptor::hasGetter )
.filter( o -> hasDependencyAnnotation( o.getGetter() ) )
.forEach( o -> addOrUpdateDependency( o.getGetter(), o ) );
_roMemoizes
.stream()
.filter( MemoizeDescriptor::hasMemoize )
.map( MemoizeDescriptor::getMethod )
.filter( this::hasDependencyAnnotation )
.forEach( this::addDependency );
candidates
.stream()
.map( CandidateMethod::getMethod )
.filter( this::hasDependencyAnnotation )
.forEach( this::addDependency );
}
private boolean hasDependencyAnnotation( @Nonnull final ExecutableElement method )
{
return null != ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_DEPENDENCY_ANNOTATION_CLASSNAME );
}
private void addOrUpdateDependency( @Nonnull final ExecutableElement method,
@Nonnull final ObservableDescriptor observable )
{
final DependencyDescriptor dependencyDescriptor =
_dependencies.computeIfAbsent( method, m -> createMethodDependencyDescriptor( method ) );
dependencyDescriptor.setObservable( observable );
}
private void addReferenceId( @Nonnull final AnnotationMirror annotation,
@Nonnull final ObservableDescriptor observable,
@Nonnull final ExecutableElement method )
{
MethodChecks.mustNotHaveAnyParameters( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeSubclassCallable( getElement(), Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method );
MethodChecks.mustReturnAValue( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method );
findOrCreateReference( getReferenceIdName( annotation, method ) ).setObservable( observable );
}
private void addReferenceId( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
{
MethodChecks.mustNotHaveAnyParameters( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeSubclassCallable( getElement(), Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method );
MethodChecks.mustReturnAValue( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME, method );
final String name = getReferenceIdName( annotation, method );
findOrCreateReference( name ).setIdMethod( method, methodType );
}
@Nonnull
private String getReferenceIdName( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method )
{
final String declaredName = getAnnotationParameter( annotation, "name" );
final String name;
if ( ProcessorUtil.isSentinelName( declaredName ) )
{
final String candidate = ProcessorUtil.deriveName( method, ID_GETTER_PATTERN, declaredName );
if ( null == candidate )
{
final String candidate2 = ProcessorUtil.deriveName( method, RAW_ID_GETTER_PATTERN, declaredName );
if ( null == candidate2 )
{
throw new ArezProcessorException( "@ReferenceId target has not specified a name and does not follow " +
"the convention \"get[Name]Id\" or \"[name]Id\"", method );
}
else
{
name = candidate2;
}
}
else
{
name = candidate;
}
}
else
{
name = declaredName;
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@ReferenceId target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@ReferenceId target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
}
return name;
}
private void addInverse( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
{
MethodChecks.mustNotHaveAnyParameters( Constants.INVERSE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeSubclassCallable( getElement(), Constants.INVERSE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.INVERSE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustReturnAValue( Constants.INVERSE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeAbstract( Constants.INVERSE_ANNOTATION_CLASSNAME, method );
final String name = getInverseName( annotation, method );
final ObservableDescriptor observable = findOrCreateObservable( name );
observable.setGetter( method, methodType );
addInverse( annotation, observable, method );
}
private void addInverse( @Nonnull final AnnotationMirror annotation,
@Nonnull final ObservableDescriptor observable,
@Nonnull final ExecutableElement method )
{
MethodChecks.mustNotHaveAnyParameters( Constants.INVERSE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeSubclassCallable( getElement(), Constants.INVERSE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.INVERSE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustReturnAValue( Constants.INVERSE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeAbstract( Constants.INVERSE_ANNOTATION_CLASSNAME, method );
final String name = getInverseName( annotation, method );
final InverseDescriptor existing = _inverses.get( name );
if ( null != existing )
{
throw new ArezProcessorException( "@Inverse target defines duplicate inverse for name '" + name +
"'. The other inverse is " + existing.getObservable().getGetter(),
method );
}
else
{
final TypeMirror type = method.getReturnType();
final Multiplicity multiplicity;
TypeElement targetType = getInverseManyTypeTarget( method );
if ( null != targetType )
{
multiplicity = Multiplicity.MANY;
}
else
{
if ( !( type instanceof DeclaredType ) ||
null == ProcessorUtil.findAnnotationByType( ( (DeclaredType) type ).asElement(),
Constants.COMPONENT_ANNOTATION_CLASSNAME ) )
{
throw new ArezProcessorException( "@Inverse target expected to return a type annotated with " +
Constants.COMPONENT_ANNOTATION_CLASSNAME, method );
}
targetType = (TypeElement) ( (DeclaredType) type ).asElement();
if ( null != ProcessorUtil.findAnnotationByType( method, Constants.NONNULL_ANNOTATION_CLASSNAME ) )
{
multiplicity = Multiplicity.ONE;
}
else if ( null != ProcessorUtil.findAnnotationByType( method, Constants.NULLABLE_ANNOTATION_CLASSNAME ) )
{
multiplicity = Multiplicity.ZERO_OR_ONE;
}
else
{
throw new ArezProcessorException( "@Inverse target expected to be annotated with either " +
Constants.NULLABLE_ANNOTATION_CLASSNAME + " or " +
Constants.NONNULL_ANNOTATION_CLASSNAME, method );
}
}
final String referenceName = getInverseReferenceNameParameter( method );
final InverseDescriptor descriptor =
new InverseDescriptor( this, observable, referenceName, multiplicity, targetType );
_inverses.put( name, descriptor );
verifyMultiplicityOfAssociatedReferenceMethod( descriptor );
}
}
private void verifyMultiplicityOfAssociatedReferenceMethod( @Nonnull final InverseDescriptor descriptor )
{
final Multiplicity multiplicity =
ProcessorUtil
.getMethods( descriptor.getTargetType(), _elements, _typeUtils )
.stream()
.map( m -> {
final AnnotationMirror a = ProcessorUtil.findAnnotationByType( m, Constants.REFERENCE_ANNOTATION_CLASSNAME );
if ( null != a && getReferenceName( a, m ).equals( descriptor.getReferenceName() ) )
{
if ( null == ProcessorUtil.findAnnotationValueNoDefaults( a, "inverse" ) &&
null == ProcessorUtil.findAnnotationValueNoDefaults( a, "inverseName" ) &&
null == ProcessorUtil.findAnnotationValueNoDefaults( a, "inverseMultiplicity" ) )
{
throw new ArezProcessorException( "@Inverse target found an associated @Reference on the method '" +
m.getSimpleName() + "' on type '" +
descriptor.getTargetType().getQualifiedName() + "' but the " +
"annotation has not configured an inverse.",
descriptor.getObservable().getGetter() );
}
ensureTargetTypeAligns( descriptor, m.getReturnType() );
return getReferenceInverseMultiplicity( a );
}
else
{
return null;
}
} )
.filter( Objects::nonNull )
.findAny()
.orElse( null );
if ( null == multiplicity )
{
throw new ArezProcessorException( "@Inverse target expected to find an associated @Reference annotation with " +
"a name parameter equal to '" + descriptor.getReferenceName() + "' on class " +
descriptor.getTargetType().getQualifiedName() + " but is unable to " +
"locate a matching method.", descriptor.getObservable().getGetter() );
}
if ( descriptor.getMultiplicity() != multiplicity )
{
throw new ArezProcessorException( "@Inverse target has a multiplicity of " + descriptor.getMultiplicity() +
" but that associated @Reference has a multiplicity of " + multiplicity +
". The multiplicity must align.", descriptor.getObservable().getGetter() );
}
}
private void ensureTargetTypeAligns( @Nonnull final InverseDescriptor descriptor, @Nonnull final TypeMirror target )
{
if ( !_typeUtils.isSameType( target, getElement().asType() ) )
{
throw new ArezProcessorException( "@Inverse target expected to find an associated @Reference annotation with " +
"a target type equal to " + descriptor.getTargetType() + " but the actual " +
"target type is " + target, descriptor.getObservable().getGetter() );
}
}
@Nullable
private TypeElement getInverseManyTypeTarget( @Nonnull final ExecutableElement method )
{
final TypeName typeName = TypeName.get( method.getReturnType() );
if ( typeName instanceof ParameterizedTypeName )
{
final ParameterizedTypeName type = (ParameterizedTypeName) typeName;
if ( isSupportedInverseCollectionType( type.rawType.toString() ) && !type.typeArguments.isEmpty() )
{
final TypeElement typeElement = _elements.getTypeElement( type.typeArguments.get( 0 ).toString() );
if ( null != ProcessorUtil.findAnnotationByType( typeElement, Constants.COMPONENT_ANNOTATION_CLASSNAME ) )
{
return typeElement;
}
else
{
throw new ArezProcessorException( "@Inverse target expected to return a type annotated with " +
Constants.COMPONENT_ANNOTATION_CLASSNAME, method );
}
}
}
return null;
}
private boolean isSupportedInverseCollectionType( @Nonnull final String typeClassname )
{
return Collection.class.getName().equals( typeClassname ) ||
Set.class.getName().equals( typeClassname ) ||
List.class.getName().equals( typeClassname );
}
@Nonnull
private String getInverseReferenceNameParameter( @Nonnull final ExecutableElement method )
{
final String declaredName =
(String) ProcessorUtil.getAnnotationValue( _elements,
method,
Constants.INVERSE_ANNOTATION_CLASSNAME,
"referenceName" ).getValue();
final String name;
if ( ProcessorUtil.isSentinelName( declaredName ) )
{
name = ProcessorUtil.firstCharacterToLowerCase( getElement().getSimpleName().toString() );
}
else
{
name = declaredName;
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@Inverse target specified an invalid referenceName '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@Inverse target specified an invalid referenceName '" + name + "'. The " +
"name must not be a java keyword.", method );
}
}
return name;
}
@Nonnull
private String getInverseName( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method )
{
final String declaredName = getAnnotationParameter( annotation, "name" );
final String name;
if ( ProcessorUtil.isSentinelName( declaredName ) )
{
final String candidate = ProcessorUtil.deriveName( method, GETTER_PATTERN, declaredName );
name = null == candidate ? method.getSimpleName().toString() : candidate;
}
else
{
name = declaredName;
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@Inverse target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@Inverse target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
}
return name;
}
private void addReference( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
{
MethodChecks.mustNotHaveAnyParameters( Constants.REFERENCE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeSubclassCallable( getElement(), Constants.REFERENCE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.REFERENCE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustReturnAValue( Constants.REFERENCE_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeAbstract( Constants.REFERENCE_ANNOTATION_CLASSNAME, method );
final String name = getReferenceName( annotation, method );
final String linkType = getLinkType( method );
final String inverseName;
final Multiplicity inverseMultiplicity;
if ( hasInverse( annotation ) )
{
inverseMultiplicity = getReferenceInverseMultiplicity( annotation );
inverseName = getReferenceInverseName( annotation, method, inverseMultiplicity );
final TypeMirror returnType = method.getReturnType();
if ( !( returnType instanceof DeclaredType ) ||
null == ProcessorUtil.findAnnotationByType( ( (DeclaredType) returnType ).asElement(),
Constants.COMPONENT_ANNOTATION_CLASSNAME ) )
{
throw new ArezProcessorException( "@Reference target expected to return a type annotated with " +
Constants.COMPONENT_ANNOTATION_CLASSNAME + " if there is an " +
"inverse reference.", method );
}
}
else
{
inverseName = null;
inverseMultiplicity = null;
}
final ReferenceDescriptor descriptor = findOrCreateReference( name );
descriptor.setMethod( method, methodType, linkType, inverseName, inverseMultiplicity );
verifyMultiplicityOfAssociatedInverseMethod( descriptor );
}
private void verifyMultiplicityOfAssociatedInverseMethod( @Nonnull final ReferenceDescriptor descriptor )
{
final TypeElement element = (TypeElement) _typeUtils.asElement( descriptor.getMethod().getReturnType() );
final String defaultInverseName =
descriptor.hasInverse() ?
null :
ProcessorUtil.firstCharacterToLowerCase( getElement().getSimpleName().toString() ) + "s";
final Multiplicity multiplicity =
ProcessorUtil
.getMethods( element, _elements, _typeUtils )
.stream()
.map( m -> {
final AnnotationMirror a = ProcessorUtil.findAnnotationByType( m, Constants.INVERSE_ANNOTATION_CLASSNAME );
if ( null == a )
{
return null;
}
final String inverseName = getInverseName( a, m );
if ( !descriptor.hasInverse() && inverseName.equals( defaultInverseName ) )
{
throw new ArezProcessorException( "@Reference target has not configured an inverse but there is an " +
"associated @Inverse annotated method named '" + m.getSimpleName() +
"' on type '" + element.getQualifiedName() + "'.",
descriptor.getMethod() );
}
if ( descriptor.hasInverse() && inverseName.equals( descriptor.getInverseName() ) )
{
final TypeElement target = getInverseManyTypeTarget( m );
if ( null != target )
{
ensureTargetTypeAligns( descriptor, target.asType() );
return Multiplicity.MANY;
}
else
{
ensureTargetTypeAligns( descriptor, m.getReturnType() );
if ( null != ProcessorUtil.findAnnotationByType( m, Constants.NONNULL_ANNOTATION_CLASSNAME ) )
{
return Multiplicity.ONE;
}
else
{
return Multiplicity.ZERO_OR_ONE;
}
}
}
else
{
return null;
}
} )
.filter( Objects::nonNull )
.findAny()
.orElse( null );
if ( descriptor.hasInverse() )
{
if ( null == multiplicity )
{
throw new ArezProcessorException( "@Reference target expected to find an associated @Inverse annotation " +
"with a name parameter equal to '" + descriptor.getInverseName() + "' on " +
"class " + descriptor.getMethod().getReturnType() + " but is unable to " +
"locate a matching method.", descriptor.getMethod() );
}
final Multiplicity inverseMultiplicity = descriptor.getInverseMultiplicity();
if ( inverseMultiplicity != multiplicity )
{
throw new ArezProcessorException( "@Reference target has an inverseMultiplicity of " + inverseMultiplicity +
" but that associated @Inverse has a multiplicity of " + multiplicity +
". The multiplicity must align.", descriptor.getMethod() );
}
}
}
private void ensureTargetTypeAligns( @Nonnull final ReferenceDescriptor descriptor, @Nonnull final TypeMirror target )
{
if ( !_typeUtils.isSameType( target, getElement().asType() ) )
{
throw new ArezProcessorException( "@Reference target expected to find an associated @Inverse annotation with " +
"a target type equal to " + getElement().getQualifiedName() + " but " +
"the actual target type is " + target, descriptor.getMethod() );
}
}
private boolean hasInverse( @Nonnull final AnnotationMirror annotation )
{
final VariableElement variableElement = ProcessorUtil.getAnnotationValue( _elements, annotation, "inverse" );
switch ( variableElement.getSimpleName().toString() )
{
case "ENABLE":
return true;
case "DISABLE":
return false;
default:
return null != ProcessorUtil.findAnnotationValueNoDefaults( annotation, "inverseName" ) ||
null != ProcessorUtil.findAnnotationValueNoDefaults( annotation, "inverseMultiplicity" );
}
}
@Nonnull
private String getReferenceInverseName( @Nonnull final AnnotationMirror annotation,
@Nonnull final ExecutableElement method,
@Nonnull final Multiplicity multiplicity )
{
final String declaredName =
ProcessorUtil.getAnnotationValue( _elements, annotation, "inverseName" );
final String name;
if ( ProcessorUtil.isSentinelName( declaredName ) )
{
final String baseName = getElement().getSimpleName().toString();
return ProcessorUtil.firstCharacterToLowerCase( baseName ) + ( Multiplicity.MANY == multiplicity ? "s" : "" );
}
else
{
name = declaredName;
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@Reference target specified an invalid inverseName '" + name + "'. The " +
"inverseName must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@Reference target specified an invalid inverseName '" + name + "'. The " +
"inverseName must not be a java keyword.", method );
}
}
return name;
}
@Nonnull
private Multiplicity getReferenceInverseMultiplicity( @Nonnull final AnnotationMirror annotation )
{
final VariableElement variableElement =
ProcessorUtil.getAnnotationValue( _elements, annotation, "inverseMultiplicity" );
switch ( variableElement.getSimpleName().toString() )
{
case "MANY":
return Multiplicity.MANY;
case "ONE":
return Multiplicity.ONE;
default:
return Multiplicity.ZERO_OR_ONE;
}
}
@Nonnull
private List<? extends VariableElement> getInjectedParameters( @Nonnull final ExecutableElement constructor )
{
return constructor
.getParameters()
.stream()
.filter( f -> null == ProcessorUtil.findAnnotationByType( f, Constants.PER_INSTANCE_ANNOTATION_CLASSNAME ) )
.collect( Collectors.toList() );
}
@Nonnull
private String getReferenceName( @Nonnull final AnnotationMirror annotation, @Nonnull final ExecutableElement method )
{
final String declaredName = getAnnotationParameter( annotation, "name" );
final String name;
if ( ProcessorUtil.isSentinelName( declaredName ) )
{
final String candidate = ProcessorUtil.deriveName( method, GETTER_PATTERN, declaredName );
if ( null == candidate )
{
name = method.getSimpleName().toString();
}
else
{
name = candidate;
}
}
else
{
name = declaredName;
if ( !SourceVersion.isIdentifier( name ) )
{
throw new ArezProcessorException( "@Reference target specified an invalid name '" + name + "'. The " +
"name must be a valid java identifier.", method );
}
else if ( SourceVersion.isKeyword( name ) )
{
throw new ArezProcessorException( "@Reference target specified an invalid name '" + name + "'. The " +
"name must not be a java keyword.", method );
}
}
return name;
}
@Nonnull
private String getLinkType( @Nonnull final ExecutableElement method )
{
final VariableElement injectParameter = (VariableElement)
ProcessorUtil.getAnnotationValue( _elements,
method,
Constants.REFERENCE_ANNOTATION_CLASSNAME,
"load" ).getValue();
return injectParameter.getSimpleName().toString();
}
private void addDependency( @Nonnull final ExecutableElement method )
{
_dependencies.put( method, createMethodDependencyDescriptor( method ) );
}
private void addDependency( @Nonnull final VariableElement field )
{
_dependencies.put( field, createFieldDependencyDescriptor( field ) );
}
@Nonnull
private DependencyDescriptor createMethodDependencyDescriptor( @Nonnull final ExecutableElement method )
{
MethodChecks.mustNotHaveAnyParameters( Constants.COMPONENT_DEPENDENCY_ANNOTATION_CLASSNAME, method );
MethodChecks.mustBeSubclassCallable( getElement(), Constants.COMPONENT_DEPENDENCY_ANNOTATION_CLASSNAME, method );
MethodChecks.mustNotThrowAnyExceptions( Constants.COMPONENT_DEPENDENCY_ANNOTATION_CLASSNAME, method );
MethodChecks.mustReturnAValue( Constants.COMPONENT_DEPENDENCY_ANNOTATION_CLASSNAME, method );
final TypeMirror type = method.getReturnType();
if ( TypeKind.DECLARED != type.getKind() )
{
throw new ArezProcessorException( "@ComponentDependency target must return a non-primitive value", method );
}
final TypeElement disposeTrackable = _elements.getTypeElement( Constants.DISPOSE_TRACKABLE_CLASSNAME );
assert null != disposeTrackable;
if ( !_typeUtils.isAssignable( type, disposeTrackable.asType() ) )
{
final TypeElement typeElement = (TypeElement) _typeUtils.asElement( type );
final AnnotationMirror value =
ProcessorUtil.findAnnotationByType( typeElement, Constants.COMPONENT_ANNOTATION_CLASSNAME );
if ( null == value || !ProcessorUtil.isDisposableTrackableRequired( _elements, typeElement ) )
{
throw new ArezProcessorException( "@ComponentDependency target must return an instance compatible with " +
Constants.DISPOSE_TRACKABLE_CLASSNAME + " or a type annotated " +
"with @ArezComponent(disposeTrackable=ENABLE)", method );
}
}
final boolean cascade = isActionCascade( method );
return new DependencyDescriptor( method, cascade );
}
@Nonnull
private DependencyDescriptor createFieldDependencyDescriptor( @Nonnull final VariableElement field )
{
MethodChecks.mustBeSubclassCallable( getElement(), Constants.COMPONENT_DEPENDENCY_ANNOTATION_CLASSNAME, field );
MethodChecks.mustBeFinal( Constants.COMPONENT_DEPENDENCY_ANNOTATION_CLASSNAME, field );
final TypeMirror type = field.asType();
if ( TypeKind.DECLARED != type.getKind() )
{
throw new ArezProcessorException( "@ComponentDependency target must be a non-primitive value", field );
}
final TypeElement disposeTrackable = _elements.getTypeElement( Constants.DISPOSE_TRACKABLE_CLASSNAME );
assert null != disposeTrackable;
if ( !_typeUtils.isAssignable( type, disposeTrackable.asType() ) )
{
final TypeElement typeElement = (TypeElement) _typeUtils.asElement( type );
final AnnotationMirror value =
ProcessorUtil.findAnnotationByType( typeElement, Constants.COMPONENT_ANNOTATION_CLASSNAME );
if ( null == value || !ProcessorUtil.isDisposableTrackableRequired( _elements, typeElement ) )
{
throw new ArezProcessorException( "@ComponentDependency target must be an instance compatible with " +
Constants.DISPOSE_TRACKABLE_CLASSNAME + " or a type annotated " +
"with @ArezComponent(disposeTrackable=ENABLE)", field );
}
}
if ( !isActionCascade( field ) )
{
throw new ArezProcessorException( "@ComponentDependency target defined an action of 'SET_NULL' but the " +
"dependency is on a final field and can not be set to null.", field );
}
return new DependencyDescriptor( field );
}
private boolean isActionCascade( @Nonnull final Element method )
{
final VariableElement injectParameter = (VariableElement)
ProcessorUtil.getAnnotationValue( _elements,
method,
Constants.COMPONENT_DEPENDENCY_ANNOTATION_CLASSNAME,
"action" ).getValue();
switch ( injectParameter.getSimpleName().toString() )
{
case "CASCADE":
return true;
case "SET_NULL":
default:
return false;
}
}
private void ensureNoAbstractMethods( @Nonnull final Collection<CandidateMethod> candidateMethods )
{
candidateMethods
.stream()
.map( CandidateMethod::getMethod )
.filter( m -> m.getModifiers().contains( Modifier.ABSTRACT ) )
.forEach( m -> {
throw new ArezProcessorException( "@ArezComponent target has an abstract method not implemented by " +
"framework. The method is named " + m.getSimpleName(), getElement() );
} );
}
private void linkObserverRefs()
{
for ( final Map.Entry<String, CandidateMethod> entry : _observerRefs.entrySet() )
{
final String key = entry.getKey();
final CandidateMethod method = entry.getValue();
final ObserveDescriptor observed = _observes.get( key );
if ( null != observed )
{
observed.setRefMethod( method.getMethod(), method.getMethodType() );
}
else
{
throw new ArezProcessorException( "@ObserverRef target defined observer named '" + key + "' but no " +
"@Observe method with that name exists", method.getMethod() );
}
}
}
private void linkUnAnnotatedObservables( @Nonnull final Map<String, CandidateMethod> getters,
@Nonnull final Map<String, CandidateMethod> setters )
throws ArezProcessorException
{
for ( final ObservableDescriptor observable : _roObservables )
{
if ( !observable.hasSetter() && !observable.hasGetter() )
{
throw new ArezProcessorException( "@ObservableValueRef target unable to be associated with an " +
"Observable property", observable.getRefMethod() );
}
else if ( !observable.hasSetter() && observable.expectSetter() )
{
final CandidateMethod candidate = setters.remove( observable.getName() );
if ( null != candidate )
{
MethodChecks.mustBeOverridable( getElement(),
Constants.OBSERVABLE_ANNOTATION_CLASSNAME,
candidate.getMethod() );
observable.setSetter( candidate.getMethod(), candidate.getMethodType() );
}
else if ( observable.hasGetter() )
{
throw new ArezProcessorException( "@Observable target defined getter but no setter was defined and no " +
"setter could be automatically determined", observable.getGetter() );
}
}
else if ( !observable.hasGetter() )
{
final CandidateMethod candidate = getters.remove( observable.getName() );
if ( null != candidate )
{
MethodChecks.mustBeOverridable( getElement(),
Constants.OBSERVABLE_ANNOTATION_CLASSNAME,
candidate.getMethod() );
observable.setGetter( candidate.getMethod(), candidate.getMethodType() );
}
else
{
throw new ArezProcessorException( "@Observable target defined setter but no getter was defined and no " +
"getter could be automatically determined", observable.getSetter() );
}
}
}
}
private void linkUnAnnotatedObserves( @Nonnull final Map<String, CandidateMethod> observes,
@Nonnull final Map<String, CandidateMethod> onDepsChanges )
throws ArezProcessorException
{
for ( final ObserveDescriptor observe : _roObserves )
{
if ( !observe.hasObserve() )
{
final CandidateMethod candidate = observes.remove( observe.getName() );
if ( null != candidate )
{
observe.setObserveMethod( false,
"NORMAL",
true,
true,
true,
"AREZ",
false,
false,
candidate.getMethod(),
candidate.getMethodType() );
}
else
{
throw new ArezProcessorException( "@OnDepsChange target has no corresponding @Observe that could " +
"be automatically determined", observe.getOnDepsChange() );
}
}
else if ( !observe.hasOnDepsChange() )
{
final CandidateMethod candidate = onDepsChanges.remove( observe.getName() );
if ( null != candidate )
{
observe.setOnDepsChange( candidate.getMethod() );
}
}
}
}
private boolean analyzeMethod( @Nonnull final ExecutableElement method,
@Nonnull final ExecutableType methodType )
throws ArezProcessorException
{
verifyNoDuplicateAnnotations( method );
final AnnotationMirror action =
ProcessorUtil.findAnnotationByType( method, Constants.ACTION_ANNOTATION_CLASSNAME );
final AnnotationMirror observed =
ProcessorUtil.findAnnotationByType( method, Constants.OBSERVE_ANNOTATION_CLASSNAME );
final AnnotationMirror observable =
ProcessorUtil.findAnnotationByType( method, Constants.OBSERVABLE_ANNOTATION_CLASSNAME );
final AnnotationMirror observableValueRef =
ProcessorUtil.findAnnotationByType( method, Constants.OBSERVABLE_VALUE_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror memoize =
ProcessorUtil.findAnnotationByType( method, Constants.MEMOIZE_ANNOTATION_CLASSNAME );
final AnnotationMirror computableValueRef =
ProcessorUtil.findAnnotationByType( method, Constants.COMPUTABLE_VALUE_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror contextRef =
ProcessorUtil.findAnnotationByType( method, Constants.CONTEXT_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror componentRef =
ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror componentId =
ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_ID_ANNOTATION_CLASSNAME );
final AnnotationMirror componentIdRef =
ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_ID_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror componentTypeName =
ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror componentName =
ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror postConstruct =
ProcessorUtil.findAnnotationByType( method, Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME );
final AnnotationMirror ejbPostConstruct =
ProcessorUtil.findAnnotationByType( method, Constants.EJB_POST_CONSTRUCT_ANNOTATION_CLASSNAME );
final AnnotationMirror preDispose =
ProcessorUtil.findAnnotationByType( method, Constants.PRE_DISPOSE_ANNOTATION_CLASSNAME );
final AnnotationMirror postDispose =
ProcessorUtil.findAnnotationByType( method, Constants.POST_DISPOSE_ANNOTATION_CLASSNAME );
final AnnotationMirror onActivate =
ProcessorUtil.findAnnotationByType( method, Constants.ON_ACTIVATE_ANNOTATION_CLASSNAME );
final AnnotationMirror onDeactivate =
ProcessorUtil.findAnnotationByType( method, Constants.ON_DEACTIVATE_ANNOTATION_CLASSNAME );
final AnnotationMirror onStale =
ProcessorUtil.findAnnotationByType( method, Constants.ON_STALE_ANNOTATION_CLASSNAME );
final AnnotationMirror onDepsChange =
ProcessorUtil.findAnnotationByType( method, Constants.ON_DEPS_CHANGE_ANNOTATION_CLASSNAME );
final AnnotationMirror observerRef =
ProcessorUtil.findAnnotationByType( method, Constants.OBSERVER_REF_ANNOTATION_CLASSNAME );
final AnnotationMirror dependency =
ProcessorUtil.findAnnotationByType( method, Constants.COMPONENT_DEPENDENCY_ANNOTATION_CLASSNAME );
final AnnotationMirror reference =
ProcessorUtil.findAnnotationByType( method, Constants.REFERENCE_ANNOTATION_CLASSNAME );
final AnnotationMirror referenceId =
ProcessorUtil.findAnnotationByType( method, Constants.REFERENCE_ID_ANNOTATION_CLASSNAME );
final AnnotationMirror inverse =
ProcessorUtil.findAnnotationByType( method, Constants.INVERSE_ANNOTATION_CLASSNAME );
final AnnotationMirror cascadeDispose =
ProcessorUtil.findAnnotationByType( method, Constants.CASCADE_DISPOSE_ANNOTATION_CLASSNAME );
if ( null != observable )
{
final ObservableDescriptor descriptor = addObservable( observable, method, methodType );
if ( null != referenceId )
{
addReferenceId( referenceId, descriptor, method );
}
if ( null != inverse )
{
addInverse( inverse, descriptor, method );
}
return true;
}
else if ( null != observableValueRef )
{
addObservableValueRef( observableValueRef, method, methodType );
return true;
}
else if ( null != action )
{
addAction( action, method, methodType );
return true;
}
else if ( null != observed )
{
addObserve( observed, method, methodType );
return true;
}
else if ( null != onDepsChange )
{
addOnDepsChange( onDepsChange, method );
return true;
}
else if ( null != observerRef )
{
addObserverRef( observerRef, method, methodType );
return true;
}
else if ( null != contextRef )
{
setContextRef( method );
return true;
}
else if ( null != memoize )
{
addMemoize( memoize, method, methodType );
return true;
}
else if ( null != computableValueRef )
{
addComputableValueRef( computableValueRef, method, methodType );
return true;
}
else if ( null != cascadeDispose )
{
addCascadeDisposeMethod( method );
return true;
}
else if ( null != componentIdRef )
{
setComponentIdRef( method );
return true;
}
else if ( null != componentRef )
{
setComponentRef( method );
return true;
}
else if ( null != componentId )
{
setComponentId( method, methodType );
return true;
}
else if ( null != componentName )
{
setComponentNameRef( method );
return true;
}
else if ( null != componentTypeName )
{
setComponentTypeNameRef( method );
return true;
}
else if ( null != ejbPostConstruct )
{
throw new ArezProcessorException( "@" + Constants.EJB_POST_CONSTRUCT_ANNOTATION_CLASSNAME + " annotation " +
"not supported in components annotated with @ArezComponent, use the @" +
Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME + " annotation instead.",
method );
}
else if ( null != postConstruct )
{
setPostConstruct( method );
return true;
}
else if ( null != preDispose )
{
setPreDispose( method );
return true;
}
else if ( null != postDispose )
{
setPostDispose( method );
return true;
}
else if ( null != onActivate )
{
addOnActivate( onActivate, method );
return true;
}
else if ( null != onDeactivate )
{
addOnDeactivate( onDeactivate, method );
return true;
}
else if ( null != onStale )
{
addOnStale( onStale, method );
return true;
}
else if ( null != dependency )
{
addDependency( method );
return false;
}
else if ( null != reference )
{
addReference( reference, method, methodType );
return true;
}
else if ( null != referenceId )
{
addReferenceId( referenceId, method, methodType );
return true;
}
else if ( null != inverse )
{
addInverse( inverse, method, methodType );
return true;
}
else
{
return false;
}
}
@Nullable
private Boolean isInitializerRequired( @Nonnull final ExecutableElement element )
{
final AnnotationMirror annotation =
ProcessorUtil.findAnnotationByType( element, Constants.OBSERVABLE_ANNOTATION_CLASSNAME );
final AnnotationValue v =
null == annotation ? null : ProcessorUtil.findAnnotationValueNoDefaults( annotation, "initializer" );
final String value = null == v ? "AUTODETECT" : ( (VariableElement) v.getValue() ).getSimpleName().toString();
switch ( value )
{
case "ENABLE":
return Boolean.TRUE;
case "DISABLE":
return Boolean.FALSE;
default:
return null;
}
}
private boolean autodetectInitializer( @Nonnull final ExecutableElement element )
{
return element.getModifiers().contains( Modifier.ABSTRACT ) &&
(
(
// Getter
element.getReturnType().getKind() != TypeKind.VOID &&
null != ProcessorUtil.findAnnotationByType( element, Constants.NONNULL_ANNOTATION_CLASSNAME ) &&
null == ProcessorUtil.findAnnotationByType( element, Constants.INVERSE_ANNOTATION_CLASSNAME )
) ||
(
// Setter
1 == element.getParameters().size() &&
null != ProcessorUtil.findAnnotationByType( element.getParameters().get( 0 ),
Constants.NONNULL_ANNOTATION_CLASSNAME )
)
);
}
private void verifyNoDuplicateAnnotations( @Nonnull final ExecutableElement method )
throws ArezProcessorException
{
final String[] annotationTypes =
new String[]{ Constants.ACTION_ANNOTATION_CLASSNAME,
Constants.OBSERVE_ANNOTATION_CLASSNAME,
Constants.ON_DEPS_CHANGE_ANNOTATION_CLASSNAME,
Constants.OBSERVER_REF_ANNOTATION_CLASSNAME,
Constants.OBSERVABLE_ANNOTATION_CLASSNAME,
Constants.OBSERVABLE_VALUE_REF_ANNOTATION_CLASSNAME,
Constants.MEMOIZE_ANNOTATION_CLASSNAME,
Constants.COMPUTABLE_VALUE_REF_ANNOTATION_CLASSNAME,
Constants.COMPONENT_REF_ANNOTATION_CLASSNAME,
Constants.COMPONENT_ID_ANNOTATION_CLASSNAME,
Constants.COMPONENT_NAME_REF_ANNOTATION_CLASSNAME,
Constants.COMPONENT_TYPE_NAME_REF_ANNOTATION_CLASSNAME,
Constants.CASCADE_DISPOSE_ANNOTATION_CLASSNAME,
Constants.CONTEXT_REF_ANNOTATION_CLASSNAME,
Constants.POST_CONSTRUCT_ANNOTATION_CLASSNAME,
Constants.PRE_DISPOSE_ANNOTATION_CLASSNAME,
Constants.POST_DISPOSE_ANNOTATION_CLASSNAME,
Constants.REFERENCE_ANNOTATION_CLASSNAME,
Constants.REFERENCE_ID_ANNOTATION_CLASSNAME,
Constants.ON_ACTIVATE_ANNOTATION_CLASSNAME,
Constants.ON_DEACTIVATE_ANNOTATION_CLASSNAME,
Constants.ON_STALE_ANNOTATION_CLASSNAME,
Constants.COMPONENT_DEPENDENCY_ANNOTATION_CLASSNAME };
for ( int i = 0; i < annotationTypes.length; i++ )
{
final String type1 = annotationTypes[ i ];
final Object annotation1 = ProcessorUtil.findAnnotationByType( method, type1 );
if ( null != annotation1 )
{
for ( int j = i + 1; j < annotationTypes.length; j++ )
{
final String type2 = annotationTypes[ j ];
final boolean observableDependency =
type1.equals( Constants.OBSERVABLE_ANNOTATION_CLASSNAME ) &&
type2.equals( Constants.COMPONENT_DEPENDENCY_ANNOTATION_CLASSNAME );
final boolean observableReferenceId =
type1.equals( Constants.OBSERVABLE_ANNOTATION_CLASSNAME ) &&
type2.equals( Constants.REFERENCE_ID_ANNOTATION_CLASSNAME );
if ( !observableDependency && !observableReferenceId )
{
final Object annotation2 = ProcessorUtil.findAnnotationByType( method, type2 );
if ( null != annotation2 )
{
final String message =
"Method can not be annotated with both @" + ProcessorUtil.toSimpleName( type1 ) +
" and @" + ProcessorUtil.toSimpleName( type2 );
throw new ArezProcessorException( message, method );
}
}
}
}
}
}
private void verifyNoDuplicateAnnotations( @Nonnull final VariableElement field )
throws ArezProcessorException
{
final String[] annotationTypes =
new String[]{ Constants.COMPONENT_DEPENDENCY_ANNOTATION_CLASSNAME,
Constants.CASCADE_DISPOSE_ANNOTATION_CLASSNAME };
for ( int i = 0; i < annotationTypes.length; i++ )
{
final String type1 = annotationTypes[ i ];
final Object annotation1 = ProcessorUtil.findAnnotationByType( field, type1 );
if ( null != annotation1 )
{
for ( int j = i + 1; j < annotationTypes.length; j++ )
{
final String type2 = annotationTypes[ j ];
final Object annotation2 = ProcessorUtil.findAnnotationByType( field, type2 );
if ( null != annotation2 )
{
final String message =
"Method can not be annotated with both @" + ProcessorUtil.toSimpleName( type1 ) +
" and @" + ProcessorUtil.toSimpleName( type2 );
throw new ArezProcessorException( message, field );
}
}
}
}
}
@Nonnull
private String getPropertyAccessorName( @Nonnull final ExecutableElement method, @Nonnull final String specifiedName )
throws ArezProcessorException
{
String name = ProcessorUtil.deriveName( method, GETTER_PATTERN, specifiedName );
if ( null != name )
{
return name;
}
if ( method.getReturnType().getKind() == TypeKind.BOOLEAN )
{
name = ProcessorUtil.deriveName( method, ISSER_PATTERN, specifiedName );
if ( null != name )
{
return name;
}
}
return method.getSimpleName().toString();
}
@Nonnull
private String getNestedClassPrefix()
{
final StringBuilder name = new StringBuilder();
TypeElement t = getElement();
while ( NestingKind.TOP_LEVEL != t.getNestingKind() )
{
t = (TypeElement) t.getEnclosingElement();
name.insert( 0, t.getSimpleName() + "_" );
}
return name.toString();
}
/**
* Build the enhanced class for the component.
*/
@Nonnull
TypeSpec buildType( @Nonnull final Types typeUtils )
throws ArezProcessorException
{
final TypeSpec.Builder builder = TypeSpec.classBuilder( getArezClassName() ).
superclass( TypeName.get( getElement().asType() ) ).
addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( asDeclaredType() ) ).
addModifiers( Modifier.FINAL );
Generator.addOriginatingTypes( getElement(), builder );
Generator.addGeneratedAnnotation( this, builder );
if ( !_roMemoizes.isEmpty() )
{
builder.addAnnotation( AnnotationSpec.builder( SuppressWarnings.class ).
addMember( "value", "$S", "unchecked" ).
build() );
}
final boolean publicType =
(
getElement().getModifiers().contains( Modifier.PUBLIC ) &&
ProcessorUtil.getConstructors( getElement() ).
stream().
anyMatch( c -> c.getModifiers().contains( Modifier.PUBLIC ) )
) || (
//Ahh dagger.... due the way we actually inject components that have to create a dagger component
// extension, this class needs to be public
needsDaggerComponentExtension()
);
final boolean hasInverseReferencedOutsideClass =
_roInverses.stream().anyMatch( inverse -> {
final PackageElement targetPackageElement = ProcessorUtil.getPackageElement( inverse.getTargetType() );
final PackageElement selfPackageElement = getPackageElement( getElement() );
return !Objects.equals( targetPackageElement.getQualifiedName(), selfPackageElement.getQualifiedName() );
} );
final boolean hasReferenceWithInverseOutsidePackage =
_roReferences
.stream()
.filter( ReferenceDescriptor::hasInverse )
.anyMatch( reference -> {
final TypeElement typeElement =
(TypeElement) _typeUtils.asElement( reference.getMethod().getReturnType() );
final PackageElement targetPackageElement = ProcessorUtil.getPackageElement( typeElement );
final PackageElement selfPackageElement = getPackageElement( getElement() );
return !Objects.equals( targetPackageElement.getQualifiedName(), selfPackageElement.getQualifiedName() );
} );
if ( publicType || hasInverseReferencedOutsideClass || hasReferenceWithInverseOutsidePackage )
{
builder.addModifiers( Modifier.PUBLIC );
}
if ( null != _scopeAnnotation )
{
final DeclaredType annotationType = _scopeAnnotation.getAnnotationType();
final TypeElement typeElement = (TypeElement) annotationType.asElement();
builder.addAnnotation( ClassName.get( typeElement ) );
}
builder.addSuperinterface( Generator.DISPOSABLE_CLASSNAME );
builder.addSuperinterface( ParameterizedTypeName.get( Generator.IDENTIFIABLE_CLASSNAME, getIdType().box() ) );
if ( _observable )
{
builder.addSuperinterface( Generator.COMPONENT_OBSERVABLE_CLASSNAME );
}
if ( _verify )
{
builder.addSuperinterface( Generator.VERIFIABLE_CLASSNAME );
}
if ( _disposeTrackable )
{
builder.addSuperinterface( Generator.DISPOSE_TRACKABLE_CLASSNAME );
}
if ( needsExplicitLink() )
{
builder.addSuperinterface( Generator.LINKABLE_CLASSNAME );
}
if ( _generatesFactoryToInject )
{
builder.addType( buildFactoryClass().build() );
}
if ( needsEnhancer() )
{
final TypeSpec.Builder enhancer =
TypeSpec.interfaceBuilder( "Enhancer" ).addModifiers( Modifier.STATIC );
enhancer.addMethod( MethodSpec
.methodBuilder( "enhance" )
.addParameter( ParameterSpec.builder( ClassName.bestGuess( getArezClassName() ),
"component" ).build() )
.addModifiers( Modifier.PUBLIC, Modifier.ABSTRACT )
.build() );
builder.addType( enhancer.build() );
}
buildFields( builder );
buildConstructors( builder, typeUtils );
if ( null != _contextRef )
{
builder.addMethod( buildContextRefMethod() );
}
if ( null != _componentRef )
{
builder.addMethod( buildComponentRefMethod() );
}
if ( null != _componentIdRef )
{
builder.addMethod( buildComponentIdRefMethod() );
}
if ( !_references.isEmpty() || !_inverses.isEmpty() )
{
builder.addMethod( buildLocatorRefMethod() );
}
if ( null == _componentId )
{
builder.addMethod( buildComponentIdMethod() );
}
builder.addMethod( buildArezIdMethod() );
if ( null != _componentNameRef )
{
builder.addMethod( buildComponentNameMethod() );
}
final MethodSpec method = buildComponentTypeNameMethod();
if ( null != method )
{
builder.addMethod( method );
}
if ( _observable )
{
builder.addMethod( buildObserve() );
}
if ( hasInternalPreDispose() )
{
builder.addMethod( buildInternalPreDispose() );
}
if ( _disposeTrackable )
{
builder.addMethod( buildNativeComponentPreDispose() );
builder.addMethod( buildNotifierAccessor() );
}
builder.addMethod( buildIsDisposed() );
builder.addMethod( buildDispose() );
builder.addMethod( buildInternalDispose() );
if ( _verify )
{
builder.addMethod( buildVerify() );
}
if ( needsExplicitLink() )
{
builder.addMethod( buildLink() );
}
_roObservables.forEach( e -> e.buildMethods( builder ) );
_roObserves.forEach( e -> e.buildMethods( builder ) );
_roActions.forEach( e -> e.buildMethods( builder ) );
_roMemoizes.forEach( e -> e.buildMethods( builder ) );
_roReferences.forEach( e -> e.buildMethods( builder ) );
_roInverses.forEach( e -> e.buildMethods( builder ) );
builder.addMethod( buildHashcodeMethod() );
builder.addMethod( buildEqualsMethod() );
if ( _generateToString )
{
builder.addMethod( buildToStringMethod() );
}
return builder.build();
}
@Nonnull
private TypeSpec.Builder buildFactoryClass()
{
final TypeSpec.Builder factory = TypeSpec.classBuilder( "Factory" )
.addModifiers( Modifier.PUBLIC, Modifier.STATIC, Modifier.FINAL );
final ExecutableElement constructor = getConstructors( _element ).get( 0 );
assert null != constructor;
final boolean needsEnhancer = needsEnhancer();
if ( needsEnhancer )
{
factory.addField( FieldSpec
.builder( ClassName.bestGuess( "Enhancer" ),
Generator.FRAMEWORK_PREFIX + "enhancer",
Modifier.PRIVATE,
Modifier.FINAL )
.addAnnotation( Generator.NONNULL_CLASSNAME )
.build() );
}
final List<? extends VariableElement> injectedParameters = getInjectedParameters( constructor );
for ( final VariableElement perInstanceParameter : injectedParameters )
{
final FieldSpec.Builder field = FieldSpec
.builder( TypeName.get( perInstanceParameter.asType() ),
perInstanceParameter.getSimpleName().toString(),
Modifier.PRIVATE,
Modifier.FINAL );
ProcessorUtil.copyWhitelistedAnnotations( perInstanceParameter, field );
factory.addField( field.build() );
}
final MethodSpec.Builder ctor = MethodSpec.constructorBuilder();
ctor.addAnnotation( Generator.INJECT_CLASSNAME );
if ( needsEnhancer )
{
final String name = Generator.FRAMEWORK_PREFIX + "enhancer";
ctor.addParameter( ParameterSpec
.builder( ClassName.bestGuess( "Enhancer" ), name, Modifier.FINAL )
.addAnnotation( Generator.NONNULL_CLASSNAME )
.build() );
ctor.addStatement( "this.$N = $T.requireNonNull( $N )", name, Objects.class, name );
}
for ( final VariableElement perInstanceParameter : injectedParameters )
{
final String name = perInstanceParameter.getSimpleName().toString();
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( perInstanceParameter.asType() ), name, Modifier.FINAL );
ProcessorUtil.copyWhitelistedAnnotations( perInstanceParameter, param );
ctor.addParameter( param.build() );
final boolean isNonNull =
null != findAnnotationByType( perInstanceParameter, Constants.NONNULL_ANNOTATION_CLASSNAME );
if ( isNonNull )
{
ctor.addStatement( "this.$N = $T.requireNonNull( $N )", name, Objects.class, name );
}
else
{
ctor.addStatement( "this.$N = $N", name, name );
}
}
factory.addMethod( ctor.build() );
{
final MethodSpec.Builder creator = MethodSpec.methodBuilder( "create" );
creator.addAnnotation( Generator.NONNULL_CLASSNAME );
creator.addModifiers( Modifier.PUBLIC, Modifier.FINAL );
creator.returns( getEnhancedClassName() );
final StringBuilder sb = new StringBuilder();
final ArrayList<Object> params = new ArrayList<>();
sb.append( "return new $T(" );
params.add( getEnhancedClassName() );
boolean firstParam = true;
for ( final VariableElement parameter : constructor.getParameters() )
{
final boolean perInstance =
null != findAnnotationByType( parameter, Constants.PER_INSTANCE_ANNOTATION_CLASSNAME );
final String name = parameter.getSimpleName().toString();
if ( perInstance )
{
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( parameter.asType() ), name, Modifier.FINAL );
ProcessorUtil.copyWhitelistedAnnotations( parameter, param );
creator.addParameter( param.build() );
}
if ( firstParam )
{
sb.append( " " );
}
else
{
sb.append( ", " );
}
firstParam = false;
if ( perInstance && null != findAnnotationByType( parameter, Constants.NONNULL_ANNOTATION_CLASSNAME ) )
{
sb.append( "$T.requireNonNull( $N )" );
params.add( Objects.class );
}
else
{
sb.append( "$N" );
}
params.add( name );
}
if ( needsEnhancer )
{
assert !firstParam;
sb.append( ", " );
firstParam = false;
sb.append( "$N" );
params.add( Generator.FRAMEWORK_PREFIX + "enhancer" );
}
if ( !firstParam )
{
sb.append( " " );
}
sb.append( ")" );
creator.addStatement( sb.toString(), params.toArray() );
factory.addMethod( creator.build() );
}
return factory;
}
private boolean needsExplicitLink()
{
return _roReferences.stream().anyMatch( r -> r.getLinkType().equals( "EXPLICIT" ) );
}
@Nonnull
private MethodSpec buildToStringMethod()
throws ArezProcessorException
{
assert _generateToString;
final MethodSpec.Builder method =
MethodSpec.methodBuilder( "toString" ).
addModifiers( Modifier.PUBLIC, Modifier.FINAL ).
addAnnotation( Override.class ).
returns( TypeName.get( String.class ) );
final CodeBlock.Builder codeBlock = CodeBlock.builder();
codeBlock.beginControlFlow( "if ( $T.areNamesEnabled() )", Generator.AREZ_CLASSNAME );
codeBlock.addStatement( "return $S + this.$N.getName() + $S",
"ArezComponent[",
Generator.KERNEL_FIELD_NAME,
"]" );
codeBlock.nextControlFlow( "else" );
codeBlock.addStatement( "return super.toString()" );
codeBlock.endControlFlow();
method.addCode( codeBlock.build() );
return method.build();
}
@Nonnull
private MethodSpec buildEqualsMethod()
throws ArezProcessorException
{
final String idMethod = getIdMethodName();
final MethodSpec.Builder method =
MethodSpec.methodBuilder( "equals" ).
addModifiers( Modifier.PUBLIC, Modifier.FINAL ).
addAnnotation( Override.class ).
addParameter( Object.class, "o", Modifier.FINAL ).
returns( TypeName.BOOLEAN );
final ClassName generatedClass = ClassName.get( getPackageName(), getArezClassName() );
final CodeBlock.Builder codeBlock = CodeBlock.builder();
codeBlock.beginControlFlow( "if ( o instanceof $T )", generatedClass );
codeBlock.addStatement( "final $T that = ($T) o", generatedClass, generatedClass );
/*
* If componentId is null then it is using synthetic id which is monotonically increasing and
* thus if the id matches then the instance match. As a result no need to check isDisposed as
* they will always match. Whereas if componentId is not null then the application controls the
* id and there maybe be multiple entities with the same id where one has been disposed. They
* should not match.
*/
final String prefix = null != _componentId ? "isDisposed() == that.isDisposed() && " : "";
final TypeKind kind = null != _componentId ? _componentId.getReturnType().getKind() : Generator.DEFAULT_ID_KIND;
if ( kind == TypeKind.DECLARED || kind == TypeKind.TYPEVAR )
{
codeBlock.addStatement( "return " + prefix + "null != $N() && $N().equals( that.$N() )",
idMethod,
idMethod,
idMethod );
}
else
{
codeBlock.addStatement( "return " + prefix + "$N() == that.$N()",
idMethod,
idMethod );
}
codeBlock.nextControlFlow( "else" );
codeBlock.addStatement( "return false" );
codeBlock.endControlFlow();
if ( _requireEquals )
{
method.addCode( codeBlock.build() );
}
else
{
final CodeBlock.Builder guardBlock = CodeBlock.builder();
guardBlock.beginControlFlow( "if ( $T.areNativeComponentsEnabled() )", Generator.AREZ_CLASSNAME );
guardBlock.add( codeBlock.build() );
guardBlock.nextControlFlow( "else" );
guardBlock.addStatement( "return super.equals( o )" );
guardBlock.endControlFlow();
method.addCode( guardBlock.build() );
}
return method.build();
}
@Nonnull
private MethodSpec buildHashcodeMethod()
throws ArezProcessorException
{
final String idMethod = getIdMethodName();
final MethodSpec.Builder method =
MethodSpec.methodBuilder( "hashCode" ).
addModifiers( Modifier.PUBLIC, Modifier.FINAL ).
addAnnotation( Override.class ).
returns( TypeName.INT );
final TypeKind kind = null != _componentId ? _componentId.getReturnType().getKind() : Generator.DEFAULT_ID_KIND;
if ( _requireEquals )
{
if ( kind == TypeKind.DECLARED || kind == TypeKind.TYPEVAR )
{
method.addStatement( "return null != $N() ? $N().hashCode() : $T.identityHashCode( this )",
idMethod,
idMethod,
System.class );
}
else if ( kind == TypeKind.BYTE )
{
method.addStatement( "return $T.hashCode( $N() )", Byte.class, idMethod );
}
else if ( kind == TypeKind.CHAR )
{
method.addStatement( "return $T.hashCode( $N() )", Character.class, idMethod );
}
else if ( kind == TypeKind.SHORT )
{
method.addStatement( "return $T.hashCode( $N() )", Short.class, idMethod );
}
else if ( kind == TypeKind.INT )
{
method.addStatement( "return $T.hashCode( $N() )", Integer.class, idMethod );
}
else if ( kind == TypeKind.LONG )
{
method.addStatement( "return $T.hashCode( $N() )", Long.class, idMethod );
}
else if ( kind == TypeKind.FLOAT )
{
method.addStatement( "return $T.hashCode( $N() )", Float.class, idMethod );
}
else if ( kind == TypeKind.DOUBLE )
{
method.addStatement( "return $T.hashCode( $N() )", Double.class, idMethod );
}
else
{
// So very unlikely but will cover it for completeness
assert kind == TypeKind.BOOLEAN;
method.addStatement( "return $T.hashCode( $N() )", Boolean.class, idMethod );
}
}
else
{
final CodeBlock.Builder guardBlock = CodeBlock.builder();
guardBlock.beginControlFlow( "if ( $T.areNativeComponentsEnabled() )", Generator.AREZ_CLASSNAME );
if ( kind == TypeKind.DECLARED || kind == TypeKind.TYPEVAR )
{
guardBlock.addStatement( "return null != $N() ? $N().hashCode() : $T.identityHashCode( this )",
idMethod,
idMethod,
System.class );
}
else if ( kind == TypeKind.BYTE )
{
guardBlock.addStatement( "return $T.hashCode( $N() )", Byte.class, idMethod );
}
else if ( kind == TypeKind.CHAR )
{
guardBlock.addStatement( "return $T.hashCode( $N() )", Character.class, idMethod );
}
else if ( kind == TypeKind.SHORT )
{
guardBlock.addStatement( "return $T.hashCode( $N() )", Short.class, idMethod );
}
else if ( kind == TypeKind.INT )
{
guardBlock.addStatement( "return $T.hashCode( $N() )", Integer.class, idMethod );
}
else if ( kind == TypeKind.LONG )
{
guardBlock.addStatement( "return $T.hashCode( $N() )", Long.class, idMethod );
}
else if ( kind == TypeKind.FLOAT )
{
guardBlock.addStatement( "return $T.hashCode( $N() )", Float.class, idMethod );
}
else if ( kind == TypeKind.DOUBLE )
{
guardBlock.addStatement( "return $T.hashCode( $N() )", Double.class, idMethod );
}
else
{
// So very unlikely but will cover it for completeness
assert kind == TypeKind.BOOLEAN;
guardBlock.addStatement( "return $T.hashCode( $N() )", Boolean.class, idMethod );
}
guardBlock.nextControlFlow( "else" );
guardBlock.addStatement( "return super.hashCode()" );
guardBlock.endControlFlow();
method.addCode( guardBlock.build() );
}
return method.build();
}
@Nonnull
private MethodSpec buildContextRefMethod()
throws ArezProcessorException
{
assert null != _contextRef;
final String methodName = _contextRef.getSimpleName().toString();
final MethodSpec.Builder method = MethodSpec.methodBuilder( methodName ).
addModifiers( Modifier.FINAL ).
addAnnotation( Override.class ).
returns( Generator.AREZ_CONTEXT_CLASSNAME );
ProcessorUtil.copyWhitelistedAnnotations( _contextRef, method );
ProcessorUtil.copyAccessModifiers( _contextRef, method );
Generator.generateNotInitializedInvariant( this, method, methodName );
method.addStatement( "return this.$N.getContext()", Generator.KERNEL_FIELD_NAME );
return method.build();
}
@Nonnull
private MethodSpec buildLocatorRefMethod()
throws ArezProcessorException
{
final String methodName = Generator.LOCATOR_METHOD_NAME;
final MethodSpec.Builder method = MethodSpec.methodBuilder( methodName ).
addModifiers( Modifier.FINAL ).
returns( Generator.LOCATOR_CLASSNAME );
Generator.generateNotInitializedInvariant( this, method, methodName );
method.addStatement( "return this.$N.getContext().locator()", Generator.KERNEL_FIELD_NAME );
return method.build();
}
@Nonnull
private MethodSpec buildComponentRefMethod()
throws ArezProcessorException
{
assert null != _componentRef;
final String methodName = _componentRef.getSimpleName().toString();
final MethodSpec.Builder method = MethodSpec.methodBuilder( methodName ).
addModifiers( Modifier.FINAL ).
returns( Generator.COMPONENT_CLASSNAME );
Generator.generateNotInitializedInvariant( this, method, methodName );
Generator.generateNotConstructedInvariant( method, methodName );
Generator.generateNotCompleteInvariant( method, methodName );
Generator.generateNotDisposedInvariant( method, methodName );
final CodeBlock.Builder block = CodeBlock.builder();
block.beginControlFlow( "if ( $T.shouldCheckInvariants() )", Generator.AREZ_CLASSNAME );
block.addStatement( "$T.invariant( () -> $T.areNativeComponentsEnabled(), () -> \"Invoked @ComponentRef " +
"method '$N' but Arez.areNativeComponentsEnabled() returned false.\" )",
Generator.GUARDS_CLASSNAME,
Generator.AREZ_CLASSNAME,
methodName );
block.endControlFlow();
method.addCode( block.build() );
method.addStatement( "return this.$N.getComponent()", Generator.KERNEL_FIELD_NAME );
ProcessorUtil.copyWhitelistedAnnotations( _componentRef, method );
ProcessorUtil.copyAccessModifiers( _componentRef, method );
return method.build();
}
@Nonnull
private MethodSpec buildComponentIdRefMethod()
throws ArezProcessorException
{
assert null != _componentIdRef;
final String methodName = _componentIdRef.getSimpleName().toString();
final MethodSpec.Builder method = MethodSpec.methodBuilder( methodName ).
addAnnotation( Override.class ).
addModifiers( Modifier.FINAL ).
returns( TypeName.get( _componentIdRef.getReturnType() ) );
method.addStatement( "return this.$N()", getIdMethodName() );
ProcessorUtil.copyWhitelistedAnnotations( _componentIdRef, method );
ProcessorUtil.copyAccessModifiers( _componentIdRef, method );
return method.build();
}
@Nonnull
private MethodSpec buildArezIdMethod()
throws ArezProcessorException
{
return MethodSpec.methodBuilder( "getArezId" ).
addAnnotation( Override.class ).
addAnnotation( Generator.NONNULL_CLASSNAME ).
addModifiers( Modifier.PUBLIC ).
addModifiers( Modifier.FINAL ).
returns( getIdType().box() ).
addStatement( "return $N()", getIdMethodName() ).build();
}
@Nonnull
private MethodSpec buildComponentIdMethod()
throws ArezProcessorException
{
assert null == _componentId;
final MethodSpec.Builder method = MethodSpec.methodBuilder( Generator.ID_FIELD_NAME ).
addModifiers( Modifier.FINAL ).
returns( Generator.DEFAULT_ID_TYPE );
return method.addStatement( "return this.$N.getId()", Generator.KERNEL_FIELD_NAME ).build();
}
/**
* Generate the getter for component name.
*/
@Nonnull
private MethodSpec buildComponentNameMethod()
throws ArezProcessorException
{
assert null != _componentNameRef;
final String methodName = _componentNameRef.getSimpleName().toString();
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( methodName ).addModifiers( Modifier.FINAL ).returns( TypeName.get( String.class ) );
ProcessorUtil.copyWhitelistedAnnotations( _componentNameRef, builder );
ProcessorUtil.copyAccessModifiers( _componentNameRef, builder );
Generator.generateNotInitializedInvariant( this, builder, methodName );
builder.addStatement( "return this.$N.getName()", Generator.KERNEL_FIELD_NAME );
return builder.build();
}
@Nullable
private MethodSpec buildComponentTypeNameMethod()
throws ArezProcessorException
{
if ( null == _componentTypeNameRef )
{
return null;
}
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( _componentTypeNameRef.getSimpleName().toString() );
ProcessorUtil.copyAccessModifiers( _componentTypeNameRef, builder );
builder.addModifiers( Modifier.FINAL );
builder.addAnnotation( Generator.NONNULL_CLASSNAME );
builder.returns( TypeName.get( String.class ) );
builder.addStatement( "return $S", _type );
return builder.build();
}
@Nonnull
private MethodSpec buildVerify()
{
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( "verify" ).
addModifiers( Modifier.PUBLIC ).
addAnnotation( Override.class );
Generator.generateNotDisposedInvariant( builder, "verify" );
if ( !_roReferences.isEmpty() || !_roInverses.isEmpty() )
{
final CodeBlock.Builder block = CodeBlock.builder();
block.beginControlFlow( "if ( $T.shouldCheckApiInvariants() && $T.isVerifyEnabled() )",
Generator.AREZ_CLASSNAME,
Generator.AREZ_CLASSNAME );
block.addStatement( "$T.apiInvariant( () -> this == $N().findById( $T.class, $N() ), () -> \"Attempted to " +
"lookup self in Locator with type $T and id '\" + $N() + \"' but unable to locate " +
"self. Actual value: \" + $N().findById( $T.class, $N() ) )",
Generator.GUARDS_CLASSNAME,
Generator.LOCATOR_METHOD_NAME,
getElement(),
getIdMethodName(),
getElement(),
getIdMethodName(),
Generator.LOCATOR_METHOD_NAME,
getElement(),
getIdMethodName() );
for ( final ReferenceDescriptor reference : _roReferences )
{
reference.buildVerify( block );
}
for ( final InverseDescriptor inverse : _roInverses )
{
inverse.buildVerify( block );
}
block.endControlFlow();
builder.addCode( block.build() );
}
return builder.build();
}
@Nonnull
private MethodSpec buildLink()
{
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( "link" ).
addModifiers( Modifier.PUBLIC ).
addAnnotation( Override.class );
Generator.generateNotDisposedInvariant( builder, "link" );
final List<ReferenceDescriptor> explicitReferences =
_roReferences.stream().filter( r -> r.getLinkType().equals( "EXPLICIT" ) ).collect( Collectors.toList() );
for ( final ReferenceDescriptor reference : explicitReferences )
{
builder.addStatement( "this.$N()", reference.getLinkMethodName() );
}
return builder.build();
}
/**
* Generate the dispose method.
*/
@Nonnull
private MethodSpec buildDispose()
throws ArezProcessorException
{
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( "dispose" ).
addModifiers( Modifier.PUBLIC ).
addAnnotation( Override.class );
builder.addStatement( "this.$N.dispose()", Generator.KERNEL_FIELD_NAME );
return builder.build();
}
@Nonnull
private MethodSpec buildInternalDispose()
throws ArezProcessorException
{
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( Generator.INTERNAL_DISPOSE_METHOD_NAME ).
addModifiers( Modifier.PRIVATE );
_roObserves.forEach( observe -> observe.buildDisposer( builder ) );
_roMemoizes.forEach( memoize -> memoize.buildDisposer( builder ) );
_roObservables.forEach( observable -> observable.buildDisposer( builder ) );
return builder.build();
}
private boolean hasInternalPreDispose()
{
return !_roReferences.isEmpty() ||
!_roInverses.isEmpty() ||
!_roCascadeDisposes.isEmpty() ||
!_roDependencies.isEmpty();
}
/**
* Generate the isDisposed method.
*/
@Nonnull
private MethodSpec buildIsDisposed()
throws ArezProcessorException
{
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( "isDisposed" ).
addModifiers( Modifier.PUBLIC ).
addAnnotation( Override.class ).
returns( TypeName.BOOLEAN );
builder.addStatement( "return this.$N.isDisposed()", Generator.KERNEL_FIELD_NAME );
return builder.build();
}
/**
* Generate the observe method.
*/
@Nonnull
private MethodSpec buildObserve()
throws ArezProcessorException
{
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( "observe" ).
addModifiers( Modifier.PUBLIC ).
addAnnotation( Override.class ).
returns( TypeName.BOOLEAN );
builder.addStatement( "return this.$N.observe()", Generator.KERNEL_FIELD_NAME );
return builder.build();
}
/**
* Generate the preDispose method only used when native components are enabled.
*/
@Nonnull
private MethodSpec buildNativeComponentPreDispose()
throws ArezProcessorException
{
assert _disposeTrackable;
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( Generator.INTERNAL_NATIVE_COMPONENT_PRE_DISPOSE_METHOD_NAME ).
addModifiers( Modifier.PRIVATE );
if ( hasInternalPreDispose() )
{
builder.addStatement( "this.$N()", Generator.INTERNAL_PRE_DISPOSE_METHOD_NAME );
}
else if ( null != _preDispose )
{
builder.addStatement( "super.$N()", _preDispose.getSimpleName() );
}
builder.addStatement( "this.$N.getDisposeNotifier().dispose()", Generator.KERNEL_FIELD_NAME );
return builder.build();
}
/**
* Generate the preDispose method.
*/
@Nonnull
private MethodSpec buildInternalPreDispose()
throws ArezProcessorException
{
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( Generator.INTERNAL_PRE_DISPOSE_METHOD_NAME ).
addModifiers( Modifier.PRIVATE );
if ( null != _preDispose )
{
builder.addStatement( "super.$N()", _preDispose.getSimpleName() );
}
_roCascadeDisposes.forEach( r -> r.buildDisposer( builder ) );
_roReferences.forEach( r -> r.buildDisposer( builder ) );
_roInverses.forEach( r -> Generator.buildInverseDisposer( r, builder ) );
if ( _disposeTrackable )
{
for ( final DependencyDescriptor dependency : _roDependencies )
{
final Element element = dependency.getElement();
final boolean isNonnull =
null != ProcessorUtil.findAnnotationByType( element, Constants.NONNULL_ANNOTATION_CLASSNAME );
if ( dependency.isMethodDependency() )
{
final ExecutableElement method = dependency.getMethod();
final String methodName = method.getSimpleName().toString();
if ( isNonnull )
{
builder.addStatement( "$T.asDisposeTrackable( $N() ).getNotifier().removeOnDisposeListener( this )",
Generator.DISPOSE_TRACKABLE_CLASSNAME,
methodName );
}
else
{
final String varName = Generator.VARIABLE_PREFIX + methodName + "_dependency";
final boolean abstractObservables = method.getModifiers().contains( Modifier.ABSTRACT );
if ( abstractObservables )
{
builder.addStatement( "final $T $N = this.$N",
method.getReturnType(),
varName,
dependency.getObservable().getDataFieldName() );
}
else
{
builder.addStatement( "final $T $N = super.$N()", method.getReturnType(), varName, methodName );
}
final CodeBlock.Builder listenerBlock = CodeBlock.builder();
listenerBlock.beginControlFlow( "if ( null != $N )", varName );
listenerBlock.addStatement( "$T.asDisposeTrackable( $N ).getNotifier().removeOnDisposeListener( this )",
Generator.DISPOSE_TRACKABLE_CLASSNAME,
varName );
listenerBlock.endControlFlow();
builder.addCode( listenerBlock.build() );
}
}
else
{
final VariableElement field = dependency.getField();
final String fieldName = field.getSimpleName().toString();
if ( isNonnull )
{
builder.addStatement( "$T.asDisposeTrackable( this.$N ).getNotifier().removeOnDisposeListener( this )",
Generator.DISPOSE_TRACKABLE_CLASSNAME,
fieldName );
}
else
{
final CodeBlock.Builder listenerBlock = CodeBlock.builder();
listenerBlock.beginControlFlow( "if ( null != this.$N )", fieldName );
listenerBlock.addStatement( "$T.asDisposeTrackable( this.$N ).getNotifier().removeOnDisposeListener( this )",
Generator.DISPOSE_TRACKABLE_CLASSNAME,
fieldName );
listenerBlock.endControlFlow();
builder.addCode( listenerBlock.build() );
}
}
}
}
return builder.build();
}
/**
* Generate the observe method.
*/
@Nonnull
private MethodSpec buildNotifierAccessor()
throws ArezProcessorException
{
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( "getNotifier" ).
addModifiers( Modifier.PUBLIC ).
addAnnotation( Override.class ).
addAnnotation( Generator.NONNULL_CLASSNAME ).
returns( Generator.DISPOSE_NOTIFIER_CLASSNAME );
builder.addStatement( "return this.$N.getDisposeNotifier()", Generator.KERNEL_FIELD_NAME );
return builder.build();
}
/**
* Build the fields required to make class Observable. This involves;
* <ul>
* <li>the context field if there is any @Action methods.</li>
* <li>the observable object for every @Observable.</li>
* <li>the ComputableValue object for every @Memoize method.</li>
* </ul>
*/
private void buildFields( @Nonnull final TypeSpec.Builder builder )
{
final FieldSpec.Builder idField =
FieldSpec.builder( Generator.KERNEL_CLASSNAME,
Generator.KERNEL_FIELD_NAME,
Modifier.FINAL,
Modifier.PRIVATE );
builder.addField( idField.build() );
// If we don't have a method for object id but we need one then synthesize it
if ( null == _componentId )
{
final FieldSpec.Builder nextIdField =
FieldSpec.builder( Generator.DEFAULT_ID_TYPE,
Generator.NEXT_ID_FIELD_NAME,
Modifier.VOLATILE,
Modifier.STATIC,
Modifier.PRIVATE );
builder.addField( nextIdField.build() );
}
_roObservables.forEach( observable -> observable.buildFields( builder ) );
_roMemoizes.forEach( memoize -> memoize.buildFields( builder ) );
_roObserves.forEach( observe -> observe.buildFields( builder ) );
_roReferences.forEach( r -> r.buildFields( builder ) );
}
/**
* Build all constructors as they appear on the ArezComponent class.
* Arez Observable fields are populated as required and parameters are passed up to superclass.
*/
private void buildConstructors( @Nonnull final TypeSpec.Builder builder,
@Nonnull final Types typeUtils )
{
final boolean requiresDeprecatedSuppress = hasDeprecatedElements();
for ( final ExecutableElement constructor : ProcessorUtil.getConstructors( getElement() ) )
{
final ExecutableType methodType =
(ExecutableType) typeUtils.asMemberOf( (DeclaredType) _element.asType(), constructor );
builder.addMethod( buildConstructor( constructor, methodType, requiresDeprecatedSuppress ) );
}
}
/**
* Build a constructor based on the supplied constructor
*/
@Nonnull
private MethodSpec buildConstructor( @Nonnull final ExecutableElement constructor,
@Nonnull final ExecutableType constructorType,
final boolean requiresDeprecatedSuppress )
{
final MethodSpec.Builder builder = MethodSpec.constructorBuilder();
if ( _generatesFactoryToInject )
{
// The constructor is private as the factory is responsible for creating component.
builder.addModifiers( Modifier.PRIVATE );
}
else if ( constructor.getModifiers().contains( Modifier.PUBLIC ) &&
getElement().getModifiers().contains( Modifier.PUBLIC ) )
{
/*
* The constructor MUST be public if annotated class is public as that implies that we expect
* that code outside the package may construct the component.
*/
builder.addModifiers( Modifier.PUBLIC );
}
ProcessorUtil.copyExceptions( constructorType, builder );
ProcessorUtil.copyTypeParameters( constructorType, builder );
if ( requiresDeprecatedSuppress )
{
builder.addAnnotation( AnnotationSpec.builder( SuppressWarnings.class )
.addMember( "value", "$S", "deprecation" )
.build() );
}
final boolean needsEnhancer = needsEnhancer();
if ( InjectMode.NONE != _injectMode && !_generatesFactoryToInject )
{
builder.addAnnotation( Generator.INJECT_CLASSNAME );
}
final List<ObservableDescriptor> initializers = getInitializers();
final StringBuilder superCall = new StringBuilder();
superCall.append( "super(" );
final ArrayList<String> parameterNames = new ArrayList<>();
boolean firstParam = true;
for ( final VariableElement element : constructor.getParameters() )
{
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL );
ProcessorUtil.copyWhitelistedAnnotations( element, param );
builder.addParameter( param.build() );
parameterNames.add( element.getSimpleName().toString() );
if ( !firstParam )
{
superCall.append( "," );
}
firstParam = false;
superCall.append( "$N" );
}
superCall.append( ")" );
builder.addStatement( superCall.toString(), parameterNames.toArray() );
if ( needsEnhancer )
{
builder.addParameter( ParameterSpec.builder( ClassName.bestGuess( "Enhancer" ),
Generator.ENHANCER_PARAM_NAME,
Modifier.FINAL )
.addAnnotation( Generator.NONNULL_CLASSNAME ).build() );
}
if ( !_references.isEmpty() )
{
final CodeBlock.Builder block = CodeBlock.builder();
block.beginControlFlow( "if ( $T.shouldCheckApiInvariants() )", Generator.AREZ_CLASSNAME );
block.addStatement( "$T.apiInvariant( () -> $T.areReferencesEnabled(), () -> \"Attempted to create instance " +
"of component of type '$N' that contains references but Arez.areReferencesEnabled() " +
"returns false. References need to be enabled to use this component\" )",
Generator.GUARDS_CLASSNAME,
Generator.AREZ_CLASSNAME,
getType() );
block.endControlFlow();
builder.addCode( block.build() );
}
buildComponentKernel( builder );
for ( final ObservableDescriptor observable : initializers )
{
final String candidateName = observable.getName();
final String name = isNameCollision( constructor, Collections.emptyList(), candidateName ) ?
Generator.INITIALIZER_PREFIX + candidateName :
candidateName;
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( observable.getGetterType().getReturnType() ),
name,
Modifier.FINAL );
ProcessorUtil.copyWhitelistedAnnotations( observable.getGetter(), param );
builder.addParameter( param.build() );
final boolean isPrimitive = TypeName.get( observable.getGetterType().getReturnType() ).isPrimitive();
if ( isPrimitive )
{
builder.addStatement( "this.$N = $N", observable.getDataFieldName(), name );
}
else if ( observable.isGetterNonnull() )
{
builder.addStatement( "this.$N = $T.requireNonNull( $N )",
observable.getDataFieldName(),
Objects.class,
name );
}
else
{
builder.addStatement( "this.$N = $N", observable.getDataFieldName(), name );
}
}
_roObservables.forEach( observable -> observable.buildInitializer( builder ) );
_roMemoizes.forEach( memoize -> memoize.buildInitializer( builder ) );
_roObserves.forEach( observe -> observe.buildInitializer( builder ) );
_roInverses.forEach( e -> e.buildInitializer( builder ) );
_roDependencies.forEach( e -> e.buildInitializer( builder ) );
builder.addStatement( "this.$N.componentConstructed()", Generator.KERNEL_FIELD_NAME );
final List<ReferenceDescriptor> eagerReferences =
_roReferences.stream().filter( r -> r.getLinkType().equals( "EAGER" ) ).collect( Collectors.toList() );
for ( final ReferenceDescriptor reference : eagerReferences )
{
builder.addStatement( "this.$N()", reference.getLinkMethodName() );
}
if ( needsEnhancer )
{
builder.addStatement( "$N.enhance( this )", Generator.ENHANCER_PARAM_NAME );
}
final ExecutableElement postConstruct = getPostConstruct();
if ( null != postConstruct )
{
builder.addStatement( "super.$N()", postConstruct.getSimpleName().toString() );
}
if ( !_deferSchedule && requiresSchedule() )
{
builder.addStatement( "this.$N.componentComplete()", Generator.KERNEL_FIELD_NAME );
}
else
{
builder.addStatement( "this.$N.componentReady()", Generator.KERNEL_FIELD_NAME );
}
return builder.build();
}
private void buildComponentKernel( @Nonnull final MethodSpec.Builder builder )
{
buildContextVar( builder );
buildSyntheticIdVarIfRequired( builder );
buildNameVar( builder );
buildNativeComponentVar( builder );
final StringBuilder sb = new StringBuilder();
final ArrayList<Object> params = new ArrayList<>();
sb.append( "this.$N = new $T( $T.areZonesEnabled() ? $N : null, $T.areNamesEnabled() ? $N : null, " );
params.add( Generator.KERNEL_FIELD_NAME );
params.add( Generator.KERNEL_CLASSNAME );
params.add( Generator.AREZ_CLASSNAME );
params.add( Generator.CONTEXT_VAR_NAME );
params.add( Generator.AREZ_CLASSNAME );
params.add( Generator.NAME_VAR_NAME );
if ( null == _componentId )
{
sb.append( "$N, " );
params.add( Generator.ID_VAR_NAME );
}
else
{
sb.append( "0, " );
}
sb.append( "$T.areNativeComponentsEnabled() ? $N : null, " );
params.add( Generator.AREZ_CLASSNAME );
params.add( Generator.COMPONENT_VAR_NAME );
if ( hasInternalPreDispose() )
{
sb.append( "$T.areNativeComponentsEnabled() ? null : this::$N, " );
params.add( Generator.AREZ_CLASSNAME );
params.add( Generator.INTERNAL_PRE_DISPOSE_METHOD_NAME );
}
else if ( null != _preDispose )
{
sb.append( "$T.areNativeComponentsEnabled() ? null : () -> super.$N(), " );
params.add( Generator.AREZ_CLASSNAME );
params.add( _preDispose.getSimpleName() );
}
else
{
sb.append( "null, " );
}
sb.append( "$T.areNativeComponentsEnabled() ? null : this::$N, " );
params.add( Generator.AREZ_CLASSNAME );
params.add( Generator.INTERNAL_DISPOSE_METHOD_NAME );
if ( null != _postDispose )
{
sb.append( "$T.areNativeComponentsEnabled() ? null : () -> super.$N(), " );
params.add( Generator.AREZ_CLASSNAME );
params.add( _postDispose.getSimpleName() );
}
else
{
sb.append( "null, " );
}
sb.append( _disposeTrackable );
sb.append( ", " );
sb.append( _observable );
sb.append( ", " );
sb.append( _disposeOnDeactivate );
sb.append( " )" );
builder.addStatement( sb.toString(), params.toArray() );
}
private void buildContextVar( @Nonnull final MethodSpec.Builder builder )
{
builder.addStatement( "final $T $N = $T.context()",
Generator.AREZ_CONTEXT_CLASSNAME,
Generator.CONTEXT_VAR_NAME,
Generator.AREZ_CLASSNAME );
}
private void buildNameVar( @Nonnull final MethodSpec.Builder builder )
{
// This is the same logic used to synthesize name in the getName() method
// Duplication is okay as it will be optimized out in production builds.
if ( _nameIncludesId )
{
builder.addStatement( "final String $N = $T.areNamesEnabled() ? $S + $N : null",
Generator.NAME_VAR_NAME,
Generator.AREZ_CLASSNAME,
_type.isEmpty() ? "" : _type + ".",
Generator.ID_VAR_NAME );
}
else
{
builder.addStatement( "final String $N = $T.areNamesEnabled() ? $S : null",
Generator.NAME_VAR_NAME,
Generator.AREZ_CLASSNAME,
_type );
}
}
private void buildSyntheticIdVarIfRequired( @Nonnull final MethodSpec.Builder builder )
{
if ( null == _componentId )
{
if ( _idRequired )
{
builder.addStatement( "final int $N = ++$N", Generator.ID_VAR_NAME, Generator.NEXT_ID_FIELD_NAME );
}
else if ( _nameIncludesId )
{
builder.addStatement( "final int $N = ( $T.areNamesEnabled() || $T.areRegistriesEnabled() || " +
"$T.areNativeComponentsEnabled() ) ? ++$N : 0",
Generator.ID_VAR_NAME,
Generator.AREZ_CLASSNAME,
Generator.AREZ_CLASSNAME,
Generator.AREZ_CLASSNAME,
Generator.NEXT_ID_FIELD_NAME );
}
else
{
builder.addStatement( "final int $N = ( $T.areRegistriesEnabled() || " +
"$T.areNativeComponentsEnabled() ) ? ++$N : 0",
Generator.ID_VAR_NAME,
Generator.AREZ_CLASSNAME,
Generator.AREZ_CLASSNAME,
Generator.NEXT_ID_FIELD_NAME );
}
}
else
{
builder.addStatement( "final Object $N = $N()", Generator.ID_VAR_NAME, _componentId.getSimpleName() );
}
}
private void buildNativeComponentVar( final MethodSpec.Builder builder )
{
final StringBuilder sb = new StringBuilder();
final ArrayList<Object> params = new ArrayList<>();
sb.append( "final $T $N = $T.areNativeComponentsEnabled() ? $N.component( $S, $N, $N" );
params.add( Generator.COMPONENT_CLASSNAME );
params.add( Generator.COMPONENT_VAR_NAME );
params.add( Generator.AREZ_CLASSNAME );
params.add( Generator.CONTEXT_VAR_NAME );
params.add( _type );
params.add( Generator.ID_VAR_NAME );
params.add( Generator.NAME_VAR_NAME );
if ( _disposeTrackable || null != _preDispose || null != _postDispose )
{
sb.append( ", " );
if ( _disposeTrackable )
{
sb.append( "() -> $N()" );
params.add( Generator.INTERNAL_NATIVE_COMPONENT_PRE_DISPOSE_METHOD_NAME );
}
else if ( null != _preDispose )
{
sb.append( "() -> super.$N()" );
params.add( _preDispose.getSimpleName().toString() );
}
if ( null != _postDispose )
{
sb.append( ", () -> super.$N()" );
params.add( _postDispose.getSimpleName().toString() );
}
}
sb.append( " ) : null" );
builder.addStatement( sb.toString(), params.toArray() );
}
@Nonnull
private List<ObservableDescriptor> getInitializers()
{
return getObservables()
.stream()
.filter( ObservableDescriptor::requireInitializer )
.collect( Collectors.toList() );
}
private boolean isNameCollision( @Nonnull final ExecutableElement constructor,
@Nonnull final List<ObservableDescriptor> initializers,
@Nonnull final String name )
{
return constructor.getParameters().stream().anyMatch( p -> p.getSimpleName().toString().equals( name ) ) ||
initializers.stream().anyMatch( o -> o.getName().equals( name ) );
}
boolean needsDaggerIntegration()
{
return _dagger;
}
boolean shouldGenerateFactoryToInject()
{
return _generatesFactoryToInject;
}
@Nonnull
InjectMode getInjectMode()
{
return _injectMode;
}
boolean needsDaggerModule()
{
return needsDaggerIntegration() && InjectMode.PROVIDE == _injectMode && !needsDaggerComponentExtension();
}
boolean needsDaggerComponentExtension()
{
return ( needsDaggerIntegration() && _generatesFactoryToInject ) || needsEnhancer();
}
boolean needsEnhancer()
{
return needsDaggerIntegration() && ( null != _postConstruct || requiresSchedule() ) && _nonConstructorInjections;
}
@Nonnull
TypeSpec buildComponentDaggerModule()
throws ArezProcessorException
{
assert needsDaggerIntegration();
final TypeSpec.Builder builder = TypeSpec.interfaceBuilder( getComponentDaggerModuleName() ).
addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( asDeclaredType() ) );
Generator.addOriginatingTypes( getElement(), builder );
Generator.addGeneratedAnnotation( this, builder );
builder.addAnnotation( Generator.DAGGER_MODULE_CLASSNAME );
builder.addModifiers( Modifier.PUBLIC );
final MethodSpec.Builder method = MethodSpec.methodBuilder( "bindComponent" ).
addAnnotation( Generator.DAGGER_BINDS_CLASSNAME ).
addModifiers( Modifier.ABSTRACT, Modifier.PUBLIC ).
addParameter( ClassName.get( getPackageName(), getArezClassName() ), "component" ).
returns( ClassName.get( getElement() ) );
if ( null != _scopeAnnotation )
{
final DeclaredType annotationType = _scopeAnnotation.getAnnotationType();
final TypeElement typeElement = (TypeElement) annotationType.asElement();
method.addAnnotation( ClassName.get( typeElement ) );
}
builder.addMethod( method.build() );
return builder.build();
}
boolean hasRepository()
{
return null != _repositoryExtensions;
}
@SuppressWarnings( "ConstantConditions" )
void configureRepository( @Nonnull final String name,
@Nonnull final List<TypeElement> extensions,
@Nonnull final String repositoryInjectMode,
@Nonnull final String repositoryDaggerConfig )
{
assert null != name;
assert null != extensions;
_repositoryInjectMode = repositoryInjectMode;
_repositoryDaggerConfig = repositoryDaggerConfig;
for ( final TypeElement extension : extensions )
{
if ( ElementKind.INTERFACE != extension.getKind() )
{
throw new ArezProcessorException( "Class annotated with @Repository defined an extension that is " +
"not an interface. Extension: " + extension.getQualifiedName(),
getElement() );
}
for ( final Element enclosedElement : extension.getEnclosedElements() )
{
if ( ElementKind.METHOD == enclosedElement.getKind() )
{
final ExecutableElement method = (ExecutableElement) enclosedElement;
if ( !method.isDefault() &&
!( method.getSimpleName().toString().equals( "self" ) && 0 == method.getParameters().size() ) )
{
throw new ArezProcessorException( "Class annotated with @Repository defined an extension that has " +
"a non default method. Extension: " + extension.getQualifiedName() +
" Method: " + method, getElement() );
}
}
}
}
_repositoryExtensions = extensions;
}
/**
* Build the enhanced class for the component.
*/
@Nonnull
TypeSpec buildRepository( @Nonnull final Types typeUtils )
throws ArezProcessorException
{
assert null != _repositoryExtensions;
final TypeElement element = getElement();
final ClassName arezType = ClassName.get( getPackageName(), getArezClassName() );
final TypeSpec.Builder builder = TypeSpec.classBuilder( getRepositoryName() ).
addTypeVariables( ProcessorUtil.getTypeArgumentsAsNames( asDeclaredType() ) );
Generator.addOriginatingTypes( element, builder );
Generator.addGeneratedAnnotation( this, builder );
final boolean addSingletonAnnotation =
"CONSUME".equals( _repositoryInjectMode ) ||
"PROVIDE".equals( _repositoryInjectMode ) ||
( "AUTODETECT".equals( _repositoryInjectMode ) &&
null != _elements.getTypeElement( Constants.INJECT_ANNOTATION_CLASSNAME ) );
final AnnotationSpec.Builder arezComponent =
AnnotationSpec.builder( ClassName.bestGuess( Constants.COMPONENT_ANNOTATION_CLASSNAME ) );
if ( !addSingletonAnnotation )
{
arezComponent.addMember( "nameIncludesId", "false" );
}
if ( !"AUTODETECT".equals( _repositoryInjectMode ) )
{
arezComponent.addMember( "inject", "$T.$N", Generator.INJECT_MODE_CLASSNAME, _repositoryInjectMode );
}
if ( !"AUTODETECT".equals( _repositoryDaggerConfig ) )
{
arezComponent.addMember( "dagger", "$T.$N", Generator.FEATURE_CLASSNAME, _repositoryDaggerConfig );
}
builder.addAnnotation( arezComponent.build() );
if ( addSingletonAnnotation )
{
builder.addAnnotation( Generator.SINGLETON_CLASSNAME );
}
builder.superclass( ParameterizedTypeName.get( Generator.ABSTRACT_REPOSITORY_CLASSNAME,
getIdType().box(),
ClassName.get( element ),
ClassName.get( getPackageName(), getRepositoryName() ) ) );
_repositoryExtensions.forEach( e -> builder.addSuperinterface( TypeName.get( e.asType() ) ) );
ProcessorUtil.copyAccessModifiers( element, builder );
/*
* If the repository will be generated as a PROVIDE inject mode when dagger is present
* but the type is not public, we still need to generate a public repository due to
* constraints imposed by dagger.
*/
if ( addSingletonAnnotation &&
!"CONSUME".equals( _repositoryInjectMode ) &&
!element.getModifiers().contains( Modifier.PUBLIC ) )
{
builder.addModifiers( Modifier.PUBLIC );
}
builder.addModifiers( Modifier.ABSTRACT );
//Add the default access, no-args constructor
builder.addMethod( MethodSpec.constructorBuilder().build() );
// Add the factory method
builder.addMethod( buildFactoryMethod() );
if ( shouldRepositoryDefineCreate() )
{
for ( final ExecutableElement constructor : ProcessorUtil.getConstructors( element ) )
{
final ExecutableType methodType =
(ExecutableType) typeUtils.asMemberOf( (DeclaredType) _element.asType(), constructor );
builder.addMethod( buildRepositoryCreate( constructor, methodType, arezType ) );
}
}
if ( shouldRepositoryDefineAttach() )
{
builder.addMethod( buildRepositoryAttach() );
}
if ( null != _componentId )
{
builder.addMethod( buildFindByIdMethod() );
builder.addMethod( buildGetByIdMethod() );
}
if ( shouldRepositoryDefineDestroy() )
{
builder.addMethod( buildRepositoryDestroy() );
}
if ( shouldRepositoryDefineDetach() )
{
builder.addMethod( buildRepositoryDetach() );
}
return builder.build();
}
@Nonnull
ClassName getEnhancedClassName()
{
return ClassName.get( getPackageName(), getArezClassName() );
}
@Nonnull
ClassName getEnhancerClassName()
{
return ClassName.get( getPackageName(), getArezClassName(), "Enhancer" );
}
@Nonnull
ClassName getClassNameToConstruct()
{
return getEnhancedClassName();
}
@Nonnull
private String getArezClassName()
{
return getNestedClassPrefix() + "Arez_" + getElement().getSimpleName();
}
@Nonnull
private String getComponentDaggerModuleName()
{
return getNestedClassPrefix() + getElement().getSimpleName() + "DaggerModule";
}
@Nonnull
ClassName getDaggerComponentExtensionClassName()
{
return ClassName.get( getPackageName(),
getNestedClassPrefix() + _element.getSimpleName() + "DaggerComponentExtension" );
}
@Nonnull
private String getArezRepositoryName()
{
return "Arez_" + getNestedClassPrefix() + getElement().getSimpleName() + "Repository";
}
@Nonnull
private String getRepositoryName()
{
return getNestedClassPrefix() + getElement().getSimpleName() + "Repository";
}
@Nonnull
private MethodSpec buildRepositoryAttach()
{
final TypeName entityType = TypeName.get( getElement().asType() );
final MethodSpec.Builder method = MethodSpec.methodBuilder( "attach" ).
addAnnotation( Override.class ).
addAnnotation( AnnotationSpec.builder( Generator.ACTION_CLASSNAME )
.addMember( "reportParameters", "false" )
.build() ).
addParameter( ParameterSpec.builder( entityType, "entity", Modifier.FINAL )
.addAnnotation( Generator.NONNULL_CLASSNAME )
.build() ).
addStatement( "super.attach( entity )" );
ProcessorUtil.copyAccessModifiers( getElement(), method );
return method.build();
}
@Nonnull
private MethodSpec buildRepositoryDetach()
{
final TypeName entityType = TypeName.get( getElement().asType() );
final MethodSpec.Builder method = MethodSpec.methodBuilder( "detach" ).
addAnnotation( Override.class ).
addAnnotation( AnnotationSpec.builder( Generator.ACTION_CLASSNAME )
.addMember( "reportParameters", "false" )
.build() ).
addParameter( ParameterSpec.builder( entityType, "entity", Modifier.FINAL )
.addAnnotation( Generator.NONNULL_CLASSNAME )
.build() ).
addStatement( "super.detach( entity )" );
ProcessorUtil.copyAccessModifiers( getElement(), method );
return method.build();
}
@Nonnull
private MethodSpec buildRepositoryDestroy()
{
final TypeName entityType = TypeName.get( getElement().asType() );
final MethodSpec.Builder method = MethodSpec.methodBuilder( "destroy" ).
addAnnotation( Override.class ).
addAnnotation( AnnotationSpec.builder( Generator.ACTION_CLASSNAME )
.addMember( "reportParameters", "false" )
.build() ).
addParameter( ParameterSpec.builder( entityType, "entity", Modifier.FINAL )
.addAnnotation( Generator.NONNULL_CLASSNAME )
.build() ).
addStatement( "super.destroy( entity )" );
ProcessorUtil.copyAccessModifiers( getElement(), method );
final Set<Modifier> modifiers = getElement().getModifiers();
if ( !modifiers.contains( Modifier.PUBLIC ) && !modifiers.contains( Modifier.PROTECTED ) )
{
/*
* The destroy method inherited from AbstractContainer is protected and the override
* must be at least the same access level.
*/
method.addModifiers( Modifier.PROTECTED );
}
return method.build();
}
@Nonnull
private MethodSpec buildFindByIdMethod()
{
assert null != _componentId;
final MethodSpec.Builder method = MethodSpec.methodBuilder( "findBy" + getIdName() ).
addModifiers( Modifier.FINAL ).
addParameter( ParameterSpec.builder( getIdType(), "id", Modifier.FINAL ).build() ).
addAnnotation( Generator.NULLABLE_CLASSNAME ).
returns( TypeName.get( getElement().asType() ) ).
addStatement( "return findByArezId( id )" );
ProcessorUtil.copyAccessModifiers( getElement(), method );
return method.build();
}
@Nonnull
private MethodSpec buildGetByIdMethod()
{
final TypeName entityType = TypeName.get( getElement().asType() );
final MethodSpec.Builder method = MethodSpec.methodBuilder( "getBy" + getIdName() ).
addModifiers( Modifier.FINAL ).
addAnnotation( Generator.NONNULL_CLASSNAME ).
addParameter( ParameterSpec.builder( getIdType(), "id", Modifier.FINAL ).build() ).
returns( entityType ).
addStatement( "return getByArezId( id )" );
ProcessorUtil.copyAccessModifiers( getElement(), method );
return method.build();
}
@Nonnull
private MethodSpec buildFactoryMethod()
{
final MethodSpec.Builder method = MethodSpec.methodBuilder( "newRepository" ).
addModifiers( Modifier.STATIC ).
addAnnotation( Generator.NONNULL_CLASSNAME ).
returns( ClassName.get( getPackageName(), getRepositoryName() ) ).
addStatement( "return new $T()", ClassName.get( getPackageName(), getArezRepositoryName() ) );
ProcessorUtil.copyAccessModifiers( getElement(), method );
return method.build();
}
@Nonnull
private MethodSpec buildRepositoryCreate( @Nonnull final ExecutableElement constructor,
@Nonnull final ExecutableType methodType,
@Nonnull final ClassName arezType )
{
final String suffix = constructor.getParameters().stream().
map( p -> p.getSimpleName().toString() ).collect( Collectors.joining( "_" ) );
final String actionName = "create" + ( suffix.isEmpty() ? "" : "_" + suffix );
final AnnotationSpec annotationSpec =
AnnotationSpec.builder( ClassName.bestGuess( Constants.ACTION_ANNOTATION_CLASSNAME ) ).
addMember( "name", "$S", actionName ).build();
final MethodSpec.Builder builder =
MethodSpec.methodBuilder( "create" ).
addAnnotation( annotationSpec ).
addAnnotation( Generator.NONNULL_CLASSNAME ).
returns( TypeName.get( asDeclaredType() ) );
ProcessorUtil.copyAccessModifiers( getElement(), builder );
ProcessorUtil.copyExceptions( methodType, builder );
ProcessorUtil.copyTypeParameters( methodType, builder );
final StringBuilder newCall = new StringBuilder();
newCall.append( "final $T entity = new $T(" );
final ArrayList<Object> parameters = new ArrayList<>();
parameters.add( arezType );
parameters.add( arezType );
boolean firstParam = true;
for ( final VariableElement element : constructor.getParameters() )
{
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( element.asType() ), element.getSimpleName().toString(), Modifier.FINAL );
ProcessorUtil.copyWhitelistedAnnotations( element, param );
builder.addParameter( param.build() );
parameters.add( element.getSimpleName().toString() );
if ( !firstParam )
{
newCall.append( "," );
}
firstParam = false;
newCall.append( "$N" );
}
for ( final ObservableDescriptor observable : getInitializers() )
{
final String candidateName = observable.getName();
final String name = isNameCollision( constructor, Collections.emptyList(), candidateName ) ?
Generator.INITIALIZER_PREFIX + candidateName :
candidateName;
final ParameterSpec.Builder param =
ParameterSpec.builder( TypeName.get( observable.getGetterType().getReturnType() ),
name,
Modifier.FINAL );
ProcessorUtil.copyWhitelistedAnnotations( observable.getGetter(), param );
builder.addParameter( param.build() );
parameters.add( name );
if ( !firstParam )
{
newCall.append( "," );
}
firstParam = false;
newCall.append( "$N" );
}
newCall.append( ")" );
builder.addStatement( newCall.toString(), parameters.toArray() );
builder.addStatement( "attach( entity )" );
builder.addStatement( "return entity" );
return builder.build();
}
@Nonnull
String getPackageName()
{
return _packageElement.getQualifiedName().toString();
}
@Nonnull
private String getIdMethodName()
{
/*
* Note that it is a deliberate choice to not use getArezId() as that will box Id which for the
* "normal" case involves converting a long to a Long and it was decided that the slight increase in
* code size was worth the slightly reduced memory pressure.
*/
return null != _componentId ? _componentId.getSimpleName().toString() : Generator.ID_FIELD_NAME;
}
@Nonnull
private String getIdName()
{
assert null != _componentId;
final String name = ProcessorUtil.deriveName( _componentId, GETTER_PATTERN, ProcessorUtil.SENTINEL_NAME );
if ( null != name )
{
return Character.toUpperCase( name.charAt( 0 ) ) + ( name.length() > 1 ? name.substring( 1 ) : "" );
}
else
{
return "Id";
}
}
@Nonnull
private TypeName getIdType()
{
return null == _componentIdMethodType ?
Generator.DEFAULT_ID_TYPE :
TypeName.get( _componentIdMethodType.getReturnType() );
}
private <T> T getAnnotationParameter( @Nonnull final AnnotationMirror annotation,
@Nonnull final String parameterName )
{
return ProcessorUtil.getAnnotationValue( _elements, annotation, parameterName );
}
private boolean shouldRepositoryDefineCreate()
{
final VariableElement injectParameter = (VariableElement)
ProcessorUtil.getAnnotationValue( _elements,
getElement(),
Constants.REPOSITORY_ANNOTATION_CLASSNAME,
"attach" ).getValue();
switch ( injectParameter.getSimpleName().toString() )
{
case "CREATE_ONLY":
case "CREATE_OR_ATTACH":
return true;
default:
return false;
}
}
private boolean shouldRepositoryDefineAttach()
{
final VariableElement injectParameter = (VariableElement)
ProcessorUtil.getAnnotationValue( _elements,
getElement(),
Constants.REPOSITORY_ANNOTATION_CLASSNAME,
"attach" ).getValue();
switch ( injectParameter.getSimpleName().toString() )
{
case "ATTACH_ONLY":
case "CREATE_OR_ATTACH":
return true;
default:
return false;
}
}
private boolean shouldRepositoryDefineDestroy()
{
final VariableElement injectParameter = (VariableElement)
ProcessorUtil.getAnnotationValue( _elements,
getElement(),
Constants.REPOSITORY_ANNOTATION_CLASSNAME,
"detach" ).getValue();
switch ( injectParameter.getSimpleName().toString() )
{
case "DESTROY_ONLY":
case "DESTROY_OR_DETACH":
return true;
default:
return false;
}
}
private boolean shouldRepositoryDefineDetach()
{
final VariableElement injectParameter = (VariableElement)
ProcessorUtil.getAnnotationValue( _elements,
getElement(),
Constants.REPOSITORY_ANNOTATION_CLASSNAME,
"detach" ).getValue();
switch ( injectParameter.getSimpleName().toString() )
{
case "DETACH_ONLY":
case "DESTROY_OR_DETACH":
return true;
default:
return false;
}
}
}
|
package edu.umd.cs.findbugs;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import edu.umd.cs.findbugs.xml.OutputStreamXMLOutput;
import edu.umd.cs.findbugs.xml.XMLOutput;
import edu.umd.cs.findbugs.xml.XMLWriteable;
/**
* Statistics resulting from analyzing a project.
*/
public class ProjectStats implements XMLWriteable {
private static final String TIMESTAMP_FORMAT = "EEE, d MMM yyyy HH:mm:ss Z";
private HashMap<String, PackageStats> packageStatsMap;
private int[] totalErrors = new int[] { 0, 0, 0, 0, 0 };
private int totalClasses;
private int totalSize;
private Date timestamp;
/**
* Constructor. Creates an empty object.
*/
public ProjectStats() {
this.packageStatsMap = new HashMap<String, PackageStats>();
this.totalClasses = 0;
this.timestamp = new Date();
}
/**
* Set the timestamp for this analysis run.
*
* @param timestamp the time of the analysis run this
* ProjectStats represents, as previously
* reported by writeXML.
*/
public void setTimestamp(String timestamp) throws ParseException {
this.timestamp = new SimpleDateFormat(TIMESTAMP_FORMAT, Locale.ENGLISH).parse(timestamp);
}
/**
* Get the number of classes analyzed.
*/
public int getNumClasses() {
return totalClasses;
}
/**
* Report that a class has been analyzed.
*
* @param className the full name of the class
* @param isInterface true if the class is an interface
* @param size a normalized class size value;
* see detect/FindBugsSummaryStats.
*/
public void addClass(String className, boolean isInterface, int size) {
String packageName;
int lastDot = className.lastIndexOf('.');
if (lastDot < 0)
packageName = "";
else
packageName = className.substring(0, lastDot);
PackageStats stat = getPackageStats(packageName);
stat.addClass(className, isInterface, size);
totalClasses++;
totalSize += size;
}
/**
* Called when a bug is reported.
*/
public void addBug(BugInstance bug) {
PackageStats stat = getPackageStats(bug.getPrimaryClass().getPackageName());
stat.addError(bug);
++totalErrors[0];
int priority = bug.getPriority();
if (priority >= 1) {
++totalErrors[Math.min(priority, totalErrors.length - 1)];
}
}
/**
* Output as XML.
*/
public void writeXML(XMLOutput xmlOutput) throws IOException {
xmlOutput.startTag("FindBugsSummary");
xmlOutput.addAttribute("timestamp",
new SimpleDateFormat(TIMESTAMP_FORMAT, Locale.ENGLISH).format(timestamp));
xmlOutput.addAttribute("total_classes", String.valueOf(totalClasses));
xmlOutput.addAttribute("total_bugs", String.valueOf(totalErrors[0]));
xmlOutput.addAttribute("total_size", String.valueOf(totalSize));
xmlOutput.addAttribute("num_packages", String.valueOf(packageStatsMap.size()));
PackageStats.writeBugPriorities(xmlOutput, totalErrors);
xmlOutput.stopTag(false);
Iterator<PackageStats> i = packageStatsMap.values().iterator();
while (i.hasNext()) {
PackageStats stats = i.next();
stats.writeXML(xmlOutput);
}
xmlOutput.closeTag("FindBugsSummary");
}
/**
* Report statistics as an XML document to given output stream.
*/
public void reportSummary(OutputStream out) throws IOException {
XMLOutput xmlOutput = new OutputStreamXMLOutput(out);
writeXML(xmlOutput);
xmlOutput.finish();
}
/**
* Transform summary information to HTML.
*
* @param htmlWriter the Writer to write the HTML output to
*/
public void transformSummaryToHTML(Writer htmlWriter)
throws IOException, TransformerException {
ByteArrayOutputStream summaryOut = new ByteArrayOutputStream(8096);
reportSummary(summaryOut);
StreamSource in = new StreamSource(new ByteArrayInputStream(summaryOut.toByteArray()));
StreamResult out = new StreamResult(htmlWriter);
InputStream xslInputStream = this.getClass().getClassLoader().getResourceAsStream("summary.xsl");
if (xslInputStream == null)
throw new IOException("Could not load summary stylesheet");
StreamSource xsl = new StreamSource(xslInputStream);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer(xsl);
transformer.transform(in, out);
Reader rdr = in.getReader();
if (rdr != null)
rdr.close();
htmlWriter.close();
InputStream is = xsl.getInputStream();
if (is != null)
is.close();
}
private PackageStats getPackageStats(String packageName) {
PackageStats stat = packageStatsMap.get(packageName);
if (stat == null) {
stat = new PackageStats(packageName);
packageStatsMap.put(packageName, stat);
}
return stat;
}
}
|
package net.sensnet.plugins.visualizer;
import java.nio.ByteBuffer;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import net.sensnet.node.DatabaseConnection;
import net.sensnet.node.dbobjects.DataPoint;
import net.sensnet.node.plugins.SensorIndexer;
public class ChemGasSensor extends SensorIndexer {
public ChemGasSensor() throws SQLException {
super();
}
@Override
public String getSensorName() {
return "chemgas5vbutan";
}
@Override
public String createIndexTableArguments() {
return "`id` int(11) unsigned NOT NULL AUTO_INCREMENT, `datapoint` "
+ "int(11) unsigned NOT NULL, `ppm` int(11) NOT NULL, PRIMARY KEY (`id`)";
}
@Override
public String getInsertionPreparedQuery() {
return "INSERT INTO " + getTableName() + " (datapoint,ppm) VALUES(?,?)";
}
@Override
public boolean indexize(PreparedStatement insertQuery, DataPoint target,
int id) throws SQLException {
insertQuery.setInt(1, id);
ByteBuffer buf = ByteBuffer.wrap(target.getValues());
short res = buf.getShort(0);
res <<= 8;
res += buf.getShort(2);
System.out.println("RES: " + res);
buf.clear();
float voltage = (3.5f / (float) Math.pow(2, 11)) * res;
System.out.println("Voltage: " + voltage);
float ohm = (20000 * voltage) / (7 - 2 * voltage);
int ppm = (int) ((186500 / 17) - ((33 * ohm) / 85));
if (ohm > 1000000 || ohm < 0) {
return true;
}
if (ppm < 100) {
ppm = 0;
}
System.out.println("ppm: " + ppm + " ohm: " + ohm);
insertQuery.setInt(2, ppm);
return insertQuery.execute();
}
@Override
public int getSensorType() {
return 2;
}
public static String[][] getLatestDosesFromAllSensors(Date upperLimit)
throws SQLException {
PreparedStatement prep = DatabaseConnection
.getInstance()
.prepare(
"SELECT receivernode, `from`, received, voltage, a.locationlat AS lat, a.locationlong AS lng FROM sensor_chemgas LEFT JOIN datapoints a ON (datapoint = a.id) WHERE received <= ? ORDER BY received DESC LIMIT 0,1");
prep.setLong(1, upperLimit.getTime() / 1000);
ResultSet resSet = prep.executeQuery();
return parseQuery(resSet);
}
private static String[][] parseQuery(ResultSet resSet) throws SQLException {
if (resSet.last()) {
String[][] res = new String[resSet.getRow()][];
resSet.beforeFirst();
int i = 0;
while (resSet.next()) {
String[] in = new String[6];
in[0] = resSet.getInt("lat") + "";
in[1] = resSet.getInt("lng") + "";
in[2] = resSet.getFloat("voltage") + "";
in[3] = resSet.getInt("received") + "";
in[4] = resSet.getInt("from") + "";
in[5] = resSet.getInt("receivernode") + "";
res[i++] = in;
}
resSet.close();
return res;
}
resSet.close();
return new String[0][];
}
@Override
public int getSensorClass() {
return 2;
}
}
|
package org.batfish.z3.expr;
import java.util.Arrays;
public class Comment extends Statement {
private String[] _lines;
public Comment(String... lines) {
_lines = lines;
}
@Override
public <T> T accept(GenericStatementVisitor<T> visitor) {
return visitor.visitComment(this);
}
@Override
public void accept(VoidStatementVisitor visitor) {
visitor.visitComment(this);
}
public String[] getLines() {
return _lines;
}
@Override
public int hashCode() {
return Arrays.hashCode(_lines);
}
@Override
public boolean statementEquals(Statement e) {
return Arrays.equals(_lines, ((Comment) e)._lines);
}
}
|
package reflex.node;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import rapture.common.RaptureTransferObject;
import rapture.common.exception.ExceptionToString;
import rapture.common.exception.RaptureException;
import rapture.common.exception.RaptureExceptionFactory;
import rapture.common.impl.jackson.JacksonUtil;
import reflex.ReflexException;
import reflex.value.ReflexFileValue;
import reflex.value.ReflexValue;
import reflex.value.internal.ReflexNullValue;
public final class KernelExecutor {
protected KernelExecutor() {
}
private static final Logger log = Logger.getLogger(KernelExecutor.class);
public static ReflexValue executeFunction(int lineNumber, Object outerApi, String areaName, String fnName, List<ReflexValue> params) {
String apiName;
if (!StringUtils.isEmpty(areaName) && areaName.length() > 1) {
apiName = areaName.substring(0, 1).toUpperCase() + areaName.substring(1);
} else {
apiName = "<api name missing>";
}
int numPassedParams = params.size();
try {
// Find the method get[AreaName], which will return the area
Method[] methods = outerApi.getClass().getMethods();
String getApiMethodName = "get" + apiName;
for (Method m : methods) {
if (m.getName().equals(getApiMethodName)) {
// Call that method to get the api requested
Object api = m.invoke(outerApi);
// Now find the method with the fnName
Method[] innerMethods = api.getClass().getMethods();
for (Method im : innerMethods) {
if (im.getName().equals(fnName)) {
// the api should just have one entry
Type[] types = im.getGenericParameterTypes();
int numExpectedParams = types.length;
if (numExpectedParams == numPassedParams) {
List<Object> callParams = new ArrayList<Object>(types.length);
// Now coerce the types...
for (int i = 0; i < types.length; i++) {
ReflexValue v = params.get(i);
Object x = convertValueToType(v, types[i]);
callParams.add(x);
}
// Now invoke
Object ret;
try {
ret = im.invoke(api, callParams.toArray());
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
throw new ReflexException(lineNumber, String.format("Error in Reflex script at line %d. Call to %s.%s failed: %s",
lineNumber, apiName, fnName, e.getTargetException().getMessage()), e);
}
ReflexValue retVal = new ReflexNullValue(lineNumber);
if (ret != null) {
retVal = new ReflexValue(convertObject(ret));
}
return retVal;
}
}
}
throw new ReflexException(lineNumber, String.format("API call not found: %s.%s (taking %s parameters)", apiName, fnName, numPassedParams));
}
}
throw new ReflexException(lineNumber, "API '" + apiName + "' not found!");
} catch (InvocationTargetException e) {
Throwable cause = e.getCause();
if (cause != null) {
if (cause instanceof OutOfMemoryError) {
log.error(ExceptionToString.format(e));
throw (OutOfMemoryError) cause;
} else if (cause instanceof RaptureException) {
log.warn(ExceptionToString.format(e));
String message = ((RaptureException) cause).getFormattedMessage();
throw new ReflexException(lineNumber, message, e);
} else {
String details = null;
if (cause.getMessage() != null) {
details = ": " + cause.getMessage();
}
RaptureException re = RaptureExceptionFactory
.create(String.format("Error executing api call: %s.%s (takes %s parameters)%s", apiName, fnName, numPassedParams, details), e);
String message = re.getFormattedMessage();
throw new ReflexException(lineNumber, message, re);
}
}
throw new ReflexException(lineNumber, e.getTargetException().getMessage(), e);
} catch (ReflexException e) {
throw e;
} catch (Exception e) {
log.error(ExceptionToString.format(e));
throw new ReflexException(lineNumber, e.getMessage(), e);
}
}
public static Object convert(List<ReflexValue> asList) {
List<Object> ret = new ArrayList<Object>(asList.size());
for (Object o : asList) {
if (o instanceof ReflexValue) {
ReflexValue e = (ReflexValue) o;
if (e.isMap()) {
ret.add(convert(e.asMap()));
} else if (e.isList()) {
ret.add(convert(e.asList()));
} else if (e.isComplex()) {
ret.add(convertObject(e.asObject()));
} else {
ret.add(e.asObject());
}
} else {
ret.add(o);
}
}
return ret;
}
public static Object convertSimpleList(List<Object> asList) {
List<Object> ret = new ArrayList<Object>(asList.size());
for (Object o : asList) {
if (o instanceof ReflexValue) {
ReflexValue e = (ReflexValue) o;
if (e.isMap()) {
ret.add(convert(e.asMap()));
} else if (e.isList()) {
ret.add(convert(e.asList()));
} else {
ret.add(e.asObject());
}
} else {
ret.add(o);
}
}
return ret;
}
@SuppressWarnings("unchecked")
public static Map<String, Object> convert(Map<String, Object> asMap) {
if (asMap == null) return null;
Map<String, Object> converted = new LinkedHashMap<String, Object>();
for (Map.Entry<String, Object> e : asMap.entrySet()) {
if (e.getValue() instanceof ReflexValue) {
ReflexValue val = (ReflexValue) e.getValue();
if (val.isMap()) {
converted.put(e.getKey(), convert(val.asMap()));
} else if (val.isList()) {
converted.put(e.getKey(), convert(val.asList()));
} else if (val.isString()) {
converted.put(e.getKey(), val.asString());
} else {
converted.put(e.getKey(), val.asObject());
}
} else if (e.getValue() instanceof List) {
List<Object> vals = (List<Object>) e.getValue();
converted.put(e.getKey(), convertSimpleList(vals));
} else if (e.getValue() instanceof Map) {
converted.put(e.getKey(), convert((Map<String, Object>) e.getValue()));
} else {
converted.put(e.getKey(), e.getValue());
}
}
return converted;
}
public static String convertValueToJson(ReflexValue value, boolean prettyFy) {
Object toJson = value.asObject();
if (value.isMap()) {
toJson = convert(value.asMap());
} else if (value.isList()) {
toJson = convert(value.asList());
} else if (value.isStruct()) {
toJson = convert(value.asStruct().asMap());
}
String ret = JacksonUtil.jsonFromObject(toJson);
if (prettyFy) {
ret = JacksonUtil.prettyfy(ret);
}
return ret;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object convertValueToType(ReflexValue v, Type type) {
if (type.equals(byte[].class)) {
if (v.isFile()) {
// Load file to bytes and return that
return getContentFromFile(v.asFile());
} else if (v.isByteArray()) {
return v.asByteArray();
} else if (v.isNull()) {
return "".getBytes();
} else {
return v.toString().getBytes();
}
} else if (type.equals(String.class)) {
if (v.isFile()) {
return new String(getContentFromFile(v.asFile()));
} else if (v.isNull()) {
return null;
} else {
return v.toString();
}
} else if (type.equals(Double.class)) {
return v.asDouble();
} else if (type.equals(Integer.class)) {
return v.asInt();
} else if (type.equals(Long.class)) {
return v.asLong();
} else if (type.equals(Boolean.class)) {
return v.asBoolean();
} else if (type instanceof ParameterizedType) {
return handleParameterizedType(v, type);
} else if (type.equals(Map.class) || type.equals(List.class)) {
return handleParameterizedType(v, type);
} else if (type instanceof Class && ((Class<?>) type).isEnum()) {
return Enum.valueOf((Class<Enum>) type, v.asString());
}
return v.asObject();
}
private static byte[] getContentFromFile(ReflexFileValue asFile) {
try {
return IOUtils.toByteArray(asFile.getInputStream());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
public static ReflexValue reconstructFromObject(Object x) throws ClassNotFoundException {
if (x instanceof ReflexValue) {
return (ReflexValue) x;
}
if (x instanceof Map) {
@SuppressWarnings("unchecked")
Map<String, Object> theMap = convert((Map<String, Object>) x);
if (theMap.containsKey("CLASS")) {
String typeName = theMap.get("CLASS").toString();
theMap.remove("CLASS");
String json = JacksonUtil.jsonFromObject(theMap);
Object realObject = JacksonUtil.objectFromJson(json, Class.forName(typeName));
return new ReflexValue(realObject);
} else {
return new ReflexValue(theMap);
}
} else if (x instanceof List) {
List<?> r = (List<?>) x;
List<ReflexValue> ret2 = new ArrayList<ReflexValue>(r.size());
for (Object inner : r) {
ret2.add(inner == null ? new ReflexNullValue() : reconstructFromObject(inner));
}
return new ReflexValue(ret2);
} else {
return new ReflexValue(x);
}
}
private static Object handleParameterizedType(ReflexValue v, Type type) {
if (!(type instanceof ParameterizedType)) {
if (type.equals(String.class)) return v.asString();
if (type.equals(Double.class)) return v.asDouble();
if (type.equals(Long.class)) return v.asLong();
if (type.equals(BigDecimal.class)) return v.asBigDecimal();
return v.asObject();
}
ParameterizedType pType = (ParameterizedType) type;
if (pType.getRawType().equals(Map.class)) {
if (!v.isMap()) {
log.error(v.toString() + " is not a map");
return null;
}
Map<String, Object> convertedMap = new LinkedHashMap<>();
for (Entry<String, Object> entry : v.asMap().entrySet()) {
Type[] innerType = pType.getActualTypeArguments();
String key = null;
if (!innerType[0].equals(String.class)) {
// This could get tricky
log.warn("Keys for maps should always be Strings");
}
key = entry.getKey().toString();
Object value = handleParameterizedType((ReflexValue) entry.getValue(), innerType[1]);
convertedMap.put(key, value);
}
return convertedMap;
} else if (pType.getRawType().equals(List.class)) {
if (!v.isList()) {
log.error(v.toString() + " is not a list");
return null;
}
List<ReflexValue> inner = v.asList();
Type innerType = pType.getActualTypeArguments()[0];
if (innerType.equals(String.class)) {
List<String> ret = new ArrayList<String>(inner.size());
for (ReflexValue vi : inner) {
ret.add(vi.asString());
}
return ret;
} else if (innerType.equals(Double.class)) {
List<Double> ret = new ArrayList<>(inner.size());
for (ReflexValue vi : inner) {
ret.add(vi.asDouble());
}
return ret;
} else if (innerType.equals(Long.class)) {
List<Long> ret = new ArrayList<>(inner.size());
for (ReflexValue vi : inner) {
ret.add(vi.asLong());
}
return ret;
} else if (innerType.equals(BigDecimal.class)) {
List<BigDecimal> ret = new ArrayList<>(inner.size());
for (ReflexValue vi : inner) {
ret.add(vi.asBigDecimal());
}
return ret;
} else if (innerType instanceof ParameterizedType || inner instanceof List) {
List<Object> ret = new ArrayList<>();
for (ReflexValue vi : inner) {
ret.add(handleParameterizedType(vi, innerType));
}
return ret;
} else {
log.warn("Cannot convert " + v.toString() + " to " + type.toString());
}
}
return v.asObject();
}
static Object convertObject(Object ret) {
if (ret instanceof Object[]) {
Object[] r = (Object[]) ret;
List<ReflexValue> ret2 = new ArrayList<ReflexValue>(r.length);
for (Object x : r) {
ret2.add(x == null ? new ReflexNullValue() : new ReflexValue(x));
}
return ret2;
} else if (ret instanceof List) {
List<?> r = (List<?>) ret;
List<ReflexValue> ret2 = new ArrayList<ReflexValue>(r.size());
for (Object x : r) {
ret2.add(x == null ? new ReflexNullValue() : new ReflexValue(convertObject(x)));
}
return ret2;
} else if (ret instanceof RaptureTransferObject) {
// RaptureTransferObject is a hint to convert this object from an
// object
// to a json doc to a map
String json = JacksonUtil.jsonFromObject(ret);
Object retMap = JacksonUtil.getMapFromJson(json);
@SuppressWarnings("unchecked")
Map<String, Object> mapAsRet = (Map<String, Object>) retMap;
mapAsRet.put("CLASS", ret.getClass().getName());
return retMap;
}
return ret;
}
}
|
package com.namelessdev.mpdroid;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.preference.*;
import android.preference.Preference.OnPreferenceClickListener;
import android.text.format.Formatter;
import android.util.Log;
import android.util.SparseArray;
import android.view.Menu;
import android.view.MenuItem;
import com.namelessdev.mpdroid.cover.CachedCover;
import com.namelessdev.mpdroid.helpers.CoverManager;
import org.a0z.mpd.MPD;
import org.a0z.mpd.MPDOutput;
import org.a0z.mpd.MPDStatus;
import org.a0z.mpd.event.StatusChangeListener;
import org.a0z.mpd.exception.MPDServerException;
import java.util.Collection;
@SuppressWarnings("deprecation")
public class SettingsActivity extends PreferenceActivity implements
StatusChangeListener {
private static final int MAIN = 0;
private static final int ADD = 1;
public static final String OPEN_OUTPUT = "open_output";
private OnPreferenceClickListener onPreferenceClickListener;
private SparseArray<CheckBoxPreference> cbPrefs;
private PreferenceScreen pOutputsScreen;
private PreferenceScreen pInformationScreen;
private Handler handler;
private EditTextPreference pCacheUsage1;
private EditTextPreference pCacheUsage2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final MPDApplication app = (MPDApplication) getApplicationContext();
handler = new Handler();
addPreferencesFromResource(R.layout.settings);
// Log.i("MPDroid", "onCreate");
onPreferenceClickListener = new OutputPreferenceClickListener();
cbPrefs = new SparseArray<CheckBoxPreference>();
pOutputsScreen = (PreferenceScreen) findPreference("outputsScreen");
pInformationScreen = (PreferenceScreen) findPreference("informationScreen");
PreferenceScreen pUpdate = (PreferenceScreen) findPreference("updateDB");
// Use the ConnectionPreferConnectionPreferenceCategoryenceCategory for
// Wi-Fi based Connection setttings
/*
* PreferenceScreen pConnectionScreen =
* (PreferenceScreen)findPreference("connectionScreen");
* PreferenceCategory wifiConnection = new
* ConnectionPreferenceCategory(this);
* wifiConnection.setTitle("Preferred connection");
* wifiConnection.setOrder(0);
* pConnectionScreen.addPreference(wifiConnection);
*/
if (!getResources().getBoolean(R.bool.isTablet)) {
final PreferenceScreen interfaceCategory = (PreferenceScreen) findPreference("nowPlayingScreen");
interfaceCategory.removePreference(findPreference("tabletUI"));
}
final EditTextPreference pVersion = (EditTextPreference) findPreference("version");
final EditTextPreference pArtists = (EditTextPreference) findPreference("artists");
final EditTextPreference pAlbums = (EditTextPreference) findPreference("albums");
final EditTextPreference pSongs = (EditTextPreference) findPreference("songs");
// set the albumart fields
CheckBoxPreference c = (CheckBoxPreference) findPreference("enableLocalCover");
Preference mp = (Preference) findPreference("musicPath");
Preference cf = (Preference) findPreference("coverFileName");
if (c.isChecked()) {
mp.setEnabled(true);
cf.setEnabled(true);
} else {
mp.setEnabled(false);
cf.setEnabled(false);
}
// artwork cache usage
long size = new CachedCover(app).getCacheUsage();
String usage = Formatter.formatFileSize(app, size);
pCacheUsage1 = (EditTextPreference) findPreference("cacheUsage1");
pCacheUsage1.setSummary(usage);
pCacheUsage2 = (EditTextPreference) findPreference("cacheUsage2");
pCacheUsage2.setSummary(usage);
// album art library listing requires cover art cache
CheckBoxPreference lcc = (CheckBoxPreference) findPreference("enableLocalCoverCache");
CheckBoxPreference aal = (CheckBoxPreference) findPreference("enableAlbumArtLibrary");
aal.setEnabled(lcc.isChecked());
// Enable/Disable playback resume when call ends only if playback pause
// is enabled when call starts
CheckBoxPreference cPause = (CheckBoxPreference) findPreference("pauseOnPhoneStateChange");
CheckBoxPreference cPlay = (CheckBoxPreference) findPreference("playOnPhoneStateChange");
cPlay.setEnabled(cPause.isChecked());
if (!app.oMPDAsyncHelper.oMPD.isConnected()) {
pOutputsScreen.setEnabled(false);
pUpdate.setEnabled(false);
pInformationScreen.setEnabled(false);
return;
}
app.oMPDAsyncHelper.addStatusChangeListener(this);
new Thread(new Runnable() {
@Override
public void run() {
try {
final String version = app.oMPDAsyncHelper.oMPD
.getMpdVersion();
final String artists = ""
+ app.oMPDAsyncHelper.oMPD.getStatistics()
.getArtists();
final String albums = ""
+ app.oMPDAsyncHelper.oMPD.getStatistics()
.getAlbums();
final String songs = ""
+ app.oMPDAsyncHelper.oMPD.getStatistics()
.getSongs();
handler.post(new Runnable() {
@Override
public void run() {
pVersion.setSummary(version);
pArtists.setSummary(artists);
pAlbums.setSummary(albums);
pSongs.setSummary(songs);
}
});
} catch (MPDServerException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
}
}
}).start();
// Server is Connected...
if (getIntent().getBooleanExtra(OPEN_OUTPUT, false)) {
populateOutputsScreen();
setPreferenceScreen(pOutputsScreen);
}
}
@Override
protected void onStart() {
super.onStart();
MPDApplication app = (MPDApplication) getApplicationContext();
app.setActivity(this);
}
@Override
protected void onStop() {
super.onStop();
MPDApplication app = (MPDApplication) getApplicationContext();
app.unsetActivity(this);
}
@Override
protected void onDestroy() {
MPDApplication app = (MPDApplication) getApplicationContext();
app.oMPDAsyncHelper.removeStatusChangeListener(this);
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
if (getPreferenceScreen().getKey().equals("connectionscreen"))
menu.add(0, ADD, 1, R.string.clear).setIcon(
android.R.drawable.ic_menu_add);
return result;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i = null;
switch (item.getItemId()) {
case MAIN:
i = new Intent(this, MainMenuActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
return true;
}
return false;
}
/**
* Method is beeing called on any click of an preference...
*/
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
Log.d("MPDroid", preferenceScreen.getKey());
MPDApplication app = (MPDApplication) getApplication();
// Is it the connectionscreen which is called?
if (preference.getKey() == null)
return false;
if (preference.getKey().equals("outputsScreen")) {
populateOutputsScreen();
return true;
} else if (preference.getKey().equals("updateDB")) {
try {
MPD oMPD = app.oMPDAsyncHelper.oMPD;
oMPD.refreshDatabase();
} catch (MPDServerException e) {
}
return true;
} else if (preference.getKey().equals("clearLocalCoverCache")) {
new AlertDialog.Builder(this)
.setTitle(R.string.clearLocalCoverCache)
.setMessage(R.string.clearLocalCoverCachePrompt)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MPDApplication app = (MPDApplication) getApplication();
// Todo : The covermanager must already have been initialized, get rid of the getInstance arguments
CoverManager.getInstance(app, null).clear();
pCacheUsage1.setSummary("0.00B");
pCacheUsage2.setSummary("0.00B");
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.show();
return true;
} else if (preference.getKey().equals("enableLocalCover")) {
CheckBoxPreference c = (CheckBoxPreference) findPreference("enableLocalCover");
Preference mp = (Preference) findPreference("musicPath");
Preference cf = (Preference) findPreference("coverFileName");
if (c.isChecked()) {
mp.setEnabled(true);
cf.setEnabled(true);
} else {
mp.setEnabled(false);
cf.setEnabled(false);
}
return true;
} else if (preference.getKey().equals("enableLocalCoverCache")) {
// album art library listing requires cover art cache
CheckBoxPreference lcc = (CheckBoxPreference) findPreference("enableLocalCoverCache");
CheckBoxPreference aal = (CheckBoxPreference) findPreference("enableAlbumArtLibrary");
if (lcc.isChecked()) {
aal.setEnabled(true);
} else {
aal.setEnabled(false);
aal.setChecked(false);
}
return true;
} else if (preference.getKey().equals("pauseOnPhoneStateChange")) {
// Enable/Disable playback resume when call ends only if playback
// pause is enabled when call starts
CheckBoxPreference cPause = (CheckBoxPreference) findPreference("pauseOnPhoneStateChange");
CheckBoxPreference c = (CheckBoxPreference) findPreference("playOnPhoneStateChange");
c.setEnabled(cPause.isChecked());
}
return false;
}
private void populateOutputsScreen() {
// Populating outputs...
PreferenceCategory pOutput = (PreferenceCategory) findPreference("outputsCategory");
final MPDApplication app = (MPDApplication) getApplication();
try {
Collection<MPDOutput> list = app.oMPDAsyncHelper.oMPD.getOutputs();
pOutput.removeAll();
for (MPDOutput out : list) {
CheckBoxPreference pref = new CheckBoxPreference(this);
pref.setPersistent(false);
pref.setTitle(out.getName());
pref.setChecked(out.isEnabled());
pref.setKey("" + out.getId());
pref.setOnPreferenceClickListener(onPreferenceClickListener);
cbPrefs.put(out.getId(), pref);
pOutput.addPreference(pref);
}
} catch (MPDServerException e) {
pOutput.removeAll(); // Connection error occured meanwhile...
}
}
class CheckPreferenceClickListener implements OnPreferenceClickListener {
MPDApplication app = (MPDApplication) getApplication();
@Override
public boolean onPreferenceClick(Preference pref) {
CheckBoxPreference prefCB = (CheckBoxPreference) pref;
MPD oMPD = app.oMPDAsyncHelper.oMPD;
try {
if (prefCB.getKey().equals("random"))
oMPD.setRandom(prefCB.isChecked());
if (prefCB.getKey().equals("repeat"))
oMPD.setRepeat(prefCB.isChecked());
return prefCB.isChecked();
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
class OutputPreferenceClickListener implements OnPreferenceClickListener {
@Override
public boolean onPreferenceClick(Preference pref) {
CheckBoxPreference prefCB = (CheckBoxPreference) pref;
MPDApplication app = (MPDApplication) getApplication();
MPD oMPD = app.oMPDAsyncHelper.oMPD;
String id = prefCB.getKey();
try {
if (prefCB.isChecked()) {
oMPD.enableOutput(Integer.parseInt(id));
return false;
} else {
oMPD.disableOutput(Integer.parseInt(id));
return true;
}
} catch (MPDServerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
}
@Override
public void volumeChanged(MPDStatus mpdStatus, int oldVolume) {
// TODO Auto-generated method stub
}
@Override
public void playlistChanged(MPDStatus mpdStatus, int oldPlaylistVersion) {
// TODO Auto-generated method stub
}
@Override
public void trackChanged(MPDStatus mpdStatus, int oldTrack) {
// TODO Auto-generated method stub
}
@Override
public void stateChanged(MPDStatus mpdStatus, String oldState) {
// TODO Auto-generated method stub
}
@Override
public void repeatChanged(boolean repeating) {
}
@Override
public void randomChanged(boolean random) {
}
@Override
public void connectionStateChanged(boolean connected, boolean connectionLost) {
// TODO Auto-generated method stub
}
@Override
public void libraryStateChanged(boolean updating) {
// TODO Auto-generated method stub
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
}
|
package com.intellij.sh.rename;
import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
import com.intellij.codeInsight.template.impl.TemplateState;
import com.intellij.openapi.actionSystem.IdeActions;
import com.intellij.openapi.application.PluginPathManager;
import com.intellij.testFramework.LightPlatformCodeInsightTestCase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class ShRenameTest extends LightPlatformCodeInsightTestCase {
@NotNull
@Override
protected String getTestDataPath() {
return PluginPathManager.getPluginHomePath("sh") + "/testData/rename/";
}
public void testBasic1() {
doTest("MY_NAME");
}
public void testBasic2() {
doTest(null);
}
public void testBasic3() {
doTest("command -v");
}
public void testSelection1() {
doTest("Bye");
}
public void testSelection2() {
doTest("zsh");
}
public void testSelection3() {
doTest("m");
}
public void testSelection4() {
doTest("4]]");
}
private void doTest(@Nullable String newName) {
configureByFile(getTestName(true) + "-before.sh");
TemplateManagerImpl.setTemplateTesting(getTestRootDisposable());
executeAction(IdeActions.ACTION_RENAME);
TemplateState templateState = TemplateManagerImpl.getTemplateState(getEditor());
if (newName != null) {
assertNotNull(templateState);
}
else {
assertNull(templateState);
return;
}
assertFalse(templateState.isFinished());
type(newName);
templateState.gotoEnd();
checkResultByFile(getTestName(true) + "-after.sh");
}
}
|
package org.pm4j.tools.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.junit.Assert;
import org.pm4j.core.pm.PmAttr;
import org.pm4j.core.pm.PmCommand;
import org.pm4j.core.pm.PmOption;
import org.pm4j.core.pm.PmCommand.CommandState;
import org.pm4j.core.pm.PmMessage;
import org.pm4j.core.pm.PmMessage.Severity;
import org.pm4j.core.pm.PmObject;
import org.pm4j.core.pm.api.PmMessageUtil;
import org.pm4j.core.pm.impl.PmUtil;
/**
* A set of junit test support methods.
*
* @author olaf boede
*/
public class PmAssert {
private PmAssert() {
}
/**
* Checks if exactly the given message text(s) exist for the given PM.
* <p>
* Notice that a {@link org.pm4j.core.pm.PmConversation} will report all messages within its
* scope. Any other PM will only report its own messages.
*
* @param pm
* the PM to check the messages for.
* @param expectedMessages
* the set of expected message texts.
*/
// @formatter:off
public static void assertMessageText(PmObject pm, String... expectedMessages) {
List<PmMessage> messages = PmMessageUtil.getPmMessages(pm);
if (messages.size() != expectedMessages.length) {
fail("Expected " + expectedMessages.length +
" messages but found " + messages.size() + " messages." +
"\nFound messages: " + messages +
"\nExpected messages: " + Arrays.asList(expectedMessages) +
"\nPM context: " + PmUtil.getAbsoluteName(pm));
}
Set<String> expectedSet = new HashSet<String>(Arrays.asList(expectedMessages));
for (PmMessage m : messages) {
if (!expectedSet.contains(m.getTitle())) {
fail("Unexpected message found." +
"\nFound messages: " + messages +
"\nExpected messages: " + Arrays.asList(expectedMessages) +
"\nPM context: " + PmUtil.getAbsoluteName(pm));
}
}
}
// @formatter:on
/**
* Checks that there are no active {@link PmMessage}s for the given PM (incl. it's sub-PMs).
*
* @param pm
* the PM to perform the check for.
*/
public static void assertNoMessagesInSubTree(PmObject pm) {
assertNoMessagesInSubTree("Unexpected messages found.", pm);
}
/**
* Checks that there are no active {@link PmMessage}s for the given PM (incl. it's sub-PMs).
*
* @param msg
* the assert message to display if the check fails.
* @param pm
* the PM to perform the check for.
*/
public static void assertNoMessagesInSubTree(String msg, PmObject pm) {
assertNoMessagesInSubTree(msg, pm, Severity.INFO);
}
/**
* Checks that there are no active {@link PmMessage}s with the given
* <code>minSeverity</code> for the given PM (incl. it's sub-PMs)
*
* @param pm
* the PM to perform the check for.
*/
public static void assertNoMessagesInSubTree(PmObject pm, Severity minSeverity) {
assertNoMessagesInSubTree("Unexpected messages found.", pm, minSeverity);
}
/**
* Checks that there are no active {@link PmMessage}s with the given
* <code>minSeverity</code> for the given PM (incl. it's sub-PMs)
*
* @param msg
* the assert message to display if the check fails.
* @param pm
* the PM to perform the check for.
*/
public static void assertNoMessagesInSubTree(String msg, PmObject pm, Severity minSeverity) {
String errMsgs = subTreeMessagesToString(pm, minSeverity);
if (StringUtils.isNotBlank(errMsgs)) {
Assert.fail(msg + " " + pm.getPmRelativeName() + ": " + errMsgs);
}
}
/**
* Checks that there are no active {@link PmMessage}s within the
* {@link org.pm4j.core.pm.PmConversation} of the given PM.
*
* @param pm
* the PM to perform the check for.
*/
public static void assertNoMessagesInConversation(PmObject pm) {
assertNoMessagesInSubTree(pm.getPmConversation());
}
/**
* Checks that there are no active {@link PmMessage}s within the
* {@link org.pm4j.core.pm.PmConversation} of the given PM.
*
* @param msg
* the assert message to display if the check fails.
* @param pm
* the PM to perform the check for.
*/
public static void assertNoMessagesInConversation(String msg, PmObject pm) {
assertNoMessagesInSubTree(msg, pm.getPmConversation());
}
/**
* Checks if there is the expected error message active for the given PM.
*
* @param pm
* the PM to check.
* @param expectedMsg
* the expexted error message.
*/
public static void assertSingleErrorMessage(PmObject pm, String expectedMsg) {
List<PmMessage> errorMessages = PmMessageUtil.getPmErrors(pm);
assertEquals("Error message expected but not found: " + expectedMsg, 1, errorMessages.size());
assertEquals(expectedMsg, errorMessages.get(0).getTitle());
}
/**
* Checks if the given set of PMs is enabled.
*
* @param pms
* the PMs to check.
*/
public static void assertEnabled(PmObject... pms) {
for (PmObject pm : pms) {
if (!pm.isPmEnabled()) {
fail(pm.getPmRelativeName() + " should be enabled.");
}
}
}
/**
* Checks if the given set of PMs is not enabled.
*
* @param pms
* the PMs to check.
*/
public static void assertNotEnabled(PmObject... pms) {
for (PmObject pm : pms) {
if (pm.isPmEnabled()) {
fail(pm.getPmRelativeName() + " should not be enabled.");
}
}
}
/**
* Checks if the given set of PMs is visible.
*
* @param pms
* the PMs to check.
*/
public static void assertVisible(PmObject... pms) {
for (PmObject pm : pms) {
if (!pm.isPmVisible()) {
fail(pm.getPmRelativeName() + " should be visible.");
}
}
}
/**
* Checks if the given set of PMs is not visible.
*
* @param pms
* the PMs to check.
*/
public static void assertNotVisible(PmObject... pms) {
for (PmObject pm : pms) {
if (pm.isPmVisible()) {
fail(pm.getPmRelativeName() + " should not be visible.");
}
}
}
/**
* Checks if the given set of {@link PmAttr}s is required.
*
* @param pms
* the PMs to check.
*/
public static void assertRequired(PmAttr<?>... pms) {
for (PmAttr<?> pm : pms) {
if (!pm.isRequired()) {
fail("\"" + pm.getPmRelativeName() + "\" attribute should be required.");
}
}
}
/**
* Checks if the given set of {@link PmAttr}s is not required.
*
* @param pms
* the PMs to check.
*/
public static void assertNotRequired(PmAttr<?>... pms) {
for (PmAttr<?> pm : pms) {
if (pm.isRequired()) {
fail("\"" + pm.getPmRelativeName() + "\" attribute should not be required, i.e. optional.");
}
}
}
/**
* Checks if the given attribute has the expected option titles.
*
* @param expectedTitles
* A comma separated string with all expected titles. E.g. "A,B,C".
* @param pmAttr
* The attribute to check.
*/
public static void assertOptionTitles(String expectedTitles, PmAttr<?> pmAttr) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (PmOption o : pmAttr.getOptionSet().getOptions()) {
if (!first) {
sb.append(",");
}
sb.append(o.getPmTitle());
first = false;
}
assertEquals(pmAttr.getPmRelativeName() + ": option titles", expectedTitles, sb.toString());
}
/**
* Checks if the given attribute has the expected option titles.
*
* @param expectedIds
* A comma separated string with all expected id's. E.g. "A,B,C".
* @param pmAttr
* The attribute to check.
*/
public static void assertOptionIds(String expectedIds, PmAttr<?> pmAttr) {
StringBuilder sb = new StringBuilder();
boolean first = true;
for (PmOption o : pmAttr.getOptionSet().getOptions()) {
if (!first) {
sb.append(",");
}
sb.append(o.getIdAsString());
first = false;
}
assertEquals(pmAttr.getPmRelativeName() + ": option ids", expectedIds, sb.toString());
}
/**
* Performs a checked set value operation.
* <p>
* Checks first if the given attribute is enabled.
* <p>
* After setting the value it verifies if there are no messages within the subtree of the
* given PM.
* <p>
* Verifies the the getValue() operation provides the expected value.
*
* @param attr
* the attribute to assign the value to.
* @param value
* the value to assign.
*/
public static <T> void setValue(PmAttr<T> attr, T value) {
assertEnabled(attr);
attr.setValue(value);
assertNoMessagesInSubTree(attr);
assertEquals(value, attr.getValue());
}
/**
* Performs a checked set value operation.
* <p>
* Checks first if the given attribute is enabled.
* <p>
* After setting the value it verifies if there are no messages within the subtree of the
* given PM.
* <p>
* Verifies the the getValue() operation provides the expected value.
*
* @param attr
* the attribute to assign the value to.
* @param value
* the value to assign.
*/
public static void setValueAsString(PmAttr<?> attr, String value) {
assertEnabled(attr);
attr.setValueAsString(value);
assertNoMessagesInSubTree(attr);
assertEquals(value, attr.getValueAsString());
}
/**
* Executes the given command.
* <ul>
* <li>Checks first if the command is enabled.</li>
* <li>Checks if the executed command has the state
* {@link org.pm4j.core.pm.PmCommand.CommandState#EXECUTED}.</li>
* <li>In case of an unexpected outcome it reports all messages found in the conversation.</li>
* </ul>
*
* @param cmd
* the command to execute.
*/
public static void doIt(PmCommand cmd) {
doIt(cmd.getPmRelativeName(), cmd, CommandState.EXECUTED);
}
/**
* Executes the given command.
* <ul>
* <li>Checks first if the command is enabled.</li>
* <li>Checks if the executed command has the state
* {@link org.pm4j.core.pm.PmCommand.CommandState#EXECUTED}.</li>
* <li>In case of an unexpected outcome it reports all messages found in the conversation.</li>
* </ul>
*
* @param msg
* the assert message to display if the operation fails.
* @param cmd
* the command to execute.
*/
public static void doIt(String msg, PmCommand cmd) {
doIt(msg, cmd, CommandState.EXECUTED);
}
/**
* Executes the given command.
* <ul>
* <li>Checks first if the command is enabled.</li>
* <li>Checks if the executed command has the expected execution result state.</li>
* <li>In case of an unexpected outcome it reports all messages found in the conversation.</li>
* </ul>
*
* @param cmd
* the command to execute.
* @param expectedState
* the expected execution result state.
*/
public static void doIt(PmCommand cmd, CommandState expectedState) {
doIt(cmd.getPmRelativeName(), cmd, expectedState);
}
/**
* Executes the given command.
* <ul>
* <li>Checks first if the command is enabled.</li>
* <li>Checks if the executed command has the expected execution result state.</li>
* <li>In case of an unexpected outcome it reports all messages found in the conversation.</li>
* </ul>
*
* @param msg
* the assert message to display if the operation fails.
* @param cmd
* the command to execute.
* @param expectedState
* the expected execution result state.
*/
public static void doIt(String msg, PmCommand cmd, CommandState expectedState) {
assertEnabled(cmd);
CommandState execState = cmd.doIt().getCommandState();
if (execState != expectedState) {
String msgPfx = StringUtils.isEmpty(msg) ? cmd.getPmRelativeName() : msg;
Assert.assertEquals(msgPfx + subTreeMessagesToString(" Messages: ", cmd.getPmConversation(), Severity.WARN), expectedState, execState);
}
}
// -- internal helper methods --
private static String subTreeMessagesToString(PmObject pm, Severity minSeverity) {
return subTreeMessagesToString(null, pm, minSeverity);
}
private static String subTreeMessagesToString(String msgPrefix, PmObject pm, Severity minSeverity) {
List<PmMessage> mlist = PmMessageUtil.getSubTreeMessages(pm, minSeverity);
if (mlist.isEmpty()) {
return "";
} else {
StringBuilder sb = new StringBuilder();
for (PmMessage m : mlist) {
if (sb.length() == 0) {
sb.append("\n");
}
sb.append(m.getPm().getPmRelativeName()).append(": ").append(m).append("\n");
}
return StringUtils.defaultString(msgPrefix) + sb.toString();
}
}
}
|
package org.b3mn.poem.handler;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.b3mn.poem.Identity;
import org.b3mn.poem.Representation;
import org.b3mn.poem.util.AccessRight;
import org.b3mn.poem.util.HandlerWithModelContext;
import org.b3mn.poem.util.RestrictAccess;
@HandlerWithModelContext(uri="/self", filterBrowser=true)
public class ModelHandler extends HandlerBase {
Properties props=null;
@Override
public void init() {
//Load properties
FileInputStream in;
//initialize properties from backend.properties
try {
in = new FileInputStream(this.getBackendRootDirectory() + "/WEB-INF/backend.properties");
props = new Properties();
props.load(in);
in.close();
}catch (Exception e) {
}
}
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response, Identity subject, Identity object) throws IOException {
String profileName=null;
try {
Representation representation = object.read();
String stencilSet=representation.getType();
Pattern p = Pattern.compile("/([^/]+)
Matcher matcher = p.matcher(stencilSet);
if(matcher.find()){
profileName=props.getProperty("org.b3mn.poem.handler.ModelHandler.profileFor."+matcher.group(1));
}
} catch (Exception e) {
// TODO Auto-generated catch block
}
if(profileName==null)
profileName="default";
String queryString = request.getQueryString(); // d=789
if (queryString != null) {
response.sendRedirect("/oryx/editor;"+profileName+"?"+queryString+"#"+object.getUri());
}
else{
response.sendRedirect("/oryx/editor;"+profileName+"#"+object.getUri());
}
}
@Override
@RestrictAccess(AccessRight.WRITE)
public void doPost(HttpServletRequest request, HttpServletResponse response, Identity subject, Identity object) throws IOException {
// TODO: add some error handling
Representation.update(object.getId(), null, null, request.getParameter("data"), request.getParameter("svg"));
response.setStatus(200);
}
@Override
public void doPut(HttpServletRequest request, HttpServletResponse response, Identity subject, Identity object) throws IOException {
response.setStatus(200);
}
@Override
@RestrictAccess(AccessRight.WRITE)
public void doDelete(HttpServletRequest request, HttpServletResponse response, Identity subject, Identity object) throws IOException {
object.delete();
response.setStatus(200);
}
}
|
package ae3.servlet;
import ae3.util.AtlasProperties;
import ae3.service.ArrayExpressSearchService;
import ae3.service.structuredquery.AtlasStructuredQueryService;
import ae3.service.structuredquery.AutoCompleteItem;
import ae3.service.structuredquery.GeneProperties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import org.apache.solr.core.SolrCore;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.util.RefCounted;
import org.apache.lucene.index.IndexReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.File;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.util.*;
import com.sun.org.apache.xpath.internal.NodeSet;
public class GeneListCacheServlet extends HttpServlet{
public static final int PageSize = 1000;
final private Logger log = LoggerFactory.getLogger(getClass());
public String getBasePath() {
return basePath;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
protected String basePath;
private static String getFileName(){
String BasePath = System.getProperty("java.io.tmpdir");
final String geneListFileName = BasePath + File.separator + "geneNames.xml";
return geneListFileName;
}
public static boolean done = false;
@Override
public void init() throws ServletException {
new Thread() { public void run() {
BufferedOutputStream bfind = null;
try {
bfind = new BufferedOutputStream(new FileOutputStream(getFileName()));
String letters = "0abcdefghigklmnopqrstuvwxyz";
bfind.write("<r>".getBytes());
for(int i=0; i!= letters.length(); i++ )
{
String prefix = String.valueOf(letters.charAt(i));
Collection<AutoCompleteItem> Genes = QueryIndex(prefix, PageSize);
if(prefix.equals("0"))
prefix = "num";
for(AutoCompleteItem j : Genes){
String geneName = j.getValue();
bfind.write(String.format("<%1$s>%2$s</%1$s>\n", prefix, geneName).getBytes());
}
}
bfind.write("</r>".getBytes());
}
catch(Exception ex){
log.info("ERROR creating gene names cache:"+ ex.getMessage());
}
finally {
if(null!=bfind)
try{
bfind.close();
done = true;
}
catch(Exception Ex)
{
//no op
}
}
} }.start();
}
public static Collection<AutoCompleteItem> getGenes(String prefix, Integer recordCount) throws Exception{
try{
if ((!done)|(recordCount > PageSize))
return QueryIndex(prefix, recordCount);
else{
Collection<AutoCompleteItem> result = new ArrayList<AutoCompleteItem>();
XPath xpath = XPathFactory.newInstance().newXPath();
if(prefix.equals("0"))
prefix = "num";
String expression = "/r/" +prefix;
InputSource inputSource = new InputSource(getFileName());
Object nodes1 = xpath.evaluate(expression, inputSource, XPathConstants.NODESET);
NodeList nodes = (NodeList) nodes1;
for(int i=0; i!= nodes.getLength(); i++)
{
Node n = nodes.item(i);
String name = n.getTextContent();
Long count = 1L;
AutoCompleteItem ai = new AutoCompleteItem(name,name,name,count);
result.add(ai);
}
return result;
}
}
catch(Exception ex)
{
///for breakpoint only
throw ex;
}
}
private static Collection<AutoCompleteItem> QueryIndex(String prefix, Integer recordCount) throws Exception{
final AtlasStructuredQueryService service = ae3.service.ArrayExpressSearchService.instance().getStructQueryService();
Collection<AutoCompleteItem> Genes = service.getGeneListHelper().autoCompleteValues(GeneProperties.GENE_PROPERTY_NAME,prefix,recordCount,null);
//AZ:2008-07-07 "0" means all numbers
if(prefix.equals("0"))
{
for(int i =1; i!=10; i++ )
{
Genes.addAll((service.getGeneListHelper().autoCompleteValues(GeneProperties.GENE_PROPERTY_NAME,String.valueOf(i) ,recordCount,null)));
}
}
ArrayList<AutoCompleteItem> result = new ArrayList<AutoCompleteItem>();
for(AutoCompleteItem a : Genes)
{
String s = a.getValue();
int iPos = Collections.binarySearch(result, a, new Comparator<AutoCompleteItem>() {
public int compare(AutoCompleteItem t1, AutoCompleteItem t2){
return t1.getValue().compareTo( t2.getValue() );
}
});
if(iPos<0)
result.add(-1*(iPos+1),a);
}
return result;
}
//return result; //new LinkedHashSet<AutoCompleteItem>(Genes);
}
|
package com.redhat.ceylon.cmr.api;
public class ArtifactLookup {
private String name;
private Type type;
public enum Type {
SRC(ArtifactContext.SRC),
JVM(ArtifactContext.CAR, ArtifactContext.JAR),
JS(ArtifactContext.JS);
private String[] suffixes;
Type(String... suffixes){
this.suffixes = suffixes;
}
public String[] getSuffixes() {
return suffixes;
}
}
public ArtifactLookup(String name, Type type){
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Type getType() {
return type;
}
public void setType(Type type) {
this.type = type;
}
}
|
package csgoscraper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.concurrent.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
import static csgoscraper.Database.*;
public class Main {
// Scraping settings
static String userAgent = "useragent";
static int i = 10; // Scraping timer in minutes
static int subcide = 0; // Amount of subcid errors
static int teame = 0; // Amount of team errors
static int updatecount;
static int matchcount;
static ArrayList<Integer> scrapedodds1 = new ArrayList<>();
static ArrayList<Integer> scrapedodds2 = new ArrayList<>();
static ArrayList<String> scrapedlinks = new ArrayList<>();
static ArrayList<Integer> scrapedtid1 = new ArrayList<>();
static ArrayList<Integer> scrapedtid2 = new ArrayList<>();
static int sz;
// Scrape for matches then insert or update
public static void getmatches() {
updatecount = 0;
matchcount = 0;
String gettime = getNextTime();
// Reset arraylists
ArrayList<String> scrapedteam1 = new ArrayList<>();
ArrayList<String> scrapedteam2 = new ArrayList<>();
ArrayList<String> matchpages = new ArrayList<>();
ArrayList<String> incommatches = new ArrayList<>();
scrapedodds1 = new ArrayList<>();
scrapedodds2 = new ArrayList<>();
scrapedtid1 = new ArrayList<>();
scrapedtid2 = new ArrayList<>();
scrapedlinks = new ArrayList<>();
//Hltv scraper
try {
// Connect to scrape page
Document doc = Jsoup.connect("http:
// Scrape for links in div.center and add to arraylist
Elements links = doc.select("div.center a");
for (Element link : links) {
String href = link.attr("href").substring(0, 15);
String match = ("http:
matchpages.add(match);
}
} catch (IOException e) {
//e.printStackTrace();
System.out.println(e + " for hltv");
}
//csgolounge scraper
try {
// Connect to scrape page
Document doc = Jsoup.connect("http:
// Scrape matchlinks
Elements links = doc.select("div.match a[href]");
for (Element link : links) {
String scraped = link.attr("href");
if(scraped.contains("predict")){}
else {
scrapedlinks.add(scraped);
}
}
// Scrape teams
Elements teams = doc.select("div.match div.teamtext b");
int count = 0;
for (Element team : teams) {
String scraped = team.text();
count++;
if(count % 2 != 0) {scrapedteam1.add(scraped);}
else{scrapedteam2.add(scraped);}
}
// Convert to teamids
for(int s = 0; s < scrapedteam1.size(); s++){
int stid1 = selectTid(scrapedteam1.get(s));
int stid2 = selectTid(scrapedteam2.get(s));
scrapedtid1.add(stid1);
scrapedtid2.add(stid2);
}
sz = scrapedtid1.size();
// Scrape odds
Elements odds = doc.select("div.match div.teamtext i");
count = 0;
for (Element odd : odds) {
String scraped = odd.text();
String scrapeodds = "0";
count++;
switch (scraped.length()) {
case 2: scrapeodds = scraped.substring(0,1); break;
case 3: scrapeodds = scraped.substring(0,2); break;
case 4: scrapeodds = scraped.substring(0,3); break;
default: scrapeodds = "0";
}
if(count % 2 != 0) {scrapedodds1.add(Integer.parseInt(scrapeodds));}
else{scrapedodds2.add(Integer.parseInt(scrapeodds));}
}
}
catch (IOException e) {
//e.printStackTrace();
System.out.println(e + " for csgolounge");
}
// Update matches
incommatches = getIncomplete(); // Get list of incomplete matches
System.out.println(incommatches.size()+" active matches");
for (int j = 0; j < incommatches.size(); j++ ){
scrapepage("Update", incommatches.get(j));
}
// Add matches
for (int i = 0; i < matchpages.size(); i++){
if (!checkMatchExist(matchpages.get(i))) {
scrapepage("Insert", matchpages.get(i));}
}
int counterrors = teame+subcide;
System.out.println("");
System.out.println(matchcount+" new matches added");
System.out.println(updatecount+" matches updated");
System.out.println("Errors: " + counterrors);
System.out.println("Team: "+ teame);
System.out.println("Competition errors: "+ subcide);
System.out.println(gettime);
}
/** scrape matchpage, then insert or update
* @param whatdo - Whether to insert or update row
* @param page - hltv matchpage
*/
public static void scrapepage(String whatdo, String page){
ArrayList<String> scrapeteams= new ArrayList<>();
ArrayList<String> scrapemaps= new ArrayList<>();
ArrayList<String> scrapescores= new ArrayList<>();
String stringdate;
String stringtime;
try {
// Connect to hltv matchpage
Document matchpage = Jsoup.connect(page).userAgent(userAgent).get();
// Scrape for teams and add to arraylist
Elements teams = matchpage.select("div.centerfade span a.nolinkstyle");
for (Element team : teams) {
scrapeteams.add(team.text());
}
// Errorhandling for unknown team names and empty list
if(scrapeteams.isEmpty()){scrapeteams.add("TBD");scrapeteams.add("TBD");}
if(selectTid(scrapeteams.get(0)) == 0){scrapeteams.set(0, "TBD"); teame++;}
if(selectTid(scrapeteams.get(1)) == 0){scrapeteams.set(1, "TBD"); teame++;}
// Get date
Elements sd = matchpage.select("div[style=padding:5px;] span[style=font-size:14px;]");
stringdate = sd.text();
// Get time
Elements time = matchpage.select("div[style=padding:5px;] span[style=margin-left:10px;]");
stringtime= time.text();
// Get competition
Elements comp = matchpage.select("div[style=padding:5px;] div[style=text-align:center;font-size: 18px;] a");
String competition = comp.text();
int subcid = selectSubcid(competition);
if(subcid == 0){
int checkcomp = frequentcomp(competition);
if(checkcomp == 0) {
subcid = 71; // filler
}
else{
subcid = checkcomp;
}
}
// Get maps
Elements maps = matchpage.select("div[style=border: 1px" +
" solid darkgray;" +
"border-radius: 5px;" +
"width:280px;" +
"height:28px;" +
"margin-bottom:3px;] img");
for (Element map : maps) {
scrapemaps.add(map.absUrl("src"));
}
int bo = 0;
bo = scrapemaps.size();
// Get scores
Elements scores = matchpage.select("div.hotmatchbox[style=margin-top: -7px;" +
"font-size: 12px;" +
"width:270px;" +
"border-top:0;]");
for (Element score : scores) {
String[] parts = regexfinder(score.text(), "^[\\d]{1,2}:[\\d]{1,2}").split(":");
scrapescores.add(parts[0]);
scrapescores.add(parts[1]);
}
// Errorhandling for scores if no scores found for map x
if(scrapescores.size() < bo * 2){
while(scrapescores.size() < bo * 2)
{
scrapescores.add("0");
}
}
// Get database variables
int tid1 = selectTid(scrapeteams.get(0)); // Get team id instead of teamname
int tid2 = selectTid(scrapeteams.get(1));
stringdate = formatdate(stringdate); // Formatdate to proper database format
// Get odds
int odds1 = 0;
int odds2 = 0;
String csgllink = null;
for(int k = 0; k < sz; k++){
if(tid1 == scrapedtid1.get(k) && tid2 == scrapedtid2.get(k)){
odds1 = scrapedodds1.get(k);
odds2 = scrapedodds2.get(k);
csgllink = "http://csgolounge.com/".concat(scrapedlinks.get(k));
}
else if(tid2 == scrapedtid1.get(k) && tid1 == scrapedtid2.get(k)) {
odds2 = scrapedodds1.get(k);
odds1 = scrapedodds2.get(k);
csgllink = "http://csgolounge.com/".concat(scrapedlinks.get(k));
}
}
if(bo != 0 && bo > 0 && bo < 8) {
// Insert match
if (whatdo.equals("Insert")) {
for (int k = 0; k < bo; k++) {
insert(tid1,
tid2,
stringdate,
stringtime,
selectMapid(selectMapname(scrapemaps.get(k))),
subcid,
csgllink,
odds1,
odds2,
page
);
}
System.out.println("Match added: " + scrapeteams.get(0) + " - " + scrapeteams.get(1));
matchcount++;
}
// Update match
else {
int mid = selectmid(page);
if (mid != 0) {
int t1wins = 0;
int t2wins = 0;
for (int k = 0; k < bo; k++) {
int score1;
int score2;
if (k > 0) { // if not first match
score1 = Integer.parseInt(scrapescores.get(2 * k));
score2 = Integer.parseInt(scrapescores.get(2 * k + 1));
} else { // If first match
score1 = Integer.parseInt(scrapescores.get(0));
score2 = Integer.parseInt(scrapescores.get(1));
}
int mapid = selectMapid(selectMapname(scrapemaps.get(k)));
int complete = 0;
if((score1 > score2 && score1 > 14) || (score1 == 1 && score2 == 0 && mapid == 10 )){
t1wins++;
complete = 1;
}
if((score2 > score1 && score2 > 14) || (score1 == 2 && score2 == 1 && mapid == 10)){
t2wins++;
complete = 1;
}
if(bo == 3 && (t1wins == 2 || t2wins == 2)) {complete = 1;}
update(
tid1,
odds1,
tid2,
odds2,
stringdate,
stringtime,
mapid,
score1,
score2,
subcid,
csgllink,
mid,
complete
);
mid++;
}
System.out.println("Updated: " + scrapeteams.get(0) + " vs " + scrapeteams.get(1));
updatecount++;
}
else{System.out.println("MID ERROR");}
}
}
}catch (IOException e) {
// e.printStackTrace();
System.out.println(e + " for hltv matchpage");
}
}
/** formats date to database format
* @param inputdate - any date format
* @return String - formatted date
*/
public static String formatdate(String inputdate) {
inputdate = inputdate.replaceAll("( of)", "");
String returndate = null;
Date parsedDate;
String[] formats = {"d'st' MMMM yyyy","d'nd' MMMM yyyy","d'rd' MMMM yyyy","d'th' MMMM yyyy"};
ParsePosition position = new ParsePosition(0);
for (String format : formats)
{
position.setIndex(0);
position.setErrorIndex(-1);
// no ParseException but a null return instead
parsedDate = new SimpleDateFormat(format, Locale.ENGLISH).parse(inputdate, position);
if (parsedDate != null) {
SimpleDateFormat date_formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
returndate = date_formatter.format(parsedDate);
}
}
return returndate;
}
/** print next scrape time
* @return String - time + 10 minutes
*/
public static String getNextTime(){
DateFormat nextformat = new SimpleDateFormat("HH:mm:ss");
Calendar next = Calendar.getInstance();
next.add(Calendar.MINUTE, i);
String time = "Next scrape at: "+nextformat.format(next.getTime());
return time;
}
/**
*
* @param text - Text to find pattern in
* @param tofindregex - regex pattern
* @return String - Found text fitting regex pattern
*/
public static String regexfinder(String text, String tofindregex){
Pattern pat = Pattern.compile(tofindregex); // Regex pattern
Matcher match = pat.matcher(text);
String result = null;
while (match.find()) {
result = match.group();
}
return result;
}
public static String selectMapname(String imgsrc){
String mapname = "TBA";
switch (imgsrc){
case "http://static.hltv.org//images/hotmatch/default.png": mapname = "Unplayed"; break;
case "http://static.hltv.org//images/hotmatch/tba.png": mapname = "TBA"; break;
case "http://static.hltv.org//images/hotmatch/mirage.png": mapname = "de_mirage"; break;
case "http://static.hltv.org//images/hotmatch/cache.png": mapname = "de_cache"; break;
case "http://static.hltv.org//images/hotmatch/cobblestone.png": mapname = "de_cbble"; break;
case "http://static.hltv.org//images/hotmatch/dust2.png": mapname = "de_dust_2"; break;
case "http://static.hltv.org//images/hotmatch/nuke.png": mapname = "de_nuke"; break;
case "http://static.hltv.org//images/hotmatch/season.png": mapname = "de_season"; break;
case "http://static.hltv.org//images/hotmatch/inferno.png": mapname = "de_inferno"; break;
case "http://static.hltv.org//images/hotmatch/overpass.png": mapname = "de_overpass"; break;
case "http://static.hltv.org//images/hotmatch/train.png": mapname = "de_train"; break;
}
return mapname;
}
// Automatically add and link frequent competitions
public static int frequentcomp(String comp){
int tmp = 0;
if(comp.contains("QuickShot")){tmp = addsubcomp(comp); addcomplink(72, tmp);}
if(comp.contains("ESL")){ tmp = addsubcomp(comp); addcomplink(6, tmp);}
if(comp.contains("ESL ESEA")){ tmp = addsubcomp(comp); addcomplink(45, tmp);}
if(comp.contains("FACEIT")){ tmp = addsubcomp(comp); addcomplink(11, tmp);}
if(comp.contains("CEVO")){ tmp = addsubcomp(comp); addcomplink(2, tmp);}
if(comp.contains("DreamHack")){tmp = addsubcomp(comp); addcomplink(3, tmp);}
if(comp.contains("ESWC")){ tmp = addsubcomp(comp); addcomplink(50, tmp);}
if(comp.contains("D!ngIT")){ tmp = addsubcomp(comp); addcomplink(40, tmp);}
return tmp;
}
// Runner that runs the program
public static Runnable runner = new Runnable() {
public void run() {
long start_time = System.currentTimeMillis();
teame = 0; // Reset team errors
subcide = 0; // Reset competition errors
getmatches();
long elapsed = 0;
do {
elapsed = 600000 - (System.currentTimeMillis() - start_time) - 10000;
System.out.print("Enter command:");
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Task());
try {
future.get(elapsed, TimeUnit.MILLISECONDS);
future.cancel(true);
executor.shutdownNow();
} catch (TimeoutException e) {
future.cancel(true);
executor.shutdownNow();
System.out.print(" Locked\n");
break;
} catch (InterruptedException e) {
e.printStackTrace();
future.cancel(true);
break;
} catch (ExecutionException e) {
e.printStackTrace();
future.cancel(true);
break;
}
executor.shutdownNow();
future.cancel(true);
}
while(elapsed > 5000);
}
};
public static void main(String[] args) {
// Start runner every i minute
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.scheduleAtFixedRate(runner, 0, i, TimeUnit.MINUTES);
}
}
|
public class Main {
public static void fitness(Individual a) {
int j[]=decode(a.gene);
a.fitness = 1-Math.abs(j[0]-dlt.getOxygenLevel())*0.005-Math.abs(j[1]-dlt.getHumidity())*0.01-Math.abs(j[2]-dlt.getFood())*0.1-Math.abs(j[3]-dlt.getTemperature())*0.01+0.1*j[4]+0.1*j[5];
}
public static int[] decode(boolean[][] a) {
int[] h=new int[a.length];
for(int i=0;i<a.length;i++){
int j=0;
for(int k=0;k<a[i].length;k++) if(a[i][k]) if(k>0) j+=2*k; else j+=1;
switch (i) {
case 0:
continue;
case 1:
h[i]=j*10;
continue;
default:
h[i]=j+1;
}
}
return h;
}
private static Population pop;
private static Environment dlt;
public static void main(String args[]){
//Set up population
dlt=new Environment();
Fenestra allah = new Fenestra(dlt);
while(Fenestra.connection==0)
{
}
pop = new Population(100);
double lastBestFitness = 0.0;
while(true){
for (int i = 0; i< Population.setOfIndividual.size(); i++){
fitness((Individual) Population.setOfIndividual.get(i));
}
//Individual temp = (Individual)(Population.setOfIndividual.firstElement());
Individual[] beforeSort=new Individual[Population.setOfIndividual.size()];
for(int i=0;i<Population.setOfIndividual.size();i++){
beforeSort[i]=(Individual) Population.setOfIndividual.get(i);
}
Individual[] afterSort=new Individual[Population.setOfIndividual.size()];
Quick.sort(beforeSort,0,Population.setOfIndividual.size()-1,afterSort);
for(int j=0;j<afterSort.length;j++){
System.out.println(afterSort[j].fitness);
}
//Vector
Population.setOfIndividual.clear();
for (Individual a : afterSort)
Population.setOfIndividual.add(a);
//0.01
Individual Best = (Individual)(Population.setOfIndividual.lastElement());
if(Best.getFitness()-lastBestFitness<0.001)
if(Best.getFitness()<lastBestFitness) {
System.out.println("**");
lastBestFitness = Best.getFitness();
System.out.println("————————————");
}
else{
System.out.println("");
EndFenestra aallah = new EndFenestra();
break;
}
else{
lastBestFitness = Best.getFitness();
System.out.println("————————————");
}
for(int i = Population.setOfIndividual.capacity()/2 -1; i< Population.setOfIndividual.size(); )
Population.setOfIndividual.remove(0);
int reproduceSize = Population.setOfIndividual.size();
while(Population.setOfIndividual.size() < Population.setOfIndividual.capacity() && reproduceSize!=0){
for(int i = 0;i<reproduceSize-1;i+=2){
Population.setOfIndividual.add(Event.reproduce((Individual) Population.setOfIndividual.get(i),(Individual) Population.setOfIndividual.get(i+1)));
}
reproduceSize /= 2 ;
if(reproduceSize <= 1)
Population.setOfIndividual.add(Event.reproduce((Individual) Population.setOfIndividual.get(Population.setOfIndividual.size()-1),(Individual) Population.setOfIndividual.get(Population.setOfIndividual.size()-2)));
}
}
}
}
|
package com.civilizer.extra.tools;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.Point;
import java.awt.PopupMenu;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
//import java.awt.event.MouseAdapter;
//import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
//import javax.swing.ImageIcon;
//import javax.swing.JMenuItem;
//import javax.swing.JPopupMenu;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.resource.ResourceCollection;
import org.eclipse.jetty.webapp.WebAppContext;
import com.civilizer.config.Configurator;
import com.civilizer.utils.FsUtil;
public final class Launcher {
private static final String PORT = "civilizer.port";
private static final String STATUS = "civilizer.status";
private static final String BROWSE_AT_STARTUP = "civilizer.browse_at_startup";
private static final String STARTING = "Starting Civilizer...";
private static final String RUNNING = "Civilizer is running...";
private static Font fontForIcon;
private final Server server;
private final int port;
private enum LogType {
INFO,
WARN,
ERROR,
}
public static void main(String[] args) {
try {
System.setProperty(STATUS, STARTING);
System.setProperty(PORT, "");
setupSystemTray();
int port = 8080;
Arrays.sort(args);
final int iii = Arrays.binarySearch(args, "--port");
if (-1 < iii && iii < args.length-1) {
try {
port = Integer.parseInt(args[iii + 1]);
if (port <= 0)
throw new NumberFormatException();
} catch (NumberFormatException e) {
l(LogType.ERROR, "'" + port + "' is not a valid port number. exiting...");
System.exit(1);
}
}
new Launcher(port).startServer();
} catch (Exception e) {
l(LogType.ERROR, "An unhandled exception triggered. exiting...");
e.printStackTrace();
System.exit(1);
}
}
private static String getCvzUrl() {
final String portStr = System.getProperty(PORT);
assert portStr.isEmpty() == false;
int port = 0;
try {
port = Integer.parseInt(portStr);
} catch (NumberFormatException e) {
throw new Error(e);
}
return "http://localhost:" + port + "/civilizer/app/home";
}
private static String getFullJarPath(final Pattern pattern){
for(final String element : System.getProperty("java.class.path", ".").split("[:;]")){
if (pattern.matcher(element).matches())
return element;
}
return null;
}
private static String getResourcePathFromJarFile(final File file, final Pattern pattern){
try (ZipFile zf = new ZipFile(file);){
final Enumeration<?> e = zf.entries();
while(e.hasMoreElements()){
final ZipEntry ze = (ZipEntry) e.nextElement();
final String fileName = ze.getName();
if(pattern.matcher(fileName).matches())
return fileName;
}
} catch(final IOException e){
e.printStackTrace();
throw new Error(e);
}
return "";
}
private static Font createFont() {
final String tgtJarPath = getFullJarPath(Pattern.compile(".*primefaces.*\\.jar"));
final String fontPath = getResourcePathFromJarFile(new File(tgtJarPath), Pattern.compile(".*/fontawesome-webfont\\.ttf"));
assert fontPath.isEmpty() == false;
final InputStream is = Launcher.class.getClassLoader().getResourceAsStream(fontPath);
assert is != null;
Font font;
try {
font = Font.createFont(Font.TRUETYPE_FONT, is);
} catch (FontFormatException e) {
e.printStackTrace();
throw new Error(e);
} catch (IOException e) {
e.printStackTrace();
throw new Error(e);
}
return font.deriveFont(Font.PLAIN, 24f);
}
private static Point calcDrawPoint(Font font, String icon, int size, Graphics2D graphics) {
int center = size / 2; // Center X and Center Y are the same
Rectangle stringBounds = graphics.getFontMetrics().getStringBounds(icon, graphics).getBounds();
Rectangle visualBounds = font.createGlyphVector(graphics.getFontRenderContext(), icon).getVisualBounds().getBounds();
return new Point(center - stringBounds.width / 2, center - visualBounds.height / 2 - visualBounds.y);
}
private static Image createFontIcon(Font font, String code, Color clr) {
final int iconSize = 24;
final BufferedImage img = new BufferedImage(iconSize, iconSize, BufferedImage.TYPE_INT_ARGB);
final Graphics2D graphics = img.createGraphics();
graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
graphics.setColor(clr);
graphics.setFont(font);
final String icon = code;
final Point pt = calcDrawPoint(font, icon, iconSize, graphics);
graphics.drawString(icon, pt.x, pt.y);
graphics.dispose();
return img;
}
private static void setupSystemTray() {
if (SystemTray.isSupported() == false)
return;
fontForIcon = createFont();
final Image img = createFontIcon(fontForIcon, "\uf19c", new Color(0xff, 0x0, 0x0));
EventQueue.invokeLater(
new Runnable() {
public void run() {
final SystemTray tray = SystemTray.getSystemTray();
assert tray != null;
assert img != null;
// final TrayIcon trayIcon = new TrayIcon(img, STARTING, null);
// trayIcon.setImageAutoSize(true);
// final JPopupMenu jpopup = new JPopupMenu();
// JMenuItem javaCupMI = new JMenuItem("Example", new ImageIcon("javacup.gif"));
// jpopup.add(javaCupMI);
// jpopup.addSeparator();
// JMenuItem exitMI = new JMenuItem("Exit");
// jpopup.add(exitMI);
// trayIcon.addMouseListener(new MouseAdapter() {
// public void mouseReleased(MouseEvent e) {
// if (e.getButton() == MouseEvent.BUTTON1) {
// jpopup.setLocation(e.getX(), e.getY());
// jpopup.setInvoker(null);
// jpopup.setVisible(true);
PopupMenu popup = new PopupMenu();
final TrayIcon trayIcon = new TrayIcon(img, STARTING, popup);
trayIcon.setImageAutoSize(true);
MenuItem item;
item = new MenuItem("\u2716 Shutdown");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
tray.remove(trayIcon);
System.exit(0);
}
});
popup.add(item);
try {
tray.add(trayIcon);
} catch (AWTException e) {
e.printStackTrace();
throw new Error(e);
}
}
}
); // EventQueue.invokeLater()
}
private static void updateSystemTray() {
// We change appearance of the system tray icon to notify that the server is ready.
// Also add extra menus.
if (SystemTray.isSupported() == false)
return;
for (TrayIcon icon : SystemTray.getSystemTray().getTrayIcons()) {
if (icon.getToolTip().equals(STARTING)) {
assert fontForIcon != null;
final Image img = createFontIcon(fontForIcon, "\uf19c", new Color(0xf0, 0xff, 0xff));
icon.setImage(img);
icon.setToolTip(RUNNING);
MenuItem item = new MenuItem("\u270d Browse");
item.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openBrowser();
}
});
icon.getPopupMenu().insert(item, 0);
break;
}
}
}
private static void openBrowser() {
if (System.getProperty(PORT).isEmpty() || ! System.getProperty(STATUS).equals(RUNNING))
return;
final String url = getCvzUrl();
try {
Desktop.getDesktop().browse(new URI(url));
} catch (IOException e1) {
e1.printStackTrace();
} catch (URISyntaxException e1) {
e1.printStackTrace();
}
}
private static void l(LogType type, String msg) {
System.out.println(MessageFormat.format("{0} : [{1}] {2}", Launcher.class.getSimpleName(), type.toString(), msg));
}
private Launcher(int port) {
assert 0 < port && port <= 0xffff;
server = new Server(port);
assert server != null;
this.port = port;
}
private boolean setupWebAppContextForDevelopment(WebAppContext waCtxt) {
if (!FsUtil.exists("pom.xml"))
return false;
final String webAppDir = FsUtil.concatPath("src", "main", "webapp");
final String tgtDir = "target";
final String webXmlFile = FsUtil.concatPath(webAppDir, "WEB-INF", "web.xml");
if (!FsUtil.exists(webAppDir) || !FsUtil.exists(tgtDir) || !FsUtil.exists(webXmlFile))
return false;
waCtxt.setBaseResource(new ResourceCollection(
new String[] { webAppDir, tgtDir }
));
waCtxt.setResourceAlias("/WEB-INF/classes/", "/classes/");
waCtxt.setDescriptor(webXmlFile);
l(LogType.INFO, "Running under the development environment...");
return true;
}
private boolean setupWebAppContextForProduction(WebAppContext waCtxt) {
final File usrDir = new File(System.getProperty("user.dir"));
final File[] pkgs = usrDir.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return (pathname.isDirectory() && pathname.getName().startsWith("civilizer"));
}
});
for (File pkg : pkgs) {
final String pkgPath = pkg.getAbsolutePath();
if (FsUtil.exists(pkgPath, "WEB-INF", "web.xml") == false
|| FsUtil.exists(pkgPath, "WEB-INF", "classes") == false
|| FsUtil.exists(pkgPath, "WEB-INF", "lib") == false
)
continue;
waCtxt.setWar(pkgPath);
return true;
}
return false;
}
private WebAppContext setupWebAppContext() {
final WebAppContext waCtxt = new WebAppContext();
waCtxt.setContextPath("/civilizer");
if (! setupWebAppContextForProduction(waCtxt))
if (! setupWebAppContextForDevelopment(waCtxt))
return null;
return waCtxt;
}
private void startServer() throws Exception {
assert server != null;
final WebAppContext waCtxt = setupWebAppContext();
assert waCtxt != null;
server.setHandler(waCtxt);
server.setStopAtShutdown(true);
server.start();
System.setProperty(STATUS, RUNNING);
System.setProperty(PORT, new Integer(port).toString());
assert System.getProperty(PORT).equals(new Integer(port).toString());
l(LogType.INFO, "Civilizer is running... access to " + getCvzUrl());
updateSystemTray();
if (Configurator.isTrue(BROWSE_AT_STARTUP)) {
openBrowser();
}
server.join();
}
}
|
package com.samourai.wallet.home;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.transition.ChangeBounds;
import android.support.transition.TransitionManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.dm.zbar.android.scanner.ZBarConstants;
import com.samourai.wallet.ExodusActivity;
import com.samourai.wallet.JSONRPC.JSONRPC;
import com.samourai.wallet.JSONRPC.PoW;
import com.samourai.wallet.JSONRPC.TrustedNodeUtil;
import com.samourai.wallet.R;
import com.samourai.wallet.ReceiveActivity;
import com.samourai.wallet.SamouraiActivity;
import com.samourai.wallet.SamouraiWallet;
import com.samourai.wallet.SettingsActivity;
import com.samourai.wallet.access.AccessFactory;
import com.samourai.wallet.api.APIFactory;
import com.samourai.wallet.api.Tx;
import com.samourai.wallet.bip47.BIP47Meta;
import com.samourai.wallet.bip47.BIP47Util;
import com.samourai.wallet.cahoots.Cahoots;
import com.samourai.wallet.cahoots.CahootsUtil;
import com.samourai.wallet.crypto.AESUtil;
import com.samourai.wallet.crypto.DecryptionException;
import com.samourai.wallet.fragments.CameraFragmentBottomSheet;
import com.samourai.wallet.hd.HD_Wallet;
import com.samourai.wallet.hd.HD_WalletFactory;
import com.samourai.wallet.home.adapters.TxAdapter;
import com.samourai.wallet.network.NetworkDashboard;
import com.samourai.wallet.network.dojo.DojoUtil;
import com.samourai.wallet.payload.PayloadUtil;
import com.samourai.wallet.paynym.ClaimPayNymActivity;
import com.samourai.wallet.paynym.PayNymHome;
import com.samourai.wallet.permissions.PermissionsUtil;
import com.samourai.wallet.ricochet.RicochetMeta;
import com.samourai.wallet.segwit.bech32.Bech32Util;
import com.samourai.wallet.send.BlockedUTXO;
import com.samourai.wallet.send.MyTransactionOutPoint;
import com.samourai.wallet.send.SendActivity;
import com.samourai.wallet.send.SweepUtil;
import com.samourai.wallet.send.UTXO;
import com.samourai.wallet.send.cahoots.ManualCahootsActivity;
import com.samourai.wallet.service.JobRefreshService;
import com.samourai.wallet.service.WebSocketService;
import com.samourai.wallet.tor.TorManager;
import com.samourai.wallet.tor.TorService;
import com.samourai.wallet.tx.TxDetailsActivity;
import com.samourai.wallet.util.AppUtil;
import com.samourai.wallet.util.CharSequenceX;
import com.samourai.wallet.util.FormatsUtil;
import com.samourai.wallet.util.MessageSignUtil;
import com.samourai.wallet.util.MonetaryUtil;
import com.samourai.wallet.util.PrefsUtil;
import com.samourai.wallet.util.PrivKeyReader;
import com.samourai.wallet.util.TimeOutUtil;
import com.samourai.wallet.utxos.UTXOSActivity;
import com.samourai.wallet.whirlpool.WhirlpoolMain;
import com.samourai.wallet.whirlpool.WhirlpoolMeta;
import com.samourai.wallet.whirlpool.service.WhirlpoolNotificationService;
import com.samourai.wallet.widgets.ItemDividerDecorator;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.crypto.BIP38PrivateKey;
import org.bitcoinj.crypto.MnemonicException;
import org.bitcoinj.script.Script;
import org.bouncycastle.util.encoders.Hex;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Collections;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.List;
import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class BalanceActivity extends SamouraiActivity {
private final static int SCAN_COLD_STORAGE = 2011;
private final static int SCAN_QR = 2012;
private static final String TAG = "BalanceActivity";
private List<Tx> txs = null;
private RecyclerView TxRecyclerView;
private ProgressBar progressBar;
private BalanceViewModel balanceViewModel;
private PoWTask powTask = null;
private RicochetQueueTask ricochetQueueTask = null;
private com.github.clans.fab.FloatingActionMenu menuFab;
private SwipeRefreshLayout txSwipeLayout;
private CollapsingToolbarLayout mCollapsingToolbar;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
private Toolbar toolbar;
private Menu menu;
private ImageView menuTorIcon;
private ProgressBar progressBarMenu;
private View whirlpoolFab, sendFab, receiveFab, paynymFab;
public static final String ACTION_INTENT = "com.samourai.wallet.BalanceFragment.REFRESH";
protected BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, Intent intent) {
if (ACTION_INTENT.equals(intent.getAction())) {
if (progressBar != null) {
progressBar.setVisibility(View.VISIBLE);
}
final boolean notifTx = intent.getBooleanExtra("notifTx", false);
final boolean fetch = intent.getBooleanExtra("fetch", false);
final String rbfHash;
final String blkHash;
if (intent.hasExtra("rbf")) {
rbfHash = intent.getStringExtra("rbf");
} else {
rbfHash = null;
}
if (intent.hasExtra("hash")) {
blkHash = intent.getStringExtra("hash");
} else {
blkHash = null;
}
Handler handler = new Handler();
handler.post(() -> {
refreshTx(notifTx, false, false);
if (BalanceActivity.this != null) {
if (rbfHash != null) {
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(rbfHash + "\n\n" + getString(R.string.rbf_incoming))
.setCancelable(true)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
doExplorerView(rbfHash);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
}).show();
}
}
});
if (BalanceActivity.this != null && blkHash != null && PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.USE_TRUSTED_NODE, false) == true && TrustedNodeUtil.getInstance().isSet()) {
// BalanceActivity.this.runOnUiThread(new Runnable() {
// @Override
handler.post(new Runnable() {
public void run() {
if (powTask == null || powTask.getStatus().equals(AsyncTask.Status.FINISHED)) {
powTask = new PoWTask();
powTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, blkHash);
}
}
});
}
}
}
};
public static final String DISPLAY_INTENT = "com.samourai.wallet.BalanceFragment.DISPLAY";
protected BroadcastReceiver receiverDisplay = new BroadcastReceiver() {
@Override
public void onReceive(final Context context, Intent intent) {
if (DISPLAY_INTENT.equals(intent.getAction())) {
updateDisplay(true);
List<UTXO> utxos = APIFactory.getInstance(BalanceActivity.this).getUtxos(false);
for (UTXO utxo : utxos) {
List<MyTransactionOutPoint> outpoints = utxo.getOutpoints();
for (MyTransactionOutPoint out : outpoints) {
byte[] scriptBytes = out.getScriptBytes();
String address = null;
try {
if (Bech32Util.getInstance().isBech32Script(Hex.toHexString(scriptBytes))) {
address = Bech32Util.getInstance().getAddressFromScript(Hex.toHexString(scriptBytes));
} else {
address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
}
} catch (Exception e) {
}
String path = APIFactory.getInstance(BalanceActivity.this).getUnspentPaths().get(address);
if (path != null && path.startsWith("M/1/")) {
continue;
}
final String hash = out.getHash().toString();
final int idx = out.getTxOutputN();
final long amount = out.getValue().longValue();
if (amount < BlockedUTXO.BLOCKED_UTXO_THRESHOLD &&
!BlockedUTXO.getInstance().contains(hash, idx) &&
!BlockedUTXO.getInstance().containsNotDusted(hash, idx)) {
// BalanceActivity.this.runOnUiThread(new Runnable() {
// @Override
Handler handler = new Handler();
handler.post(new Runnable() {
public void run() {
String message = BalanceActivity.this.getString(R.string.dusting_attempt);
message += "\n\n";
message += BalanceActivity.this.getString(R.string.dusting_attempt_amount);
message += " ";
message += Coin.valueOf(amount).toPlainString();
message += " BTC\n";
message += BalanceActivity.this.getString(R.string.dusting_attempt_id);
message += " ";
message += hash + "-" + idx;
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.dusting_tx)
.setMessage(message)
.setCancelable(false)
.setPositiveButton(R.string.dusting_attempt_mark_unspendable, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
BlockedUTXO.getInstance().add(hash, idx, amount);
}
}).setNegativeButton(R.string.dusting_attempt_ignore, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
BlockedUTXO.getInstance().addNotDusted(hash, idx);
}
});
if (!isFinishing()) {
dlg.show();
}
}
});
}
}
}
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_balance);
balanceViewModel = ViewModelProviders.of(this).get(BalanceViewModel.class);
makePaynymAvatarcache();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
TxRecyclerView = findViewById(R.id.rv_txes);
progressBar = findViewById(R.id.progressBar);
toolbar = findViewById(R.id.toolbar);
mCollapsingToolbar = findViewById(R.id.toolbar_layout);
txSwipeLayout = findViewById(R.id.tx_swipe_container);
setSupportActionBar(toolbar);
TxRecyclerView.setLayoutManager(new LinearLayoutManager(this));
Drawable drawable = this.getResources().getDrawable(R.drawable.divider);
TxRecyclerView.addItemDecoration(new ItemDividerDecorator(drawable));
menuFab = findViewById(R.id.fab_menu);
txs = new ArrayList<>();
whirlpoolFab = findViewById(R.id.whirlpool_fab);
sendFab = findViewById(R.id.send_fab);
receiveFab = findViewById(R.id.receive_fab);
paynymFab = findViewById(R.id.paynym_fab);
findViewById(R.id.whirlpool_fab).setOnClickListener(view -> {
Intent intent = new Intent(BalanceActivity.this, WhirlpoolMain.class);
startActivity(intent);
menuFab.toggle(true);
});
sendFab.setOnClickListener(view -> {
Intent intent = new Intent(BalanceActivity.this, SendActivity.class);
intent.putExtra("via_menu", true);
intent.putExtra("_account", account);
startActivity(intent);
menuFab.toggle(true);
});
setBalance(0L, false);
receiveFab.setOnClickListener(view -> {
menuFab.toggle(true);
try {
HD_Wallet hdw = HD_WalletFactory.getInstance(BalanceActivity.this).get();
if (hdw != null) {
Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class);
startActivity(intent);
}
} catch (IOException | MnemonicException.MnemonicLengthException e) {
}
});
paynymFab.setOnClickListener(view -> {
menuFab.toggle(true);
Intent intent = new Intent(BalanceActivity.this, PayNymHome.class);
startActivity(intent);
});
txSwipeLayout.setOnRefreshListener(() -> {
refreshTx(false, true, false);
txSwipeLayout.setRefreshing(false);
progressBar.setVisibility(View.VISIBLE);
});
IntentFilter filter = new IntentFilter(ACTION_INTENT);
LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter);
IntentFilter filterDisplay = new IntentFilter(DISPLAY_INTENT);
LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiverDisplay, filterDisplay);
if (!PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.READ_EXTERNAL_STORAGE) || !PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
PermissionsUtil.getInstance(BalanceActivity.this).showRequestPermissionsInfoAlertDialog(PermissionsUtil.READ_WRITE_EXTERNAL_PERMISSION_CODE);
}
if (!PermissionsUtil.getInstance(BalanceActivity.this).hasPermission(Manifest.permission.CAMERA)) {
PermissionsUtil.getInstance(BalanceActivity.this).showRequestPermissionsInfoAlertDialog(PermissionsUtil.CAMERA_PERMISSION_CODE);
}
if (PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) == true && PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, false) == false) {
doFeaturePayNymUpdate();
} else if (PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_CLAIMED, false) == false &&
PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.PAYNYM_REFUSED, false) == false) {
doClaimPayNym();
} else {
}
if (RicochetMeta.getInstance(BalanceActivity.this).getQueue().size() > 0) {
if (ricochetQueueTask == null || ricochetQueueTask.getStatus().equals(AsyncTask.Status.FINISHED)) {
ricochetQueueTask = new RicochetQueueTask();
ricochetQueueTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
}
if (!AppUtil.getInstance(BalanceActivity.this).isClipboardSeen()) {
doClipboardCheck();
}
if (!AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
}
setUpTor();
initViewModel();
progressBar.setVisibility(View.VISIBLE);
if (account == 0) {
final Handler delayedHandler = new Handler();
delayedHandler.postDelayed(() -> {
boolean notifTx = false;
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey("notifTx")) {
notifTx = extras.getBoolean("notifTx");
}
refreshTx(notifTx, false, true);
updateDisplay(false);
}, 100L);
getSupportActionBar().setIcon(R.drawable.ic_samourai_logo_toolbar);
boolean hadContentDescription = android.text.TextUtils.isEmpty(toolbar.getLogoDescription());
String contentDescription = String.valueOf(!hadContentDescription ? toolbar.getLogoDescription() : "logoContentDescription");
toolbar.setLogoDescription(contentDescription);
ArrayList<View> potentialViews = new ArrayList<View>();
toolbar.findViewsWithText(potentialViews,contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
View logoView = null;
if(potentialViews.size() > 0){
logoView = potentialViews.get(0);
logoView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intent _intent = new Intent(BalanceActivity.this, BalanceActivity.class);
_intent.putExtra("_account", WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix());
startActivity(_intent);
} });
}
balanceViewModel.loadOfflineData();
} else {
getSupportActionBar().setIcon(R.drawable.ic_samourai_logo_toolbar);
boolean hadContentDescription = android.text.TextUtils.isEmpty(toolbar.getLogoDescription());
String contentDescription = String.valueOf(!hadContentDescription ? toolbar.getLogoDescription() : "logoContentDescription");
toolbar.setLogoDescription(contentDescription);
ArrayList<View> potentialViews = new ArrayList<View>();
toolbar.findViewsWithText(potentialViews,contentDescription, View.FIND_VIEWS_WITH_CONTENT_DESCRIPTION);
View logoView = null;
if(potentialViews.size() > 0){
logoView = potentialViews.get(0);
logoView.setScaleX(-1.0f);
logoView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
Intent _intent = new Intent(BalanceActivity.this, BalanceActivity.class);
_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(_intent);
} });
}
receiveFab.setVisibility(View.GONE);
whirlpoolFab.setVisibility(View.GONE);
paynymFab.setVisibility(View.GONE);
new Handler().postDelayed(() -> updateDisplay(true), 600L);
}
updateDisplay(false);
checkDeepLinks();
}
private void checkDeepLinks() {
Bundle bundle = getIntent().getExtras();
if (bundle == null) {
return;
}
if (bundle.containsKey("pcode") || bundle.containsKey("uri") || bundle.containsKey("amount")) {
if (balanceViewModel.getBalance().getValue() != null)
bundle.putLong("balance", balanceViewModel.getBalance().getValue());
Intent intent = new Intent(this, SendActivity.class);
intent.putExtra("_account",account);
intent.putExtras(bundle);
startActivity(intent);
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}
private void initViewModel() {
TxAdapter adapter = new TxAdapter(getApplicationContext(), new ArrayList<>(), account);
adapter.setHasStableIds(true);
adapter.setClickListener((position, tx) -> txDetails(tx));
TxRecyclerView.setAdapter(adapter);
balanceViewModel.getBalance().observe(this, balance -> {
if (balance < 0) {
return;
}
if (balanceViewModel.getSatState().getValue() != null) {
setBalance(balance, balanceViewModel.getSatState().getValue());
} else {
setBalance(balance, false);
}
});
adapter.setTxes(balanceViewModel.getTxs().getValue());
setBalance(balanceViewModel.getBalance().getValue(), false);
balanceViewModel.getSatState().observe(this, state -> {
if (state == null) {
state = false;
}
setBalance(balanceViewModel.getBalance().getValue(), state);
adapter.toggleDisplayUnit(state);
});
balanceViewModel.getTxs().observe(this, new Observer<List<Tx>>() {
@Override
public void onChanged(@Nullable List<Tx> list) {
adapter.setTxes(list);
}
});
mCollapsingToolbar.setOnClickListener(view -> balanceViewModel.toggleSat());
}
private void setBalance(Long balance, boolean isSat) {
if (balance == null) {
return;
}
if (getSupportActionBar() != null) {
TransitionManager.beginDelayedTransition(mCollapsingToolbar, new ChangeBounds());
String displayAmount = "".concat(isSat ? getSatoshiDisplayAmount(balance) : getBTCDisplayAmount(balance));
String Unit = isSat ? getSatoshiDisplayUnits() : getBTCDisplayUnits();
displayAmount = displayAmount.concat(" ").concat(Unit);
toolbar.setTitle(displayAmount);
setTitle(displayAmount);
mCollapsingToolbar.setTitle(displayAmount);
}
Log.i(TAG, "setBalance: ".concat(getBTCDisplayAmount(balance)));
}
@Override
public void onResume() {
super.onResume();
// IntentFilter filter = new IntentFilter(ACTION_INTENT);
// LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter);
AppUtil.getInstance(BalanceActivity.this).checkTimeOut();
// Intent intent = new Intent("com.samourai.wallet.MainActivity2.RESTART_SERVICE");
// LocalBroadcastManager.getInstance(BalanceActivity.this).sendBroadcast(intent);
}
public View createTag(String text){
float scale = getResources().getDisplayMetrics().density;
LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
TextView textView = new TextView(getApplicationContext());
textView.setText(text);
textView.setTextColor(ContextCompat.getColor(getApplicationContext(), R.color.white));
textView.setLayoutParams(lparams);
textView.setBackgroundResource(R.drawable.tag_round_shape);
textView.setPadding((int) (8 * scale + 0.5f), (int) (6 * scale + 0.5f), (int) (8 * scale + 0.5f), (int) (6 * scale + 0.5f));
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
return textView;
}
@Override
public void onPause() {
super.onPause();
// ibQuickSend.collapse();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
}
}
private void makePaynymAvatarcache() {
try {
ArrayList<String> paymentCodes = new ArrayList<>(BIP47Meta.getInstance().getSortedByLabels(false, true));
for (String code : paymentCodes) {
Picasso.with(getBaseContext())
.load(com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + code + "/avatar").fetch(new Callback() {
@Override
public void onSuccess() {
/*NO OP*/
}
@Override
public void onError() {
/*NO OP*/
}
});
}
} catch (Exception ignored) {
}
}
@Override
public void onDestroy() {
LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver);
LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiverDisplay);
if(account == 0) {
if (AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) {
stopService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class));
}
}
super.onDestroy();
if(compositeDisposable != null && !compositeDisposable.isDisposed()) {
compositeDisposable.dispose();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
menu.findItem(R.id.action_refresh).setVisible(false);
menu.findItem(R.id.action_share_receive).setVisible(false);
menu.findItem(R.id.action_ricochet).setVisible(false);
menu.findItem(R.id.action_empty_ricochet).setVisible(false);
menu.findItem(R.id.action_sign).setVisible(false);
menu.findItem(R.id.action_fees).setVisible(false);
menu.findItem(R.id.action_batch).setVisible(false);
WhirlpoolMeta.getInstance(getApplicationContext());
if (account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix()) {
menu.findItem(R.id.action_network_dashboard).setVisible(false);
MenuItem item = menu.findItem(R.id.action_menu_account);
item.setActionView(createTag(" POST-MIX "));
item.setVisible(true);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
}
this.menu = menu;
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if(id == android.R.id.home){
this.finish();
return super.onOptionsItemSelected(item);
}
// noinspection SimplifiableIfStatement
if (id == R.id.action_network_dashboard) {
startActivity(new Intent(this, NetworkDashboard.class));
} // noinspection SimplifiableIfStatement
if (id == R.id.action_copy_cahoots) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
if(clipboard.hasPrimaryClip()) {
ClipData.Item clipItem = clipboard.getPrimaryClip().getItemAt(0);
if(Cahoots.isCahoots(clipItem.getText().toString().trim())){
Intent cahootIntent = new Intent(this, ManualCahootsActivity.class);
cahootIntent.putExtra("payload",clipItem.getText().toString().trim());
cahootIntent.putExtra("account",account);
startActivity(cahootIntent);
}else {
Toast.makeText(this,R.string.cannot_process_cahoots,Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(this,R.string.clipboard_empty,Toast.LENGTH_SHORT).show();
}
}
if (id == R.id.action_settings) {
doSettings();
} else if (id == R.id.action_support) {
doSupport();
} else if (id == R.id.action_sweep) {
if (!AppUtil.getInstance(BalanceActivity.this).isOfflineMode()) {
doSweep();
} else {
Toast.makeText(BalanceActivity.this, R.string.in_offline_mode, Toast.LENGTH_SHORT).show();
}
} else if (id == R.id.action_utxo) {
doUTXO();
} else if (id == R.id.action_backup) {
if (SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) {
try {
if (HD_WalletFactory.getInstance(BalanceActivity.this).get() != null && SamouraiWallet.getInstance().hasPassphrase(BalanceActivity.this)) {
doBackup();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.passphrase_needed_for_backup).setCancelable(false);
AlertDialog alert = builder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
if (!isFinishing()) {
alert.show();
}
}
} catch (MnemonicException.MnemonicLengthException mle) {
} catch (IOException ioe) {
}
} else {
Toast.makeText(BalanceActivity.this, R.string.passphrase_required, Toast.LENGTH_SHORT).show();
}
} else if (id == R.id.action_scan_qr) {
doScan();
} else if (id == R.id.action_postmix) {
Intent intent = new Intent(BalanceActivity.this, SendActivity.class);
intent.putExtra("_account", WhirlpoolMeta.getInstance(BalanceActivity.this).getWhirlpoolPostmix());
startActivity(intent);
} else {
;
}
return super.onOptionsItemSelected(item);
}
private void setUpTor() {
Disposable disposable = TorManager.getInstance(this)
.torStatus
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(state -> {
if (state == TorManager.CONNECTION_STATES.CONNECTED) {
PrefsUtil.getInstance(this).setValue(PrefsUtil.ENABLE_TOR, true);
if (this.progressBarMenu != null) {
this.progressBarMenu.setVisibility(View.INVISIBLE);
this.menuTorIcon.setImageResource(R.drawable.tor_on);
}
} else if (state == TorManager.CONNECTION_STATES.CONNECTING) {
if (this.progressBarMenu != null) {
this.progressBarMenu.setVisibility(View.VISIBLE);
this.menuTorIcon.setImageResource(R.drawable.tor_on);
}
} else {
if (this.progressBarMenu != null) {
this.progressBarMenu.setVisibility(View.INVISIBLE);
this.menuTorIcon.setImageResource(R.drawable.tor_off);
}
}
});
compositeDisposable.add(disposable);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) {
if (data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {
final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);
doPrivKey(strResult);
}
} else if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) {
} else if (resultCode == Activity.RESULT_OK && requestCode == SCAN_QR) {
if (data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) {
final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT);
PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(strResult.trim()));
try {
if (privKeyReader.getFormat() != null) {
doPrivKey(strResult.trim());
} else if (Cahoots.isCahoots(strResult.trim())) {
Intent cahootIntent = new Intent(this, ManualCahootsActivity.class);
cahootIntent.putExtra("_account", account);
cahootIntent.putExtra("payload", strResult.trim());
startActivity(cahootIntent);
} else if (FormatsUtil.getInstance().isPSBT(strResult.trim())) {
CahootsUtil.getInstance(BalanceActivity.this).doPSBT(strResult.trim());
} else if (DojoUtil.getInstance(BalanceActivity.this).isValidPairingPayload(strResult.trim())) {
Intent intent = new Intent(BalanceActivity.this, NetworkDashboard.class);
intent.putExtra("params", strResult.trim());
startActivity(intent);
} else {
Intent intent = new Intent(BalanceActivity.this, SendActivity.class);
intent.putExtra("uri", strResult.trim());
intent.putExtra("_account", account);
startActivity(intent);
}
} catch (Exception e) {
}
}
} else if (resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_QR) {
} else {
;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Show exit option if the account is 0 otherwise finish the activity
if (keyCode == KeyEvent.KEYCODE_BACK && account == 0) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.ask_you_sure_exit).setCancelable(false);
AlertDialog alert = builder.create();
alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), (dialog, id) -> {
try {
PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN()));
} catch (MnemonicException.MnemonicLengthException mle) {
} catch (JSONException je) {
} catch (IOException ioe) {
} catch (DecryptionException de) {
}
// disconnect Whirlpool on app back key exit
WhirlpoolNotificationService.stopService(getApplicationContext());
if (TorManager.getInstance(getApplicationContext()).isRequired()) {
Intent startIntent = new Intent(getApplicationContext(), TorService.class);
startIntent.setAction(TorService.STOP_SERVICE);
startIntent.putExtra("KILL_TOR",true);
startService(startIntent);
}
Intent intent = new Intent(BalanceActivity.this, ExodusActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
BalanceActivity.this.startActivity(intent);
});
alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
}
});
if (!isFinishing()) {
alert.show();
}
return true;
} else {
finish();
}
return false;
}
private void updateDisplay(boolean fromRefreshService) {
Disposable txDisposable = loadTxes(account)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((txes, throwable) -> {
if (throwable != null)
throwable.printStackTrace();
if (txes != null) {
if (txes.size() != 0) {
balanceViewModel.setTx(txes);
} else {
if (balanceViewModel.getTxs().getValue() != null && balanceViewModel.getTxs().getValue().size() == 0) {
balanceViewModel.setTx(txes);
}
}
Collections.sort(txes, new APIFactory.TxMostRecentDateComparator());
txs.clear();
txs.addAll(txes);
}
if (progressBar.getVisibility() == View.VISIBLE && fromRefreshService) {
progressBar.setVisibility(View.INVISIBLE);
}
});
Disposable balanceDisposable = loadBalance(account)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((balance, throwable) -> {
if (throwable != null)
throwable.printStackTrace();
if (balanceViewModel.getBalance().getValue() != null) {
if (balance != 0L) {
balanceViewModel.setBalance(balance);
}
} else {
balanceViewModel.setBalance(balance);
}
});
compositeDisposable.add(balanceDisposable);
compositeDisposable.add(txDisposable);
// displayBalance();
// txAdapter.notifyDataSetChanged();
}
private Single<List<Tx>> loadTxes(int account) {
return Single.fromCallable(() -> {
List<Tx> loadedTxes = new ArrayList<>();
if (account == 0) {
loadedTxes = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs();
} else if (account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix()) {
loadedTxes = APIFactory.getInstance(BalanceActivity.this).getAllPostMixTxs();
}
return loadedTxes;
});
}
private Single<Long> loadBalance(int account) {
return Single.fromCallable(() -> {
long loadedBalance = 0L;
if (account == 0) {
loadedBalance = APIFactory.getInstance(BalanceActivity.this).getXpubBalance();
} else if (account == WhirlpoolMeta.getInstance(getApplicationContext()).getWhirlpoolPostmix()) {
loadedBalance = APIFactory.getInstance(BalanceActivity.this).getXpubPostMixBalance();
}
return loadedBalance;
});
}
private void doClaimPayNym() {
Intent intent = new Intent(BalanceActivity.this, ClaimPayNymActivity.class);
startActivity(intent);
}
private void doSettings() {
TimeOutUtil.getInstance().updatePin();
Intent intent = new Intent(BalanceActivity.this, SettingsActivity.class);
startActivity(intent);
}
private void doSupport() {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://support.samourai.io/"));
startActivity(intent);
}
private void doUTXO() {
Intent intent = new Intent(BalanceActivity.this, UTXOSActivity.class);
intent.putExtra("_account", account);
startActivity(intent);
}
private void doScan() {
CameraFragmentBottomSheet cameraFragmentBottomSheet = new CameraFragmentBottomSheet();
cameraFragmentBottomSheet.show(getSupportFragmentManager(), cameraFragmentBottomSheet.getTag());
cameraFragmentBottomSheet.setQrCodeScanLisenter(code -> {
cameraFragmentBottomSheet.dismissAllowingStateLoss();
PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(code.trim()));
try {
if (privKeyReader.getFormat() != null) {
doPrivKey(code.trim());
} else if (Cahoots.isCahoots(code.trim())) {
Intent cahootIntent = new Intent(this, ManualCahootsActivity.class);
cahootIntent.putExtra("payload", code.trim());
cahootIntent.putExtra("_account", account);
startActivity(cahootIntent);
// CahootsUtil.getInstance(BalanceActivity.this).processCahoots(code.trim(), 0);
} else if (FormatsUtil.getInstance().isPSBT(code.trim())) {
CahootsUtil.getInstance(BalanceActivity.this).doPSBT(code.trim());
} else if (DojoUtil.getInstance(BalanceActivity.this).isValidPairingPayload(code.trim())) {
Intent intent = new Intent(BalanceActivity.this, NetworkDashboard.class);
intent.putExtra("params", code.trim());
startActivity(intent);
} else {
Intent intent = new Intent(BalanceActivity.this, SendActivity.class);
intent.putExtra("uri", code.trim());
intent.putExtra("_account", account);
startActivity(intent);
}
} catch (Exception e) {
}
});
}
private void doSweepViaScan() {
CameraFragmentBottomSheet cameraFragmentBottomSheet = new CameraFragmentBottomSheet();
cameraFragmentBottomSheet.show(getSupportFragmentManager(), cameraFragmentBottomSheet.getTag());
cameraFragmentBottomSheet.setQrCodeScanLisenter(code -> {
cameraFragmentBottomSheet.dismissAllowingStateLoss();
PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(code.trim()));
try {
if (privKeyReader.getFormat() != null) {
doPrivKey(code.trim());
} else if (Cahoots.isCahoots(code.trim())) {
Intent cahootIntent = new Intent(this, ManualCahootsActivity.class);
cahootIntent.putExtra("payload",code.trim());
cahootIntent.putExtra("_account",account);
startActivity(cahootIntent);
} else if (FormatsUtil.getInstance().isPSBT(code.trim())) {
CahootsUtil.getInstance(BalanceActivity.this).doPSBT(code.trim());
} else if (DojoUtil.getInstance(BalanceActivity.this).isValidPairingPayload(code.trim())) {
Toast.makeText(BalanceActivity.this, "Samourai Dojo full node coming soon.", Toast.LENGTH_SHORT).show();
} else {
Intent intent = new Intent(BalanceActivity.this, SendActivity.class);
intent.putExtra("uri", code.trim());
intent.putExtra("_account", account);
startActivity(intent);
}
} catch (Exception e) {
}
});
}
private void doSweep() {
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.action_sweep)
.setCancelable(true)
.setPositiveButton(R.string.enter_privkey, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final EditText privkey = new EditText(BalanceActivity.this);
privkey.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.enter_privkey)
.setView(privkey)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final String strPrivKey = privkey.getText().toString();
if (strPrivKey != null && strPrivKey.length() > 0) {
doPrivKey(strPrivKey);
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
if (!isFinishing()) {
dlg.show();
}
}
}).setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
doSweepViaScan();
}
});
if (!isFinishing()) {
dlg.show();
}
}
private void doPrivKey(final String data) {
PrivKeyReader privKeyReader = null;
String format = null;
try {
privKeyReader = new PrivKeyReader(new CharSequenceX(data), null);
format = privKeyReader.getFormat();
} catch (Exception e) {
Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
if (format != null) {
if (format.equals(PrivKeyReader.BIP38)) {
final PrivKeyReader pvr = privKeyReader;
final EditText password38 = new EditText(BalanceActivity.this);
password38.setSingleLine(true);
password38.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.bip38_pw)
.setView(password38)
.setCancelable(false)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String password = password38.getText().toString();
ProgressDialog progress = new ProgressDialog(BalanceActivity.this);
progress.setCancelable(false);
progress.setTitle(R.string.app_name);
progress.setMessage(getString(R.string.decrypting_bip38));
progress.show();
boolean keyDecoded = false;
try {
BIP38PrivateKey bip38 = new BIP38PrivateKey(SamouraiWallet.getInstance().getCurrentNetworkParams(), data);
final ECKey ecKey = bip38.decrypt(password);
if (ecKey != null && ecKey.hasPrivKey()) {
if (progress != null && progress.isShowing()) {
progress.cancel();
}
pvr.setPassword(new CharSequenceX(password));
keyDecoded = true;
Toast.makeText(BalanceActivity.this, pvr.getFormat(), Toast.LENGTH_SHORT).show();
Toast.makeText(BalanceActivity.this, pvr.getKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show();
}
if (progress != null && progress.isShowing()) {
progress.cancel();
}
if (keyDecoded) {
SweepUtil.getInstance(BalanceActivity.this).sweep(pvr, SweepUtil.TYPE_P2PKH);
}
}
}).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show();
}
});
if (!isFinishing()) {
dlg.show();
}
} else if (privKeyReader != null) {
SweepUtil.getInstance(BalanceActivity.this).sweep(privKeyReader, SweepUtil.TYPE_P2PKH);
} else {
;
}
} else {
Toast.makeText(BalanceActivity.this, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show();
}
}
private void doBackup() {
try {
final String passphrase = HD_WalletFactory.getInstance(BalanceActivity.this).get().getPassphrase();
final String[] export_methods = new String[2];
export_methods[0] = getString(R.string.export_to_clipboard);
export_methods[1] = getString(R.string.export_to_email);
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.options_export)
.setSingleChoiceItems(export_methods, 0, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
try {
PayloadUtil.getInstance(BalanceActivity.this).saveWalletToJSON(new CharSequenceX(AccessFactory.getInstance(BalanceActivity.this).getGUID() + AccessFactory.getInstance(BalanceActivity.this).getPIN()));
} catch (IOException ioe) {
;
} catch (JSONException je) {
;
} catch (DecryptionException de) {
;
} catch (MnemonicException.MnemonicLengthException mle) {
;
}
String encrypted = null;
try {
encrypted = AESUtil.encrypt(PayloadUtil.getInstance(BalanceActivity.this).getPayload().toString(), new CharSequenceX(passphrase), AESUtil.DefaultPBKDF2Iterations);
} catch (Exception e) {
Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
} finally {
if (encrypted == null) {
Toast.makeText(BalanceActivity.this, R.string.encryption_error, Toast.LENGTH_SHORT).show();
return;
}
}
JSONObject obj = PayloadUtil.getInstance(BalanceActivity.this).putPayload(encrypted, true);
if (which == 0) {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(android.content.Context.CLIPBOARD_SERVICE);
android.content.ClipData clip = null;
clip = android.content.ClipData.newPlainText("Wallet backup", obj.toString());
clipboard.setPrimaryClip(clip);
Toast.makeText(BalanceActivity.this, R.string.copied_to_clipboard, Toast.LENGTH_SHORT).show();
} else {
Intent email = new Intent(Intent.ACTION_SEND);
email.putExtra(Intent.EXTRA_SUBJECT, "Samourai Wallet backup");
email.putExtra(Intent.EXTRA_TEXT, obj.toString());
email.setType("message/rfc822");
startActivity(Intent.createChooser(email, BalanceActivity.this.getText(R.string.choose_email_client)));
}
dialog.dismiss();
}
}
).show();
} catch (IOException ioe) {
ioe.printStackTrace();
Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show();
} catch (MnemonicException.MnemonicLengthException mle) {
mle.printStackTrace();
Toast.makeText(BalanceActivity.this, "HD wallet error", Toast.LENGTH_SHORT).show();
}
}
private void doClipboardCheck() {
final android.content.ClipboardManager clipboard = (android.content.ClipboardManager) BalanceActivity.this.getSystemService(android.content.Context.CLIPBOARD_SERVICE);
if (clipboard.hasPrimaryClip()) {
final ClipData clip = clipboard.getPrimaryClip();
ClipData.Item item = clip.getItemAt(0);
if (item.getText() != null) {
String text = item.getText().toString();
String[] s = text.split("\\s+");
try {
for (int i = 0; i < s.length; i++) {
PrivKeyReader privKeyReader = new PrivKeyReader(new CharSequenceX(s[i]));
if (privKeyReader.getFormat() != null &&
(privKeyReader.getFormat().equals(PrivKeyReader.WIF_COMPRESSED) ||
privKeyReader.getFormat().equals(PrivKeyReader.WIF_UNCOMPRESSED) ||
privKeyReader.getFormat().equals(PrivKeyReader.BIP38) ||
FormatsUtil.getInstance().isValidXprv(s[i])
)
) {
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(R.string.privkey_clipboard)
.setCancelable(false)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
clipboard.setPrimaryClip(ClipData.newPlainText("", ""));
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
;
}
}).show();
}
}
} catch (Exception e) {
;
}
}
}
}
private void refreshTx(final boolean notifTx, final boolean dragged, final boolean launch) {
if (AppUtil.getInstance(BalanceActivity.this).isOfflineMode()) {
Toast.makeText(BalanceActivity.this, R.string.in_offline_mode, Toast.LENGTH_SHORT).show();
/*
CoordinatorLayout coordinatorLayout = new CoordinatorLayout(BalanceActivity.this);
Snackbar snackbar = Snackbar.make(coordinatorLayout, R.string.in_offline_mode, Snackbar.LENGTH_LONG);
snackbar.show();
*/
}
Intent intent = new Intent(this, JobRefreshService.class);
intent.putExtra("notifTx", notifTx);
intent.putExtra("dragged", dragged);
intent.putExtra("launch", launch);
JobRefreshService.enqueueWork(getApplicationContext(), intent);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// startForegroundService(intent);
// } else {
// startService(intent);
}
private String getBTCDisplayAmount(long value) {
return Coin.valueOf(value).toPlainString();
}
private String getSatoshiDisplayAmount(long value) {
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
DecimalFormat df = new DecimalFormat("#", symbols);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(16);
df.setGroupingUsed(true);
df.setGroupingSize(3);
return df.format(value);
}
private String getBTCDisplayUnits() {
return MonetaryUtil.getInstance().getBTCUnits();
}
private String getSatoshiDisplayUnits() {
return MonetaryUtil.getInstance().getSatoshiUnits();
}
private void doExplorerView(String strHash) {
if (strHash != null) {
String blockExplorer = "https://m.oxt.me/transaction/";
if (SamouraiWallet.getInstance().isTestNet()) {
blockExplorer = "https://blockstream.info/testnet/";
}
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(blockExplorer + strHash));
startActivity(browserIntent);
}
}
private void txDetails(Tx tx) {
Intent txIntent = new Intent(this, TxDetailsActivity.class);
txIntent.putExtra("TX", tx.toJSON().toString());
startActivity(txIntent);
}
private class RicochetQueueTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
if (RicochetMeta.getInstance(BalanceActivity.this).getQueue().size() > 0) {
int count = 0;
final Iterator<JSONObject> itr = RicochetMeta.getInstance(BalanceActivity.this).getIterator();
while (itr.hasNext()) {
if (count == 3) {
break;
}
try {
JSONObject jObj = itr.next();
JSONArray jHops = jObj.getJSONArray("hops");
if (jHops.length() > 0) {
JSONObject jHop = jHops.getJSONObject(jHops.length() - 1);
String txHash = jHop.getString("hash");
JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(txHash);
if (txObj != null && txObj.has("block_height") && txObj.getInt("block_height") != -1) {
itr.remove();
count++;
}
}
} catch (JSONException je) {
;
}
}
}
if (RicochetMeta.getInstance(BalanceActivity.this).getStaggered().size() > 0) {
int count = 0;
List<JSONObject> staggered = RicochetMeta.getInstance(BalanceActivity.this).getStaggered();
List<JSONObject> _staggered = new ArrayList<JSONObject>();
for (JSONObject jObj : staggered) {
if (count == 3) {
break;
}
try {
JSONArray jHops = jObj.getJSONArray("script");
if (jHops.length() > 0) {
JSONObject jHop = jHops.getJSONObject(jHops.length() - 1);
String txHash = jHop.getString("tx");
JSONObject txObj = APIFactory.getInstance(BalanceActivity.this).getTxInfo(txHash);
if (txObj != null && txObj.has("block_height") && txObj.getInt("block_height") != -1) {
count++;
} else {
_staggered.add(jObj);
}
}
} catch (JSONException je) {
;
} catch (ConcurrentModificationException cme) {
;
}
}
}
return "OK";
}
@Override
protected void onPostExecute(String result) {
;
}
@Override
protected void onPreExecute() {
;
}
}
private class PoWTask extends AsyncTask<String, Void, String> {
private boolean isOK = true;
private String strBlockHash = null;
@Override
protected String doInBackground(String... params) {
strBlockHash = params[0];
JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort());
JSONObject nodeObj = jsonrpc.getBlockHeader(strBlockHash);
if (nodeObj != null && nodeObj.has("hash")) {
PoW pow = new PoW(strBlockHash);
String hash = pow.calcHash(nodeObj);
if (hash != null && hash.toLowerCase().equals(strBlockHash.toLowerCase())) {
JSONObject headerObj = APIFactory.getInstance(BalanceActivity.this).getBlockHeader(strBlockHash);
if (headerObj != null && headerObj.has("")) {
if (!pow.check(headerObj, nodeObj, hash)) {
isOK = false;
}
}
} else {
isOK = false;
}
}
return "OK";
}
@Override
protected void onPostExecute(String result) {
if (!isOK) {
new AlertDialog.Builder(BalanceActivity.this)
.setTitle(R.string.app_name)
.setMessage(getString(R.string.trusted_node_pow_failed) + "\n" + "Block hash:" + strBlockHash)
.setCancelable(false)
.setPositiveButton(R.string.close, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}).show();
}
}
@Override
protected void onPreExecute() {
;
}
}
private void doFeaturePayNymUpdate() {
Disposable disposable = Observable.fromCallable(() -> {
JSONObject obj = new JSONObject();
obj.put("code", BIP47Util.getInstance(BalanceActivity.this).getPaymentCode().toString());
// Log.d("BalanceActivity", obj.toString());
String res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(BalanceActivity.this).postURL("application/json", null, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + "api/v1/token", obj.toString());
// Log.d("BalanceActivity", res);
JSONObject responseObj = new JSONObject(res);
if (responseObj.has("token")) {
String token = responseObj.getString("token");
String sig = MessageSignUtil.getInstance(BalanceActivity.this).signMessage(BIP47Util.getInstance(BalanceActivity.this).getNotificationAddress().getECKey(), token);
// Log.d("BalanceActivity", sig);
obj = new JSONObject();
obj.put("nym", BIP47Util.getInstance(BalanceActivity.this).getPaymentCode().toString());
obj.put("code", BIP47Util.getInstance(BalanceActivity.this).getFeaturePaymentCode().toString());
obj.put("signature", sig);
// Log.d("BalanceActivity", "nym/add:" + obj.toString());
res = com.samourai.wallet.bip47.paynym.WebUtil.getInstance(BalanceActivity.this).postURL("application/json", token, com.samourai.wallet.bip47.paynym.WebUtil.PAYNYM_API + "api/v1/nym/add", obj.toString());
// Log.d("BalanceActivity", res);
responseObj = new JSONObject(res);
if (responseObj.has("segwit") && responseObj.has("token")) {
PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, true);
} else if (responseObj.has("claimed") && responseObj.getBoolean("claimed") == true) {
PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.PAYNYM_FEATURED_SEGWIT, true);
}
}
return true;
}).subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(aBoolean -> {
Log.i(TAG, "doFeaturePayNymUpdate: Feature update complete");
}, error -> {
Log.i(TAG, "doFeaturePayNymUpdate: Feature update Fail");
});
compositeDisposable.add(disposable);
}
}
|
package io.spine.validate;
import com.google.common.base.Function;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.collect.ImmutableList;
import io.spine.string.Stringifiers;
import javax.annotation.Nullable;
import java.util.List;
import static com.google.common.base.Joiner.on;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.transform;
/**
* An exception, thrown if a {@code Message} does not pass the validation.
*
* @author Illia Shepilov
* @author Alex Tymchenko
*/
public class ValidationException extends RuntimeException {
private static final long serialVersionUID = 0L;
private static final Function<ConstraintViolation, String> TO_STRING_FN = new ToStringFn();
/**
* List of the constraint violations, that were found during the validation.
*/
private final List<ConstraintViolation> constraintViolations;
public ValidationException(Iterable<ConstraintViolation> violations) {
super();
this.constraintViolations = ImmutableList.copyOf(violations);
}
@SuppressWarnings({"AssignmentOrReturnOfFieldWithMutableType" /* returns immutable impl. */,
"unused" /* part of public API of the exception. */})
public List<ConstraintViolation> getConstraintViolations() {
return constraintViolations;
}
@Override
public String toString() {
final ToStringHelper helper = MoreObjects.toStringHelper(this);
final String violationContent = constraintViolations.isEmpty()
? "[]"
: on(", ").join(transform(constraintViolations, TO_STRING_FN));
return helper.add("constraintViolations", violationContent)
.toString();
}
/**
* A function, transforming a {@linkplain ConstraintViolation constraint violation}
* into a {@code String}.
*/
private static final class ToStringFn implements Function<ConstraintViolation, String> {
@Nullable
@Override
public String apply(@Nullable ConstraintViolation input) {
checkNotNull(input);
return Stringifiers.toString(input);
}
}
}
|
package org.voltdb.compilereport;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.voltdb.VoltDB;
import org.voltdb.VoltType;
import org.voltdb.catalog.Catalog;
import org.voltdb.catalog.CatalogMap;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Column;
import org.voltdb.catalog.ColumnRef;
import org.voltdb.catalog.Constraint;
import org.voltdb.catalog.Database;
import org.voltdb.catalog.GroupRef;
import org.voltdb.catalog.Index;
import org.voltdb.catalog.ProcParameter;
import org.voltdb.catalog.Procedure;
import org.voltdb.catalog.Statement;
import org.voltdb.catalog.StmtParameter;
import org.voltdb.catalog.Table;
import org.voltdb.dtxn.SiteTracker;
import org.voltdb.types.ConstraintType;
import org.voltdb.types.IndexType;
import org.voltdb.utils.CatalogUtil;
import org.voltdb.utils.Encoder;
import org.voltdb.utils.PlatformProperties;
import org.voltdb.utils.SystemStatsCollector;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
public class ReportMaker {
static Date m_timestamp = new Date();
/**
* Make an html bootstrap tag with our custom css class.
*/
static void tag(StringBuilder sb, String color, String text) {
sb.append("<span class='label label");
if (color != null) {
sb.append("-").append(color);
}
String classText = text.replace(' ', '_');
sb.append(" l-").append(classText).append("'>").append(text).append("</span>");
}
static String genrateIndexRow(Table table, Index index) {
StringBuilder sb = new StringBuilder();
sb.append(" <tr class='primaryrow2'>");
// name column
String anchor = (table.getTypeName() + "-" + index.getTypeName()).toLowerCase();
sb.append("<td style='white-space: nowrap'><i id='s-" + anchor + "--icon' class='icon-chevron-right'></i> <a href='#' id='s-");
sb.append(anchor).append("' class='togglex'>");
sb.append(index.getTypeName());
sb.append("</a></td>");
// type column
sb.append("<td>");
sb.append(IndexType.get(index.getType()).toString());
sb.append("</td>");
// columns column
sb.append("<td>");
List<ColumnRef> cols = CatalogUtil.getSortedCatalogItems(index.getColumns(), "index");
List<String> columnNames = new ArrayList<String>();
for (ColumnRef colRef : cols) {
columnNames.add(colRef.getColumn().getTypeName());
}
sb.append(StringUtils.join(columnNames, ", "));
sb.append("</td>");
// uniqueness column
sb.append("<td>");
if (index.getUnique()) {
tag(sb, "important", "Unique");
}
else {
tag(sb, "info", "Multikey");
}
sb.append("</td>");
sb.append("</tr>\n");
// BUILD THE DROPDOWN FOR THE PLAN/DETAIL TABLE
sb.append("<tr class='dropdown2'><td colspan='5' id='s-"+ table.getTypeName().toLowerCase() +
"-" + index.getTypeName().toLowerCase() + "--dropdown'>\n");
IndexAnnotation annotation = (IndexAnnotation) index.getAnnotation();
if (annotation != null) {
if (annotation.proceduresThatUseThis.size() > 0) {
sb.append("<p>Used by procedures: ");
List<String> procs = new ArrayList<String>();
for (Procedure proc : annotation.proceduresThatUseThis) {
procs.add("<a href='#p-" + proc.getTypeName() + "'>" + proc.getTypeName() + "</a>");
}
sb.append(StringUtils.join(procs, ", "));
sb.append("</p>");
}
}
sb.append("</td></tr>\n");
return sb.toString();
}
static String generateIndexesTable(Table table) {
StringBuilder sb = new StringBuilder();
sb.append(" <table class='table tableL2 table-condensed'>\n <thead><tr>" +
"<th>Index Name</th>" +
"<th>Type</th>" +
"<th>Columns</th>" +
"<th>Uniqueness</th>" +
"</tr></thead>\n <tbody>\n");
for (Index index : table.getIndexes()) {
sb.append(genrateIndexRow(table, index));
}
sb.append(" </tbody>\n </table>\n");
return sb.toString();
}
static String generateSchemaRow(Table table) {
StringBuilder sb = new StringBuilder();
sb.append("<tr class='primaryrow'>");
// column 1: table name
String anchor = table.getTypeName().toLowerCase();
sb.append("<td style='white-space: nowrap;'><i id='s-" + anchor + "--icon' class='icon-chevron-right'></i> <a href='#' id='s-");
sb.append(anchor).append("' class='togglex'>");
sb.append(table.getTypeName());
sb.append("</a></td>");
// column 2: type
sb.append("<td>");
if (table.getMaterializer() != null) {
tag(sb, "info", "Materialized View");
}
else {
tag(sb, null, "Table");
}
sb.append("</td>");
// column 3: partitioning
sb.append("<td style='whitespace: nowrap;'>");
if (table.getIsreplicated()) {
tag(sb, "warning", "Replicated");
}
else {
tag(sb, "success", "Partitioned");
Column partitionCol = table.getPartitioncolumn();
if (partitionCol != null) {
sb.append("<small> on " + partitionCol.getName() + "</small>");
}
else {
Table matSrc = table.getMaterializer();
if (matSrc != null) {
sb.append("<small> with " + matSrc.getTypeName() + "</small>");
}
}
}
sb.append("</td>");
// column 4: column count
sb.append("<td>");
sb.append(table.getColumns().size());
sb.append("</td>");
// column 5: index count
sb.append("<td>");
sb.append(table.getIndexes().size());
sb.append("</td>");
// column 6: has pkey
sb.append("<td>");
boolean found = false;
for (Constraint constraint : table.getConstraints()) {
if (ConstraintType.get(constraint.getType()) == ConstraintType.PRIMARY_KEY) {
found = true;
break;
}
}
if (found) {
tag(sb, "info", "Has-PKey");
}
else {
tag(sb, null, "No-PKey");
}
sb.append("</td>");
sb.append("</tr>\n");
// BUILD THE DROPDOWN FOR THE DDL / INDEXES DETAIL
sb.append("<tr class='tablesorter-childRow'><td class='invert' colspan='6' id='s-"+ table.getTypeName().toLowerCase() + "--dropdown'>\n");
TableAnnotation annotation = (TableAnnotation) table.getAnnotation();
if (annotation != null) {
// output the DDL
if (annotation.ddl == null) {
sb.append("<p>MISSING DDL</p>\n");
}
else {
String ddl = annotation.ddl;
sb.append("<p><pre>" + ddl + "</pre></p>\n");
}
// make sure procs appear in only one category
annotation.proceduresThatReadThis.removeAll(annotation.proceduresThatUpdateThis);
if (annotation.proceduresThatReadThis.size() > 0) {
sb.append("<p>Read-only by procedures: ");
List<String> procs = new ArrayList<String>();
for (Procedure proc : annotation.proceduresThatReadThis) {
procs.add("<a href='#p-" + proc.getTypeName() + "'>" + proc.getTypeName() + "</a>");
}
sb.append(StringUtils.join(procs, ", "));
sb.append("</p>");
}
if (annotation.proceduresThatUpdateThis.size() > 0) {
sb.append("<p>Read/Write by procedures: ");
List<String> procs = new ArrayList<String>();
for (Procedure proc : annotation.proceduresThatUpdateThis) {
procs.add("<a href='#p-" + proc.getTypeName() + "'>" + proc.getTypeName() + "</a>");
}
sb.append(StringUtils.join(procs, ", "));
sb.append("</p>");
}
}
if (table.getIndexes().size() > 0) {
sb.append(generateIndexesTable(table));
}
else {
sb.append("<p>No indexes defined on table.</p>\n");
}
sb.append("</td></tr>\n");
return sb.toString();
}
static String generateSchemaTable(CatalogMap<Table> tables) {
StringBuilder sb = new StringBuilder();
for (Table table : tables) {
sb.append(generateSchemaRow(table));
}
return sb.toString();
}
static String genrateStatementRow(Procedure procedure, Statement statement) {
StringBuilder sb = new StringBuilder();
sb.append(" <tr class='primaryrow2'>");
// name column
String anchor = (procedure.getTypeName() + "-" + statement.getTypeName()).toLowerCase();
sb.append("<td style='white-space: nowrap'><i id='p-" + anchor + "--icon' class='icon-chevron-right'></i> <a href='#' id='p-");
sb.append(anchor).append("' class='togglex'>");
sb.append(statement.getTypeName());
sb.append("</a></td>");
// sql column
sb.append("<td><tt>");
sb.append(statement.getSqltext());
sb.append("</td></tt>");
// params column
sb.append("<td>");
List<StmtParameter> params = CatalogUtil.getSortedCatalogItems(statement.getParameters(), "index");
List<String> paramTypes = new ArrayList<String>();
for (StmtParameter param : params) {
paramTypes.add(VoltType.get((byte) param.getJavatype()).name());
}
if (paramTypes.size() == 0) {
sb.append("<i>None</i>");
}
sb.append(StringUtils.join(paramTypes, ", "));
sb.append("</td>");
// r/w column
sb.append("<td>");
if (statement.getReadonly()) {
tag(sb, "success", "Read");
}
else {
tag(sb, "warning", "Write");
}
sb.append("</td>");
// attributes
sb.append("<td>");
if (!statement.getIscontentdeterministic() || !statement.getIsorderdeterministic()) {
tag(sb, "inverse", "Determinism");
}
if (statement.getSeqscancount() > 0) {
tag(sb, "important", "Scans");
}
sb.append("</td>");
sb.append("</tr>\n");
// BUILD THE DROPDOWN FOR THE PLAN/DETAIL TABLE
sb.append("<tr class='dropdown2'><td colspan='5' id='p-"+ procedure.getTypeName().toLowerCase() +
"-" + statement.getTypeName().toLowerCase() + "--dropdown'>\n");
sb.append("<div class='well well-small'><h4>Explain Plan:</h4>\n");
StatementAnnotation annotation = (StatementAnnotation) statement.getAnnotation();
if (annotation != null) {
String plan = annotation.explainPlan;
plan = plan.replace("\n", "<br/>");
plan = plan.replace(" ", " ");
for (Table t : annotation.tablesRead) {
String name = t.getTypeName().toUpperCase();
String link = "\"<a href='#s-" + t.getTypeName() + "'>" + name + "</a>\"";
plan = plan.replace("\"" + name + "\"", link);
}
for (Table t : annotation.tablesUpdated) {
String name = t.getTypeName().toUpperCase();
String link = "\"<a href='#s-" + t.getTypeName() + "'>" + name + "</a>\"";
plan = plan.replace("\"" + name + "\"", link);
}
for (Index i : annotation.indexesUsed) {
Table t = (Table) i.getParent();
String name = i.getTypeName().toUpperCase();
String link = "\"<a href='#s-" + t.getTypeName() + "-" + i.getTypeName() +"'>" + name + "</a>\"";
plan = plan.replace("\"" + name + "\"", link);
}
sb.append("<tt>").append(plan).append("</tt>");
}
else {
sb.append("<i>No SQL explain plan found.</i>\n");
}
sb.append("</div>\n");
sb.append("</td></tr>\n");
return sb.toString();
}
static String generateStatementsTable(Procedure procedure) {
StringBuilder sb = new StringBuilder();
sb.append(" <table class='table tableL2 table-condensed'>\n <thead><tr>" +
"<th><span style='white-space: nowrap;'>Statement Name</span></th>" +
"<th>Statement SQL</th>" +
"<th>Params</th>" +
"<th>R/W</th>" +
"<th>Attributes</th>" +
"</tr></thead>\n <tbody>\n");
for (Statement statement : procedure.getStatements()) {
sb.append(genrateStatementRow(procedure, statement));
}
sb.append(" </tbody>\n </table>\n");
return sb.toString();
}
static String generateProcedureRow(Procedure procedure) {
StringBuilder sb = new StringBuilder();
sb.append("<tr class='primaryrow'>");
// column 1: procedure name
String anchor = procedure.getTypeName().toLowerCase();
sb.append("<td style='white-space: nowrap'><i id='p-" + anchor + "--icon' class='icon-chevron-right'></i> <a href='
sb.append(anchor).append("' id='p-").append(anchor).append("' class='togglex'>");
sb.append(procedure.getTypeName());
sb.append("</a></td>");
// column 2: parameter types
sb.append("<td>");
List<ProcParameter> params = CatalogUtil.getSortedCatalogItems(procedure.getParameters(), "index");
List<String> paramTypes = new ArrayList<String>();
for (ProcParameter param : params) {
String paramType = VoltType.get((byte) param.getType()).name();
if (param.getIsarray()) {
paramType += "[]";
}
paramTypes.add(paramType);
}
if (paramTypes.size() == 0) {
sb.append("<i>None</i>");
}
sb.append(StringUtils.join(paramTypes, ", "));
sb.append("</td>");
// column 3: partitioning
sb.append("<td>");
if (procedure.getSinglepartition()) {
tag(sb, "success", "Single");
}
else {
tag(sb, "warning", "Multi");
}
sb.append("</td>");
// column 4: read/write
sb.append("<td>");
if (procedure.getReadonly()) {
tag(sb, "success", "Read");
}
else {
tag(sb, "warning", "Write");
}
sb.append("</td>");
// column 5: access
sb.append("<td>");
List<String> groupNames = new ArrayList<String>();
for (GroupRef groupRef : procedure.getAuthgroups()) {
groupNames.add(groupRef.getGroup().getTypeName());
}
if (groupNames.size() == 0) {
sb.append("<i>None</i>");
}
sb.append(StringUtils.join(groupNames, ", "));
sb.append("</td>");
// column 6: attributes
sb.append("<td>");
if (procedure.getHasjava()) {
tag(sb, "info", "Java");
}
else {
tag(sb, null, "Single-Stmt");
}
boolean isND = false;
int scanCount = 0;
for (Statement stmt : procedure.getStatements()) {
scanCount += stmt.getSeqscancount();
if (!stmt.getIscontentdeterministic() || !stmt.getIsorderdeterministic()) {
isND = false;
}
}
if (isND) {
tag(sb, "inverse", "Determinism");
}
if (scanCount > 0) {
tag(sb, "important", "Scans");
}
sb.append("</td>");
sb.append("</tr>\n");
// BUILD THE DROPDOWN FOR THE STATEMENT/DETAIL TABLE
sb.append("<tr class='tablesorter-childRow'><td class='invert' colspan='6' id='p-"+ procedure.getTypeName().toLowerCase() + "--dropdown'>\n");
// output partitioning parameter info
if (procedure.getSinglepartition()) {
String pTable = procedure.getPartitioncolumn().getParent().getTypeName();
String pColumn = procedure.getPartitioncolumn().getTypeName();
int pIndex = procedure.getPartitionparameter();
sb.append(String.format("<p>Partitioned on parameter %d which maps to column %s" +
" of table <a class='invert' href='#s-%s'>%s</a>.</p>",
pIndex, pColumn, pTable, pTable));
}
// output what schema this interacts with
ProcedureAnnotation annotation = (ProcedureAnnotation) procedure.getAnnotation();
if (annotation != null) {
// make sure tables appear in only one category
annotation.tablesRead.removeAll(annotation.tablesUpdated);
if (annotation.tablesRead.size() > 0) {
sb.append("<p>Read-only access to tables: ");
List<String> tables = new ArrayList<String>();
for (Table table : annotation.tablesRead) {
tables.add("<a href='#s-" + table.getTypeName() + "'>" + table.getTypeName() + "</a>");
}
sb.append(StringUtils.join(tables, ", "));
sb.append("</p>");
}
if (annotation.tablesUpdated.size() > 0) {
sb.append("<p>Read/Write access to tables: ");
List<String> tables = new ArrayList<String>();
for (Table table : annotation.tablesUpdated) {
tables.add("<a href='#s-" + table.getTypeName() + "'>" + table.getTypeName() + "</a>");
}
sb.append(StringUtils.join(tables, ", "));
sb.append("</p>");
}
if (annotation.indexesUsed.size() > 0) {
sb.append("<p>Uses indexes: ");
List<String> indexes = new ArrayList<String>();
for (Index index : annotation.indexesUsed) {
Table table = (Table) index.getParent();
indexes.add("<a href='#s-" + table.getTypeName() + "-" + index.getTypeName() + "'>" + index.getTypeName() + "</a>");
}
sb.append(StringUtils.join(indexes, ", "));
sb.append("</p>");
}
}
sb.append(generateStatementsTable(procedure));
sb.append("</td></tr>\n");
return sb.toString();
}
static String generateProceduresTable(CatalogMap<Procedure> procedures) {
StringBuilder sb = new StringBuilder();
for (Procedure procedure : procedures) {
if (procedure.getDefaultproc()) {
continue;
}
sb.append(generateProcedureRow(procedure));
}
return sb.toString();
}
/**
* Get some embeddable HTML of some generic catalog/application stats
* that is drawn on the first page of the report.
*/
static String getStatsHTML(Database db) {
StringBuilder sb = new StringBuilder();
sb.append("<table class='table table-condensed'>\n");
// count things
int indexes = 0, views = 0, statements = 0;
int partitionedTables = 0, replicatedTables = 0;
int partitionedProcs = 0, replicatedProcs = 0;
int readProcs = 0, writeProcs = 0;
for (Table t : db.getTables()) {
if (t.getMaterializer() != null) {
views++;
}
else {
if (t.getIsreplicated()) {
replicatedTables++;
}
else {
partitionedTables++;
}
}
indexes += t.getIndexes().size();
}
for (Procedure p : db.getProcedures()) {
// skip auto-generated crud procs
if (p.getDefaultproc()) {
continue;
}
if (p.getSinglepartition()) {
partitionedProcs++;
}
else {
replicatedProcs++;
}
if (p.getReadonly()) {
readProcs++;
}
else {
writeProcs++;
}
statements += p.getStatements().size();
}
// version
sb.append("<tr><td>Compiled by VoltDB Version</td><td>");
sb.append(VoltDB.instance().getVersionString()).append("</td></tr>\n");
// timestamp
sb.append("<tr><td>Compiled on</td><td>");
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
sb.append(sdf.format(m_timestamp)).append("</td></tr>\n");
// tables
sb.append("<tr><td>Table Count</td><td>");
sb.append(String.format("%d (%d partitioned / %d replicated)",
partitionedTables + replicatedTables, partitionedTables, replicatedTables));
sb.append("</td></tr>\n");
// views
sb.append("<tr><td>Materialized View Count</td><td>").append(views).append("</td></tr>\n");
// indexes
sb.append("<tr><td>Index Count</td><td>").append(indexes).append("</td></tr>\n");
// procedures
sb.append("<tr><td>Procedure Count</td><td>");
sb.append(String.format("%d (%d partitioned / %d replicated) (%d read-only / %d read-write)",
partitionedProcs + replicatedProcs, partitionedProcs, replicatedProcs,
readProcs, writeProcs));
sb.append("</td></tr>\n");
// statements
sb.append("<tr><td>SQL Statement Count</td><td>").append(statements).append("</td></tr>\n");
sb.append("</table>\n");
return sb.toString();
}
/**
* Generate the HTML catalog report from a newly compiled VoltDB catalog
*/
public static String report(Catalog catalog) throws IOException {
// asynchronously get platform properties
new Thread() {
@Override
public void run() {
PlatformProperties.getPlatformProperties();
}
}.start();
URL url = Resources.getResource(ReportMaker.class, "template.html");
String contents = Resources.toString(url, Charsets.UTF_8);
Cluster cluster = catalog.getClusters().get("cluster");
assert(cluster != null);
Database db = cluster.getDatabases().get("database");
assert(db != null);
String statsData = getStatsHTML(db);
contents = contents.replace("##STATS##", statsData);
String schemaData = generateSchemaTable(db.getTables());
contents = contents.replace("##SCHEMA##", schemaData);
String procData = generateProceduresTable(db.getProcedures());
contents = contents.replace("##PROCS##", procData);
String platformData = PlatformProperties.getPlatformProperties().toHTML();
contents = contents.replace("##PLATFORM##", platformData);
contents = contents.replace("##VERSION##", VoltDB.instance().getVersionString());
DateFormat df = new SimpleDateFormat("d MMM yyyy HH:mm:ss z");
contents = contents.replace("##TIMESTAMP##", df.format(m_timestamp));
String msg = Encoder.hexEncode(VoltDB.instance().getVersionString() + "," + System.currentTimeMillis());
contents = contents.replace("get.py?a=KEY&", String.format("get.py?a=%s&", msg));
return contents;
}
public static String getLiveSystemOverview()
{
// get the start time
long t = SystemStatsCollector.getStartTime();
Date date = new Date(t);
long duration = System.currentTimeMillis() - t;
long minutes = duration / 60000;
long hours = minutes / 60; minutes -= hours * 60;
long days = hours / 24; hours -= days * 24;
String starttime = String.format("%s (%dd %dh %dm)",
date.toString(), days, hours, minutes);
// handle the basic info page below this
SiteTracker st = VoltDB.instance().getSiteTrackerForSnapshot();
// get the cluster info
String clusterinfo = st.getAllHosts().size() + " hosts ";
clusterinfo += " with " + st.getAllSites().size() + " sites ";
clusterinfo += " (" + st.getAllSites().size() / st.getAllHosts().size();
clusterinfo += " per host)";
StringBuilder sb = new StringBuilder();
sb.append("<table class='table table-condensed'>\n");
sb.append("<tr><td>Mode </td><td>" + VoltDB.instance().getMode().toString() + "</td><td>\n");
sb.append("<tr><td>VoltDB Version </td><td>" + VoltDB.instance().getVersionString() + "</td><td>\n");
sb.append("<tr><td>Buildstring </td><td>" + VoltDB.instance().getBuildString() + "</td><td>\n");
sb.append("<tr><td>Cluster Composition </td><td>" + clusterinfo + "</td><td>\n");
sb.append("<tr><td>Running Since </td><td>" + starttime + "</td><td>\n");
sb.append("</table>\n");
return sb.toString();
}
/**
* Find the pre-compild catalog report in the jarfile, and modify it for use in the
* the built-in web portal.
*/
public static String liveReport() {
byte[] reportbytes = VoltDB.instance().getCatalogContext().getFileInJar("catalog-report.html");
String report = new String(reportbytes, Charsets.UTF_8);
// remove commented out code
report = report.replace("<!--##RESOURCES", "");
report = report.replace("##RESOURCES-->", "");
// inject the cluster overview
String clusterStr = "<h4>System Overview</h4>\n<p>" + getLiveSystemOverview() + "</p><br/>\n";
report = report.replace("<!--##CLUSTER##-->", clusterStr);
// inject the running system platform properties
PlatformProperties pp = PlatformProperties.getPlatformProperties();
String ppStr = "<h4>Cluster Platform</h4>\n<p>" + pp.toHTML() + "</p><br/>\n";
report = report.replace("<!--##PLATFORM2##-->", ppStr);
// change the live/static var to live
if (VoltDB.instance().getConfig().m_isEnterprise) {
report = report.replace("&b=r&", "&b=e&");
}
else {
report = report.replace("&b=r&", "&b=c&");
}
return report;
}
}
|
package io.geeteshk.hyper.adapter;
import android.animation.Animator;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.storage.FirebaseStorage;
import java.io.File;
import java.io.IOException;
import io.geeteshk.hyper.helper.Constants;
import io.geeteshk.hyper.activity.EncryptActivity;
import io.geeteshk.hyper.activity.MainActivity;
import io.geeteshk.hyper.activity.ProjectActivity;
import io.geeteshk.hyper.R;
import io.geeteshk.hyper.activity.WebActivity;
import io.geeteshk.hyper.helper.Firebase;
import io.geeteshk.hyper.helper.Hyperion;
import io.geeteshk.hyper.helper.Jason;
import io.geeteshk.hyper.helper.Network;
import io.geeteshk.hyper.helper.Pref;
import io.geeteshk.hyper.helper.Project;
/**
* Adapter to list all projects
*/
public class ProjectAdapter extends RecyclerView.Adapter<ProjectAdapter.MyViewHolder> {
private static final String TAG = ProjectAdapter.class.getSimpleName();
/**
* Context used for various purposes such as loading files and inflating layouts
*/
Context mContext;
/**
* Array of objects to fill list
*/
String[] mObjects;
boolean mImprove;
FirebaseAuth mAuth;
FirebaseStorage mStorage;
public ProjectAdapter(Context context, String[] objects, boolean improve, FirebaseAuth auth, FirebaseStorage storage) {
this.mContext = context;
this.mObjects = objects;
this.mImprove = improve;
this.mAuth = auth;
this.mStorage = storage;
}
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_project, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
int color = Color.parseColor(Jason.getProjectProperty(mObjects[position], "color"));
final int newPos = holder.getAdapterPosition();
holder.mTitle.setText(mObjects[position]);
holder.mDescription.setText(Jason.getProjectProperty(mObjects[position], "description"));
holder.mFavicon.setImageBitmap(Project.getFavicon(mObjects[position]));
holder.mColor.setBackgroundColor(color);
if (mImprove) {
holder.mFavicon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent;
if (Pref.get(mContext, "pin", "").equals("")) {
intent = new Intent(mContext, ProjectActivity.class);
intent.putExtra("project", mObjects[newPos]);
intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
if (Build.VERSION.SDK_INT >= 21) {
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
}
((AppCompatActivity) mContext).startActivityForResult(intent, 0);
} else {
intent = new Intent(mContext, EncryptActivity.class);
intent.putExtra("project", mObjects[newPos]);
mContext.startActivity(intent);
}
}
});
} else {
holder.mFavicon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Network.setDrive(new Hyperion(mObjects[newPos]));
try {
Network.getDrive().start();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
}
if (Pref.get(mContext, "pin", "").equals("")) {
Intent intent = new Intent(mContext, WebActivity.class);
if (Network.getDrive().wasStarted() && Network.getDrive().isAlive() && Network.getIpAddress() != null) {
intent.putExtra("url", "http:///" + Network.getIpAddress() + ":8080");
} else {
intent.putExtra("url", "file:///" + Constants.HYPER_ROOT + File.separator + mObjects[newPos] + File.separator + "index.html");
}
intent.putExtra("name", mObjects[newPos]);
intent.putExtra("pilot", true);
mContext.startActivity(intent);
} else {
Intent intent = new Intent(mContext, EncryptActivity.class);
if (Network.getDrive().wasStarted() && Network.getDrive().isAlive() && Network.getIpAddress() != null) {
intent.putExtra("url", "http:///" + Network.getIpAddress() + ":8080");
} else {
intent.putExtra("url", "file:///" + Constants.HYPER_ROOT + File.separator + mObjects[newPos] + File.separator + "index.html");
}
intent.putExtra("name", mObjects[newPos]);
intent.putExtra("pilot", true);
mContext.startActivity(intent);
}
}
});
}
holder.mFavicon.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle(mContext.getString(R.string.delete) + " " + mObjects[newPos] + "?");
builder.setMessage(R.string.change_undone);
builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (Project.deleteProject(mContext, mObjects[newPos])) {
holder.itemView.animate().alpha(0).setDuration(300).setListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
Firebase.removeProject(mAuth, mStorage, mObjects[newPos]);
Firebase.deleteProjectFiles(mAuth, mStorage, mObjects[newPos]);
MainActivity.update(mContext, ((AppCompatActivity) mContext).getSupportFragmentManager(), 1);
}
@Override
public void onAnimationCancel(Animator animation) {
Firebase.removeProject(mAuth, mStorage, mObjects[newPos]);
Firebase.deleteProjectFiles(mAuth, mStorage, mObjects[newPos]);
MainActivity.update(mContext, ((AppCompatActivity) mContext).getSupportFragmentManager(), 1);
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
Toast.makeText(mContext, mContext.getString(R.string.goodbye) + " " + mObjects[newPos] + ".", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, mContext.getString(R.string.oops_delete) + " " + mObjects[newPos] + ".", Toast.LENGTH_SHORT).show();
}
}
});
builder.setNegativeButton(R.string.cancel, null);
builder.show();
return true;
}
});
if (new File(Constants.HYPER_ROOT + File.separator + mObjects[position], ".git").exists() && new File(Constants.HYPER_ROOT + File.separator + mObjects[position], ".git").isDirectory()) {
holder.mRepo.setVisibility(View.VISIBLE);
}
}
@Override
public int getItemCount() {
return mObjects.length;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle, mDescription;
public ImageView mFavicon, mRepo;
public View mColor;
public MyViewHolder(View view) {
super(view);
mTitle = (TextView) view.findViewById(R.id.title);
mDescription = (TextView) view.findViewById(R.id.desc);
mRepo = (ImageView) view.findViewById(R.id.git_repo);
mFavicon = (ImageView) view.findViewById(R.id.favicon);
mColor = view.findViewById(R.id.project_color);
}
}
}
|
package io.spine.validate.diags;
import io.spine.validate.ConstraintViolation;
import java.util.List;
import java.util.stream.StreamSupport;
import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;
import static java.lang.System.lineSeparator;
import static java.util.stream.Collectors.joining;
/**
* Provides error diagnostic text for a violation of a validation constraint.
*
* <p>If a {@link ConstraintViolation} has nested violations, they are listed in separate lines.
*/
public final class ViolationText {
private final ConstraintViolation violation;
/**
* Creates a new instance of the text for the passed violation.
*/
public static ViolationText of(ConstraintViolation violation) {
checkNotNull(violation);
return new ViolationText(violation);
}
/**
* Creates text with diagnostics for the passed violations, starting each of them from
* a new line.
*/
public static String ofAll(Iterable<ConstraintViolation> violations) {
String result =
StreamSupport.stream(violations.spliterator(), false)
.map(ViolationText::of)
.map(ViolationText::toString)
.collect(joining(lineSeparator()));
return result;
}
private ViolationText(ConstraintViolation violation) {
this.violation = violation;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(formattedMessage());
for (ConstraintViolation v : violation.getViolationList()) {
builder.append(lineSeparator());
ViolationText nested = of(v);
builder.append(nested.toString());
}
return builder.toString();
}
private String formattedMessage() {
String format = violation.getMsgFormat();
List<String> params = violation.getParamList();
String result = format(format, params.toArray());
return result;
}
}
|
package org.basex.util.ft;
import java.util.*;
import org.basex.util.*;
final class GermanStemmer extends InternalStemmer {
/** Removed characters. */
private int subst;
/**
* Constructor.
* @param fti full-text iterator
*/
GermanStemmer(final FTIterator fti) {
super(fti);
}
@Override
Stemmer get(final Language lang, final FTIterator fti) {
return new GermanStemmer(fti);
}
@Override
Collection<Language> languages() {
return collection("de");
}
@Override
protected byte[] stem(final byte[] word) {
subst = 0;
return part(resub(opt(strip(subst(new TokenBuilder(word)))))).finish();
}
/**
* Does some substitutions.
* @param tb string builder
* @return substituted string
*/
private TokenBuilder subst(final TokenBuilder tb) {
subst = 0;
final int s = tb.size();
final TokenBuilder tmp = new TokenBuilder(s);
int ls = 0;
int nx = tb.cp(0);
for(int c = 0; c < s;) {
int ch = nx;
c += tb.cl(c);
nx = c < s ? tb.cp(c) : 0;
int sb = 0;
if(ch == ls) {
ch = '*';
} else if(ch == '\u00e4') {
ch = 'a';
} else if(ch == '\u00f6') {
ch = 'o';
} else if(ch == '\u00fc') {
ch = 'u';
} else if(ch == '\u00df') {
tmp.add('s');
ch = 's';
subst++;
} else if(ch == 's' && nx == 'c' && c + 1 < s && tb.get(c + 1) == 'h') {
ch = '\1';
sb = 2;
} else if(ch == 'c' && nx == 'h') {
ch = '\2';
sb = 1;
} else if(ch == 'e' && nx == 'i') {
ch = '\3';
sb = 1;
} else if(ch == 'i' && nx == 'e') {
ch = '\4';
sb = 1;
} else if(ch == 'i' && nx == 'g') {
ch = '\5';
sb = 1;
} else if(ch == 's' && nx == 't') {
ch = '\6';
sb = 1;
}
if(sb > 0) {
c += sb;
nx = c < s ? tb.cp(c) : 0;
subst += sb;
}
ls = ch;
tmp.add(ch);
}
return tmp;
}
/**
* Strips suffixes.
* @param tb token builder
* @return token builder
*/
private TokenBuilder strip(final TokenBuilder tb) {
while(tb.size() > 3) {
final int tl = tb.size(), c1 = tb.get(tl - 1), c2 = tb.get(tl - 2);
if(tl + subst > 5 && c2 == 'n' && c1 == 'd' ||
tl + subst > 4 && c2 == 'e' && (c1 == 'm' || c1 == 'r')) {
tb.size(tl - 2);
} else if(c1 == 'e' || c1 == 's' || c1 == 'n' || c1 == 't') {
tb.size(tl - 1);
} else {
break;
}
}
return tb;
}
/**
* Does optimizations.
* @param tb token builder
* @return token builder
*/
private TokenBuilder opt(final TokenBuilder tb) {
int tl = tb.size();
if(tl > 5 && tb.get(tl - 5) == 'e' && tb.get(tl - 4) == 'r' &&
tb.get(tl - 3) == 'i' && tb.get(tl - 2) == 'n' && tb.get(tl - 1) == '*') {
tb.size(tl - 1);
strip(tb);
}
tl = tb.size();
if(tl > 0 && tb.get(tl - 1) == 'z') tb.set(tl - 1, (byte) 'x');
return tb;
}
/**
* Undoes the changes made by substitute.
* @param tb token builder
* @return new token builder
*/
private static TokenBuilder resub(final TokenBuilder tb) {
final TokenBuilder tmp = new TokenBuilder();
final int s = tb.size();
for(int c = 0; c < s; c++) {
final int ch = tb.get(c);
if(ch == '*') {
tmp.add(tmp.get(c - 1));
} else if(ch == '\1') {
tmp.add('s').add('c').add('h');
} else if(ch == '\2') {
tmp.add('c').add('h');
} else if(ch == '\3') {
tmp.add('e').add('i');
} else if(ch == '\4') {
tmp.add('i').add('e');
} else if(ch == '\5') {
tmp.add('i').add('g');
} else if(ch == '\6') {
tmp.add('s').add('t');
} else {
tmp.add(ch);
}
}
return tmp;
}
/**
* Removes a particle denotion ("ge") from a term.
* @param tb token builder
* @return token builder
*/
private static TokenBuilder part(final TokenBuilder tb) {
for(int c = 0; c < tb.size() - 3; c++) {
if(tb.get(c) == 'g' && tb.get(c + 1) == 'e' && tb.get(c + 2) == 'g' && tb.get(c + 3) == 'e') {
tb.delete(c, 2);
break;
}
}
return tb;
}
}
|
package com.opengamma.web.server;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;
import org.cometd.Client;
import org.cometd.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.view.ViewComputationResultModel;
import com.opengamma.engine.view.ViewDeltaResultModel;
import com.opengamma.engine.view.client.ViewClient;
import com.opengamma.engine.view.compilation.CompiledViewDefinition;
import com.opengamma.engine.view.execution.ExecutionOptions;
import com.opengamma.engine.view.listener.AbstractViewResultListener;
import com.opengamma.livedata.UserPrincipal;
import com.opengamma.web.server.conversion.ResultConverterCache;
public class WebView {
private static final Logger s_logger = LoggerFactory.getLogger(WebView.class);
private static final String STARTED_DISPLAY_NAME = "Live";
private static final String PAUSED_DISPLAY_NAME = "Paused";
private final Client _local;
private final Client _remote;
private final ViewClient _client;
private final String _viewDefinitionName;
private final ExecutorService _executorService;
private final ResultConverterCache _resultConverterCache;
private final ReentrantLock _updateLock = new ReentrantLock();
private boolean _awaitingUpdate;
private AtomicBoolean _isInit = new AtomicBoolean(false);
private final Map<String, WebViewGrid> _gridsByName;
private WebViewGrid _portfolioGrid;
private WebViewGrid _primitivesGrid;
public WebView(final Client local, final Client remote, final ViewClient client, final String viewDefinitionName,
final UserPrincipal user, final ExecutorService executorService, final ResultConverterCache resultConverterCache) {
_local = local;
_remote = remote;
_client = client;
_viewDefinitionName = viewDefinitionName;
_executorService = executorService;
_resultConverterCache = resultConverterCache;
_gridsByName = new HashMap<String, WebViewGrid>();
_client.setResultListener(new AbstractViewResultListener() {
@Override
public void viewDefinitionCompiled(CompiledViewDefinition compiledViewDefinition) {
// TODO: support for changing compilation results
s_logger.warn("View definition compiled: {}", compiledViewDefinition.getViewDefinition().getName());
initGrids(compiledViewDefinition);
}
@Override
public void cycleCompleted(ViewComputationResultModel fullResult, ViewDeltaResultModel deltaResult) {
s_logger.info("New result arrived for view '{}'", getViewDefinitionName());
_updateLock.lock();
try {
if (_awaitingUpdate) {
_awaitingUpdate = false;
sendUpdateAsync(fullResult);
}
} finally {
_updateLock.unlock();
}
}
});
client.attachToViewProcess(viewDefinitionName, ExecutionOptions.realTime());
}
// Initialisation
private void initGrids(CompiledViewDefinition compiledViewDefinition) {
if (_isInit.getAndSet(true)) {
// Already initialised
return;
}
WebViewGrid portfolioGrid = new WebViewPortfolioGrid(compiledViewDefinition, getResultConverterCache(), getLocal(), getRemote());
if (portfolioGrid.getGridStructure().isEmpty()) {
_portfolioGrid = null;
} else {
_portfolioGrid = portfolioGrid;
_gridsByName.put(_portfolioGrid.getName(), _portfolioGrid);
}
WebViewGrid primitivesGrid = new WebViewPrimitivesGrid(compiledViewDefinition, getResultConverterCache(), getLocal(), getRemote());
if (primitivesGrid.getGridStructure().isEmpty()) {
_primitivesGrid = null;
} else {
_primitivesGrid = primitivesGrid;
_gridsByName.put(_primitivesGrid.getName(), _primitivesGrid);
}
notifyInitialized();
}
private void notifyInitialized() {
getRemote().deliver(getLocal(), "/initialize", getJsonGridStructures(), null);
}
/*package*/ void reconnected() {
if (_isInit.get()) {
notifyInitialized();
}
}
// Update control
public void pause() {
getViewClient().pause();
sendViewStatus(false, PAUSED_DISPLAY_NAME);
}
public void resume() {
getViewClient().resume();
sendViewStatus(true, STARTED_DISPLAY_NAME);
}
public void shutdown() {
// Removes all listeners
getViewClient().shutdown();
}
public String getViewDefinitionName() {
return _viewDefinitionName;
}
public WebViewGrid getGridByName(String name) {
return _gridsByName.get(name);
}
@SuppressWarnings("unchecked")
public void triggerUpdate(Message message) {
Map<String, Object> dataMap = (Map<String, Object>) message.getData();
boolean immediateResponse = (Boolean) dataMap.get("immediateResponse");
if (getPortfolioGrid() != null) {
Map<String, Object> portfolioViewport = (Map<String, Object>) dataMap.get("portfolioViewport");
getPortfolioGrid().setViewport(processViewportData(portfolioViewport));
}
if (getPrimitivesGrid() != null) {
Map<String, Object> primitiveViewport = (Map<String, Object>) dataMap.get("primitiveViewport");
getPrimitivesGrid().setViewport(processViewportData(primitiveViewport));
}
_updateLock.lock();
try {
if (!immediateResponse) {
_awaitingUpdate = true;
} else {
ViewComputationResultModel latestResult = getViewClient().getLatestResult();
if (latestResult == null) {
_awaitingUpdate = true;
} else {
sendUpdateAsync(latestResult);
_awaitingUpdate = false;
}
}
} finally {
_updateLock.unlock();
}
}
private SortedMap<Long, Long> processViewportData(Map<String, Object> viewportData) {
SortedMap<Long, Long> result = new TreeMap<Long, Long>();
if (viewportData.isEmpty()) {
return result;
}
Object[] ids = (Object[]) viewportData.get("rowIds");
Object[] lastTimes = (Object[]) viewportData.get("lastTimestamps");
for (int i = 0; i < ids.length; i++) {
if (ids[i] instanceof Number) {
Long rowId = (Long) ids[i];
if (lastTimes[i] != null) {
Long lastTime = (Long) lastTimes[i];
result.put(rowId, lastTime);
} else {
result.put(rowId, null);
}
} else {
throw new OpenGammaRuntimeException("Unexpected type of webId: " + ids[i]);
}
}
return result;
}
private void sendUpdateAsync(final ViewComputationResultModel update) {
getExecutorService().submit(new Runnable() {
@Override
public void run() {
getRemote().startBatch();
long liveDataTimestampMillis = update.getValuationTime().toEpochMillisLong();
long resultTimestampMillis = update.getResultTimestamp().toEpochMillisLong();
sendStartMessage(resultTimestampMillis, resultTimestampMillis - liveDataTimestampMillis);
processResult(update);
sendEndMessage();
getRemote().endBatch();
}
});
}
private void processResult(ViewComputationResultModel resultModel) {
long resultTimestamp = resultModel.getResultTimestamp().toEpochMillisLong();
for (ComputationTargetSpecification target : resultModel.getAllTargets()) {
switch (target.getType()) {
case PRIMITIVE:
if (getPrimitivesGrid() != null) {
getPrimitivesGrid().processTargetResult(target, resultModel.getTargetResult(target), resultTimestamp);
}
break;
case PORTFOLIO_NODE:
case POSITION:
if (getPortfolioGrid() != null) {
getPortfolioGrid().processTargetResult(target, resultModel.getTargetResult(target), resultTimestamp);
}
break;
default:
// Something that the client does not display
continue;
}
}
}
/**
* Tells the remote client that updates are starting, relating to a particular timestamp.
*/
private void sendStartMessage(long timestamp, long calculationLatency) {
Map<String, Object> startMessage = new HashMap<String, Object>();
startMessage.put("timestamp", timestamp);
startMessage.put("latency", calculationLatency);
getRemote().deliver(getLocal(), "/updates/control/start", startMessage, null);
}
/**
* Tells the remote client that updates have finished.
*/
private void sendEndMessage() {
getRemote().deliver(getLocal(), "/updates/control/end", new HashMap<String, Object>(), null);
}
private void sendViewStatus(boolean isRunning, String status) {
Map<String, Object> output = new HashMap<String, Object>();
output.put("isRunning", isRunning);
output.put("status", status);
getRemote().deliver(getLocal(), "/status", output, null);
}
public Map<String, Object> getJsonGridStructures() {
Map<String, Object> gridStructures = new HashMap<String, Object>();
if (getPrimitivesGrid() != null) {
gridStructures.put("primitives", getPrimitivesGrid().getJsonGridStructure());
}
if (getPortfolioGrid() != null) {
gridStructures.put("portfolio", getPortfolioGrid().getJsonGridStructure());
}
return gridStructures;
}
private ExecutorService getExecutorService() {
return _executorService;
}
private WebViewGrid getPortfolioGrid() {
return _portfolioGrid;
}
private WebViewGrid getPrimitivesGrid() {
return _primitivesGrid;
}
private ViewClient getViewClient() {
return _client;
}
private Client getLocal() {
return _local;
}
private Client getRemote() {
return _remote;
}
private ResultConverterCache getResultConverterCache() {
return _resultConverterCache;
}
}
|
import java.text.SimpleDateFormat;
import java.util.Date;
public class Assignment implements Cloneable {
private int id;
private Date dueDate;
private int points;
private double score;
private String name;
private assignmentType type;
// Constructors
public Assignment(int id, Date dueDate, int points, String name, assignmentType type) {
this.dueDate = dueDate;
this.points = points;
this.name = name;
this.type = type;
score = -1;
}
public Assignment(int id, int points, String name, assignmentType type) {
this(id, new Date(), points, name, type);
}
public Assignment(int id) {
this(id, new Date(), 0, "DEFAULT", assignmentType.HOMEWORK);
}
// Getters
public Date getDueDate() {
return dueDate;
}
public int getPoints() {
return points;
}
public double getScore() {
return score;
}
public assignmentType getAssignmentType() {
return type;
}
public String getName() {
return name;
}
public int getID() {
return id;
}
// Setters
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public void setPoints(int points) {
this.points = points;
}
public void setScore(double score) {
this.score = score;
}
public void setassignmentType(assignmentType type) {
this.type = type;
}
public void setName(String name) {
this.name = name;
}
public void setID(int id){
this.id = id;
}
@Override
public String toString() {
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String date = dateFormat.format(dueDate);
return "Assignment " + name + " is " + type + ". It is due " + date +
" and it's worth " + points + " point(s).";
}
public String getGrad() {
return score + " out of " + points + " points";
}
@Override
public Object clone() throws CloneNotSupportedException {
Assignment assignmentClone = (Assignment)super.clone();
assignmentClone.setDueDate((Date)(this.getDueDate().clone()));
return assignmentClone;
}
}
|
package com.allyants.boardview;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.ScaleAnimation;
import android.widget.FrameLayout;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Scroller;
import java.util.ArrayList;
public class BoardView extends FrameLayout {
private static final float GLOBAL_SCALE = 0.6f;
private static final int SCROLL_ANIMATION_DURATION = 325;
private boolean mCellIsMobile = false;
private BitmapDrawable mHoverCell;
private Rect mHoverCellCurrentBounds;
private Rect mHoverCellOriginalBounds;
private HorizontalScrollView mRootLayout;
private LinearLayout mParentLayout;
private int originalPosition = -1;
private int originalItemPosition = -1;
private DoneListener mDoneCallback = new DoneListener() {
@Override
public void onDone() {
}
};
private HeaderClickListener headerClickListener = new HeaderClickListener() {
@Override
public void onClick(View v, int column_pos) {
}
};
private ItemClickListener itemClickListener = new ItemClickListener() {
@Override
public void onClick(View v, int column_pos, int item_pos) {
}
};
private DragColumnStartCallback mDragColumnStartCallback = new DragColumnStartCallback() {
@Override
public void startDrag(View itemView, int originalPosition) {
}
@Override
public void changedPosition(View itemView, int originalPosition, int newPosition) {
}
@Override
public void endDrag(View itemView, int originalPosition, int newPosition) {
}
};
private DragItemStartCallback mDragItemStartCallback = new DragItemStartCallback() {
@Override
public void startDrag(View itemView, int originalPosition,int originalColumn) {
}
@Override
public void changedPosition(View itemView, int originalPosition,int originalColumn, int newPosition, int newColumn) {
}
@Override
public void endDrag(View itemView, int originalPosition,int originalColumn, int newPosition, int newColumn) {
}
};
public boolean constWidth = true;
private final int LINE_THICKNESS = 15;
private boolean can_scroll = false;
private boolean created = false;
private int mLastEventX = -1;
private int mLastEventY = -1;
private Scroller mScroller;
public interface DragColumnStartCallback{
void startDrag(View itemView, int originalPosition);
void changedPosition(View itemView, int originalPosition, int newPosition);
void endDrag(View itemView, int originalPosition, int newPosition);
}
public interface DragItemStartCallback{
void startDrag(View itemView, int originalPosition,int originalColumn);
void changedPosition(View itemView, int originalPosition,int originalColumn, int newPosition, int newColumn);
void endDrag(View itemView, int originalPosition,int originalColumn, int newPosition, int newColumn);
}
public interface HeaderClickListener{
void onClick(View v,int column_pos);
}
public interface ItemClickListener{
void onClick(View v,int column_pos,int item_pos);
}
public void setOnHeaderClickListener(HeaderClickListener headerClickListener){
this.headerClickListener = headerClickListener;
}
public void setOnItemClickListener(ItemClickListener itemClickListener){
this.itemClickListener = itemClickListener;
}
public void setOnDragColumnListener(DragColumnStartCallback dragStartCallback){
mDragColumnStartCallback = dragStartCallback;
}
public void setOnDragItemListener(DragItemStartCallback dragStartCallback){
mDragItemStartCallback = dragStartCallback;
}
public void setOnDoneListener(DoneListener onDoneListener){
mDoneCallback = onDoneListener;
}
long last_swap = System.currentTimeMillis();
long last_swap_item = System.currentTimeMillis();
final long ANIM_TIME = 300;
long mDelaySwap = 400;
long mDelaySwapItem = 400;
private int mLastSwap = -1;
private int mDownY = -1;
private int mDownX = -1;
private boolean mSwapped = false;
private boolean canDragHorizontal = true;
private boolean canDragVertical = true;
private boolean mCellSubIsMobile = false;
private int mTotalOffsetX = 0;
private int mTotalOffsetY = 0;
BoardAdapter boardAdapter;
private View mobileView;
public BoardView(Context context) {
super(context);
}
public BoardView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public BoardView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public interface DoneListener {
void onDone();
}
public void setAdapter(BoardAdapter boardAdapter){
this.boardAdapter = boardAdapter;
boardAdapter.createColumns();
for(int i = 0;i < boardAdapter.columns.size();i++){
BoardAdapter.Column column = boardAdapter.columns.get(i);
addColumnList(column.header,column.views,null);
}
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
mRootLayout = new HorizontalScrollView(getContext());
mRootLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
mParentLayout = new LinearLayout(getContext());
mParentLayout.setOrientation(LinearLayout.HORIZONTAL);
mScroller = new Scroller(mRootLayout.getContext(), new DecelerateInterpolator(1.2f));
mParentLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
mRootLayout.addView(mParentLayout);
addView(mRootLayout);
}
@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
if(!created){
created = true;
mDoneCallback.onDone();
}
if(mHoverCell != null){
mHoverCell.draw(canvas);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean colValue = handleColumnDragEvent(event);
return colValue || super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean colValue = handleColumnDragEvent(event);
return colValue || super.onTouchEvent(event);
}
public int getStatusBarHeight() {
int result = 0;
int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = getResources().getDimensionPixelSize(resourceId);
}
return result;
}
public void scrollToColumn(int column,boolean animate){
if(column >= 0) {
View childView = mParentLayout.getChildAt(column);
if(childView != null) {
int newX = childView.getLeft() - (int) (((getMeasuredWidth() - childView.getMeasuredWidth()) / 2));
if (animate) {
mRootLayout.smoothScrollTo(newX, 0);
} else {
mRootLayout.scrollTo(newX, 0);
}
}
}
}
public boolean handleColumnDragEvent(MotionEvent event){
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mDownX = (int)event.getX();
mDownY = (int)event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
if(mDownY == -1){
mDownY = (int)event.getRawY();
}
if(mDownX == -1){
mDownX = (int)event.getX();
}
mLastEventX = (int) event.getX();
mLastEventY = (int) event.getRawY();
int deltaX = mLastEventX - mDownX;
int deltaY = mLastEventY - mDownY;
if(mCellSubIsMobile){
int offsetX = 0;
if(canDragHorizontal){
offsetX = deltaX;
}
int offsetY = mHoverCellOriginalBounds.top;
if(canDragVertical){
offsetY = mHoverCellOriginalBounds.top + deltaY;
}
mHoverCellCurrentBounds.offsetTo(offsetX,
offsetY);
mHoverCell.setBounds(rotatedBounds(mHoverCellCurrentBounds,0.0523599f));
invalidate();
handleItemSwitchHorizontal();
return true;
}else if (mCellIsMobile) {
int offsetX = 0;
if(canDragHorizontal){
offsetX = deltaX;
}
int offsetY = mHoverCellOriginalBounds.top;
if(canDragVertical){
offsetY = mHoverCellOriginalBounds.top + deltaY + mTotalOffsetY;
}
mHoverCellCurrentBounds.offsetTo(offsetX,
offsetY);
mHoverCell.setBounds(rotatedBounds(mHoverCellCurrentBounds,0.0523599f));
invalidate();
handleColumnSwitchHorizontal();
return true;
}
break;
case MotionEvent.ACTION_UP:
touchEventsCancelled();
break;
case MotionEvent.ACTION_CANCEL:
touchEventsCancelled();
break;
case MotionEvent.ACTION_POINTER_UP:
/* If a multitouch event took place and the original touch dictating
* the movement of the hover cell has ended, then the dragging event
* ends and the hover cell is animated to its corresponding position
* in the listview. */
// pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >>
// MotionEvent.ACTION_POINTER_INDEX_SHIFT;
// final int pointerId = event.getPointerId(pointerIndex);
// if (pointerId == mActivePointerId) {
break;
default:
break;
}
return false;
}
@Override
public void computeScroll() {
if (!mScroller.isFinished() && mScroller.computeScrollOffset()) {
int x = mScroller.getCurrX();
int y = mScroller.getCurrY();
if (getScrollX() != x || getScrollY() != y) {
scrollTo(x, y);
}
ViewCompat.postInvalidateOnAnimation(this);
} else {
super.computeScroll();
}
}
private void handleItemSwitchHorizontal(){
int itemPos = ((LinearLayout)(mobileView.getParent())).indexOfChild(mobileView);
View aboveView = ((LinearLayout)(mobileView.getParent())).getChildAt(itemPos - 1);
View belowView = ((LinearLayout)(mobileView.getParent())).getChildAt(itemPos + 1);
//swapping above
int[] location = new int[2];
mobileView.getLocationOnScreen(location);
int[] parentLocation = new int[2];
ScrollView parent = ((ScrollView)((LinearLayout)mobileView.getParent()).getParent());
parent.getLocationOnScreen(parentLocation);
if(location[1]-mobileView.getHeight() < parentLocation[1]){
parent.smoothScrollBy(0,-10);
}
if(location[1]+mobileView.getHeight()+mobileView.getHeight() > parentLocation[1]+parent.getHeight()){
parent.smoothScrollBy(0,10);
}
if(aboveView != null){
int[] locationAbove = new int[2];
aboveView.getLocationInWindow(locationAbove);
if(locationAbove[1]+aboveView.getHeight() > mLastEventY){
switchItemFromPosition(-1,mobileView);
}
}
//swapping below
if(belowView != null){
int[] locationBelow = new int[2];
belowView.getLocationOnScreen(locationBelow);
if(locationBelow[1] < mLastEventY){
switchItemFromPosition(1,mobileView);
}
}
int columnPos = mParentLayout.indexOfChild((View)(mobileView.getParent().getParent().getParent()));
View leftView = mParentLayout.getChildAt(columnPos - 1);
View currentView = mParentLayout.getChildAt(columnPos);
View rightView = mParentLayout.getChildAt(columnPos + 1);
if(leftView != null){
int[] locationLeft = new int[2];
leftView.getLocationOnScreen(locationLeft);
if (locationLeft[0] + leftView.getWidth() > mLastEventX) {
int pos = ((LinearLayout)mobileView.getParent()).indexOfChild(mobileView);
if(last_swap_item <= System.currentTimeMillis() - mDelaySwapItem) {
last_swap_item = System.currentTimeMillis();
if(((LinearLayout)mobileView.getParent()) != null) {
((LinearLayout) mobileView.getParent()).removeViewAt(pos);
((LinearLayout)((ScrollView)((ViewGroup)leftView).getChildAt(1)).getChildAt(0)).addView(mobileView);
scrollToColumn(columnPos-1,true);
int newItemPos = ((LinearLayout)((ViewGroup)leftView).getChildAt(0)).indexOfChild(mobileView)-1;
int newColumnPos = ((LinearLayout)mobileView.getParent().getParent().getParent()).indexOfChild((View)(mobileView.getParent().getParent()));
mDragItemStartCallback.changedPosition(mobileView,originalItemPosition,originalPosition,newItemPos,newColumnPos);
}
}
}
}
if(rightView != null){
int[] locationRight = new int[2];
rightView.getLocationOnScreen(locationRight);
if (locationRight[0] < mLastEventX) {
int pos = ((LinearLayout)mobileView.getParent()).indexOfChild(mobileView);
if(last_swap_item <= System.currentTimeMillis() - mDelaySwapItem) {
last_swap_item = System.currentTimeMillis();
if(((LinearLayout)mobileView.getParent()) != null) {
((LinearLayout) mobileView.getParent()).removeViewAt(pos);
((LinearLayout)((ScrollView)((ViewGroup)rightView).getChildAt(1)).getChildAt(0)).addView(mobileView);
scrollToColumn(columnPos+1,true);
int newItemPos = ((LinearLayout)((ViewGroup)rightView).getChildAt(0)).indexOfChild(mobileView)-1;
int newColumnPos = ((LinearLayout)mobileView.getParent().getParent().getParent()).indexOfChild((View)(mobileView.getParent().getParent()));
mDragItemStartCallback.changedPosition(mobileView,originalItemPosition,originalPosition,newItemPos,newColumnPos);
}
}
}
}
}
private void switchItemFromPosition(int change,View view){
LinearLayout parentLayout = (LinearLayout)(view.getParent());
int columnPos = parentLayout.indexOfChild(view);
if(columnPos+change >= 0 && columnPos+change < parentLayout.getChildCount()) {
parentLayout.removeView(view);
parentLayout.addView(view, columnPos + change);
if(mDragItemStartCallback != null){
int newPos = parentLayout.indexOfChild(view);
last_swap = System.currentTimeMillis();
mLastSwap = newPos;
int newColumnPos = ((LinearLayout)mobileView.getParent().getParent().getParent().getParent()).indexOfChild((View)(mobileView.getParent().getParent().getParent()));
mDragItemStartCallback.changedPosition(view,originalItemPosition,originalPosition,newPos,newColumnPos);
}
}
}
private void handleColumnSwitchHorizontal(){
if(can_scroll && last_swap <= System.currentTimeMillis()-mDelaySwap) {
int columnPos = mParentLayout.indexOfChild(mobileView);
View leftView = mParentLayout.getChildAt(columnPos - 1);
View rightView = mParentLayout.getChildAt(columnPos + 1);
int[] locationRight = new int[2];
if (rightView != null) {
rightView.getLocationOnScreen(locationRight);
if (locationRight[0] < mLastEventX) {
//Scroll to the right
switchColumnFromPosition(1,mobileView);
if (locationRight[0] + (rightView.getWidth() / 2) < mLastEventX) {
}
}
}
int[] locationLeft = new int[2];
if (leftView != null) {
leftView.getLocationOnScreen(locationLeft);
if (locationLeft[0] + leftView.getWidth() > mLastEventX) {
//Scroll to the right
switchColumnFromPosition(-1,mobileView);
//mRootLayout.scrollBy(-1 * 2, 0);
if (locationLeft[0] + (leftView.getWidth() / 2) > mLastEventX) {
}
}
}
}
}
private void switchColumnFromPosition(int change,View view){
int columnPos = mParentLayout.indexOfChild(view);
if(columnPos+change >= 0 && last_swap <= System.currentTimeMillis()-mDelaySwap) {
mParentLayout.removeView(view);
mParentLayout.addView(view, columnPos + change);
if(mDragColumnStartCallback != null){
int newPos = mParentLayout.indexOfChild(view);
last_swap = System.currentTimeMillis();
mLastSwap = newPos;
Handler handlerTimer = new Handler();
handlerTimer.postDelayed(new Runnable(){
public void run() {
scrollToColumn(mLastSwap,true);
}}, 0);
mDragColumnStartCallback.changedPosition(((LinearLayout)view).getChildAt(0),originalPosition,newPos);
}
}
}
private void touchEventsCancelled() {
if(mCellSubIsMobile){
mobileView.setVisibility(VISIBLE);
mHoverCell = null;
invalidate();
if(mDragItemStartCallback != null){
LinearLayout parentLayout = (LinearLayout)(mobileView.getParent().getParent().getParent().getParent());
int columnPos = parentLayout.indexOfChild((View)(mobileView.getParent().getParent().getParent()));
//Subtract one because the first view is the header
int pos = ((LinearLayout)mobileView.getParent()).indexOfChild(mobileView);
View tmpView = boardAdapter.columns.get(originalPosition).views.get(originalItemPosition);
boardAdapter.columns.get(originalPosition).views.remove(originalItemPosition);
boardAdapter.columns.get(columnPos).views.add(pos,tmpView);
Object tmpObject = boardAdapter.columns.get(originalPosition).objects.get(originalItemPosition);
boardAdapter.columns.get(originalPosition).objects.remove(originalItemPosition);
boardAdapter.columns.get(columnPos).objects.add(pos,tmpObject);
mDragItemStartCallback.endDrag(mobileView,originalPosition,originalItemPosition,pos,columnPos);
}
}else if(mCellIsMobile){
for(int i = 0;i < mParentLayout.getChildCount();i++){
BoardItem parentView = (BoardItem)mParentLayout.getChildAt(i);//Gets the parent layout
for(int j = 0;j < parentView.getChildCount();j++) {
View childView = ((LinearLayout) parentView).getChildAt(j);
scrollToColumn(originalPosition, true);
scaleView(childView, parentView, GLOBAL_SCALE, 1f);
}
}
mobileView.setVisibility(VISIBLE);
mHoverCell = null;
invalidate();
if(mDragColumnStartCallback != null){
int columnPos = mParentLayout.indexOfChild(mobileView);
scrollToColumn(columnPos,true);
BoardAdapter.Column column = boardAdapter.columns.get(originalPosition);
boardAdapter.columns.remove(originalPosition);
boardAdapter.columns.add(columnPos,column);
mDragColumnStartCallback.endDrag(((LinearLayout)mobileView).getChildAt(0),originalPosition,columnPos);
}
}
mDownX = -1;
mDownY = -1;
mCellSubIsMobile = false;
mCellIsMobile = false;
}
Handler handler = new Handler();
public void scaleView(final View v, final BoardItem parent, final float startScale, final float endScale) {
final Animation anim = new ScaleAnimation(
startScale, endScale, // Start and end values for the X axis scaling
startScale, endScale, // Start and end values for the Y axis scaling
Animation.RELATIVE_TO_SELF,0f, // Pivot point of X scaling
Animation.RELATIVE_TO_SELF, 0f); // Pivot point of Y scaling
anim.setFillAfter(true); // Needed to keep the result of the animation
anim.setFillBefore(false);
anim.setFillEnabled(true);
anim.setDuration(ANIM_TIME);
v.startAnimation(anim);
final long startTime = System.currentTimeMillis();
anim.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
handler.post(createRunnable(parent,startTime,startScale,endScale));
can_scroll = false;
}
@Override
public void onAnimationEnd(Animation animation) {
parent.scale = endScale;
scrollToColumn(mLastSwap,true);
parent.requestLayout();
parent.invalidate();
can_scroll = true;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
}
private Runnable createRunnable(final BoardItem parent, final long startTime, final float startScale, final float endScale){
Runnable runnable = new Runnable() {
@Override
public void run() {
long time = System.currentTimeMillis()-startTime;
float scale_time = time/(float)ANIM_TIME;
if(scale_time > 1){
scale_time = 1;
}
scrollToColumn(mLastSwap,true);
parent.scale = startScale + (endScale - startScale)*scale_time;
parent.requestLayout();
parent.invalidate();
if(scale_time != 1) {
handler.postDelayed(this,10);
}
}
};
return runnable;
}
private void addColumnList(@Nullable View header, ArrayList<View> items, @Nullable View footer){
final BoardItem parent_layout = new BoardItem(getContext());
final LinearLayout layout = new LinearLayout(getContext());
final ScrollView scroll_view = new ScrollView(getContext());
final LinearLayout layout_children = new LinearLayout(getContext());
layout_children.setOrientation(LinearLayout.VERTICAL);
layout.setOrientation(LinearLayout.VERTICAL);
parent_layout.setOrientation(LinearLayout.VERTICAL);
if(constWidth) {
int margin = calculatePixelFromDensity(5);
LayoutParams params = new LayoutParams(calculatePixelFromDensity(240), LayoutParams.WRAP_CONTENT);
params.setMargins(margin,margin,margin,margin);
layout.setLayoutParams(params);
parent_layout.setLayoutParams(params);
}else {
int margin = calculatePixelFromDensity(5);
LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(margin,margin,margin,margin);
layout.setLayoutParams(params);
parent_layout.setLayoutParams(params);
}
parent_layout.addView(layout);
if(header != null){
layout.addView(header);
header.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int pos = mParentLayout.indexOfChild(parent_layout);
scrollToColumn(pos,true);
headerClickListener.onClick(v,pos);
}
});
header.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (mDragColumnStartCallback == null) {
return false;
}
originalPosition = mParentLayout.indexOfChild(parent_layout);
mDragColumnStartCallback.startDrag(layout,originalPosition);
mLastSwap = originalPosition;
for(int i = 0;i < mParentLayout.getChildCount();i++){
BoardItem parentView = (BoardItem)mParentLayout.getChildAt(i);//Gets the parent layout
for(int j = 0;j < parentView.getChildCount();j++) {
View childView = ((LinearLayout) parentView).getChildAt(j);
scrollToColumn(originalPosition, true);
scaleView(childView, parentView, 1f, GLOBAL_SCALE);
}
}
scrollToColumn(originalPosition,false);
mCellIsMobile = true;
mobileView = (View)(parent_layout);
mHoverCell = getAndAddHoverView(mobileView,GLOBAL_SCALE);
mobileView.setVisibility(INVISIBLE);
return false;
}
});
}
if(items.size() > 0){
parent_layout.addView(scroll_view);
scroll_view.addView(layout_children);
for(int i = 0;i < items.size();i++){
final View view = items.get(i);
layout_children.addView(view);
final int finalI = i;
view.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
int pos = mParentLayout.indexOfChild(parent_layout);
itemClickListener.onClick(v,pos, finalI);
}
});
view.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
if (mDragItemStartCallback == null) {
return false;
}
originalPosition = mParentLayout.indexOfChild(parent_layout);
originalItemPosition = ((LinearLayout)view.getParent()).indexOfChild(view);
mDragItemStartCallback.startDrag(view,originalPosition,originalItemPosition);
mCellSubIsMobile = true;
mobileView = (View)(view);
mHoverCell = getAndAddHoverView(mobileView,1);
mobileView.setVisibility(INVISIBLE);
return false;
}
});
}
}
if(footer != null) {
layout.addView(footer);
}
mParentLayout.addView(parent_layout);
}
private int calculatePixelFromDensity(float dp){
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
float fpixels = metrics.density * dp;
int pixels = (int) (fpixels + 0.5f);
return pixels;
}
private BitmapDrawable getAndAddHoverView(View v, float scale){
int w = v.getWidth();
int h = v.getHeight();
int top = v.getTop();
int left = v.getLeft();
Bitmap b = getBitmapWithBorder(v,scale);
BitmapDrawable drawable = new BitmapDrawable(getResources(),b);
mHoverCellOriginalBounds = new Rect(left,top,left+w,top+h);
mHoverCellCurrentBounds = new Rect(mHoverCellOriginalBounds);
drawable.setBounds(mHoverCellCurrentBounds);
return drawable;
}
private Bitmap getBitmapWithBorder(View v, float scale) {
Bitmap bitmap = getBitmapFromView(v,0);
Bitmap b = getBitmapFromView(v,1);
Canvas can = new Canvas(bitmap);
Paint paint = new Paint();
paint.setAlpha(150);
can.scale(scale,scale,mDownX,mDownY);
can.rotate(3);
can.drawBitmap(b,0,0,paint);
return bitmap;
}
private Bitmap getBitmapFromView(View v, float scale){
double radians = 0.0523599f;
double s = Math.abs(Math.sin(radians));
double c = Math.abs(Math.cos(radians));
int width = (int)(v.getHeight()*s + v.getWidth()*c);
int height = (int)(v.getWidth()*s + v.getHeight()*c);
Bitmap bitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.scale(scale,scale);
v.draw(canvas);
return bitmap;
}
private Rect rotatedBounds(Rect tmp,double radians){
double s = Math.abs(Math.sin(radians));
double c = Math.abs(Math.cos(radians));
int width = (int)(tmp.height()*s + tmp.width()*c);
int height = (int)(tmp.width()*s + tmp.height()*c);
return new Rect(tmp.left,tmp.top,tmp.left+width,tmp.top+height);
}
}
|
package uk.me.karlsen.ode;
import java.util.ArrayList;
import java.util.List;
/**
* A store for base item objects belonging
* to the BaseItem class. Interfaces with
* ReaderWriter for the purposes of reading
* in items to the store and writing out
* items back to the EXE.
*/
public class BaseItemStore {
private ReaderWriter rw;
private List<BaseItem> baseItems;
public BaseItemStore(ReaderWriter rw) {
this.rw = rw;
baseItems = new ArrayList<BaseItem>();
this.readInItems();
}
private void readInItems() {
long pos = TomeOfKnowledge.BASE_ITEMS_OFFSET;
rw.seek(pos);
for(int i = 0; i < TomeOfKnowledge.NUMBER_OF_BASE_ITEMS; i++){
byte[] itemBytes = new byte[TomeOfKnowledge.BASE_ITEM_LENGTH_IN_BYTES];
itemBytes = rw.readBytes(TomeOfKnowledge.BASE_ITEM_LENGTH_IN_BYTES);
BaseItem bi = new BaseItem(i, itemBytes, rw);
baseItems.add(bi);
pos = pos + TomeOfKnowledge.BASE_ITEM_LENGTH_IN_BYTES;
rw.seek(pos);
}
}
public void printItems() {
for(BaseItem bi : baseItems){
bi.printItem();
}
}
public void writeItemsToEXE() {
long pos = TomeOfKnowledge.BASE_ITEMS_OFFSET;
for(BaseItem bi : baseItems){
byte[] itemAsBytes = bi.getItemAsBytes();
rw.writeBytes(itemAsBytes, pos);
pos = pos + TomeOfKnowledge.BASE_ITEM_LENGTH_IN_BYTES;
}
}
}
|
package com.browseengine.bobo.api;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.FieldSelector;
import org.apache.lucene.document.FieldSelectorResult;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.search.Collector;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.SortField;
import org.apache.lucene.search.Weight;
import com.browseengine.bobo.facets.CombinedFacetAccessible;
import com.browseengine.bobo.facets.FacetCountCollector;
import com.browseengine.bobo.facets.FacetHandler;
import com.browseengine.bobo.facets.FacetHandlerInitializerParam;
import com.browseengine.bobo.facets.RuntimeFacetHandler;
import com.browseengine.bobo.facets.RuntimeFacetHandlerFactory;
import com.browseengine.bobo.facets.filter.AndFilter;
import com.browseengine.bobo.facets.filter.RandomAccessFilter;
import com.browseengine.bobo.search.BoboSearcher2;
import com.browseengine.bobo.search.FacetHitCollector;
import com.browseengine.bobo.sort.SortCollector;
/**
* This class implements the browsing functionality.
*/
public class BoboSubBrowser extends BoboSearcher2 implements Browsable
{
private static Logger logger = Logger.getLogger(BoboSubBrowser.class);
private final BoboIndexReader _reader;
private final Map<String, RuntimeFacetHandlerFactory<?,?>> _runtimeFacetHandlerFactoryMap;
private final HashMap<String, FacetHandler<?>> _runtimeFacetHandlerMap;
private HashMap<String, FacetHandler<?>> _allFacetHandlerMap;
private ArrayList<RuntimeFacetHandler<?>> _runtimeFacetHandlers = null;
public BoboIndexReader getIndexReader()
{
return _reader;
}
/**
* Constructor.
*
* @param reader
* A bobo reader instance
*/
public BoboSubBrowser(BoboIndexReader reader)
{
super(reader);
_reader = reader;
_runtimeFacetHandlerMap = new HashMap<String, FacetHandler<?>>();
_runtimeFacetHandlerFactoryMap = reader.getRuntimeFacetHandlerFactoryMap();
_allFacetHandlerMap = null;
}
private boolean isNoQueryNoFilter(BrowseRequest req)
{
Query q = req.getQuery();
Filter filter = req.getFilter();
return ((q == null || q instanceof MatchAllDocsQuery) && filter == null && !_reader.hasDeletions());
}
public Object[] getRawFieldVal(int docid,String fieldname) throws IOException{
FacetHandler<?> facetHandler = getFacetHandler(fieldname);
if (facetHandler==null){
return getFieldVal(docid,fieldname);
}
else{
return facetHandler.getRawFieldValues(_reader,docid);
}
}
/**
* Sets runtime facet handler. If has the same name as a preload handler, for the
* duration of this browser, this one will be used.
*
* @param facetHandler
* Runtime facet handler
*/
public void setFacetHandler(FacetHandler<?> facetHandler) throws IOException
{
Set<String> dependsOn = facetHandler.getDependsOn();
BoboIndexReader reader = (BoboIndexReader) getIndexReader();
if (dependsOn.size() > 0)
{
Iterator<String> iter = dependsOn.iterator();
while(iter.hasNext())
{
String fn = iter.next();
FacetHandler<?> f = _runtimeFacetHandlerMap.get(fn);
if (f == null)
{
f = reader.getFacetHandler(fn);
}
if (f==null)
{
throw new IOException("depended on facet handler: "+fn+", but is not found");
}
facetHandler.putDependedFacetHandler(f);
}
}
facetHandler.loadFacetData(reader);
_runtimeFacetHandlerMap.put(facetHandler.getName(), facetHandler);
}
/**
* Gets a defined facet handler
*
* @param name
* facet name
* @return a facet handler
*/
public FacetHandler<?> getFacetHandler(String name)
{
return getFacetHandlerMap().get(name);
}
public Map<String,FacetHandler<?>> getFacetHandlerMap(){
if (_allFacetHandlerMap == null){
_allFacetHandlerMap = new HashMap<String,FacetHandler<?>>(_reader.getFacetHandlerMap());
}
_allFacetHandlerMap.putAll(_runtimeFacetHandlerMap);
return _allFacetHandlerMap;
}
/**
* Gets a set of facet names
*
* @return set of facet names
*/
public Set<String> getFacetNames()
{
Map<String,FacetHandler<?>> map = getFacetHandlerMap();
return map.keySet();
}
/**
* browses the index.
*
* @param req
* browse request
* @param collector
* collector for the hits
* @param facetMap map to gather facet data
*/
public void browse(BrowseRequest req,
Collector collector,
Map<String, FacetAccessible> facetMap) throws BrowseException
{
browse(req, collector, facetMap, 0);
}
public void browse(BrowseRequest req,
Collector collector,
Map<String, FacetAccessible> facetMap,
int start) throws BrowseException
{
Weight w = null;
try
{
Query q = req.getQuery();
if (q == null)
{
q = new MatchAllDocsQuery();
}
w = createWeight(q);
}
catch (IOException ioe)
{
throw new BrowseException(ioe.getMessage(), ioe);
}
browse(req, w, collector, facetMap, start);
}
public void browse(BrowseRequest req,
Weight weight,
Collector collector,
Map<String, FacetAccessible> facetMap,
int start) throws BrowseException
{
if (_reader == null)
return;
// initialize all RuntimeFacetHandlers with data supplied by user at run-time.
_runtimeFacetHandlers = new ArrayList<RuntimeFacetHandler<?>>(_runtimeFacetHandlerFactoryMap.size());
Set<String> runtimeFacetNames = _runtimeFacetHandlerFactoryMap.keySet();
for(String facetName : runtimeFacetNames)
{
FacetHandler<?> sfacetHandler = this.getFacetHandler(facetName);
if (sfacetHandler!=null)
{
logger.warn("attempting to reset facetHandler: " + sfacetHandler);
continue;
}
RuntimeFacetHandlerFactory<FacetHandlerInitializerParam,?> factory = (RuntimeFacetHandlerFactory<FacetHandlerInitializerParam, ?>) _runtimeFacetHandlerFactoryMap.get(facetName);
FacetHandlerInitializerParam data = req.getFacethandlerData(facetName);
if(data != null)
{
RuntimeFacetHandler<?> facetHandler = factory.get(data);
_runtimeFacetHandlers.add(facetHandler); // add to a list so we close them after search
try
{
this.setFacetHandler(facetHandler);
}
catch (IOException e)
{
logger.warn("error trying to set FacetHandler : " + facetHandler);
}
}
}
// done initialize all RuntimeFacetHandlers with data supplied by user at run-time.
Set<String> fields = getFacetNames();
LinkedList<Filter> preFilterList = new LinkedList<Filter>();
List<FacetHitCollector> facetHitCollectorList = new LinkedList<FacetHitCollector>();
Filter baseFilter = req.getFilter();
if (baseFilter != null)
{
preFilterList.add(baseFilter);
}
int selCount = req.getSelectionCount();
boolean isNoQueryNoFilter = isNoQueryNoFilter(req);
boolean isDefaultSearch = isNoQueryNoFilter && selCount == 0;
try
{
for (String name : fields)
{
BrowseSelection sel = req.getSelection(name);
FacetSpec ospec = req.getFacetSpec(name);
FacetHandler<?> handler = getFacetHandler(name);
if (handler == null){
logger.warn("facet handler: "+name+" is not defined, ignored.");
continue;
}
FacetHitCollector facetHitCollector = null;
RandomAccessFilter filter = null;
if (sel != null)
{
filter = handler.buildFilter(sel);
}
if (ospec == null)
{
if (filter != null)
{
preFilterList.add(filter);
}
}
else
{
/*FacetSpec fspec = new FacetSpec(); // OrderValueAsc,
fspec.setMaxCount(0);
fspec.setMinHitCount(1);
fspec.setExpandSelection(ospec.isExpandSelection());*/
FacetSpec fspec = ospec;
facetHitCollector = new FacetHitCollector();
facetHitCollector.facetHandler = handler;
if (isDefaultSearch)
{
facetHitCollector._collectAllSource=handler.getFacetCountCollectorSource(sel, fspec);
}
else
{
facetHitCollector._facetCountCollectorSource = handler.getFacetCountCollectorSource(sel, fspec);
if (ospec.isExpandSelection())
{
if (isNoQueryNoFilter && sel!=null && selCount == 1)
{
facetHitCollector._collectAllSource=handler.getFacetCountCollectorSource(sel, fspec);
if (filter != null)
{
preFilterList.add(filter);
}
}
else
{
if (filter != null)
{
facetHitCollector._filter = filter;
}
}
}
else
{
if (filter != null)
{
preFilterList.add(filter);
}
}
}
}
if (facetHitCollector != null)
{
facetHitCollectorList.add(facetHitCollector);
}
}
Filter finalFilter = null;
if (preFilterList.size() > 0)
{
if (preFilterList.size() == 1)
{
finalFilter = preFilterList.getFirst();
}
else
{
finalFilter = new AndFilter(preFilterList);
}
}
setFacetHitCollectorList(facetHitCollectorList);
try
{
search(weight, finalFilter, collector, start);
}
finally
{
for (FacetHitCollector facetCollector : facetHitCollectorList)
{
String name = facetCollector.facetHandler.getName();
LinkedList<FacetCountCollector> resultcollector=null;
resultcollector = facetCollector._countCollectorList;
if (resultcollector == null || resultcollector.size() == 0){
resultcollector = facetCollector._collectAllCollectorList;
}
if (resultcollector!=null){
FacetSpec fspec = req.getFacetSpec(name);
assert fspec != null;
if(resultcollector.size() == 1)
{
facetMap.put(name, resultcollector.get(0));
}
else
{
ArrayList<FacetAccessible> finalList = new ArrayList<FacetAccessible>(resultcollector.size());
for (FacetCountCollector fc : resultcollector){
finalList.add((FacetAccessible)fc);
}
CombinedFacetAccessible combinedCollector = new CombinedFacetAccessible(fspec, finalList);
facetMap.put(name, combinedCollector);
}
}
}
}
}
catch (IOException ioe)
{
throw new BrowseException(ioe.getMessage(), ioe);
}
}
public SortCollector getSortCollector(SortField[] sort,Query q,int offset,int count,boolean fetchStoredFields,boolean forceScoring){
return SortCollector.buildSortCollector(this,q,sort, offset, count, forceScoring,fetchStoredFields);
}
/**
* browses the index.
*
* @param req
* browse request
* @return browse result
*/
public BrowseResult browse(BrowseRequest req) throws BrowseException
{
if (_reader == null)
return new BrowseResult();
final BrowseResult result = new BrowseResult();
long start = System.currentTimeMillis();
SortCollector collector = getSortCollector(req.getSort(),req.getQuery(), req.getOffset(), req.getCount(), req.isFetchStoredFields(),false);
Map<String, FacetAccessible> facetCollectors = new HashMap<String, FacetAccessible>();
browse(req, collector, facetCollectors);
BrowseHit[] hits = null;
try
{
hits = collector.topDocs();
}
catch (IOException e)
{
logger.error(e.getMessage(), e);
hits = new BrowseHit[0];
}
Query q = req.getQuery();
if (q == null){
q = new MatchAllDocsQuery();
}
if (req.isShowExplanation()){
for (BrowseHit hit : hits){
try {
Explanation expl = explain(q, hit.getDocid());
hit.setExplanation(expl);
} catch (IOException e) {
logger.error(e.getMessage(),e);
}
}
}
result.setHits(hits);
result.setNumHits(collector.getTotalHits());
result.setTotalDocs(_reader.numDocs());
result.addAll(facetCollectors);
long end = System.currentTimeMillis();
result.setTime(end - start);
return result;
}
public Map<String, FacetHandler<?>> getRuntimeFacetHandlerMap()
{
return _runtimeFacetHandlerMap;
}
public int numDocs()
{
return _reader.numDocs();
}
@Override
public Document doc(int docid) throws CorruptIndexException,
IOException
{
Document doc = super.doc(docid);
for (FacetHandler<?> handler : _runtimeFacetHandlerMap.values())
{
String[] vals = handler.getFieldValues(_reader,docid);
for (String val : vals)
{
doc.add(new Field(handler.getName(),
val,
Field.Store.NO,
Field.Index.NOT_ANALYZED));
}
}
return doc;
}
/**
* Returns the field data for a given doc.
*
* @param docid
* doc
* @param fieldname
* name of the field
* @return field data
*/
public String[] getFieldVal(int docid, final String fieldname) throws IOException
{
FacetHandler<?> facetHandler = getFacetHandler(fieldname);
if (facetHandler != null)
{
return facetHandler.getFieldValues(_reader,docid);
}
else
{
logger.warn("facet handler: " + fieldname
+ " not defined, looking at stored field.");
// this is not predefined, so it will be slow
Document doc = _reader.document(docid, new FieldSelector()
{
private static final long serialVersionUID = 1L;
public FieldSelectorResult accept(String field)
{
if (fieldname.equals(field))
{
return FieldSelectorResult.LOAD_AND_BREAK;
}
else
{
return FieldSelectorResult.NO_LOAD;
}
}
});
return doc.getValues(fieldname);
}
}
public void close() throws IOException
{
if (_runtimeFacetHandlers!=null)
{
for(RuntimeFacetHandler<?> handler : _runtimeFacetHandlers)
{
handler.close();
}
}
if(_reader != null) _reader.clearRuntimeFacetData();
super.close();
}
}
|
package org.azavea.otm.ui;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import org.azavea.otm.App;
import org.azavea.otm.R;
import org.azavea.otm.FilterManager;
import org.azavea.otm.adapters.SpeciesAdapter;
import org.azavea.otm.data.Species;
import org.json.JSONException;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class SpeciesListDisplay extends ListActivity {
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
FilterManager search = App.getFilterManager();
if (search.getSpecies().size() > 0) {
renderSpeciesList();
} else {
search.loadSpeciesList(new Callback() {
@Override
public boolean handleMessage(Message msg) {
if (msg.getData().getBoolean("success")) {
renderSpeciesList();
} else
{
Toast.makeText(App.getInstance(), "Could not get species list",
Toast.LENGTH_SHORT).show();
}
return true;
}
});
}
}
private void renderSpeciesList() {
LinkedHashMap<Integer, Species> list = App.getFilterManager().getSpecies();
Species[] species = new Species[list.size()];
int i = 0;
for (Map.Entry<Integer,Species> entry : list.entrySet()) {
species[i] = entry.getValue();
i++;
}
// Sort by common name
Arrays.sort(species);
// Bind the custom adapter to the view
SpeciesAdapter adapter = new SpeciesAdapter(this, R.layout.species_list_row,
species);
Log.d(App.LOG_TAG, list.size() + " species loaded");
setListAdapter(adapter);
setContentView(R.layout.species_list_selector);
setupFiltering(adapter);
}
private void setupFiltering(final SpeciesAdapter adapter) {
EditText filterEditText = (EditText) findViewById(R.id.species_filter_text);
setKeyboardChangeEvents(adapter, filterEditText);
setTextWatcherEvents(adapter, filterEditText);
}
/**
* Listen on events of the filter text box to pass along filter text
* and invalidate the current view
*/
private void setTextWatcherEvents(final SpeciesAdapter adapter,
EditText filterEditText) {
filterEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {}
@Override
public void afterTextChanged(Editable s) {
adapter.getFilter().filter(s);
adapter.notifyDataSetChanged();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {}
});
}
/**
* Listen on events the keyboard emits when finished editing
* ('Done' and 'Next' are the ENTER event).
* The Keyboard ENTER event on a ListActivity will re-render
* the list, so the current view must be invalidated
*/
private void setKeyboardChangeEvents(final SpeciesAdapter adapter,
EditText filterEditText) {
filterEditText.setOnKeyListener(new View.OnKeyListener()
{
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
{
adapter.notifyDataSetChanged();
}
return false;
}
});
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Species selection = (Species)l.getItemAtPosition(position);
Intent result = new Intent();
// The underlying JSONObject of Species is not serializable, so just
// return the information to use for querying
try {
result.putExtra("species_id", selection.getId());
} catch (JSONException e) {
e.printStackTrace();
}
setResult(RESULT_OK, result);
finish();
}
}
|
package com.intellij.ui;
import com.intellij.featureStatistics.FeatureUsageTracker;
import com.intellij.ide.DataManager;
import com.intellij.ide.ui.UISettings;
import com.intellij.internal.statistic.eventLog.FeatureUsageData;
import com.intellij.internal.statistic.service.fus.collectors.UIEventId;
import com.intellij.internal.statistic.service.fus.collectors.UIEventLogger;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.CustomShortcutSet;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Disposer;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowManager;
import com.intellij.openapi.wm.ex.ToolWindowManagerListener;
import com.intellij.ui.border.CustomLineBorder;
import com.intellij.ui.speedSearch.SpeedSearch;
import com.intellij.ui.speedSearch.SpeedSearchSupply;
import com.intellij.util.text.NameUtilCore;
import com.intellij.util.ui.JBUI;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;
import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ListIterator;
import java.util.NoSuchElementException;
public abstract class SpeedSearchBase<Comp extends JComponent> extends SpeedSearchSupply {
private static final Logger LOG = Logger.getInstance(SpeedSearchBase.class);
private static final Border BORDER = new CustomLineBorder(JBColor.namedColor("SpeedSearch.borderColor", JBColor.GRAY), JBUI.insets(1));
private static final Color FOREGROUND_COLOR = JBColor.namedColor("SpeedSearch.foreground", UIUtil.getToolTipForeground());
private static final Color BACKGROUND_COLOR = JBColor.namedColor("SpeedSearch.background", new JBColor(Gray.xFF, Gray._111));
private static final Color ERROR_FOREGROUND_COLOR = JBColor.namedColor("SpeedSearch.errorForeground", JBColor.RED);
private SearchPopup mySearchPopup;
private JLayeredPane myPopupLayeredPane;
protected final Comp myComponent;
private final ToolWindowManagerListener myWindowManagerListener = new ToolWindowManagerListener() {
@Override
public void stateChanged(@NotNull ToolWindowManager toolWindowManager) {
if (isInsideActiveToolWindow(toolWindowManager)) {
if (!isPopupActive()) {
showPopup();
}
} else {
manageSearchPopup(null);
}
}
private boolean isInsideActiveToolWindow(@NotNull ToolWindowManager toolWindowManager) {
ToolWindow toolWindow = toolWindowManager.getToolWindow(toolWindowManager.getActiveToolWindowId());
return toolWindow != null && SwingUtilities.isDescendingFrom(myComponent, toolWindow.getComponent());
}
};
private final PropertyChangeSupport myChangeSupport = new PropertyChangeSupport(this);
private String myRecentEnteredPrefix;
private SpeedSearchComparator myComparator = new SpeedSearchComparator(false);
private boolean myClearSearchOnNavigateNoMatch;
private Disposable myListenerDisposable;
public SpeedSearchBase(@NotNull Comp component) {
myComponent = component;
myComponent.addComponentListener(new ComponentAdapter() {
@Override
public void componentHidden(ComponentEvent event) {
manageSearchPopup(null);
}
@Override
public void componentMoved(ComponentEvent event) {
moveSearchPopup();
}
@Override
public void componentResized(ComponentEvent event) {
moveSearchPopup();
}
});
myComponent.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
manageSearchPopup(null);
}
});
myComponent.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent e) {
processKeyEvent(e);
}
@Override
public void keyPressed(KeyEvent e) {
processKeyEvent(e);
}
});
new AnAction() {
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
final String prefix = getEnteredPrefix();
assert prefix != null;
final String[] strings = NameUtilCore.splitNameIntoWords(prefix);
final String last = strings[strings.length - 1];
final int i = prefix.lastIndexOf(last);
mySearchPopup.mySearchField.setText(prefix.substring(0, i).trim());
}
@Override
public void update(@NotNull AnActionEvent e) {
e.getPresentation().setEnabled(isPopupActive() && !StringUtil.isEmpty(getEnteredPrefix()));
}
}.registerCustomShortcutSet(CustomShortcutSet.fromString(SystemInfo.isMac ? "meta BACK_SPACE" : "control BACK_SPACE"), myComponent);
installSupplyTo(component);
}
@Nullable
public JTextField getSearchField() {
if (mySearchPopup != null) {
return mySearchPopup.mySearchField;
}
return null;
}
public static boolean hasActiveSpeedSearch(JComponent component) {
return getSupply(component) != null;
}
public void setClearSearchOnNavigateNoMatch(boolean clearSearchOnNavigateNoMatch) {
myClearSearchOnNavigateNoMatch = clearSearchOnNavigateNoMatch;
}
@Override
public boolean isPopupActive() {
return mySearchPopup != null && mySearchPopup.isVisible();
}
@Override
public Iterable<TextRange> matchingFragments(@NotNull String text) {
if (!isPopupActive()) return null;
final SpeedSearchComparator comparator = getComparator();
final String recentSearchText = comparator.getRecentSearchText();
return StringUtil.isNotEmpty(recentSearchText) ? comparator.matchingFragments(recentSearchText, text) : null;
}
/**
* Returns visual (view) selection index.
*/
protected abstract int getSelectedIndex();
protected abstract Object @NotNull [] getAllElements();
@Nullable
protected abstract String getElementText(Object element);
protected int getElementCount() {
return getAllElements().length;
}
/**
* Should convert given view index to model index
*/
protected int convertIndexToModel(final int viewIndex) {
return viewIndex;
}
/**
* @param element Element to select. Don't forget to convert model index to view index if needed (i.e. table.convertRowIndexToView(modelIndex), etc).
* @param selectedText search text
*/
protected abstract void selectElement(Object element, String selectedText);
@NotNull
protected ListIterator<Object> getElementIterator(int startingIndex) {
return new ViewIterator(this, startingIndex < 0 ? getElementCount() : startingIndex);
}
@Override
public void addChangeListener(@NotNull PropertyChangeListener listener) {
myChangeSupport.addPropertyChangeListener(listener);
}
@Override
public void removeChangeListener(@NotNull PropertyChangeListener listener) {
myChangeSupport.removePropertyChangeListener(listener);
}
private void fireStateChanged() {
String enteredPrefix = getEnteredPrefix();
myChangeSupport.firePropertyChange(ENTERED_PREFIX_PROPERTY_NAME, myRecentEnteredPrefix, enteredPrefix);
myRecentEnteredPrefix = enteredPrefix;
}
protected boolean isMatchingElement(Object element, String pattern) {
String str = getElementText(element);
return str != null && compare(str, pattern);
}
protected boolean compare(@NotNull String text, @Nullable String pattern) {
return pattern != null && myComparator.matchingFragments(pattern, text) != null;
}
public SpeedSearchComparator getComparator() {
return myComparator;
}
public void setComparator(final SpeedSearchComparator comparator) {
myComparator = comparator;
}
@Nullable
private Object findNextElement(String s) {
final int selectedIndex = getSelectedIndex();
final ListIterator<?> it = getElementIterator(selectedIndex + 1);
final Object current;
if (it.hasPrevious()) {
current = it.previous();
it.next();
}
else {
current = null;
}
final String _s = s.trim();
while (it.hasNext()) {
final Object element = it.next();
if (isMatchingElement(element, _s)) return element;
}
if (UISettings.getInstance().getCycleScrolling()) {
final ListIterator<Object> i = getElementIterator(0);
while (i.hasNext()) {
final Object element = i.next();
if (isMatchingElement(element, _s)) return element;
}
}
return current != null && isMatchingElement(current, _s) ? current : null;
}
@Nullable
private Object findPreviousElement(@NotNull String s) {
final int selectedIndex = getSelectedIndex();
if (selectedIndex < 0) return null;
final ListIterator<?> it = getElementIterator(selectedIndex);
final Object current;
if (it.hasNext()) {
current = it.next();
it.previous();
}
else {
current = null;
}
final String _s = s.trim();
while (it.hasPrevious()) {
final Object element = it.previous();
if (isMatchingElement(element, _s)) return element;
}
if (UISettings.getInstance().getCycleScrolling()) {
final ListIterator<Object> i = getElementIterator(getElementCount());
while (i.hasPrevious()) {
final Object element = i.previous();
if (isMatchingElement(element, _s)) return element;
}
}
return isMatchingElement(current, _s) ? current : null;
}
@Nullable
protected Object findElement(@NotNull String s) {
int selectedIndex = getSelectedIndex();
if (selectedIndex < 0) {
selectedIndex = 0;
}
final ListIterator<Object> it = getElementIterator(selectedIndex);
final String _s = s.trim();
while (it.hasNext()) {
final Object element = it.next();
if (isMatchingElement(element, _s)) return element;
}
if (selectedIndex > 0) {
while (it.hasPrevious()) it.previous();
while (it.hasNext() && it.nextIndex() != selectedIndex) {
final Object element = it.next();
if (isMatchingElement(element, _s)) return element;
}
}
return null;
}
@Nullable
private Object findFirstElement(String s) {
final String _s = s.trim();
for (ListIterator<?> it = getElementIterator(0); it.hasNext();) {
final Object element = it.next();
if (isMatchingElement(element, _s)) return element;
}
return null;
}
@Nullable
private Object findLastElement(String s) {
final String _s = s.trim();
for (ListIterator<?> it = getElementIterator(-1); it.hasPrevious();) {
final Object element = it.previous();
if (isMatchingElement(element, _s)) return element;
}
return null;
}
public void showPopup(String searchText) {
manageSearchPopup(new SearchPopup(searchText));
}
public void showPopup() {
showPopup("");
}
public void hidePopup() {
manageSearchPopup(null);
}
protected void processKeyEvent(KeyEvent e) {
if (e.isAltDown()) return;
if (e.isShiftDown() && isNavigationKey(e.getKeyCode())) return;
if (mySearchPopup != null) {
mySearchPopup.processKeyEvent(e);
return;
}
if (!isSpeedSearchEnabled()) return;
if (e.getID() == KeyEvent.KEY_TYPED) {
if (!UIUtil.isReallyTypedEvent(e)) return;
char c = e.getKeyChar();
if (Character.isLetterOrDigit(c) || !Character.isWhitespace(c) && SpeedSearch.PUNCTUATION_MARKS.indexOf(c) != -1) {
manageSearchPopup(new SearchPopup(String.valueOf(c)));
e.consume();
}
}
}
private void logEvent(UIEventId id) {
FeatureUsageData data = new FeatureUsageData();
data.addData("class", myComponent.getClass().getName());
UIEventLogger.logUIEvent(id, data);
}
public Comp getComponent() {
return myComponent;
}
protected boolean isSpeedSearchEnabled() {
return true;
}
@Override
@Nullable
public String getEnteredPrefix() {
return mySearchPopup != null ? mySearchPopup.mySearchField.getText() : null;
}
@Override
public void refreshSelection() {
if ( mySearchPopup != null ) mySearchPopup.refreshSelection();
}
@Override
public void findAndSelectElement(@NotNull String searchQuery) {
selectElement(findElement(searchQuery), searchQuery);
}
public boolean adjustSelection(int keyCode, @NotNull String searchQuery) {
if (isUpDownHomeEnd(keyCode)) {
logEvent(UIEventId.IncrementalSearchNextPrevItemSelected);
Object element = findTargetElement(keyCode, searchQuery);
if (element != null) {
selectElement(element, searchQuery);
return true;
}
}
return false;
}
@Nullable
private Object findTargetElement(int keyCode, @NotNull String searchPrefix) {
if (keyCode == KeyEvent.VK_UP) {
return findPreviousElement(searchPrefix);
}
else if (keyCode == KeyEvent.VK_DOWN) {
return findNextElement(searchPrefix);
}
else if (keyCode == KeyEvent.VK_HOME) {
return findFirstElement(searchPrefix);
}
else {
assert keyCode == KeyEvent.VK_END;
return findLastElement(searchPrefix);
}
}
private class SearchPopup extends JPanel {
private final SearchField mySearchField;
SearchPopup(String initialString) {
mySearchField = new SearchField();
final JLabel searchLabel = new JLabel(" " + UIBundle.message("search.popup.search.for.label") + " ");
searchLabel.setFont(searchLabel.getFont().deriveFont(Font.BOLD));
searchLabel.setForeground(FOREGROUND_COLOR);
mySearchField.setBorder(null);
mySearchField.setBackground(BACKGROUND_COLOR);
mySearchField.setForeground(FOREGROUND_COLOR);
mySearchField.setDocument(new PlainDocument() {
@Override
public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
String oldText;
try {
oldText = getText(0, getLength());
}
catch (BadLocationException e1) {
oldText = "";
}
String newText = oldText.substring(0, offs) + str + oldText.substring(offs);
super.insertString(offs, str, a);
if (findElement(newText) == null) {
mySearchField.setForeground(ERROR_FOREGROUND_COLOR);
}
else {
mySearchField.setForeground(FOREGROUND_COLOR);
}
}
});
mySearchField.setText(initialString);
setBorder(BORDER);
setBackground(BACKGROUND_COLOR);
setLayout(new BorderLayout());
add(searchLabel, BorderLayout.WEST);
add(mySearchField, BorderLayout.EAST);
Object element = findElement(mySearchField.getText());
onSearchFieldUpdated(initialString);
updateSelection(element);
}
@Override
public void processKeyEvent(KeyEvent e) {
mySearchField.processKeyEvent(e);
if (e.isConsumed()) {
String s = mySearchField.getText();
onSearchFieldUpdated(s);
int keyCode = e.getKeyCode();
Object element;
if (isUpDownHomeEnd(keyCode)) {
element = findTargetElement(keyCode, s);
if (myClearSearchOnNavigateNoMatch && element == null) {
manageSearchPopup(null);
element = findTargetElement(keyCode, "");
}
}
else {
logEvent(UIEventId.IncrementalSearchKeyTyped);
element = findElement(s);
}
updateSelection(element);
}
}
void refreshSelection() {
findAndSelectElement(mySearchField.getText());
}
private void updateSelection(Object element) {
if (element != null) {
selectElement(element, mySearchField.getText());
mySearchField.setForeground(FOREGROUND_COLOR);
}
else {
mySearchField.setForeground(ERROR_FOREGROUND_COLOR);
}
if (mySearchPopup != null) {
mySearchPopup.setSize(mySearchPopup.getPreferredSize());
mySearchPopup.validate();
}
fireStateChanged();
}
}
protected void onSearchFieldUpdated(String pattern) {
}
private class SearchField extends JTextField {
SearchField() {
setFocusable(false);
}
@Override
public void setForeground(Color color) {
super.setForeground(color);
}
@Override
public Dimension getPreferredSize() {
Dimension dim = super.getPreferredSize();
Insets m = getMargin();
dim.width = getFontMetrics(getFont()).stringWidth(getText()) + 10 + m.left + m.right;
return dim;
}
/**
* I made this method public in order to be able to call it from the outside.
* This is needed for delegating calls.
*/
@Override
public void processKeyEvent(KeyEvent e) {
int i = e.getKeyCode();
if (i == KeyEvent.VK_BACK_SPACE && getDocument().getLength() == 0) {
e.consume();
return;
}
if (
i == KeyEvent.VK_ENTER ||
i == KeyEvent.VK_ESCAPE ||
i == KeyEvent.VK_PAGE_UP ||
i == KeyEvent.VK_PAGE_DOWN ||
i == KeyEvent.VK_LEFT ||
i == KeyEvent.VK_RIGHT
) {
manageSearchPopup(null);
if (i == KeyEvent.VK_ESCAPE) {
e.consume();
}
return;
}
if (isUpDownHomeEnd(i)) {
e.consume();
return;
}
super.processKeyEvent(e);
if (i == KeyEvent.VK_BACK_SPACE) {
e.consume();
}
}
}
private static boolean isUpDownHomeEnd(int keyCode) {
return keyCode == KeyEvent.VK_HOME || keyCode == KeyEvent.VK_END || keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_DOWN;
}
private static boolean isPgUpPgDown(int keyCode) {
return keyCode == KeyEvent.VK_PAGE_UP || keyCode == KeyEvent.VK_PAGE_DOWN;
}
private static boolean isNavigationKey(int keyCode) {
return isPgUpPgDown(keyCode) || isUpDownHomeEnd(keyCode);
}
private void manageSearchPopup(@Nullable SearchPopup searchPopup) {
Project project = null;
if (ApplicationManager.getApplication() != null && !ApplicationManager.getApplication().isDisposed()) {
project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(myComponent));
}
if (project != null && project.isDefault()) {
project = null;
}
if (mySearchPopup != null) {
logEvent(UIEventId.IncrementalSearchCancelled);
if (myPopupLayeredPane != null) {
myPopupLayeredPane.remove(mySearchPopup);
myPopupLayeredPane.validate();
myPopupLayeredPane.repaint();
myPopupLayeredPane = null;
}
if (myListenerDisposable != null) {
Disposer.dispose(myListenerDisposable);
myListenerDisposable = null;
}
}
else if (searchPopup != null) {
FeatureUsageTracker.getInstance().triggerFeatureUsed("ui.tree.speedsearch");
logEvent(UIEventId.IncrementalSearchActivated);
}
mySearchPopup = myComponent.isShowing() ? searchPopup : null;
fireStateChanged();
//select here!
if (mySearchPopup == null || !myComponent.isDisplayable()) return;
if (project != null) {
myListenerDisposable = Disposer.newDisposable();
project.getMessageBus().connect(myListenerDisposable).subscribe(ToolWindowManagerListener.TOPIC, myWindowManagerListener);
}
JRootPane rootPane = myComponent.getRootPane();
myPopupLayeredPane = rootPane == null ? null : rootPane.getLayeredPane();
if (myPopupLayeredPane == null) {
LOG.error(this + " in " + myComponent);
return;
}
myPopupLayeredPane.add(mySearchPopup, JLayeredPane.POPUP_LAYER);
moveSearchPopup();
mySearchPopup.refreshSelection();
}
private void moveSearchPopup() {
if (myComponent == null || mySearchPopup == null || myPopupLayeredPane == null) return;
Point lPaneP = myPopupLayeredPane.getLocationOnScreen();
Point componentP = getComponentLocationOnScreen();
Rectangle r = getComponentVisibleRect();
Dimension prefSize = mySearchPopup.getPreferredSize();
Window window = (Window)SwingUtilities.getAncestorOfClass(Window.class, myComponent);
Point windowP;
if (window instanceof JDialog) {
windowP = ((JDialog)window).getContentPane().getLocationOnScreen();
}
else if (window instanceof JFrame) {
windowP = ((JFrame)window).getContentPane().getLocationOnScreen();
}
else {
windowP = window.getLocationOnScreen();
}
int y = r.y + componentP.y - lPaneP.y - prefSize.height;
y = Math.max(y, windowP.y - lPaneP.y);
mySearchPopup.setLocation(componentP.x - lPaneP.x + r.x, y);
mySearchPopup.setSize(prefSize);
mySearchPopup.setVisible(true);
mySearchPopup.validate();
}
protected Rectangle getComponentVisibleRect() {
return myComponent.getVisibleRect();
}
protected Point getComponentLocationOnScreen() {
return myComponent.getLocationOnScreen();
}
protected final class ViewIterator implements ListIterator<Object> {
private final SpeedSearchBase mySpeedSearch;
private int myCurrentIndex;
private final Object[] myElements;
ViewIterator(@NotNull final SpeedSearchBase speedSearch, final int startIndex) {
mySpeedSearch = speedSearch;
myCurrentIndex = startIndex;
myElements = speedSearch.getAllElements();
if (startIndex < 0 || startIndex > myElements.length) {
throw new IndexOutOfBoundsException("Index: " + startIndex + " in: " + SpeedSearchBase.this.getClass());
}
}
@Override
public boolean hasPrevious() {
return myCurrentIndex != 0;
}
@Override
public Object previous() {
final int i = myCurrentIndex - 1;
if (i < 0) throw new NoSuchElementException();
final Object previous = myElements[mySpeedSearch.convertIndexToModel(i)];
myCurrentIndex = i;
return previous;
}
@Override
public int nextIndex() {
return myCurrentIndex;
}
@Override
public int previousIndex() {
return myCurrentIndex - 1;
}
@Override
public boolean hasNext() {
return myCurrentIndex != myElements.length;
}
@Override
public Object next() {
if (myCurrentIndex + 1 > myElements.length) throw new NoSuchElementException();
return myElements[mySpeedSearch.convertIndexToModel(myCurrentIndex++)];
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not implemented in: " + getClass().getCanonicalName());
}
@Override
public void set(Object o) {
throw new UnsupportedOperationException("Not implemented in: " + getClass().getCanonicalName());
}
@Override
public void add(Object o) {
throw new UnsupportedOperationException("Not implemented in: " + getClass().getCanonicalName());
}
}
}
|
package uk.gov.dvla.domain.portal;
import org.joda.time.DateTime;
import uk.gov.dvla.domain.DomainConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
public class PortalDTO {
private static final Logger logger = LoggerFactory.getLogger(PortalDTO.class.getName());
private Driver driver;
public Driver getDriver() {
return driver;
}
public void setDriver(Driver driver) {
this.driver = driver;
}
public static class Driver {
private String currentDriverNumber;
private BirthDetails birthDetails;
private Name name;
private Licence licence;
private Integer gender;
private Address address;
private DriverStatus status;
private List<DriverFlag> flags;
private List<TestPass> testPasses;
private List<Integer> restrictionKeys;
private Date disqualifiedUntilDate;
private DriverStatedFlags driverStatedFlags;
private List<Disqualification> disqualifications;
public String getCurrentDriverNumber() {
return currentDriverNumber;
}
public void setCurrentDriverNumber(String currentDriverNumber) {
this.currentDriverNumber = currentDriverNumber;
}
public BirthDetails getBirthDetails() {
return birthDetails;
}
public void setBirthDetails(BirthDetails birthDetails) {
this.birthDetails = birthDetails;
}
public Name getName() {
return name;
}
public void setName(Name name) {
this.name = name;
}
public Licence getLicence() {
return this.licence;
}
public void setLicence(Licence licence) {
this.licence = licence;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public DriverStatus getStatus() {
return status;
}
public void setStatus(DriverStatus status) {
this.status = status;
}
public void addDriverFlag(DriverFlag flag) {
if (null == flags) {
flags = new ArrayList<DriverFlag>();
}
flags.add(flag);
}
public List<DriverFlag> getFlags() {
return flags;
}
public void setFlags(List<DriverFlag> flags) {
this.flags = flags;
}
public void addTestPass(TestPass testPass) {
if (null == testPasses) {
testPasses = new ArrayList<TestPass>();
}
testPasses.add(testPass);
}
public List<TestPass> getTestPasses() {
return testPasses;
}
public void setTestPasses(List<TestPass> testPasses) {
this.testPasses = testPasses;
}
public TestPass getTestPassForEntitlement(uk.gov.dvla.domain.Entitlement ent) {
ArrayList<TestPass> possibleTestPasses = new ArrayList<TestPass>();
if (testPasses == null) {
return null;
}
for (TestPass testPass : testPasses) {
if (testPass.getEntitlementType().equals(ent.getCode())) {
possibleTestPasses.add(testPass);
}
}
if (possibleTestPasses.size() == 0) {
return null;
} else {
//Ensure the most recent is returned
Collections.reverse(possibleTestPasses);
return possibleTestPasses.get(0);
}
}
public void addRestrictionKey(Integer key) {
if (null == restrictionKeys) {
restrictionKeys = new ArrayList<Integer>();
}
restrictionKeys.add(key);
}
public List<Integer> getRestrictionKeys() {
return restrictionKeys;
}
public void setRestrictionKeys(List<Integer> restrictionKeys) {
this.restrictionKeys = restrictionKeys;
}
public Date getDisqualifiedUntilDate() {
return disqualifiedUntilDate;
}
public void setDisqualifiedUntilDate(Date disqualifiedUntilDate) {
this.disqualifiedUntilDate = disqualifiedUntilDate;
}
public DriverStatedFlags getDriverStatedFlags() {
return driverStatedFlags;
}
public void setDriverStatedFlags(DriverStatedFlags driverStatedFlags) {
this.driverStatedFlags = driverStatedFlags;
}
public List<Disqualification> getDisqualifications() {
return disqualifications;
}
public void setDisqualifications(List<Disqualification> disqualifications) {
this.disqualifications = disqualifications;
}
}
public static class Name {
private String title = null;
private List<String> givenName = null;
private String familyName = null;
public void addGivenName(String gn) {
if (null == givenName) {
givenName = new ArrayList<String>();
}
givenName.add(gn);
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getGivenName() {
return givenName;
}
public void setGivenName(List<String> givenName) {
this.givenName = givenName;
}
public String getFamilyName() {
return familyName;
}
public void setFamilyName(String familyName) {
this.familyName = familyName;
}
}
public static class Address {
private String buildingName;
private String ddtfare;
private String postTown;
private String postCode;
private String type;
private List<String> uLine;
private String uPostCode;
public String getBuildingName() {
return buildingName;
}
public void setBuildingName(String buildingName) {
this.buildingName = buildingName;
}
public String getDdtfare() {
return ddtfare;
}
public void setDdtfare(String ddtfare) {
this.ddtfare = ddtfare;
}
public String getPostTown() {
return postTown;
}
public void setPostTown(String postTown) {
this.postTown = postTown;
}
public String getPostCode() {
return postCode;
}
public void setPostCode(String postCode) {
this.postCode = postCode;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<String> getuLine() {
return uLine;
}
public void setuLine(List<String> uLine) {
this.uLine = uLine;
}
public String getuPostCode() {
return uPostCode;
}
public void setuPostCode(String uPostCode) {
this.uPostCode = uPostCode;
}
}
public static class BirthDetails {
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
public static class Licence {
private String currentIssueNum;
private Date validFrom;
private Date validTo;
private int directiveStatus;
private List<Entitlement> entitlements;
private List<Endorsement> endorsements;
private Date photoExpiryDate;
public Date getValidFrom() {
return validFrom;
}
public void setValidFrom(Date validFrom) {
this.validFrom = validFrom;
}
public Date getValidTo() {
return validTo;
}
public void setValidTo(Date validTo) {
this.validTo = validTo;
}
public Integer getDirectiveStatus() {
return directiveStatus;
}
public void setDirectiveStatus(Integer directiveStatus) {
this.directiveStatus = directiveStatus;
}
public List<Entitlement> getEntitlements() {
return entitlements;
}
public void setEntitlements(List<Entitlement> entitlements) {
this.entitlements = entitlements;
}
public List<Endorsement> getEndorsements() {
return endorsements;
}
public void setEndorsements(List<Endorsement> endorsements) {
this.endorsements = endorsements;
}
public Date getPhotoExpiryDate() {
return photoExpiryDate;
}
public void setPhotoExpiryDate(Date photoExpiryDate) {
this.photoExpiryDate = photoExpiryDate;
}
public String getCurrentIssueNum() {
return currentIssueNum;
}
public void setCurrentIssueNum(String currentIssueNum) {
this.currentIssueNum = currentIssueNum;
}
}
public static class Entitlement {
private String code;
private Date validFrom;
private Date validTo;
private Boolean provisional;
private Boolean priorTo;
private List<EntitlementRestriction> restrictions;
private Boolean vocational;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public Date getValidFrom() {
return validFrom;
}
public void setValidFrom(Date validFrom) {
this.validFrom = validFrom;
}
public Date getValidTo() {
return validTo;
}
public void setValidTo(Date validTo) {
this.validTo = validTo;
}
public Boolean getProvisional() {
return provisional;
}
public void setProvisional(Boolean provisional) {
this.provisional = provisional;
}
public Boolean getPriorTo() {
return priorTo;
}
public void setPriorTo(Boolean priorTo) {
this.priorTo = priorTo;
}
public List<EntitlementRestriction> getRestrictions() {
return restrictions;
}
public void setRestrictions(List<EntitlementRestriction> restrictions) {
this.restrictions = restrictions;
}
public Boolean getVocational() {
return vocational;
}
public void setVocational(Boolean vocational) {
this.vocational = vocational;
}
}
public static class Endorsement {
private Integer id;
private Boolean disqual;
private String code;
private String convictingCourt;
private Date offence;
private Date expires;
private Date removed;
private Date conviction;
private Date sentencing;
private String duration;
private Double fine;
private Integer noPoints;
private OtherSentence otherSentence;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Boolean getDisqual() {
return disqual;
}
public void setDisqual(Boolean disqual) {
this.disqual = disqual;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getConvictingCourt() {
return convictingCourt;
}
public void setConvictingCourt(String convictingCourt) {
this.convictingCourt = convictingCourt;
}
public Date getOffence() {
return offence;
}
public void setOffence(Date offence) {
this.offence = offence;
}
public Date getExpires() {
return expires;
}
public void setExpires(Date expires) {
this.expires = expires;
}
public Date getRemoved() {
return removed;
}
public void setRemoved(Date removed) {
this.removed = removed;
}
public Date getConviction() {
return conviction;
}
public void setConviction(Date conviction) {
this.conviction = conviction;
}
public Date getSentencing() {
return sentencing;
}
public void setSentencing(Date sentencing) {
this.sentencing = sentencing;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public Double getFine() {
return fine;
}
public void setFine(Double fine) {
this.fine = fine;
}
public Integer getNoPoints() {
return noPoints;
}
public void setNoPoints(Integer noPoints) {
this.noPoints = noPoints;
}
public OtherSentence getOtherSentence() {
return otherSentence;
}
public void setOtherSentence(uk.gov.dvla.domain.OtherSentence otherSentence) {
OtherSentence DTOotherSentence = new OtherSentence();
DTOotherSentence.code = otherSentence.getCode();
DTOotherSentence.duration = otherSentence.getDuration();
this.otherSentence = DTOotherSentence;
}
}
public static class OtherSentence {
private String code;
private String duration;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
}
public static class EntitlementRestriction {
private String code;
private String categoryCode;
private Date validTo;
public EntitlementRestriction() {
}
public EntitlementRestriction(String code, String categoryCode, Date validTo) {
if (code == null) {
logger.debug("code must be specified");
throw new RuntimeException("code must be specified");
}
this.code = code;
this.categoryCode = categoryCode;
this.validTo = validTo;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getCategoryCode() {
return categoryCode;
}
public void setCategoryCode(String categoryCode) {
this.categoryCode = categoryCode;
}
public Date getValidTo() {
return validTo;
}
public void setValidTo(Date validTo) {
this.validTo = validTo;
}
}
public static class TestPass {
private String entitlementType;
private String statusType;
private Date testPassDate;
public String getEntitlementType() {
return entitlementType;
}
public void setEntitlementType(String entitlementType) {
this.entitlementType = entitlementType;
}
public String getStatusType() {
return statusType;
}
public void setStatusType(String statusType) {
this.statusType = statusType;
}
public Date getTestPassDate() {
return testPassDate;
}
public void setTestPassDate(Date testPassDate) {
this.testPassDate = testPassDate;
}
}
public static class DriverStatedFlags {
private Boolean excessEndorsements;
public Boolean getExcessEndorsements() {
return excessEndorsements;
}
public void setExcessEndorsements(Boolean excessEndorsements) {
this.excessEndorsements = excessEndorsements;
}
}
public static class DriverStatus {
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
}
public static class Disqualification {
private Date disqFromDate;
private Date disqToDate;
private Integer endorsementID;
private String type;
public Date getDisqFromDate() {
return disqFromDate;
}
public void setDisqFromDate(Date disqFromDate) {
this.disqFromDate = disqFromDate;
}
public Date getDisqToDate() {
return disqToDate;
}
public void setDisqToDate(Date disqToDate) {
this.disqToDate = disqToDate;
}
public Integer getEndorsementID() {
return endorsementID;
}
public void setEndorsementID(Integer endorsementID) {
this.endorsementID = endorsementID;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
public static class DriverFlag {
private String flag;
private boolean manual;
private boolean caseType;
public String getFlag() {
return flag;
}
public void setFlag(String flag) {
this.flag = flag;
}
public boolean isManual() {
return manual;
}
public void setManual(boolean manual) {
this.manual = manual;
}
public boolean isCaseType() {
return caseType;
}
public void setCaseType(boolean caseType) {
this.caseType = caseType;
}
}
}
|
package io.spacedog.services.file;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.Collectors;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import io.spacedog.client.file.FileBucket;
import io.spacedog.client.file.FileStoreType;
import io.spacedog.client.file.SpaceFile;
import io.spacedog.client.file.SpaceFile.FileList;
import io.spacedog.client.http.SpaceFields;
import io.spacedog.client.schema.Schema;
import io.spacedog.server.Server;
import io.spacedog.server.ServerConfig;
import io.spacedog.services.Services;
import io.spacedog.services.SpaceService;
import io.spacedog.services.elastic.ElasticIndex;
import io.spacedog.services.file.FileStore.PutResult;
import io.spacedog.services.snapshot.FileBackup;
import io.spacedog.utils.Exceptions;
import io.spacedog.utils.Json;
import io.spacedog.utils.Utils;
import net.codestory.http.payload.StreamingOutput;
public class FileService extends SpaceService {
public static final String SERVICE_NAME = "files";
// fields
private int defaultListSize = 100;
private FileStore systemStore = new SystemFileStore(ServerConfig.filesStorePath());
private FileStore s3Store = new S3FileStore(ServerConfig.awsBucketPrefix() + SERVICE_NAME);
public FileService() {
}
public FileService setDefaultListSize(int listSize) {
this.defaultListSize = listSize;
return this;
}
public FileList listAll(String bucket) {
return list(bucket, "/");
}
public FileList list(String bucket, String path) {
return list(bucket, path, null, defaultListSize, false);
}
public FileList list(String bucket, String path, String next, int size, boolean refresh) {
SearchResponse response = null;
if (Strings.isNullOrEmpty(next)) {
elastic().refreshIndex(refresh, index(bucket));
SearchSourceBuilder source = SearchSourceBuilder.searchSource()
.query(QueryBuilders.prefixQuery(PATH_FIELD, path))
.size(size)
.sort(SortBuilders.fieldSort(PATH_FIELD));
SearchRequest request = elastic().prepareSearch(index(bucket))
.scroll(TimeValue.timeValueMinutes(1))
.source(source);
response = elastic().search(request);
} else {
response = elastic().scroll(next, TimeValue.timeValueMinutes(1));
}
SearchHits hits = response.getHits();
FileList fileList = new FileList();
fileList.next = hits.getHits().length == 0 ? null : response.getScrollId();
fileList.total = hits.getTotalHits().value;
fileList.files = Lists.newArrayListWithCapacity(hits.getHits().length);
for (SearchHit hit : hits.getHits())
fileList.files.add(toSpaceFile(hit));
return fileList;
}
private SpaceFile toSpaceFile(SearchHit hit) {
byte[] bytes = BytesReference.toBytes(hit.getSourceRef());
return Json.toPojo(bytes, SpaceFile.class);
}
// Get
public SpaceFile getMeta(String bucket, String path, boolean throwNotFound) {
GetResponse response = elastic().get(index(bucket), path);
if (response.isExists())
return Json.toPojo(response.getSourceAsBytes(), SpaceFile.class);
if (throwNotFound)
throw Exceptions.objectNotFound(bucket, path);
return null;
}
public byte[] getAsByteArray(String bucket, SpaceFile file) {
return Utils.toByteArray(getAsByteStream(bucket, file));
}
public InputStream getAsByteStream(String bucket, SpaceFile file) {
return getAsByteStream(bucket, file.getKey());
}
public byte[] getAsByteArray(String bucket, String key) {
return Utils.toByteArray(getAsByteStream(bucket, key));
}
public InputStream getAsByteStream(String bucket, String key) {
return store(bucket).get(Server.backend().id(), bucket, key);
}
// Export
public StreamingOutput exportFromPaths(String bucket, boolean flatZip, String... paths) {
return exportFromPaths(bucket, flatZip, Lists.newArrayList(paths));
}
public StreamingOutput exportFromPaths(String bucket, boolean flatZip, List<String> paths) {
List<SpaceFile> files = paths.stream()
.map(path -> getMeta(bucket, path, true))
.collect(Collectors.toList());
return export(bucket, flatZip, files);
}
public StreamingOutput export(String bucket, boolean flatZip, List<SpaceFile> files) {
return new FileBucketExport(bucket, flatZip, files);
}
// Put
public SpaceFile upload(String bucket, SpaceFile file, byte[] bytes) {
return upload(bucket, file, new ByteArrayInputStream(bytes));
}
public SpaceFile upload(String bucket, SpaceFile file, InputStream bytes) {
FileStore store = store(bucket);
PutResult result = store.put(Server.backend().id(),
bucket, file.getLength(), bytes);
file.setKey(result.key);
file.setHash(result.hash);
file.setSnapshot(false);
try {
return update(bucket, file);
} catch (Exception e) {
store.delete(Server.backend().id(), bucket, file.getKey());
throw e;
}
}
// Delete
public long deleteAll(String bucket) {
return deleteAll(bucket, "/");
}
public long deleteAll(String bucket, String path) {
BulkByScrollResponse response = elastic().deleteByQuery(
QueryBuilders.prefixQuery(PATH_FIELD, path),
index(bucket));
return response.getDeleted();
}
public boolean delete(String bucket, SpaceFile file) {
boolean deleted = elastic().delete(
index(bucket), file.getPath(), false, false);
try {
store(bucket).delete(Server.backend().id(), bucket, file.getKey());
} catch (Exception ignore) {
// It's not a big deal if file is not deleted:
// - since they are not accessible anymore,
// - since they can be updated/replaced.
// TODO a job should garbage collect them.
}
return deleted;
}
// Buckets
public InternalFileSettings listBuckets() {
return Services.settings().getOrThrow(InternalFileSettings.class);
}
public FileBucket getBucket(String name) {
FileBucket bucketSettings = listBuckets().get(name);
if (bucketSettings == null)
throw Exceptions.objectNotFound("file bucket", name);
return bucketSettings;
}
public void setBucket(FileBucket bucket) {
InternalFileSettings buckets = listBuckets();
FileBucket previousBucket = buckets.get(bucket.name);
if (previousBucket == null) {
createBucketIndex(bucket);
// make sure no files from past deleted backend
store(bucket).deleteAll(Server.backend().id(), bucket.name);
} else if (!bucket.type.equals(previousBucket.type))
throw Exceptions.illegalArgument("updating store type of file buckets is forbidden");
buckets.put(bucket.name, bucket);
Services.settings().save(buckets);
}
public void deleteBucket(String name) {
elastic().deleteIndices(index(name));
InternalFileSettings buckets = listBuckets();
FileBucket bucket = buckets.get(name);
store(bucket).deleteAll(Server.backend().id(), name);
buckets.remove(name);
Services.settings().save(buckets);
}
public void deleteAllBuckets() {
InternalFileSettings buckets = listBuckets();
for (FileBucket bucket : buckets.values())
// delete backend to make sure
// any unregistered bucket is deleted
store(bucket).deleteAll(Server.backend().id());
buckets.clear();
Services.settings().save(buckets);
}
private void createBucketIndex(FileBucket bucket) {
Schema.checkName(bucket.name);
Schema schema = getSchema(bucket.name);
ElasticIndex index = index(bucket.name);
if (elastic().exists(index))
elastic().putMapping(index, schema.mapping());
else
elastic().createIndex(index, schema, false);
}
public Schema getSchema(String bucket) {
return Schema.builder(bucket)
.keyword(PATH_FIELD)
.keyword(KEY_FIELD)
.keyword(NAME_FIELD)
.keyword(ENCRYPTION_FIELD)
.keyword(CONTENT_TYPE_FIELD)
.longg(LENGTH_FIELD)
.keyword(TAGS_FIELD)
.keyword(HASH_FIELD)
.keyword(SNAPSHOT_FIELD)
.keyword(OWNER_FIELD)
.keyword(GROUP_FIELD)
.timestamp(CREATED_AT_FIELD)
.timestamp(UPDATED_AT_FIELD)
.build();
}
public ElasticIndex index(String bucket) {
return new ElasticIndex(SERVICE_NAME).type(bucket);
}
// Snapshot and restore
private static final TimeValue ONE_MINUTE = TimeValue.timeValueSeconds(60);
public void snapshot(FileBackup backup) {
ElasticIndex[] indices = listBuckets().values().stream()
.map(bucket -> Services.files().index(bucket.name))
.toArray(ElasticIndex[]::new);
if (!Utils.isNullOrEmpty(indices)) {
elastic().refreshIndex(indices);
SearchSourceBuilder builder = SearchSourceBuilder.searchSource()
.query(QueryBuilders.termQuery(SpaceFields.SNAPSHOT_FIELD, false))
.size(1000);
SearchRequest request = elastic().prepareSearch(indices)
.source(builder)
.scroll(ONE_MINUTE);
SearchResponse response = elastic().search(request);
do {
for (SearchHit hit : response.getHits()) {
SpaceFile file = toSpaceFile(hit);
String bucket = ElasticIndex.valueOf(hit.getIndex()).type();
snapshot(backup, bucket, file);
}
response = elastic().scroll(response.getScrollId(), ONE_MINUTE);
} while (response.getHits().getHits().length != 0);
}
}
private void snapshot(FileBackup backup, String bucket, SpaceFile file) {
Utils.info("Snapshoting /%s/%s%s", backup.backendId(), bucket, file.getPath());
try (InputStream bytes = store(bucket).get(backup.backendId(), bucket, file.getKey())) {
backup.restore(bucket, file.getKey(), file.getLength(), bytes);
// TODO read copy and check hash is correct
file.setSnapshot(true);
update(bucket, file);
} catch (IOException e) {
throw Exceptions.runtime(e, "snapshot file [%s][%s] failed", bucket, file.getPath());
}
}
public void restore(FileBackup backup) {
ElasticIndex[] indices = listBuckets().values().stream()
.map(bucket -> Services.files().index(bucket.name))
.toArray(ElasticIndex[]::new);
if (!Utils.isNullOrEmpty(indices)) {
elastic().refreshIndex(indices);
SearchSourceBuilder builder = SearchSourceBuilder.searchSource()
.query(QueryBuilders.matchAllQuery())
.size(1000);
SearchRequest request = elastic().prepareSearch(indices)
.source(builder)
.scroll(ONE_MINUTE);
SearchResponse response = elastic().search(request);
do {
for (SearchHit hit : response.getHits()) {
SpaceFile file = toSpaceFile(hit);
restore(backup, hit.getType(), file);
}
response = elastic().scroll(response.getScrollId(), ONE_MINUTE);
} while (response.getHits().getHits().length != 0);
}
}
private void restore(FileBackup backup, String bucket, SpaceFile file) {
Utils.info("Restoring /%s/%s%s", backup.backendId(), bucket, file.getPath());
FileStore store = store(bucket);
if (!store.check(backup.backendId(), bucket, file.getKey(), file.getHash())) {
try (InputStream bytes = backup.get(bucket, file.getKey())) {
store.restore(backup.backendId(), bucket, file.getKey(), file.getLength(), bytes);
} catch (IOException e) {
throw Exceptions.runtime(e, "restore file [%s][%s] failed", bucket, file.getPath());
}
}
}
// Implementation
private SpaceFile update(String bucket, SpaceFile file) {
elastic().index(index(bucket), file.getPath(), file);
return file;
}
private FileStore store(String bucket) {
return store(getBucket(bucket));
}
private FileStore store(FileBucket bucket) {
if (bucket.type.equals(FileStoreType.fs))
return systemStore;
if (bucket.type.equals(FileStoreType.s3))
return s3Store;
throw Exceptions.runtime("file bucket type [%s] is invalid", bucket.type);
}
}
|
package org.drools.agent;
import org.drools.ChangeSet;
import org.drools.KnowledgeBase;
import org.drools.SystemEventListener;
import org.drools.event.knowledgeagent.KnowledgeAgentEventListener;
import org.drools.io.Resource;
import org.drools.runtime.KnowledgeSessionConfiguration;
import org.drools.runtime.StatelessKnowledgeSession;
/**
* The KnolwedgeAgentFactory provides detailed information on how to create and use the KnowledgeAgent.
*
* @see org.drools.agent.KnowledgeAgentFactory
* @see org.drools.agent.KnowledgeAgentConfiguration
*
*/
public interface KnowledgeAgent {
void addEventListener(KnowledgeAgentEventListener listener);
public enum ResourceStatus{
RESOURCE_ADDED,
RESOURCE_MODIFIED,
RESOURCE_REMOVED;
}
/**
*
* @return
* The name
*/
String getName();
/**
* Returns the cached KnowledgeBase
* @return
* The KnowledgeBase
*/
KnowledgeBase getKnowledgeBase();
/**
* StatelessKnowledgeSession created from here will always have the execute() method called against the latest built KnowledgeBase
* @return
*/
StatelessKnowledgeSession newStatelessKnowledgeSession();
/**
* StatelessKnowledgeSession created from here will always have the execute() method called against the latest built KnowledgeBase
* @return
*/
StatelessKnowledgeSession newStatelessKnowledgeSession(KnowledgeSessionConfiguration conf);
void monitorResourceChangeEvents(boolean monitor);
void applyChangeSet(Resource resource);
void applyChangeSet(ChangeSet changeSet);
void setSystemEventListener(SystemEventListener listener);
void dispose();
}
|
package band.wukong.mz.g.customer.service;
import band.wukong.mz.base.exception.IllegalParameterException;
import band.wukong.mz.g.customer.bean.Customer;
import band.wukong.mz.nutz.NutzDaoHelper;
import org.nutz.dao.Cnd;
import org.nutz.dao.Condition;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import java.util.List;
/**
* As you see...
*
* @author wukong(wukonggg@139.com)
*/
@IocBean(name = "custService")
public class CustomerService {
private static final Log log = Logs.get();
@Inject
private Dao dao;
/**
* save. savestateCustomer.STATE_OK
*
* @param c c
* @return savecustomer
*/
public Customer save(Customer c) {
if (!CustomerServiceValidator.save(c)) {
throw new IllegalParameterException();
}
c.setState(Customer.STATE_OK);
return dao.insert(c);
}
public Customer find(long id) {
if (id <= 0) {
throw new IllegalParameterException();
}
return dao.fetch(Customer.class, id);
}
public Customer find(String cid) {
if (Strings.isBlank(cid)) {
throw new IllegalParameterException();
}
return dao.fetch(Customer.class, cid);
}
/**
* find.
*
* @param id id
* @param state
* @return
*/
public Customer findByState(long id, String state) {
if (id <= 0 || Strings.isBlank(state)) {
throw new IllegalParameterException();
}
return dao.fetch(Customer.class, Cnd.where("id", "=", id).and("state", "=", state));
}
/**
* find.
*
* @param cid
* @param state
* @return
*/
public Customer findByState(String cid, String state) {
if (Strings.isBlank(cid) || Strings.isBlank(state)) {
throw new IllegalParameterException();
}
return dao.fetch(Customer.class, Cnd.where("cid", "=", cid).and("state", "=", state));
}
/**
* udpate
*
* @param c
*/
public void update(Customer c) {
if (!CustomerServiceValidator.update(c)) {
throw new IllegalParameterException();
}
Customer cust = dao.fetch(Customer.class, c.getId());
c.setPaymentClothing(cust.getPaymentClothing());
c.setState(Customer.STATE_OK);//stateok
dao.update(c);
}
/**
* rm.warn,
*
* @param id id
*/
public void rm(long id) {
if (id <= 0) {
throw new IllegalParameterException();
}
Customer cust = find(id);
if (null == cust) {
log.warn("Could not rm customer whose id = " + id + ", cause could not find him.");
return;
}
cust.setState(Customer.STATE_RM);
dao.update(cust);
}
/**
* rm.warn,
*
* @param cid cid
*/
public void rm(String cid) {
if (Strings.isBlank(cid)) {
throw new IllegalParameterException();
}
Customer cust = find(cid);
if (null == cust) {
log.warn("Could not rm customer whose cid = " + cid + ", cause could not find him.");
return;
}
cust.setState(Customer.STATE_RM);
dao.update(cust);
}
/**
* list by page
*
* @param qcond
* @param pageNum
* @param pageSize
* @return
*/
public QueryResult list(String qcond, int pageNum, int pageSize) {
Condition condition = null;
SqlExpressionGroup e1 = Cnd.exps("state", "=", Customer.STATE_OK);
if (Strings.isNotBlank(qcond)) {
SqlExpressionGroup e2 = Cnd.exps("cid", "=", qcond).or("name", "=", qcond).or("msisdn", "=", qcond);
condition = Cnd.where(e1).and(e2).orderBy("cid", "asc");
} else {
condition = Cnd.where(e1).orderBy("cid", "asc");
}
int recordCount = dao.count(Customer.class, condition);
Pager pager = NutzDaoHelper.createPager(pageNum, pageSize, recordCount);
List<Customer> clist = dao.query(Customer.class, condition, pager);
return new QueryResult(clist, pager);
}
/**
*
*
* @param keyword keyword
* @return
*/
public String autoComplete(String keyword) {
if (Strings.isBlank(keyword)) {
return "";
}
Condition c = Cnd
.where("name", "like", keyword + "%")
.or("msisdn", "like", keyword + "%")
.or("cid", "like", keyword + "%");
List<Customer> custList = dao.query(Customer.class, c);
StringBuilder custs = new StringBuilder();
for (Customer cust : custList) {
custs.append(", \"" + cust.getCid() + "/" + cust.getName() + "/" + cust.getMsisdn() + "\"");
}
return "[\n" + custs.toString().substring(2) + "\n]";
}
/**
* udpate payment orderpayreturn
*
* @param c
*/
public void updatePayment(Customer c) {
if (!CustomerServiceValidator.updatePayment(c)) {
throw new IllegalParameterException();
}
dao.update(c);
}
}
|
package ca.intelliware.ihtsdo.mlds.domain;
import java.util.Collections;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.apache.commons.lang.Validate;
import org.hibernate.annotations.SQLDelete;
import org.hibernate.annotations.Where;
import org.joda.time.Instant;
import org.joda.time.LocalDate;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Sets;
@Entity
@Table(name="commercial_usage")
@Where(clause = "inactive_at IS NULL")
@SQLDelete(sql="UPDATE commercial_usage SET inactive_at = now() WHERE commercial_usage_id = ?")
public class CommercialUsage extends BaseEntity {
@Id
@GeneratedValue
@Column(name="commercial_usage_id")
Long commercialUsageId;
// the parent
//FIXME review dependency graph!
@JsonIgnoreProperties(value={"application", "applications", "commercialUsages"}, allowSetters=true)
@ManyToOne
@JoinColumn(name="affiliate_id")
Affiliate affiliate;
@Enumerated(EnumType.STRING)
AffiliateType type;
//@Type(type="jodatimeInstant")
Instant created = Instant.now();
@JsonIgnore
@Column(name="inactive_at")
Instant inactiveAt;
@Column(name="start_date")
LocalDate startDate;
@Column(name="end_date")
LocalDate endDate;
@Enumerated(EnumType.STRING)
@Column(name = "state")
private UsageReportState state;
private String note;
@Column(name="effective_to")
private Instant effectiveTo;
@Embedded
UsageContext context;
//@Type(type="jodatimeInstant")
private Instant submitted = null;
@JsonProperty("entries")
@OneToMany(cascade=CascadeType.PERSIST, mappedBy="commercialUsage")
@Where(clause = "inactive_at IS NULL")
Set<CommercialUsageEntry> usage = Sets.newHashSet();
@JsonProperty("countries")
@OneToMany(cascade=CascadeType.PERSIST, mappedBy="commercialUsage")
@Where(clause = "inactive_at IS NULL")
Set<CommercialUsageCountry> countries = Sets.newHashSet();
public CommercialUsage() {
}
// For Testing
public CommercialUsage(Long commercialUsageId, Affiliate affiliate) {
this.commercialUsageId = commercialUsageId;
this.affiliate = affiliate;
}
public Long getCommercialUsageId() {
return commercialUsageId;
}
public LocalDate getStartDate() {
return startDate;
}
public void setStartDate(LocalDate startDate) {
this.startDate = startDate;
}
public LocalDate getEndDate() {
return endDate;
}
public void setEndDate(LocalDate endDate) {
this.endDate = endDate;
}
public Instant getCreated() {
return created;
}
public void addEntry(CommercialUsageEntry newEntryValue) {
Validate.notNull(newEntryValue.commercialUsageEntryId);
if (newEntryValue.commercialUsage != null) {
newEntryValue.commercialUsage.usage.remove(newEntryValue);
}
newEntryValue.commercialUsage = this;
usage.add(newEntryValue);
}
@JsonIgnore
public Set<CommercialUsageEntry> getEntries() {
return Collections.unmodifiableSet(usage);
}
public void addCount(CommercialUsageCountry newCountryValue) {
Validate.notNull(newCountryValue.commercialUsageCountId);
if (newCountryValue.commercialUsage != null) {
//Not sure why we're asking the incoming object for a reference to 'this'
//Think I'll blow up if the two aren't one and the same object
if (newCountryValue.commercialUsage.commercialUsageId != this.commercialUsageId) {
throw new IllegalArgumentException("Object owner incompatibility between commercial usage object "
+ newCountryValue.commercialUsage.commercialUsageId + " and " + this.commercialUsageId);
}
//newCountryValue.commercialUsage.countries.remove(newCountryValue);
countries.remove(newCountryValue);
}
newCountryValue.commercialUsage = this;
countries.add(newCountryValue);
}
@JsonIgnore
public Set<CommercialUsageCountry> getCountries() {
return Collections.unmodifiableSet(countries);
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Instant getSubmitted() {
return submitted;
}
public void setSubmitted(Instant submitted) {
this.submitted = submitted;
}
public UsageReportState getState() {
return state;
}
public void setState(UsageReportState state) {
this.state = state;
}
public void setCommercialUsageId(Long commercialUsageId) {
this.commercialUsageId = commercialUsageId;
}
public Affiliate getAffiliate() {
return affiliate;
}
public UsageContext getContext() {
return context;
}
public void setContext(UsageContext context) {
this.context = context;
}
public AffiliateType getType() {
return type;
}
public void setType(AffiliateType type) {
this.type = type;
}
@Override
protected Object getPK() {
return commercialUsageId;
}
public Instant getEffectiveTo() {
return effectiveTo;
}
public void setEffectiveTo(Instant effectiveTo) {
this.effectiveTo = effectiveTo;
}
@JsonIgnore
public boolean isActive() {
return getEffectiveTo() == null;
}
public boolean exists(CommercialUsageCountry newCountValue) {
// Does this usage report have a country count for this country?
String newCode = newCountValue.getCountry().getIsoCode2();
for (CommercialUsageCountry countryCount : countries) {
if (countryCount.getCountry().getIsoCode2().equalsIgnoreCase(newCode)) {
return true;
}
}
return false;
}
}
|
package com.alvazan.orm.layer0.base;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alvazan.orm.api.base.MetaLayer;
import com.alvazan.orm.api.base.NoSqlEntityManager;
import com.alvazan.orm.api.base.Query;
import com.alvazan.orm.api.z3api.NoSqlTypedSession;
import com.alvazan.orm.api.z5api.IndexColumnInfo;
import com.alvazan.orm.api.z5api.NoSqlSession;
import com.alvazan.orm.api.z5api.SpiMetaQuery;
import com.alvazan.orm.api.z5api.SpiQueryAdapter;
import com.alvazan.orm.api.z8spi.KeyValue;
import com.alvazan.orm.api.z8spi.MetaLoader;
import com.alvazan.orm.api.z8spi.MetaLookup;
import com.alvazan.orm.api.z8spi.Row;
import com.alvazan.orm.api.z8spi.action.Column;
import com.alvazan.orm.api.z8spi.conv.StorageTypeEnum;
import com.alvazan.orm.api.z8spi.iter.AbstractCursor;
import com.alvazan.orm.api.z8spi.iter.Cursor;
import com.alvazan.orm.api.z8spi.iter.DirectCursor;
import com.alvazan.orm.api.z8spi.iter.IndiceToVirtual;
import com.alvazan.orm.api.z8spi.iter.IterToVirtual;
import com.alvazan.orm.api.z8spi.iter.IterableWrappingCursor;
import com.alvazan.orm.api.z8spi.meta.DboColumnIdMeta;
import com.alvazan.orm.api.z8spi.meta.DboColumnMeta;
import com.alvazan.orm.api.z8spi.meta.DboDatabaseMeta;
import com.alvazan.orm.api.z8spi.meta.DboTableMeta;
import com.alvazan.orm.api.z8spi.meta.IndexData;
import com.alvazan.orm.api.z8spi.meta.RowToPersist;
import com.alvazan.orm.api.z8spi.meta.ViewInfo;
import com.alvazan.orm.impl.meta.data.MetaClass;
import com.alvazan.orm.impl.meta.data.MetaIdField;
import com.alvazan.orm.impl.meta.data.MetaInfo;
import com.alvazan.orm.impl.meta.data.NoSqlProxy;
import com.alvazan.orm.layer3.typed.IndiceCursorProxy;
import com.alvazan.orm.layer3.typed.NoSqlTypedSessionImpl;
public class BaseEntityManagerImpl implements NoSqlEntityManager, MetaLookup, MetaLoader {
private static final Logger log = LoggerFactory.getLogger(BaseEntityManagerImpl.class);
@Inject @Named("readcachelayer")
private NoSqlSession session;
@Inject
private MetaInfo metaInfo;
@SuppressWarnings("rawtypes")
@Inject
private Provider<QueryAdapter> adapterFactory;
@Inject
private NoSqlTypedSessionImpl typedSession;
@Inject
private DboDatabaseMeta databaseInfo;
@Inject
private MetaLayerImpl metaImpl;
private boolean isTypedSessionInitialized = false;
@SuppressWarnings("rawtypes")
public void put(Object entity, boolean isInsert) {
boolean needRead = false;
if(!isInsert && !(entity instanceof NoSqlProxy)) {
if(log.isDebugEnabled())
log.debug("need read as isInsert="+isInsert);
needRead = true;
}
Class cl = entity.getClass();
MetaClass metaClass = metaInfo.getMetaClass(cl);
if(metaClass == null)
throw new IllegalArgumentException("Entity type="+entity.getClass().getName()+" was not scanned and added to meta information on startup. It is either missing @NoSqlEntity annotation or it was not in list of scanned packages");
putImpl(entity, needRead, metaClass);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void put(Object entity) {
Class cl = entity.getClass();
MetaClass metaClass = metaInfo.getMetaClass(cl);
if(metaClass == null)
throw new IllegalArgumentException("Entity type="+entity.getClass().getName()+" was not scanned and added to meta information on startup. It is either missing @NoSqlEntity annotation or it was not in list of scanned packages");
boolean needRead = false;
MetaIdField idField = metaClass.getIdField();
Object id = metaClass.fetchId(entity);
if(idField.isAutoGen() && id != null && !(entity instanceof NoSqlProxy)) {
//We do NOT have the data from the database IF this is NOT a NoSqlProxy and we need it since this is an
//update
needRead = true;
}
putImpl(entity, needRead, metaClass);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void putImpl(Object originalEntity, boolean needRead, MetaClass metaClass) {
Object entity = originalEntity;
if(needRead) {
Object id = metaClass.fetchId(originalEntity);
Object temp = find(metaClass.getMetaClass(), id);
if(log.isDebugEnabled())
log.debug("entity with id="+id+" is="+temp);
if(temp != null) {
entity = temp;
BeanProps.copyProps(originalEntity, entity);
}
}
RowToPersist row = metaClass.translateToRow(entity);
DboTableMeta metaDbo = metaClass.getMetaDbo();
if (metaDbo.isEmbeddable())
throw new IllegalArgumentException("Entity type="+entity.getClass().getName()+" can not be saved as it is Embedded Entity. And Embeddable entitites are only saved along with their parent entity");
//This is if we need to be removing columns from the row that represents the entity in a oneToMany or ManyToMany
//as the entity.accounts may have removed one of the accounts!!!
if(row.hasRemoves())
session.remove(metaDbo, row.getKey(), row.getColumnNamesToRemove());
//NOW for index removals if any indexed values change of the entity, we remove from the index
for(IndexData ind : row.getIndexToRemove()) {
session.removeFromIndex(metaDbo, ind.getColumnFamilyName(), ind.getRowKeyBytes(), ind.getIndexColumn());
}
//NOW for index adds, if it is a new entity or if values change, we persist those values
for(IndexData ind : row.getIndexToAdd()) {
session.persistIndex(metaDbo, ind.getColumnFamilyName(), ind.getRowKeyBytes(), ind.getIndexColumn());
}
byte[] virtKey = row.getVirtualKey();
List<Column> cols = row.getColumns();
int ttl = row.getTtl();
if (ttl > 0) {
for(Column c:row.getColumns()) {
c.setTtl(ttl);
}
}
session.put(metaDbo, virtKey, cols);
}
@Override
public <T> T find(Class<T> entityType, Object key) {
if(key == null)
throw new IllegalArgumentException("key must be supplied but was null");
List<Object> keys = new ArrayList<Object>();
keys.add(key);
Cursor<KeyValue<T>> entities = findAll(entityType, keys);
if (entities.next())
return entities.getCurrent().getValue();
else
return null;
}
@SuppressWarnings("unchecked")
@Override
public <T> Cursor<KeyValue<T>> findAll(Class<T> entityType, Iterable<? extends Object> keys) {
if(keys == null)
throw new IllegalArgumentException("keys list cannot be null");
MetaClass<T> meta = metaInfo.getMetaClass(entityType);
if(meta == null)
throw new IllegalArgumentException("Class type="+entityType.getName()+" was not found, please check that you scanned the right package and look at the logs to see if this class was scanned");
Iterable<byte[]> iter = new IterableKey<T>(meta, keys);
Iterable<byte[]> virtKeys = new IterToVirtual(meta.getMetaDbo(), iter);
//we pass in null for batch size such that we do infinite size or basically all keys passed into this method in one
//shot
return findAllImpl2(meta, new IterableWrappingCursor<byte[]>(virtKeys), null, true, null);
}
<T> AbstractCursor<KeyValue<T>> findAllImpl2(MetaClass<T> meta, ViewInfo mainView, DirectCursor<IndexColumnInfo> keys, String query, boolean cacheResults, Integer batchSize) {
//OKAY, so this gets interesting. The noSqlKeys could be a proxy iterable to
//millions of keys with some batch size. We canNOT do a find inline here but must do the find in
//batches as well
IndiceCursorProxy indiceCursor = new IndiceCursorProxy(mainView, keys);
DirectCursor<byte[]> virtKeys = new IndiceToVirtual(meta.getMetaDbo(), indiceCursor);
return findAllImpl2(meta, virtKeys, query, cacheResults, batchSize);
}
<T> AbstractCursor<KeyValue<T>> findAllImpl2(MetaClass<T> meta, DirectCursor<byte[]> keys, String query, boolean cacheResults, Integer batchSize) {
boolean skipCache = query != null;
AbstractCursor<KeyValue<Row>> cursor = session.find(meta.getMetaDbo(), keys, skipCache, cacheResults, batchSize);
return new CursorRow<T>(session, meta, cursor, query);
}
@SuppressWarnings("unchecked")
public <T> List<KeyValue<T>> findAllList(Class<T> entityType, List<? extends Object> keys) {
if(keys == null)
throw new IllegalArgumentException("keys list cannot be null");
MetaClass<T> meta = metaInfo.getMetaClass(entityType);
if(meta == null)
throw new IllegalArgumentException("Class type="+entityType.getName()+" was not found, please check that you scanned the right package and look at the logs to see if this class was scanned");
List<KeyValue<T>> all = new ArrayList<KeyValue<T>>();
Cursor<KeyValue<T>> results = findAll(entityType, keys);
while(results.next()) {
KeyValue<T> r = results.getCurrent();
all.add(r);
}
return all;
}
@Override
public void flush() {
session.flush();
}
@SuppressWarnings("unchecked")
@Override
public <T> Query<T> createNamedQuery(Class<T> forEntity, String namedQuery) {
MetaClass<T> metaClass = metaInfo.getMetaClass(forEntity);
if(metaClass == null)
throw new IllegalArgumentException("Class not scanned="+metaClass+" so you may need to add @NoSqlEntity");
SpiMetaQuery metaQuery = metaClass.getNamedQuery(forEntity, namedQuery);
SpiQueryAdapter spiAdapter = metaQuery.createQueryInstanceFromQuery(session);
//We cannot return MetaQuery since it is used by all QueryAdapters and each QueryAdapter
//runs in a different thread potentially while MetaQuery is one used by all threads
QueryAdapter<T> adapter = adapterFactory.get();
adapter.setup(metaClass, metaQuery, spiAdapter, this, forEntity);
return adapter;
}
@SuppressWarnings("unchecked")
@Override
public <T> T getReference(Class<T> entityType, Object key) {
MetaClass<T> metaClass = metaInfo.getMetaClass(entityType);
MetaIdField<T> field = metaClass.getIdField();
return field.convertIdToProxy(session, key, null);
}
@Override
public NoSqlSession getSession() {
return session;
}
@Override
public MetaLayer getMeta() {
return metaImpl;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void fillInWithKey(Object entity) {
MetaClass metaClass = metaInfo.getMetaClass(entity.getClass());
MetaIdField idField = metaClass.getIdField();
if (idField != null)
idField.fillInAndFetchId(entity);
}
@Override
public void clearDatabase(boolean recreateMeta) {
session.clearDb();
saveMetaData();
}
void saveMetaData() {
BaseEntityManagerImpl tempMgr = this;
//DboDatabaseMeta existing = tempMgr.find(DboDatabaseMeta.class, DboDatabaseMeta.META_DB_ROWKEY);
// if(existing != null)
for(DboTableMeta table : databaseInfo.getAllTables()) {
for(DboColumnMeta col : table.getAllColumns()) {
tempMgr.put(col);
}
if (!table.isEmbeddable() && table.getIdColumnMeta() != null)
tempMgr.put(table.getIdColumnMeta());
tempMgr.put(table);
}
databaseInfo.setId(DboDatabaseMeta.META_DB_ROWKEY);
//NOW, on top of the ORM entites, we have 3 special index column families of String, BigInteger and BigDecimal
//which are one of the types in the composite column name.(the row keys are all strings). The column names
//are <value being indexed of String or BigInteger or BigDecimal><primarykey><length of first value> so we can
//sort it BUT we can determine the length of first value so we can get to primary key.
for(StorageTypeEnum type : StorageTypeEnum.values()) {
//Do we want a byte[] index that could be used with == but not < and not >, etc. etc.
//Do we want a separate Boolean index???? I don't think so
if(type != StorageTypeEnum.DECIMAL
&& type != StorageTypeEnum.INTEGER
&& type != StorageTypeEnum.STRING)
continue;
DboTableMeta cf = new DboTableMeta();
//TODO: PUT this in virtual partition????
cf.setup(null, type.getIndexTableName(), false, false);
cf.setColNamePrefixType(type);
DboColumnIdMeta idMeta = new DboColumnIdMeta();
idMeta.setup(cf, "id", String.class, false);
tempMgr.put(idMeta);
tempMgr.put(cf);
databaseInfo.addMetaClassDbo(cf);
}
tempMgr.put(databaseInfo);
tempMgr.flush();
}
public void setup() {
session.setOrmSessionForMeta(this);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void remove(Object entity) {
if (entity == null)
return;
MetaClass metaClass = metaInfo.getMetaClass(entity.getClass());
if(metaClass == null)
throw new IllegalArgumentException("Entity type="+entity.getClass().getName()+" was not scanned and added to meta information on startup. It is either missing @NoSqlEntity annotation or it was not in list of scanned packages");
Object proxy = entity;
Object pk = metaClass.fetchId(entity);
MetaIdField idField = metaClass.getIdField();
byte[] rowKey = idField.convertIdToNonVirtKey(pk);
byte[] virtKey = idField.formVirtRowKey(rowKey);
DboTableMeta metaDbo = metaClass.getMetaDbo();
if(!metaClass.hasIndexedField(entity)) {
session.remove(metaDbo, virtKey);
return;
} else if(!(entity instanceof NoSqlProxy)) {
//then we don't have the database information for indexes so we need to read from the database
proxy = find(metaClass.getMetaClass(), pk);
}
List<IndexData> indexToRemove = metaClass.findIndexRemoves((NoSqlProxy)proxy, rowKey);
//REMOVE EVERYTHING HERE, we are probably removing extra and could optimize this later
for(IndexData ind : indexToRemove) {
session.removeFromIndex(metaDbo, ind.getColumnFamilyName(), ind.getRowKeyBytes(), ind.getIndexColumn());
}
session.remove(metaDbo, virtKey);
}
@Override
public NoSqlTypedSession getTypedSession() {
if(!isTypedSessionInitialized) {
typedSession.setInformation(session, this);
}
return typedSession;
}
@Override
public void clear() {
session.clear();
}
@Override
public <T> Cursor<T> allRows(Class<T> baseEntity, String cf, int batchSize) {
MetaClass<T> meta;
if(cf == null) {
meta = metaInfo.getMetaClass(baseEntity);
if(meta == null)
throw new IllegalArgumentException("Class type="+baseEntity.getName()+" was not found, please check that you scanned the right package and look at the logs to see if this class was scanned");
} else {
meta = metaInfo.lookupCf(cf);
if(meta == null)
throw new IllegalArgumentException("A real CF="+cf+" was not found in the meta data");
else if(!baseEntity.isAssignableFrom(meta.getMetaClass()))
throw new IllegalArgumentException("baseEntity="+baseEntity+" was not a superclass of type="+meta.getMetaClass());
}
AbstractCursor<Row> allRows = session.allRows(meta.getMetaDbo(), batchSize);
boolean isVirtual = baseEntity.equals(Object.class);
if(meta != null) {
isVirtual = meta.getMetaDbo().isVirtualCf();
}
return new CursorRowPlain<T>(session, meta, allRows, metaInfo, isVirtual);
}
}
|
package com.conveyal.gtfs.error;
import java.io.Serializable;
/** Indicates that an entity referenced another entity that does not exist. */
public class ReferentialIntegrityError extends GTFSError implements Serializable {
public static final long serialVersionUID = 1L;
// TODO: maybe also store the entity ID of the entity which contained the bad reference, in addition to the row number
public final String badReference;
public ReferentialIntegrityError(String tableName, long row, String field, String badReference) {
super(tableName, row, field);
this.badReference = badReference;
}
/** must be comparable to put into mapdb */
@Override
public int compareTo (GTFSError o) {
int compare = super.compareTo(o);
if (compare != 0) return compare;
return this.badReference.compareTo((((ReferentialIntegrityError) o).badReference));
}
@Override public String getMessage() {
return String.format(badReference);
}
}
|
package ML.Train;
import ML.Classify.Observation;
import ML.featureDetection.Event;
import ML.featureDetection.FindBeats;
import java.util.ArrayList;
import java.util.Iterator;
/**
*
* @author jplr
*/
public class Segmentation {
public ArrayList segmentedBeats = new ArrayList();
private final FindBeats cb;
public Segmentation(FindBeats cibi) {
cb = cibi;
}
/**
* we have ProbableBeats which contains the probable S1 events and moreBeats
* which contains the probable S1, S2, S3, S4 We will use ProbableBeats to
* find the probable locations of other Sx events in moreBeats So we use
* moreBeats to detect events at proximity of the found time for S1 events.
* Once a S1 S1 is detected, the nextPB S1 before the after this S1 and
* before the nextPB is supposed to be S2, and so on for S3 and S4.
*
* @param norm
* @param rate
* @return
*/
public void segmentation(FindBeats norm, int rate) {
/* int S1 = 0;
int S2 = 0;
int S3 = 0;
int S4 = 0;
Integer S1MB, S1PB; */
Iterator itrMB = norm.getMoreBeats().iterator();
do {
if (!itrMB.hasNext()) {
break;
}
ArrayList beats = norm.getProbableBeats();
if (beats.isEmpty()) {
System.out.println("segmentation: Beat is zero");
return;
}
// This possible S1 event is situated between two S1 events in the
// ProbableBeats List,
// We try to find which S1 is the closest.
segmentTheBeat(itrMB, norm);
} while (true);
return;
}
/**
* This possible S1 event is situated between two S1 events in the
* ProbableBeats List, We try to find which S1 is the closest.
*
* @param S1mb
* @param norm
*/
private void segmentTheBeat(Iterator S1mb, FindBeats norm) {
ArrayList mb = norm.getMoreBeats();
ArrayList pb = norm.getProbableBeats();
Event prevPB = null, nextPB = null;
int cnt = 1;
Event S1MB = null;
Observation eventHMM = null;
int averageDistance = -1;
ArrayList beats = norm.getProbableBeats();
/* Take in account the "noisyness" of the file */
int beatsSize = beats.size() - norm.getNoisyFile();
System.out.println("Segmentation, corrected beat rate: " + beatsSize) ;
if (beatsSize > 0) {
averageDistance = norm.getNormalizedData().length / beatsSize;
} else {
return;
}
Iterator iterPB = pb.iterator();
// Get the first element of ProbableBeats, that arrives sooner than S1MB
if (iterPB.hasNext()) {
prevPB = (Event) iterPB.next();
}
boolean flag = true;
while (iterPB.hasNext()) {
if (flag == true) {
nextPB = (Event) iterPB.next();
} else {
// flag was found to be false, now make it true
flag = true;
}
// Analyse one beat to discern how many events there are inside
// one event at a time
while (S1mb.hasNext()) {
S1MB = (Event) S1mb.next();
if (S1MB.timeStampValue().intValue() > nextPB.timeStampValue().intValue()) {
prevPB = nextPB;
flag = true;
cnt = 1;
// Nothing found in this PB event, go to the next
break;
}
// S1 appears in the first quarter of the heartbeat
// S2 in the second quarter, etc..
// Event suffix progresses
float un = averageDistance / (nextPB.timeStampValue().intValue() - prevPB.timeStampValue().intValue());
// cnt = 1;
do {
eventHMM = analalyse(prevPB.timeStampValue(), nextPB.timeStampValue(), S1MB.timeStampValue(), norm, cnt);
if (eventHMM != null) {
addEvents(eventHMM);
cnt++;
} else {
// Nothing found in this PB event, go to the next
;
}
un = un - 1;
} while (un > 1.5);
/*
// S1MB = 1260, prevPB = 1280, nextPB = 3342
*/
}
}
return;
}
public void addEvents(Observation eventHMM) {
segmentedBeats.add(eventHMM);
}
ArrayList getSegmentedBeats() {
return segmentedBeats;
}
private Observation makeHMMObs(String pref, int Sx, int S1base, int S1next, FindBeats norm) {
// make a string for the relative position of the event in the beat
// Obtain a FFT of the time between S1base and Sx and make a string of it
// First get the sample between S1base and Sx
float[] data = norm.getNormalizedData();
float[] sample = new float[(Sx - S1base) + 1];
if (sample.length < 3) {
// not enough values in sample
return null;
}
// arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
System.arraycopy(data, S1base, sample, 0, Sx - S1base);
float offsetAbs = (Sx - S1base);
float offsetRel = (float) (Sx - S1base) / (float) (S1next - S1base);
// calculate a beat signature
ArrayList efft = cb.beatSign(sample);
// For the HMM to separate the observations in more cases than S1-S4, we need to
// add a "minor" numbering to the "Sx" string.
// However it will be added later, to have a reasonnable amount of Observations
Observation obs = new Observation(
pref, Sx, offsetRel, offsetAbs, efft,
norm.getNoisyFile(), norm.getShift());
return obs;
}
private Observation analalyse(
Integer prev,
Integer next,
Integer S1MB,
FindBeats norm,
int cnt
) {
String eventName;
if ((S1MB.intValue() > prev.intValue()) && (S1MB.intValue() < next.intValue())) {
eventName = "S" + String.valueOf(cnt);
Observation eventHMM = makeHMMObs(eventName, S1MB.intValue(), prev.intValue(), next.intValue(), norm);
if (eventHMM == null) {
return null; // continue
} else {
return eventHMM;
}
}
return null; // not continue
}
}
|
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TimeZone;
import javax.xml.bind.DatatypeConverter;
import org.json.JSONException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.bitcoin.core.Transaction;
import com.google.common.primitives.Ints;
public class Roll {
static Logger logger = LoggerFactory.getLogger(Roll.class);
public static Integer length = 32+8;
public static Integer length2 = 32+8+8; //last parameter is amount of CHA given for bet made with BTC
public static Integer id = 14;
public static void parse(Integer txIndex, List<Byte> message) {
Database db = Database.getInstance();
ResultSet rs = db.executeQuery("select * from transactions where tx_index="+txIndex.toString());
try {
if (rs.next()) {
String source = rs.getString("source");
String destination = rs.getString("destination");
BigInteger btcAmount = BigInteger.valueOf(rs.getLong("btc_amount"));
BigInteger fee = BigInteger.valueOf(rs.getLong("fee"));
Integer blockIndex = rs.getInt("block_index");
String txHash = rs.getString("tx_hash");
ResultSet rsCheck = db.executeQuery("select * from rolls where tx_index='"+txIndex.toString()+"'");
if (rsCheck.next()) return;
if (message.size() == length || message.size() == length2) {
String rollTxHash = new BigInteger(1, Util.toByteArray(message.subList(0, 32))).toString(16);
while (rollTxHash.length()<64) rollTxHash = "0"+rollTxHash;
ByteBuffer byteBuffer = ByteBuffer.allocate(message.size());
for (byte b : message) {
byteBuffer.put(b);
}
Double roll = byteBuffer.getDouble(32) * 100.0;
BigInteger chaAmount = BigInteger.ZERO;
if (message.size() == length2) {
chaAmount = BigInteger.valueOf(byteBuffer.getLong(32+8));
}
String validity = "invalid";
if (source.equals(Config.feeAddress)) {
validity = "valid";
}
if (chaAmount.compareTo(BigInteger.ZERO)>0) {
Util.debit(source, "CHA", chaAmount, "Debit CHA amount from casino liquidity provider", txHash, blockIndex);
db.executeUpdate("update bets set bet = bet+"+chaAmount.toString()+" where tx_hash='"+rollTxHash.toString()+"';");
}
ResultSet rsBet = db.executeQuery("select * from bets where tx_hash='"+rollTxHash.toString()+"' and resolved='true';");
if (rsBet.next()) {
db.executeUpdate("update bets set resolved='', profit='0', roll='', rolla='', rollb='' where tx_hash='"+rollTxHash.toString()+"';");
db.executeUpdate("delete from credits where event='"+rollTxHash.toString()+"';");
}
db.executeUpdate("insert into rolls(tx_index, tx_hash, block_index, source, destination, roll_tx_hash, roll, cha_amount, validity) values('"+txIndex.toString()+"','"+txHash+"','"+blockIndex.toString()+"','"+source+"','"+destination+"','"+rollTxHash.toString()+"','"+roll.toString()+"','"+chaAmount.toString()+"','"+validity+"')");
}
}
} catch (SQLException e) {
}
}
public static List<RollRequestInfo> getPendingRollRequests(String source) {
Database db = Database.getInstance();
ResultSet rs = db.executeQuery("select * from transactions where block_index<0 and source='"+source+"' order by tx_index desc;");
List<RollRequestInfo> rolls = new ArrayList<RollRequestInfo>();
Blocks blocks = Blocks.getInstance();
try {
while (rs.next()) {
String destination = rs.getString("destination");
BigInteger btcAmount = BigInteger.valueOf(rs.getLong("btc_amount"));
BigInteger fee = BigInteger.valueOf(rs.getLong("fee"));
Integer blockIndex = rs.getInt("block_index");
String txHash = rs.getString("tx_hash");
Integer txIndex = rs.getInt("tx_index");
String dataString = rs.getString("data");
ResultSet rsCheck = db.executeQuery("select * from rolls where tx_index='"+txIndex.toString()+"'");
if (!rsCheck.next()) {
List<Byte> messageType = blocks.getMessageTypeFromTransaction(dataString);
List<Byte> message = blocks.getMessageFromTransaction(dataString);
if (messageType.get(3)==Roll.id.byteValue() && (message.size() == length || message.size() == length2)) {
ByteBuffer byteBuffer = ByteBuffer.allocate(message.size());
for (byte b : message) {
byteBuffer.put(b);
}
String rollTxHash = new BigInteger(1, Util.toByteArray(message.subList(0, 32))).toString(16);
while (rollTxHash.length()<64) rollTxHash = "0"+rollTxHash;
Double roll = byteBuffer.getDouble(32);
BigInteger chaAmount = BigInteger.ZERO;
if (message.size() == length2) {
chaAmount = BigInteger.valueOf(byteBuffer.getLong(32+8));
}
RollRequestInfo rollInfo = new RollRequestInfo();
rollInfo.roll = roll;
rollInfo.chaAmount = chaAmount;
rollInfo.rollTxHash = rollTxHash;
rollInfo.source = source;
rolls.add(rollInfo);
}
}
}
} catch (SQLException e) {
}
return rolls;
}
public static Transaction create(String source, String destination, BigInteger btcAmount, String rollTxHash, BigInteger chaAmount, String useUnspentTxHash, Integer useUnspentVout) throws Exception {
List<String> destinations = new ArrayList<String>();
destinations.add(destination);
List<BigInteger> btcAmounts = new ArrayList<BigInteger>();
btcAmounts.add(btcAmount);
return create(source, destinations, btcAmounts, rollTxHash, chaAmount, useUnspentTxHash, useUnspentVout);
}
public static Transaction create(String source, List<String> destinations, List<BigInteger> btcAmounts, String rollTxHash, BigInteger chaAmount, String useUnspentTxHash, Integer useUnspentVout) throws Exception {
Database db = Database.getInstance();
rollTxHash = rollTxHash.substring(0, 64);
byte[] rollTxHashBytes = DatatypeConverter.parseHexBinary(rollTxHash);
Blocks blocks = Blocks.getInstance();
ByteBuffer byteBuffer = null;
if (chaAmount.compareTo(BigInteger.ZERO)>0) {
byteBuffer = ByteBuffer.allocate(length2+4);
} else {
byteBuffer = ByteBuffer.allocate(length+4);
}
byteBuffer.putInt(0, id);
for (int i = 0; i<rollTxHashBytes.length; i++) byteBuffer.put(0+4+i, rollTxHashBytes[i]);
Random random = new Random();
Double roll = random.nextDouble();
byteBuffer.putDouble(32+4, roll); //random double on (0,1)
if (chaAmount.compareTo(BigInteger.ZERO)>0) {
byteBuffer.putLong(32+4+8, chaAmount.longValue());
}
List<Byte> dataArrayList = Util.toByteArrayList(byteBuffer.array());
dataArrayList.addAll(0, Util.toByteArrayList(Config.prefix.getBytes()));
byte[] data = Util.toByteArray(dataArrayList);
String dataString = "";
try {
dataString = new String(data,"ISO-8859-1");
} catch (UnsupportedEncodingException e) {
}
logger.info("Rolling the dice for "+rollTxHash+": "+roll);
Transaction tx = blocks.transaction(source, destinations, btcAmounts, BigInteger.valueOf(Config.minFee), dataString, useUnspentTxHash, useUnspentVout);
return tx;
}
public static void serviceRollRequests() {
if (Util.isOwnAddress(Config.feeAddress)) {
List<RollRequestInfo> rollsPending = getPendingRollRequests(Config.feeAddress);
Blocks blocks = Blocks.getInstance();
Database db = Database.getInstance();
List<UnspentOutput> unspents = Util.getUnspents(Config.feeAddress);
for (UnspentOutput unspent : unspents) {
if (unspent.confirmations.equals(0) && unspent.type.equals("pubkeyhash")) {
BigInteger amount = new BigDecimal(unspent.amount*Config.unit).toBigInteger();
if (amount.compareTo(BigInteger.valueOf(Config.feeAddressFee))>=0) {
TransactionInfoInsight txInfo = Util.getTransactionInsight(unspent.txid);
String rollTxHash = unspent.txid;
try {
ResultSet rs = db.executeQuery("select * from rolls where roll_tx_hash='"+rollTxHash+"';");
Boolean pending = false;
for (RollRequestInfo rollInfo : rollsPending) {
if (rollInfo.rollTxHash.equals(rollTxHash)) {
pending = true;
}
}
if (!pending && !rs.next()) {
try {
List<String> destinations = new ArrayList<String>();
List<BigInteger> btcAmounts = new ArrayList<BigInteger>();
destinations.add(Config.marketMakingAddress);
BigInteger convertToCha = amount.subtract(BigInteger.valueOf(Config.feeAddressFee));
btcAmounts.add(convertToCha.add(BigInteger.valueOf(Config.minFee)));
BigInteger chaAmount = BigInteger.ZERO;
if (convertToCha.compareTo(BigInteger.valueOf(Config.minFee))>0) {
Double price = Util.getBestOfferOnExchanges(convertToCha.doubleValue()/Config.unit.doubleValue());
Util.buyBestOfferOnExchanges(convertToCha.doubleValue()/Config.unit.doubleValue());
if (price == null) { //if we can't get a price from Poloniex, we shall look for the previous traded price
ResultSet previousPrices = db.executeQuery("select 1.0*btc_amount/cha_amount as price from rolls,bets,transactions where rolls.roll_tx_hash=bets.tx_hash and transactions.tx_hash=bets.tx_hash and cha_amount>0 order by bets.tx_index desc limit 1;");
if (previousPrices.next()) {
price = previousPrices.getDouble("price");
}
}
if (price == null) price = Config.burnPrice; //if all else fails, we default to the burn valuation
chaAmount = new BigDecimal(convertToCha.doubleValue() / price).toBigInteger();
logger.info("Converting "+convertToCha+" BTC into "+chaAmount+" CHA at a price of "+price);
}
Transaction tx = Roll.create(Config.feeAddress, destinations, btcAmounts, rollTxHash, chaAmount, unspent.txid, unspent.vout);
blocks.sendTransaction(Config.feeAddress, tx);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
}
}
}
}
}
}
}
class RollRequestInfo {
public String source;
public String rollTxHash;
public Double roll;
public BigInteger chaAmount;
}
|
import com.sun.rowset.internal.Row;
abstract class Rule {
public abstract short check(Chess[][] ChessStatus);
}
interface Eatable {
public void eat(Chess[][] ChessStatus);
}
class GoRule extends Rule implements Eatable {
@Override
public short check(final Chess[][] ChessStatus) {
// TODO: GO/FinishCheck
int Row_len = ChessStatus.length, Col_len = ChessStatus[0].length;
int WhiteColorCounter = 0, BlackColorCounter = 0;
for (int i = 0; i < Row_len; i++) {
for (int j = 0; j < Col_len; j++) {
if (ChessStatus[i][j] != null) {
short nowColor = ChessStatus[i][j].getColor();
if (nowColor == Const.WHITE_CHESS) {
WhiteColorCounter++;
} else {
BlackColorCounter++;
}
}
}
}
if (WhiteColorCounter >= 177 || BlackColorCounter >= 183) {
if (WhiteColorCounter >= 177 && BlackColorCounter < 183) {
return Const.WHITE_WIN;
} else if (BlackColorCounter >= 183 && WhiteColorCounter < 177) {
return Const.BLACK_WIN;
}
} else if (WhiteColorCounter > BlackColorCounter - 6) {
return Const.WHITE_WIN;
} else if (BlackColorCounter > WhiteColorCounter + 6) {
return Const.BLACK_WIN;
} else {
return Const.TIE;
}
return Const.NO_WIN;
}
@Override
public void eat(Chess[][] ChessStatus) {
// TODO: Eat Dot
int Row_len = ChessStatus.length, Col_len = ChessStatus[0].length, i, j, CheckLocX, CheckLocY, Mark = 0;
int[][] Mapping = new int[Row_len][Col_len], CanBeEat = new int[Row_len][Col_len], HasGone = new int[Row_len][Col_len];
int[][][] CheckPoint = new int[Row_len][Col_len][4], Stack = new int[Row_len][Col_len][2], CanGo = new int[Row_len][Col_len][4];
//CheckPoint Comment
//Order: Up -> Left -> Down -> Right
boolean EatAble = false;
ArrayIniter(ChessStatus, Mapping, CanBeEat, HasGone, Stack, CheckPoint, CanGo, Row_len, Col_len);//init array
//Mapping
for (i = 0; i < Row_len; i++) {
for (j = 0; j < Col_len; j++) {
CheckLocX = i;
CheckLocY = j;
if (Mapping[i][j] != Const.NO_CHESS) {
Stack[i][j][Const.LOCX] = Const.STARTPOS;
Stack[i][j][Const.LOCY] = Const.STARTPOS;//start positon init
HasGone[i][j] = Const.HASGONE;
while (Stack[i][j][Const.LOCX] == Const.NOITEM && Stack[i][j][Const.LOCY] == Const.NOITEM) {
Mark = Checker(CheckPoint, Mapping, CheckLocX, CheckLocY);//check
if (Mark == 1)//if check Nothing
break;
//if checked, go next, and stack position
//first, search where can go
for (int CheckCanGo = Const.UP; CheckCanGo < Const.LEFT; CheckCanGo++) {//check where can go
if (CheckCanGo == Const.UP) {
if (CheckPoint[CheckLocX][CheckLocY][CheckCanGo] == Const.SAME_COLOR && HasGone[CheckLocX][CheckLocY + 1] == Const.HAVENGONE)
CanGo[CheckLocX][CheckLocY][CheckCanGo] = Const.CANGO;
}
if (CheckCanGo == Const.RIGHT) {
if (CheckPoint[CheckLocX][CheckLocY][CheckCanGo] == Const.SAME_COLOR && HasGone[CheckLocX + 1][CheckLocY] == Const.HAVENGONE)
CanGo[CheckLocX][CheckLocY][CheckCanGo] = Const.CANGO;
}
if (CheckCanGo == Const.DOWN) {
if (CheckPoint[CheckLocX][CheckLocY][CheckCanGo] == Const.SAME_COLOR && HasGone[CheckLocX][CheckLocY - 1] == Const.HAVENGONE)
CanGo[CheckLocX][CheckLocY][CheckCanGo] = Const.CANGO;
}
if (CheckCanGo == Const.LEFT) {
if (CheckPoint[CheckLocX][CheckLocY][CheckCanGo] == Const.SAME_COLOR && HasGone[CheckLocX - 1][CheckLocY] == Const.HAVENGONE)
CanGo[CheckLocX][CheckLocY][CheckCanGo] = Const.CANGO;
}
}
for (int Way_to_go = Const.UP; Way_to_go < Const.LEFT; Way_to_go++) {//goto next point
if (CheckPoint[CheckLocX][CheckLocY][Way_to_go] == Const.SAME_COLOR) {//if same color
if (Way_to_go == Const.UP) {
CheckLocY++;//move
if (HasGone[CheckLocX][CheckLocY] == Const.HAVENGONE) {// if never gone
HasGone[CheckLocX][CheckLocY] = Const.HASGONE;//now is gone
CanGo[CheckLocX][CheckLocY - 1][Way_to_go] = Const.CANNOTGO;//now cannot go
CanBeEat[CheckLocX][CheckLocY - 1] = Const.CANBEEAT;//Mark Eatable Buff
Stack[CheckLocX][CheckLocY][0] = CheckLocX;//Stack LocX Record
Stack[CheckLocX][CheckLocY][1] = CheckLocY - 1;//Stack LocY Record
break;//don't do others
} else
CheckLocY--;//return move back
} else if (Way_to_go == Const.RIGHT) {
CheckLocX++;
if (HasGone[CheckLocX][CheckLocY] == Const.HAVENGONE) {
HasGone[CheckLocX][CheckLocY] = Const.HASGONE;
CanGo[CheckLocX - 1][CheckLocY][Way_to_go] = Const.CANNOTGO;
CanBeEat[CheckLocX - 1][CheckLocY] = Const.CANBEEAT;
Stack[CheckLocX][CheckLocY][0] = CheckLocX - 1;
Stack[CheckLocX][CheckLocY][1] = CheckLocY;
break;
} else
CheckLocX++;
} else if (Way_to_go == Const.DOWN) {
CheckLocY
if (HasGone[CheckLocX][CheckLocY] == Const.HAVENGONE) {
HasGone[CheckLocX][CheckLocY] = Const.HASGONE;
CanGo[CheckLocX][CheckLocY + 1][Way_to_go] = Const.CANNOTGO;
CanBeEat[CheckLocX][CheckLocY + 1] = Const.CANBEEAT;
Stack[CheckLocX][CheckLocY][0] = CheckLocX;
Stack[CheckLocX][CheckLocY][1] = CheckLocY + 1;
break;
} else
CheckLocY++;
} else {//Const.LEFT
CheckLocX
if (HasGone[CheckLocX][CheckLocY] == Const.HAVENGONE) {
HasGone[CheckLocX][CheckLocY] = Const.HASGONE;
CanGo[CheckLocX + 1][CheckLocY][Way_to_go] = Const.CANNOTGO;
CanBeEat[CheckLocX + 1][CheckLocY] = Const.CANBEEAT;
Stack[CheckLocX][CheckLocY][0] = CheckLocX + 1;
Stack[CheckLocX][CheckLocY][1] = CheckLocY;
break;
} else
CheckLocX
}
}
}//first step end
//Second, if no where to go, back to nearst position which has CanGo == 1
if (CanGo[CheckLocX][CheckLocY][Const.UP] == Const.CANNOTGO && CanGo[CheckLocX][CheckLocY][Const.RIGHT] == Const.CANNOTGO
&& CanGo[CheckLocX][CheckLocY][Const.DOWN] == Const.CANNOTGO && CanGo[CheckLocX][CheckLocY][Const.LEFT] == Const.CANNOTGO) {
while (CanGo[CheckLocX][CheckLocY][Const.UP] == Const.CANNOTGO || CanGo[CheckLocX][CheckLocY][Const.RIGHT] == Const.CANNOTGO
|| CanGo[CheckLocX][CheckLocY][Const.DOWN] == Const.CANNOTGO || CanGo[CheckLocX][CheckLocY][Const.LEFT] == Const.CANNOTGO) {
int StackLocX = Stack[CheckLocX][CheckLocY][Const.LOCX], StackLocY = Stack[CheckLocX][CheckLocY][Const.LOCY];
if (CheckLocX == i && CheckLocY == j) {
if (CanGo[CheckLocX][CheckLocY][Const.UP] == Const.CANNOTGO && CanGo[CheckLocX][CheckLocY][Const.RIGHT] == Const.CANNOTGO
&& CanGo[CheckLocX][CheckLocY][Const.DOWN] == Const.CANNOTGO && CanGo[CheckLocX][CheckLocY][Const.LEFT] == Const.CANNOTGO) {
Stack[CheckLocX][CheckLocY][Const.LOCY] = Const.NOITEM;
Stack[CheckLocX][CheckLocY][Const.LOCY] = Const.NOITEM;
} else {
Stack[CheckLocX][CheckLocY][Const.LOCX] = Const.STARTPOS;
Stack[CheckLocX][CheckLocY][Const.LOCY] = Const.STARTPOS;
}
} else {
Stack[CheckLocX][CheckLocY][Const.LOCX] = Const.NOITEM;
Stack[CheckLocX][CheckLocY][Const.LOCY] = Const.NOITEM;
}
CheckLocX = StackLocX;
CheckLocY = StackLocY;
}
}
}//While loop end
if (Mark == 0) {//check where can be eat
EatAble = true;
} else {// nothing to eat
ArrayIniter(ChessStatus, Mapping, CanBeEat, HasGone, Stack, CheckPoint, CanGo, Row_len, Col_len);//init array
}
if (EatAble) {//Eating
Eating(ChessStatus, CanBeEat, Row_len, Col_len);
ArrayIniter(ChessStatus, Mapping, CanBeEat, HasGone, Stack, CheckPoint, CanGo, Row_len, Col_len);//init array
EatAble = false;
}
}//if has chess
}//for j loop
}// for i loop
}
public static void Eating(Chess[][] ChessStatus, int[][] CanBeEat, int Row_len, int Col_len) {
for (int i = 0; i < Row_len; i++) {
for (int j = 0; j < Col_len; j++) {
if (CanBeEat[i][j] == 1) {
ChessStatus[i][j] = null;
}
}
}
}
public static void ArrayIniter(Chess[][] ChessStatus, int[][] Mapping, int[][] CanBeEat, int[][] HasGone, int[][][] Stack, int[][][] CheckPoint, int[][][] CanGo, int Row_len, int Col_len) {
for (int i = 0; i < Row_len; i++) {
for (int j = 0; j < Col_len; j++) {
if (ChessStatus[i][j] == null) {
Mapping[i][j] = Const.NO_CHESS;
} else {
Mapping[i][j] = ChessStatus[i][j].getColor();
}
HasGone[i][j] = Const.HAVENGONE;
CanBeEat[i][j] = Const.CANNOTEAT;
Stack[i][j][Const.LOCX] = Const.NOITEM;
Stack[i][j][Const.LOCY] = Const.NOITEM;
CanGo[i][j][Const.UP] = Const.CANNOTGO;
CanGo[i][j][Const.RIGHT] = Const.CANNOTGO;
CanGo[i][j][Const.DOWN] = Const.CANNOTGO;
CanGo[i][j][Const.LEFT] = Const.CANNOTGO;
CheckPoint[i][j][Const.UP] = Const.INIT;
CheckPoint[i][j][Const.RIGHT] = Const.INIT;
CheckPoint[i][j][Const.DOWN] = Const.INIT;
CheckPoint[i][j][Const.LEFT] = Const.INIT;
}
}
}
public static short Checker(int[][][] CheckPoint, int[][] Mapping, int i, int j) {
int Row_len = Mapping.length, Col_len = Mapping[0].length;
short Mark = 0;
if (i + 1 > Row_len) {//check if has wall
CheckPoint[i][j][Const.RIGHT] = Const.DIFF_COLOR;
} else if (i - 1 < 0) {
CheckPoint[i][j][Const.LEFT] = Const.DIFF_COLOR;
} else if (j + 1 > Col_len) {
CheckPoint[i][j][Const.UP] = Const.DIFF_COLOR;
} else if (j - 1 < 0) {
CheckPoint[i][j][Const.DOWN] = Const.DIFF_COLOR;
} else if (Mapping[i][j] != Mapping[i][j + 1] && Mapping[i][j + 1] != Const.NO_CHESS) {//check if Diff Color
CheckPoint[i][j][Const.UP] = Const.DIFF_COLOR;
} else if (Mapping[i][j] != Mapping[i + 1][j] && Mapping[i + 1][j] != Const.NO_CHESS) {
CheckPoint[i][j][Const.RIGHT] = Const.DIFF_COLOR;
} else if (Mapping[i][j] != Mapping[i][j - 1] && Mapping[i][j - 1] != Const.NO_CHESS) {
CheckPoint[i][j][Const.DOWN] = Const.DIFF_COLOR;
} else if (Mapping[i][j] != Mapping[i - 1][j] && Mapping[i - 1][j] != Const.NO_CHESS) {
CheckPoint[i][j][Const.LEFT] = Const.DIFF_COLOR;
} else if (Mapping[i][j] == Mapping[i][j + 1]) {//check if Same Color
CheckPoint[i][j][Const.UP] = Const.SAME_COLOR;
} else if (Mapping[i][j] != Mapping[i + 1][j]) {
CheckPoint[i][j][Const.RIGHT] = Const.SAME_COLOR;
} else if (Mapping[i][j] != Mapping[i][j - 1]) {
CheckPoint[i][j][Const.DOWN] = Const.SAME_COLOR;
} else if (Mapping[i][j] != Mapping[i - 1][j]) {
CheckPoint[i][j][Const.LEFT] = Const.SAME_COLOR;
} else if (Mapping[i][j + 1] == Const.NO_CHESS) {//check if Nothing here
CheckPoint[i][j][Const.UP] = Const.NOTHING;
Mark = 1;
} else if (Mapping[i + 1][j] == Const.NO_CHESS) {
CheckPoint[i][j][Const.RIGHT] = Const.NOTHING;
Mark = 1;
} else if (Mapping[i][j - 1] == Const.NO_CHESS) {
CheckPoint[i][j][Const.DOWN] = Const.NOTHING;
Mark = 1;
} else if (Mapping[i - 1][j] == Const.NO_CHESS) {
CheckPoint[i][j][Const.LEFT] = Const.NOTHING;
Mark = 1;
}
return Mark;
}
}
class GomokuRule extends Rule {
// Fixme: Change to short and return who win
@Override
public short check(final Chess[][] ChessStatus) {
int Row_len = ChessStatus.length, Col_len = ChessStatus[0].length, i, j;
short CheckResault = Const.NO_WIN;
Chess CheckChess;
for (i = 0; i < Row_len; i++) {
for (j = 0; j < Col_len; j++) {
CheckChess = ChessStatus[i][j];
if (ChessStatus[i][j] != null) {
if (CheckResault == Const.NO_WIN) {
CheckResault = LeftLastCheck(ChessStatus, CheckChess);
}
if (CheckResault == Const.NO_WIN) {
CheckResault = DownLastCheck(ChessStatus, CheckChess);
}
if (CheckResault == Const.NO_WIN) {
CheckResault = LeftDownLastCheck(ChessStatus, CheckChess);
}
if (CheckResault == Const.NO_WIN) {
CheckResault = LeftUpLastCheck(ChessStatus, CheckChess);
}
if (CheckResault == Const.NO_WIN) {
CheckResault = TieCheck(ChessStatus, CheckChess);
}
}
}
}
if (CheckResault != Const.NO_WIN) {
return CheckResault;
}
return Const.NO_WIN;
}
public short DownLastCheck(final Chess[][] ChessStatus, Chess CheckChess) {
int Row_len = ChessStatus.length, LocX = CheckChess.getNowLocX(), LocY = CheckChess.getNowLocY();
int CheckPoint = LocY;
int CheckResault = 0;
while (CheckPoint < Row_len && CheckPoint < LocY + 6 && ChessStatus[LocX][CheckPoint] != null) {
if (CheckChess.getColor() == ChessStatus[LocX][CheckPoint].getColor()) {
CheckResault++;
}
CheckPoint++;
}
if (CheckResault >= 5) {
if (CheckChess.getColor() == Const.WHITE_CHESS) {
return Const.WHITE_WIN;
} else {
return Const.BLACK_WIN;
}
}
return Const.NO_WIN;
}
public short LeftLastCheck(final Chess[][] ChessStatus, Chess CheckChess) {
int Col_len = ChessStatus[0].length, LocX = CheckChess.getNowLocX(), LocY = CheckChess.getNowLocY();
int CheckPoint = LocX;
int CheckResault = 0;
while (CheckPoint < Col_len && CheckPoint < LocX + 6 && ChessStatus[CheckPoint][LocY] != null) {
if (CheckChess.getColor() == ChessStatus[CheckPoint][LocY].getColor()) {
CheckResault++;
}
CheckPoint++;
}
if (CheckResault >= 5) {
if (CheckChess.getColor() == Const.WHITE_CHESS) {
return Const.WHITE_WIN;
} else {
return Const.BLACK_WIN;
}
}
return Const.NO_WIN;
}
public short LeftDownLastCheck(final Chess[][] ChessStatus, Chess CheckChess) {
int Row_len = ChessStatus.length, Col_len = ChessStatus[0].length, LocX = CheckChess.getNowLocX(), LocY = CheckChess.getNowLocY();
int CheckPointX = LocX, CheckPointY = LocY;
int CheckResault = 0;
while (CheckPointX < Row_len && CheckPointY < Col_len && CheckPointX < LocX + 6 && CheckPointY < LocY + 6 && ChessStatus[CheckPointX][CheckPointY] != null) {
if (CheckChess.getColor() == ChessStatus[CheckPointX][CheckPointY].getColor()) {
CheckResault++;
}
CheckPointX++;
CheckPointY++;
}
if (CheckResault >= 5) {
if (CheckChess.getColor() == Const.WHITE_CHESS) {
return Const.WHITE_WIN;
} else {
return Const.BLACK_WIN;
}
}
return Const.NO_WIN;
}
public short LeftUpLastCheck(final Chess[][] ChessStatus, Chess CheckChess) {
int Row_len = ChessStatus.length, Col_len = ChessStatus[0].length, LocX = CheckChess.getNowLocX(), LocY = CheckChess.getNowLocY();
int CheckPointX = LocX, CheckPointY = LocY;
int CheckResault = 0;
while (CheckPointX < Row_len && CheckPointY > 0 && CheckPointX < LocX + 6 && CheckPointY < LocY + 6 && ChessStatus[CheckPointX][CheckPointY] != null) {
if (CheckChess.getColor() == ChessStatus[CheckPointX][CheckPointY].getColor()) {
CheckResault++;
}
CheckPointX++;
CheckPointY
}
if (CheckResault >= 5) {
if (CheckChess.getColor() == Const.WHITE_CHESS) {
return Const.WHITE_WIN;
} else {
return Const.BLACK_WIN;
}
}
return Const.NO_WIN;
}
public short TieCheck(final Chess[][] ChessStatus, Chess CheckChess) {
int Row_len = ChessStatus.length, Col_len = ChessStatus[0].length, LocX = CheckChess.getNowLocX(), LocY = CheckChess.getNowLocY();
if (Row_len == LocX && Col_len == LocY) {
return Const.TIE;
}
return Const.NO_WIN;
}
}
|
package com.ferreusveritas.dynamictrees.trees;
import java.util.List;
import java.util.Random;
import java.util.function.BiFunction;
import com.ferreusveritas.dynamictrees.ModBlocks;
import com.ferreusveritas.dynamictrees.ModConfigs;
import com.ferreusveritas.dynamictrees.api.TreeHelper;
import com.ferreusveritas.dynamictrees.blocks.BlockSurfaceRoot;
import com.ferreusveritas.dynamictrees.systems.GrowSignal;
import com.ferreusveritas.dynamictrees.systems.dropcreators.DropCreatorApple;
import com.ferreusveritas.dynamictrees.systems.featuregen.FeatureGenClearVolume;
import com.ferreusveritas.dynamictrees.systems.featuregen.FeatureGenFlareBottom;
import com.ferreusveritas.dynamictrees.systems.featuregen.FeatureGenHugeMushrooms;
import com.ferreusveritas.dynamictrees.systems.featuregen.FeatureGenMound;
import com.ferreusveritas.dynamictrees.systems.featuregen.FeatureGenRoots;
import net.minecraft.block.Block;
import net.minecraft.block.BlockNewLeaf;
import net.minecraft.block.BlockPlanks;
import net.minecraft.block.material.Material;
import net.minecraft.init.Biomes;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraftforge.common.BiomeDictionary.Type;
public class TreeDarkOak extends TreeFamilyVanilla {
public class SpeciesDarkOak extends Species {
protected FeatureGenHugeMushrooms underGen;
protected FeatureGenFlareBottom flareBottomGen;
protected FeatureGenRoots rootGen;
protected FeatureGenMound moundGen;
SpeciesDarkOak(TreeFamily treeFamily) {
super(treeFamily.getName(), treeFamily, ModBlocks.darkOakLeavesProperties);
//Dark Oak Trees are tall, slowly growing, thick trees
setBasicGrowingParameters(0.30f, 18.0f, 4, 6, 0.8f);
setSoilLongevity(14);//Grows for a long long time
envFactor(Type.COLD, 0.75f);
envFactor(Type.HOT, 0.50f);
envFactor(Type.DRY, 0.25f);
envFactor(Type.MUSHROOM, 1.25f);
if(ModConfigs.worldGen && !ModConfigs.enableAppleTrees) {
addDropCreator(new DropCreatorApple());
}
setupStandardSeedDropping();
//Add species features
addGenFeature(new FeatureGenClearVolume(6));//Clear a spot for the thick tree trunk
addGenFeature(new FeatureGenFlareBottom(this));//Flare the bottom
addGenFeature(new FeatureGenMound(this, 5));//Establish mounds
addGenFeature(new FeatureGenHugeMushrooms(this).setMaxShrooms(1).setMaxAttempts(3));//Generate Huge Mushrooms
addGenFeature(new FeatureGenRoots(this, 13).setScaler(getRootScaler()));//Finally Generate Roots
}
protected BiFunction<Integer, Integer, Integer> getRootScaler() {
return (inRadius, trunkRadius) -> {
float scale = MathHelper.clamp(trunkRadius >= 13 ? (trunkRadius / 24f) : 0, 0, 1);
return (int) (inRadius * scale);
};
}
@Override
public boolean isBiomePerfect(Biome biome) {
return isOneOfBiomes(biome, Biomes.ROOFED_FOREST);
};
@Override
public int getLowestBranchHeight(World world, BlockPos pos) {
return (int)(super.getLowestBranchHeight(world, pos) * biomeSuitability(world, pos));
}
@Override
public float getEnergy(World world, BlockPos pos) {
return super.getEnergy(world, pos) * biomeSuitability(world, pos);
}
@Override
public float getGrowthRate(World world, BlockPos pos) {
return super.getGrowthRate(world, pos) * biomeSuitability(world, pos);
}
@Override
protected int[] customDirectionManipulation(World world, BlockPos pos, int radius, GrowSignal signal, int probMap[]) {
probMap[EnumFacing.UP.getIndex()] = 4;
//Disallow up/down turns after having turned out of the trunk once.
if(!signal.isInTrunk()) {
probMap[EnumFacing.UP.getIndex()] = 0;
probMap[EnumFacing.DOWN.getIndex()] = 0;
probMap[signal.dir.ordinal()] *= 0.35;//Promotes the zag of the horizontal branches
}
//Amplify cardinal directions to encourage spread the higher we get
float energyRatio = signal.delta.getY() / getEnergy(world, pos);
float spreadPush = energyRatio * 2;
spreadPush = spreadPush < 1.0f ? 1.0f : spreadPush;
for(EnumFacing dir: EnumFacing.HORIZONTALS) {
probMap[dir.ordinal()] *= spreadPush;
}
//Ensure that the branch gets out of the trunk at least two blocks so it won't interfere with new side branches at the same level
if(signal.numTurns == 1 && signal.delta.distanceSq(0, signal.delta.getY(), 0) == 1.0 ) {
for(EnumFacing dir: EnumFacing.HORIZONTALS) {
if(signal.dir != dir) {
probMap[dir.ordinal()] = 0;
}
}
}
//If the side branches are too swole then give some other branches a chance
if(signal.isInTrunk()) {
for(EnumFacing dir: EnumFacing.HORIZONTALS) {
if(probMap[dir.ordinal()] >= 7) {
probMap[dir.ordinal()] = 2;
}
}
if(signal.delta.getY() > getLowestBranchHeight() + 5) {
probMap[EnumFacing.UP.ordinal()] = 0;
signal.energy = 2;
}
}
return probMap;
}
@Override
public boolean rot(World world, BlockPos pos, int neighborCount, int radius, Random random, boolean rapid) {
if(super.rot(world, pos, neighborCount, radius, random, rapid)) {
if(radius > 2 && TreeHelper.isRooty(world.getBlockState(pos.down())) && world.getLightFor(EnumSkyBlock.SKY, pos) < 6) {
world.setBlockState(pos, ModBlocks.blockStates.redMushroom);//Change branch to a red mushroom
world.setBlockState(pos.down(), ModBlocks.blockStates.podzol);//Change rooty dirt to Podzol
}
return true;
}
return false;
}
}
BlockSurfaceRoot surfaceRootBlock;
public TreeDarkOak() {
super(BlockPlanks.EnumType.DARK_OAK);
ModBlocks.darkOakLeavesProperties.setTree(this);
hasConiferVariants = true;
surfaceRootBlock = new BlockSurfaceRoot(Material.WOOD, getName() + "root");
addConnectableVanillaLeaves((state) -> { return state.getBlock() instanceof BlockNewLeaf && (state.getValue(BlockNewLeaf.VARIANT) == BlockPlanks.EnumType.DARK_OAK); });
}
@Override
public void createSpecies() {
setCommonSpecies(new SpeciesDarkOak(this));
}
@Override
public boolean isThick() {
return true;
}
@Override
public List<Block> getRegisterableBlocks(List<Block> blockList) {
blockList = super.getRegisterableBlocks(blockList);
blockList.add(surfaceRootBlock);
return blockList;
}
@Override
public BlockSurfaceRoot getSurfaceRoots() {
return surfaceRootBlock;
}
}
|
// $Header: /cvsshare/content/cvsroot/cdecurate/src/gov/nih/nci/cadsr/cdecurate/tool/InsACService.java,v 1.77 2009-04-29 16:15:00 veerlah Exp $
// $Name: not supported by cvs2svn $
package gov.nih.nci.cadsr.cdecurate.tool;
import gov.nih.nci.cadsr.cdecurate.database.SQLHelper;
import gov.nih.nci.cadsr.cdecurate.util.DataManager;
import gov.nih.nci.cadsr.persist.concept.Con_Derivation_Rules_Ext_Mgr;
import gov.nih.nci.cadsr.persist.de.DeComp;
import gov.nih.nci.cadsr.persist.de.DeErrorCodes;
import gov.nih.nci.cadsr.persist.de.DeVO;
import gov.nih.nci.cadsr.persist.evs.EvsVO;
import gov.nih.nci.cadsr.persist.evs.Evs_Mgr;
import gov.nih.nci.cadsr.persist.evs.ResultVO;
import gov.nih.nci.cadsr.persist.exception.DBException;
import gov.nih.nci.cadsr.persist.oc.Object_Classes_Ext_Mgr;
import gov.nih.nci.cadsr.persist.prop.Properties_Ext_Mgr;
import gov.nih.nci.cadsr.persist.rep.Representations_Ext_Mgr;
import java.io.Serializable;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import oracle.jdbc.driver.OracleTypes;
import org.apache.log4j.Logger;
/**
* InsACService class is used in submit action of the tool for all components.
* where all calls to insert or update to the database after the validation is
* done here.
* <P>
*
* @author Sumana Hegde
* @version 3.0
*
*/
// @SuppressWarnings("unchecked")
public class InsACService implements Serializable {
private static final long serialVersionUID = 738251122350261121L;
CurationServlet m_servlet = null;
UtilService m_util = new UtilService();
HttpServletRequest m_classReq = null;
HttpServletResponse m_classRes = null;
Logger logger = Logger.getLogger(InsACService.class.getName());
/**
* Constructs a new instance.
*
* @param req
* The HttpServletRequest object.
* @param res
* HttpServletResponse object.
* @param CurationServlet
* NCICuration servlet object.
*/
public InsACService(HttpServletRequest req, HttpServletResponse res,
CurationServlet CurationServlet) {
m_classReq = req;
m_classRes = res;
m_servlet = CurationServlet;
}
/**
* stores status message in the session
*
* @param sMsg
* string message to append to.
*/
@SuppressWarnings("unchecked")
private void storeStatusMsg(String sMsg) {
try {
m_servlet.storeStatusMsg(sMsg);
} catch (Exception e) {
logger.error(
"ERROR in InsACService-storeStatusMsg for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Message Exception");
}
}
/**
* To insert a new value domain or update the existing one in the database
* after the validation. Called from CurationServlet. Gets all the attribute
* values from the bean, sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_VD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"
* to submit If no error occurs from query execute, calls 'setVD_PVS' to
* make relationship between Permissible values and value domain, calls
* 'setDES' to store selected rep term, rep qualifier, and language in the
* database,
*
* @param sAction
* Insert or update Action.
* @param vd
* VD Bean.
* @param sInsertFor
* for Versioning.
* @param oldVD
* VD IDseq.
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
@SuppressWarnings("unchecked")
public String setVD(String sAction, VD_Bean vd, String sInsertFor,
VD_Bean oldVD) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
String sVDParent = "";
try {
String sOriginAction = (String) session
.getAttribute("originAction");
if (sOriginAction == null)
sOriginAction = "";
m_classReq.setAttribute("retcode", ""); // empty retcode to track it
// all through this request
if (oldVD == null)
oldVD = new VD_Bean();
String sVD_ID = vd.getVD_VD_IDSEQ();
String sName = vd.getVD_PREFERRED_NAME();
if (sName == null)
sName = "";
String pageVDType = vd.getVD_TYPE_FLAG();
String sContextID = vd.getVD_CONTE_IDSEQ();
String sLongName = vd.getVD_LONG_NAME();
String oldASLName = oldVD.getVD_ASL_NAME();
if (oldASLName == null)
oldASLName = "";
String prefType = vd.getAC_PREF_NAME_TYPE();
// do this only for insert because parent concept is not yet updated
// to get it from API
if (prefType != null && prefType.equals("SYS")
&& sAction.equals("INS")) // && sName.equals("(Generated
// by the System)"))
sName = "System Generated";
// store versioned status message
if (sInsertFor.equals("Version"))
this.storeStatusMsg("\\t Created new version successfully.");
if (!sOriginAction.equals("BlockEditVD")) // not for block edit
{
// remove vd_pvs relationship if vd type has changed from enum
// to non-enum
Vector<PV_Bean> vVDPVs = vd.getRemoved_VDPVList(); // vd.getVD_PV_List();
// //(Vector)session.getAttribute("VDPVList");
if (!pageVDType.equals("E") && sAction.equals("UPD")
&& vVDPVs != null && vVDPVs.size() > 0) {
PVServlet pvser = new PVServlet(m_classReq, m_classRes,
m_servlet);
String sStat = pvser.doRemoveVDPV(vd); // TODO -
// this.addRemoveVDPVS(vd,
// false);
if (sReturnCode != null && !sReturnCode.equals(""))
vd.setVD_TYPE_FLAG("E");
if (sStat != null && !sStat.equals(""))
this.storeStatusMsg(sStat);
}
}
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_VD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_VD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
// cstmt.registerOutParameter(1, java.sql.Types.VARCHAR);
// //ua_name
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // vd id
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // preferred
// name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // context
cstmt.registerOutParameter(8, java.sql.Types.DECIMAL); // version
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // preferred
// definition
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // cd id
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // asl
// name
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // latest
// version
// ind
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // dtl
// name
cstmt.registerOutParameter(14, java.sql.Types.NUMERIC); // Max
// Length
// Number
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // Long
// name
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // Forml
// Name
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // Forml
// Description
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // Forml
// Comment
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // UOML
// name
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // UOML
// Desciption
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // UOML
// comment
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); // Low
// value
// number
cstmt.registerOutParameter(23, java.sql.Types.VARCHAR); // High
// Value
// Number
cstmt.registerOutParameter(24, java.sql.Types.NUMERIC); // Min
// Lenght
// Num
cstmt.registerOutParameter(25, java.sql.Types.NUMERIC); // Decimal
// Place
cstmt.registerOutParameter(26, java.sql.Types.VARCHAR); // Char
// set
// name
cstmt.registerOutParameter(27, java.sql.Types.VARCHAR); // begin
// date
cstmt.registerOutParameter(28, java.sql.Types.VARCHAR); // end
// date
cstmt.registerOutParameter(29, java.sql.Types.VARCHAR); // change
// note
cstmt.registerOutParameter(30, java.sql.Types.VARCHAR); // type
// flag
cstmt.registerOutParameter(31, java.sql.Types.VARCHAR); // created
cstmt.registerOutParameter(32, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(33, java.sql.Types.VARCHAR); // modified
cstmt.registerOutParameter(34, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(35, java.sql.Types.VARCHAR); // deleted
// ind
cstmt.registerOutParameter(36, java.sql.Types.VARCHAR); // condr_idseq
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(3, ""); // make it empty default
cstmt.setString(4, sAction); // ACTION - INS, UPD or DEL
if ((sAction.equals("UPD")) || (sAction.equals("DEL")))
cstmt.setString(5, sVD_ID);
// make it null for editing released elements
if (sAction.equals("UPD") && oldASLName.equals("RELEASED")
&& !sInsertFor.equals("Version")) {
cstmt.setString(6, null); // preferred name - not null for
// INS, must be null for UPD
cstmt.setString(7, null); // context id - not null for
// INS, must be null for UPD
} else // INS case
{
cstmt.setString(6, sName); // preferred name - not null for
// INS, must be null for UPD
cstmt.setString(7, sContextID); // context id - not null for
// INS, must be null for UPD
}
cstmt.setString(37, ""); // rep term idseq, null by default
cstmt.setString(38, ""); // rep qualifier - null by default
cstmt.setString(39, ""); // origin
// String sContext = vd.getVD_CONTEXT_NAME();
Double DVersion = new Double(vd.getVD_VERSION());
double dVersion = DVersion.doubleValue();
String sDefinition = vd.getVD_PREFERRED_DEFINITION();
String sCD_ID = vd.getVD_CD_IDSEQ();
// Vector sPV_ID = vd.getVD_PV_ID();
String sAslName = vd.getVD_ASL_NAME();
// String sLatestVersion = vd.getVD_LATEST_VERSION_IND();
String sDtlName = vd.getVD_DATA_TYPE();
String sTypeFlag = vd.getVD_TYPE_FLAG();
String sRepTerm = m_util.formatStringVDSubmit(sAction,
"RepTerm", vd, oldVD);
String sSource = m_util.formatStringVDSubmit(sAction, "Source",
vd, oldVD);
String sChangeNote = m_util.formatStringVDSubmit(sAction,
"ChangeNote", vd, oldVD);
String sEndDate = m_util.formatStringVDSubmit(sAction,
"EndDate", vd, oldVD);
String sBeginDate = m_util.formatStringVDSubmit(sAction,
"BeginDate", vd, oldVD);
String sUomlName = m_util.formatStringVDSubmit(sAction,
"UOMLName", vd, oldVD);
String sFormlName = m_util.formatStringVDSubmit(sAction,
"FORMLName", vd, oldVD);
String sMaxLength = m_util.formatStringVDSubmit(sAction,
"MaxLen", vd, oldVD);
String sMinLength = m_util.formatStringVDSubmit(sAction,
"MinLen", vd, oldVD);
String sLowValue = m_util.formatStringVDSubmit(sAction,
"LowValue", vd, oldVD);
String sHighValue = m_util.formatStringVDSubmit(sAction,
"HighValue", vd, oldVD);
String sDecimalPlace = m_util.formatStringVDSubmit(sAction,
"Decimal", vd, oldVD);
// create concepts and pass them in comma-delimited format
if (!sOriginAction.equals("BlockEditVD"))
sVDParent = this.setEVSParentConcept(vd); // "", sVDCondr
if (sVDParent == null)
sVDParent = "";
// Set the In parameters (which are inherited from the
// PreparedStatement class)
cstmt.setString(3, sVDParent); // comma-delimited con idseqs
if (sVDParent.equals("removeParent"))
cstmt.setString(3, ""); // do not set vdconcepts
cstmt.setDouble(8, dVersion); // version - test says must have
// a value
cstmt.setString(9, sDefinition); // preferred definition -
// not null for INS
cstmt.setString(10, sCD_ID); // cd id - not null for INS
cstmt.setString(11, sAslName);
if (sAction.equals("INS"))
cstmt.setString(12, "Yes");
cstmt.setString(13, sDtlName);
if (sMaxLength != null && sMaxLength.length() > 0) {
Integer IntTmp = new Integer(sMaxLength);
cstmt.setInt(14, IntTmp.intValue());
}
cstmt.setString(15, sLongName); // long name - can be null
cstmt.setString(16, sFormlName);
cstmt.setString(19, sUomlName);
cstmt.setString(22, sLowValue);
cstmt.setString(23, sHighValue);
if (sMinLength != null && sMinLength.length() > 0) {
Integer IntTmp = new Integer(sMinLength);
cstmt.setInt(24, IntTmp.intValue());
}
if (sDecimalPlace != null && sDecimalPlace.length() > 0) {
Integer IntTmp = new Integer(sDecimalPlace);
cstmt.setInt(25, IntTmp.intValue());
}
cstmt.setString(27, sBeginDate);
cstmt.setString(28, sEndDate);
cstmt.setString(29, sChangeNote);
cstmt.setString(30, sTypeFlag); // type flag - E by default
if (sOriginAction.equals("BlockEditVD")
&& sInsertFor.equals("Version"))
cstmt.setString(36, vd.getVD_PAR_CONDR_IDSEQ()); // set
// the
// earlier
// one.
else {
if (sAction.equals("UPD")
&& sVDParent.equals("removeParent"))
cstmt.setString(36, " "); // remove the existing
// parent if removing them
// all
}
cstmt.setString(37, sRepTerm); // rep term idseq, null by
// default
cstmt.setString(38, ""); // rep qualifier - null by default
cstmt.setString(39, sSource); // origin
cstmt.execute();
// capture the duration
// logger.info(m_servlet.getLogMessage(m_classReq, "setVD",
// "execute ok", startDate, new java.util.Date()));
sReturnCode = cstmt.getString(2);
String prefName = cstmt.getString(6);
if (prefName != null)
vd.setVD_PREFERRED_NAME(prefName);
if (sReturnCode == null || sReturnCode.equals("")) {
m_servlet.clearBuildingBlockSessionAttributes(m_classReq,
m_classRes);
vd.setVD_REP_QUALIFIER_NAMES(null);
vd.setVD_REP_QUALIFIER_CODES(null);
vd.setVD_REP_QUALIFIER_DB(null);
}
vd.setVD_PAR_CONDR_IDSEQ(cstmt.getString(35));
sVD_ID = cstmt.getString(5);
vd.setVD_VD_IDSEQ(sVD_ID);
String sReturn = "";
if (sAction.equals("INS"))
this.storeStatusMsg("Value Domain Name : "
+ vd.getVD_LONG_NAME());
// continue update even if not null
if (sReturnCode != null && sAction.equals("INS")) {
this
.storeStatusMsg("\\t "
+ sReturnCode
+ " : Unable to create new Value Domain Successfully.");
logger
.error(sReturnCode
+ " Unable to create new Value Domain Successfully.");
} else if ((sReturnCode == null || (sReturnCode != null && sAction
.equals("UPD")))
&& !sVD_ID.equals("")) {
// store the status message in the session
if (sAction.equals("INS")) {
String sPublicID = this.getPublicID(sVD_ID);
vd.setVD_VD_ID(sPublicID);
this.storeStatusMsg("Public ID : " + vd.getVD_VD_ID());
this
.storeStatusMsg("\\t Successfully created New Value Domain");
} else if (sAction.equals("UPD") && sReturnCode != null
&& !sReturnCode.equals(""))
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update mandatory attributes.");
// store returncode in request to track it all through this
// request
if (sReturnCode != null && !sReturnCode.equals(""))
m_classReq.setAttribute("retcode", sReturnCode);
// create non evs parent concept in reference documents
// table
sReturn = this.setNonEVSParentConcept(vd);
// This writes the source of a Meta parent to Ref Docs
// sVDParent is string of con_idseqs for parent concepts
// if(sVDParent != null && !sVDParent.equals(""))
if (vd.getVD_PAR_CONDR_IDSEQ() != null
&& !vd.getVD_PAR_CONDR_IDSEQ().equals(""))
sReturn = this.setRDMetaConceptSource(vd);
// set create/modify attributes into bean
if (cstmt.getString(31) != null
&& !cstmt.getString(31).equals(""))
vd.setVD_CREATED_BY(getFullName(cstmt.getString(31)));
else
vd.setVD_CREATED_BY(oldVD.getVD_CREATED_BY());
if (cstmt.getString(32) != null
&& !cstmt.getString(32).equals(""))
vd.setVD_DATE_CREATED(m_util.getCurationDate(cstmt
.getString(32)));
else
vd.setVD_DATE_CREATED(oldVD.getVD_DATE_CREATED());
vd.setVD_MODIFIED_BY(getFullName(cstmt.getString(33)));
vd.setVD_DATE_MODIFIED(m_util.getCurationDate(cstmt
.getString(34)));
// insert the vd pv relationships in vd_pvs table if not
// block edit
if (!sOriginAction.equals("BlockEditVD")) {
if (vd.getVD_TYPE_FLAG().equals("E")
&& (pageVDType == null || pageVDType.equals("") || pageVDType
.equals("E"))) {
PVServlet pvser = new PVServlet(m_classReq,
m_classRes, m_servlet);
String sStat = pvser.submitPV(vd);
if (sStat != null && !sStat.equals(""))
this.storeStatusMsg(sStat);
Vector<PV_Bean> vPV = vd.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList");
// //vd.getVD_PV_NAME();
for (int j = 0; j < vPV.size(); j++) {
PV_Bean pv = (PV_Bean) vPV.elementAt(j);
VM_Bean vm = pv.getPV_VM();
if (vm != null && !vm.getVM_IDSEQ().equals("")) {
// System.out.println(vm.getVM_IDSEQ() + "
// vm alt name " + sContextID + " vd " +
// vd.getVD_VD_IDSEQ());
vm.save(session, m_servlet.getConn(), vm
.getVM_IDSEQ(), sContextID);
}
}
session.removeAttribute("AllAltNameList");
}
}
// reset the pv counts to reset more hyperlink
String pvName = "";
Integer pvCount = new Integer(0);
if (vd.getVD_TYPE_FLAG().equals("E")) {
Vector<PV_Bean> vPV = vd.getVD_PV_List(); // (Vector)session.getAttribute("VDPVList");
// //vd.getVD_PV_NAME();
if (vPV != null && vPV.size() > 0) {
PV_Bean pvBean = (PV_Bean) vPV.elementAt(0);
pvName = pvBean.getPV_VALUE();
pvCount = new Integer(vPV.size());
}
}
vd.setVD_Permissible_Value(pvName);
vd.setVD_Permissible_Value_Count(pvCount);
// do this for new version, to check whether we need to
// write to AC_HISTORIES table later
if (sInsertFor.equals("Version")) {
vd.setVD_DATE_CREATED(vd.getVD_DATE_MODIFIED());
vd.setVD_CREATED_BY(vd.getVD_MODIFIED_BY());
vd.setVD_VD_ID(oldVD.getVD_VD_ID()); // adds public
// id to the
// bean
}
// insert and delete ac-csi relationship
Vector vAC_CS = vd.getAC_AC_CSI_VECTOR();
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes,
m_servlet);
Vector vRemove_ACCSI = getAC.doCSCSI_ACSearch(sVD_ID, ""); // (Vector)session.getAttribute("vAC_CSI");
Vector vACID = (Vector) session.getAttribute("vACId");
this.addRemoveACCSI(sVD_ID, vAC_CS, vRemove_ACCSI, vACID,
sInsertFor, sLongName);
// store back altname and ref docs to session
m_servlet.doMarkACBeanForAltRef(m_classReq, m_classRes,
"ValueDomain", "all", "submitAR");
// do alternate names create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doAltVersionUpdate(sVD_ID, oldVD.getVD_VD_IDSEQ());
vd.save(session, m_servlet.getConn(), sVD_ID, sContextID);
session.removeAttribute("AllAltNameList");
/*
* Vector<ALT_NAME_Bean> tBean =
* AltNamesDefsSession.getAltNameBeans(session,
* AltNamesDefsSession._searchVD, sVD_ID, sContextID); if
* (tBean != null) DataManager.setAttribute(session,
* "AllAltNameList", tBean);
*/
String oneAlt = this.doAddRemoveAltNames(sVD_ID,
sContextID, sAction); // , "create");
vd.setALTERNATE_NAME(oneAlt);
// do reference docuemnts create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doRefVersionUpdate(sVD_ID, oldVD.getVD_VD_IDSEQ());
String oneRD = this.doAddRemoveRefDocs(sVD_ID, sContextID,
sAction); // "create");
vd.setREFERENCE_DOCUMENT(oneRD);
// do contact updates
Hashtable vdConts = vd.getAC_CONTACTS();
if (vdConts != null && vdConts.size() > 0)
vd.setAC_CONTACTS(this.addRemoveAC_Contacts(vdConts,
sVD_ID, sInsertFor));
// get one concept name for this vd
vd.setAC_CONCEPT_NAME(this.getOneConName("", sVD_ID));
// add success message if no error
sReturn = (String) m_classReq.getAttribute("retcode");
if (sAction.equals("UPD")
&& (sReturn == null || sReturn.equals("")))
this
.storeStatusMsg("\\t Successfully updated Value Domain.");
}
else if (sReturnCode != null && !sReturnCode.equals("")) {
this
.storeStatusMsg("\\t Unable to update the Short Name of the Value Domain.");
logger
.error(sReturnCode
+ " Unable to update the Short Name of the Value Domain.");
}
}
this.storeStatusMsg("\\n");
// capture the duration
// logger.info(m_servlet.getLogMessage(m_classReq, "setVD", "done
// set", startDate, new java.util.Date()));
} catch (Exception e) {
logger.error("ERROR in InsAerrorice-setVD for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update Value Domain attributes.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
}
/**
* The UpdateCRFValue method updates the quest contents table with the vp
* idseq. calls setQuestContent to update.
*
* @param pv
* PVid idseq of the permissible value
*/
public void UpdateCRFValue(PV_Bean pv) {
try {
HttpSession session = m_classReq.getSession();
String sMenuAction = (String) session
.getAttribute(Session_Data.SESSION_MENU_ACTION);
if (sMenuAction.equals("Questions")
&& pv.getVP_SUBMIT_ACTION().equals("INS")) {
// get the crf value vector to update
String sVVid = pv.getQUESTION_VALUE_IDSEQ();
String sVPid = pv.getPV_VDPVS_IDSEQ();
String ret = "";
if (sVPid != null && !sVPid.equals("") && sVVid != null
&& !sVVid.equals(""))
ret = setQuestContent(null, sVVid, sVPid);
}
} catch (RuntimeException e) {
logger.error("Error - " + e);
}
} // end of UpdateCRFValue
/**
* To insert a new DEConcept or update the existing one in the database
* after the validation. Called from CurationServlet. Gets all the attribute
* values from the bean, sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_DEC(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"
* to submit If no error occurs from query execute calls 'setDES' to store
* selected language in the database,
*
* @param sAction
* Insert or update Action.
* @param dec
* DEC Bean.
* @param sInsertFor
* for Versioning.
* @param oldDEC
* string dec idseq
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
public String setDEC(String sAction, DEC_Bean dec, String sInsertFor,
DEC_Bean oldDEC) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
// String v_ac = "";
String oldDECID = "";
// String oldContext = "";
// String oldName = "";
// String oldContextID = "";
String oldAslName = "";
String oldSource = "";
String oldEndDate = "";
String oldBeginDate = "";
String oldChangeNote = "";
try {
m_classReq.setAttribute("retcode", ""); // empty retcode to track
// returncodes
String sInsFor = sInsertFor;
if (sInsFor.equals("BlockVersion"))
sInsertFor = "Version";
// add the dec name into the message
if (sAction.equals("INS"))
this.storeStatusMsg("Data Element Concept Name : "
+ dec.getDEC_LONG_NAME());
// store versioned status message
if (sInsertFor.equals("Version"))
this.storeStatusMsg("\\t Created new version successfully.");
if (oldDEC == null)
oldDEC = new DEC_Bean();
String sName = dec.getDEC_PREFERRED_NAME();
String sContextID = dec.getDEC_CONTE_IDSEQ();
String sContext = dec.getDEC_CONTEXT_NAME();
Double DVersion = new Double(dec.getDEC_VERSION());
double dVersion = DVersion.doubleValue();
String sDefinition = dec.getDEC_PREFERRED_DEFINITION();
String sCD_ID = dec.getDEC_CD_IDSEQ();
String sLongName = dec.getDEC_LONG_NAME();
String sBeginDate = m_util.getOracleDate(dec.getDEC_BEGIN_DATE());
String sEndDate = m_util.getOracleDate(dec.getDEC_END_DATE());
// String sLanguage = dec.getDEC_LANGUAGE();
String sSource = dec.getDEC_SOURCE();
String sDEC_ID = dec.getDEC_DEC_IDSEQ();
String sChangeNote = dec.getDEC_CHANGE_NOTE();
// check if it is valid oc/prop for block dec at submit
boolean bValidOC_PROP = true;
if (sInsFor.equals("BlockEdit") || sInsFor.equals("BlockVersion")) {
// do the oc prop pair checking only if they exist
if ((dec.getDEC_OC_CONDR_IDSEQ() == null || dec
.getDEC_OC_CONDR_IDSEQ().equals(""))
&& (dec.getDEC_PROP_CONDR_IDSEQ() == null || dec
.getDEC_PROP_CONDR_IDSEQ().equals(""))) {
// display message if sys or abbr was selected for non oc
// prop dec.
if (dec.getAC_PREF_NAME_TYPE() != null
&& (dec.getAC_PREF_NAME_TYPE().equals("SYS") || dec
.getAC_PREF_NAME_TYPE().equals("ABBR"))) {
this
.storeStatusMsg("\\t Unable to change the Short Name type to System Generated or Abbreviated"
+ "\\n\\t\\t because Object Class and Property do not exist.");
bValidOC_PROP = false;
}
} else {
// SetACService setAC = new SetACService(m_servlet);
// String validOCProp = setAC.checkUniqueOCPropPair(dec,
// m_classReq, m_classRes, "EditDEC");
String validOCProp = this.checkUniqueOCPropPair(dec,
"Unique", "EditDEC");
if (validOCProp != null && !validOCProp.equals("")
&& validOCProp.indexOf("Warning") < 0) {
bValidOC_PROP = false;
this.storeStatusMsg("\\t " + validOCProp); // append
// the
// message
// reset back to old one
dec.setDEC_OC_CONDR_IDSEQ(oldDEC
.getDEC_OC_CONDR_IDSEQ());
dec.setDEC_OCL_IDSEQ(oldDEC.getDEC_OCL_IDSEQ());
dec.setDEC_PROP_CONDR_IDSEQ(oldDEC
.getDEC_PROP_CONDR_IDSEQ());
dec.setDEC_PROPL_IDSEQ(oldDEC.getDEC_PROPL_IDSEQ());
}
}
}
String sOCID = "";
String sPropL = "";
// get the system generated name for DEC from OC and Prop if oc-prop
// combination is valid
if (bValidOC_PROP == true) {
// need to send in ids not names
String sOldOCName = "";
String sOCName = "";
if (dec.getDEC_OCL_NAME() != null)
sOCName = dec.getDEC_OCL_NAME();
if (oldDEC != null)
sOldOCName = oldDEC.getDEC_OCL_NAME();
if ((sOCName == null || sOCName.equals(""))
&& sAction.equals("UPD") && !sOCName.equals(sOldOCName)) {
sOCID = " ";
dec.setDEC_OCL_IDSEQ("");
} else
sOCID = dec.getDEC_OCL_IDSEQ();
String sOldPropName = "";
String sPropName = "";
if (dec.getDEC_PROPL_NAME() != null)
sPropName = dec.getDEC_PROPL_NAME();
if (oldDEC != null)
sOldPropName = oldDEC.getDEC_PROPL_NAME();
if ((sPropName == null || sPropName.equals(""))
&& sAction.equals("UPD")
&& !sPropName.equals(sOldPropName)) {
sPropL = " ";
dec.setDEC_PROPL_IDSEQ("");
} else
sPropL = dec.getDEC_PROPL_IDSEQ();
// make condr idseq's empty if oc or prop idseqs are emtpy
if (dec.getDEC_OCL_IDSEQ() == null
|| dec.getDEC_OCL_IDSEQ().equals(""))
dec.setDEC_OC_CONDR_IDSEQ("");
if (dec.getDEC_PROPL_IDSEQ() == null
|| dec.getDEC_PROPL_IDSEQ().equals(""))
dec.setDEC_PROP_CONDR_IDSEQ("");
// get the valid preferred name
DEC_Bean vDEC = this.changeDECPrefName(dec, oldDEC, sInsertFor,
sAction);
if (vDEC == null)
return "Unique Constraint";
else
dec = vDEC;
sName = dec.getDEC_PREFERRED_NAME(); // update submit
// variable
}
// get the old attributes from the oldbean
if (oldDEC != null && !oldDEC.equals("")) {
oldDECID = oldDEC.getDEC_DEC_IDSEQ();
// oldContext = oldDEC.getDEC_CONTEXT_NAME();
// oldName = oldDEC.getDEC_PREFERRED_NAME();
// oldContextID = oldDEC.getDEC_CONTE_IDSEQ();
oldAslName = oldDEC.getDEC_ASL_NAME();
}
if (oldDEC != null)
oldSource = oldDEC.getDEC_SOURCE();
if (oldSource == null)
oldSource = "";
if (sSource == null)
sSource = "";
if ((sSource == null || sSource.equals(""))
&& sAction.equals("UPD") && !sSource.equals(oldSource))
sSource = " ";
if (oldDEC != null)
oldChangeNote = oldDEC.getDEC_CHANGE_NOTE();
if (oldChangeNote == null)
oldChangeNote = "";
if (sChangeNote == null)
sChangeNote = "";
if ((sChangeNote == null || sChangeNote.equals(""))
&& sAction.equals("UPD")
&& !sChangeNote.equals(oldChangeNote))
sChangeNote = " ";
// pass empty string if changed to null
sBeginDate = dec.getDEC_BEGIN_DATE();
if (oldDEC != null)
oldBeginDate = oldDEC.getDEC_BEGIN_DATE();
if (oldBeginDate == null)
oldBeginDate = "";
if (sBeginDate == null)
sBeginDate = "";
if ((sBeginDate == null || sBeginDate.equals(""))
&& sAction.equals("UPD")
&& !sBeginDate.equals(oldBeginDate))
sBeginDate = " ";
else
sBeginDate = m_util.getOracleDate(dec.getDEC_BEGIN_DATE());
sEndDate = dec.getDEC_END_DATE();
if (oldDEC != null)
oldEndDate = oldDEC.getDEC_END_DATE();
if (oldEndDate == null)
oldEndDate = "";
if (sEndDate == null)
sEndDate = "";
if ((sEndDate == null || sEndDate.equals(""))
&& sAction.equals("UPD") && !sEndDate.equals(oldEndDate))
sEndDate = " ";
else
sEndDate = m_util.getOracleDate(dec.getDEC_END_DATE());
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_DEC(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_DEC(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
// cstmt.registerOutParameter(1,
// java.sql.Types.VARCHAR);//ua_name
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // dec
// vd ID
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // preferred
// name
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // context
cstmt.registerOutParameter(7, java.sql.Types.DECIMAL); // version
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // preferred
// definition
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // cd id
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // asl
// name
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // latest
// version
// ind
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // long
// name
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // OCL
// name
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // PROPL
// Name
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // PROPERTY
// QUALIFIER
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // OBJ
// CLASS
// QUALIFIER
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // begin
// date
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // end
// date
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // change
// note
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // created
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); // modified
cstmt.registerOutParameter(23, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(24, java.sql.Types.VARCHAR); // deleted
// ind
cstmt.registerOutParameter(25, java.sql.Types.VARCHAR); // origin
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(3, sAction); // ACTION - INS, UPD or DEL
if ((sAction.equals("UPD")) || (sAction.equals("DEL"))) {
sDEC_ID = dec.getDEC_DEC_IDSEQ();
cstmt.setString(4, sDEC_ID);
}
// only for editing released elements
if (sAction.equals("UPD") && oldAslName.equals("RELEASED")
&& !sInsertFor.equals("Version")) {
cstmt.setString(6, null); // context id - not null for
// INS, must be null for UPD
cstmt.setString(5, null); // preferred name - not null for
// INS, must be null for UPD
} else // INS case
{
cstmt.setString(6, sContextID); // context id - not null for
// INS, must be null for UPD
cstmt.setString(5, sName); // preferred name - not null for
// INS, must be null for UPD
}
cstmt.setDouble(7, dVersion); // version - test says must have
// a value
cstmt.setString(8, sDefinition); // preferred definition -
// not null for INS
cstmt.setString(9, sCD_ID); // cd id - not null for INS
cstmt.setString(10, dec.getDEC_ASL_NAME()); // workflow status
if (sAction.equals("INS"))
cstmt.setString(11, "Yes");
cstmt.setString(12, sLongName); // long name - can be null
cstmt.setString(13, sOCID); // OCL id
cstmt.setString(14, sPropL); // PROPL id
cstmt.setString(15, null); // OC Qualifier name
cstmt.setString(16, null); // Property qualifier name
cstmt.setString(17, sBeginDate); // sBeginDate - can be null
cstmt.setString(18, sEndDate); // sEndDate - can be null
cstmt.setString(19, sChangeNote);
cstmt.setString(25, sSource);
// Now we are ready to call the stored procedure
cstmt.execute();
// capture the duration
// logger.info(m_servlet.getLogMessage(m_classReq, "setDEC",
// "execute done", startDate, new java.util.Date()));
sDEC_ID = cstmt.getString(4);
dec.setDEC_DEC_IDSEQ(sDEC_ID);
sReturnCode = cstmt.getString(2);
// m_servlet.clearBuildingBlockSessionAttributes(m_classReq,
// m_classRes);
// String sOriginAction =
// (String)session.getAttribute("originAction");
if (sReturnCode == null || sReturnCode.equals("")) // (!sOriginAction.equals("BlockEditDEC"))
{
m_servlet.clearBuildingBlockSessionAttributes(m_classReq,
m_classRes);
dec.setDEC_OC_QUALIFIER_NAMES(null);
dec.setDEC_OC_QUALIFIER_CODES(null);
dec.setDEC_OC_QUALIFIER_DB(null);
dec.setDEC_PROP_QUALIFIER_NAMES(null);
dec.setDEC_PROP_QUALIFIER_CODES(null);
dec.setDEC_PROP_QUALIFIER_DB(null);
}
// insert newly created row into hold vector
if (sReturnCode != null && sAction.equals("INS"))
this
.storeStatusMsg("\\t "
+ sReturnCode
+ " : Unable to create new Data Element Concept Successfully.");
else if ((sReturnCode == null || (sReturnCode != null && sAction
.equals("UPD")))
&& !sDEC_ID.equals("")) {
// store the status message in the session
if (sAction.equals("INS")) {
String sPublicID = this.getPublicID(sDEC_ID);
dec.setDEC_DEC_ID(sPublicID);
this.storeStatusMsg("Public ID : "
+ dec.getDEC_DEC_ID());
this
.storeStatusMsg("\\t Successfully created New Data Element Concept.");
} else if (sAction.equals("UPD") && sReturnCode != null
&& !sReturnCode.equals(""))
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update mandatory attributes.");
// store returncode in request to track it all through this
// request
if (sReturnCode != null && !sReturnCode.equals(""))
m_classReq.setAttribute("retcode", sReturnCode);
// set create/modify attributes into bean
if (cstmt.getString(20) != null
&& !cstmt.getString(20).equals(""))
dec.setDEC_CREATED_BY(getFullName(cstmt.getString(20)));
else
dec.setDEC_CREATED_BY(oldDEC.getDEC_CREATED_BY());
if (cstmt.getString(21) != null
&& !cstmt.getString(21).equals(""))
dec.setDEC_DATE_CREATED(m_util.getCurationDate(cstmt
.getString(21)));
else
dec.setDEC_DATE_CREATED(oldDEC.getDEC_DATE_CREATED());
dec.setDEC_MODIFIED_BY(getFullName(cstmt.getString(22)));
dec.setDEC_DATE_MODIFIED(m_util.getCurationDate(cstmt
.getString(23)));
// do this for new version, to check whether we need to
// write to AC_HISTORIES table later
if (sInsertFor.equals("Version")) {
// created and modifed are same if veriosing
dec.setDEC_CREATED_BY(dec.getDEC_MODIFIED_BY());
dec.setDEC_DATE_CREATED(dec.getDEC_DATE_MODIFIED());
dec.setDEC_DEC_ID(oldDEC.getDEC_DEC_ID()); // get the
// oldpublic
}
String sReturn = "";
// insert and delete ac-csi relationship
Vector<AC_CSI_Bean> vAC_CS = dec.getAC_AC_CSI_VECTOR();
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes,
m_servlet);
Vector<AC_CSI_Bean> vRemove_ACCSI = getAC.doCSCSI_ACSearch(
sDEC_ID, ""); // (Vector)session.getAttribute("vAC_CSI");
Vector vACID = (Vector) session.getAttribute("vACId");
this.addRemoveACCSI(sDEC_ID, vAC_CS, vRemove_ACCSI, vACID,
sInsertFor, sLongName);
// store back altname and ref docs to session
m_servlet.doMarkACBeanForAltRef(m_classReq, m_classRes,
"DataElementConcept", "all", "submitAR");
// do alternate names create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doAltVersionUpdate(sDEC_ID, oldDECID);
dec.save(session, m_servlet.getConn(), sDEC_ID, sContextID);
session.removeAttribute("AllAltNameList");
/*
* Vector<ALT_NAME_Bean> tBean =
* AltNamesDefsSession.getAltNameBeans(session,
* AltNamesDefsSession._searchDEC, sDEC_ID, sContextID); if
* (tBean != null) DataManager.setAttribute(session,
* "AllAltNameList", tBean);
*/
String oneAlt = this.doAddRemoveAltNames(sDEC_ID,
sContextID, sAction); // , "create");
dec.setALTERNATE_NAME(oneAlt);
// do reference docuemnts create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doRefVersionUpdate(sDEC_ID, oldDECID);
String oneRD = this.doAddRemoveRefDocs(sDEC_ID, sContextID,
sAction); // "create");
dec.setREFERENCE_DOCUMENT(oneRD);
// do contact updates
Hashtable<String, AC_CONTACT_Bean> decConts = dec
.getAC_CONTACTS();
if (decConts != null && decConts.size() > 0)
dec.setAC_CONTACTS(this.addRemoveAC_Contacts(decConts,
sDEC_ID, sInsertFor));
// get one concept name for this dec
dec.setAC_CONCEPT_NAME(this.getOneConName(sDEC_ID, ""));
sReturn = (String) m_classReq.getAttribute("retcode");
if (sAction.equals("UPD")
&& (sReturn == null || sReturn.equals("")))
this
.storeStatusMsg("\\t Successfully updated Data Element Concept.");
}
}
this.storeStatusMsg("\\n");
// capture the duration
// logger.info(m_servlet.getLogMessage(m_classReq, "setDEC", "end
// set", startDate, new java.util.Date()));
} catch (Exception e) {
logger.error("ERROR in InsACService-setDEC for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update Data Element Concept attributes.");
}
finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
}
private DEC_Bean changeDECPrefName(DEC_Bean dec, DEC_Bean oldDEC,
String sInsFor, String sAction) throws Exception {
EVSSearch evs = new EVSSearch(m_classReq, m_classRes, m_servlet);
String sName = dec.getDEC_PREFERRED_NAME();
if (sName == null)
sName = "";
String sNameType = dec.getAC_PREF_NAME_TYPE();
if (sNameType == null)
sNameType = "";
String oldAslName = oldDEC.getDEC_ASL_NAME();
if (oldAslName == null)
oldAslName = "";
// display messge if released dec
if (oldAslName.equals("RELEASED") && sInsFor.equals("BlockEdit")
&& !sNameType.equals("") && !sNameType.equals("USER")) {
this
.storeStatusMsg("\\t Short Name of the RELEASED Data Element Concept cannot be changed.");
return dec;
}
// get teh right sys name
String curType = "existing";
if (sNameType.equals("SYS")) {
curType = "system generated";
String sysName = this.getDECSysName(dec);
if (sysName == null)
sysName = "";
dec.setAC_SYS_PREF_NAME(sysName);
dec.setDEC_PREFERRED_NAME(sysName);
}
// abbreviated type
if (sNameType.equals("ABBR")) {
curType = "abbreviated";
// get abbr name for block edit or version
if (sInsFor.equals("BlockEdit")
|| (sAction.equals("UPD") && sInsFor.equals("Version"))) {
// GetACSearch serAC = new GetACSearch(m_classReq, m_classRes,
// m_servlet);
if (dec.getDEC_OC_CONDR_IDSEQ() != null
&& !dec.getDEC_OC_CONDR_IDSEQ().equals(""))
evs
.fillOCVectors(dec.getDEC_OC_CONDR_IDSEQ(), dec,
sAction);
if (dec.getDEC_PROP_CONDR_IDSEQ() != null
&& !dec.getDEC_PROP_CONDR_IDSEQ().equals(""))
evs.fillPropVectors(dec.getDEC_PROP_CONDR_IDSEQ(), dec,
sAction);
EVS_Bean nullEVS = null;
dec = (DEC_Bean) m_servlet.getACNames(nullEVS, "SubmitDEC", dec);
dec.setDEC_PREFERRED_NAME(dec.getAC_ABBR_PREF_NAME());
}
}
SetACService setAC = new SetACService(m_servlet);
GetACService getAC = new GetACService(m_classReq, m_classRes, m_servlet);
String sDECAction = "create";
if (sAction.equals("UPD"))
sDECAction = "Edit";
String sValid = setAC.checkUniqueInContext("Name", "DEC", null, dec,
null, getAC, sDECAction);
if (sValid != null && !sValid.equals("")) {
if (sAction.equals("UPD"))
sDECAction = "update";
String sMsg = "\\tUnable to " + sDECAction
+ " this Data Element Concept because the " + curType
+ "\\n\\t" + "Short Name " + dec.getDEC_PREFERRED_NAME()
+ " already exists in the database for this "
+ "Context and Version.";
// add moreMsg and return with error for create new dec
if (!sAction.equals("UPD")) {
String sMoreMsg = "\\n\\tClick OK to return to the Data Element Concept screen "
+ "to " + sDECAction + " a unique Short Name.";
this.storeStatusMsg(sMsg + sMoreMsg);
// return "Unique Constraint";
return null;
} else // reset pref name back to earlier name and continue with
// other submissions for upd dec
{
dec.setDEC_PREFERRED_NAME(sName); // back to the old name
this.storeStatusMsg(sMsg);
}
}
return dec;
}
/**
* to add or remove cs-csi relationship for the selected AC. Called from
* setDE, setVD, setDEC.
*
* @param ac_id
* string ac_idseq.
* @param vAC_CS
* vector of cs csi contained in the selected ac.
* @param vRemove_ACCSI
* vector of selected ac-csi.
* @param vACID
* @param acAction
* @param acName
* @throws Exception
*
*/
public void addRemoveACCSI(String ac_id, Vector<AC_CSI_Bean> vAC_CS,
Vector<AC_CSI_Bean> vRemove_ACCSI, Vector vACID, String acAction,
String acName) throws Exception {
Vector<String> vExistACCSI = new Vector<String>();
Vector<String> vExistCSCSI = new Vector<String>();
if (vAC_CS != null) // accsi list from the page for the selected cs-csi
// includes new or existing ones
{
for (int i = 0; i < vAC_CS.size(); i++) {
AC_CSI_Bean acCSI = (AC_CSI_Bean) vAC_CS.elementAt(i);
CSI_Bean csiBean = (CSI_Bean) acCSI.getCSI_BEAN();
// insert this relationship if it does not exist already
String accsiID = acCSI.getAC_CSI_IDSEQ();
String accsiName = csiBean.getCSI_NAME(); // acCSI.getCSI_NAME();
vExistCSCSI.addElement(csiBean.getCSI_CSCSI_IDSEQ());
// vExistCSCSI.addElement(acCSI.getCSCSI_IDSEQ());
if ((acName == null || acName.equals("") || acName
.equals("null"))
&& acCSI.getAC_IDSEQ().equals(ac_id))
acName = acCSI.getAC_LONG_NAME();
if (acCSI.getAC_CSI_IDSEQ() == null
|| acCSI.getAC_CSI_IDSEQ().equals("") || acCSI.getAC_CSI_IDSEQ().equals("undefined"))
accsiID = setACCSI(csiBean.getCSI_CSCSI_IDSEQ(), "INS",
ac_id, "", acName, accsiName);
// insert it if ac of the old one doesn't match new ac
else if (vACID != null && !vACID.contains(ac_id)
&& !acAction.equals("Version")) {
accsiID = setACCSI(csiBean.getCSI_CSCSI_IDSEQ(), "INS",
ac_id, "", acName, accsiName);
vExistACCSI.addElement(accsiID); // add this to not to
// remove
} else
vExistACCSI.addElement(accsiID); // add to the vector to
// use at remove
}
}
// remove ac-csi relationship
if (vRemove_ACCSI != null) // list from origial search does not include
// new ones
{
for (int j = 0; j < vRemove_ACCSI.size(); j++) {
AC_CSI_Bean acCSI = (AC_CSI_Bean) vRemove_ACCSI.elementAt(j);
CSI_Bean csiBean = (CSI_Bean) acCSI.getCSI_BEAN();
String accsiName = csiBean.getCSI_NAME(); // acCSI.getCSI_NAME();
// delete this relationship if it does not contain in the
// insert/update vector (vAC_CS)
// if ac is not same as this one and it doesn't exist in
// ExistACCCI (retained from the page)
if (acCSI.getAC_CSI_IDSEQ() != null
&& acCSI.getAC_IDSEQ().equals(ac_id)
&& (vExistACCSI == null || !vExistACCSI.contains(acCSI
.getAC_CSI_IDSEQ()))) {
if (vExistCSCSI == null
|| !vExistCSCSI.contains(csiBean
.getCSI_CSCSI_IDSEQ())) {
setACCSI(csiBean.getCSI_CSCSI_IDSEQ(), "DEL", ac_id,
acCSI.getAC_CSI_IDSEQ(), acName, accsiName);
}
}
}
}
} // end addRemoveCSCSI
/**
*
* @param sCondrString
* string condr idseq
*
* @return sCondrString
*/
public String prepCondrStringForSubmit(String sCondrString) {
if (sCondrString.length() < 1)
return "";
int index = -1;
String sComma = ",";
Vector<String> vTokens = new Vector<String>();
String sCondrStringSecondary = "";
String sNewSecondaryString = "";
String sPrimary = "";
index = sCondrString.indexOf(sComma);
if (index > -1) {
sPrimary = sCondrString.substring(0, index);
sCondrStringSecondary = sCondrString.substring(index, sCondrString
.length());
sCondrString = sPrimary;
if ((sCondrStringSecondary != null)
&& (!sCondrStringSecondary.equals(""))) {
StringTokenizer desTokens = new StringTokenizer(
sCondrStringSecondary, ",");
while (desTokens.hasMoreTokens()) {
String thisToken = desTokens.nextToken().trim();
if (thisToken != null && !thisToken.equals("")) {
vTokens.addElement(thisToken);
}
}
for (int i = (vTokens.size() - 1); i > -1; i
sNewSecondaryString = (String) vTokens.elementAt(i);
sCondrString = sCondrString + "," + sNewSecondaryString;
}
}
}
return sCondrString;
}
/**
* To insert a Object Class or update the existing one in the database after
* the validation. Called from CurationServlet. Gets all the attribute
* values from the bean, sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_OBJECT_CLASS(?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param dec
* DEC Bean.
* @param req
* HttpServletRequest Object.
*
* @return DEC_Bean return bean updated with change attributes.
*/
public DEC_Bean setObjectClassDEC(String sAction, DEC_Bean dec,
HttpServletRequest req) {
HttpSession session = m_classReq.getSession();
ResultSet rs = null;
CallableStatement cstmt = null;
String sReturnCode = "";
String sOCL_IDSEQ = "";
try {
// String sOCLName = "";
String sContextID = "";
if (dec != null) {
sContextID = dec.getDEC_CONTE_IDSEQ();
if (sContextID == null)
sContextID = "";
}
// create concepts and pass them in comma-delimited format
Vector vObjectClass = (Vector) session.getAttribute("vObjectClass");
if (vObjectClass == null)
vObjectClass = new Vector();
String sOCCondr = "";
String sOCCondrString = "";
for (int m = 1; m < vObjectClass.size(); m++) {
EVS_Bean OCBean = (EVS_Bean) vObjectClass.elementAt(m);
if (OCBean.getCON_AC_SUBMIT_ACTION() == null)
OCBean.setCON_AC_SUBMIT_ACTION("");
// if not deleted, create and append them one by one
if (OCBean != null) {
if (!OCBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
String sRet = "";
String conIDseq = OCBean.getIDSEQ();
// create it only if doesn't exist
if (conIDseq == null || conIDseq.equals(""))
conIDseq = this.setConcept("INS", sRet, OCBean);
if (conIDseq != null && !conIDseq.equals("")) {
// add the concept value to the conidseq
String nvp = OCBean.getNVP_CONCEPT_VALUE();
if (nvp != null && !nvp.equals(""))
conIDseq += ":" + nvp;
if (sOCCondrString.equals(""))
sOCCondrString = conIDseq;
else
sOCCondrString = sOCCondrString + ","
+ conIDseq;
}
} else if (sOCCondr == null)
sOCCondr = OCBean.getCONDR_IDSEQ();
}
}
// Primary
EVS_Bean OCBean = new EVS_Bean();
if (vObjectClass.size() > 0)
OCBean = (EVS_Bean) vObjectClass.elementAt(0);
if (OCBean != null && OCBean.getLONG_NAME() != null) {
if (sContextID == null || sContextID.equals(""))
sContextID = OCBean.getCONTE_IDSEQ();
if (sContextID == null)
sContextID = "";
if (OCBean.getCON_AC_SUBMIT_ACTION() == null)
OCBean.setCON_AC_SUBMIT_ACTION("");
if (!OCBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
String sRet = "";
String conIDseq = OCBean.getIDSEQ();
// create it only if doesn't exist
if (conIDseq == null || conIDseq.equals(""))
conIDseq = this.setConcept("INS", sRet, OCBean);
if (conIDseq != null && !conIDseq.equals("")) {
if (sOCCondrString.equals(""))
sOCCondrString = conIDseq;
else
sOCCondrString = sOCCondrString + "," + conIDseq;
}
}
}
if (sOCCondr == null)
sOCCondr = "";
if (sContextID == null)
sContextID = "";
if (!sOCCondrString.equals("")) {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_OC_CONDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_OC_CONDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
// cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); //
// ua_name
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // OCL
// IDSEQ
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // preferred_name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // long_name
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // preferred_definition
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // version
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // asl_name
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // latest_version_ind
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // change_note
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // origin
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // definition_source
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // begin_date
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // end_date
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // date_created
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // created_by
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // date_modified
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // modified_by
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // deleted_ind
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); // oc_condr_idseq
cstmt.registerOutParameter(23, java.sql.Types.VARCHAR); // oc_id
//System.out.println(OCBean.getLONG_NAME()
//+ " oc submit ready " + sOCCondrString);
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(2, sOCCondrString); // comma-delimited con
// idseqs
cstmt.setString(3, sContextID);
cstmt.execute();
sReturnCode = cstmt.getString(4);
sOCL_IDSEQ = cstmt.getString(5);
if (sOCL_IDSEQ == null)
sOCL_IDSEQ = "";
String sOCL_CONDR_IDSEQ = cstmt.getString(22);
if (sOCL_CONDR_IDSEQ == null)
sOCL_CONDR_IDSEQ = "";
// DataManager.setAttribute(session, "newObjectClass", "");
// store the idseq in the bean
if (dec != null
&& (sReturnCode == null || sReturnCode.equals("") || sReturnCode
.equals("API_OC_500"))) {
dec.setDEC_OCL_IDSEQ(sOCL_IDSEQ);
dec.setDEC_OC_CONDR_IDSEQ(sOCL_CONDR_IDSEQ);
dec.setDEC_OBJ_ASL_NAME(cstmt.getString(10));
req.setAttribute("OCL_IDSEQ", sOCL_IDSEQ);
}
if (sReturnCode != null && !sReturnCode.equals(""))
// !sReturnCode.equals("API_OC_500"))
{
sReturnCode = sReturnCode.replaceAll("\\n", " ");
sReturnCode = sReturnCode.replaceAll("\\t", " ");
sReturnCode = sReturnCode.replaceAll("\"", "");
this.storeStatusMsg(sReturnCode
+ " : Unable to create Object Class ");
m_classReq.setAttribute("retcode", sReturnCode);
dec.setDEC_OCL_IDSEQ("");
}
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setObjectClassDEC for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("Exception Error : Unable to create Object Class.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return dec;
}
/**
* To insert a Property Class or update the existing one in the database
* after the validation. Called from CurationServlet. Gets all the attribute
* values from the bean, sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_PROP_CONDR(?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param dec
* DEC Bean.
* @param req
* HttpServletRequest Object.
*
* @return DEC_Bean return bean updated with change attributes.
*/
public DEC_Bean setPropertyDEC(String sAction, DEC_Bean dec,
HttpServletRequest req) {
// capture the duration
// java.util.Date startDate = new java.util.Date();
// logger.info(m_servlet.getLogMessage(m_classReq, "setPropertyDEC",
// "starting set", startDate, startDate));
HttpSession session = req.getSession();
// Connection conn = null;
ResultSet rs = null;
CallableStatement cstmt = null;
String sReturnCode = "";
String sPROPL_IDSEQ = "";
try {
String sContextID = "";
if (dec != null)
sContextID = dec.getDEC_CONTE_IDSEQ();
if (sContextID == null)
sContextID = "";
// create concepts and pass them in comma-delimited format
Vector vProperty = (Vector) session.getAttribute("vProperty");
if (vProperty == null)
vProperty = new Vector();
String sPCCondr = "";
String sPCCondrString = "";
for (int m = 1; m < vProperty.size(); m++) {
EVS_Bean PCBean = (EVS_Bean) vProperty.elementAt(m);
if (PCBean.getCON_AC_SUBMIT_ACTION() == null)
PCBean.setCON_AC_SUBMIT_ACTION("");
// if not deleted, create and append them one by one
if (PCBean != null) {
if (!PCBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
String sRet = "";
String conIDseq = PCBean.getIDSEQ();
// create it only if doesn't exist
if (conIDseq == null || conIDseq.equals(""))
conIDseq = this.setConcept("INS", sRet, PCBean);
if (conIDseq != null && !conIDseq.equals("")) {
// add the concept value to the conidseq
String nvp = PCBean.getNVP_CONCEPT_VALUE();
if (nvp != null && !nvp.equals(""))
conIDseq += ":" + nvp;
if (sPCCondrString.equals(""))
sPCCondrString = conIDseq;
else
sPCCondrString = sPCCondrString + ","
+ conIDseq;
}
} else if (sPCCondr == null)
sPCCondr = PCBean.getCONDR_IDSEQ();
}
}
// Primary
EVS_Bean PCBean = new EVS_Bean();
if (vProperty.size() > 0)
PCBean = (EVS_Bean) vProperty.elementAt(0);
if (PCBean != null && PCBean.getLONG_NAME() != null) {
if (sContextID == null || sContextID.equals(""))
sContextID = PCBean.getCONTE_IDSEQ();
if (sContextID == null)
sContextID = "";
if (PCBean.getCON_AC_SUBMIT_ACTION() == null)
PCBean.setCON_AC_SUBMIT_ACTION("");
if (!PCBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
String sRet = "";
String conIDseq = PCBean.getIDSEQ();
// create it only if doesn't exist
if (conIDseq == null || conIDseq.equals(""))
conIDseq = this.setConcept("INS", sRet, PCBean);
if (conIDseq != null && !conIDseq.equals("")) {
if (sPCCondrString.equals(""))
sPCCondrString = conIDseq;
else
sPCCondrString = sPCCondrString + "," + conIDseq;
}
}
}
if (sPCCondr == null)
sPCCondr = "";
if (sContextID == null)
sContextID = "";
if (!sPCCondrString.equals("")) {
// conn = m_servlet.connectDB(m_classReq, m_classRes);
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_PROP_CONDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_PROP_CONDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
// cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); //
// ua_name
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // PROP_IDSEQ
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // preferred_name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // long_name
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // preferred_definition
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // version
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // asl_name
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // latest_version_ind
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // change_note
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // origin
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // definition_source
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // begin_date
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // end_date
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // date_created
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // created_by
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // date_modified
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // modified_by
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // deleted_ind
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); // prop_condr_idseq
cstmt.registerOutParameter(23, java.sql.Types.VARCHAR); // prop_id
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(2, sPCCondrString); // comma-delimited con
// idseqs
cstmt.setString(3, sContextID);
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(4);
sPROPL_IDSEQ = cstmt.getString(5);
if (sPROPL_IDSEQ == null)
sPROPL_IDSEQ = "";
String sPROPL_CONDR_IDSEQ = cstmt.getString(22);
if (sPROPL_CONDR_IDSEQ == null)
sPROPL_CONDR_IDSEQ = "";
if (dec != null
&& (sReturnCode == null || sReturnCode.equals("") || sReturnCode
.equals("API_PROP_500"))) {
dec.setDEC_PROPL_IDSEQ(sPROPL_IDSEQ);
dec.setDEC_PROP_CONDR_IDSEQ(sPROPL_CONDR_IDSEQ);
dec.setDEC_PROP_ASL_NAME(cstmt.getString(10));
req.setAttribute("PROPL_IDSEQ", sPROPL_IDSEQ);
}
// DataManager.setAttribute(session, "newProperty", "");
if (sReturnCode != null && !sReturnCode.equals(""))
// !sReturnCode.equals("API_PROP_500"))
{
this.storeStatusMsg(sReturnCode
+ " : Unable to create Property ");
m_classReq.setAttribute("retcode", sReturnCode);
dec.setDEC_PROPL_IDSEQ("");
}
}
}
} catch (Exception e) {
logger.error(
"ERROR in InsACService-setPropertyClassDEC for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this.storeStatusMsg("Exception Error : Unable to create Property.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return dec;
}
/**
* To insert a Representation Term or update the existing one in the
* database after the validation. Called from CurationServlet. Gets all the
* attribute values from the bean, sets in parameters, and registers output
* parameter. Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_representation(?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param sREP_IDSEQ
* string rep idseq
* @param VD
* VD Bean.
* @param rep
* rep bean
* @param req
* HttpServletRequest Object.
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
public String setRepresentation(String sAction, String sREP_IDSEQ, // out
VD_Bean VD, EVS_Bean rep, HttpServletRequest req) {
HttpSession session = m_classReq.getSession();
ResultSet rs = null;
CallableStatement cstmt = null;
String sReturnCode = "";
try {
String sREPName = "";
String sContextID = "";
if (VD != null) {
sContextID = VD.getVD_CONTE_IDSEQ();
if (sContextID == null)
sContextID = "";
}
// get the existing property if alreay there
// create concepts and pass them in comma-delimited format
Vector vRepTerm = (Vector) session.getAttribute("vRepTerm");
if (vRepTerm == null)
vRepTerm = new Vector();
String sOCCondr = "";
String sOCCondrString = "";
for (int m = 1; m < vRepTerm.size(); m++) {
EVS_Bean REPBean = (EVS_Bean) vRepTerm.elementAt(m);
if (REPBean.getCON_AC_SUBMIT_ACTION() == null)
REPBean.setCON_AC_SUBMIT_ACTION("");
// if not deleted, create and append them one by one
if (REPBean != null) {
if (!REPBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
String sRet = "";
String conIDseq = REPBean.getIDSEQ();
// create it only if doesn't exist
if (conIDseq == null || conIDseq.equals(""))
conIDseq = this.setConcept("INS", sRet, REPBean);
if (conIDseq != null && !conIDseq.equals("")) {
// add the concept value to the conidseq
String nvp = REPBean.getNVP_CONCEPT_VALUE();
if (nvp != null && !nvp.equals(""))
conIDseq += ":" + nvp;
if (sOCCondrString.equals(""))
sOCCondrString = conIDseq;
else
sOCCondrString = sOCCondrString + ","
+ conIDseq;
}
} else if (sOCCondr == null)
sOCCondr = REPBean.getCONDR_IDSEQ();
}
}
// Primary
EVS_Bean REPBean = (EVS_Bean) vRepTerm.elementAt(0);
if (REPBean != null && REPBean.getLONG_NAME() != null) {
if (sContextID == null || sContextID.equals(""))
sContextID = REPBean.getCONTE_IDSEQ();
if (sContextID == null)
sContextID = "";
if (REPBean.getCON_AC_SUBMIT_ACTION() == null)
REPBean.setCON_AC_SUBMIT_ACTION("");
if (!REPBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
String sRet = "";
String conIDseq = REPBean.getIDSEQ();
// create it only if doesn't exist
if (conIDseq == null || conIDseq.equals(""))
conIDseq = this.setConcept("INS", sRet, REPBean);
if (conIDseq != null && !conIDseq.equals("")) {
if (sOCCondrString.equals(""))
sOCCondrString = conIDseq;
else
sOCCondrString = sOCCondrString + "," + conIDseq;
}
}
}
if (sOCCondr == null)
sOCCondr = "";
// if (!sContextID.equals("") && !sOCCondrString.equals(""))
if (!sOCCondrString.equals("")) {
if (sREPName != null || !sREPName.equals("")) {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_REP_CONDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_REP_CONDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // OCL
// IDSEQ
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // preferred_name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // long_name
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // preferred_definition
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // version
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // asl_name
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // latest_version_ind
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // change_note
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // origin
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // definition_source
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // begin_date
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // end_date
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // date_created
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // created_by
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // date_modified
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // modified_by
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // deleted_ind
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); // rep_condr_idseq
cstmt.registerOutParameter(23, java.sql.Types.VARCHAR); // rep_id
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session
.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(2, sOCCondrString); // comma-delimited
// con idseqs
cstmt.setString(3, sContextID);
cstmt.execute();
sReturnCode = cstmt.getString(4);
sREP_IDSEQ = cstmt.getString(5);
if (sREP_IDSEQ == null)
sREP_IDSEQ = "";
sREP_IDSEQ = sREP_IDSEQ.trim();
String sREP_CONDR_IDSEQ = cstmt.getString(22);
if (sREP_CONDR_IDSEQ == null)
sREP_CONDR_IDSEQ = "";
DataManager.setAttribute(session, "newRepTerm", "");
if (VD != null
&& (sReturnCode == null
|| sReturnCode.equals("") || sReturnCode
.equals("API_REP_500"))) {
VD.setVD_REP_IDSEQ(sREP_IDSEQ);
VD.setVD_REP_CONDR_IDSEQ(sREP_CONDR_IDSEQ);
VD.setVD_REP_ASL_NAME(cstmt.getString(10));
req.setAttribute("REP_IDSEQ", sREP_IDSEQ);
}
if (sReturnCode != null && !sReturnCode.equals("")
&& !sReturnCode.equals("API_REP_500")) {
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update Rep Term.");
m_classReq.setAttribute("retcode", sReturnCode);
VD.setVD_REP_IDSEQ("");
}
}
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setRepresentation for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update or remove Representation Term.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
}
/**
* To check whether data is unique value in the database for the selected
* component, called from setValidatePageValuesDE, setValidatePageValuesDEC,
* setValidatePageValuesVD methods. Creates the sql queries for the selected
* field, to check if the value exists in the database. Calls
* 'getAC.doComponentExist' to execute the query.
*
* @param mDEC
* Data Element Concept Bean.
* @param editAct
* string edit action
* @param setAction
* string set action
*
* @return String retValue message if exists already. Otherwise empty
* string.
*/
public String checkUniqueOCPropPair(DEC_Bean mDEC, String editAct,
String setAction) {
ResultSet rs = null;
PreparedStatement pstmt = null;
String uniqueMsg = "";
try {
HttpSession session = m_classReq.getSession();
String menuAction = (String) session
.getAttribute(Session_Data.SESSION_MENU_ACTION);
String sContID = mDEC.getDEC_CONTE_IDSEQ();
String sPublicID = ""; // mDEC.getDEC_DEC_ID();
String sOCID = mDEC.getDEC_OCL_IDSEQ();
if (sOCID == null)
sOCID = "";
String sPropID = mDEC.getDEC_PROPL_IDSEQ();
if (sPropID == null)
sPropID = "";
// String sOCasl = mDEC.getDEC_OBJ_ASL_NAME();
// String sPROPasl = mDEC.getDEC_PROP_ASL_NAME();
String sReturnID = "";
if (setAction.equalsIgnoreCase("EditDEC")
|| setAction.equalsIgnoreCase("editDECfromDE")
|| menuAction.equals("NewDECVersion"))
sPublicID = mDEC.getDEC_DEC_ID();
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select Sbrext_Common_Routines.get_dec_conte(?,?,?,?) from DUAL");
pstmt.setString(1, sOCID); // oc id
pstmt.setString(2, sPropID); // prop id
pstmt.setString(3, sContID); // dec context
pstmt.setString(4, sPublicID); // dec pubilic id
rs = pstmt.executeQuery(); // call teh query
while (rs.next())
sReturnID = rs.getString(1);
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
// oc-prop-context is not unique
if (sReturnID != null && !sReturnID.equals(""))
uniqueMsg = "Combination of Object Class, Property and Context already exists in DEC with Public ID(s): "
+ sReturnID + "<br>";
else // check if it exists in other contexts
{
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select Sbrext_Common_Routines.get_dec_list(?,?,?) from DUAL");
pstmt.setString(1, sOCID); // oc id
pstmt.setString(2, sPropID); // prop id
pstmt.setString(3, sPublicID); // dec pubilic id
rs = pstmt.executeQuery(); // call teh query
while (rs.next())
sReturnID = rs.getString(1);
// oc-prop is not unique in other contexts
if (sReturnID != null && !sReturnID.equals(""))
uniqueMsg = "Warning: DEC's with combination of Object Class and Property already exists in other contexts with Public ID(s): "
+ sReturnID + "<br>";
}
}
} catch (Exception e) {
logger.error(
"ERROR in InsACService-checkUniqueOCPropPair for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return uniqueMsg;
}
/**
* to created object class, property and qualifier value from EVS into cadsr. Retrieves the session bean m_DEC.
* calls 'insAC.setDECQualifier' to insert the database.
*
* @param m_classReq
* The HttpServletRequest from the client
* @param m_classRes
* The HttpServletResponse back to the client
* @param DECBeanSR
* dec attribute bean.
*
* @return DEC_Bean return the bean with the changed attributes
* @throws Exception
*/
public DEC_Bean doInsertDECBlocks(DEC_Bean DECBeanSR)
throws Exception
{
// logger.debug("doInsertDECBlocks");
HttpSession session = m_classReq.getSession();
//InsACService insAC = new InsACService(m_classReq, m_classRes, this);
String sNewOC = (String) session.getAttribute("newObjectClass");
String sNewProp = (String) session.getAttribute("newProperty");
if (sNewOC == null)
sNewOC = "";
if (sNewProp == null)
sNewProp = "";
if (DECBeanSR == null)
DECBeanSR = (DEC_Bean) session.getAttribute("m_DEC");
String sRemoveOCBlock = (String) session.getAttribute("RemoveOCBlock");
String sRemovePropBlock = (String) session.getAttribute("RemovePropBlock");
if (sRemoveOCBlock == null)
sRemoveOCBlock = "";
if (sRemovePropBlock == null)
sRemovePropBlock = "";
/*
* if (sNewOC.equals("true")) DECBeanSR = insAC.setObjectClassDEC("INS", DECBeanSR, m_classReq); else
* if(sRemoveOCBlock.equals("true"))
*/
String sOC = DECBeanSR.getDEC_OCL_NAME();
if (sOC != null && !sOC.equals(""))
DECBeanSR = setObjectClassDEC("INS", DECBeanSR, m_classReq);
/*
* if (sNewProp.equals("true")) DECBeanSR = insAC.setPropertyDEC("INS", DECBeanSR, m_classReq); else
* if(sRemovePropBlock.equals("true"))
*/
String sProp = DECBeanSR.getDEC_PROPL_NAME();
if (sProp != null && !sProp.equals(""))
DECBeanSR = setPropertyDEC("INS", DECBeanSR, m_classReq);
return DECBeanSR;
}
/**
* To insert a Qualifier Term or update the existing one in the database
* after the validation. Called from CurationServlet. Gets all the attribute
* values from the bean, sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_QUAL(?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param sREP_IDSEQ.
* @param VD
* VD Bean.
* @param req
* HttpServletRequest Object.
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
/**
* To insert a Qualifier Term or update the existing one in the database
* after the validation. Called from CurationServlet. Gets all the attribute
* values from the bean, sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_QUAL(?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param sREP_IDSEQ.
* @param VD
* VD Bean.
* @param req
* HttpServletRequest Object.
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
/**
* To insert a new Data Element or update the existing one in the database
* after the validation. Called from CurationServlet. Gets all the attribute
* values from the bean, sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_DE(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}" to
* submit If no error occurs from query execute, calls 'setDES' to create
* CDEID for new DE and to store selected language in the database, calls
* 'setRD' to store reference document and source attributes. calls
* 'getCSCSI' to insert in CSCSI relationship table for Classification
* Scheme/items/DE relationship. calls 'updCSCSI' to update in CSCSI
* relationship for edit.
*
* @param sAction
* Insert or update Action.
* @param de
* DE Bean.
* @param sInsertFor
* for Versioning.
* @param oldDE
* DE IDseq
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
@SuppressWarnings("unchecked")
public String setDE(String sAction, DE_Bean de, String sInsertFor,
DE_Bean oldDE) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
String v_ac = "";
String oldDEID = "";
String oldContext = "";
String oldName = "";
String oldContextID = "";
String oldAslName = "";
String sDE_ID = "";
String oldDocText = "";
String oldSource = "";
String oldEndDate = "";
String oldBeginDate = "";
String oldChangeNote = "";
try {
m_classReq.setAttribute("retcode", ""); // set to empty retcode in
// request to track it all
// through this request
if (oldDE == null)
oldDE = new DE_Bean();
String sName = de.getDE_PREFERRED_NAME();
String sContextID = de.getDE_CONTE_IDSEQ();
String sContext = de.getDE_CONTEXT_NAME();
Double DVersion = new Double(de.getDE_VERSION());
double dVersion = DVersion.doubleValue();
String sDefinition = de.getDE_PREFERRED_DEFINITION();
String sDEC_ID = de.getDE_DEC_IDSEQ();
String sVD_ID = de.getDE_VD_IDSEQ();
String sLongName = de.getDE_LONG_NAME();
String sDocText = de.getDOC_TEXT_PREFERRED_QUESTION();
String sBeginDate = m_util.getOracleDate(de.getDE_BEGIN_DATE());
String sEndDate = m_util.getOracleDate(de.getDE_END_DATE());
String sChangeNote = de.getDE_CHANGE_NOTE();
String sSource = de.getDE_SOURCE();
String sLanguage = de.getDE_LANGUAGE();
if (sSource == null)
sSource = "";
// store versioned status message
if (sInsertFor.equals("Version"))
this.storeStatusMsg("\\t Successfully created new version.");
// get the old attributes from the oldbean
if (oldDE != null && !oldDE.equals("")) {
sDE_ID = oldDE.getDE_DE_IDSEQ();
oldDEID = oldDE.getDE_DE_IDSEQ();
oldContext = oldDE.getDE_CONTEXT_NAME();
oldName = oldDE.getDE_PREFERRED_NAME();
oldContextID = oldDE.getDE_CONTE_IDSEQ();
oldAslName = oldDE.getDE_ASL_NAME();
}
if (oldDE != null)
oldSource = oldDE.getDE_SOURCE();
if (oldSource == null)
oldSource = "";
if (sSource == null)
sSource = "";
if ((sSource == null || sSource.equals(""))
&& sAction.equals("UPD") && !sSource.equals(oldSource))
sSource = " ";
if (oldDE != null)
oldChangeNote = oldDE.getDE_CHANGE_NOTE();
if (oldChangeNote == null)
oldChangeNote = "";
if (sChangeNote == null)
sChangeNote = "";
if ((sChangeNote == null || sChangeNote.equals(""))
&& sAction.equals("UPD")
&& !sChangeNote.equals(oldChangeNote))
sChangeNote = " ";
sBeginDate = de.getDE_BEGIN_DATE();
if (sBeginDate == null)
sBeginDate = "";
if (oldDE != null)
oldBeginDate = oldDE.getDE_BEGIN_DATE();
if (oldBeginDate == null)
oldBeginDate = "";
if ((sBeginDate == null || sBeginDate.equals(""))
&& sAction.equals("UPD")
&& !sBeginDate.equals(oldBeginDate))
sBeginDate = " ";
else
sBeginDate = m_util.getOracleDate(de.getDE_BEGIN_DATE());
sEndDate = de.getDE_END_DATE();
if (oldDE != null)
oldEndDate = oldDE.getDE_END_DATE();
if (sEndDate == null)
sEndDate = "";
if ((sEndDate == null || sEndDate.equals(""))
&& sAction.equals("UPD") && !sEndDate.equals(oldEndDate))
sEndDate = " ";
else
sEndDate = m_util.getOracleDate(de.getDE_END_DATE());
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
DeVO deVO = new DeVO();
if ((sAction.equals("UPD")) || (sAction.equals("DEL"))) {
deVO.setModified_by(userName);
} else if (sAction.equals("INS")) {
deVO.setCreated_by(userName);
}
if ((sAction.equals("UPD")) || (sAction.equals("DEL"))) {
sDE_ID = de.getDE_DE_IDSEQ();
deVO.setDe_IDSEQ(sDE_ID);
}
// make it null for editing released elements
if (sAction.equals("UPD") && oldAslName.equals("RELEASED") && !sInsertFor.equals("Version")) {
deVO.setConte_IDSEQ(null); // context id-not null for INS, must be null for UPD
deVO.setPrefferred_name(null); // preferred name-not null for INS, must be null for UPD
} else // INS case
{
deVO.setConte_IDSEQ(sContextID);// context id-not null for INS, must be null for UPD
deVO.setPrefferred_name(sName); // preferred name-not null for INS, must be null for UPD
}
deVO.setVersion(dVersion); // version-test says must have a value
deVO.setPrefferred_def(sDefinition); // preferred definition-not null for INS
deVO.setDec_IDSEQ(sDEC_ID); // dec id-not null for INS
deVO.setVd_IDSEQ(sVD_ID); // vd id-not null for INS
deVO.setAsl_name(de.getDE_ASL_NAME()); // status
if (sAction.equals("INS"))
deVO.setLastest_version_ind("Yes"); // latest version indicator
deVO.setLong_name(sLongName); // long name-can be null
deVO.setBegin_date(m_util.getSQLTimestamp(de.getDE_BEGIN_DATE())); // sBeginDate-can be null
deVO.setEnd_date(m_util.getSQLTimestamp(de.getDE_END_DATE())); // sEndDate-can be null
deVO.setChange_note(sChangeNote);
deVO.setOrigin(sSource); // origin
DeComp deComp = new DeComp();
ArrayList errorList = deComp.setDe(deVO, sAction, m_servlet.getConn());
if (errorList != null && errorList.size() > 0) {
DeErrorCodes deErrorCode = (DeErrorCodes) errorList.get(0);
sReturnCode = deErrorCode.getErrorMessage();
} else {
sReturnCode = null;
}
sDE_ID = deVO.getDe_IDSEQ();
// store ac name in the status message
if (sAction.equals("INS"))
this.storeStatusMsg("Data Element Name : " + de.getDE_LONG_NAME());
if (sReturnCode != null && sAction.equals("INS"))
this.storeStatusMsg("\\t " + sReturnCode + " : Unable to create new Data Element Successfully.");
else if ((sReturnCode == null)|| (sReturnCode != null && sAction.equals("UPD")) && !sDE_ID.equals("")) {
// store returncode in request to track it all through this request
if (sReturnCode != null && !sReturnCode.equals(""))
m_classReq.setAttribute("retcode", sReturnCode);
// store the status message in the session
if (sAction.equals("INS")) {
String sPublicID = this.getPublicID(sDE_ID);
de.setDE_MIN_CDE_ID(sPublicID);
this.storeStatusMsg("Public ID : " + de.getDE_MIN_CDE_ID());
this.storeStatusMsg("\\t Successfully created New Data Element.");
} else if (sAction.equals("UPD") && sReturnCode != null && !sReturnCode.equals(""))
this.storeStatusMsg("\\t " + sReturnCode + " : Unable to update mandatory attributes.");
de.setDE_DE_IDSEQ(sDE_ID);
// set create /mofiy attributes into bean
if (deVO.getCreated_by() != null && !deVO.getCreated_by().equals(""))
de.setDE_CREATED_BY(getFullName(deVO.getCreated_by()));
else
de.setDE_CREATED_BY(oldDE.getDE_CREATED_BY());
if (deVO.getDate_created() != null && !deVO.getDate_created().equals(""))
de.setDE_DATE_CREATED(m_util.getCurationDateFromSQLTimestamp(deVO.getDate_created()));
else
de.setDE_DATE_CREATED(oldDE.getDE_DATE_CREATED());
de.setDE_MODIFIED_BY(getFullName(deVO.getModified_by()));
de.setDE_DATE_MODIFIED(m_util.getCurationDateFromSQLTimestamp(deVO.getDate_created()));
// insert row into DES (designation) to create CDEID for new
// DE or copies from old if new version
if (sInsertFor.equals("Version")) {
// created and modifed are same if veriosing
de.setDE_CREATED_BY(de.getDE_MODIFIED_BY());
de.setDE_DATE_CREATED(de.getDE_DATE_MODIFIED());
de.setDE_MIN_CDE_ID(oldDE.getDE_MIN_CDE_ID()); // refill
// the
// oldpublic
}
// insert/update row into DES (designation)
String sReturn = "";
sReturn = "";
// registration status insert or update if not null
if (de.getDE_REG_STATUS() != null
&& !de.getDE_REG_STATUS().equals("")) {
de.setDE_REG_STATUS_IDSEQ(this.getAC_REG(sDE_ID));
if (de.getDE_REG_STATUS_IDSEQ() == null
|| de.getDE_REG_STATUS_IDSEQ().equals(""))
sReturn = this.setReg_Status("INS", "", sDE_ID, de
.getDE_REG_STATUS());
else
sReturn = this.setReg_Status("UPD", de
.getDE_REG_STATUS_IDSEQ(), sDE_ID, de
.getDE_REG_STATUS());
if (sReturn != null && !sReturn.equals(""))
this.storeStatusMsg("\\t "
+ sReturn
+ " : Unable to update Registration Status.");
} else {
// delete if reg status is empty and idseq is not null
if (de.getDE_REG_STATUS_IDSEQ() != null
&& !de.getDE_REG_STATUS_IDSEQ().equals(""))
sReturn = this.setReg_Status("DEL", de
.getDE_REG_STATUS_IDSEQ(), sDE_ID, de
.getDE_REG_STATUS());
if (sReturn != null && !sReturn.equals(""))
this
.storeStatusMsg("\\t "
+ sReturn
+ " : Unable to remove Registration Status.");
}
// store returncode in request to track it all through this
// request
if (sAction.equals("UPD") && sReturn != null
&& !sReturn.equals(""))
m_classReq.setAttribute("retcode", sReturn);
// insert and delete ac-csi relationship
Vector<AC_CSI_Bean> vAC_CS = de.getAC_AC_CSI_VECTOR();
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes,
m_servlet);
Vector<AC_CSI_Bean> vRemove_ACCSI = getAC.doCSCSI_ACSearch(
sDE_ID, ""); // search for cscsi again with de
// idseq.
Vector vACID = (Vector) session.getAttribute("vACId");
this.addRemoveACCSI(sDE_ID, vAC_CS, vRemove_ACCSI, vACID,
sInsertFor, sLongName);
// store back altname and ref docs to session
m_servlet.doMarkACBeanForAltRef(m_classReq, m_classRes,
"DataElement", "all", "submitAR");
// do alternate names create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doAltVersionUpdate(sDE_ID, oldDEID);
de.save(session, m_servlet.getConn(), sDE_ID, sContextID);
session.removeAttribute("AllAltNameList");
/*
* Vector<ALT_NAME_Bean> tBean =
* AltNamesDefsSession.getAltNameBeans(session,
* AltNamesDefsSession._searchDE, sDE_ID, sContextID); if
* (tBean != null) DataManager.setAttribute(session,
* "AllAltNameList", tBean);
*/
String oneAlt = this.doAddRemoveAltNames(sDE_ID,
sContextID, sAction); // , "create");
de.setALTERNATE_NAME(oneAlt);
// do reference docuemnts create
if (sInsertFor.equalsIgnoreCase("Version"))
this.doRefVersionUpdate(sDE_ID, oldDEID);
// insert/upadte row into RD (REFERENCE DOCUMENTS ) //right
// now only for INS.
String sLang = "ENGLISH";
// get the rd idseq for new version
if (sInsertFor.equalsIgnoreCase("Version"))
de
.setDOC_TEXT_PREFERRED_QUESTION_IDSEQ(getRD_ID(sDE_ID));
if ((sDocText != null) && (!sDocText.equals(""))) {
if (sDocText.length() > 30)
sDocText = sDocText.substring(0, 29);
if (de.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ() == null
|| de.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ()
.equals(""))
sReturn = setRD("INS", sDocText, sDE_ID, de
.getDOC_TEXT_PREFERRED_QUESTION(),
"Preferred Question Text", "", sContextID,
de.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ(),
sLang);
else
sReturn = setRD("UPD", sDocText, sDE_ID, de
.getDOC_TEXT_PREFERRED_QUESTION(),
"Preferred Question Text", "", sContextID,
de.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ(),
sLang);
} else { // delete RD if null
if (de.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ() != null
&& !de.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ()
.equals("")) {
// sReturn = setRD("DEL", sDocText, sDE_ID,
// de.getDOC_TEXT_PREFERRED_QUESTION(), "Preferred
// Question Text", "", "",
// de.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ(),
// sLang); //?????
// mark it deleted to do the action with other RDs.
Vector<REF_DOC_Bean> vRefDocs = (Vector) session
.getAttribute("AllRefDocList");
for (int i = 0; i < vRefDocs.size(); i++) {
REF_DOC_Bean rBean = (REF_DOC_Bean) vRefDocs
.elementAt(i);
String refID = rBean.getREF_DOC_IDSEQ();
if (refID != null
&& refID
.equalsIgnoreCase(de
.getDOC_TEXT_PREFERRED_QUESTION_IDSEQ())) {
rBean.setREF_SUBMIT_ACTION("DEL");
// System.out.println(" pqt removed " +
// rBean.getDOCUMENT_NAME());
vRefDocs.setElementAt(rBean, i);
DataManager.setAttribute(session,
"AllRefDocList", vRefDocs);
break;
}
}
}
}
// store returncode in request to track it all through this
// request
if (sAction.equals("UPD") && sReturn != null
&& !sReturn.equals(""))
m_classReq.setAttribute("retcode", sReturn);
String oneRD = this.doAddRemoveRefDocs(sDE_ID, sContextID,
sAction); // "create");
de.setREFERENCE_DOCUMENT(oneRD);
// do contact updates
Hashtable<String, AC_CONTACT_Bean> deConts = de
.getAC_CONTACTS();
if (deConts != null && deConts.size() > 0)
de.setAC_CONTACTS(this.addRemoveAC_Contacts(deConts,
sDE_ID, sInsertFor));
// get one concept name for this de
DEC_Bean de_dec = (DEC_Bean) de.getDE_DEC_Bean();
VD_Bean de_vd = (VD_Bean) de.getDE_VD_Bean();
String oneCon = "";
if (de_dec != null && de_dec.getAC_CONCEPT_NAME() != null)
oneCon = de_dec.getAC_CONCEPT_NAME();
if (de_vd != null && de_vd.getAC_CONCEPT_NAME() != null
&& oneCon.equals(""))
oneCon = de_vd.getAC_CONCEPT_NAME();
de.setAC_CONCEPT_NAME(oneCon);
String otherRet = (String) m_classReq
.getAttribute("retcode");
if (sAction.equals("UPD")
&& (otherRet == null || otherRet.equals("")))
this
.storeStatusMsg("\\t Successfully updated Data Element attributes.");
}
}
this.storeStatusMsg("\\n");
} catch (Exception e) {
logger.error("ERROR in InsACService-setDE for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update Data Element Attributes.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
} // end set DE
/**
* To insert create a new version for an Administered component. Called from
* CurationServlet. Calls oracle stored procedure according to the selected
* AC. "{call META_CONFIG_MGMT.DE_VERSION(?,?,?,?)}" to create new version
* update the respective bean with the new idseq if successful
*
* @param de
* DE_Bean.
* @param dec
* DEC_Bean.
* @param vd
* VD_Bean.
* @param ACName
* String administerd component.
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
public String setAC_VERSION(DE_Bean de, DEC_Bean dec, VD_Bean vd,
String ACName) {
ResultSet rs = null;
CallableStatement cstmt = null;
String sReturnCode = "None";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
String ACID = "";
String sVersion = "";
// call the methods according to the ac componenets
if (ACName.equals("DataElement")) {
cstmt = m_servlet.getConn().prepareCall(
"{call META_CONFIG_MGMT.DE_VERSION(?,?,?,?,?)}");
ACID = de.getDE_DE_IDSEQ();
sVersion = de.getDE_VERSION();
} else if (ACName.equals("DataElementConcept")) {
cstmt = m_servlet.getConn().prepareCall(
"{call META_CONFIG_MGMT.DEC_VERSION(?,?,?,?,?)}");
ACID = dec.getDEC_DEC_IDSEQ();
sVersion = dec.getDEC_VERSION();
} else if (ACName.equals("ValueDomain")) {
cstmt = m_servlet.getConn().prepareCall(
"{call META_CONFIG_MGMT.VD_VERSION(?,?,?,?,?)}");
ACID = vd.getVD_VD_IDSEQ();
sVersion = vd.getVD_VERSION();
}
// Set the out parameters (which are inherited from the
// PreparedStatement class)
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR); // NEW
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // RETURN
// CODE
cstmt.setString(1, ACID); // AC idseq
Double DVersion = new Double(sVersion); // convert the version
// to double type
double dVersion = DVersion.doubleValue();
cstmt.setDouble(2, dVersion); // version
// Get the username from the session.
String userName = (String) m_classReq.getSession().getAttribute("Username");
cstmt.setString(5, userName); // username
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(4);
String newACID = cstmt.getString(3);
// trim off the extra spaces in it
if (newACID != null && !newACID.equals(""))
newACID = newACID.trim();
// update the bean if return code is null and new de id is not
// null
if (sReturnCode == null && newACID != null) {
// update the bean according to the ac componenets
if (ACName.equals("DataElement"))
de.setDE_DE_IDSEQ(newACID);
else if (ACName.equals("DataElementConcept"))
dec.setDEC_DEC_IDSEQ(newACID);
else if (ACName.equals("ValueDomain"))
vd.setVD_VD_IDSEQ(newACID);
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-AC_version for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to version an Administered Component.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
}
/**
* To insert create a new version for an Administered component. Called from
* CurationServlet. Calls oracle stored procedure according to the selected
* AC. "{call META_CONFIG_MGMT.DE_VERSION(?,?,?,?)}" to create new version
* update the respective bean with the new idseq if successful
*
* @param acIDseq
* string ac idseq
* @param ACType
* String AC type
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
public String setOC_PROP_REP_VERSION(String acIDseq, String ACType) {
ResultSet rs = null;
CallableStatement cstmt = null;
String newACID = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
String sReturnCode = "None";
// String sVersion = "";
acIDseq = acIDseq.trim();
// call the methods according to the ac componenets
if (ACType.equals("ObjectClass"))
cstmt = m_servlet.getConn().prepareCall(
"{call META_CONFIG_MGMT.OC_VERSION(?,?,?)}");
else if (ACType.equals("Property"))
cstmt = m_servlet.getConn().prepareCall(
"{call META_CONFIG_MGMT.PROP_VERSION(?,?,?)}");
else if (ACType.equals("RepTerm"))
cstmt = m_servlet.getConn().prepareCall(
"{call META_CONFIG_MGMT.REP_VERSION(?,?,?)}");
// Set the out parameters (which are inherited from the
// PreparedStatement class)
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // NEW
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR); // RETURN
// CODE
cstmt.setString(1, acIDseq); // AC idseq
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(3);
newACID = cstmt.getString(2);
// trim off the extra spaces in it
if ((sReturnCode == null || sReturnCode.equals(""))
&& newACID != null && !newACID.equals(""))
newACID = newACID.trim();
else {
newACID = "";
String stmsg = sReturnCode
+ " : Unable to version an Administered Component - "
+ ACType + ".";
logger.error(stmsg);
m_classReq.setAttribute("retcode", sReturnCode);
this.storeStatusMsg("\\t : " + stmsg);
}
}
} catch (Exception e) {
logger.error(
"ERROR in InsACService-setOC_PROP_REP_VERSION for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to version an Administered Component.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return newACID;
}
/**
* To insert a new row or update the existing one in designations table
* after the validation. Called from 'setDE', 'setVD', 'setDEC' method. Sets
* in parameters, and registers output parameter. Calls oracle stored
* procedure "{call SBREXT_Set_Row.SET_DES(?,?,?,?,?,?,?,?,?,?,?,?)}" to
* submit
*
* @param sAction
* Insert or update Action.
* @param sAC_ID
* selected component's idseq.
* @param sContextID
* selected context idseq.
* @param sContext
* context name to set
* @param desType
* designation type.
* @param sValue
* input value.
* @param sLAE
* language name.
* @param desIDSEQ
* designation idseq for update.
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
@SuppressWarnings("unchecked")
public String setDES(String sAction, String sAC_ID, String sContextID,
String sContext, String desType, String sValue, String sLAE,
String desIDSEQ) {
// capture the duration
java.util.Date startDate = new java.util.Date();
// logger.info(m_servlet.getLogMessage(m_classReq, "setDES", "starting
// set", startDate, startDate));
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
try {
// remove the new line character before submitting
if (sValue != null && !sValue.equals(""))
sValue = m_util.removeNewLineChar(sValue);
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_DES(?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_DES(?,?,?,?,?,?,?,?,?,?,?,?,?)}");
// cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); //
// ua_name
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // des
// desig
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // des
// name
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // des
// detl
// name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // des
// ac id
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // context
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // lae
// name
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // created
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // modified
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // date
// modified
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
if ((sAction.equals("UPD")) || (sAction.equals("DEL"))) {
if ((desIDSEQ != null) && (!desIDSEQ.equals("")))
cstmt.setString(4, desIDSEQ); // desig idseq if
// updated
else
sAction = "INS"; // INSERT A NEW RECORD IF NOT
// EXISTED
}
cstmt.setString(3, sAction); // ACTION - INS, UPD or DEL
cstmt.setString(5, sValue); // selected value for rep and null
// for cde_id
cstmt.setString(6, desType); // detl name - must be string
// CDE_ID
cstmt.setString(7, sAC_ID); // ac id - must be NULL FOR UPDATE
cstmt.setString(8, sContextID); // context id - must be same as
// in set_DE
cstmt.setString(9, sLAE); // language name - can be null
// Now we are ready to call the stored procedure
boolean bExcuteOk = cstmt.execute();
sReturnCode = cstmt.getString(2);
// already exists in the database
if (sReturnCode == null || sReturnCode.equals("API_DES_300")) {
desIDSEQ = cstmt.getString(4);
// store the desIDseq in the hash table for designation
if ((sAction.equals("INS") || sAction.equals("DEL"))
&& desType.equals("USED_BY")) {
// HttpSession session = m_classReq.getSession();
Hashtable<String, String> desTable = (Hashtable) session
.getAttribute("desHashTable");
if (desTable == null)
desTable = new Hashtable<String, String>();
// add or remove from hash table according to the action
if (desIDSEQ == null || desIDSEQ.equals("")) {
this
.storeStatusMsg("\\t "
+ sReturnCode
+ " : Unable to get the ID of Alternate Name - "
+ sValue + " of Type " + desType
+ ".");
m_classReq.setAttribute("retcode", sReturnCode);
} else {
if (sAction.equals("INS")
&& !desTable.contains(sContext + ","
+ sAC_ID))
desTable.put(sContext + "," + sAC_ID, desIDSEQ);
else if (sAction.equals("DEL")
&& desTable.contains(sContext + ","
+ sAC_ID))
desTable.remove(sContext + "," + sAC_ID);
// store it back
DataManager.setAttribute(session, "desHashTable",
desTable);
// refresh used by context in the search results
// list
/*
* GetACSearch serAC = new GetACSearch(m_classReq,
* m_classRes, m_servlet);
* serAC.refreshDesData(sAC_ID, desIDSEQ, sValue,
* sContext, sContextID, sAction);
*/
}
}
} else {
if (sAction.equals("INS") || sAction.equals("UPD"))
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update Alternate Name - "
+ sValue + " of Type " + desType + ".");
else
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to remove Alternate Name - "
+ sValue + " of Type " + desType + ".");
m_classReq.setAttribute("retcode", sReturnCode); // store
// returncode
// request
// track
// all
// through
// this
// request
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setDES for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception e : Unable to update or remove an Alternate Name.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
} // end set DES
/**
* After Primary DE and Component DEs are created, insert entries to table
* complex_data_element for DDE info and complex_de_relationship for DE
* Component Calls oracle stored procedure: set_complex_de,
* set_cde_relationship This method is call by doInsertDEfromMenuAction in
* servlet
*
* @param sP_DE_IDSEQ
* string de idseq new created primary DE.
* @param sOverRideAction
* string for New DE Version/Template, use INS instead of UPD
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
public String setDDE(String sP_DE_IDSEQ, String sOverRideAction) {
CallableStatement cstmt = null;
String sReturnCode = "";
// boolean bExcuteOk;
String sAction = "";
// Collect data first
HttpSession session = m_classReq.getSession();
// get DEComp rule... from page
String sRulesAction = (String) session.getAttribute("sRulesAction");
String sDDERepType = (String) session.getAttribute("sRepType");
if ((sRulesAction == null || sRulesAction.equals("newRule"))
&& (sDDERepType == null || sDDERepType.length() < 1)) {
// logger.error(" setDDE return nada");
return "";
}
String sDDERule = (String) session.getAttribute("sRule");
String sDDEMethod = (String) session.getAttribute("sMethod");
String sDDEConcatChar = (String) session.getAttribute("sConcatChar");
// get DEComp, DECompID and DECompOrder vector from session, which be
// set in doUpdateDDEInfo
Vector vDEComp = new Vector();
Vector vDECompID = new Vector();
Vector vDECompOrder = new Vector();
Vector vDECompRelID = new Vector();
Vector vDECompDelete = new Vector();
Vector vDECompDelName = new Vector();
vDEComp = (Vector) session.getAttribute("vDEComp");
vDECompID = (Vector) session.getAttribute("vDECompID");
vDECompOrder = (Vector) session.getAttribute("vDECompOrder");
vDECompRelID = (Vector) session.getAttribute("vDECompRelID");
vDECompDelete = (Vector) session.getAttribute("vDECompDelete");
vDECompDelName = (Vector) session.getAttribute("vDECompDelName");
// put them into DB tables
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// call Set_Complex_DE to ins/upd/del rules
if (sRulesAction.equals("existedRule")) {
if (sDDERepType == null || sDDERepType.length() < 1) // existed
// rule
// deleted
{
sAction = "DEL"; // action
if (!vDECompDelete.isEmpty())
deleteDEComp(m_servlet.getConn(), session,
vDECompDelete, vDECompDelName);
} else
sAction = "UPD"; // action
} else
sAction = "INS"; // action
if (sOverRideAction.length() > 0)
sAction = sOverRideAction;
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.Set_Complex_DE(?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_Complex_DE(?,?,?,?,?,?,?,?,?,?,?,?)}");
// Set the In parameters
// cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); //
// ua_name
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // cdt_created_by
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // cdt_date_created
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // cdt_modified_by
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // cdt_date_modified
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // return
// code
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
/*
logger.info("Arguments to sbrext_set_row.set_complex_de()\nuserName\t" + userName
+ "\nsAction\t" + sAction
+ "\nsP_DE_IDSEQ\t" + sP_DE_IDSEQ
+ "\nsDDEMethod\t" + sDDEMethod
+ "\nsDDERule\t" + sDDERule
+ "\nsDDEConcatChar\t" + sDDEConcatChar
+ "\nsDDERepType\t" + sDDERepType);
*/
cstmt.setString(1, userName); // set ua_name
cstmt.setString(2, sAction); // action
cstmt.setString(3, sP_DE_IDSEQ); // primary DE idseq
cstmt.setString(4, sDDEMethod); // method
cstmt.setString(5, sDDERule); // rule
cstmt.setString(6, sDDEConcatChar); // conca char
cstmt.setString(7, sDDERepType); // rep type
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(12);
// add error message to list
if (sReturnCode != null && !sReturnCode.equals(""))
this
.storeStatusMsg("\\t "
+ sReturnCode
+ " : Unable to update Derived Data Element attributes");
// call Set_CDE_Relationship for DEComps
// check if any DEComp removed (only for de updates) commented
// by sumana 7/14/05)
// System.out.println(vDECompDelete.isEmpty() + " before delete
// " + sRulesAction);
if (!vDECompDelete.isEmpty()
&& sRulesAction.equals("existedRule"))
deleteDEComp(m_servlet.getConn(), session, vDECompDelete,
vDECompDelName);
// insert or update DEComp
if (!vDEComp.isEmpty()) {
cstmt = SQLHelper.closeCallableStatement(cstmt);
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.Set_CDE_Relationship(?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_CDE_Relationship(?,?,?,?,?,?,?,?,?,?,?)}");
// Set the In parameters
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR); // cdr_idseq
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // cdr_p_de_idseq
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // cdr_c_de_idseq
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // cdr_display_order
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // cdr_created_by
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // cdr_date_created
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // cdr_modified_by
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // cdr_date_modified
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // return
// code
for (int i = 0; i < vDEComp.size(); i++) {
String sDECompName = (String) vDEComp.elementAt(i);
String sDECompID = (String) vDECompID.elementAt(i);
String sDECompOrder = (String) vDECompOrder
.elementAt(i);
String sDECompRelID = (String) vDECompRelID
.elementAt(i);
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Set the username from the session.
cstmt.setString(1, userName); // set ua_name
if (sDECompRelID.equals("newDEComp")
|| sRulesAction.equals("newRule")) // insert if
// new rule
sAction = "INS"; // action
else {
sAction = "UPD"; // action
cstmt.setString(3, sDECompRelID); // Complex DE
// Relationship
// idseq
}
if (sOverRideAction.length() > 0)
sAction = sOverRideAction;
cstmt.setString(2, sAction); // action
cstmt.setString(4, sP_DE_IDSEQ); // primary DE idseq
cstmt.setString(5, sDECompID); // DE Comp ID
cstmt.setString(6, sDECompOrder); // DE Comp Order
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(11);
if (sReturnCode != null && !sReturnCode.equals(""))
this
.storeStatusMsg("\\t "
+ sReturnCode
+ " : Unable to update Derived Data Element Component "
+ sDECompName);
} // end of for
} // end of if(!vDEComp.isEmpty())
} // end of if (conn == null)
} // end of try
catch (Exception e) {
logger.error("ERROR in InsACService-setDEComp for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update or remove Derived Data Elements");
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
} // end setDEComp
/**
* Delete DE Component Calls oracle stored procedure: set_cde_relationship
* This method is call by setDEComp
*
* @param conn
* @param session
* @param vDECompDelete
* @param vDECompDelName
*
*
*/
public void deleteDEComp(Connection conn, HttpSession session,
Vector vDECompDelete, Vector vDECompDelName) {
CallableStatement cstmt = null;
try {
String sReturnCode = "";
// call Set_CDE_Relationship for DEComps
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.Set_CDE_Relationship(?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = conn
.prepareCall("{call SBREXT_SET_ROW.SET_CDE_Relationship(?,?,?,?,?,?,?,?,?,?,?)}");
// Set the In parameters
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR); // cdr_idseq
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // cdr_p_de_idseq
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // cdr_c_de_idseq
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // cdr_display_order
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // cdr_created_by
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // cdr_date_created
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // cdr_modified_by
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // cdr_date_modified
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // return
// code
for (int i = 0; i < vDECompDelete.size(); i++) {
String sDECompDeleteID = (String) vDECompDelete.elementAt(i);
String sDECompDeleteName = (String) vDECompDelName.elementAt(i);
// delete DEComp when DEL action in Set_CDE_Relationship is
// ready
if (sDECompDeleteID != null && !sDECompDeleteID.equals("")
&& !sDECompDeleteID.equalsIgnoreCase("newDEComp")) {
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// PreparedStatement class)
// Set the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(2, "DEL"); // action
cstmt.setString(3, sDECompDeleteID); // Complex DE
// Relationship
// idseq, key field
// System.out.println(" dde id " + sDECompDeleteID);
cstmt.setString(4, ""); // primary DE idseq
cstmt.setString(5, ""); // DE Comp ID
cstmt.setString(6, ""); // DE Comp Order
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(11);
if (sReturnCode != null && !sReturnCode.equals(""))
this
.storeStatusMsg("\\t "
+ sReturnCode
+ " : Unable to remove Derived Data Element Component "
+ sDECompDeleteName);
}
}
vDECompDelete.clear();
} catch (Exception ee) {
logger.error("ERROR in InsACService-deleteDEComp : "
+ ee.toString(), ee);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to remove Derived Data Element Component.");
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
} // end of deleteDEComp()
/**
* To insert a new row or update the existing one in reference documents
* table after the validation. Called from 'setDE', 'setVD', 'setDEC'
* method. Sets in parameters, and registers output parameter. Calls oracle
* stored procedure "{call SBREXT_Set_Row.SET_RD(?,?,?,?,?,?,?,?,?,?,?,?)}"
* to submit
*
* @param sAction
* Insert or update Action.
* @param sRDName
* any text value.
* @param sDE_ID
* DE idseq.
* @param sDocText
* value of document text.
* @param sRDType
* Preferred Question Text for Doc Text and DATA_ELEMENT_SOURCE
* for source.
* @param sRDURL
* refercne document's url to set
* @param sRDCont
* reference document context to set
* @param rdIDSEQ
* reference document's idseq for update.
* @param sLang
* Rd language to set
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
public String setRD(String sAction, String sRDName, String sDE_ID,
String sDocText, String sRDType, String sRDURL, String sRDCont,
String rdIDSEQ, String sLang) {
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
try {
// remove the new line character before submitting
if (sRDName != null && !sRDName.equals(""))
sRDName = m_util.removeNewLineChar(sRDName);
if (sDocText != null && !sDocText.equals(""))
sDocText = m_util.removeNewLineChar(sDocText);
if (sRDURL != null && !sRDURL.equals(""))
sRDURL = m_util.removeNewLineChar(sRDURL);
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_RD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_RD(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // RD id
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // name
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // dctl
// name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // ac id
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // ach
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // ar id
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // doc
// text
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // org
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // url
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // created
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // modified
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // lae
// name
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
if (sAction.equals("UPD") || sAction.equals("DEL")) {
if ((rdIDSEQ != null) && (!rdIDSEQ.equals("")))
cstmt.setString(4, rdIDSEQ); // rd idseq if updated
else
sAction = "INS"; // insert new one if not existed
}
cstmt.setString(3, sAction); // ACTION - INS, UPD or DEL
cstmt.setString(5, sRDName); // rd name - cannot be null
cstmt.setString(6, sRDType); // dCtl name - long name for
// refrence document
if (sAction.equals("INS"))
cstmt.setString(7, sDE_ID); // ac id - must be NULL FOR
// UPDATE
cstmt.setString(10, sDocText); // doc text -
cstmt.setString(12, sRDURL); // URL -
cstmt.setString(17, sLang); // URL -
cstmt.setString(18, sRDCont); // context -
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(2);
if (sReturnCode != null && !sReturnCode.equals("API_RD_300")) {
if (sAction.equals("INS") || sAction.equals("UPD"))
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update Reference Documents - "
+ sRDName + " of Type " + sRDType + ".");
else
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to remove Reference Documents - "
+ sRDName + " of Type " + sRDType + ".");
m_classReq.setAttribute("retcode", sReturnCode); // store
// returncode
// request
// track
// all
// through
// this
// request
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setRD for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update or remove Reference Documents");
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
} // end set RD
/**
* To get idseq from get_cscsi stored proc to add relationship between csCSI
* and DE. Called from 'setDE' method. Uses the sql query "SELECT
* cs_csi_idseq FROM cs_Csi_view WHERE cs_idseq = '" + csID + "' AND
* csi_idseq = '" + csiID + "'"; Calls 'setACCSI' to add a row in
* relationship table.
*
* @param csID
* classification scheme idseq.
* @param csiID
* classification scheme items idseq.
* @param sAction
* Insert or update Action.
* @param sDE_ID
* DE idseq.
*
*/
public void getCSCSI(String csID, String csiID, String sAction,
String sDE_ID) {
ResultSet rs = null;
CallableStatement cstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet.getConn().prepareCall(
"{call SBREXT_CDE_CURATOR_PKG.GET_CSCSI(?,?,?)}");
cstmt.setString(1, csID);
cstmt.setString(2, csiID);
cstmt.registerOutParameter(3, OracleTypes.CURSOR);
cstmt.execute();
rs = (ResultSet) cstmt.getObject(3);
String s;
while (rs.next()) {
s = rs.getString(1);
if (s != "") // cs_csi_idseq
setACCSI(s, sAction, sDE_ID, "", "", "");
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getCSCSI for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
} // end cscsi
/**
* To insert a row in AC_CSI table to add relationship between csCSI and DE.
* Called from 'getCSCSI' method. Sets in parameters, and registers output
* parameter. Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_ACCSI(?,?,?,?,?,?,?,?,?)}" to submit
*
* @param CSCSIID
* cscsi idseq from cs_csi table.
* @param sAction
* Insert or update Action.
* @param sAC_ID
* String ac idseq
* @param sAC_CSI_ID
* String accsi idseq
* @param sAC_Name
* String ac name
* @param csiName
* String csi name
*
* @return String ACCSI id
*/
public String setACCSI(String CSCSIID, String sAction, String sAC_ID,
String sAC_CSI_ID, String sAC_Name, String csiName) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_ACCSI(?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_ACCSI(?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // AC_CSI
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // AC id
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // CS_CSI
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // created
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // modified
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // date
// modified
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(3, sAction); // ACTION - INS, UPD or DEL
cstmt.setString(4, sAC_CSI_ID); // AC ID - not null
cstmt.setString(5, sAC_ID); // AC ID - not null
cstmt.setString(6, CSCSIID); // CS_CSI_ID - cannot be null
// Now we are ready to call the stored procedure
cstmt.execute();
String ret = cstmt.getString(2);
// get its accsi id if already exists in the database
if (ret != null && ret.equals("API_ACCSI_300"))
sAC_CSI_ID = cstmt.getString(4);
else if (ret != null && !ret.equals("")) {
if (sAction.equals("INS") || sAction.equals("UPD"))
this.storeStatusMsg("\\t " + ret
+ " : Unable to update CSI-" + csiName + ".");
else
this.storeStatusMsg("\\t " + ret
+ " : Unable to remove CSI-" + csiName + ".");
m_classReq.setAttribute("retcode", ret); // store
// returncode in
// request to
// track it all
// through this
// request
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setACCSI for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update or remove AC_CSI relationship.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sAC_CSI_ID;
}
/**
* To retrieve a row in AC_CSI table. Called from 'setDE' method. Calls
* oracle stored procedure "{call
* SBREXT_Get_Row.SET_ACCSI(?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sCSCSIID
* cscsi idseq from cs_csi table.
* @param sDE_ID
* DE idseq.
* @return String accsi idseq
*
*/
public String getACCSI(String sCSCSIID, String sDE_ID) {
CallableStatement cstmt = null;
String sACCSI = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet.getConn().prepareCall(
"{call SBREXT_Get_Row.GET_AC_CSI(?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // accsi
// out
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR); // CS_CSI
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR);
// idseq
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // created
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // modified
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // date
// modified
// Set the In parameters (which are inherited from the
// PreparedStatement class)
cstmt.setString(3, sCSCSIID); // AC ID - not null
cstmt.setString(4, sDE_ID); // AC ID - not null
// Now we are ready to call the stored procedure
cstmt.execute();
sACCSI = cstmt.getString(2);
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setACCSI for exception : "
+ e.toString(), e);
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sACCSI;
}
/**
* not using anymore because source is not a drop down list. To insert a row
* in AC_SOURCES table to add relationship between sources and DE. Called
* from 'setDE' method. Sets in parameters, and registers output parameter.
* Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_ACSRC(?,?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param sDE_ID
* DE idseq.
*
*/
public void setACSRC(String sAction, String sDE_ID) {
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_ACSRC(?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_ACSRC(?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // ACS
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // AC id
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // SRC
// name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // date
// submitted
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // created
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // modified
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(3, sAction); // ACTION - INS, UPD or DEL
cstmt.setString(5, sDE_ID); // AC ID - not null
cstmt.setString(6, "AJCC"); // SRC name - cannot be null ????
// Now we are ready to call the stored procedure
cstmt.execute();
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setACSRC for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update or remove Origin.");
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
} // end of setACSRC
/**
* To update relationship between sources and DE. Called from 'setDE' method
* for update. Sets in parameters, and registers output parameter. Calls
* oracle stored procedure "{call
* SBREXT_CDE_CURATOR_PKG.UPD_CS(?,?,?,?,?,?)}" to submit
*
* @param sDE_ID
* DE idseq.
* @param sCS_ID
* classification scheme idseq.
* @param sCSI_ID
* classification scheme items idseq.
*/
public void updCSCSI(String sDE_ID, String sCS_ID, String sCSI_ID) {
CallableStatement cstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet.getConn().prepareCall(
"{call SBREXT_CDE_CURATOR_PKG.UPD_CS(?,?,?,?,?,?)}");
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // error
// code
// Set the In parameters (which are inherited from the
// PreparedStatement class)
cstmt.setString(1, sDE_ID); // DE idseq
cstmt.setString(2, sCS_ID); // new cs ID
cstmt.setString(3, sCSI_ID); // new csi id
cstmt.setString(4, ""); // old cs id
cstmt.setString(5, ""); // old csi id
// Now we are ready to call the stored procedure
cstmt.execute();
}
} catch (Exception e) {
logger.error("ERROR in InsACService-updCSCSI for exception : "
+ e.toString(), e);
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
} // end of setACSRC
/**
* Called from 'setPV' method for insert of PV. Sets in parameters, and
* registers output parameter. Calls oracle stored procedure "{call
* SBREXT_GET_ROW.GET_PV(?,?,?,?,?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sValue
* existing Value.
* @param sMeaning
* existing meaning.
*
* @return String existing pv_idseq from the stored procedure call.
*/
public String getExistingPV(String sValue, String sMeaning)
{
String sPV_IDSEQ = "";
CallableStatement cstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_GET_ROW.GET_PV(?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // PV_IDSEQ
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // MEANING_DESCRIPTION
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // HIGH_VALUE_NUM
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // LOW_VALUE_NUM
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // BEGIN_DATE
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // END_DATE
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // CREATED_BY
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // Date
// Created
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // MODIFIED_BY
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // DATE_MODIFIED
cstmt.setString(3, sValue); // Value
cstmt.setString(4, sMeaning); // Meaning
// Now we are ready to call the stored procedure
cstmt.execute();
sPV_IDSEQ = (String) cstmt.getObject(2);
if (sPV_IDSEQ == null)
sPV_IDSEQ = "";
}
} catch (Exception e) {
logger.error(
"ERROR in InsACService- getExistingPV for exception : "
+ e.toString(), e);
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sPV_IDSEQ;
}
/**
* To copy cde_id from old de to new de when versioning. Called from 'setDE'
* method for insert at version. Sets in parameters, and registers output
* parameter. Calls oracle stored procedure "{call META_CONFIG_MGMT(?,?,?)}"
* to submit
*
* @param sOldACID
* OLD DE idseq.
* @param sNewACID
* NEW DE idseq.
*/
private void copyAC_ID(String sOldACID, String sNewACID) {
CallableStatement cstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet.getConn().prepareCall(
"{call META_CONFIG_MGMT.COPYACNAMES(?,?,?)}");
// Set the In parameters (which are inherited from the
// PreparedStatement class)
cstmt.setString(1, sOldACID); // DE idseq
cstmt.setString(2, sNewACID); // new DE ID
cstmt.setString(3, "V"); // new csi id
// Now we are ready to call the stored procedure
cstmt.execute();
}
} catch (Exception e) {
logger.error("ERROR in InsACService-copyACID for exception : "
+ e.toString(), e);
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
} }
/**
* To update history table, connecting last version to this version. Called
* from 'setDE' method for insert at version. Sets in parameters, and
* registers output parameter. Calls oracle stored procedure "{call
* META_CONFIG_MGMT.DE_VERSION(?,?,?)}" to submit
*
* @param sNewID
* New DE idseq.
* @param sOldID
* OLD DE idseq.
* @param sACType
* string ac type
*/
private void createACHistories(String sNewID, String sOldID, String sACType) {
CallableStatement cstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet
.getConn()
.prepareCall(
"{call META_CONFIG_MGMT.CREATE_AC_HISTORIES(?,?,?,?,?)}");
// Set the In parameters (which are inherited from the
// PreparedStatement class)
cstmt.setString(1, sOldID); // DE idseq
cstmt.setString(2, sNewID); // new DE ID
cstmt.setString(3, "VERSIONED"); // Config type
cstmt.setString(4, sACType); // type of AC
cstmt.setString(5, ""); // table name, default null
// Now we are ready to call the stored procedure
cstmt.execute();
}
} catch (Exception e) {
logger.error(
"ERROR in InsACService-createACHistory for exception : "
+ e.toString(), e);
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
}
/**
* To get ac_idseq of latest version. Called from 'setDE' method. Sets in
* parameters, and registers output parameter.
*
* @param sName
* Short Name.
* @param sContextID .
* @param sACType
* String type of AC.
* @return ac idseq
*/
private String getVersionAC(String sName, String sContextID, String sACType) {
ResultSet rs = null;
String sReturnID = "";
PreparedStatement pstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select Sbrext_Common_Routines.get_version_ac(?,?,?) from DUAL");
pstmt.setString(1, sName); // DE idseq
pstmt.setString(2, sContextID); // new DE ID
pstmt.setString(3, sACType); // type of AC
rs = pstmt.executeQuery();
while (rs.next()) {
sReturnID = rs.getString(1);
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getversionac for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return sReturnID;
}
/**
* To update the existing Question in questionContents table after the de
* create/update or vd_pvs create for questions. Called from servlet. Sets
* in parameters, and registers output parameter. Calls oracle stored
* procedure "{call
* SBREXT_Set_Row.SET_QC(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}"
* to submit
*
* @param questBean
* Quest_Bean when this is used for questions update, else null.
* @param QCid
* string question's idseq when this is used for Valid Value
* update, else null.
* @param VPid
* string vd_pvs idseq when this is used for valid value update,
* else null
*
* @return String return code from the stored procedure call. null if no
* error occurred.
*/
public String setQuestContent(Quest_Bean questBean, String QCid, String VPid) {
// capture the duration
java.util.Date startDate = new java.util.Date();
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_QC(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_QC(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // oc id
cstmt.registerOutParameter(5, java.sql.Types.DECIMAL); // version
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // Short
// Name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // definiton
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // context
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // asl
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // deID
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // vp id
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // match
// ind
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(23, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(24, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(25, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(26, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(27, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(28, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(29, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(30, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(31, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(32, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(33, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(34, java.sql.Types.VARCHAR); // submitted
// cde
// long
// name
cstmt.registerOutParameter(35, java.sql.Types.VARCHAR);
cstmt.registerOutParameter(36, java.sql.Types.VARCHAR);
// idseq
cstmt.registerOutParameter(37, java.sql.Types.VARCHAR); // created
cstmt.registerOutParameter(38, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(39, java.sql.Types.VARCHAR); // modified
cstmt.registerOutParameter(40, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(41, java.sql.Types.VARCHAR); // deleted
// ind
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(3, "UPD"); // ACTION - INS, UPD or DEL
if (VPid != null && !VPid.equals("")) {
cstmt.setString(4, QCid); // qc idseq if updated
cstmt.setString(15, VPid); // VP idseq for valid values
cstmt.setString(9, "EXACT MATCH"); // workflow status of
// the valid value
cstmt.setString(19, "E"); // match ind of the valid value
} else {
cstmt.setString(4, questBean.getQC_IDSEQ()); // qc idseq
// updated
cstmt.setString(7, questBean.getQUEST_DEFINITION()); // QUEST
// definition
cstmt.setString(14, questBean.getDE_IDSEQ()); // de_idseq
cstmt.setString(34, questBean.getSUBMITTED_LONG_NAME()); // submitted
// long
// cde
// name
cstmt.setString(36, questBean.getVD_IDSEQ()); // vd idseq
}
cstmt.setString(42, null); // de long name
cstmt.setString(43, null); // de long name
cstmt.setString(44, null); // de long name
cstmt.setString(45, null); // de long name
cstmt.setString(46, null); // de long name
cstmt.setString(47, null); // de long name
cstmt.setString(48, null); // de long name
cstmt.setString(49, null); // questBean.getDE_LONG_NAME());
// //de long name
cstmt.setString(50, null); // questBean.getVD_LONG_NAME()); //
// vd long name
cstmt.setString(51, null);
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(2);
if (sReturnCode != null && !sReturnCode.equals("")) {
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update Question attributes.");
m_classReq.setAttribute("retcode", sReturnCode);
}
}
} catch (Exception e) {
logger.error(
"ERROR in InsACService-setQuestContent for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update Question attributes.");
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sReturnCode;
} // end set quest content
/**
* To get RDidseq from get_RD_ID for the selected AC. Called from 'setDE'
* method. Uses the stored Proc call
* SBREXT_COMMON_ROUTINES.GET_RD_IDSEQ(?,?,?)}
*
* @param acID
* administed componenet idseq.
*
* @return String RD_ID.
*/
public String getRD_ID(String acID) {
ResultSet rs = null;
CallableStatement cstmt = null;
String rd_ID = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet.getConn().prepareCall(
"{call SBREXT_COMMON_ROUTINES.GET_RD_IDSEQ(?,?,?)}");
cstmt.setString(1, acID);
cstmt.setString(2, "Preferred Question Text");
cstmt.registerOutParameter(3, OracleTypes.CURSOR);
cstmt.execute();
rs = (ResultSet) cstmt.getObject(3);
while (rs.next()) {
rd_ID = rs.getString(1);
if (rd_ID != null)
break;
}
if (rd_ID == null)
rd_ID = "";
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getRD_ID for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return rd_ID;
} // end RD_ID
/**
* To get UA_FullName from a UserName. Called from 'set' methods. Uses the
* stored Proc call SBREXT_COMMON_ROUTINES.GET_UA_FULL_NAME(?,?,?)}
*
* @param sName
* short Name.
*
* @return String sFullName.
*/
public String getFullName(String sName) {
ResultSet rs = null;
String sFullName = "";
PreparedStatement pstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select SBREXT_CDE_CURATOR_PKG.GET_UA_FULL_NAME(?) from DUAL");
pstmt.setString(1, sName); // short name
rs = pstmt.executeQuery();
while (rs.next()) {
sFullName = rs.getString(1);
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getFullName for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return sFullName;
} // end getFullName
/**
* To get language idseq from get_Desig_ID for the selected AC . Called from
* 'setDE', 'setDEC', 'setVD' methods. Uses the stored Proc call
* SBREXT_COMMON_ROUTINES.GET_DESIG_IDSEQ(?,?,?)}
*
* @param acID
* administed componenet idseq.
* @param DesType
* type of designation
*
* @return String Desig_ID.
*/
public String getDesig_ID(String acID, String DesType) {
ResultSet rs = null;
CallableStatement cstmt = null;
String Desig_ID = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet.getConn().prepareCall(
"{call SBREXT_COMMON_ROUTINES.GET_DESIG_IDSEQ(?,?,?)}");
cstmt.setString(1, acID);
cstmt.setString(2, DesType);
cstmt.registerOutParameter(3, OracleTypes.CURSOR);
cstmt.execute();
rs = (ResultSet) cstmt.getObject(3);
while (rs.next()) {
Desig_ID = rs.getString(1);
if (Desig_ID != null)
break;
}
if (Desig_ID == null)
Desig_ID = "";
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getDesig_ID for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);;
}
return Desig_ID;
} // end Desig_ID
/**
* To insert a row in AC_Registrations table to add relationship between
* reg_status and DE. Called from 'setDE' method. Sets in parameters, and
* registers output parameter. Calls oracle stored procedure "{call
* SBREXT_Set_Row.SET_REGISTRATION(?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param sAR_ID
* idseq from ac_registratins table.
* @param sAC_ID
* AC idseq.
* @param regStatus
* registration status
*
* @return String sAR_ID
*/
public String setReg_Status(String sAction, String sAR_ID, String sAC_ID,
String regStatus) {
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String ret = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_REGISTRATION(?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_Set_Row.SET_REGISTRATION(?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR); // sAR_ID
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // sAC_ID
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // regStatus
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // created
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // modified
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // return
// code
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(2, sAction); // ACTION - INS, UPD or DEL
cstmt.setString(3, sAR_ID); // AR ID - not null if upd or del
cstmt.setString(4, sAC_ID); // AC ID - not null if ins
cstmt.setString(5, regStatus); // regStatus - cannot be null
// Now we are ready to call the stored procedure
cstmt.execute();
// get its AR id if already exists in the database
if (cstmt.getString(10) != null)
ret = cstmt.getString(10);
// else
// sAR_ID = cstmt.getString(2);
if (ret != null && !ret.equals("")) {
if (sAction.equals("DEL"))
this.storeStatusMsg("\\t " + ret
+ " : Unable to remove Registration Status - "
+ regStatus + ".");
else
this.storeStatusMsg("\\t " + ret
+ " : Unable to update Registration Status - "
+ regStatus + ".");
m_classReq.setAttribute("retcode", ret); // store
// returncode in
// request to
// track it all
// through this
// request
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setReg_Status for exception : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update or remove Registration Status.");
}finally{
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return ret;
}
/**
* The getAC_REG method queries the db, checking whether component exists
* and gets idseq if exists.
*
* @param ac_id
* string ac idseq
*
* @return String idseq indicating whether component exists.
*/
public String getAC_REG(String ac_id) // returns idseq
{
ResultSet rs = null;
Statement cstmt = null;
String regID = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet.getConn().createStatement();
rs = cstmt
.executeQuery("SELECT ar_idseq FROM sbr.ac_registrations_view WHERE ac_idseq = '"
+ ac_id + "'");
// loop through to printout the outstrings
while (rs.next()) {
regID = rs.getString(1);
}// end of while
}
} catch (Exception e) {
logger.error("ERROR in getAC_REG : " + e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeStatement(cstmt);
}
return regID;
} // end getAC_REG
/**
* Classifies designated data element(s), called from servlet calls
* addRemoveACCSI to add or remove the selected cs and csi for each element.
* goes back to search results page
*
* @param desAction
* @throws Exception
*/
@SuppressWarnings("unchecked")
public void doSubmitDesDE(String desAction) throws Exception {
HttpSession session = m_classReq.getSession();
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes, m_servlet);
DataManager.setAttribute(session, Session_Data.SESSION_STATUS_MESSAGE,
"");
Vector vACList = (Vector) session.getAttribute("vBEResult");
Vector<String> vACID = (Vector) session.getAttribute("vACId");
Vector<String> vNames = (Vector) session.getAttribute("vACName");
DE_Bean deBean = (DE_Bean) session.getAttribute("m_DE");
String sContextID = (String) m_classReq.getParameter("selContext");
Vector vContName = (Vector) session.getAttribute("vWriteContextDE");
Vector vContID = (Vector) session.getAttribute("vWriteContextDE_ID");
String sContext = m_util.getNameByID(vContName, vContID, sContextID);
if (vACList == null) {
vACList = new Vector();
vACID = new Vector<String>();
vACList.addElement(deBean);
vACID.addElement(deBean.getDE_DE_IDSEQ());
}
for (int k = 0; k < vACList.size(); k++) {
m_classReq.setAttribute("retcode", "");
DE_Bean thisDE = (DE_Bean) vACList.elementAt(k);
if (thisDE == null)
thisDE = new DE_Bean();
// store the ac name in the message
this.storeStatusMsg("Data Element Name : "
+ thisDE.getDE_LONG_NAME());
this.storeStatusMsg("Public ID : " + thisDE.getDE_MIN_CDE_ID());
String deID = thisDE.getDE_DE_IDSEQ();
String deName = thisDE.getDE_LONG_NAME();
String deCont = thisDE.getDE_CONTE_IDSEQ();
// add remove designated context
String desAct = this.addRemoveDesignation(deID, desAction, thisDE,
sContextID, sContext);
// add remove alternate names
String oneAlt = this.doAddRemoveAltNames(deID, deCont, desAction);
// add remove reference documents
String oneRD = this.doAddRemoveRefDocs(deID, deCont, desAction);
// insert and delete ac-csi relationship
SetACService setAC = new SetACService(m_servlet);
deBean = setAC.setDECSCSIfromPage(m_classReq, deBean);
Vector<AC_CSI_Bean> vAC_CS = deBean.getAC_AC_CSI_VECTOR();
Vector<AC_CSI_Bean> vRemove_ACCSI = getAC
.doCSCSI_ACSearch(deID, ""); // (Vector)session.getAttribute("vAC_CSI");
this.addRemoveACCSI(deID, vAC_CS, vRemove_ACCSI, vACID,
"designate", deName);
// refresh used by context in the search results list
GetACSearch serAC = new GetACSearch(m_classReq, m_classRes,
m_servlet);
serAC.refreshDesData(deID, sContext, sContextID, desAct, oneAlt,
oneRD);
// display success message if no error exists for each DE
String sReturn = (String) m_classReq.getAttribute("retcode");
if (sReturn == null || sReturn.equals(""))
this
.storeStatusMsg("\\t Successfully updated Used By Attributes");
}
}
/**
* to get one alternate name for the selected ac
*
* @param acID
* ac idseq
* @return altname from the database
*/
public String getOneAltName(String acID) {
ResultSet rs = null;
String sName = "";
PreparedStatement pstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select SBREXT_CDE_CURATOR_PKG.GET_ONE_ALT_NAME(?) from DUAL");
pstmt.setString(1, acID); // acid
rs = pstmt.executeQuery();
while (rs.next()) {
sName = rs.getString(1);
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getOneAltName for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return sName;
} // end getOneAltName
/**
* to get one reference documents for the selected ac
*
* @param acID
* ac idseq
* @return ref doc from the database
*/
public String getOneRDName(String acID) {
ResultSet rs = null;
String sName = "";
PreparedStatement pstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select SBREXT_CDE_CURATOR_PKG.GET_ONE_RD_NAME(?) from DUAL");
pstmt.setString(1, acID); // acid
rs = pstmt.executeQuery();
while (rs.next()) {
sName = rs.getString(1);
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getOneRDName for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return sName;
} // end getOneRDName
/**
* to get one concept name for the selected ac
*
* @param decID
* String dec idseq
* @param vdID
* String vd idseq
* @return altname from the database
*/
public String getOneConName(String decID, String vdID) {
ResultSet rs = null;
String sName = "";
PreparedStatement pstmt = null;
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select SBREXT_CDE_CURATOR_PKG.GET_ONE_CON_NAME(?,?) from DUAL");
pstmt.setString(1, decID); // decid
pstmt.setString(2, vdID); // vdid
rs = pstmt.executeQuery();
while (rs.next()) {
sName = rs.getString(1);
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getOneConName for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}return sName;
} // end getOneConName
/**
* submits to add or remove the designation for the selected ac Called from
* 'classifyde' method gets the 'desHashTable' table from the session and
* gets the desID using desContext and ACID.
*
* @param CompID
* String component ID
* @param desAction
* String designated submit action
* @param deBean
* DE_Bean Object
* @param useCont
* String context idseq
* @param useContName
* String context name
* @return String return code
*
* @throws Exception
*/
private String addRemoveDesignation(String CompID, String desAction,
DE_Bean deBean, String useCont, String useContName)
throws Exception {
HttpSession session = m_classReq.getSession();
// designate used by context if not exists before
String refreshAct = "";
Vector vUsedCont = (Vector) deBean.getDE_USEDBY_CONTEXT_ID();
String sLang = (String) m_classReq.getParameter("dispLanguage");
if (sLang == null || sLang.equals(""))
sLang = "ENGLISH";
if ((vUsedCont == null || !vUsedCont.contains(useCont))
&& desAction.equals("create")) {
String deCont = deBean.getDE_CONTE_IDSEQ();
// create usedby only if not in the same context as the ac is
if (!deCont.equals(useCont)) {
String sRet = this.setDES("INS", CompID, useCont, useContName,
"USED_BY", useContName, sLang, "");
if (sRet == null || sRet.equals("API_DES_300"))
refreshAct = "INS";
} else {
this
.storeStatusMsg("\\t API_DES_00: Unable to designate in the same context as the owned by context.");
m_classReq.setAttribute("retcode", "API_DES_00");
}
} else if (vUsedCont != null && vUsedCont.contains(useCont)
&& desAction.equals("remove")) {
Hashtable desTable = (Hashtable) session
.getAttribute("desHashTable");
String desID = (String) desTable.get(useContName + "," + CompID);
// call method to delete designation if desidseq is found
if (desID != null && !desID.equals("")) {
String sRet = this.setDES("DEL", CompID, useCont, useContName,
"USED_BY", useContName, sLang, desID);
if (sRet == null || sRet.equals("API_DES_300"))
refreshAct = "DEL";
}
}
return refreshAct;
}
/**
* To get public id of an administerd component. Called from 'set' methods.
* Uses the stored Proc call SBREXT_COMMON_ROUTINES.GET_PUBLIC_ID(?)}
*
* @param dec
* dec bean object
*
* @return String public ID.
*/
public String getDECSysName(DEC_Bean dec) {
ResultSet rs = null;
PreparedStatement pstmt = null;
String sysName = "";
try {
String ocIDseq = dec.getDEC_OCL_IDSEQ();
String propIDseq = dec.getDEC_PROPL_IDSEQ();
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select SBREXT_COMMON_ROUTINES.GENERATE_DEC_PREFERRED_NAME(?,?) from DUAL");
pstmt.setString(1, ocIDseq); // oc idseq
pstmt.setString(2, propIDseq); // property idseq
rs = pstmt.executeQuery();
while (rs.next()) {
sysName = rs.getString(1);
}
if (sysName == null)
sysName = "";
if (sysName.equalsIgnoreCase("OC and PROP are null")
|| sysName.equalsIgnoreCase("Invalid Object")
|| sysName.equalsIgnoreCase("Invalid Property"))
sysName = "";
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getPublicID for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return sysName;
} // end getDEC system name
/**
* To get public id of an administerd component. Called from 'set' methods.
* Uses the stored Proc call SBREXT_COMMON_ROUTINES.GET_PUBLIC_ID(?)}
*
* @param ac_idseq
* unique id of an AC.
*
* @return String public ID.
*/
public String getPublicID(String ac_idseq) {
ResultSet rs = null;
PreparedStatement pstmt = null;
String sPublicID = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
pstmt = m_servlet
.getConn()
.prepareStatement(
"Select SBREXT_COMMON_ROUTINES.GET_PUBLIC_ID(?) from DUAL");
pstmt.setString(1, ac_idseq); // short name
rs = pstmt.executeQuery();
while (rs.next()) {
Integer iPublic = new Integer(rs.getInt(1));
sPublicID = iPublic.toString();
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-getPublicID for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
pstmt = SQLHelper.closePreparedStatement(pstmt);
}
return sPublicID;
} // end getPublicID
@SuppressWarnings("unchecked")
private void doAltVersionUpdate(String newAC, String oldAC) {
HttpSession session = m_classReq.getSession();
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes, m_servlet);
// first get the alt and ref for new version
Vector<ALT_NAME_Bean> vNewAlt = new Vector<ALT_NAME_Bean>();
Vector<ALT_NAME_Bean> vOldAlt = (Vector) session
.getAttribute("AllAltNameList");
// search if alt names exists before versioning
if (vOldAlt != null && vOldAlt.size() > 0)
vNewAlt = getAC.doAltNameSearch(newAC, "", "", "EditDesDE",
"Version");
// loop through the lists to find the old alt/ref matching ac and table
if (vNewAlt != null) {
for (int i = 0; i < vOldAlt.size(); i++) {
ALT_NAME_Bean thisAlt = (ALT_NAME_Bean) vOldAlt.elementAt(i);
String altAC = thisAlt.getAC_IDSEQ();
// udpate the idseq if found
if (altAC.equals(oldAC)) {
thisAlt.setAC_IDSEQ(newAC);
// find the matching altname, context, alttype in new list
// to get altidseq
String altName = thisAlt.getALTERNATE_NAME();
if (altName == null)
altName = "";
String altCont = thisAlt.getCONTE_IDSEQ();
if (altCont == null)
altCont = "";
String altType = thisAlt.getALT_TYPE_NAME();
if (altType == null)
altType = "";
for (int k = 0; k < vNewAlt.size(); k++) {
ALT_NAME_Bean newAlt = (ALT_NAME_Bean) vNewAlt
.elementAt(k);
String nName = newAlt.getALTERNATE_NAME();
if (nName == null)
nName = "";
String nCont = newAlt.getCONTE_IDSEQ();
if (nCont == null)
nCont = "";
String nType = newAlt.getALT_TYPE_NAME();
if (nType == null)
nType = "";
// replace it in the bean if found
// System.out.println(nType + " new alts " + nName);
if (nName.equals(altName) && altCont.equals(nCont)
&& altType.equals(nType)) {
String altID = newAlt.getALT_NAME_IDSEQ();
if (altID != null && !altID.equals(""))
thisAlt.setALT_NAME_IDSEQ(altID);
break;
}
}
// update the bean and vector
vOldAlt.setElementAt(thisAlt, i);
}
}
// set it back in the session
DataManager.setAttribute(session, "AllAltNameList", vOldAlt);
}
}
/**
* @param newAC
* @param oldAC
*/
@SuppressWarnings( { "unchecked", "unchecked" })
private void doRefVersionUpdate(String newAC, String oldAC) {
HttpSession session = m_classReq.getSession();
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes, m_servlet);
// first get the alt and ref for new version
Vector<REF_DOC_Bean> vNewRef = new Vector<REF_DOC_Bean>();
Vector<REF_DOC_Bean> vOldRef = (Vector) session
.getAttribute("AllRefDocList");
// search if Ref names exists before versioning
if (vOldRef != null && vOldRef.size() > 0)
vNewRef = getAC.doRefDocSearch(newAC, "ALL TYPES", "Version");
// loop through the lists to find the old Ref/ref matching ac and table
if (vNewRef != null) {
for (int i = 0; i < vOldRef.size(); i++) {
REF_DOC_Bean thisRef = (REF_DOC_Bean) vOldRef.elementAt(i);
String RefAC = thisRef.getAC_IDSEQ();
// udpate the idseq if found
if (RefAC.equals(oldAC)) {
thisRef.setAC_IDSEQ(newAC);
// find the matching Refname, context, Reftype in new list
// to get Refidseq
String RefName = thisRef.getDOCUMENT_NAME();
if (RefName == null)
RefName = "";
String RefCont = thisRef.getCONTE_IDSEQ();
if (RefCont == null)
RefCont = "";
String RefType = thisRef.getDOC_TYPE_NAME();
if (RefType == null)
RefType = "";
for (int k = 0; k < vNewRef.size(); k++) {
REF_DOC_Bean newRef = (REF_DOC_Bean) vNewRef
.elementAt(k);
String nName = newRef.getDOCUMENT_NAME();
if (nName == null)
nName = "";
String nCont = newRef.getCONTE_IDSEQ();
if (nCont == null)
nCont = "";
String nType = newRef.getDOC_TYPE_NAME();
if (nType == null)
nType = "";
// System.out.println(nType + " new ref " + nName);
// replace it in the bean if found
if (nName.equals(RefName) && RefCont.equals(nCont)
&& RefType.equals(nType)) {
String RefID = newRef.getREF_DOC_IDSEQ();
if (RefID != null && !RefID.equals("")) {
thisRef.setREF_DOC_IDSEQ(RefID);
}
break;
}
}
// update the bean and vector
vOldRef.setElementAt(thisRef, i);
}
}
// set it back in the session
DataManager.setAttribute(session, "AllRefDocList", vOldRef);
}
}
/**
* add revove alternate name attributes for the selected ac loops through
* the list of selected types and looks for the matching ac calls setDES to
* create or insert according to the submit action
*
* @param sDE
* unique id of an AC.
* @param deCont
* owned by context id of the ac.
* @param desAction
* String designation action
* @return return one alt name after designation
*/
public String doAddRemoveAltNames(String sDE, String deCont,
String desAction) {
String oneAltName = "";
try {
HttpSession session = m_classReq.getSession();
String sCont = m_classReq.getParameter("selContext");
if (sCont == null)
sCont = "";
Vector vAllAltName = (Vector) session
.getAttribute("AllAltNameList");
if (vAllAltName == null)
vAllAltName = new Vector();
for (int i = 0; i < vAllAltName.size(); i++) {
ALT_NAME_Bean altNameBean = (ALT_NAME_Bean) vAllAltName
.elementAt(i);
if (altNameBean == null)
altNameBean = new ALT_NAME_Bean();
String altAC = altNameBean.getAC_IDSEQ();
// new de from owning context
if (altAC == null || altAC.equals("") || altAC.equals("new")
|| desAction.equals("INS"))
altAC = sDE;
// System.out.println(sDE + " add alt names AC " + altAC);
// remove it only for matching ac
if (altAC != null && sDE.equals(altAC)) {
String altContID = altNameBean.getCONTE_IDSEQ();
// new context from owning context
if (altContID == null || altContID.equals("")
|| altContID.equals("new"))
altContID = deCont;
if (desAction.equals("remove") && altContID != null
&& sCont != null && altContID.equals(sCont))
altNameBean.setALT_SUBMIT_ACTION("DEL");
// get other attributes
String altID = altNameBean.getALT_NAME_IDSEQ();
String altType = altNameBean.getALT_TYPE_NAME();
String altSubmit = altNameBean.getALT_SUBMIT_ACTION();
String altName = altNameBean.getALTERNATE_NAME();
String altContext = altNameBean.getCONTEXT_NAME();
String altLang = altNameBean.getAC_LANGUAGE();
// mark the new ones ins or upd according to add or remove
if (altID == null || altID.equals("")
|| altID.equals("new")) {
if (desAction.equals("remove")
|| altSubmit.equals("DEL"))
altSubmit = "UPD"; // mark new one as update so
// that it won't create
else
altSubmit = "INS";
}
String ret = "";
if (!altSubmit.equals("UPD")) // call method to create
// alternate name in the
// database
ret = this.setDES(altSubmit, altAC, altContID,
altContext, altType, altName, altLang, altID);
}
}
// get one alt name for the AC after ins or del actions
oneAltName = this.getOneAltName(sDE);
} catch (Exception e) {
logger.error(
"ERROR in InsACService-addRemoveAltNames for exception : "
+ e.toString(), e);
}
return oneAltName;
} // end doAddRemoveAltNames
/**
* add revove reference documents attributes for the selected ac loops
* through the list of selected types and looks for the matching ac calls
* setRD to create or insert according to the submit action
*
* @param sDE
* unique id of an AC.
* @param deCont
* owned by context id of the ac.
* @param desAction
* designation action
* @return String retun one ref doc
*/
public String doAddRemoveRefDocs(String sDE, String deCont, String desAction) {
String oneRD = "";
try {
HttpSession session = m_classReq.getSession();
String sCont = m_classReq.getParameter("selContext");
if (sCont == null)
sCont = "";
// get reference doc attributes
Vector vAllRefDoc = (Vector) session.getAttribute("AllRefDocList");
if (vAllRefDoc == null)
vAllRefDoc = new Vector();
for (int i = 0; i < vAllRefDoc.size(); i++) {
REF_DOC_Bean refDocBean = (REF_DOC_Bean) vAllRefDoc
.elementAt(i);
if (refDocBean == null)
refDocBean = new REF_DOC_Bean();
String refAC = refDocBean.getAC_IDSEQ();
// new de from owning context
if (refAC == null || refAC.equals("") || refAC.equals("new")
|| desAction.equals("INS"))
refAC = sDE;
if (refAC != null && sDE.equals(refAC)) {
// mark the all its alt names to be deleted if action is to
// undesignate
String refContID = refDocBean.getCONTE_IDSEQ();
// new context from owning context
if (refContID == null || refContID.equals("")
|| refContID.equals("new"))
refContID = deCont;
// System.out.println(deCont + " add refdocs context " +
// refContID);
if (desAction.equals("remove") && refContID != null
&& sCont != null && refContID.equals(sCont))
refDocBean.setREF_SUBMIT_ACTION("DEL");
String refID = refDocBean.getREF_DOC_IDSEQ();
String refType = refDocBean.getDOC_TYPE_NAME();
String refName = refDocBean.getDOCUMENT_NAME();
String refText = refDocBean.getDOCUMENT_TEXT();
String refURL = refDocBean.getDOCUMENT_URL();
String refSubmit = refDocBean.getREF_SUBMIT_ACTION();
String refContext = refDocBean.getCONTEXT_NAME();
String refLang = refDocBean.getAC_LANGUAGE();
if (refID == null || refID.equals("")
|| refID.equals("new")) {
if (desAction.equals("remove")
|| refSubmit.equals("DEL"))
refSubmit = "UPD"; // mark new one as update so
// that it won't create
else
refSubmit = "INS";
}
// check if creating used by in the same context as created
String ret = "";
if (!refSubmit.equals("UPD")) // call method to create
// reference documents in
// the database
{
// delete teh reference blobs before deleting the RD
if (refSubmit.equals("DEL")) {
RefDocAttachment RDAclass = new RefDocAttachment(
m_classReq, m_classRes, m_servlet);
String sMsg = RDAclass
.doDeleteAllAttachments(refID);
if (sMsg != null && !sMsg.equals(""))
this.storeStatusMsg("\\t" + sMsg);
}
// System.out.println(refName + " rd idseq " + refID);
ret = this.setRD(refSubmit, refName, refAC, refText,
refType, refURL, refContID, refID, refLang);
}
}
}
oneRD = this.getOneRDName(sDE); // get the one rd name for the ac
} catch (Exception e) {
logger.error(
"ERROR in InsACService-addRemoveRefDocs for exception : "
+ e.toString(), e);
}
return oneRD;
} // end doAddRemoveAltNames
/***************************************************************************
* / takes the thesaurus concept if meta was selected
*
* @param evsBean
* EVS_Bean of the selected concept
* @return EVS_Bean
*/
/*
* public EVS_Bean takeThesaurusConcept(EVS_Bean evsBean) { HttpSession
* session = m_classReq.getSession(); String sConceptName =
* evsBean.getLONG_NAME(); String sContextID = evsBean.getCONTE_IDSEQ(); //
* sConceptName = filterName(sConceptName, "js"); String sConceptDefinition =
* evsBean.getPREFERRED_DEFINITION(); if(sConceptDefinition.length()>30)
* sConceptDefinition = sConceptDefinition.substring(5,30); else
* if(sConceptDefinition.length()>20) sConceptDefinition =
* sConceptDefinition.substring(5,20); else
* if(sConceptDefinition.length()>15) sConceptDefinition =
* sConceptDefinition.substring(5,15); String sDefinition = ""; String sName =
* ""; try { GetACSearch getAC = new GetACSearch(m_classReq, m_classRes,
* m_servlet); EVSSearch evs = new EVSSearch(m_classReq, m_classRes,
* m_servlet); Vector vAC = new Vector(); DataManager.setAttribute(session,
* "creKeyword", sConceptName); //store it in the session before calling vAC =
* evs.doVocabSearch(vAC, sConceptName, "NCI_Thesarus", "Synonym", "", "",
* "Exclude", "", 100, false, -1, ""); // evs.do_EVSSearch(sConceptName,
* vAC, "NCI_Thesaurus", "Synonym", // "All Sources", 100, "termThesOnly",
* "Exclude", sContextID, -1); for(int i=0; i<(vAC.size()); i++) { EVS_Bean
* OCBean = new EVS_Bean(); OCBean = (EVS_Bean)vAC.elementAt(i); sName =
* OCBean.getLONG_NAME(); String sDefSource = OCBean.getEVS_DEF_SOURCE();
* String sConSource = OCBean.getEVS_CONCEPT_SOURCE(); sDefinition =
* OCBean.getPREFERRED_DEFINITION(); if(sDefinition.length()>30) sDefinition =
* sDefinition.substring(5,30); else if(sDefinition.length()>20) sDefinition =
* sDefinition.substring(5,20); else if(sDefinition.length()>15) sDefinition =
* sDefinition.substring(5,15); if(sName.equalsIgnoreCase(sConceptName)) {
* if(sDefinition.equalsIgnoreCase(sConceptDefinition)) return OCBean; } } }
* catch(Exception e) { logger.error("ERROR in
* InsACService-takeThesaurusConcep for other : " + e.toString()); } return
* evsBean; }
*/
/***************************************************************************
* / Puts in and takes out "_"
*
* @param String
* nodeName.
* @param String
* type.
*/
/*
* private final String filterName(String nodeName, String type) {
* if(type.equals("display")) nodeName = nodeName.replaceAll("_"," "); else
* if(type.equals("js")) nodeName = nodeName.replaceAll(" ","_"); return
* nodeName; }
*/
/**
* To insert a new concept from evs to cadsr. Gets all the attribute values
* from the bean, sets in parameters, and registers output parameter. Calls
* oracle stored procedure "{call
* SBREXT_Set_Row.SET_CONCEPT(?,?,?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sAction
* Insert or update Action.
* @param sReturnCode
* string oracle error code
* @param evsBean
* EVS_Bean.
*
* @return String concept idseq from the table.
*/
public String setConcept(String sAction, String sReturnCode,
EVS_Bean evsBean) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String conIdseq = "";
try {
// If the concept is from Metathesaurus, try to take it from
// Thesaurus
/*
* if(evsBean != null && evsBean.getEVS_DATABASE() != null) {
* if(evsBean.getEVS_DATABASE().equals("NCI Metathesaurus")) {
* sEvsSource = evsBean.getEVS_DEF_SOURCE(); if(sEvsSource == null)
* sEvsSource = ""; if(sEvsSource.equalsIgnoreCase("NCI-Gloss") ||
* sEvsSource.equalsIgnoreCase("NCI04")) evsBean =
* takeThesaurusConcept(evsBean); logger.info("after takeThes " +
* evsBean.getCONCEPT_IDENTIFIER()); } }
*/
// return the concept id if the concept alredy exists in caDSR.
conIdseq = this.getConcept(sReturnCode, evsBean, false);
if (conIdseq == null || conIdseq.equals("")) {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
// cstmt = conn.prepareCall("{call
// SBREXT_SET_ROW.SET_CONCEPT(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_CONCEPT(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
// register the Out parameters
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // con
// idseq
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // preferred
// name
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // long
// name
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // prefered
// definition
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // context
// idseq
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // version
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // asl
// name
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // latest
// version
// ind
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // change
// note
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // origin
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // definition
// source
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // evs
// source
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // begin
// date
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // end
// date
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // created
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // modified
cstmt.registerOutParameter(22, java.sql.Types.VARCHAR); // deleted
// ind
// truncate the definition to be 2000 long.
String sDef = evsBean.getPREFERRED_DEFINITION();
// if (sDef == null) sDef = "";
// if (sDef.length() > 2000) sDef = sDef.substring(0, 2000);
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
cstmt.setString(3, sAction);
cstmt.setString(5, evsBean.getCONCEPT_IDENTIFIER());
// make sure that :: is removed from the long name
String sName = evsBean.getLONG_NAME();
int nvpInd = sName.indexOf("::");
if (nvpInd > 0)
sName = sName.substring(0, nvpInd);
nvpInd = sDef.indexOf("::");
if (nvpInd > 0)
sDef = sDef.substring(0, nvpInd);
cstmt.setString(6, sName);
cstmt.setString(7, sDef);
// cstmt.setString(7, evsBean.getCONTE_IDSEQ()); caBIG by
// default
cstmt.setString(9, "1.0");
cstmt.setString(10, "RELEASED");
cstmt.setString(11, "Yes");
cstmt.setString(13, evsBean.getEVS_DATABASE());
cstmt.setString(14, evsBean.getEVS_DEF_SOURCE());
cstmt.setString(15, evsBean.getNCI_CC_TYPE());
// Now we are ready to call the stored procedure
// logger.info("setConcept " +
// evsBean.getCONCEPT_IDENTIFIER());
cstmt.execute();
sReturnCode = cstmt.getString(2);
conIdseq = cstmt.getString(4);
evsBean.setIDSEQ(conIdseq);
if (sReturnCode != null) {
this.storeStatusMsg("\\t " + sReturnCode
+ " : Unable to update Concept attributes - "
+ evsBean.getCONCEPT_IDENTIFIER() + ": "
+ evsBean.getLONG_NAME() + ".");
m_classReq.setAttribute("retcode", sReturnCode); // store
// returncode
// request
// track
// all
// through
// this
// request
}
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService-setConcept for other : "
+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception : Unable to update Concept attributes.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return conIdseq;
} // end concept
/**
* Called to check if the concept exists in teh database already. Sets in
* parameters, and registers output parameters and returns concept id of
* found one. Calls oracle stored procedure "{call
* SBREXT_GET_ROW.GET_CON(?,?,?,?,?,?,?,?,?,?,?,?,?)}" to submit
*
* @param sReturn
* return code to catpure errors if any
* @param evsBean
* EVS_Bean.
* @param bValidateConceptCodeUnique
* boolean to check if unique
*
* @return String con_idseq from the stored procedure call.
*/
public String getConcept(String sReturn, EVS_Bean evsBean,
boolean bValidateConceptCodeUnique) {
ResultSet rs = null;
String sCON_IDSEQ = "";
CallableStatement cstmt = null;
try {
HttpSession session = (HttpSession) m_classReq.getSession();
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_GET_ROW.GET_CON(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(1, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // con
// idseq
cstmt.registerOutParameter(3, java.sql.Types.VARCHAR); // preferred
// name
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // context
// idseq
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // version
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // prefered
// definition
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR); // long
// name
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // asl
// name
cstmt.registerOutParameter(9, java.sql.Types.VARCHAR); // definition
// source
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // latest
// version
// ind
cstmt.registerOutParameter(11, java.sql.Types.VARCHAR); // evs
// source
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // CON
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // origin
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // begin
// date
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // end
// date
cstmt.registerOutParameter(16, java.sql.Types.VARCHAR); // change
// note
cstmt.registerOutParameter(17, java.sql.Types.VARCHAR); // created
cstmt.registerOutParameter(18, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(19, java.sql.Types.VARCHAR); // modified
cstmt.registerOutParameter(20, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(21, java.sql.Types.VARCHAR); // deleted
// ind
cstmt.setString(2, evsBean.getIDSEQ()); // con idseq
cstmt.setString(3, evsBean.getCONCEPT_IDENTIFIER()); // concept
// code
// Now we are ready to call the stored procedure
cstmt.execute();
sCON_IDSEQ = (String) cstmt.getObject(2);
evsBean.setIDSEQ(sCON_IDSEQ);
sReturn = (String) cstmt.getObject(1);
if (sReturn == null || sReturn.equals("")) {
// Sometimes we use this method to validate a concept code
// is unique across databases
if (bValidateConceptCodeUnique == true) {
String dbOrigin = (String) cstmt.getObject(13);
String evsOrigin = evsBean.getEVS_DATABASE();
if (evsOrigin.equals(EVSSearch.META_VALUE)) // "MetaValue"))
evsOrigin = evsBean.getEVS_ORIGIN();
if (dbOrigin != null && evsOrigin != null
&& !dbOrigin.equals(evsOrigin)) {
sCON_IDSEQ = "Another Concept Exists in caDSR with same Concept Code "
+ evsBean.getCONCEPT_IDENTIFIER()
+ ", but in a different Vocabulary ("
+ dbOrigin
+ "). New concept therefore cannot be created. Please choose another concept. <br>";
}
} else {
String dbOrigin = (String) cstmt.getObject(13);
EVS_UserBean eUser = (EVS_UserBean) m_servlet.sessionData.EvsUsrBean; // (EVS_UserBean)session.getAttribute(EVSSearch.EVS_USER_BEAN_ARG);
// //("EvsUserBean");
if (eUser == null)
eUser = new EVS_UserBean();
String sDef = (String) cstmt.getObject(6);
if (sDef == null || sDef.equals(""))
sDef = eUser.getDefDefaultValue();
EVS_Bean vmConcept = new EVS_Bean();
String evsOrigin = vmConcept.getVocabAttr(eUser,
dbOrigin, EVSSearch.VOCAB_DBORIGIN,
EVSSearch.VOCAB_NAME); // "vocabDBOrigin",
evsBean.setEVSBean(sDef, (String) cstmt.getObject(9),
(String) cstmt.getObject(7), (String) cstmt
.getObject(7), (String) cstmt
.getObject(11), (String) cstmt
.getObject(3), evsOrigin, dbOrigin, 0,
"", (String) cstmt.getObject(4), "",
(String) cstmt.getObject(8), "", "", "");
evsBean.markNVPConcept(evsBean, session); // store
// name
// value
// pair
}
}
}
} catch (Exception e) {
logger.error("ERROR in InsACService- getConcept for exception : "
+ e.toString(), e);
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return sCON_IDSEQ; // TODO check what is parent concept id
} // end get concept
/**
* handles add remove actionof the vd.
*
* @param vd
* page vd bean
* @return string comma delimited conidseqs or remove parent string
* @throws java.lang.Exception
*/
private String setEVSParentConcept(VD_Bean vd) throws Exception {
Vector<EVS_Bean> vParentCon = vd.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept");
if (vParentCon == null)
vParentCon = new Vector<EVS_Bean>();
String sVDParent = "", sVDCondr = "";
for (int m = 0; m < vParentCon.size(); m++) {
sVDCondr = vd.getVD_PAR_CONDR_IDSEQ();
EVS_Bean parBean = (EVS_Bean) vParentCon.elementAt(m);
// if not deleted, create and append them one by one
if (parBean != null) {
// handle the only evs parent
if (parBean.getEVS_DATABASE() == null)
logger
.error("setEVSParentConcept - parent why database null?");
else if (!parBean.getEVS_DATABASE().equals("Non_EVS")) {
if (!parBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
String sRet = "";
parBean.setCONTE_IDSEQ(vd.getVD_CONTE_IDSEQ());
String conIDseq = parBean.getIDSEQ();
// create it only if doesn't exist
if (conIDseq == null || conIDseq.equals(""))
conIDseq = this.setConcept("INS", sRet, parBean);
if (conIDseq != null && !conIDseq.equals("")) {
parBean.setIDSEQ(conIDseq);
vParentCon.setElementAt(parBean, m);
if (sVDParent.equals(""))
sVDParent = conIDseq;
else
sVDParent = sVDParent + "," + conIDseq;
}
} else if (sVDCondr == null)
sVDCondr = parBean.getCONDR_IDSEQ();
if (parBean.getCON_AC_SUBMIT_ACTION().equals("DEL")) {
if (parBean.getEVS_DATABASE() != null
&& parBean.getEVS_DATABASE().equals(
"NCI Metathesaurus"))
doRemoveMetaParentRefDoc(vd, parBean);
}
}
}
}
vd.setReferenceConceptList(vParentCon);
if (sVDParent.equals("") && sVDCondr != null && !sVDCondr.equals(""))
sVDParent = "removeParent";
return sVDParent;
} // end evs parent concept
/**
* removes the meta parent concept filter source from reference documents
*
* @param vd
* page vd bean
* @param parBean
* selected meta parent bean
* @throws java.lang.Exception
*/
private void doRemoveMetaParentRefDoc(VD_Bean vd, EVS_Bean parBean)
throws Exception {
String sCont = vd.getVD_CONTE_IDSEQ();
String sACid = vd.getVD_VD_IDSEQ();
String sCuiVal = parBean.getCONCEPT_IDENTIFIER();
String rdIDseq = "";
String sMetaSource = parBean.getEVS_CONCEPT_SOURCE();
if (sMetaSource == null)
sMetaSource = "";
String sRDMetaCUI = "";
GetACSearch getAC = new GetACSearch(m_classReq, m_classRes, m_servlet);
Vector vRef = getAC.doRefDocSearch(vd.getVD_VD_IDSEQ(),
"META_CONCEPT_SOURCE", "open");
Vector vList = (Vector) m_classReq.getAttribute("RefDocList");
if (vList != null && vList.size() > 0) {
for (int i = 0; i < vList.size(); i++) {
REF_DOC_Bean RDBean = (REF_DOC_Bean) vList.elementAt(i);
// copy rd attributes to evs attribute
if (RDBean != null && RDBean.getDOCUMENT_NAME() != null
&& !RDBean.getDOCUMENT_NAME().equals("")) {
sRDMetaCUI = RDBean.getDOCUMENT_TEXT();
if (sRDMetaCUI.equals(sCuiVal))
rdIDseq = RDBean.getREF_DOC_IDSEQ();
}
}
}
String sAction = parBean.getCON_AC_SUBMIT_ACTION();
if (sAction == null || sAction.equals(""))
sAction = "INS";
String sRet = "";
String sLang = "ENGLISH";
if (rdIDseq != null && !rdIDseq.equals("")) {
sRet = this.setRD("DEL", sMetaSource, sACid, sCuiVal,
"META_CONCEPT_SOURCE", "", sCont, rdIDseq, sLang);
}
}
/**
* creates non evs parents
*
* @param vd
* current VD_Bean
* @return returns success message
* @throws java.lang.Exception
*/
@SuppressWarnings("unchecked")
private String setNonEVSParentConcept(VD_Bean vd) throws Exception {
HttpSession session = m_classReq.getSession();
Vector vParentCon = vd.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept");
if (vParentCon == null)
vParentCon = new Vector();
String sRet = "";
String sLang = "ENGLISH";
for (int m = 0; m < vParentCon.size(); m++) {
EVS_Bean parBean = (EVS_Bean) vParentCon.elementAt(m);
// if not deleted, create and append them one by one
if (parBean != null) {
// handle the add/remove of non evs parent
if (parBean.getEVS_DATABASE() == null)
logger.error("setNonEVSParentConcept - why no database?");
else if (parBean.getEVS_DATABASE().equals("Non_EVS")) {
String sCont = vd.getVD_CONTE_IDSEQ();
String sACid = vd.getVD_VD_IDSEQ();
String sName = parBean.getLONG_NAME();
String sDoc = parBean.getPREFERRED_DEFINITION();
String sType = parBean.getCONCEPT_IDENTIFIER();
String sURL = parBean.getEVS_DEF_SOURCE();
String rdIDseq = parBean.getIDSEQ();
String sAction = parBean.getCON_AC_SUBMIT_ACTION();
if (sAction == null || sAction.equals(""))
sAction = "INS";
// do not delete if not existed in cadsr already
if (sAction.equals("DEL")
&& (rdIDseq == null || rdIDseq.equals("")))
continue;
// mark it to delete to be deleted later with all other
// reference documents to avoid duplicate deletion.
if (sAction.equals("DEL")) {
Vector<REF_DOC_Bean> vRefDocs = (Vector) session
.getAttribute("AllRefDocList");
for (int i = 0; i < vRefDocs.size(); i++) {
REF_DOC_Bean rBean = (REF_DOC_Bean) vRefDocs
.elementAt(i);
String refID = rBean.getREF_DOC_IDSEQ();
if (refID != null
&& refID.equalsIgnoreCase(rdIDseq)) {
rBean.setREF_SUBMIT_ACTION("DEL");
vRefDocs.setElementAt(rBean, i);
DataManager.setAttribute(session,
"AllRefDocList", vRefDocs);
break;
}
}
} else if (!sAction.equals("UPD"))
sRet = this.setRD(sAction, sName, sACid, sDoc, sType,
sURL, sCont, rdIDseq, sLang);
}
}
}
return sRet;
} // non evs parent concept
/**
* creates filtered concept source for the meta parent
*
* @param vd
* VD_Bean
* @return string success message
* @throws java.lang.Exception
*/
private String setRDMetaConceptSource(VD_Bean vd) throws Exception {
// HttpSession session = m_classReq.getSession();
Vector vParentCon = vd.getReferenceConceptList(); // (Vector)session.getAttribute("VDParentConcept");
if (vParentCon == null)
vParentCon = new Vector();
String sRet = "";
for (int m = 0; m < vParentCon.size(); m++) {
EVS_Bean parBean = (EVS_Bean) vParentCon.elementAt(m);
// if not deleted, create and append them one by one
if (parBean != null) {
// handle the add/remove of non evs parent
if (parBean.getEVS_DATABASE() == null)
logger.error("setRDMetaConceptSource - why no database?");
else if (parBean.getEVS_DATABASE() != null
&& parBean.getEVS_DATABASE()
.equals("NCI Metathesaurus")) {
String sCont = vd.getVD_CONTE_IDSEQ();
String sACid = vd.getVD_VD_IDSEQ();
String sCuiVal = parBean.getCONCEPT_IDENTIFIER();
String sMetaSource = parBean.getEVS_CONCEPT_SOURCE();
if (sMetaSource == null)
sMetaSource = "";
String rdIDseq = null; // parBean.getIDSEQ();
String sAction = parBean.getCON_AC_SUBMIT_ACTION();
if (sAction == null || sAction.equals(""))
sAction = "INS";
String sLang = "ENGLISH";
if (sAction.equals("INS") && !sMetaSource.equals("")
&& !sMetaSource.equals("All Sources")
&& !sCuiVal.equals("")) {
sRet = this.setRD("INS", sMetaSource, sACid, sCuiVal,
"META_CONCEPT_SOURCE", "", sCont, rdIDseq,
sLang);
}
}
}
}
return sRet;
} // non evs parent concept
// store the contact related info into the database
private Hashtable<String, AC_CONTACT_Bean> addRemoveAC_Contacts(
Hashtable<String, AC_CONTACT_Bean> hConts, String acID, String acAct) {
try {
// loop through the contacts in the hash table
if (hConts != null) {
Enumeration enum1 = hConts.keys();
while (enum1.hasMoreElements()) {
String sName = (String) enum1.nextElement();
AC_CONTACT_Bean acc = (AC_CONTACT_Bean) hConts.get(sName);
if (acc == null)
acc = new AC_CONTACT_Bean();
String conSubmit = acc.getACC_SUBMIT_ACTION();
if (conSubmit == null || conSubmit.equals(""))
conSubmit = "INS";
// for new version or new AC, make it a new record if not
// deleted
if (acAct.equalsIgnoreCase("Version")
|| acAct.equalsIgnoreCase("New")) {
if (conSubmit.equals("DEL"))
conSubmit = "NONE"; // do not add the deleted ones
else
conSubmit = "INS";
}
// check if contact attributes has changed
if (!conSubmit.equals("NONE")) {
acc.setAC_IDSEQ(acID);
acc.setACC_SUBMIT_ACTION(conSubmit);
String sOrgID = acc.getORG_IDSEQ();
String sPerID = acc.getPERSON_IDSEQ();
// call method to do contact comm updates
Vector<AC_COMM_Bean> vComms = acc.getACC_COMM_List();
if (vComms != null)
acc.setACC_COMM_List(this.setContact_Comms(vComms,
sOrgID, sPerID));
// call method to do contact addr update
Vector<AC_ADDR_Bean> vAddrs = acc.getACC_ADDR_List();
if (vAddrs != null)
acc.setACC_ADDR_List(this.setContact_Addrs(vAddrs,
sOrgID, sPerID));
// call method to do contact attribute updates
acc = this.setAC_Contact(acc);
hConts.put(sName, acc);
}
}
}
} catch (Exception e) {
logger.error("Error - setAC_Contacts : " + e.toString(), e);
}
return hConts;
}
private Vector<AC_COMM_Bean> setContact_Comms(Vector<AC_COMM_Bean> vCom,
String orgID, String perID) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
for (int i = 0; i < vCom.size(); i++) {
try {
AC_COMM_Bean comBean = (AC_COMM_Bean) vCom.elementAt(i);
String sAction = "INS";
if (comBean != null)
sAction = comBean.getCOMM_SUBMIT_ACTION();
if (!sAction.equals("NONE")) {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_CONTACT_COMM(?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_CONTACT_COMM(?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(2,
java.sql.Types.VARCHAR); // return code
cstmt.registerOutParameter(4,
java.sql.Types.VARCHAR); // comm idseq
cstmt.registerOutParameter(5,
java.sql.Types.VARCHAR); // org idseq
cstmt.registerOutParameter(6,
java.sql.Types.VARCHAR); // per idseq
cstmt.registerOutParameter(7,
java.sql.Types.VARCHAR); // ctlname
cstmt.registerOutParameter(8,
java.sql.Types.VARCHAR); // rank order
cstmt.registerOutParameter(9,
java.sql.Types.VARCHAR); // cyber address
cstmt.registerOutParameter(10, java.sql.Types.DATE); // .VARCHAR);
// //created
cstmt.registerOutParameter(11,
java.sql.Types.VARCHAR); // date created
cstmt.registerOutParameter(12, java.sql.Types.DATE); // .VARCHAR);
// //modified
cstmt.registerOutParameter(13,
java.sql.Types.VARCHAR); // date modified
// Set the In parameters (which are inherited from
// the PreparedStatement class)
// Get the username from the session.
String userName = (String) session
.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
if ((sAction.equals("UPD"))
|| (sAction.equals("DEL"))) {
if ((comBean.getAC_COMM_IDSEQ() != null)
&& (!comBean.getAC_COMM_IDSEQ().equals(
"")))
cstmt.setString(4, comBean
.getAC_COMM_IDSEQ()); // comm
// idseq if
// updated
else
sAction = "INS"; // INSERT A NEW RECORD
// IF NOT EXISTED
}
cstmt.setString(3, sAction); // ACTION - INS, UPD
// or DEL
cstmt.setString(5, orgID); // org idseq
cstmt.setString(6, perID); // per idseq
cstmt.setString(7, comBean.getCTL_NAME()); // selected
// comm
// type
cstmt.setString(8, comBean.getRANK_ORDER()); // rank
// order
// for
// the
// comm
cstmt.setString(9, comBean.getCYBER_ADDR()); // comm
// value
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(2);
if (sReturnCode != null && !sReturnCode.equals(""))
// !sReturnCode.equals("API_OC_500"))
{
String comName = comBean.getCTL_NAME() + "_"
+ comBean.getRANK_ORDER() + "_"
+ comBean.getCYBER_ADDR();
this
.storeStatusMsg(sReturnCode
+ " : Unable to update contact communication - "
+ comName);
m_classReq.setAttribute("retcode", sReturnCode);
} else {
comBean.setAC_COMM_IDSEQ(cstmt.getString(4));
comBean.setCOMM_SUBMIT_ACTION("NONE");
vCom.setElementAt(comBean, i);
}
}
} catch (Exception ee) {
logger.error(
"ERROR in InsACService-setContact_Comms for bean : "
+ ee.toString(), ee);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception ee : Unable to update or remove Communication attributes.");
continue; // continue with other ones
}
}
}
} catch (Exception e) {
logger.error("Error - setContact_Comms : " + e.toString(), e);
}
finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return vCom;
}
private Vector<AC_ADDR_Bean> setContact_Addrs(Vector<AC_ADDR_Bean> vAdr,
String orgID, String perID) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
for (int i = 0; i < vAdr.size(); i++) {
try {
AC_ADDR_Bean adrBean = (AC_ADDR_Bean) vAdr.elementAt(i);
String sAction = "INS";
if (adrBean != null)
sAction = adrBean.getADDR_SUBMIT_ACTION();
if (!sAction.equals("NONE")) {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_CONTACT_ADDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_CONTACT_ADDR(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(2,
java.sql.Types.VARCHAR); // return code
cstmt.registerOutParameter(4,
java.sql.Types.VARCHAR); // addr idseq
cstmt.registerOutParameter(5,
java.sql.Types.VARCHAR); // org idseq
cstmt.registerOutParameter(6,
java.sql.Types.VARCHAR); // per idseq
cstmt.registerOutParameter(7,
java.sql.Types.VARCHAR); // atlname
cstmt.registerOutParameter(8,
java.sql.Types.VARCHAR); // rank order
cstmt.registerOutParameter(9,
java.sql.Types.VARCHAR); // address line
cstmt.registerOutParameter(10,
java.sql.Types.VARCHAR); // address line
cstmt.registerOutParameter(11,
java.sql.Types.VARCHAR); // city
cstmt.registerOutParameter(12,
java.sql.Types.VARCHAR); // state
cstmt.registerOutParameter(13,
java.sql.Types.VARCHAR); // postal code
cstmt.registerOutParameter(14,
java.sql.Types.VARCHAR); // country
cstmt.registerOutParameter(15, java.sql.Types.DATE); // .VARCHAR);
// //created
cstmt.registerOutParameter(16,
java.sql.Types.VARCHAR); // date created
cstmt.registerOutParameter(17, java.sql.Types.DATE); // .VARCHAR);
// //modified
cstmt.registerOutParameter(18,
java.sql.Types.VARCHAR); // date modified
// Set the In parameters (which are inherited from
// the PreparedStatement class)
// Get the username from the session.
String userName = (String) session
.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
if ((sAction.equals("UPD"))
|| (sAction.equals("DEL"))) {
if ((adrBean.getAC_ADDR_IDSEQ() != null)
&& (!adrBean.getAC_ADDR_IDSEQ().equals(
"")))
cstmt.setString(4, adrBean
.getAC_ADDR_IDSEQ()); // comm
// idseq if
// updated
else
sAction = "INS"; // INSERT A NEW RECORD
// IF NOT EXISTED
}
cstmt.setString(3, sAction); // ACTION - INS, UPD
// or DEL
cstmt.setString(5, orgID); // org idseq
cstmt.setString(6, perID); // per idseq
cstmt.setString(7, adrBean.getATL_NAME()); // selected
// addr
// type
cstmt.setString(8, adrBean.getRANK_ORDER()); // rank
// order
// for
// the
// addr
cstmt.setString(9, adrBean.getADDR_LINE1()); // addr
// line
String A2 = adrBean.getADDR_LINE2();
if (A2 == null || A2.equals(""))
A2 = " ";
cstmt.setString(10, A2); // addr line 2
cstmt.setString(11, adrBean.getCITY()); // city
cstmt.setString(12, adrBean.getSTATE_PROV()); // state
cstmt.setString(13, adrBean.getPOSTAL_CODE()); // zip
// code
String Ct = adrBean.getCOUNTRY();
if (Ct == null || Ct.equals(""))
Ct = " ";
cstmt.setString(14, Ct); // country
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(2);
if (sReturnCode != null && !sReturnCode.equals(""))
// !sReturnCode.equals("API_OC_500"))
{
String adrName = adrBean.getATL_NAME() + "_"
+ adrBean.getRANK_ORDER() + "_"
+ adrBean.getADDR_LINE1();
this
.storeStatusMsg(sReturnCode
+ " : Unable to update contact address - "
+ adrName);
m_classReq.setAttribute("retcode", sReturnCode);
} else {
adrBean.setAC_ADDR_IDSEQ(cstmt.getString(4));
adrBean.setADDR_SUBMIT_ACTION("NONE");
vAdr.setElementAt(adrBean, i);
}
}
} catch (Exception ee) {
logger.error(
"ERROR in InsACService-setContact_Addrs for bean : "
+ ee.toString(), ee);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception ee : Unable to update or remove Address attributes.");
continue; // continue with other ones
}
}
}
} catch (Exception e) {
logger.error("Error - setContact_Addrs : " + e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception ee : Unable to update or remove Address attributes.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return vAdr;
}
private AC_CONTACT_Bean setAC_Contact(AC_CONTACT_Bean accB) {
ResultSet rs = null;
CallableStatement cstmt = null;
HttpSession session = m_classReq.getSession();
String sReturnCode = "";
try {
if (m_servlet.getConn() == null)
m_servlet.ErrorLogin(m_classReq, m_classRes);
else {
String sAction = accB.getACC_SUBMIT_ACTION();
if (sAction == null || sAction.equals(""))
sAction = "INS";
if (!sAction.equals("NONE")) {
// cstmt = conn.prepareCall("{call
// SBREXT_Set_Row.SET_AC_CONTACT(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt = m_servlet
.getConn()
.prepareCall(
"{call SBREXT_SET_ROW.SET_AC_CONTACT(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)}");
cstmt.registerOutParameter(2, java.sql.Types.VARCHAR); // return
// code
cstmt.registerOutParameter(4, java.sql.Types.VARCHAR); // comm
// idseq
cstmt.registerOutParameter(5, java.sql.Types.VARCHAR); // org
// idseq
cstmt.registerOutParameter(6, java.sql.Types.VARCHAR); // per
// idseq
cstmt.registerOutParameter(7, java.sql.Types.VARCHAR);
// idseq
cstmt.registerOutParameter(8, java.sql.Types.VARCHAR); // rank
// order
cstmt.registerOutParameter(9, java.sql.Types.DATE); // .VARCHAR);
// //created
cstmt.registerOutParameter(10, java.sql.Types.VARCHAR); // date
// created
cstmt.registerOutParameter(11, java.sql.Types.DATE); // .VARCHAR);
// //modified
cstmt.registerOutParameter(12, java.sql.Types.VARCHAR); // date
// modified
cstmt.registerOutParameter(13, java.sql.Types.VARCHAR); // p_cscsi_idseq
cstmt.registerOutParameter(14, java.sql.Types.VARCHAR); // p_csi_idseq
cstmt.registerOutParameter(15, java.sql.Types.VARCHAR); // p_contact
// role
// Set the In parameters (which are inherited from the
// PreparedStatement class)
// Get the username from the session.
String userName = (String) session.getAttribute("Username");
cstmt.setString(1, userName); // set ua_name
if ((sAction.equals("UPD")) || (sAction.equals("DEL"))) {
if ((accB.getAC_CONTACT_IDSEQ() != null)
&& (!accB.getAC_CONTACT_IDSEQ().equals("")))
cstmt.setString(4, accB.getAC_CONTACT_IDSEQ()); // acc
// idseq
// updated
else
sAction = "INS"; // INSERT A NEW RECORD IF NOT
// EXISTED
}
cstmt.setString(3, sAction); // ACTION - INS, UPD or DEL
cstmt.setString(5, accB.getORG_IDSEQ()); // org idseq
cstmt.setString(6, accB.getPERSON_IDSEQ()); // per idseq
cstmt.setString(7, accB.getAC_IDSEQ()); // ac idseq
cstmt.setString(8, accB.getRANK_ORDER()); // rank order
cstmt.setString(15, accB.getCONTACT_ROLE()); // contact
// role
// Now we are ready to call the stored procedure
cstmt.execute();
sReturnCode = cstmt.getString(2);
if (sReturnCode != null && !sReturnCode.equals(""))
// !sReturnCode.equals("API_OC_500"))
{
String accName = accB.getORG_NAME();
if (accName == null || accName.equals(""))
accName = accB.getPERSON_NAME();
this.storeStatusMsg(sReturnCode
+ " : Unable to update contact attributes - "
+ accName);
m_classReq.setAttribute("retcode", sReturnCode);
} else {
accB.setAC_CONTACT_IDSEQ(cstmt.getString(4));
accB.setACC_SUBMIT_ACTION("NONE");
}
}
}
} catch (Exception e) {
logger.error("Error - setAC_Contact : " + e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this
.storeStatusMsg("\\t Exception ee : Unable to update or remove contact attributes.");
}finally{
rs = SQLHelper.closeResultSet(rs);
cstmt = SQLHelper.closeCallableStatement(cstmt);
}
return accB;
}
public ArrayList getConBeanList(Vector evsBean, boolean isAllConceptsExists){
ArrayList<ConBean> conBeanList = new ArrayList();
if (evsBean != null){
int display_order = evsBean.size() - 1;
for (int i = 1; i < evsBean.size(); i++) {
EVS_Bean ocBean = (EVS_Bean) evsBean.elementAt(i);
String conIdseq = ocBean.getIDSEQ();
if((!isAllConceptsExists) && (conIdseq == null || conIdseq.equals(""))){
conIdseq = this.setConcept("INS", "", ocBean);
}
if (conIdseq != null || conIdseq.equals("")) {
ConBean conBean = new ConBean();
conBean.setCon_IDSEQ(conIdseq);
conBean.setConcept_value(ocBean.getNVP_CONCEPT_VALUE());
conBean.setDisplay_order(display_order);
display_order = display_order - 1;
conBeanList.add(conBean);
}
}
// primary
EVS_Bean ocBean = (EVS_Bean) evsBean.elementAt(0);
String conIdseq = ocBean.getIDSEQ();
if((!isAllConceptsExists) && (conIdseq == null || conIdseq.equals(""))){
conIdseq = this.setConcept("INS", "", ocBean);
}
if (conIdseq != null || conIdseq.equals("")) {
ConBean conBean = new ConBean();
conBean.setCon_IDSEQ(ocBean.getIDSEQ());
conBean.setConcept_value(ocBean.getNVP_CONCEPT_VALUE());
conBean.setDisplay_order(0);
conBeanList.add(conBean);
}
}
return conBeanList;
}
public String getName(Vector evsBean){
String name ="";
if (evsBean != null) {
for (int i = 1; i < evsBean.size(); i++) {
EVS_Bean eBean = (EVS_Bean) evsBean.elementAt(i);
if (name.equals("")) {
name = eBean.getCONCEPT_IDENTIFIER();
} else {
name = name + ":" + eBean.getCONCEPT_IDENTIFIER();
}
}
// primary
EVS_Bean eBean = (EVS_Bean) evsBean.elementAt(0);
if (name.equals("")) {
name = eBean.getCONCEPT_IDENTIFIER();
} else {
name = name + ":" + eBean.getCONCEPT_IDENTIFIER();
}
}
return name;
}
public String doSetDEC(String sAction, DEC_Bean dec, String sInsertFor, DEC_Bean oldDEC){
String sReturnCode = "";
HttpSession session = m_classReq.getSession();
ValidationStatusBean ocStatusBean = new ValidationStatusBean();
ValidationStatusBean propStatusBean = new ValidationStatusBean();
Vector vObjectClass = (Vector) session.getAttribute("vObjectClass");
Vector vProperty = (Vector) session.getAttribute("vProperty");
String userName = (String)session.getAttribute("Username");
HashMap<String, String> defaultContext = (HashMap)session.getAttribute("defaultContext");
String conteIdseq= (String)defaultContext.get("idseq");
String checkValidityOC = (String)session.getAttribute("checkValidityOC");
String checkValidityProp = (String)session.getAttribute("checkValidityProp");
try{
m_classReq.setAttribute("retcode", "");
if (checkValidityOC.equals("Yes")){
if ((vObjectClass != null && vObjectClass.size()>0) && (defaultContext != null && defaultContext.size()>0)){
ocStatusBean = this.evsBeanCheck(vObjectClass, defaultContext, "", "Object Class");
}
}
if (checkValidityProp.equals("Yes")){
if ((vProperty != null && vProperty.size()>0) && (defaultContext != null && defaultContext.size()>0)){
propStatusBean = this.evsBeanCheck(vProperty, defaultContext, "", "Property");
}
}
if (checkValidityOC.equals("Yes")){
//set OC if it is null
if ((vObjectClass != null && vObjectClass.size()>0)){
if (!ocStatusBean.isEvsBeanExists()){
if (ocStatusBean.isCondrExists()) {
dec.setDEC_OC_CONDR_IDSEQ(ocStatusBean.getCondrIDSEQ());
// Create Object Class
String ocIdseq = this.createEvsBean(userName, ocStatusBean.getCondrIDSEQ(), conteIdseq, "Object Class");
if (ocIdseq != null && !ocIdseq.equals("")) {
dec.setDEC_OCL_IDSEQ(ocIdseq);
}
} else {
// Create Condr
String condrIdseq = this.createCondr(vObjectClass, ocStatusBean.isAllConceptsExists());
String ocIdseq = "";
// Create Object Class
if (condrIdseq != null && !condrIdseq.equals("")) {
dec.setDEC_OC_CONDR_IDSEQ(condrIdseq);
ocIdseq = this.createEvsBean(userName, condrIdseq, conteIdseq, "Object Class");
}
if (ocIdseq != null && !ocIdseq.equals("")) {
dec.setDEC_OCL_IDSEQ(ocIdseq);
}
}
}else{
if (ocStatusBean.isNewVersion()) {
if (ocStatusBean.getEvsBeanIDSEQ() != null && !ocStatusBean.getEvsBeanIDSEQ().equals("")){
String newID = "";
newID = this.setOC_PROP_REP_VERSION(ocStatusBean.getEvsBeanIDSEQ(), "ObjectClass");
if (newID != null && !newID.equals("")){
dec.setDEC_OC_CONDR_IDSEQ(ocStatusBean.getCondrIDSEQ());
dec.setDEC_OCL_IDSEQ(newID);
}
}
} else {
dec.setDEC_OC_CONDR_IDSEQ(ocStatusBean.getCondrIDSEQ());
dec.setDEC_OCL_IDSEQ(ocStatusBean.getEvsBeanIDSEQ());
}
}
}
}
if (checkValidityProp.equals("Yes")){
//set property if it is null
if ((vProperty != null && vProperty.size()>0)){
if (!propStatusBean.isEvsBeanExists()){
if (propStatusBean.isCondrExists()) {
dec.setDEC_PROP_CONDR_IDSEQ(propStatusBean.getCondrIDSEQ());
// Create Property
String propIdseq = this.createEvsBean(userName, propStatusBean.getCondrIDSEQ(), conteIdseq, "Property");
if (propIdseq != null && !propIdseq.equals("")) {
dec.setDEC_PROPL_IDSEQ(propIdseq);
}
} else {
// Create Condr
String condrIdseq = this.createCondr(vProperty, propStatusBean.isAllConceptsExists());
String propIdseq = "";
// Create Property
if (condrIdseq != null && !condrIdseq.equals("")) {
dec.setDEC_PROP_CONDR_IDSEQ(condrIdseq);
propIdseq = this.createEvsBean(userName, condrIdseq, conteIdseq,"Property");
}
if (propIdseq != null && !propIdseq.equals("")) {
dec.setDEC_PROPL_IDSEQ(propIdseq);
}
}
}else{
if (propStatusBean.isNewVersion()) {
if (propStatusBean.getEvsBeanIDSEQ() != null && !propStatusBean.getEvsBeanIDSEQ().equals("")){
String newID = "";
newID = this.setOC_PROP_REP_VERSION(propStatusBean.getEvsBeanIDSEQ(), "Property");
if (newID != null && !newID.equals("")){
dec.setDEC_PROP_CONDR_IDSEQ(propStatusBean.getCondrIDSEQ());
dec.setDEC_PROPL_IDSEQ(newID);
}
}
} else {
dec.setDEC_PROP_CONDR_IDSEQ(propStatusBean.getCondrIDSEQ());
dec.setDEC_PROPL_IDSEQ(propStatusBean.getEvsBeanIDSEQ());
}
}
}
}
sReturnCode = this.setDEC(sAction, dec, sInsertFor, oldDEC);
}catch(Exception e){
logger.error("ERROR in InsACService-setDEC for other : "+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this.storeStatusMsg("\\t Exception : Unable to update Data Element Concept attributes.");
}
return sReturnCode;
}
public String createCondr(Vector vConceptList, boolean isAllConceptsExists){
String condrIdseq = "";
try {
ArrayList<ConBean> conBeanList = this.getConBeanList(vConceptList, isAllConceptsExists);
String name = this.getName(vConceptList);
Con_Derivation_Rules_Ext_Mgr mgr = new Con_Derivation_Rules_Ext_Mgr();
condrIdseq = mgr.setCondr(conBeanList, name, m_servlet.getConn());
} catch (DBException e) {
logger.error("ERROR in InsACService-createCondr: "+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this.storeStatusMsg("Exception Error : Unable to create Condr");
}
return condrIdseq;
}
/**
* Gets validation string for rep term, object class and property
* @param evsBeanList
* @param defaultContext
* @param lName
* @param type
* @return
* @throws Exception
*/
public ValidationStatusBean evsBeanCheck(Vector evsBeanList, HashMap<String,String> defaultContext, String lName, String type)throws Exception{
ValidationStatusBean statusBean = new ValidationStatusBean();
HttpSession session = m_classReq.getSession();
String id = null;
String name =null;
if (type.equals("Object Class")){
DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC");
id = m_DEC.getDEC_OCL_IDSEQ();
name = "OCStatusBean";
}
if (type.equals("Property")){
DEC_Bean m_DEC = (DEC_Bean) session.getAttribute("m_DEC");
id = m_DEC.getDEC_PROPL_IDSEQ();
name = "PropStatusBean";
}
if (type.equals("Representation Term")){
VD_Bean m_VD = (VD_Bean) session.getAttribute("m_VD");
id = m_VD.getVD_REP_IDSEQ();
name = "VdStatusBean";
}
//If user selected existing OC or Prop or Rep Term in any context
if (id != null && !id.equals("")){
statusBean = (ValidationStatusBean)session.getAttribute(name);
}else{
//If user selected by concepts
statusBean = this.evsBeanCheckDB(evsBeanList, defaultContext, lName, type);
}
return statusBean;
}
public ValidationStatusBean evsBeanCheckDB(Vector evsBeanList, HashMap<String,String> defaultContext, String lName, String type)throws Exception{
ValidationStatusBean statusBean = new ValidationStatusBean();
ArrayList<ResultVO> resultList = new ArrayList();
Evs_Mgr mgr = null;
if (type.equals("Object Class")){
mgr = new Object_Classes_Ext_Mgr();
}else if (type.equals("Property")){
mgr = new Properties_Ext_Mgr();
}else if (type.equals("Representation Term")){
mgr = new Representations_Ext_Mgr();
}
statusBean.setAllConceptsExists(true);
for(int i=0; i<evsBeanList.size(); i++){
EVS_Bean conceptBean = (EVS_Bean) evsBeanList.elementAt(i);
String conIdseq = this.getConcept("", conceptBean, false);
if (conIdseq == null || conIdseq.equals("")){
statusBean.setAllConceptsExists(false);
break;
}
}
//if all the concepts exists
if (statusBean.isAllConceptsExists()) {
ArrayList<ConBean> conBeanList = this.getConBeanList(evsBeanList, statusBean.isAllConceptsExists());
try {
resultList = mgr.isCondrExists(conBeanList, m_servlet.getConn());
} catch (DBException e) {
logger.error("ERROR in InsACService-evsBeanCheck : "+ e.toString(), e);
throw new Exception(e);
}
//if nothing found, create new oc or prop or rep term
if (resultList == null || resultList.size() < 1) {
statusBean.setStatusMessage("** Creating a new "+type + " in caBIG");
statusBean.setCondrExists(false);
statusBean.setEvsBeanExists(false);
} else {
String idseq = null;
String condrIDSEQ = null;
String longName = null;
String publicID = null;
String version = null;
String idseqM = null;
String condrIDSEQM = null;
String longNameM = null;
String publicIDM = null;
String versionM = null;
ArrayList<ResultVO> foundBeanList = new ArrayList();
//select all which are owned by the default(caBIG) Context
for (int i = 0; i < resultList.size(); i++) {
ResultVO vo = resultList.get(i);
if (vo.getContext() != null) {
if (vo.getContext().equals(defaultContext.get("name"))) {
foundBeanList.add(vo);
}
}
}
//If none are found owned by the default(caBIG) Context
if (foundBeanList == null || foundBeanList.size() < 1) {
for (int i = 0; i < resultList.size(); i++) {
ResultVO vo = resultList.get(i);
//select the one in different context, create new (oc or prop or rep term) in default(caBIG) context
if (vo.getContext() != null) {
statusBean.setStatusMessage("** Matched "+type+" with "
+ vo.getLong_name() + " (" + vo.getPublicId()
+ "v" + vo.getVersion() + ") in " + vo.getContext()
+ " context; will create a new "+type+" in caBIG.");
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(vo.getCondr_IDSEQ());
statusBean.setEvsBeanExists(false);
return statusBean;
}
}
//if none are found in different context and condr exists, create new (oc or prop or rep term) in caBIG
ResultVO vo = resultList.get(0);
if (vo.getCondr_IDSEQ() != null) {
statusBean.setStatusMessage("** Creating a new "+type + " in caBIG");
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(vo.getCondr_IDSEQ());
statusBean.setEvsBeanExists(false);
return statusBean;
}
}//go thru all the records owned by the default(caBIG) Context
else if (foundBeanList != null && foundBeanList.size() > 0) {
//select the one with a Workflow Status RELEASED
for (int i = 0; i < foundBeanList.size(); i++) {
ResultVO vo = foundBeanList.get(i);
if (vo.getAsl_name().equals("RELEASED")) {
condrIDSEQ = vo.getCondr_IDSEQ();
idseq = vo.getIDSEQ();
longName = vo.getLong_name();
publicID = vo.getPublicId();
version = vo.getVersion();
break;
}
}
//use the released existing one if exists
if ((idseq != null) && !(idseq.equals(""))) {
statusBean.setStatusMessage("** Using existing "+type+" "+longName+" ("+publicID+"v"+version+") from caBIG");
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(condrIDSEQ);
statusBean.setEvsBeanExists(true);
statusBean.setEvsBeanIDSEQ(idseq);
} else {
if (foundBeanList != null && foundBeanList.size() > 0) {
//if none are found with a Workflow Status RELEASED, select one with a Workflow Status DRAFT NEW or DRAFT MOD.
for (int i = 0; i < foundBeanList.size(); i++) {
ResultVO vo = foundBeanList.get(i);
if (vo.getAsl_name().equals("DRAFT NEW") || vo.getAsl_name().equals("DRAFT MOD")) {
condrIDSEQM = vo.getCondr_IDSEQ();
idseqM = vo.getIDSEQ();
longNameM = vo.getLong_name();
publicIDM = vo.getPublicId();
versionM = vo.getVersion();
break;
}
}
}
//use the recommended existing data
if ((idseqM != null) && !(idseqM.equals(""))) {
statusBean.setStatusMessage("** Recommending to use "+type+" "+longNameM+" ("+publicIDM+"v"+versionM+") from caBIG");
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(condrIDSEQM);
statusBean.setEvsBeanExists(true);
statusBean.setEvsBeanIDSEQ(idseqM);
} else {
//If none are found, select any other Workflow Status and create a New Version of it.
ResultVO vo = foundBeanList.get(0);
statusBean.setStatusMessage("** Creating new Version of "+type+" "+vo.getLong_name()+" ("+vo.getPublicId()+"v"+vo.getVersion()+") in caBIG");
statusBean.setNewVersion(true);
statusBean.setCondrExists(true);
statusBean.setCondrIDSEQ(vo.getCondr_IDSEQ());
statusBean.setEvsBeanExists(true);
statusBean.setEvsBeanIDSEQ(vo.getIDSEQ());
}
}
}
}
} else {//if all the concepts does not exist
statusBean.setStatusMessage("** Creating a new "+type + " in caBIG");
}
return statusBean;
}
/**
*
* @param userName
* @param condrIdseq
* @param defaultContextIdseq
* @param type
* @return
*/
public String createEvsBean(String userName, String condrIdseq, String defaultContextIdseq, String type){
String idseq= "";
Evs_Mgr mgr = null;
try{
if (type.equals("Object Class")){
mgr = new Object_Classes_Ext_Mgr();
}else if (type.equals("Property")){
mgr = new Properties_Ext_Mgr();
}else if (type.equals("Representation Term")){
mgr = new Representations_Ext_Mgr();
}
EvsVO vo = new EvsVO();
vo.setCondr_IDSEQ(condrIdseq);
vo.setConte_IDSEQ(defaultContextIdseq);
vo.setCreated_by(userName);
idseq = mgr.insert(vo, m_servlet.getConn());
}catch (DBException e){
logger.error("ERROR in InsACService-createEvsBean: "+ e.toString(), e);
m_classReq.setAttribute("retcode", "Exception");
this.storeStatusMsg("Exception Error : Unable to create " + type);
}
return idseq;
}
}// close the class
|
package au.edu.uts.eng.remotelabs.rigclient.server.pages;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* The default page.
*/
public class IndexPage extends AbstractPage
{
/** Page links. */
private final Map<String, String> links;
/** Operations. */
private final Map<String, String> operations;
/** Icons. */
private final Map<String, String> icons;
/** Tooltips. */
private final Map<String, String> toolTips;
public IndexPage()
{
this.links = new LinkedHashMap<String, String>(5);
this.links.put("Status", "/status");
this.links.put("Configuration", "/config");
this.links.put("Logs", "/logs");
this.links.put("Runtime_Information", "/info");
this.links.put("Documentation", "/doc");
this.operations = new LinkedHashMap<String, String>(4);
this.operations.put("Restart", "/op/restart");
this.operations.put("Shutdown", "/op/shutdown");
this.icons = new HashMap<String, String>(9);
this.icons.put("Status", "status");
this.icons.put("Configuration", "config");
this.icons.put("Logs", "logs");
this.icons.put("Documentation", "doc");
this.icons.put("Runtime_Information", "runtime");
this.icons.put("Restart", "restart");
this.icons.put("Shutdown", "shutdown");
this.toolTips = new HashMap<String, String>(9);
this.toolTips.put("Status", "The status of the rig client including session details and exerciser tests " +
"statuses.");
this.toolTips.put("Configuration", "Allows configuration properties of the rig client to be viewed and " +
"changed.");
this.toolTips.put("Logs", "Log viewer of the latest log messages of the rig client since startup.");
this.toolTips.put("Documentation", "Documentation about the rig client.");
this.toolTips.put("Runtime_Information", "Runtime information about the rig client such as classpath, system " +
"properties, uptime...");
this.toolTips.put("Restart", "Restarts the rig client. This is only a soft restart since the rig client service " +
"process is not restarted.");
this.toolTips.put("Shutdown", "Shuts down the rig client. The rig client service is stopped.");
}
@Override
public void contents(HttpServletRequest req, HttpServletResponse resp) throws IOException
{
this.println("<div id='alllinks'>");
/* Link pages. */
this.println("<div id='linklist'>");
this.println(" <div class='listtitle'>");
this.println(" Pages");
this.println(" </div>");
this.println(" <ul class='ullinklist'>");
int i = 0;
for (Entry<String, String> e : this.links.entrySet())
{
String name = e.getKey();
String classes = "linkbut plaina";
if (i == 0) classes += " ui-corner-top";
else if (i == this.links.size() - 1) classes += " ui-corner-bottom";
this.println(" <li><a id='" + name + "link' class='" + classes + "' href='" + e.getValue() + "'>");
this.println(" <div class='linkbutcont'>");
this.println(" <div class='linkbutconticon'>");
this.println(" <img src='/img/" + this.icons.get(name) + "_small.png' alt='" + name + "' />");
this.println(" </div>");
this.println(" <div class='linkbutcontlabel'>" + this.stringTransform(name) + "</div>");
this.println(" <div id='" + name + "hover' class='leghov ui-corner-all'>");
this.println(" <div class='legimg'><img src='/img/" + this.icons.get(name) + ".png' alt='"+ name + "' /></div>");
this.println(" <div class='legdesc'>" + this.toolTips.get(name) + "</div>");
this.println(" </div>");
this.println(" </div>");
this.println(" </a></li>");
i++;
}
this.println(" </ul>"); // ullinklist
this.println("</div>"); // linklist
/* Operations pages. */
this.println("<div id='operationlist'>");
this.println(" <div class='listtitle'>");
this.println(" Operations");
this.println(" </div>");
this.println(" <ul class='ullinklist'>");
i = 0;
for (Entry<String, String> e : this.operations.entrySet())
{
String name = e.getKey();
String classes = "linkbut plaina";
if (i == 0) classes += " ui-corner-top";
else if (i == this.links.size() - 1) classes += " ui-corner-bottom";
this.println(" <li><a id='" + name + "link' class='" + classes + "' href='" + e.getValue() + "'>");
this.println(" <div class='linkbutcont'>");
this.println(" <div class='linkbutconticon'>");
this.println(" <img src='/img/" + this.icons.get(name) + "_small.png' alt='" + name + "' />");
this.println(" </div>");
this.println(" <div class='linkbutcontlabel'>" + this.stringTransform(name) + "</div>");
this.println(" <div id='" + name + "hover' class='leghov ui-corner-all'>");
this.println(" <div class='legimg'><img src='/img/" + this.icons.get(name) + ".png' alt='"+ name + "' /></div>");
this.println(" <div class='legdesc'>" + this.toolTips.get(name) + "</div>");
this.println(" </div>");
this.println(" </div>");
this.println(" </a></li>");
i++;
}
this.println(" </ul>"); // ullinklist
this.println("</div>"); // operationlist
this.println("</div>");
/* Tooltip hover events. */
this.println("<script type='text/javascript'>");
this.println("var ttStates = new Object();");
this.println(
"function loadIndexToolTip(name)\n" +
"{\n" +
" if (ttStates[name])\n" +
" {\n" +
" $('#' + name + 'hover').fadeIn();\n" +
" $('#' + name + 'link').css('font-weight', 'bold');\n" +
" }\n" +
"}\n");
this.println("$(document).ready(function() {");
for (String name : this.toolTips.keySet())
{
this.println(" ttStates['" + name + "'] = false;");
this.println(" $('#" + name + "link').hover(");
this.println(" function() {");
this.println(" ttStates['" + name + "'] = true;");
this.println(" setTimeout('loadIndexToolTip(\"" + name + "\")', 1200);");
this.println(" },");
this.println(" function() {");
this.println(" if (ttStates['" + name + "'])");
this.println(" {");
this.println(" $('#" + name + "hover').fadeOut();");
this.println(" $('#" + name + "link').css('font-weight', 'normal');");
this.println(" ttStates['" + name + "'] = false;");
this.println(" }");
this.println(" }");
this.println(" )");
}
this.println("})");
this.println("</script>");
}
@Override
protected String getPageHeader()
{
return "Welcome to " + this.config.getProperty("Rig_Name");
}
@Override
protected String getPageType()
{
return "Main";
}
}
|
package com.malhartech.stram;
import com.malhartech.dag.DAG;
import com.malhartech.dag.DAG.Operator;
import com.malhartech.dag.GenericTestModule;
import com.malhartech.dag.Module;
import com.malhartech.dag.ModuleContext;
import com.malhartech.dag.TestGeneratorInputModule;
import com.malhartech.stram.PhysicalPlan.PTOperator;
import com.malhartech.stram.StramLocalCluster.LocalStramChild;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeat;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeatResponse;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StramToNodeRequest;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StramToNodeRequest.RequestType;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingContainerContext;
import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat;
import com.malhartech.stream.StramTestSupport;
import java.io.File;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.fs.FileContext;
import org.apache.hadoop.fs.Path;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CheckpointTest {
private static final Logger LOG = LoggerFactory.getLogger(CheckpointTest.class);
private static File testWorkDir = new File("target", CheckpointTest.class.getName());
@BeforeClass
public static void setup() {
try {
FileContext.getLocalFSFileContext().delete(
new Path(testWorkDir.getAbsolutePath()), true);
} catch (Exception e) {
throw new RuntimeException("could not cleanup test dir", e);
}
}
/**
* Test saving of node state at window boundary.
*
* @throws Exception
*/
@Test
public void testBackup() throws Exception
{
DAG dag = new DAG();
// node with no inputs will be connected to window generator
dag.addOperator("node1", TestGeneratorInputModule.class)
.setProperty(TestGeneratorInputModule.KEY_MAX_TUPLES, "1");
dag.getConf().set(DAG.STRAM_CHECKPOINT_DIR, testWorkDir.getPath());
StreamingContainerManager dnm = new StreamingContainerManager(dag);
Assert.assertEquals("number required containers", 1, dnm.getNumRequiredContainers());
String containerId = "container1";
StreamingContainerContext cc = dnm.assignContainerForTest(containerId, InetSocketAddress.createUnresolved("localhost", 0));
ManualScheduledExecutorService mses = new ManualScheduledExecutorService(1);
WindowGenerator wingen = StramTestSupport.setupWindowGenerator(mses);
LocalStramChild container = new LocalStramChild(containerId, null, wingen);
container.setup(cc);
mses.tick(1); // begin window 1
Assert.assertEquals("number operators", 1, container.getNodes().size());
Module node = container.getNode(cc.nodeList.get(0).id);
ModuleContext context = container.getNodeContext(cc.nodeList.get(0).id);
Assert.assertNotNull("node deployed " + cc.nodeList.get(0), node);
Assert.assertEquals("nodeId", cc.nodeList.get(0).id, context.getId());
Assert.assertEquals("maxTupes", 1, ((TestGeneratorInputModule)node).getMaxTuples());
StramToNodeRequest backupRequest = new StramToNodeRequest();
backupRequest.setNodeId(context.getId());
backupRequest.setRequestType(RequestType.CHECKPOINT);
ContainerHeartbeatResponse rsp = new ContainerHeartbeatResponse();
rsp.nodeRequests = Collections.singletonList(backupRequest);
container.processHeartbeatResponse(rsp);
mses.tick(1); // end window 1, begin window 2
// node to move to next window before we verify the checkpoint state
// if (node.context.getLastProcessedWindowId() < 2) {
// Thread.sleep(500);
Assert.assertTrue("node >= window 1",
1 <= context.getLastProcessedWindowId());
File cpFile1 = new File(testWorkDir, backupRequest.getNodeId() + "/1");
Assert.assertTrue("checkpoint file not found: " + cpFile1, cpFile1.exists() && cpFile1.isFile());
StreamingNodeHeartbeat hbe = new StreamingNodeHeartbeat();
hbe.setNodeId(context.getId());
hbe.setLastBackupWindowId(1);
ContainerHeartbeat hb = new ContainerHeartbeat();
hb.setContainerId(containerId);
hb.setDnodeEntries(Collections.singletonList(hbe));
// fake heartbeat to propagate checkpoint
dnm.processHeartbeat(hb);
container.processHeartbeatResponse(rsp);
mses.tick(1); // end window 2
File cpFile2 = new File(testWorkDir, backupRequest.getNodeId() + "/2");
Assert.assertTrue("checkpoint file not found: " + cpFile2, cpFile2.exists() && cpFile2.isFile());
// fake heartbeat to propagate checkpoint
hbe.setLastBackupWindowId(2);
dnm.processHeartbeat(hb);
// purge checkpoints
dnm.monitorHeartbeat();
Assert.assertTrue("checkpoint file not purged: " + cpFile1, !cpFile1.exists());
Assert.assertTrue("checkpoint file purged: " + cpFile2, cpFile2.exists() && cpFile2.isFile());
LOG.debug("Shutdown container {}", container.getContainerId());
container.teardown();
}
@Test
public void testRecoveryCheckpoint() throws Exception
{
DAG dag = new DAG();
Operator node1 = dag.addOperator("node1", GenericTestModule.class);
Operator node2 = dag.addOperator("node2", GenericTestModule.class);
dag.addStream("n1n2")
.setSource(node1.getOutput(GenericTestModule.OUTPUT1))
.addSink(node2.getInput(GenericTestModule.INPUT1));
StreamingContainerManager dnm = new StreamingContainerManager(dag);
PhysicalPlan deployer = dnm.getTopologyDeployer();
List<PTOperator> nodes1 = deployer.getOperators(node1);
Assert.assertNotNull(nodes1);
Assert.assertEquals(1, nodes1.size());
PTOperator pnode1 = nodes1.get(0);
List<PTOperator> nodes2 = deployer.getOperators(node2);
Assert.assertNotNull(nodes2);
Assert.assertEquals(1, nodes2.size());
PTOperator pnode2 = nodes2.get(0);
Map<PTOperator, Long> checkpoints = new HashMap<PTOperator, Long>();
long cp = dnm.updateRecoveryCheckpoints(pnode2, checkpoints);
Assert.assertEquals("no checkpoints " + pnode2, 0, cp);
cp = dnm.updateRecoveryCheckpoints(pnode1, new HashMap<PTOperator, Long>());
Assert.assertEquals("no checkpoints " + pnode1, 0, cp);
// adding checkpoints to upstream only does not move recovery checkpoint
pnode1.checkpointWindows.add(3L);
pnode1.checkpointWindows.add(5L);
cp = dnm.updateRecoveryCheckpoints(pnode1, new HashMap<PTOperator, Long>());
Assert.assertEquals("no checkpoints " + pnode1, 0L, cp);
pnode2.checkpointWindows.add(3L);
checkpoints = new HashMap<PTOperator, Long>();
cp = dnm.updateRecoveryCheckpoints(pnode1, checkpoints);
Assert.assertEquals("checkpoint pnode1", 3L, cp);
pnode2.checkpointWindows.add(4L);
checkpoints = new HashMap<PTOperator, Long>();
cp = dnm.updateRecoveryCheckpoints(pnode1, checkpoints);
Assert.assertEquals("checkpoint pnode1", 3L, cp);
pnode1.checkpointWindows.add(1, 4L);
Assert.assertEquals(pnode1.checkpointWindows, Arrays.asList(new Long[]{3L, 4L, 5L}));
checkpoints = new HashMap<PTOperator, Long>();
cp = dnm.updateRecoveryCheckpoints(pnode1, checkpoints);
Assert.assertEquals("checkpoint pnode1", 4L, cp);
Assert.assertEquals(pnode1.checkpointWindows, Arrays.asList(new Long[]{4L, 5L}));
}
}
|
/**
*
* $Id: NewDropdownUtil.java,v 1.46 2006-05-24 18:54:37 georgeda Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.45 2006/05/24 16:53:09 pandyas
* Converted StainingMethod to lookup - modified code to pull dropdown list from DB
* All changes from earlier version were merged into this version manually
*
* Revision 1.44 2006/05/23 18:16:38 georgeda
* Removed hardcode of other into species dropdown
*
* Revision 1.43 2006/05/19 16:41:54 pandyas
* Defect #249 - add other to species on the Xenograft screen
*
* Revision 1.42 2006/05/15 15:45:40 georgeda
* Cleaned up contact info management
*
* Revision 1.41 2006/05/10 14:16:14 schroedn
* New Features - Changes from code review
*
* Revision 1.40 2006/04/17 19:08:38 pandyas
* caMod 2.1 OM changes
*
* Revision 1.39 2005/11/29 20:47:21 georgeda
* Removed system.out
*
* Revision 1.38 2005/11/16 21:36:40 georgeda
* Defect #47, Clean up EF querying
*
* Revision 1.37 2005/11/16 19:26:30 pandyas
* added javadocs
*
*
*/
package gov.nih.nci.camod.webapp.util;
import gov.nih.nci.camod.Constants;
import gov.nih.nci.camod.domain.*;
import gov.nih.nci.camod.service.*;
import gov.nih.nci.camod.service.impl.CurationManagerImpl;
import gov.nih.nci.camod.service.impl.QueryManagerSingleton;
import gov.nih.nci.common.persistence.Search;
import gov.nih.nci.camod.service.SpeciesManager;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class NewDropdownUtil
{
private static final Log log = LogFactory.getLog(NewDropdownUtil.class);
private static Map ourFileBasedLists = new HashMap();
public static void populateDropdown(HttpServletRequest inRequest,
String inDropdownKey,
String inFilter) throws Exception
{
log.trace("Entering NewDropdownUtil.populateDropdown");
log.debug("Generating a dropdown for the following key: " + inDropdownKey);
List theList = null;
if (inDropdownKey.indexOf(".txt") != -1)
{
theList = getTextFileDropdown(inRequest, inDropdownKey);
}
else if (inDropdownKey.indexOf(".db") != -1)
{
theList = getDatabaseDropdown(inRequest, inDropdownKey, inFilter);
}
// Add a blank as the first line
if (Constants.Dropdowns.ADD_BLANK.equals(inFilter))
{
addBlank(theList);
}
// Add a blank as the first line
else if (Constants.Dropdowns.ADD_BLANK_OPTION.equals(inFilter))
{
addBlankOption(theList);
}
// Add a blank as the first line
else if (Constants.Dropdowns.ADD_OTHER.equals(inFilter))
{
addOther(theList);
}
// Add a blank as the first line
else if (Constants.Dropdowns.ADD_OTHER_OPTION.equals(inFilter))
{
addOtherOption(theList);
}
else if (Constants.Dropdowns.ADD_BLANK_AND_OTHER.equals(inFilter))
{
addOther(theList);
addBlank(theList);
}
else if (Constants.Dropdowns.ADD_BLANK_AND_OTHER_OPTION.equals(inFilter))
{
addOtherOption(theList);
addBlankOption(theList);
}
if (theList == null)
{
throw new IllegalArgumentException("Unknown dropdown list key: " + inDropdownKey);
}
inRequest.getSession().setAttribute(inDropdownKey, theList);
log.trace("Exiting NewDropdownUtil.populateDropdown");
}
private static List getDatabaseDropdown(HttpServletRequest inRequest,
String inDropdownKey,
String inFilter) throws Exception
{
log.info("Entering NewDropdownUtil.getDatabaseDropdown");
List theReturnList = null;
// Grab them for the first time
if (inDropdownKey.equals(Constants.Dropdowns.SPECIESDROP))
{
theReturnList = getSpeciesList(inRequest, inFilter);
}
//modified for species from DB
else if (inDropdownKey.equals(Constants.Dropdowns.SPECIESQUERYDROP))
{
theReturnList = getQueryOnlySpeciesList(inRequest, inFilter);
}
else if (inDropdownKey.equals(Constants.Dropdowns.SPECIESQUERYDROP))
{
theReturnList = getQueryOnlySpeciesList(inRequest, inFilter);
}
else if (inDropdownKey.equals(Constants.Dropdowns.STRAINDROP))
{
theReturnList = getStrainsList(inRequest, inFilter);
}
else if (inDropdownKey.equals(Constants.Dropdowns.VIRALVECTORDROP))
{
theReturnList = getViralVectorList(inRequest);
}
else if (inDropdownKey.equals(Constants.Dropdowns.EXPRESSIONLEVELDROP))
{
theReturnList = getExpressionLevelList(inRequest);
}
// Environmental Factors - Carciogenic Interventions
else if (inDropdownKey.equals(Constants.Dropdowns.SURGERYDROP))
{
theReturnList = getEnvironmentalFactorList("Other");
}
else if (inDropdownKey.equals(Constants.Dropdowns.SURGERYQUERYDROP))
{
theReturnList = getQueryOnlyEnvironmentalFactorList("Other");
}
else if (inDropdownKey.equals(Constants.Dropdowns.HORMONEDROP))
{
theReturnList = getEnvironmentalFactorList("Hormone");
}
else if (inDropdownKey.equals(Constants.Dropdowns.HORMONEQUERYDROP))
{
theReturnList = getQueryOnlyEnvironmentalFactorList("Hormone");
}
else if (inDropdownKey.equals(Constants.Dropdowns.GROWTHFACTORDROP))
{
theReturnList = getEnvironmentalFactorList("Growth Factor");
}
else if (inDropdownKey.equals(Constants.Dropdowns.GROWTHFACTORQUERYDROP))
{
theReturnList = getQueryOnlyEnvironmentalFactorList("Growth Factor");
}
else if (inDropdownKey.equals(Constants.Dropdowns.CHEMICALDRUGDROP))
{
theReturnList = getEnvironmentalFactorList("Chemical / Drug");
}
else if (inDropdownKey.equals(Constants.Dropdowns.CHEMICALDRUGQUERYDROP))
{
theReturnList = getQueryOnlyEnvironmentalFactorList("Chemical / Drug");
}
else if (inDropdownKey.equals(Constants.Dropdowns.VIRUSDROP))
{
theReturnList = getEnvironmentalFactorList("Viral");
}
else if (inDropdownKey.equals(Constants.Dropdowns.VIRUSQUERYDROP))
{
theReturnList = getQueryOnlyEnvironmentalFactorList("Viral");
}
else if (inDropdownKey.equals(Constants.Dropdowns.RADIATIONDROP))
{
theReturnList = getEnvironmentalFactorList("Radiation");
}
else if (inDropdownKey.equals(Constants.Dropdowns.RADIATIONQUERYDROP))
{
theReturnList = getQueryOnlyEnvironmentalFactorList("Radiation");
}
else if (inDropdownKey.equals(Constants.Dropdowns.NUTRITIONFACTORDROP))
{
theReturnList = getEnvironmentalFactorList("Nutrition");
}
else if (inDropdownKey.equals(Constants.Dropdowns.ENVIRONFACTORDROP))
{
theReturnList = getEnvironmentalFactorList("Environment");
}
else if (inDropdownKey.equals(Constants.Dropdowns.ENVIRONFACTORDROP))
{
theReturnList = getEnvironmentalFactorList("Environment");
}
else if (inDropdownKey.equals(Constants.Dropdowns.PRINCIPALINVESTIGATORDROP))
{
theReturnList = getPrincipalInvestigatorList(inRequest, inFilter);
}
else if (inDropdownKey.equals(Constants.Dropdowns.PRINCIPALINVESTIGATORQUERYDROP))
{
theReturnList = getQueryOnlyPrincipalInvestigatorList(inRequest, inFilter);
}
else if (inDropdownKey.equals(Constants.Dropdowns.INDUCEDMUTATIONAGENTQUERYDROP))
{
theReturnList = getQueryOnlyInducedMutationAgentList(inRequest, inFilter);
}
else if (inDropdownKey.equals(Constants.Dropdowns.USERSDROP))
{
theReturnList = getUsersList(inRequest, inFilter);
}
else if (inDropdownKey.equals(Constants.Dropdowns.CURATIONSTATESDROP))
{
theReturnList = getCurationStatesList(inRequest, inFilter);
}
else if (inDropdownKey.equals(Constants.Dropdowns.USERSFORROLEDROP))
{
theReturnList = getUsersForRoleList(inRequest, inFilter);
}
else if (inDropdownKey.equals(Constants.Dropdowns.ROLESDROP))
{
theReturnList = getRolesList(inRequest);
}
else if (inDropdownKey.equals(Constants.Dropdowns.STAININGDROP))
{
theReturnList = getStainingMethod(inRequest);
}
else
{
log.error("No matching dropdown for key: " + inDropdownKey);
theReturnList = new ArrayList();
}
log.info("Exiting NewDropdownUtil.getDatabaseDropdown");
return theReturnList;
}
// Get the context so we can get to our managers
private static WebApplicationContext getContext(HttpServletRequest inRequest)
{
return WebApplicationContextUtils.getRequiredWebApplicationContext(inRequest.getSession().getServletContext());
}
// Get a text file dropdown
private static synchronized List getTextFileDropdown(HttpServletRequest inRequest,
String inDropdownKey) throws Exception
{
log.trace("Entering NewDropdownUtil.getTextFileDropdown");
List theReturnList = new ArrayList();
if (ourFileBasedLists.containsKey(inDropdownKey))
{
log.debug("Dropdown already cached");
List theCachedList = (List) ourFileBasedLists.get(inDropdownKey);
theReturnList.addAll(theCachedList);
}
else
{
String theFilename = inRequest.getSession().getServletContext().getRealPath("/config/dropdowns") + "/" + inDropdownKey;
List theList = readListFromFile(theFilename);
// Built a list. Add to static hash
if (theList.size() != 0)
{
log.debug("Caching new dropdown: " + theList);
ourFileBasedLists.put(inDropdownKey, theList);
theReturnList.addAll(theList);
}
}
log.trace("Exiting NewDropdownUtil.getTextFileDropdown");
return theReturnList;
}
// Read from a file
static private List readListFromFile(String inFilename) throws Exception
{
List theReturnList = new ArrayList();
log.debug("Filename to read dropdown from: " + inFilename);
BufferedReader in = new BufferedReader(new FileReader(inFilename));
boolean isDropdownOption = false;
String str;
while ((str = in.readLine()) != null)
{
log.info("readListFromFile method: Reading value from file: " + str);
// It's a DropdownOption file
if (str.indexOf("DROPDOWN_OPTION") > 0)
{
isDropdownOption = true;
}
else if (isDropdownOption == true)
{
StringTokenizer theTokenizer = new StringTokenizer(str);
String theLabel = theTokenizer.nextToken(",");
String theValue = theTokenizer.nextToken(",");
DropdownOption theDropdownOption = new DropdownOption(theLabel, theValue);
theReturnList.add(theDropdownOption);
}
else
{
theReturnList.add(str);
}
}
in.close();
return theReturnList;
}
/**
* Returns a list of Species and Strains that are edited-approved (3 currently)
* Used for search screens
*
* @return speciesNames
* @throws Exception
*/
protected static List getSpeciesList(HttpServletRequest inRequest,
String inAddBlank) throws Exception
{
log.trace("Entering NewDropdownUtil.getSpeciesList");
// Get values for dropdown lists for Species
// for each Species, get it's commonName (scientificName)
List theSpeciesList = QueryManagerSingleton.instance().getApprovedSpecies(inRequest);
List<DropdownOption> theReturnList = new ArrayList<DropdownOption>();
if (theSpeciesList != null)
{
for (int i = 0; i < theSpeciesList.size(); i++)
{
Species theSpecies = (Species) theSpeciesList.get(i);
if (theSpecies.getScientificName() != null)
{
String theDisplayName = theSpecies.getDisplayName();
if (theDisplayName.length() > 0)
{
DropdownOption theOption = new DropdownOption(theDisplayName, theSpecies.getScientificName());
theReturnList.add(theOption);
}
}
}
}
log.trace("Exiting NewDropdownUtil.getQueryOnlySpeciesList");
return theReturnList;
}
/**
* Returns a list of all Species and Strains
* Used for search screens
*
* @return speciesNames
* @throws Exception
*/
private static List getQueryOnlySpeciesList(HttpServletRequest inRequest,
String inAddBlank) throws Exception
{
log.trace("Entering NewDropdownUtil.getQueryOnlySpeciesList");
// Get values for dropdown lists for Species
// for each Species, get it's commonName (scientificName)
List theSpeciesList = QueryManagerSingleton.instance().getQueryOnlySpecies(inRequest);
List<DropdownOption> theReturnList = new ArrayList<DropdownOption>();
if (theSpeciesList != null)
{
for (int i = 0; i < theSpeciesList.size(); i++)
{
Species theSpecies = (Species) theSpeciesList.get(i);
if (theSpecies.getScientificName() != null)
{
String theDisplayName = theSpecies.getDisplayName();
if (theDisplayName.length() > 0)
{
DropdownOption theOption = new DropdownOption(theDisplayName, theSpecies.getScientificName());
theReturnList.add(theOption);
}
}
}
}
return theReturnList;
}
/**
* Based on a species name retrieve a list of all Strains
*
* @param speciesName
* @return strainNames
* @throws Exception
*/
private static List getStrainsList(HttpServletRequest inRequest,
String speciesName) throws Exception
{
log.info("Entering NewDropdownUtil.getStrainsList");
//Set constant for the Animal Model species here
inRequest.getSession().setAttribute(Constants.AMMODELSPECIES, speciesName);
SpeciesManager speciesManager = (SpeciesManager) getContext(inRequest).getBean("speciesManager");
Species species = null;
List<Strain> strainList = new ArrayList<Strain>();
List<String> strainNames = new ArrayList<String>();
if (speciesName != null && speciesName.length() > 0)
{
// Add blank, other, and Not Specified to strain if user selects other for species
if (speciesName.equals(Constants.Dropdowns.OTHER_OPTION))
{
addNotSpecified(strainNames);
addOther(strainNames);
addBlank(strainNames);
}
else
{
species = speciesManager.getByName(speciesName);
strainList = new ArrayList<Strain>(species.getStrainCollection());
if (strainList.size() > 0)
{
//print out strain names
for (int i = 0; i < strainList.size(); i++)
{
Strain strain = (Strain) strainList.get(i);
if (strain.getName() != null && !strainNames.contains(strain.getName()))
{
System.out.println("strain.getName(): " + strain.getName());
strainNames.add(strain.getName());
}
}
// Sort the list in 'abc' order
Collections.sort(strainNames);
addOther(strainNames);
addBlank(strainNames);
}
else
{
addOther(strainNames);
addBlank(strainNames);
}
}
}
return strainNames;
}
/**
* Returns a list of all Administrative Routes
*
* @return adminList
* @throws Exception
*/
private static List getViralVectorList(HttpServletRequest inRequest) throws Exception
{
// Get values for dropdown lists for Species, Strains
GeneDeliveryManager geneDeliveryManager = (GeneDeliveryManager) getContext(inRequest).getBean("geneDeliveryManager");
List<GeneDelivery> geneDeliveryList = null;
geneDeliveryList = geneDeliveryManager.getAll();
List<String> viralVectorList = new ArrayList<String>();
GeneDelivery tmp;
if (geneDeliveryList != null)
{
for (int i = 0; i < geneDeliveryList.size(); i++)
{
tmp = (GeneDelivery) geneDeliveryList.get(i);
if (tmp.getViralVector() != null)
{
// if the name is not already in the List, add it
// (only get unique names)
if (!viralVectorList.contains(tmp.getViralVector()))
viralVectorList.add(tmp.getViralVector());
}
}
}
Collections.sort(viralVectorList);
addOther(viralVectorList);
return viralVectorList;
}
/**
* Returns a list for a type of environmental Factors
*
* @return envList
*/
private static List getEnvironmentalFactorList(String type) throws Exception
{
List theEnvFactorList = QueryManagerSingleton.instance().getEnvironmentalFactors(type);
addOther(theEnvFactorList);
return theEnvFactorList;
}
/**
* Returns a list for a type of environmental Factore
*
* @return envList
*/
private static List getQueryOnlyEnvironmentalFactorList(String type) throws Exception
{
List theEnvFactorList = QueryManagerSingleton.instance().getQueryOnlyEnvironmentalFactors(type);
return theEnvFactorList;
}
/**
* Returns a list of all Principal Investigators
*
* @return list of PI's
* @throws Exception
*/
private static List getPrincipalInvestigatorList(HttpServletRequest inRequest,
String inAddBlank) throws Exception
{
log.trace("Entering NewDropdownUtil.getPrincipalInvestigatorList");
List thePIList = QueryManagerSingleton.instance().getPrincipalInvestigators();
List<DropdownOption> theReturnList = new ArrayList<DropdownOption>();
if (thePIList != null)
{
for (int i = 0; i < thePIList.size(); i++)
{
Person thePerson = (Person) thePIList.get(i);
if (thePerson.getIsPrincipalInvestigator() != null)
{
String theDisplayName = thePerson.getDisplayName();
if (theDisplayName.length() > 0)
{
DropdownOption theOption = new DropdownOption(theDisplayName, thePerson.getUsername());
theReturnList.add(theOption);
}
}
}
}
log.trace("Exiting NewDropdownUtil.getPrincipalInvestigatorList");
return theReturnList;
}
/**
* Returns a list of all Principal Investigators
*
* @return list of PI's
* @throws Exception
*/
private static List getQueryOnlyPrincipalInvestigatorList(HttpServletRequest inRequest,
String inAddBlank) throws Exception
{
log.info("Entering NewDropdownUtil.getQueryOnlyPrincipalInvestigatorList");
return QueryManagerSingleton.instance().getQueryOnlyPrincipalInvestigators();
}
/**
* Returns a list of all Agents that were used to induce a mutation
*
* @return list of agent names
* @throws Exception
*/
private static List getQueryOnlyInducedMutationAgentList(HttpServletRequest inRequest,
String inAddBlank) throws Exception
{
log.trace("Entering NewDropdownUtil.getQueryOnlyInducedMutationAgentList");
List inducedMutationList = QueryManagerSingleton.instance().getQueryOnlyInducedMutationAgents();
addOther(inducedMutationList);
return inducedMutationList;
}
/**
* Returns a list of all users
*
* @return list of users
* @throws Exception
*/
private static List getUsersList(HttpServletRequest inRequest,
String inAddBlank) throws Exception
{
log.trace("Entering NewDropdownUtil.getUsersList");
List thePersonList = Search.query(Person.class);
List<DropdownOption> theReturnList = new ArrayList<DropdownOption>();
// Add all of the display names
if (thePersonList != null)
{
for (int i = 0; i < thePersonList.size(); i++)
{
Person thePerson = (Person) thePersonList.get(i);
DropdownOption theOption = new DropdownOption(thePerson.getDisplayNameWithOrg(), thePerson.getId().toString());
theReturnList.add(theOption);
}
}
log.trace("Exiting NewDropdownUtil.getUsersList");
Collections.sort(theReturnList);
return theReturnList;
}
/**
* Returns a list of all Staining Method Names
*
* @throws Exception
*/
private static List getStainingMethod(HttpServletRequest inRequest) throws Exception
{
log.info("Entering NewDropdownUtil.getStainingMethod");
// Get values for dropdown lists for StainingMethod
StainingMethodManager stainingMethodManager = (StainingMethodManager) getContext(inRequest).getBean("stainingMethodManager");
List stainingList = null;
stainingList = stainingMethodManager.getAll();
List<String> stainingMethodList = new ArrayList<String>();
StainingMethod tmp;
if (stainingList != null)
{
for (int i = 0; i < stainingList.size(); i++)
{
tmp = (StainingMethod) stainingList.get(i);
if (tmp.getName() != null)
{
// if the StainingMethod is not already in the List, add it
// (only get unique names)
if (!stainingMethodList.contains(tmp.getName()))
stainingMethodList.add(tmp.getName());
}
}
}
Collections.sort(stainingMethodList);
log.info("Exiting NewDropdownUtil.getStainingMethod");
return stainingMethodList;
}
/**
* Returns a list of all Expression Level Descriptions
*
* @return list of users
* @throws Exception
*/
private static List getExpressionLevelList(HttpServletRequest inRequest) throws Exception
{
// Get values for dropdown lists for Expression Level
ExpressionLevelDescManager expressionLevelDescManager = (ExpressionLevelDescManager) getContext(inRequest).getBean(
"expressionLevelDescManager");
List expList = null;
expList = expressionLevelDescManager.getAll();
List<String> expressionLevelList = new ArrayList<String>();
ExpressionLevelDesc tmp;
if (expList != null)
{
for (int i = 0; i < expList.size(); i++)
{
tmp = (ExpressionLevelDesc) expList.get(i);
if (tmp.getExpressionLevel() != null)
{
// if the ExpressionLevel is not already in the List, add it
// (only get unique names)
if (!expressionLevelList.contains(tmp.getExpressionLevel()))
expressionLevelList.add(tmp.getExpressionLevel());
}
}
}
Collections.sort(expressionLevelList);
return expressionLevelList;
}
/**
* Returns a list of all states for a curation flow
*
* @return list of curation states
*
* @throws Exception
*/
private static List getCurationStatesList(HttpServletRequest inRequest,
String inWorkflow) throws Exception
{
log.trace("Entering NewDropdownUtil.getCurationStatesList");
// Get the curation manager workflow XML
CurationManager theCurationManager = new CurationManagerImpl(inRequest.getSession().getServletContext().getRealPath("/") + inWorkflow);
return theCurationManager.getAllStateNames();
}
/**
* Returns a list of all states for a curation flow
*
* @return list of curation states
*
* @throws Exception
*/
private static List getUsersForRoleList(HttpServletRequest inRequest,
String inRoleName) throws Exception
{
log.trace("Entering NewDropdownUtil.getUsersForRoleList");
List theUserList = new ArrayList();
Role theRole = new Role();
theRole.setName(inRoleName);
try
{
List theRoles = Search.query(theRole);
if (theRoles.size() > 0)
{
theRole = (Role) theRoles.get(0);
// Get the users for the role
Set<Party> theUsers = theRole.getPartyCollection();
Iterator theIterator = theUsers.iterator();
// Go through the list of returned Party objects
while (theIterator.hasNext())
{
Object theObject = theIterator.next();
// Only add when it's actually a person
if (theObject instanceof Person)
{
Person thePerson = (Person) theObject;
theUserList.add(new DropdownOption(thePerson.getDisplayName(), thePerson.getUsername()));
}
}
}
else
{
log.warn("Role not found in database: " + inRoleName);
}
}
catch (Exception e)
{
log.error("Unable to get roles for user: ", e);
throw e;
}
return theUserList;
}
/**
* Returns a list of all the known roles
*
* @return list of roles
*/
private static List getRolesList(HttpServletRequest inRequest)
{
// Generate the roles list
List<String> theRoles = new ArrayList<String>();
theRoles.add(Constants.Admin.Roles.ALL);
theRoles.add(Constants.Admin.Roles.COORDINATOR);
theRoles.add(Constants.Admin.Roles.EDITOR);
theRoles.add(Constants.Admin.Roles.SCREENER);
return theRoles;
}
/**
* Add Other to the list in the first spot if it's not already there.
* Removes it and put's it in the first spot if it is.
*/
private static void addOther(List inList)
{
if (!inList.contains(Constants.Dropdowns.OTHER_OPTION))
{
inList.add(0, Constants.Dropdowns.OTHER_OPTION);
}
else
{
inList.remove(Constants.Dropdowns.OTHER_OPTION);
inList.add(0, Constants.Dropdowns.OTHER_OPTION);
}
}
/**
* Add Not Specified to the list in the first spot if it's not already there.
* Removes it and put's it in the second spot if it is.
*/
private static void addNotSpecified(List inList)
{
if (!inList.contains(Constants.Dropdowns.NOT_SPECIFIED_OPTION))
{
inList.add(0, Constants.Dropdowns.NOT_SPECIFIED_OPTION);
}
else
{
inList.remove(Constants.Dropdowns.NOT_SPECIFIED_OPTION);
inList.add(0, Constants.Dropdowns.NOT_SPECIFIED_OPTION);
}
}
/**
* Add Other to the list in the first spot if it's not already there.
* Removes it and put's it in the first spot if it is.
*/
private static void addOtherOption(List inList)
{
DropdownOption theDropdownOption = new DropdownOption(Constants.Dropdowns.OTHER_OPTION, Constants.Dropdowns.OTHER_OPTION);
if (!inList.contains(theDropdownOption))
{
inList.add(0, theDropdownOption);
}
else
{
inList.remove(theDropdownOption);
inList.add(0, theDropdownOption);
}
}
/**
* Add "" to the list in the first spot if it's not already there. Removes
* it and put's it in the first spot if it is.
*/
private static void addBlank(List inList)
{
if (!inList.contains(""))
{
inList.add(0, "");
}
else
{
inList.remove("");
inList.add(0, "");
}
}
/**
* Add "" to the list in the first spot if it's not already there. Removes
* it and put's it in the first spot if it is.
*/
private static void addBlankOption(List inList)
{
DropdownOption theDropdownOption = new DropdownOption("", "");
if (!inList.contains(theDropdownOption))
{
inList.add(0, theDropdownOption);
}
else
{
inList.remove(theDropdownOption);
inList.add(0, theDropdownOption);
}
}
}
|
package ca.concordia.cssanalyser.parser.less;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang.NotImplementedException;
import org.slf4j.Logger;
import ca.concordia.cssanalyser.app.FileLogger;
import ca.concordia.cssanalyser.cssmodel.LocationInfo;
import ca.concordia.cssanalyser.cssmodel.StyleSheet;
import ca.concordia.cssanalyser.cssmodel.declaration.Declaration;
import ca.concordia.cssanalyser.cssmodel.declaration.DeclarationFactory;
import ca.concordia.cssanalyser.cssmodel.declaration.value.DeclarationValue;
import ca.concordia.cssanalyser.cssmodel.declaration.value.DeclarationValueFactory;
import ca.concordia.cssanalyser.cssmodel.declaration.value.ValueType;
import ca.concordia.cssanalyser.cssmodel.media.MediaFeatureExpression;
import ca.concordia.cssanalyser.cssmodel.media.MediaQuery;
import ca.concordia.cssanalyser.cssmodel.media.MediaQuery.MediaQueryPrefix;
import ca.concordia.cssanalyser.cssmodel.media.MediaQueryList;
import ca.concordia.cssanalyser.cssmodel.selectors.AdjacentSiblingSelector;
import ca.concordia.cssanalyser.cssmodel.selectors.BaseSelector;
import ca.concordia.cssanalyser.cssmodel.selectors.ChildSelector;
import ca.concordia.cssanalyser.cssmodel.selectors.DescendantSelector;
import ca.concordia.cssanalyser.cssmodel.selectors.GroupingSelector;
import ca.concordia.cssanalyser.cssmodel.selectors.NegationPseudoClass;
import ca.concordia.cssanalyser.cssmodel.selectors.PseudoClass;
import ca.concordia.cssanalyser.cssmodel.selectors.PseudoElement;
import ca.concordia.cssanalyser.cssmodel.selectors.Selector;
import ca.concordia.cssanalyser.cssmodel.selectors.SiblingSelector;
import ca.concordia.cssanalyser.cssmodel.selectors.SimpleSelector;
import ca.concordia.cssanalyser.cssmodel.selectors.conditions.SelectorCondition;
import ca.concordia.cssanalyser.cssmodel.selectors.conditions.SelectorConditionType;
import ca.concordia.cssanalyser.migration.topreprocessors.less.LessPreprocessorNodeFinder;
import ca.concordia.cssanalyser.parser.ParseException;
import com.github.sommeri.less4j.core.ast.ASTCssNode;
import com.github.sommeri.less4j.core.ast.BinaryExpression;
import com.github.sommeri.less4j.core.ast.ColorExpression;
import com.github.sommeri.less4j.core.ast.ColorExpression.ColorWithAlphaExpression;
import com.github.sommeri.less4j.core.ast.CssClass;
import com.github.sommeri.less4j.core.ast.CssString;
import com.github.sommeri.less4j.core.ast.Expression;
import com.github.sommeri.less4j.core.ast.FixedMediaExpression;
import com.github.sommeri.less4j.core.ast.FunctionExpression;
import com.github.sommeri.less4j.core.ast.IdSelector;
import com.github.sommeri.less4j.core.ast.IdentifierExpression;
import com.github.sommeri.less4j.core.ast.InterpolableName;
import com.github.sommeri.less4j.core.ast.InterpolatedMediaExpression;
import com.github.sommeri.less4j.core.ast.ListExpression;
import com.github.sommeri.less4j.core.ast.ListExpressionOperator.Operator;
import com.github.sommeri.less4j.core.ast.MediaExpression;
import com.github.sommeri.less4j.core.ast.NamedColorExpression;
import com.github.sommeri.less4j.core.ast.Nth;
import com.github.sommeri.less4j.core.ast.NumberExpression;
import com.github.sommeri.less4j.core.ast.RuleSet;
import com.github.sommeri.less4j.core.ast.SelectorAttribute;
import com.github.sommeri.less4j.core.ast.SelectorPart;
/**
* Adapts a Less StyleSheet object to a CSSAnalyser StyleSheet object
* @author Davood Mazinanian
*
*/
public class LessStyleSheetAdapter {
private static Logger LOGGER = FileLogger.getLogger(LessStyleSheetAdapter.class);
private final ASTCssNode lessStyleSheet;
public LessStyleSheetAdapter(ASTCssNode lessStyleSheet) {
this.lessStyleSheet = lessStyleSheet;
}
private void adapt(StyleSheet ourStyleSheet) {
List<? extends ASTCssNode> nodes = lessStyleSheet.getChilds();
addSelectorsToStyleSheetFromLessASTNodes(ourStyleSheet, nodes);
}
private void addSelectorsToStyleSheetFromLessASTNodes(StyleSheet styleSheet, List<? extends ASTCssNode> nodes) {
addSelectorsToStyleSheetFromLessASTNodes(styleSheet, nodes, null);
}
private void addSelectorsToStyleSheetFromLessASTNodes(StyleSheet styleSheet, List<? extends ASTCssNode> nodes, MediaQueryList mediaQueries) {
for (ASTCssNode node : nodes) {
if (node instanceof RuleSet) {
RuleSet ruleSetNode = (RuleSet)node;
Selector selector = getSelectorFromLessRuleSet(ruleSetNode);
if (mediaQueries != null)
selector.addMediaQueryList(mediaQueries);
styleSheet.addSelector(selector);
} else if (node instanceof com.github.sommeri.less4j.core.ast.Media) {
com.github.sommeri.less4j.core.ast.Media lessMedia = (com.github.sommeri.less4j.core.ast.Media)node;
MediaQueryList mediaQueryList = getMediaQueryListFromLessMedia(lessMedia);
addSelectorsToStyleSheetFromLessASTNodes(styleSheet, lessMedia.getBody().getMembers(), mediaQueryList);
}
}
}
private MediaQueryList getMediaQueryListFromLessMedia(com.github.sommeri.less4j.core.ast.Media lessMedia) {
// x and y, z and t is a list of media queries containing two media queries
MediaQueryList mediaQueryList = new MediaQueryList();
for (com.github.sommeri.less4j.core.ast.MediaQuery lessMediaQuery : lessMedia.getMediums()) {
MediaQueryPrefix prefix = null;
String mediumType = "";
if (lessMediaQuery.getMedium() != null) {
if (lessMediaQuery.getMedium().getModifier() != null) {
switch (lessMediaQuery.getMedium().getModifier().getModifier()) {
case NOT:
prefix = MediaQueryPrefix.NOT;
break;
case ONLY:
prefix = MediaQueryPrefix.ONLY;
break;
case NONE:
default:
prefix = null;
break;
}
}
if (lessMediaQuery.getMedium().getMediumType() != null)
mediumType = lessMediaQuery.getMedium().getMediumType().getName();
}
MediaQuery query = new MediaQuery(prefix, mediumType);
for (MediaExpression lessMediaExpression : lessMediaQuery.getExpressions()) {
try {
String feature = "";
String expression = "";
if (lessMediaExpression instanceof FixedMediaExpression) {
FixedMediaExpression fixedMediaExpression = (FixedMediaExpression)lessMediaExpression;
if (fixedMediaExpression.getExpression() != null) {
// Lets re-use a method that we already have, in an ugly manner
List<DeclarationValue> values = getListOfDeclarationValuesFromLessExpression("fake", fixedMediaExpression.getExpression());
for (DeclarationValue value : values)
expression += value;
}
feature = fixedMediaExpression.getFeature().getFeature();
} else if (lessMediaExpression instanceof InterpolatedMediaExpression) {
throw new RuntimeException("What is " + lessMediaExpression);
}
MediaFeatureExpression featureExpression = new MediaFeatureExpression(feature, expression);
featureExpression.setLocationInfo(LessPreprocessorNodeFinder.getLocationInfoForLessASTCssNode(lessMediaExpression));
query.addMediaFeatureExpression(featureExpression);
} catch (ParseException ex) {
LOGGER.warn(String.format("Ignored media expression %s", lessMediaExpression.toString()));
}
}
query.setLocationInfo(LessPreprocessorNodeFinder.getLocationInfoForLessASTCssNode(lessMediaQuery));
mediaQueryList.addMediaQuery(query);
}
mediaQueryList.setLocationInfo(LessPreprocessorNodeFinder.getLocationInfoForLessASTCssNode(lessMedia));
return mediaQueryList;
}
public Selector getSelectorFromLessRuleSet(RuleSet ruleSetNode) {
Selector selector = null;
if (ruleSetNode.getSelectors().size() == 1) { // One selector, this is a base selector
selector = getBaseSelectorFromLessSelector(ruleSetNode.getSelectors().get(0));
} else { // More than 1 selector, this is a grouping selector
GroupingSelector grouping = new GroupingSelector();
for (com.github.sommeri.less4j.core.ast.Selector lessSelector : ruleSetNode.getSelectors()) {
grouping.add(getBaseSelectorFromLessSelector(lessSelector));
}
selector = grouping;
}
selector.setLocationInfo(LessPreprocessorNodeFinder.getLocationInfoForLessASTCssNode(ruleSetNode));
// Handle declarations
addDeclarationsToSelectorFromLessRuleSetNode(ruleSetNode, selector);
return selector;
}
private void addDeclarationsToSelectorFromLessRuleSetNode(RuleSet ruleSetNode, Selector selector) {
for (ASTCssNode declarationNode : ruleSetNode.getBody().getDeclarations()) {
Declaration declaration = getDeclarationFromLessDeclaration(declarationNode);
if (declaration != null)
selector.addDeclaration(declaration);
}
}
public Declaration getDeclarationFromLessDeclaration(ASTCssNode declarationNode) {
Declaration declaration = null;
if (declarationNode instanceof com.github.sommeri.less4j.core.ast.Declaration) {
try {
com.github.sommeri.less4j.core.ast.Declaration lessDeclaration = (com.github.sommeri.less4j.core.ast.Declaration)declarationNode;
String property = lessDeclaration.getNameAsString();
List<DeclarationValue> values;
if (lessDeclaration.getExpression() != null) {
values = getListOfDeclarationValuesFromLessExpression(property, lessDeclaration.getExpression());
} else { // If a declaration does not have a value, happened in some cases
values = new ArrayList<>();
values.add(new DeclarationValue("", ValueType.OTHER));
}
if (values.size() == 0) {
LOGGER.warn(String.format("No CSS values could be found for property %s at line %s, column %s", property,
lessDeclaration.getSourceLine(), lessDeclaration.getSourceColumn()));
} else {
declaration = DeclarationFactory.getDeclaration(
property, values, null, lessDeclaration.isImportant(), true, LessPreprocessorNodeFinder.getLocationInfoForLessASTCssNode(declarationNode));
}
} catch (Exception ex) {
LOGGER.warn("Could not read " + declarationNode + "; " + ex);
}
} else {
throw new RuntimeException("What is that?" + declarationNode);
}
return declaration;
}
private List<DeclarationValue> getListOfDeclarationValuesFromLessExpression(String property, Expression expression) throws ParseException {
List<DeclarationValue> values = new ArrayList<>();
if (expression instanceof ListExpression) {
ListExpression listExpression = (ListExpression)expression;
for (Iterator<Expression> iterator = listExpression.getExpressions().iterator(); iterator.hasNext();) {
Expression expr = iterator.next();
List<DeclarationValue> vals = getListOfDeclarationValuesFromLessExpression(property, expr);
values.addAll(vals);
if (listExpression.getOperator() != null) {
if (listExpression.getOperator().getOperator() == Operator.COMMA) {
if (iterator.hasNext()) {
DeclarationValue value = DeclarationValueFactory.getDeclarationValue(property, ",", ValueType.SEPARATOR);
value.setLocationInfo(LessPreprocessorNodeFinder.getLocationInfoForLessASTCssNode(listExpression.getOperator()));
values.add(value);
}
} else if (listExpression.getOperator().getOperator() == Operator.EMPTY_OPERATOR) {
// Do nothing
} else {
throw new RuntimeException("Operator = " + listExpression.getOperator());
}
} else {
throw new RuntimeException("Operator = " + listExpression.getOperator());
}
}
} else if (expression instanceof BinaryExpression) {
BinaryExpression binary = (BinaryExpression)expression;
values.addAll(getListOfDeclarationValuesFromLessExpression(property, binary.getLeft()));
// Operator
DeclarationValueFactory.getDeclarationValue(property, binary.getOperator().toString(), ValueType.OPERATOR);
DeclarationValue operator = DeclarationValueFactory.getDeclarationValue(property, binary.getOperator().toString(), ValueType.OPERATOR);
operator.setLocationInfo(LessPreprocessorNodeFinder.getLocationInfoForLessASTCssNode(binary.getOperator()));
values.add(operator);
values.addAll(getListOfDeclarationValuesFromLessExpression(property, binary.getRight()));
} else {
values.add(getSingleValueFromLessValueExpression(property, expression));
}
return values;
}
private DeclarationValue getSingleValueFromLessValueExpression(String property, Expression expression) throws ParseException {
DeclarationValue value = null;
if (expression instanceof NumberExpression) {
NumberExpression numberExpression = (NumberExpression)expression;
value = getDeclarationValueFromLessNumberExpression(property, numberExpression);
} else if (expression instanceof NamedColorExpression) {
NamedColorExpression namedExpression = (NamedColorExpression)expression;
value = DeclarationValueFactory.getDeclarationValue(property, namedExpression.getColorName(), ValueType.IDENT);
} else if (expression instanceof ColorWithAlphaExpression) {
ColorWithAlphaExpression colorWithAlpha = (ColorWithAlphaExpression)expression;
throw new RuntimeException(colorWithAlpha.toString());
} else if (expression instanceof IdentifierExpression) {
IdentifierExpression identifier = (IdentifierExpression)expression;
String valueString = identifier.getValue();
if (valueString == null)
valueString = "";
value = DeclarationValueFactory.getDeclarationValue(property, valueString, ValueType.IDENT);
} else if (expression instanceof ColorExpression) {
ColorExpression colorExpression = (ColorExpression) expression;
value = DeclarationValueFactory.getDeclarationValue(property, colorExpression.getValue(), ValueType.COLOR);
} else if (expression instanceof FunctionExpression) {
FunctionExpression function = (FunctionExpression)expression;
String functionName = function.getName();
if ("rgb".equals(functionName) || "hsl".equals(functionName) || "rgba".equals(functionName) || "hsla".equals(functionName)) {
String functionString = getFunctionStringFromLessFunctionExpression(property, function);
value = DeclarationValueFactory.getDeclarationValue(property, functionString, ValueType.COLOR);
} else if(functionName.equals("url")) {
if (function.getParameter().getChilds().get(1) instanceof CssString) {
String url = "url('" + ((CssString)function.getParameter().getChilds().get(1)).getValue() + "')";
value = DeclarationValueFactory.getDeclarationValue(property, url, ValueType.URL);
} else {
throw new RuntimeException("What is that?" + expression);
}
} else {
String functionString = getFunctionStringFromLessFunctionExpression(property, function);
value = DeclarationValueFactory.getDeclarationValue(property, functionString, ValueType.FUNCTION);
}
} else if (expression instanceof CssString) {
value = DeclarationValueFactory.getDeclarationValue(property, "'" + ((CssString)expression).getValue() + "'", ValueType.STRING);
//} else if (expression instanceof Variable) {
// value = DeclarationValueFactory.getDeclarationValue(property, expression.toString(), ValueType.OTHER);
} else {
throw new RuntimeException("What is that?" + expression);
}
value.setLocationInfo(LessPreprocessorNodeFinder.getLocationInfoForLessASTCssNode(expression));
return value;
}
private DeclarationValue getDeclarationValueFromLessNumberExpression(String property, NumberExpression numberExpression) throws ParseException {
DeclarationValue value = null;
switch(numberExpression.getDimension()) {
case ANGLE:
value = DeclarationValueFactory.getDeclarationValue(property, numberExpression.getOriginalString(), ValueType.ANGLE);
case EMS:
case EXS:
case LENGTH:
value = DeclarationValueFactory.getDeclarationValue(property, numberExpression.getOriginalString(), ValueType.LENGTH);
break;
case FREQ:
value = DeclarationValueFactory.getDeclarationValue(property, numberExpression.getOriginalString(), ValueType.FREQUENCY);
break;
case NUMBER:
if (numberExpression.getOriginalString().indexOf(".") > -1)
value = DeclarationValueFactory.getDeclarationValue(property, DeclarationValueFactory.formatFloat(numberExpression.getValueAsDouble()), ValueType.REAL);
else
value = DeclarationValueFactory.getDeclarationValue(property, DeclarationValueFactory.formatFloat(numberExpression.getValueAsDouble()), ValueType.INTEGER);
break;
case PERCENTAGE:
value = DeclarationValueFactory.getDeclarationValue(property, numberExpression.getOriginalString(), ValueType.PERCENTAGE);
break;
case REPEATER:
throw new RuntimeException("What is " + property + ":" + numberExpression.getOriginalString());
case TIME:
value = DeclarationValueFactory.getDeclarationValue(property, numberExpression.getOriginalString(), ValueType.TIME);
break;
case UNKNOWN:
if ("turn".equals(numberExpression.getSuffix().toLowerCase()))
value = DeclarationValueFactory.getDeclarationValue(property, numberExpression.getOriginalString(), ValueType.ANGLE);
else if ("rem".equals(numberExpression.getSuffix().toLowerCase()))
value = DeclarationValueFactory.getDeclarationValue(property, numberExpression.getOriginalString(), ValueType.PERCENTAGE);
else
throw new ParseException("What is " + property + ":" + numberExpression.getOriginalString());
default:
break;
}
value.setLocationInfo(LessPreprocessorNodeFinder.getLocationInfoForLessASTCssNode(numberExpression));
return value;
}
private String getFunctionStringFromLessFunctionExpression(String property, FunctionExpression function) throws ParseException {
StringBuilder functionString = new StringBuilder(function.getName());
functionString.append("(");
List<DeclarationValue> values = getListOfDeclarationValuesFromLessExpression(property, function.getParameter());
for (Iterator<DeclarationValue> iterator = values.iterator(); iterator.hasNext(); ) {
DeclarationValue value = iterator.next();
if ("".equals(value.getValue()))
throw new ParseException(String.format("Could not parse one of the parameters for function %s at <%s:%s>", function.getName(), function.getSourceLine(), function.getSourceColumn()));
if (value.getType() != ValueType.SEPARATOR && !functionString.toString().endsWith("(")) {
functionString.append(" ");
}
functionString.append(value.getValue());
}
functionString.append(")");
return functionString.toString();
}
/**
* Converts a Less4j Selector which only has one child to a BaseSelector.
* A Less4j Selector might be a combinator or a simple selector.
* @param lessSelector
* @return
*/
private BaseSelector getBaseSelectorFromLessSelector(com.github.sommeri.less4j.core.ast.Selector lessSelector) {
BaseSelector toReturn = null;
// In the Less selector, every part is a simple selector
if (lessSelector.getParts().size() == 1) { // simple selector, not a combinator
toReturn = getSimpleSelectorFromLessSelectorPart(lessSelector.getParts().get(0));
} else { // combinator
toReturn = getCombinatorFromLessSelectorParts(lessSelector.getParts());
}
return toReturn;
}
private BaseSelector getCombinatorFromLessSelectorParts(List<SelectorPart> parts) {
if (parts.size() == 0)
return null;
// Don't touch the original list
List<SelectorPart> partsCopy = new ArrayList<>(parts);
// Get the right most selector. It is always a SimpleSelector
SelectorPart lastPart = partsCopy.get(partsCopy.size() - 1);
SimpleSelector rightHandSelector = getSimpleSelectorFromLessSelectorPart(lastPart);
BaseSelector baseSelectorToReturn = rightHandSelector;
partsCopy.remove(partsCopy.size() - 1);
if (partsCopy.size() != 0) {
BaseSelector leftHandSelector = getCombinatorFromLessSelectorParts(partsCopy);
switch (lastPart.getLeadingCombinator().getCombinator()) {
//ADJACENT_SIBLING("+"), CHILD(">"), DESCENDANT("' '"), GENERAL_SIBLING("~"), HAT("^"), CAT("^^");
case ADJACENT_SIBLING:
baseSelectorToReturn = new AdjacentSiblingSelector(leftHandSelector, rightHandSelector);
break;
case CHILD:
baseSelectorToReturn = new ChildSelector(leftHandSelector, rightHandSelector);
break;
case DESCENDANT:
baseSelectorToReturn = new DescendantSelector(leftHandSelector, rightHandSelector);
break;
case GENERAL_SIBLING:
baseSelectorToReturn = new SiblingSelector(leftHandSelector, rightHandSelector);
break;
case HAT:
case CAT:
// Not supported
return null;
}
int lineNumber = leftHandSelector.getSelectorNameLocationInfo().getLineNumber();
int colNumber = leftHandSelector.getSelectorNameLocationInfo().getColumnNumber();
int offset = leftHandSelector.getSelectorNameLocationInfo().getOffset();
int length = rightHandSelector.getSelectorNameLocationInfo().getOffset() + rightHandSelector.getSelectorNameLocationInfo().getLength() - offset;
LocationInfo selectorNameLocationInfo = new LocationInfo(lineNumber, colNumber, offset, length);
baseSelectorToReturn.setSelectorNameLocationInfo(selectorNameLocationInfo);
}
return baseSelectorToReturn;
}
private SimpleSelector getSimpleSelectorFromLessSelectorPart(SelectorPart selectorPart) {
SimpleSelector simpleSelector = new SimpleSelector();
for (ASTCssNode cssASTNode : selectorPart.getChilds()) {
if (cssASTNode instanceof InterpolableName) {
InterpolableName name = (InterpolableName)cssASTNode;
simpleSelector.setSelectedElementName(name.getName());
} else if (cssASTNode instanceof IdSelector) {
IdSelector id = (IdSelector)cssASTNode;
simpleSelector.setElementID(id.getName());
} else if (cssASTNode instanceof CssClass) {
CssClass className = (CssClass)cssASTNode;
simpleSelector.addClassName(className.getName());
} else if (cssASTNode instanceof SelectorAttribute) {
SelectorAttribute attribute = (SelectorAttribute)cssASTNode;
SelectorCondition condition = new SelectorCondition(attribute.getName());
SelectorConditionType adaptedConditionType = null;
switch (attribute.getOperator().getOperator()) {
case NONE:
adaptedConditionType = SelectorConditionType.HAS_ATTRIBUTE;
break;
case EQUALS:
adaptedConditionType = SelectorConditionType.VALUE_EQUALS_EXACTLY;
break;
case INCLUDES:
adaptedConditionType = SelectorConditionType.VALUE_CONTAINS_WORD_SPACE_SEPARATED;
break;
case PREFIXMATCH:
adaptedConditionType = SelectorConditionType.VALUE_STARTS_WITH;
break;
case SPECIAL_PREFIX:
adaptedConditionType = SelectorConditionType.VALUE_START_WITH_DASH_SEPARATED;
break;
case SUBSTRINGMATCH:
adaptedConditionType = SelectorConditionType.VALUE_CONTAINS;
break;
case SUFFIXMATCH:
adaptedConditionType = SelectorConditionType.VALUE_ENDS_WITH;
}
condition.setConditionType(adaptedConditionType);
if (adaptedConditionType != SelectorConditionType.HAS_ATTRIBUTE)
condition.setValue(attribute.getValue().toString());
simpleSelector.addCondition(condition);
} else if (cssASTNode instanceof com.github.sommeri.less4j.core.ast.PseudoClass) {
com.github.sommeri.less4j.core.ast.PseudoClass pseudoClass = (com.github.sommeri.less4j.core.ast.PseudoClass) cssASTNode;
PseudoClass adaptedPseudoClass = null;
if ("not".equals(pseudoClass.getName().toLowerCase())) {
com.github.sommeri.less4j.core.ast.Selector parameter = (com.github.sommeri.less4j.core.ast.Selector)pseudoClass.getParameter();
adaptedPseudoClass = new NegationPseudoClass(getBaseSelectorFromLessSelector(parameter));
} else {
adaptedPseudoClass = new PseudoClass(pseudoClass.getName());
if (pseudoClass.hasParameters()) {
if (pseudoClass.getParameter() instanceof Nth) {
adaptedPseudoClass.setValue(NthToString((Nth)pseudoClass.getParameter()));
} else if ("lang".equals(pseudoClass.getName().toLowerCase())) {
adaptedPseudoClass.setValue(pseudoClass.getParameter().toString());
} else {
throw new NotImplementedException("Unhandled parameter for pseudo class :" + pseudoClass.getParameter());
}
}
}
simpleSelector.addPseudoClass(adaptedPseudoClass);
} else if (cssASTNode instanceof com.github.sommeri.less4j.core.ast.PseudoElement) {
com.github.sommeri.less4j.core.ast.PseudoElement pseudoElement = (com.github.sommeri.less4j.core.ast.PseudoElement) cssASTNode;
PseudoElement adaptedPseudoElement = new PseudoElement(pseudoElement.getName());
simpleSelector.addPseudoElement(adaptedPseudoElement);
}
}
simpleSelector.setSelectorNameLocationInfo(LessPreprocessorNodeFinder.getLocationInfoForLessASTCssNode(selectorPart));
return simpleSelector;
}
private String NthToString(Nth parameter) {
String toReturn = "";
switch (parameter.getForm()) {
case EVEN:
toReturn = "even";
break;
case ODD:
toReturn = "odd";
case STANDARD:
if (parameter.getRepeater() != null)
toReturn = parameter.getRepeater().toString();
if (parameter.getMod() != null)
toReturn += parameter.getMod().toString();
break;
}
return toReturn;
}
public StyleSheet getAdaptedStyleSheet() {
StyleSheet ourStyleSheet = new StyleSheet();
ourStyleSheet.setPath(lessStyleSheet.getSource().toString());
adapt(ourStyleSheet);
return ourStyleSheet;
}
public ASTCssNode getLessStyleSheet() {
return lessStyleSheet;
}
}
|
package jme3tools.optimize;
import com.jme3.material.Material;
import com.jme3.math.Matrix4f;
import com.jme3.math.Transform;
import com.jme3.math.Vector3f;
import com.jme3.scene.Mesh.Mode;
import com.jme3.scene.*;
import com.jme3.scene.VertexBuffer.Format;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.scene.VertexBuffer.Usage;
import com.jme3.scene.mesh.IndexBuffer;
import com.jme3.util.BufferUtils;
import com.jme3.util.IntMap.Entry;
import java.nio.Buffer;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;
import java.util.*;
import java.util.logging.Logger;
public class GeometryBatchFactory {
private static final Logger logger = Logger.getLogger(GeometryBatchFactory.class.getName());
private static void doTransformVerts(FloatBuffer inBuf, int offset, FloatBuffer outBuf, Matrix4f transform) {
Vector3f pos = new Vector3f();
// offset is given in element units
// convert to be in component units
offset *= 3;
for (int i = 0; i < inBuf.capacity() / 3; i++) {
pos.x = inBuf.get(i * 3 + 0);
pos.y = inBuf.get(i * 3 + 1);
pos.z = inBuf.get(i * 3 + 2);
transform.mult(pos, pos);
outBuf.put(offset + i * 3 + 0, pos.x);
outBuf.put(offset + i * 3 + 1, pos.y);
outBuf.put(offset + i * 3 + 2, pos.z);
}
}
private static void doTransformNorms(FloatBuffer inBuf, int offset, FloatBuffer outBuf, Matrix4f transform) {
Vector3f norm = new Vector3f();
// offset is given in element units
// convert to be in component units
offset *= 3;
for (int i = 0; i < inBuf.capacity() / 3; i++) {
norm.x = inBuf.get(i * 3 + 0);
norm.y = inBuf.get(i * 3 + 1);
norm.z = inBuf.get(i * 3 + 2);
transform.multNormal(norm, norm);
outBuf.put(offset + i * 3 + 0, norm.x);
outBuf.put(offset + i * 3 + 1, norm.y);
outBuf.put(offset + i * 3 + 2, norm.z);
}
}
private static void doTransformTangents(FloatBuffer inBuf, int offset, int components, FloatBuffer outBuf, Matrix4f transform) {
Vector3f tan = new Vector3f();
float handedness;
// offset is given in element units
// convert to be in component units
offset *= components;
for (int i = 0; i < inBuf.capacity() / components; i++) {
tan.x = inBuf.get(i * 4 + 0);
tan.y = inBuf.get(i * 4 + 1);
tan.z = inBuf.get(i * 4 + 2);
handedness = inBuf.get(i * 4 + 3);
transform.multNormal(tan, tan);
outBuf.put(offset + i * 4 + 0, tan.x);
outBuf.put(offset + i * 4 + 1, tan.y);
outBuf.put(offset + i * 4 + 2, tan.z);
outBuf.put(offset + i * 4 + 3, handedness);
}
}
/**
* Merges all geometries in the collection into
* the output mesh. Creates a new material using the TextureAtlas.
*
* @param geometries
* @param outMesh
*/
public static void mergeGeometries(Collection<Geometry> geometries, Mesh outMesh) {
int[] compsForBuf = new int[VertexBuffer.Type.values().length];
Format[] formatForBuf = new Format[compsForBuf.length];
int totalVerts = 0;
int totalTris = 0;
int totalLodLevels = 0;
Mode mode = null;
for (Geometry geom : geometries) {
totalVerts += geom.getVertexCount();
totalTris += geom.getTriangleCount();
totalLodLevels = Math.min(totalLodLevels, geom.getMesh().getNumLodLevels());
Mode listMode;
int components;
switch (geom.getMesh().getMode()) {
case Points:
listMode = Mode.Points;
components = 1;
break;
case LineLoop:
case LineStrip:
case Lines:
listMode = Mode.Lines;
components = 2;
break;
case TriangleFan:
case TriangleStrip:
case Triangles:
listMode = Mode.Triangles;
components = 3;
break;
default:
throw new UnsupportedOperationException();
}
for (Entry<VertexBuffer> entry : geom.getMesh().getBuffers()) {
compsForBuf[entry.getKey()] = entry.getValue().getNumComponents();
formatForBuf[entry.getKey()] = entry.getValue().getFormat();
}
if (mode != null && mode != listMode) {
throw new UnsupportedOperationException("Cannot combine different"
+ " primitive types: " + mode + " != " + listMode);
}
mode = listMode;
compsForBuf[Type.Index.ordinal()] = components;
}
outMesh.setMode(mode);
if (totalVerts >= 65536) {
// make sure we create an UnsignedInt buffer so
// we can fit all of the meshes
formatForBuf[Type.Index.ordinal()] = Format.UnsignedInt;
} else {
formatForBuf[Type.Index.ordinal()] = Format.UnsignedShort;
}
// generate output buffers based on retrieved info
for (int i = 0; i < compsForBuf.length; i++) {
if (compsForBuf[i] == 0) {
continue;
}
Buffer data;
if (i == Type.Index.ordinal()) {
data = VertexBuffer.createBuffer(formatForBuf[i], compsForBuf[i], totalTris);
} else {
data = VertexBuffer.createBuffer(formatForBuf[i], compsForBuf[i], totalVerts);
}
VertexBuffer vb = new VertexBuffer(Type.values()[i]);
vb.setupData(Usage.Static, compsForBuf[i], formatForBuf[i], data);
outMesh.setBuffer(vb);
}
int globalVertIndex = 0;
int globalTriIndex = 0;
for (Geometry geom : geometries) {
Mesh inMesh = geom.getMesh();
geom.computeWorldMatrix();
Matrix4f worldMatrix = geom.getWorldMatrix();
int geomVertCount = inMesh.getVertexCount();
int geomTriCount = inMesh.getTriangleCount();
for (int bufType = 0; bufType < compsForBuf.length; bufType++) {
VertexBuffer inBuf = inMesh.getBuffer(Type.values()[bufType]);
VertexBuffer outBuf = outMesh.getBuffer(Type.values()[bufType]);
if (inBuf == null || outBuf == null) {
continue;
}
if (Type.Index.ordinal() == bufType) {
int components = compsForBuf[bufType];
IndexBuffer inIdx = inMesh.getIndicesAsList();
IndexBuffer outIdx = outMesh.getIndexBuffer();
for (int tri = 0; tri < geomTriCount; tri++) {
for (int comp = 0; comp < components; comp++) {
int idx = inIdx.get(tri * components + comp) + globalVertIndex;
outIdx.put((globalTriIndex + tri) * components + comp, idx);
}
}
} else if (Type.Position.ordinal() == bufType) {
FloatBuffer inPos = (FloatBuffer) inBuf.getDataReadOnly();
FloatBuffer outPos = (FloatBuffer) outBuf.getData();
doTransformVerts(inPos, globalVertIndex, outPos, worldMatrix);
} else if (Type.Normal.ordinal() == bufType) {
FloatBuffer inPos = (FloatBuffer) inBuf.getDataReadOnly();
FloatBuffer outPos = (FloatBuffer) outBuf.getData();
doTransformNorms(inPos, globalVertIndex, outPos, worldMatrix);
}else if(Type.Tangent.ordinal() == bufType){
FloatBuffer inPos = (FloatBuffer) inBuf.getDataReadOnly();
FloatBuffer outPos = (FloatBuffer) outBuf.getData();
int components = inBuf.getNumComponents();
doTransformTangents(inPos, globalVertIndex, components, outPos, worldMatrix);
} else {
inBuf.copyElements(0, outBuf, globalVertIndex, geomVertCount);
}
}
globalVertIndex += geomVertCount;
globalTriIndex += geomTriCount;
}
}
public static void makeLods(Collection<Geometry> geometries, Mesh outMesh) {
int lodLevels = 0;
int[] lodSize = null;
int index = 0;
for (Geometry g : geometries) {
if (lodLevels == 0) {
lodLevels = g.getMesh().getNumLodLevels();
}
if (lodSize == null) {
lodSize = new int[lodLevels];
}
for (int i = 0; i < lodLevels; i++) {
lodSize[i] += g.getMesh().getLodLevel(i).getData().capacity();
//if( i == 0) System.out.println(index + " " +lodSize[i]);
}
index++;
}
int[][] lodData = new int[lodLevels][];
for (int i = 0; i < lodLevels; i++) {
lodData[i] = new int[lodSize[i]];
}
VertexBuffer[] lods = new VertexBuffer[lodLevels];
int bufferPos[] = new int[lodLevels];
//int index = 0;
int numOfVertices = 0;
int curGeom = 0;
for (Geometry g : geometries) {
if (numOfVertices == 0) {
numOfVertices = g.getVertexCount();
}
for (int i = 0; i < lodLevels; i++) {
ShortBuffer buffer = (ShortBuffer) g.getMesh().getLodLevel(i).getDataReadOnly();
//System.out.println("buffer: " + buffer.capacity() + " limit: " + lodSize[i] + " " + index);
for (int j = 0; j < buffer.capacity(); j++) {
lodData[i][bufferPos[i] + j] = buffer.get() + numOfVertices * curGeom;
//bufferPos[i]++;
}
bufferPos[i] += buffer.capacity();
}
curGeom++;
}
for (int i = 0; i < lodLevels; i++) {
lods[i] = new VertexBuffer(Type.Index);
lods[i].setupData(Usage.Dynamic, 1, Format.UnsignedInt, BufferUtils.createIntBuffer(lodData[i]));
}
System.out.println(lods.length);
outMesh.setLodLevels(lods);
}
public static List<Geometry> makeBatches(Collection<Geometry> geometries) {
return makeBatches(geometries, false);
}
/**
* Batches a collection of Geometries so that all with the same material get combined.
* @param geometries The Geometries to combine
* @return A List of newly created Geometries, each with a distinct material
*/
public static List<Geometry> makeBatches(Collection<Geometry> geometries, boolean useLods) {
ArrayList<Geometry> retVal = new ArrayList<Geometry>();
HashMap<Material, List<Geometry>> matToGeom = new HashMap<Material, List<Geometry>>();
for (Geometry geom : geometries) {
List<Geometry> outList = matToGeom.get(geom.getMaterial());
if (outList == null) {
outList = new ArrayList<Geometry>();
matToGeom.put(geom.getMaterial(), outList);
}
outList.add(geom);
}
int batchNum = 0;
for (Map.Entry<Material, List<Geometry>> entry : matToGeom.entrySet()) {
Material mat = entry.getKey();
List<Geometry> geomsForMat = entry.getValue();
Mesh mesh = new Mesh();
mergeGeometries(geomsForMat, mesh);
// lods
if (useLods) {
makeLods(geomsForMat, mesh);
}
mesh.updateCounts();
mesh.updateBound();
Geometry out = new Geometry("batch[" + (batchNum++) + "]", mesh);
out.setMaterial(mat);
retVal.add(out);
}
return retVal;
}
public static void gatherGeoms(Spatial scene, List<Geometry> geoms) {
if (scene instanceof Node) {
Node node = (Node) scene;
for (Spatial child : node.getChildren()) {
gatherGeoms(child, geoms);
}
} else if (scene instanceof Geometry) {
geoms.add((Geometry) scene);
}
}
/**
* Optimizes a scene by combining Geometry with the same material.
* All Geometries found in the scene are detached from their parent and
* a new Node containing the optimized Geometries is attached.
* @param scene The scene to optimize
* @return The newly created optimized geometries attached to a node
*/
public static Spatial optimize(Node scene) {
return optimize(scene, false);
}
/**
* Optimizes a scene by combining Geometry with the same material.
* All Geometries found in the scene are detached from their parent and
* a new Node containing the optimized Geometries is attached.
* @param scene The scene to optimize
* @param useLods true if you want the resulting geometry to keep lod information
* @return The newly created optimized geometries attached to a node
*/
public static Node optimize(Node scene, boolean useLods) {
ArrayList<Geometry> geoms = new ArrayList<Geometry>();
gatherGeoms(scene, geoms);
List<Geometry> batchedGeoms = makeBatches(geoms, useLods);
for (Geometry geom : batchedGeoms) {
scene.attachChild(geom);
}
for (Iterator<Geometry> it = geoms.iterator(); it.hasNext();) {
Geometry geometry = it.next();
geometry.removeFromParent();
}
// Since the scene is returned unaltered the transform must be reset
scene.setLocalTransform(Transform.IDENTITY);
return scene;
}
public static void printMesh(Mesh mesh) {
for (int bufType = 0; bufType < Type.values().length; bufType++) {
VertexBuffer outBuf = mesh.getBuffer(Type.values()[bufType]);
if (outBuf == null) {
continue;
}
System.out.println(outBuf.getBufferType() + ": ");
for (int vert = 0; vert < outBuf.getNumElements(); vert++) {
String str = "[";
for (int comp = 0; comp < outBuf.getNumComponents(); comp++) {
Object val = outBuf.getElementComponent(vert, comp);
outBuf.setElementComponent(vert, comp, val);
val = outBuf.getElementComponent(vert, comp);
str += val;
if (comp != outBuf.getNumComponents() - 1) {
str += ", ";
}
}
str += "]";
System.out.println(str);
}
System.out.println("
}
}
public static void main(String[] args) {
Mesh mesh = new Mesh();
mesh.setBuffer(Type.Position, 3, new float[]{
0, 0, 0,
1, 0, 0,
1, 1, 0,
0, 1, 0
});
mesh.setBuffer(Type.Index, 2, new short[]{
0, 1,
1, 2,
2, 3,
3, 0
});
Geometry g1 = new Geometry("g1", mesh);
ArrayList<Geometry> geoms = new ArrayList<Geometry>();
geoms.add(g1);
Mesh outMesh = new Mesh();
mergeGeometries(geoms, outMesh);
printMesh(outMesh);
}
}
|
package com.tapad.tracking;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import com.tapad.tracking.deviceidentification.*;
import com.tapad.util.Logging;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
/**
* Public entry-point to the tracking API.
*/
public class Tracking {
protected static final String PREF_TAPAD_DEVICE_ID = "_tapad_device_id";
protected static final String PREF_INSTALL_SENT = "_tapad_install_sent";
protected static final String PREF_FIRST_RUN_SENT = "_tapad_first_run_sent";
protected static final String EVENT_INSTALL = "install";
protected static final String EVENT_FIRST_RUN = "first-run";
public static final String OPTED_OUT_DEVICE_ID = "OptedOut";
private static TrackingService service = null;
private static String deviceId;
private static String typedDeviceIds;
private static IdentifierSource idCollector = new IdentifierSourceAggregator(defaultIdSources());
private static DeviceIdentifier deviceIdLocator = new DeviceIdentifier() {
@Override
public String get() {
return deviceId;
}
@Override
public String getTypedIds() {
return typedDeviceIds;
}
@Override
public boolean isOptedOut() {
return Tracking.isOptedOut();
}
};
/**
* Initializes the tracking API with application id as specified in AndroidManifest.xml:
* <p/>
* <application>
* <meta-data android:name="tapad.APP_ID" android:value="INSERT_APP_ID_HERE"/>
* ...
* </application>
* <p/>
* The default id sources are AndroidId, PhoneId, and WifiMac, but
* this can be configured to suit the developer's privacy policy through the AndroidManifest.xml:
* <p/>
* <application>
* <meta-data android:name="tapad.ID_SOURCES" android:value="AndroidId,PhoneId,WifiMac"/>
* ...
* </application>
*
* @param context a context reference
*/
public static void init(Context context) {
init(context, null, null);
}
/**
* Initializes the tracking API using the supplied application id. If the
* supplied value is null or consist only of white space, then the AndroidManifest.xml
* values are used (@see #init(android.content.Context)).
* <p/>
* If the idSources is null or empty, then the AndroidManifest.xml values are used (@see #init(android.content.Context)).
* <p/>
* One of the initialization functions must be called before TrackingService.get().
*
* @param context a context reference
* @param appId the application identifier
* @param idSources a list of identifier sources to use to collect ids
* @see #init(android.content.Context)
*/
public static void init(Context context, String appId, List<IdentifierSource> idSources) {
setupAPI(context, appId, idSources);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// The install event may have been sent by the InstallReferrerReceiver,
// so first-run and install are not always sent at the same time.
// Since 3.x, the marketplace behavior has been to fire the INSTALL_REFERRER intent
// after first launch. So we are leaving FIRST_RUN here and letting the InstallReferrerReceiver
// fire the INSTALL event. Otherwise, we will either get two install events or one without the
// referrer value, which is useful for determining proper attribution.
if (!prefs.getBoolean(PREF_FIRST_RUN_SENT, false)) {
get().onEvent(EVENT_FIRST_RUN);
prefs.edit().putBoolean(PREF_FIRST_RUN_SENT, true).commit();
}
}
/**
* Configures the API.
*/
protected static void setupAPI(Context context, String appId, List<IdentifierSource> idSources) {
synchronized (Tracking.class) {
if (service == null) {
if (appId == null || appId.trim().length() == 0) {
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
Object appIdMetaData = ai.metaData.get("tapad.APP_ID");
if (appIdMetaData == null)
throw new RuntimeException("tapad.APP_ID is not set in AndroidManifest.xml");
else
appId = appIdMetaData.toString();
} catch (Exception e) {
throw new RuntimeException("No app id specified and unable to read tapad.APP_ID from AndroidManifest.xml", e);
}
}
if (idSources == null || idSources.isEmpty()) {
try {
ApplicationInfo ai = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
String[] idSourceClasses = ai.metaData.getString("tapad.ID_SOURCES").split(",");
idSources = new ArrayList<IdentifierSource>();
for (String className : idSourceClasses) {
try {
idSources.add((IdentifierSource) Class.forName("com.tapad.tracking.deviceidentification." + className.trim()).newInstance());
} catch (Exception e) {
Logging.warn("Tracking", "Unable to instantiate identifier source: " + className.trim());
}
}
if (idSources.isEmpty()) {
idSources = defaultIdSources();
}
} catch (Exception e) {
idSources = defaultIdSources();
}
}
idCollector = new IdentifierSourceAggregator(idSources);
collectIds(context);
service = new TrackingServiceImpl(
new EventDispatcher(new EventResource(appId, deviceIdLocator, DeviceInfo.getUserAgent(context)))
);
}
}
}
/**
* Creates the default identifier sources to use should none be specified.
* The default is all.
*
* @return the list of default id sources
*/
private static List<IdentifierSource> defaultIdSources() {
return Arrays.asList(new AndroidId(), new PhoneId(), new WifiMac());
}
/**
* Uses the idCollector to generate ids, if any. This is not done if the user is already opted out through
* preferences. If there were no ids generated, a random UUID is generated and persisted through
* preferences.
*
* @param context context object used to find/collect/persist ids
*/
private static void collectIds(Context context) {
deviceId = PreferenceManager.getDefaultSharedPreferences(context).getString(PREF_TAPAD_DEVICE_ID, null);
// do not attempt to collect any ids if the device is opted out
if (OPTED_OUT_DEVICE_ID.equals(deviceId)) {
typedDeviceIds = null;
} else {
// collect ids
List<TypedIdentifier> ids = idCollector.get(context);
// if no ids
if (ids.isEmpty()) {
// generate and store a new id if there is no saved id
if (deviceId == null) {
Logging.warn("Tracking", "Unable to retrieve any device identifiers, using a UUID instead.");
deviceId = UUID.randomUUID().toString();
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(PREF_TAPAD_DEVICE_ID, deviceId).commit();
}
// ensure that typed id is set to null
typedDeviceIds = null;
} else {
// set the deviceId to the first typed id, but don't save it in prefs because that space is reserved for the generated UUID/Opt-out
deviceId = ids.get(0).getValue();
// set the typedDeviceIds to the full string representation
typedDeviceIds = TextUtils.join(",", ids);
}
}
}
/**
* Opts the device out of all tracking / personalization by setting the device id to the constant
* string OptedOut. This means that it is now impossible to distinguish this device from all
* other opted out device.
*
* @param context a context reference
*/
public static void optOut(Context context) {
deviceId = OPTED_OUT_DEVICE_ID;
typedDeviceIds = null;
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.putString(PREF_TAPAD_DEVICE_ID, deviceId)
.commit();
}
/**
* Opts the device back in after an opt out.
*
* @param context a context reference
*/
public static void optIn(Context context) {
// we clear the saved preferences and run through id collection logic once more
PreferenceManager.getDefaultSharedPreferences(context)
.edit()
.remove(PREF_TAPAD_DEVICE_ID)
.commit();
collectIds(context);
}
private static void assertInitialized() {
if (service == null)
throw new IllegalStateException("Please call Tracking.init(context) to initialize the API first!");
}
/**
* Gets device identifier locator used by the Tracking API.
*
* @return the identifier locator
*/
public static DeviceIdentifier getDeviceId() {
assertInitialized();
return deviceIdLocator;
}
/**
* Checks if the device is opted out of tracking. Note that the opt out is enforced by the API itself,
* so this check is just for UI purposes (e.g, determine if the opt out checkbox should be checked or not).
*
* @return true if the device is opted out
*/
public static boolean isOptedOut() {
assertInitialized();
return OPTED_OUT_DEVICE_ID.equals(deviceId);
}
public static TrackingService get() {
assertInitialized();
return service;
}
}
|
package com.googlecode.jsonrpc4j;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import static com.googlecode.jsonrpc4j.Util.hasNonNullObjectData;
import static com.googlecode.jsonrpc4j.Util.hasNonNullTextualData;
/**
* Default implementation of the {@link ExceptionResolver} interface that attempts to re-throw the same exception
* that was thrown by the server. This always returns a {@link Throwable}.
*/
@SuppressWarnings("WeakerAccess")
public enum DefaultExceptionResolver implements ExceptionResolver {
INSTANCE;
private static final Logger logger = LoggerFactory.getLogger(DefaultExceptionResolver.class);
/**
* {@inheritDoc}
*/
public Throwable resolveException(ObjectNode response) {
ObjectNode errorObject = ObjectNode.class.cast(response.get(JsonRpcBasicServer.ERROR));
if (!hasNonNullObjectData(errorObject, JsonRpcBasicServer.DATA))
return createJsonRpcClientException(errorObject);
ObjectNode dataObject = ObjectNode.class.cast(errorObject.get(JsonRpcBasicServer.DATA));
if (!hasNonNullTextualData(dataObject, JsonRpcBasicServer.EXCEPTION_TYPE_NAME))
return createJsonRpcClientException(errorObject);
try {
String exceptionTypeName = dataObject.get(JsonRpcBasicServer.EXCEPTION_TYPE_NAME).asText();
String message = hasNonNullTextualData(dataObject, JsonRpcBasicServer.ERROR_MESSAGE) ? dataObject.get(JsonRpcBasicServer.ERROR_MESSAGE).asText() : null;
return createThrowable(exceptionTypeName, message);
} catch (Exception e) {
logger.warn("Unable to create throwable", e);
return createJsonRpcClientException(errorObject);
}
}
/**
* Creates a {@link JsonRpcClientException} from the given
* {@link ObjectNode}.
*
* @param errorObject the error object
* @return the exception
*/
private JsonRpcClientException createJsonRpcClientException(ObjectNode errorObject) {
int code = errorObject.has(JsonRpcBasicServer.ERROR_CODE) ? errorObject.get(JsonRpcBasicServer.ERROR_CODE).asInt() : 0;
return new JsonRpcClientException(code, errorObject.get(JsonRpcBasicServer.ERROR_MESSAGE).asText(), errorObject.get(JsonRpcBasicServer.DATA));
}
private Throwable createThrowable(String typeName, String message) throws IllegalAccessException, InvocationTargetException, InstantiationException, ClassNotFoundException {
Class<? extends Throwable> clazz = loadThrowableClass(typeName);
Constructor<? extends Throwable> defaultCtr = getDefaultConstructor(clazz);
Constructor<? extends Throwable> messageCtr = getMessageConstructor(clazz);
if (message != null && messageCtr != null) {
return messageCtr.newInstance(message);
} else if (message != null && defaultCtr != null) {
logger.warn("Unable to invoke message constructor for {}, fallback to default", clazz.getName());
return defaultCtr.newInstance();
} else if (message == null && defaultCtr != null) {
return defaultCtr.newInstance();
} else if (message == null && messageCtr != null) {
logger.warn("Passing null message to message constructor for {}", clazz.getName());
return messageCtr.newInstance((String) null);
} else {
logger.error("Unable to find message or default constructor for {} have {}", clazz.getName(), clazz.getDeclaredConstructors());
return null;
}
}
private Class<? extends Throwable> loadThrowableClass(String typeName) throws ClassNotFoundException {
Class<?> clazz;
try {
clazz = Class.forName(typeName);
if (!Throwable.class.isAssignableFrom(clazz)) {
logger.warn("Type does not inherit from Throwable {}", clazz.getName());
} else {
return clazz.asSubclass(Throwable.class);
}
} catch(ClassNotFoundException e) {
logger.warn("Unable to load Throwable class {}", typeName);
throw e;
} catch(Exception e) {
logger.warn("Unable to load Throwable class {}", typeName);
}
return null;
}
private Constructor<? extends Throwable> getDefaultConstructor(Class<? extends Throwable> clazz) {
Constructor<? extends Throwable> defaultCtr = null;
try {
defaultCtr = clazz.getConstructor();
} catch (NoSuchMethodException e) {
handleException(e);
}
return defaultCtr;
}
private Constructor<? extends Throwable> getMessageConstructor(Class<? extends Throwable> clazz) {
Constructor<? extends Throwable> messageCtr = null;
try {
messageCtr = clazz.getConstructor(String.class);
} catch (NoSuchMethodException e) {
handleException(e);
}
return messageCtr;
}
@SuppressWarnings("UnusedParameters")
private void handleException(Exception e) {
/* do nothing */
}
}
|
package com.t28.draggableview;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.t28.draggablelistview.DraggableListView;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ActionBarActivity implements ItemAdapter.OnItemClickListener {
private DraggableListView mListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (DraggableListView) findViewById(R.id.main_container);
mListView.setHasFixedSize(true);
mListView.setLayoutManager(new LinearLayoutManager(this));
final List<String> dataSet = Arrays.asList(getResources().getStringArray(R.array.lineups));
final ItemAdapter adapter = new ItemAdapter(dataSet);
adapter.setOnItemClickListener(this);
mListView.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onItemClick(View view, int position) {
}
@Override
public void onItemLongClick(View view, int position) {
if (mListView.isDragging()) {
return;
}
mListView.startDrag(view, new DraggableListView.ShadowBuilder(view) {
});
}
}
|
package com.infinityraider.ninjagear.handler;
import com.infinityraider.ninjagear.NinjaGear;
import com.infinityraider.ninjagear.capability.CapabilityNinjaArmor;
import com.infinityraider.ninjagear.item.ItemNinjaArmor;
import net.minecraft.item.ArmorItem;
import net.minecraft.item.ItemStack;
import net.minecraft.util.text.StringTextComponent;
import net.minecraftforge.event.AnvilUpdateEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
public class AnvilHandler {
private static final AnvilHandler INSTANCE = new AnvilHandler();
public static final AnvilHandler getInstance() {
return INSTANCE;
}
private AnvilHandler() {}
@SubscribeEvent
@SuppressWarnings("unused")
public void onAnvilUse(AnvilUpdateEvent event) {
// Fetch input stacks
ItemStack left = event.getLeft();
ItemStack right = event.getRight();
// Verify imbuing conditions
if(left == null || right == null || left.isEmpty() || right.isEmpty()) {
// Do nothing if either slot is empty
return;
}
if(!(left.getItem() instanceof ArmorItem)) {
// Do nothing if the left slot does not contain an armor piece
return;
}
if(!(right.getItem() instanceof ArmorItem)) {
// Do nothing if the right slot does not contain an armor piece
return;
}
if((left.getItem() instanceof ItemNinjaArmor) && (right.getItem() instanceof ItemNinjaArmor)) {
// Do nothing if both slots contain ninja armor
return;
}
if(!(left.getItem() instanceof ItemNinjaArmor) && !(right.getItem() instanceof ItemNinjaArmor)) {
// Do nothing if neither slot contains ninja armor
return;
}
if(((ArmorItem) left.getItem()).getEquipmentSlot() != ((ArmorItem) right.getItem()).getEquipmentSlot()) {
// Do nothing if the slots contain armor pieces for different body parts
return;
}
// Fetch the input ItemStack
ItemStack input = (left.getItem() instanceof ItemNinjaArmor) ? right : left;
// Check if the input stack is imbued already
if(CapabilityNinjaArmor.isNinjaArmor(input)) {
// Do nothing if the input stack is already imbued
return;
}
// Copy the input ItemStack
ItemStack output = input.copy();
// Activate the ninja armor status on the capability
output.getCapability(CapabilityNinjaArmor.CAPABILITY).ifPresent(cap -> cap.setNinjaArmor(true));
// Set the name
String inputName = event.getName();
if(inputName == null || inputName.isEmpty()) {
output.clearCustomName();
} else {
output.setDisplayName(new StringTextComponent(inputName));
}
// Set the output
event.setOutput(output);
// Set the cost
event.setCost(NinjaGear.instance.getConfig().getImbueCost());
}
}
|
package com.github.takuji31.appbase.widget;
import java.util.ArrayList;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.github.takuji31.appbase.app.BaseActivity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
public class TabFragmentPagerAdapter extends FragmentPagerAdapter implements
ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
OnPageChangeListener mPageChangeListener;
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabFragmentPagerAdapter(SherlockFragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void setOnPageChangeListenr(OnPageChangeListener lisntener) {
mPageChangeListener = lisntener;
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
@Override
public int getCount() {
return mTabs.size();
}
@Override
public Fragment getItem(int position) {
TabInfo info = mTabs.get(position);
return Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
if (mPageChangeListener != null) {
mPageChangeListener.onPageScrolled(position, positionOffset,
positionOffsetPixels);
}
}
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
if (mPageChangeListener != null) {
mPageChangeListener.onPageSelected(position);
}
}
public void onPageScrollStateChanged(int state) {
if (mPageChangeListener != null) {
mPageChangeListener.onPageScrollStateChanged(state);
}
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Object tag = tab.getTag();
for (int i = 0; i < mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
|
package com.intalio.web.server;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
import org.osgi.framework.ServiceReference;
import com.intalio.web.profile.IDiagramProfile;
import com.intalio.web.profile.IDiagramProfileService;
import com.intalio.web.profile.impl.DefaultProfileImpl;
import com.intalio.web.profile.impl.ProfileServiceImpl;
import com.intalio.web.repository.DiagramValidationException;
import com.intalio.web.repository.IUUIDBasedRepository;
import com.intalio.web.repository.IUUIDBasedRepositoryService;
import com.intalio.web.repository.impl.UUIDBasedFileRepository;
/**
* @author Antoine Toulme
* a file based repository that uses the UUID element to save models
* using a repository, which may be passed by a backend in an OSGi environment
* or saved to file system.
*
*/
public class UUIDBasedRepositoryServlet extends HttpServlet {
/**
* Serializable comes with this field.
*/
private static final long serialVersionUID = 1433687917432938596L;
/**
* da logger
*/
private static final Logger _logger = Logger.getLogger(UUIDBasedRepositoryServlet.class);
/**
* The class name of the default repository.
*/
private static final String DEFAULT_REPOSITORY = UUIDBasedFileRepository.class.getName();
/**
* The default factory for creation of repositories.
*
* The factory uses the initialization parameter repositoryClass
* to know which class to instantiate.
* The class is loaded using the current thread context class loader,
* or the UUIDBasedRepositoryServlet class loader if none is set.
*/
private static IUUIDBasedRepositoryService _factory = new IUUIDBasedRepositoryService() {
/**
* @param config
* the servlet config to help create the repository
* @return a new IUUIDBasedRepository object
*/
@SuppressWarnings("rawtypes")
public IUUIDBasedRepository createRepository(ServletConfig config)
throws ServletException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = UUIDBasedRepositoryServlet.class.getClassLoader();
}
String className = config.getInitParameter("repositoryClass");
if (className == null) {
_logger.debug("Defaulting the repository to the default class");
className = DEFAULT_REPOSITORY;
}
try {
Class clazz = cl.loadClass(className);
return (IUUIDBasedRepository) clazz.newInstance();
} catch (Exception e) {
throw new IllegalArgumentException(e.getMessage(), e);
}
}
};
/**
* The factory used in an OSGi context.
*
* The factory looks for a registered IUUIDBasedRepositoryService using
* the current BundleContext.
* If none is found, it will throw a UnavailableException.
* The first one found will otherwise be used to create the repository.
*/
private static IUUIDBasedRepositoryService _osgiFactory = new IUUIDBasedRepositoryService() {
/**
* @param config
* the servlet config to help create the repository
* @return a new IUUIDBasedRepository object
* @throws ServletException
*/
public IUUIDBasedRepository createRepository(ServletConfig config) throws ServletException {
BundleContext bundleContext = ((BundleReference) getClass().
getClassLoader()).getBundle().getBundleContext();
ServiceReference ref = bundleContext.getServiceReference(
IUUIDBasedRepositoryService.class.getName());
if (ref == null) {
_logger.error("No service registered for IUUIDBasedRepositoryService");
throw new UnavailableException(
"No service registered for IUUIDBasedRepositoryService", 0);
}
IUUIDBasedRepositoryService service = (IUUIDBasedRepositoryService)
bundleContext.getService(ref);
return service.createRepository(config);
}
};
/**
* The repository used to save and load models.
*/
private IUUIDBasedRepository _repository;
/**
* Initiates the repository servlet.
*
* The behavior is based on the initialization parameters read from web.xml
*
* repositoryServiceType:
* -null
* The classloader of the class is investigated to see if we are operating
* in a OSGi context. If yes we use osgi.
* -default
* We will use the _factory static field to create the repository.
* -osgi
* We will use the _osgiFactory to create the repository.
*
* Please refer to the documentation of both fields for further information.
*
*/
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
String repoType = config.getInitParameter("repositoryServiceType");
if (repoType == null) {
// look up the current class loader
if (UUIDBasedRepositoryServlet.class.getClassLoader()
instanceof BundleReference) {
repoType = "osgi";
} else {
repoType = "default";
}
}
if ("default".equals(repoType)) {
_repository = _factory.createRepository(config);
} else if ("osgi".equals(repoType)){
_repository = _osgiFactory.createRepository(config);
} else {
throw new IllegalArgumentException("Invalid value for init " +
"parameter repositoryServiceType : " + repoType);
}
_repository.configure(this);
} catch (Exception e) {
if (e instanceof ServletException) {
throw (ServletException) e;
}
throw new ServletException(e);
}
}
/**
* This method populates the response with the contents of the model.
* It expects two parameters to be passed via the request, uuid and profile.
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
if (resp.isCommitted()) {
return;//called twice... need to clean-up the FilterChainImpl that is quite wrong.
}
String uuid = req.getParameter("uuid");
if (uuid == null) {
throw new ServletException("uuid parameter required");
}
IDiagramProfile profile = getProfile(req, req.getParameter("profile"));
ByteArrayInputStream input = new ByteArrayInputStream(
_repository.load(req, uuid, profile.getSerializedModelExtension()));
byte[] buffer = new byte[4096];
int read;
while ((read = input.read(buffer)) != -1) {
resp.getOutputStream().write(buffer, 0, read);
}
}
/**
* This method saves the model contents based on the json sent as the
* body of the request.
*
* The json should look like:
*
* { "data" : ....,
* "svg" : <svg>...</svg>,
* "uuid" : "1234",
* "profile" : "default"
* }
*
* The data is the json representation of the model.
* The svg represents the graphical model as a SVG format.
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
if (resp.isCommitted()) {
return;//called twice... need to clean-up the FilterChainImpl that is quite wrong.
}
BufferedReader reader = req.getReader();
StringWriter reqWriter = new StringWriter();
char[] buffer = new char[4096];
int read;
while ((read = reader.read(buffer)) != -1) {
reqWriter.write(buffer, 0, read);
}
String data = reqWriter.toString();
try {
JSONObject jsonObject = new JSONObject(data);
String json = (String) jsonObject.get("data");
String svg = (String) jsonObject.get("svg");
String uuid = (String) jsonObject.get("uuid");
String profileName = (String) jsonObject.get("profile");
boolean autosave = jsonObject.getBoolean("savetype");
if (_logger.isDebugEnabled()) {
_logger.debug("Calling UUIDBasedRepositoryServlet doPost()...");
_logger.debug("autosave: " + autosave);
}
IDiagramProfile profile = getProfile(req, profileName);
if (_logger.isDebugEnabled()) {
_logger.debug("Begin saving the diagram");
}
_repository.save(req, uuid, json, svg, profile, autosave);
if (_logger.isDebugEnabled()) {
_logger.debug("Finish saving the diagram");
}
} catch (JSONException e1) {
throw new ServletException(e1);
} catch (DiagramValidationException e) {
// set the error JSON to response
resp.getWriter().write(e.getErrorJsonStr());
}
}
/**
* FIXME this needs to go as it duplicates part of the functionality for
* profiles resolution. We should only write this code once.
*/
private IDiagramProfile getProfile(HttpServletRequest req, String profileName) {
IDiagramProfile profile = null;
// get the profile, either through the OSGi DS or by using the default one:
if (getClass().getClassLoader() instanceof BundleReference) {
BundleContext bundleContext = ((BundleReference) getClass().getClassLoader()).getBundle().getBundleContext();
ServiceReference ref = bundleContext.getServiceReference(IDiagramProfileService.class.getName());
if (ref == null) {
throw new IllegalArgumentException(profileName + " is not registered");
}
IDiagramProfileService service = (IDiagramProfileService) bundleContext.getService(ref);
profile = service.findProfile(req, profileName);
} else if ("default".equals(profileName)) {
profile = new DefaultProfileImpl(getServletContext(), false);
} else {
// check w/o BundleReference
IDiagramProfileService service = new ProfileServiceImpl();
service.init(getServletContext());
profile = service.findProfile(req, profileName);
if(profile == null) {
throw new IllegalArgumentException("Cannot determine the profile to use for interpreting models");
}
}
return profile;
}
}
|
package it.unimi.dsi.sux4j.mph;
import it.unimi.dsi.Util;
import it.unimi.dsi.bits.BitVector;
import it.unimi.dsi.bits.LongArrayBitVector;
import it.unimi.dsi.bits.TransformationStrategies;
import it.unimi.dsi.bits.TransformationStrategy;
import it.unimi.dsi.fastutil.io.BinIO;
import it.unimi.dsi.fastutil.io.FastBufferedOutputStream;
import it.unimi.dsi.fastutil.longs.LongIterators;
import it.unimi.dsi.fastutil.objects.AbstractObject2LongFunction;
import it.unimi.dsi.fastutil.objects.AbstractObjectIterator;
import it.unimi.dsi.fastutil.objects.Object2LongFunction;
import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap;
import it.unimi.dsi.fastutil.objects.ObjectOpenHashSet;
import it.unimi.dsi.io.InputBitStream;
import it.unimi.dsi.io.OutputBitStream;
import it.unimi.dsi.lang.MutableString;
import it.unimi.dsi.sux4j.bits.BalancedParentheses;
import it.unimi.dsi.sux4j.bits.JacobsonBalancedParentheses;
import it.unimi.dsi.sux4j.util.EliasFanoLongBigList;
import it.unimi.dsi.util.LongBigList;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.apache.log4j.Logger;
/** A distributor based on a hollow trie.
*
* <h2>Implementation details</h2>
*
* <p>This class implements a distributor on top of a hollow trie. First, a compacted trie is built from the delimiter set.
* Then, for each key we compute the node of the trie in which the bucket of the key is established. This gives us,
* for each node of the trie, a set of paths to which we must associate an action (exit on the left,
* go through, exit on the right). Overall, the number of such paths is equal to the number of keys plus the number of delimiters, so
* the mapping from each pair node/path to the respective action takes linear space. Now, from the compacted trie we just
* retain a hollow trie, as the path-length information is sufficient to rebuild the keys of the above mapping.
* By sizing the bucket size around the logarithm of the average length, we obtain a distributor that occupies linear space.
*/
public class HollowTrieDistributor3<T> extends AbstractObject2LongFunction<T> {
private final static Logger LOGGER = Util.getLogger( HollowTrieDistributor3.class );
private static final long serialVersionUID = 2L;
private static final boolean DEBUG = false;
private static final boolean DDEBUG = false;
private static final boolean ASSERTS = false;
/** An integer representing the exit-on-the-left behaviour. */
private final static int LEFT = 0;
/** An integer representing the exit-on-the-right behaviour. */
private final static int RIGHT = 1;
/** An integer representing the follow-the-try behaviour. */
private final static int FOLLOW = 2;
/** The transformation used to map object to bit vectors. */
private final TransformationStrategy<? super T> transformationStrategy;
/** The bitstream representing the hollow trie. */
private final LongArrayBitVector trie;
/** The list of skips, indexed by the internal nodes (we do not need skips on the leaves). */
private final EliasFanoLongBigList skips;
/** For each external node and each possible path, the related behaviour. */
private final MWHCFunction<BitVector> externalBehaviour;
/** The number of (internal and external) nodes of the trie. */
private final int size;
/** A debug function used to store explicitly {@link #externalBehaviour}. */
private final Object2LongFunction<BitVector> externalTestFunction;
/** A debug set used to store explicitly false follows. */
private final ObjectOpenHashSet<BitVector> falseFollows;
private final BalancedParentheses balParen;
private final MWHCFunction<BitVector> falseFollowsDetector;
/** The average skip. */
protected double meanSkip;
/** An intermediate class containing the compacted trie generated by the delimiters. After its construction,
* {@link #externalKeysFile} contains the pairs node/path that must be mapped
* to {@link #lValues}, respectively, to obtain the desired behaviour. */
private final static class IntermediateTrie<T> {
/** A debug function used to store explicitly the internal behaviour. */
private Object2LongFunction<BitVector> externalTestFunction;
/** A debug set used to store explicitly false follows. */
private ObjectOpenHashSet<BitVector> falseFollows;
/** The root of the trie. */
protected final Node root;
/** The number of overall elements to distribute. */
protected final int numElements;
/** The number of internal nodes of the trie. */
protected final int size;
/** The file containing the external keys (pairs node/path). */
private final File externalKeysFile;
/** The values associated to the keys in {@link #externalKeysFile}. */
private LongBigList externalValues;
/** The file containing the keys (pairs node/path) that are (either true or false) follows. */
private final File falseFollowsKeyFile;
/** The values (true/false) associated to the keys in {@link #falseFollows}. */
private LongBigList falseFollowsValues;
/** A node in the trie. */
public static class Node {
/** Left child. */
private Node left;
/** Right child. */
private Node right;
/** The path compacted in this node (<code>null</code> if there is no compaction at this node). */
private final LongArrayBitVector path;
/** Whether we have already emitted the path at this node during the computation of the behaviour. */
private boolean emitted;
/** The index of this node in the Jacobson representation. */
private int index;
/** Creates a node.
*
* @param left the left child.
* @param right the right child.
* @param path the path compacted at this node.
*/
public Node( final Node left, final Node right, final LongArrayBitVector path ) {
this.left = left;
this.right = right;
this.path = path;
}
/** Returns true if this node is a leaf.
*
* @return true if this node is a leaf.
*/
public boolean isLeaf() {
return right == null && left == null;
}
public String toString() {
return "[" + path + "]";
}
}
private int visit( final Node node, int index ) {
if ( node == null ) return index;
node.index = index++;
index = visit( node.left, index );
return visit( node.right, index ); // This adds the closing parenthesis
}
/** Creates a partial compacted trie using given elements, bucket size and transformation strategy.
*
* @param elements the elements among which the trie must be able to rank.
* @param log2BucketSize the size of a bucket.
* @param transformationStrategy a transformation strategy that must turn the elements in <code>elements</code> into a list of
* distinct, prefix-free, lexicographically increasing (in iteration order) bit vectors.
* @param tempDir a directory for the temporary files created during construction, or <code>null</code> for the default temporary directory.
*/
public IntermediateTrie( final Iterable<? extends T> elements, final int log2BucketSize, final TransformationStrategy<? super T> transformationStrategy, final File tempDir ) throws IOException {
if ( ASSERTS ) {
externalTestFunction = new Object2LongOpenHashMap<BitVector>();
externalTestFunction.defaultReturnValue( -1 );
falseFollows = new ObjectOpenHashSet<BitVector>();
}
final int bucketSizeMask = ( 1 << log2BucketSize ) - 1;
Iterator<? extends T> iterator = elements.iterator();
if ( iterator.hasNext() ) {
LongArrayBitVector prev = LongArrayBitVector.copy( transformationStrategy.toBitVector( iterator.next() ) );
LongArrayBitVector prevDelimiter = LongArrayBitVector.getInstance();
Node node, root = null;
BitVector curr;
int cmp, pos, prefix, count = 1;
long maxLength = prev.length();
while( iterator.hasNext() ) {
// Check order
curr = transformationStrategy.toBitVector( iterator.next() ).fast();
cmp = prev.compareTo( curr );
if ( cmp == 0 ) throw new IllegalArgumentException( "The input bit vectors are not distinct" );
if ( cmp > 0 ) throw new IllegalArgumentException( "The input bit vectors are not lexicographically sorted" );
if ( curr.longestCommonPrefixLength( prev ) == prev.length() ) throw new IllegalArgumentException( "The input bit vectors are not prefix-free" );
if ( ( count & bucketSizeMask ) == 0 ) {
// Found delimiter. Insert into trie.
if ( root == null ) {
root = new Node( null, null, prev.copy() );
prevDelimiter.replace( prev );
}
else {
prefix = (int)prev.longestCommonPrefixLength( prevDelimiter );
pos = 0;
node = root;
Node n = null;
while( node != null ) {
final long pathLength = node.path.length();
if ( prefix < pathLength ) {
n = new Node( node.left, node.right, node.path.copy( prefix + 1, pathLength ) );
node.path.length( prefix );
node.path.trim();
node.left = n;
node.right = new Node( null, null, prev.copy( pos + prefix + 1, prev.length() ) );
break;
}
prefix -= pathLength + 1;
pos += pathLength + 1;
node = node.right;
if ( ASSERTS ) assert node == null || prefix >= 0 : prefix + " <= " + 0;
}
if ( ASSERTS ) assert node != null;
prevDelimiter.replace( prev );
}
}
prev.replace( curr );
maxLength = Math.max( maxLength, prev.length() );
count++;
}
this.numElements = count;
this.root = root;
externalKeysFile = File.createTempFile( HollowTrieDistributor3.class.getName(), "ext", tempDir );
externalKeysFile.deleteOnExit();
falseFollowsKeyFile = File.createTempFile( HollowTrieDistributor3.class.getName(), "false", tempDir );
falseFollowsKeyFile.deleteOnExit();
if ( root != null ) {
LOGGER.info( "Numbering nodes..." );
size = visit( root, 0 ); // Number nodes; we start from one so to add the fake root
LOGGER.info( "Computing function keys..." );
final OutputBitStream externalKeys = new OutputBitStream( externalKeysFile );
final OutputBitStream falseFollowsKeys = new OutputBitStream( falseFollowsKeyFile );
externalValues = LongArrayBitVector.getInstance().asLongBigList( 1 );
falseFollowsValues = LongArrayBitVector.getInstance().asLongBigList( 1 );
iterator = elements.iterator();
// The stack of nodes visited the last time
final Node stack[] = new Node[ (int)maxLength ];
// The length of the path compacted in the trie up to the corresponding node, excluded
final int[] len = new int[ (int)maxLength ];
stack[ 0 ] = root;
int depth = 0, behaviour, pathLength;
boolean first = true;
Node lastNode = null;
BitVector currFromPos, path, lastPath = null;
LongArrayBitVector nodePath;
OutputBitStream obs;
while( iterator.hasNext() ) {
curr = transformationStrategy.toBitVector( iterator.next() ).fast();
if ( DEBUG ) System.err.println( curr );
if ( ! first ) {
// Adjust stack using lcp between present string and previous one
prefix = (int)prev.longestCommonPrefixLength( curr );
while( depth > 0 && len[ depth ] > prefix ) depth
}
else first = false;
node = stack[ depth ];
pos = len[ depth ];
for(;;) {
nodePath = node.path;
currFromPos = curr.subVector( pos );
prefix = (int)currFromPos.longestCommonPrefixLength( nodePath );
int falseFollow = -1;
if ( prefix < nodePath.length() || ! node.emitted ) {
// Either we must code an exit behaviour, or the follow behaviour of this node has not been coded yet.
if ( prefix == nodePath.length() ) {
behaviour = LEFT;
path = nodePath;
node.emitted = true;
if ( ! node.isLeaf() ) {
falseFollow = 0;
behaviour = FOLLOW;
}
if ( ASSERTS ) assert ! node.isLeaf() || currFromPos.length() == nodePath.length();
}
else {
// Exit. LEFT or RIGHT, depending on the bit at the end of the common prefix. The
// path is the remaining path at the current position for external nodes, or a prefix of length
// at most pathLength for internal nodes.
behaviour = nodePath.getBoolean( prefix ) ? LEFT : RIGHT;
path = node.isLeaf() ? currFromPos.copy() : currFromPos.subVector( 0, Math.min( currFromPos.length(), nodePath.length() ) ).copy();
}
if ( behaviour != FOLLOW && ( lastNode != node || ! path.equals( lastPath ) ) ) {
externalValues.add( behaviour );
obs = externalKeys;
pathLength = (int)path.length();
obs.writeLong( node.index, Long.SIZE );
obs.writeDelta( pathLength );
for( int i = 0; i < pathLength; i += Long.SIZE ) obs.writeLong( path.getLong( i, Math.min( i + Long.SIZE, pathLength) ), Math.min( Long.SIZE, pathLength - i ) );
lastNode = node;
lastPath = path;
if ( ! node.isLeaf() ) falseFollow = 1;
if ( ASSERTS ) {
long key[] = new long[ ( pathLength + Long.SIZE - 1 ) / Long.SIZE + 1 ];
key[ 0 ] = node.index;
for( int i = 0; i < pathLength; i += Long.SIZE ) key[ i / Long.SIZE + 1 ] = path.getLong( i, Math.min( i + Long.SIZE, pathLength ) );
externalTestFunction.put( LongArrayBitVector.wrap( key, pathLength + Long.SIZE ), behaviour );
if ( ! node.isLeaf() )
falseFollows.add( LongArrayBitVector.wrap( key, pathLength + Long.SIZE ) );
}
if ( DEBUG ) {
System.err.println( "Computed " + ( node.isLeaf() ? "leaf " : "" ) + "mapping <" + node.index + ", [" + path.length() + ", " + Integer.toHexString( path.hashCode() ) + "] " + path + "> -> " + behaviour );
System.err.println( externalTestFunction );
}
}
if ( falseFollow != -1 ) {
falseFollowsValues.add( falseFollow );
pathLength = (int)path.length();
falseFollowsKeys.writeLong( node.index, Long.SIZE );
falseFollowsKeys.writeDelta( pathLength );
for( int i = 0; i < pathLength; i += Long.SIZE ) falseFollowsKeys.writeLong( path.getLong( i, Math.min( i + Long.SIZE, pathLength) ), Math.min( Long.SIZE, pathLength - i ) );
}
if ( behaviour != FOLLOW ) break;
}
pos += nodePath.length() + 1;
if ( pos > curr.length() ) break;
node = curr.getBoolean( pos - 1 ) ? node.right : node.left;
// Update stack
len[ ++depth ] = pos;
stack[ depth ] = node;
}
prev.replace( curr );
}
externalKeys.close();
falseFollowsKeys.close();
}
else size = 0;
}
else {
// No elements.
this.root = null;
this.size = this.numElements = 0;
falseFollowsKeyFile = externalKeysFile = null;
}
}
private void recToString( final Node n, final MutableString printPrefix, final MutableString result, final MutableString path, final int level ) {
if ( n == null ) return;
result.append( printPrefix ).append( '(' ).append( level ).append( ')' ).append( " [" ).append( n.index ).append( ']' );
if ( n.path != null ) {
path.append( n.path );
result.append( " path: " ).append( "[" ).append( path.length() ).append( ", " ).append( Integer.toHexString( path.hashCode() ) ).append( "] " ).append( n.path );
}
result.append( '\n' );
path.append( '0' );
recToString( n.left, printPrefix.append( '\t' ).append( "0 => " ), result, path, level + 1 );
path.charAt( path.length() - 1, '1' );
recToString( n.right, printPrefix.replace( printPrefix.length() - 5, printPrefix.length(), "1 => "), result, path, level + 1 );
path.delete( path.length() - 1, path.length() );
printPrefix.delete( printPrefix.length() - 6, printPrefix.length() );
path.delete( (int)( path.length() - n.path.length() ), path.length() );
}
public String toString() {
MutableString s = new MutableString();
recToString( root, new MutableString(), s, new MutableString(), 0 );
return s.toString();
}
}
private long sumSkips;
private long visit( final IntermediateTrie.Node node, LongArrayBitVector bitVector, long pos, DataOutputStream skips ) throws IOException {
if ( node.isLeaf() ) return pos;
bitVector.set( pos++ ); // This adds the open parentheses
final int skip = (int)node.path.length();
skips.writeInt( skip );
sumSkips += skip;
pos = visit( node.left, bitVector, pos, skips );
return visit( node.right, bitVector, pos + 1, skips ); // This adds the closing parenthesis
}
/** Creates a partial compacted trie using given elements, bucket size and transformation strategy.
*
* @param elements the elements among which the trie must be able to rank.
* @param log2BucketSize the logarithm of the size of a bucket.
* @param transformationStrategy a transformation strategy that must turn the elements in <code>elements</code> into a list of
* distinct, lexicographically increasing (in iteration order) bit vectors.
*/
public HollowTrieDistributor3( final Iterable<? extends T> elements, final int log2BucketSize, final TransformationStrategy<? super T> transformationStrategy ) throws IOException {
this( elements, log2BucketSize, transformationStrategy, null );
}
/** Creates a partial compacted trie using given elements, bucket size, transformation strategy, and temporary directory.
*
* @param elements the elements among which the trie must be able to rank.
* @param log2BucketSize the logarithm of the size of a bucket.
* @param transformationStrategy a transformation strategy that must turn the elements in <code>elements</code> into a list of
* distinct, lexicographically increasing (in iteration order) bit vectors.
* @param tempDir the directory where temporary files will be created, or <code>for the default directory</code>.
*/
public HollowTrieDistributor3( final Iterable<? extends T> elements, final int log2BucketSize, final TransformationStrategy<? super T> transformationStrategy, final File tempDir ) throws IOException {
this.transformationStrategy = transformationStrategy;
final int bucketSize = 1 << log2BucketSize;
if ( DEBUG ) System.err.println( "Bucket size: " + bucketSize );
final IntermediateTrie<T> intermediateTrie = new IntermediateTrie<T>( elements, log2BucketSize, transformationStrategy, tempDir );
size = intermediateTrie.size;
externalTestFunction = intermediateTrie.externalTestFunction;
falseFollows = intermediateTrie.falseFollows;
trie = LongArrayBitVector.ofLength( size + 1 );
trie.set( 0 );
File skipFile = File.createTempFile( HollowTrieDistributor3.class.getSimpleName(), "skips", tempDir );
skipFile.deleteOnExit();
final DataOutputStream skips = new DataOutputStream( new FastBufferedOutputStream( new FileOutputStream( skipFile ) ) );
// Turn the compacted trie into a hollow trie.
if ( intermediateTrie.root != null ) {
if ( DDEBUG ) System.err.println( intermediateTrie );
visit( intermediateTrie.root, trie, 1, skips );
}
skips.close();
balParen = new JacobsonBalancedParentheses( trie, false, true, false );
meanSkip = (double)sumSkips / skips.size();
this.skips = new EliasFanoLongBigList( LongIterators.wrap( BinIO.asIntIterator( skipFile ) ), 0, true );
skipFile.delete();
LOGGER.info( "Bits per skip: " + bitsPerSkip() );
/** A class iterating over the temporary files produced by the intermediate trie. */
class IterableStream implements Iterable<BitVector> {
private InputBitStream ibs;
private int n;
private Object2LongFunction<BitVector> test;
private LongBigList values;
public IterableStream( final InputBitStream ibs, final Object2LongFunction<BitVector> testFunction, final LongBigList testValues ) {
this.ibs = ibs;
this.n = testValues.size();
this.test = testFunction;
this.values = testValues;
}
public Iterator<BitVector> iterator() {
try {
ibs.position( 0 );
return new AbstractObjectIterator<BitVector>() {
private int pos = 0;
public boolean hasNext() {
return pos < n;
}
public BitVector next() {
if ( ! hasNext() ) throw new NoSuchElementException();
try {
final long index = ibs.readLong( 64 );
final int pathLength = ibs.readDelta();
final long key[] = new long[ ( ( pathLength + Long.SIZE - 1 ) / Long.SIZE + 1 ) ];
key[ 0 ] = index;
for( int i = 0; i < ( pathLength + Long.SIZE - 1 ) / Long.SIZE; i++ ) key[ i + 1 ] = ibs.readLong( Math.min( Long.SIZE, pathLength - i * Long.SIZE ) );
if ( DEBUG ) {
System.err.println( "Adding mapping <" + index + ", " + LongArrayBitVector.wrap( key, pathLength + Long.SIZE ).subVector( Long.SIZE ) + "> -> " + values.getLong( pos ));
System.err.println( LongArrayBitVector.wrap( key, pathLength + Long.SIZE ) );
}
if ( ASSERTS && test != null ) assert test.getLong( LongArrayBitVector.wrap( key, pathLength + Long.SIZE ) ) == values.getLong( pos ) : test.getLong( LongArrayBitVector.wrap( key, pathLength + Long.SIZE ) ) + " != " + values.getLong( pos ) ;
pos++;
return LongArrayBitVector.wrap( key, pathLength + Long.SIZE );
}
catch ( IOException e ) {
throw new RuntimeException( e );
}
}
};
}
catch ( IOException e ) {
throw new RuntimeException( e );
}
}
};
externalBehaviour = new MWHCFunction<BitVector>( new IterableStream( new InputBitStream( intermediateTrie.externalKeysFile ), externalTestFunction, intermediateTrie.externalValues ), TransformationStrategies.identity(), intermediateTrie.externalValues, 1 );
falseFollowsDetector = new MWHCFunction<BitVector>( new IterableStream( new InputBitStream( intermediateTrie.falseFollowsKeyFile ), null, intermediateTrie.falseFollowsValues ), TransformationStrategies.identity(), intermediateTrie.falseFollowsValues, 1 );
LOGGER.debug( "False positives: " + ( falseFollowsDetector.size() - size / 2 ) );
intermediateTrie.externalKeysFile.delete();
if ( ASSERTS ) {
if ( size > 0 ) {
Iterator<BitVector>iterator = TransformationStrategies.wrap( elements.iterator(), transformationStrategy );
int c = 0;
while( iterator.hasNext() ) {
BitVector curr = iterator.next();
if ( DEBUG ) System.err.println( "Checking element number " + c + ( ( c + 1 ) % bucketSize == 0 ? " (bucket)" : "" ));
long t = getLong( curr );
assert c / bucketSize == t : c / bucketSize + " != " + t;
c++;
}
}
}
}
@SuppressWarnings("unchecked")
public long getLong( final Object o ) {
if ( size == 0 ) return 0;
final BitVector bitVector = transformationStrategy.toBitVector( (T)o ).fast();
LongArrayBitVector key = LongArrayBitVector.getInstance();
BitVector fragment = null;
long p = 1, length = bitVector.length(), index = 0, r = 0;
int s = 0, skip = 0, behaviour;
long lastLeftTurn = 0;
long lastLeftTurnIndex = 0;
boolean isInternal;
if ( DEBUG ) System.err.println( "Distributing " + bitVector + "\ntrie:" + trie );
for(;;) {
isInternal = trie.getBoolean( p );
if ( isInternal ) skip = (int)skips.getLong( r );
if ( DEBUG ) System.err.println( "Interrogating" + ( isInternal ? "" : " leaf" ) + " <" + ( p - 1 ) + ", [" + Math.min( length, s + skip ) + ", " + Integer.toHexString( bitVector.subVector( s, Math.min( length, s + skip ) ).hashCode() ) + "] " + bitVector.subVector( s, Math.min( length, s + skip ) ) + "> (skip: " + skip + ")" );
//if ( isInternal ) System.err.println( signature == ( Hashes.jenkins( bitVector.subVector( s, Math.min( length, s + skip ) ) ) & ( 1 << SKIPBITS )- 1 ) );
if ( isInternal && falseFollowsDetector.getLong( key.length( 0 ).append( p - 1, Long.SIZE ).append( fragment = bitVector.subVector( s, Math.min( length, s + skip ) ) ) ) == 0 ) behaviour = FOLLOW;
else behaviour = (int)externalBehaviour.getLong( key.length( 0 ).append( p - 1, Long.SIZE ).append( isInternal ? fragment : bitVector.subVector( s, length ) ) );
if ( ASSERTS ) {
if ( behaviour != FOLLOW ) {
final long result;
result = externalTestFunction.getLong( key.length( 0 ).append( p - 1, Long.SIZE ).append( bitVector.subVector( s, isInternal ? Math.min( length, s + skip ) : length ) ) );
//assert result != -1; // Only if you don't test with non-keys
if ( result != -1 ) assert result == behaviour : result + " != " + behaviour;
}
else assert ! falseFollows.contains( key.length( 0 ).append( p - 1, Long.SIZE ).append( bitVector.subVector( s, Math.min( length, s + skip ) ) ) );
}
//if ( ASSERTS ) assert behaviour == LEFT || behaviour == RIGHT || behaviour == FOLLOW : behaviour; // Only if you don't test with non-keys
if ( DEBUG ) System.err.println( "Exit behaviour: " + behaviour );
if ( behaviour != FOLLOW || ! isInternal || ( s += skip ) >= length ) break;
if ( DEBUG ) System.err.print( "Turning " + ( bitVector.getBoolean( s ) ? "right" : "left" ) + " at bit " + s + "... " );
if ( bitVector.getBoolean( s ) ) {
final long q = balParen.findClose( p ) + 1;
index += ( q - p ) / 2;
r += ( q - p ) / 2;
//System.err.println( "Increasing index by " + ( q - p + 1 ) / 2 + " to " + index + "..." );
p = q;
}
else {
lastLeftTurn = p;
lastLeftTurnIndex = index;
p++;
r++;
}
if ( ASSERTS ) assert p < trie.length();
s++;
}
if ( behaviour == LEFT ) {
if ( DEBUG ) System.err.println( "Returning (on the left) " + index );
return index;
}
else {
if ( isInternal ) {
final long q = balParen.findClose( lastLeftTurn );
//System.err.println( p + ", " + q + " ," + lastLeftTurn + ", " +lastLeftTurnIndex);;
index = ( q - lastLeftTurn + 1 ) / 2 + lastLeftTurnIndex;
if ( DEBUG ) System.err.println( "Returning (on the right, internal) " + index );
}
else {
index++;
if ( DEBUG ) System.err.println( "Returning (on the right, external) " + index );
}
return index;
}
}
public long numBits() {
return trie.length() + skips.numBits() + falseFollowsDetector.numBits() + balParen.numBits() + externalBehaviour.numBits() + transformationStrategy.numBits();
}
public boolean containsKey( Object o ) {
return true;
}
public int size() {
return size;
}
public double bitsPerSkip() {
return (double)skips.numBits() / skips.length();
}
}
|
package com.j256.ormlite.android;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import com.j256.ormlite.dao.ObjectCache;
import com.j256.ormlite.field.SqlType;
import com.j256.ormlite.logger.Logger;
import com.j256.ormlite.logger.LoggerFactory;
import com.j256.ormlite.misc.SqlExceptionUtil;
import com.j256.ormlite.stmt.StatementBuilder.StatementType;
import com.j256.ormlite.support.CompiledStatement;
import com.j256.ormlite.support.DatabaseResults;
/**
* Android implementation of the compiled statement.
*
* @author kevingalligan, graywatson
*/
public class AndroidCompiledStatement implements CompiledStatement {
private static Logger logger = LoggerFactory.getLogger(AndroidCompiledStatement.class);
private final String sql;
private final SQLiteDatabase db;
private final StatementType type;
private static final String[] NO_STRING_ARGS = new String[0];
private Cursor cursor;
private List<Object> args;
private Integer max;
public AndroidCompiledStatement(String sql, SQLiteDatabase db, StatementType type) {
this.sql = sql;
this.db = db;
this.type = type;
}
public int getColumnCount() throws SQLException {
return getCursor().getColumnCount();
}
public String getColumnName(int column) throws SQLException {
return getCursor().getColumnName(column);
}
public DatabaseResults runQuery(ObjectCache objectCache) throws SQLException {
// this could come from DELETE or UPDATE, just not a SELECT
if (!type.isOkForQuery()) {
throw new IllegalArgumentException("Cannot call query on a " + type + " statement");
}
return new AndroidDatabaseResults(getCursor(), objectCache);
}
public int runUpdate() throws SQLException {
if (!type.isOkForUpdate()) {
throw new IllegalArgumentException("Cannot call update on a " + type + " statement");
}
String finalSql;
if (max == null) {
finalSql = sql;
} else {
finalSql = sql + " " + max;
}
return execSql("runUpdate", finalSql);
}
public int runExecute() throws SQLException {
if (!type.isOkForExecute()) {
throw new IllegalArgumentException("Cannot call execute on a " + type + " statement");
}
return execSql("runExecute", sql);
}
public void close() throws SQLException {
if (cursor != null) {
try {
cursor.close();
} catch (android.database.SQLException e) {
throw SqlExceptionUtil.create("Problems closing Android cursor", e);
}
}
}
public void setObject(int parameterIndex, Object obj, SqlType sqlType) throws SQLException {
isInPrep();
if (args == null) {
args = new ArrayList<Object>();
}
if (obj == null) {
args.add(parameterIndex, null);
} else {
args.add(parameterIndex, obj.toString());
}
}
public void setMaxRows(int max) throws SQLException {
isInPrep();
this.max = max;
}
public void setQueryTimeout(long millis) {
// as far as I could tell this is not supported by Android API
}
/***
* This is mostly an internal class but is exposed for those people who need access to the Cursor itself.
*
* <p>
* NOTE: This is not thread safe. Not sure if we need it, but keep that in mind.
* </p>
*/
public Cursor getCursor() throws SQLException {
if (cursor == null) {
String finalSql = null;
try {
if (max == null) {
finalSql = sql;
} else {
finalSql = sql + " " + max;
}
cursor = db.rawQuery(finalSql, getStringArray());
cursor.moveToFirst();
logger.trace("{}: started rawQuery cursor for: {}", this, finalSql);
} catch (android.database.SQLException e) {
throw SqlExceptionUtil.create("Problems executing Android query: " + finalSql, e);
}
}
return cursor;
}
@Override
public String toString() {
return getClass().getSimpleName() + "@" + Integer.toHexString(super.hashCode());
}
private void isInPrep() throws SQLException {
if (cursor != null) {
throw new SQLException("Query already run. Cannot add argument values.");
}
}
private int execSql(String label, String finalSql) throws SQLException {
try {
db.execSQL(finalSql, getArgArray());
} catch (android.database.SQLException e) {
throw SqlExceptionUtil.create("Problems executing " + label + " Android statement: " + finalSql, e);
}
int result;
SQLiteStatement stmt = null;
try {
// ask sqlite how many rows were just changed
stmt = db.compileStatement("SELECT CHANGES()");
result = (int) stmt.simpleQueryForLong();
} catch (android.database.SQLException e) {
// ignore the exception and just return 1 if it failed
result = 1;
} finally {
if (stmt != null) {
stmt.close();
}
}
logger.trace("compiled statement {} changed {} rows: {}", label, result, finalSql);
return result;
}
private Object[] getArgArray() {
if (args == null) {
// this will work for Object[] as well as String[]
return NO_STRING_ARGS;
} else {
return args.toArray(new Object[args.size()]);
}
}
private String[] getStringArray() {
if (args == null) {
return NO_STRING_ARGS;
} else {
// we assume we have Strings in args
return args.toArray(new String[args.size()]);
}
}
}
|
// Depot library - a Java relational persistence library
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.samskivert.depot.tools;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.util.ClasspathUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import com.samskivert.depot.PersistentRecord;
import com.samskivert.depot.annotation.Id;
import com.samskivert.depot.annotation.Transient;
import com.samskivert.depot.impl.DepotUtil;
import com.samskivert.util.ClassUtil;
import com.samskivert.util.GenUtil;
import com.samskivert.util.StringUtil;
import com.samskivert.velocity.VelocityUtil;
/**
* An ant task that updates the column constants for a persistent record.
*/
public class GenRecordTask extends Task
{
/**
* Adds a nested fileset element which enumerates record source files.
*/
public void addFileset (FileSet set)
{
_filesets.add(set);
}
/**
* Configures that classpath that we'll use to load record classes.
*/
public void setClasspathref (Reference pathref)
{
_cloader = ClasspathUtils.getClassLoaderForPath(getProject(), pathref);
}
@Override
public void execute () throws BuildException
{
if (_cloader == null) {
String errmsg = "This task requires a 'classpathref' attribute " +
"to be set to the project's classpath.";
throw new BuildException(errmsg);
}
try {
_velocity = VelocityUtil.createEngine();
} catch (Exception e) {
throw new BuildException("Failure initializing Velocity", e);
}
// resolve the PersistentRecord class using our classloader
try {
_prclass = _cloader.loadClass(PersistentRecord.class.getName());
} catch (Exception e) {
throw new BuildException("Can't resolve InvocationListener", e);
}
for (FileSet fs : _filesets) {
DirectoryScanner ds = fs.getDirectoryScanner(getProject());
File fromDir = fs.getDir(getProject());
String[] srcFiles = ds.getIncludedFiles();
for (int f = 0; f < srcFiles.length; f++) {
processRecord(new File(fromDir, srcFiles[f]));
}
}
}
/**
* Processes a distributed object source file.
*/
protected void processRecord (File source)
{
// System.err.println("Processing " + source + "...");
// load up the file and determine it's package and classname
String name = null;
try {
name = readClassName(source);
} catch (Exception e) {
System.err.println("Failed to parse " + source + ": " + e.getMessage());
}
try {
processRecord(source, _cloader.loadClass(name));
} catch (ClassNotFoundException cnfe) {
System.err.println("Failed to load " + name + ".\n" +
"Missing class: " + cnfe.getMessage());
System.err.println("Be sure to set the 'classpathref' attribute to a classpath\n" +
"that contains your projects invocation service classes.");
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
/** Processes a resolved persistent record class instance. */
protected void processRecord (File source, Class<?> rclass)
{
// make sure we extend persistent record
if (!_prclass.isAssignableFrom(rclass)) {
// System.err.println("Skipping " + rclass.getName() + "...");
return;
}
boolean isAbstract = Modifier.isAbstract(rclass.getModifiers());
// determine our primary key fields for getKey() generation (if we're not an abstract)
List<Field> kflist = Lists.newArrayList();
if (!isAbstract) {
// determine which fields make up our primary key; we'd just use Class.getFields() but
// that returns things in a random order whereas ClassUtil returns fields in
// declaration order starting from the top-most class and going down the line
for (Field field : ClassUtil.getFields(rclass)) {
if (hasAnnotation(field, Id.class)) {
kflist.add(field);
continue;
}
}
}
// determine which fields we need to generate constants for
List<Field> flist = Lists.newArrayList();
for (Field field : rclass.getFields()) {
if (isPersistentField(field)) {
flist.add(field);
}
}
Set<Field> declared = Sets.newHashSet();
for (Field field : rclass.getDeclaredFields()) {
if (isPersistentField(field)) {
declared.add(field);
}
}
// slurp our source file into newline separated strings
String[] lines = null;
try {
BufferedReader bin = new BufferedReader(new FileReader(source));
List<String> llist = Lists.newArrayList();
String line = null;
while ((line = bin.readLine()) != null) {
llist.add(line);
}
lines = llist.toArray(new String[llist.size()]);
bin.close();
} catch (IOException ioe) {
System.err.println("Error reading '" + source + "': " + ioe);
return;
}
// now determine where to insert our static field declarations
int bstart = -1, bend = -1;
int nstart = -1, nend = -1;
int mstart = -1, mend = -1;
for (int ii = 0; ii < lines.length; ii++) {
String line = lines[ii].trim();
// look for the start of the class body
if (NAME_PATTERN.matcher(line).find()) {
if (line.endsWith("{")) {
bstart = ii+1;
} else {
// search down a few lines for the open brace
for (int oo = 1; oo < 10; oo++) {
if (get(lines, ii+oo).trim().endsWith("{")) {
bstart = ii+oo+1;
break;
}
}
}
// track the last } on a line by itself and we'll call that the end of the class body
} else if (line.equals("}")) {
bend = ii;
// look for our field and method markers
} else if (line.equals(FIELDS_START)) {
nstart = ii;
} else if (line.equals(FIELDS_END)) {
nend = ii+1;
} else if (line.equals(METHODS_START)) {
mstart = ii;
} else if (line.equals(METHODS_END)) {
mend = ii+1;
}
}
// sanity check the markers
if (check(source, "fields start", nstart, "fields end", nend) ||
check(source, "fields end", nend, "fields start", nstart) ||
check(source, "methods start", mstart, "methods end", mend) ||
check(source, "methods end", mend, "methods start", mstart)) {
return;
}
// we have no previous markers then stuff the fields at the top of the class body and the
// methods at the bottom
if (nstart == -1) {
nstart = bstart;
nend = bstart;
}
if (mstart == -1) {
mstart = bend;
mend = bend;
}
// get the unqualified class name
String rname = DepotUtil.justClassName(rclass);
// generate our fields section
StringBuilder fsection = new StringBuilder();
// add our prototype declaration
VelocityContext ctx = new VelocityContext();
ctx.put("record", rname);
fsection.append(mergeTemplate(PROTO_TMPL, ctx));
// add our ColumnExp constants
for (int ii = 0; ii < flist.size(); ii++) {
Field f = flist.get(ii);
String fname = f.getName();
// create our velocity context
VelocityContext fctx = (VelocityContext)ctx.clone();
fctx.put("field", fname);
fctx.put("capfield", StringUtil.unStudlyName(fname).toUpperCase());
// now generate our bits
fsection.append(mergeTemplate(COL_TMPL, fctx));
}
// generate our methods section
StringBuilder msection = new StringBuilder();
// add a getKey() method, if applicable
if (kflist.size() > 0) {
StringBuilder argList = new StringBuilder();
StringBuilder argNameList = new StringBuilder();
StringBuilder fieldNameList = new StringBuilder();
for (Field keyField : kflist) {
if (argList.length() > 0) {
argList.append(", ");
argNameList.append(", ");
fieldNameList.append(", ");
}
String name = keyField.getName();
argList.append(GenUtil.simpleName(keyField)).append(" ").append(name);
argNameList.append(name);
fieldNameList.append(StringUtil.unStudlyName(name));
}
ctx.put("argList", argList.toString());
ctx.put("argNameList", argNameList.toString());
ctx.put("fieldNameList", fieldNameList.toString());
// generate our bits and append them as appropriate to the string buffers
msection.append(mergeTemplate(KEY_TMPL, ctx));
}
// now bolt everything back together into a class declaration
try {
BufferedWriter bout = new BufferedWriter(new FileWriter(source));
for (int ii = 0; ii < nstart; ii++) {
writeln(bout, lines[ii]);
}
if (fsection.length() > 0) {
String prev = get(lines, nstart-1);
if (!StringUtil.isBlank(prev) && !prev.equals("{")) {
bout.newLine();
}
writeln(bout, " " + FIELDS_START);
bout.write(fsection.toString());
writeln(bout, " " + FIELDS_END);
if (!StringUtil.isBlank(get(lines, nend))) {
bout.newLine();
}
}
for (int ii = nend; ii < mstart; ii++) {
writeln(bout, lines[ii]);
}
if (msection.length() > 0) {
if (!StringUtil.isBlank(get(lines, mstart-1))) {
bout.newLine();
}
writeln(bout, " " + METHODS_START);
bout.write(msection.toString());
writeln(bout, " " + METHODS_END);
String next = get(lines, mend);
if (!StringUtil.isBlank(next) && !next.equals("}")) {
bout.newLine();
}
}
for (int ii = mend; ii < lines.length; ii++) {
writeln(bout, lines[ii]);
}
bout.close();
} catch (IOException ioe) {
System.err.println("Error writing to '" + source + "': " + ioe);
}
}
/**
* Returns true if the supplied field is part of a persistent record (is a public, non-static,
* non-transient field).
*/
protected boolean isPersistentField (Field field)
{
int mods = field.getModifiers();
return Modifier.isPublic(mods) && !Modifier.isStatic(mods) &&
!Modifier.isTransient(mods) && !hasAnnotation(field, Transient.class);
}
/**
* Safely gets the <code>index</code>th line, returning the empty string if we exceed the
* length of the array.
*/
protected String get (String[] lines, int index)
{
return (index < lines.length) ? lines[index] : "";
}
/** Helper function for sanity checking marker existence. */
protected boolean check (File source, String mname, int mline, String fname, int fline)
{
if (mline == -1 && fline != -1) {
System.err.println("Found " + fname + " marker (at line " + (fline+1) + ") but no " +
mname + " marker in '" + source + "'.");
return true;
}
return false;
}
/** Helper function for writing a string and a newline to a writer. */
protected void writeln (BufferedWriter bout, String line)
throws IOException
{
bout.write(line);
bout.newLine();
}
/** Helper function for generating our boilerplate code. */
protected String mergeTemplate (String tmpl, VelocityContext ctx)
{
StringWriter writer = new StringWriter();
try {
_velocity.mergeTemplate(tmpl, "UTF-8", ctx, writer);
} catch (Exception e) {
System.err.println("Failed processing template [tmpl=" + tmpl + "]");
e.printStackTrace(System.err);
}
return writer.toString();
}
protected static boolean hasAnnotation (Field field, Class<?> annotation)
{
// iterate becase getAnnotation() fails if we're dealing with multiple classloaders
for (Annotation a : field.getAnnotations()) {
if (annotation.getName().equals(a.annotationType().getName())) {
return true;
}
}
return false;
}
/**
* Reads in the supplied source file and locates the package and class or interface name and
* returns a fully qualified class name.
*/
protected static String readClassName (File source)
throws IOException
{
// load up the file and determine it's package and classname
String pkgname = null, name = null;
BufferedReader bin = new BufferedReader(new FileReader(source));
String line;
while ((line = bin.readLine()) != null) {
Matcher pm = PACKAGE_PATTERN.matcher(line);
if (pm.find()) {
pkgname = pm.group(1);
}
Matcher nm = NAME_PATTERN.matcher(line);
if (nm.find()) {
name = nm.group(2);
break;
}
}
bin.close();
// make sure we found something
if (name == null) {
throw new IOException("Unable to locate class or interface name in " + source + ".");
}
// prepend the package name to get a name we can Class.forName()
if (pkgname != null) {
name = pkgname + "." + name;
}
return name;
}
/** A list of filesets that contain tile images. */
protected List<FileSet> _filesets = Lists.newArrayList();
/** Used to do our own classpath business. */
protected ClassLoader _cloader;
/** Used to generate source files from templates. */
protected VelocityEngine _velocity;
/** {@link PersistentRecord} resolved with the proper classloader so that we can compare it to
* loaded derived classes. */
protected Class<?> _prclass;
/** Specifies the path to the name code template. */
protected static final String PROTO_TMPL = "com/samskivert/depot/tools/record_proto.tmpl";
/** Specifies the path to the column code template. */
protected static final String COL_TMPL = "com/samskivert/depot/tools/record_column.tmpl";
/** Specifies the path to the key code template. */
protected static final String KEY_TMPL = "com/samskivert/depot/tools/record_key.tmpl";
// markers
protected static final String MARKER = "// AUTO-GENERATED: ";
protected static final String FIELDS_START = MARKER + "FIELDS START";
protected static final String FIELDS_END = MARKER + "FIELDS END";
protected static final String METHODS_START = MARKER + "METHODS START";
protected static final String METHODS_END = MARKER + "METHODS END";
/** A regular expression for matching the package declaration. */
protected static final Pattern PACKAGE_PATTERN = Pattern.compile("^\\s*package\\s+(\\S+)\\W");
/** A regular expression for matching the class or interface declaration. */
protected static final Pattern NAME_PATTERN = Pattern.compile(
"^\\s*public\\s+(?:abstract\\s+)?(interface|class)\\s+(\\w+)(\\W|$)");
}
|
package com.itmill.toolkit.demo.colorpicker;
import com.itmill.toolkit.data.Property.ValueChangeEvent;
import com.itmill.toolkit.data.Property.ValueChangeListener;
import com.itmill.toolkit.ui.*;
import com.itmill.toolkit.ui.Button.ClickEvent;
/**
* Demonstration application that shows how to use a simple custom client-side
* GWT component, the ColorPicker.
*/
public class ColorPickerApplication extends com.itmill.toolkit.Application {
Window main = new Window("Color Picker Demo");
/* The custom component. */
ColorPicker colorselector = new ColorPicker();
/* Another component. */
Label colorname;
public void init() {
setMainWindow(main);
// Listen for value change events in the custom component,
// triggered when user clicks a button to select another color.
colorselector.addListener(new ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
// Provide some server-side feedback
colorname.setValue("Selected color: "
+ colorselector.getColor());
}
});
main.addComponent(colorselector);
// Add another component to give feedback from server-side code
colorname = new Label("Selected color: " + colorselector.getColor());
main.addComponent(colorname);
// Server-side manipulation of the component state
Button button = new Button("Set to white");
button.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
colorselector.setColor("white");
}
});
main.addComponent(button);
}
}
|
package com.jenjinstudios.io.connection;
import com.jenjinstudios.io.ExecutionContext;
import com.jenjinstudios.io.MessageIOFactory;
import com.jenjinstudios.io.MessageReader;
import com.jenjinstudios.io.MessageWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Collection;
import java.util.LinkedList;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
/**
* Used to configure and create a Connection.
*
* @author Caleb Brinkman
*/
public class ConnectionBuilder
{
private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionBuilder.class);
private final Collection<Consumer<ExecutionContext>> contextualTasks = new LinkedList<>();
private MessageIOFactory messageIOFactory;
private MessageReader messageReader;
private MessageWriter messageWriter;
private ExecutionContext executionContext;
private BiConsumer<Connection, Throwable> errorCallback;
/**
* Build a connection using all the values supplied to this builder.
*
* @return A connection built with all the values supplied to this builder.
*/
public Connection build() {
if (messageReader == null) { throw new IllegalStateException("MessageReader not set"); }
if (messageWriter == null) { throw new IllegalStateException("MessageWriter not set"); }
if (executionContext == null) { throw new IllegalStateException("Execution Context not set"); }
return new Connection(executionContext, messageReader, messageWriter, errorCallback, contextualTasks);
}
/**
* Construct a new ConnectionBuilder that will establish a connection over the given socket.
*
* @param socket The socket over which the connection will be made.
*
* @throws IOException If there is an exception when creating streams from the given socket.
* @return This ConnectionBuilder.
*/
public ConnectionBuilder withSocket(Socket socket) throws IOException {
final InputStream inputStream = socket.getInputStream();
final OutputStream outputStream = socket.getOutputStream();
withInputStream(inputStream);
withOutputStream(outputStream);
return this;
}
/**
* Use the given MessageIOFactory to create MessageReader and MessageWriter instances from Java Input and Output
* streams.
*
* @param factory The MessageIOFactory.
* @return This ConnectionBuilder.
*/
public ConnectionBuilder withMessageIOFactory(MessageIOFactory factory) {
if (messageIOFactory == null) {
if ((messageReader != null) || (messageWriter != null)) {
LOGGER.warn("Applying MessageIOFactory after one or both streams have already been set");
}
this.messageIOFactory = factory;
} else {
throw new IllegalStateException("MessageIOFactory already set");
}
return this;
}
/**
* Build a connection with the given InputStream.
*
* @param inputStream The stream the Connection will use to read messages.
*
* @return This ConnectionBuilder
*/
public ConnectionBuilder withInputStream(InputStream inputStream) {
if (messageIOFactory == null) {
throw new IllegalStateException("MessageIOFactory not set");
}
if (messageReader == null) {
messageReader = messageIOFactory.createReader(inputStream);
} else {
throw new IllegalStateException("MessageReader is already set");
}
return this;
}
/**
* Build a connection with the given OutputStream.
*
* @param outputStream The output stream the Connection will use to write messages.
*
* @return This ConnectionBuilder
*/
public ConnectionBuilder withOutputStream(OutputStream outputStream) {
if (messageIOFactory == null) {
throw new IllegalStateException("MessageIOFactory not set");
}
if (messageWriter == null) {
messageWriter = messageIOFactory.createWriter(outputStream);
} else {
throw new IllegalStateException("MessageWriter is already set");
}
return this;
}
/**
* Build a connection with the given InputStream.
*
* @param reader The stream the Connection will use to read messages.
*
* @return This ConnectionBuilder
*/
public ConnectionBuilder withMessageReader(MessageReader reader) {
if (messageReader == null) {
messageReader = reader;
} else {
throw new IllegalStateException("MessageReader is already set");
}
return this;
}
/**
* Build a connection with the given OutputStream.
*
* @param writer The output stream the Connection will use to write messages.
* @return This ConnectionBuilder
*/
public ConnectionBuilder withMessageWriter(MessageWriter writer) {
if (messageWriter == null) {
messageWriter = writer;
} else {
throw new IllegalStateException("MessageWriter is already set");
}
return this;
}
/**
* Build a connection with the given ExecutionContext.
*
* @param context The context in which the Connection will execute messages.
* @return This ConnectionBuilder.
*/
public ConnectionBuilder withExecutionContext(ExecutionContext context) {
if (executionContext == null) {
executionContext = context;
} else {
throw new IllegalStateException("Execution context is already set");
}
return this;
}
/**
* Build a connection with the given error callback function.
*
* @param callback The Consumer (accepting a Connection and Throwable) that will be invoked when an error is
* encountered.
*
* @return This ConnectionBuilder.
*/
public ConnectionBuilder withErrorCallback(BiConsumer<Connection, Throwable> callback) {
this.errorCallback = callback;
return this;
}
/**
* Build a connection that includes the given contextual task to be executed synchronously with message execution.
*
* @param task The task to be executed; a Consumer accepting an ExecutionContext.
*
* @return This ConnectionBuilder.
*/
public ConnectionBuilder withContextualTask(Consumer<ExecutionContext> task) {
contextualTasks.add(task);
return this;
}
/**
* Build a connection that includes the given contextual task to be executed synchronously with message execution.
*
* @param tasks The tasks to be executed; Consumers accepting an ExecutionContext.
*
* @return This ConnectionBuilder.
*/
@SafeVarargs
public final ConnectionBuilder withContextualTasks(Consumer<ExecutionContext>... tasks) {
for (Consumer<ExecutionContext> task : tasks) {
withContextualTask(task);
}
return this;
}
/**
* Build a connection that includes the given contextual task to be executed synchronously with message execution.
*
* @param tasks The tasks to be executed; Consumers accepting an ExecutionContext.
*
* @return This ConnectionBuilder.
*/
public ConnectionBuilder withContextualTasks(Iterable<Consumer<ExecutionContext>> tasks) {
tasks.forEach(this::withContextualTask);
return this;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.