answer stringlengths 17 10.2M |
|---|
package com.mamewo.malarm24;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Binder;
import android.os.IBinder;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.KeyEvent;
public class MalarmPlayerService
extends Service
implements MediaPlayer.OnCompletionListener,
MediaPlayer.OnErrorListener
{
final static
public String PACKAGE_NAME = MalarmActivity.class.getPackage().getName();
final static
public String WAKEUP_ACTION = PACKAGE_NAME + ".WAKEUP_ACTION";
final static
public String START_WAKEUP_SERVICE_ACTION = PACKAGE_NAME + ".START_WAKEUP_SERVICE_ACTION";
final static
public String SLEEP_ACTION = PACKAGE_NAME + ".SLEEP_ACTION";
final static
public String PLAYSTOP_ACTION = PACKAGE_NAME + ".PLAYSTOP_ACTION";
final static
public String PLAYNEXT_ACTION = PACKAGE_NAME + ".PLAYNEXT_ACTION";
final static
public String STOP_MUSIC_ACTION = PACKAGE_NAME + ".STOP_MUSIC_ACTION";
final static
public String LOAD_PLAYLIST_ACTION = PACKAGE_NAME + ".LOAD_PLAYLIST_ACTION";
final static
public String UNPLUGGED_ACTION = PACKAGE_NAME + ".UNPLUGGED_ACTION";
final static
public String MEDIA_BUTTON_ACTION = PACKAGE_NAME + ".MEDIA_BUTTON_ACTION";
final static
public String WAKEUP_PLAYLIST_FILENAME = "wakeup.m3u";
final static
public String SLEEP_PLAYLIST_FILENAME = "sleep.m3u";
final static
private int NOTIFY_PLAYING_ID = 1;
final private Class<MalarmActivity> userClass_ = MalarmActivity.class;
//error code from base/include/media/stagefright/MediaErrors.h
final static
private int MEDIA_ERROR_BASE = -1000;
final static
private int ERROR_ALREADY_CONNECTED = MEDIA_ERROR_BASE;
final static
private int ERROR_NOT_CONNECTED = MEDIA_ERROR_BASE - 1;
final static
private int ERROR_UNKNOWN_HOST = MEDIA_ERROR_BASE - 2;
final static
private int ERROR_CANNOT_CONNECT = MEDIA_ERROR_BASE - 3;
final static
private int ERROR_IO = MEDIA_ERROR_BASE - 4;
final static
private int ERROR_CONNECTION_LOST = MEDIA_ERROR_BASE - 5;
final static
private int ERROR_MALFORMED = MEDIA_ERROR_BASE - 7;
final static
private int ERROR_OUT_OF_RANGE = MEDIA_ERROR_BASE - 8;
final static
private int ERROR_BUFFER_TOO_SMALL = MEDIA_ERROR_BASE - 9;
final static
private int ERROR_UNSUPPORTED = MEDIA_ERROR_BASE - 10;
final static
private int ERROR_END_OF_STREAM = MEDIA_ERROR_BASE - 11;
// Not technically an error.
final static
private int INFO_FORMAT_CHANGED = MEDIA_ERROR_BASE - 12;
final static
private int INFO_DISCONTINUITY = MEDIA_ERROR_BASE - 13;
final static
private String TAG = "malarm";
final static
private long VIBRATE_PATTERN[] =
{ 10, 1500, 500, 1500, 500, 1500, 500, 1500, 500 };
private final IBinder binder_ = new LocalBinder();
private Playlist currentPlaylist_;
private String currentMusicName_;
private MediaPlayer player_;
private UnpluggedReceiver receiver_;
private int iconId_ = 0;
private ComponentName mediaButtonReceiver_;
static
public M3UPlaylist wakeupPlaylist_ = null;
static
public M3UPlaylist sleepPlaylist_ = null;
private Ringtone tone_ = null;
private List<PlayerStateListener> listenerList_;
private String currentNoteTitle_ = "";
@Override
public int onStartCommand(Intent intent, int flags, int startId){
String action = intent.getAction();
Log.d(TAG, "onStartCommand: " + action);
if(START_WAKEUP_SERVICE_ACTION.equals(action)){
loadPlaylist();
SharedPreferences pref =
PreferenceManager.getDefaultSharedPreferences(this);
int volume = Integer.valueOf(pref.getString(MalarmPreference.PREFKEY_WAKEUP_VOLUME,
MalarmPreference.DEFAULT_WAKEUP_VOLUME));
AudioManager mgr = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
stopMusic();
if(null == wakeupPlaylist_){
//TODO: test volume
mgr.setStreamVolume(AudioManager.STREAM_RING, volume, AudioManager.FLAG_SHOW_UI);
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
tone_ = RingtoneManager.getRingtone(this, uri);
if (null == tone_) {
uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
tone_ = RingtoneManager.getRingtone(this, uri);
}
if (null != tone_) {
tone_.play();
}
}
else {
currentNoteTitle_ = getString(R.string.notify_wakeup_text);
mgr.setStreamVolume(AudioManager.STREAM_MUSIC, volume, AudioManager.FLAG_SHOW_UI);
Log.d(TAG, "onStartCommand: playMusic");
playMusic(wakeupPlaylist_, false);
}
boolean vibrate =
pref.getBoolean(MalarmPreference.PREFKEY_VIBRATE, MalarmPreference.DEFAULT_VIBRATION);
if (vibrate) {
startVibrator();
}
Intent activityIntent = new Intent(this, MalarmActivity.class);
activityIntent.setAction(WAKEUP_ACTION);
activityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(activityIntent);
}
else if (STOP_MUSIC_ACTION.equals(action)) {
stopMusic();
}
else if (PLAYSTOP_ACTION.equals(action)) {
if (isPlaying()) {
pauseMusic();
}
else {
if (null == currentPlaylist_) {
loadPlaylist();
currentPlaylist_ = wakeupPlaylist_;
}
playMusic(true);
}
}
else if (PLAYNEXT_ACTION.equals(action)) {
if (isPlaying()) {
playNext();
}
}
else if (LOAD_PLAYLIST_ACTION.equals(action)) {
Log.d(TAG, "LOAD_PLAYLIST_ACTION");
loadPlaylist();
}
else if (UNPLUGGED_ACTION.equals(action)) {
SharedPreferences pref =
PreferenceManager.getDefaultSharedPreferences(this);
boolean stop = pref.getBoolean("stop_on_unplugged", true);
if (stop) {
pauseMusic();
}
}
else if (MEDIA_BUTTON_ACTION.equals(action)) {
KeyEvent event = intent.getParcelableExtra("event");
Log.d(TAG, "SERVICE: Received media button: " + event.getKeyCode());
if (event.getAction() != KeyEvent.ACTION_UP) {
return START_STICKY;
}
switch(event.getKeyCode()) {
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
if (player_.isPlaying()){
pauseMusic();
}
else {
playMusic(true);
}
break;
case KeyEvent.KEYCODE_MEDIA_NEXT:
if (player_.isPlaying()) {
playNext();
}
break;
case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
//rewind...
playMusic();
break;
default:
break;
}
}
return START_STICKY;
}
public void loadPlaylist() {
SharedPreferences pref =
PreferenceManager.getDefaultSharedPreferences(this);
String playlistPath = pref.getString(MalarmPreference.PREFKEY_PLAYLIST_PATH,
MalarmPreference.DEFAULT_PLAYLIST_PATH.getAbsolutePath());
Log.d(TAG, "loadPlaylist is called:" + playlistPath);
try {
wakeupPlaylist_ = new M3UPlaylist(playlistPath, WAKEUP_PLAYLIST_FILENAME);
}
catch (FileNotFoundException e) {
Log.i(TAG, "wakeup playlist is not found: " + WAKEUP_PLAYLIST_FILENAME);
wakeupPlaylist_ = null;
}
catch (IOException e) {
Log.i(TAG, "wakeup playlist cannot be load: " + WAKEUP_PLAYLIST_FILENAME);
wakeupPlaylist_ = null;
}
try {
sleepPlaylist_ = new M3UPlaylist(playlistPath, SLEEP_PLAYLIST_FILENAME);
}
catch (FileNotFoundException e) {
Log.i(TAG, "sleep playlist is not found: " + SLEEP_PLAYLIST_FILENAME);
sleepPlaylist_ = null;
}
catch (IOException e) {
Log.i(TAG, "sleep playlist cannot be load: " + WAKEUP_PLAYLIST_FILENAME);
sleepPlaylist_ = null;
}
}
public boolean isPlaying() {
return player_.isPlaying();
}
//not used..
public void playMusicNativePlayer(Context context, File f) {
Intent i = new Intent();
i.setAction(Intent.ACTION_VIEW);
/**
* play given playlist from beginning.
*
* @param playlist playlist to play
* @return true if playlist is played, false if it fails.
*/
public boolean playMusic(Playlist playlist, boolean notify) {
return playMusic(playlist, 0, notify);
}
public boolean playMusic(Playlist playlist, int pos, boolean notify) {
currentPlaylist_ = playlist;
if(null == playlist){
return false;
}
playlist.setPosition(pos);
return playMusic(notify);
}
public boolean playMusic(boolean playingNotification) {
if(playingNotification) {
iconId_ = R.drawable.playing;
currentNoteTitle_ = getString(R.string.playing);
}
return playMusic();
}
public boolean playMusic() {
if (null == currentPlaylist_ || currentPlaylist_.isEmpty()) {
Log.i(TAG, "playMusic: playlist is null");
return false;
}
//TODO: remove this check
if (player_.isPlaying()) {
player_.stop();
}
String path = "";
//skip unsupported files filtering by filename ...
for (int i = 0; i < 10; i++) {
path = currentPlaylist_.getURL();
if (path.startsWith("http:
break;
}
File f = new File(path);
// ... m4p is protected audio file
if ((!path.endsWith(".m4p")) && f.exists()) {
break;
}
int pos = currentPlaylist_.getCurrentPosition();
pos = (pos + 1) % currentPlaylist_.size();
currentPlaylist_.setPosition(pos);
}
Log.i(TAG, "playMusic: " + path);
//TODO: get title from file
currentMusicName_ = (new File(path)).getName();
try {
player_.reset();
player_.setDataSource(path);
player_.prepare();
player_.start();
for (PlayerStateListener listener: listenerList_) {
listener.onStartMusic(currentMusicName_);
}
if (iconId_ != 0) {
//TODO: modify notification title
showNotification(currentNoteTitle_, currentMusicName_, iconId_);
}
}
catch (IOException e) {
return false;
}
return true;
}
public void stopMusic() {
if(null != tone_){
tone_.stop();
}
if(player_.isPlaying()){
player_.stop();
for (PlayerStateListener listener: listenerList_) {
listener.onStopMusic();
}
}
//umm...
if(iconId_ == R.drawable.playing) {
clearNotification();
}
//clear music title
if (iconId_ == R.drawable.img) {
showNotification(currentNoteTitle_, "");
}
}
public void pauseMusic() {
if(! player_.isPlaying()) {
return;
}
player_.pause();
for (PlayerStateListener listener: listenerList_) {
listener.onStopMusic();
}
//umm...
if(iconId_ == R.drawable.playing) {
clearNotification();
}
//clear music title
if (iconId_ == R.drawable.img) {
showNotification(currentNoteTitle_, "");
}
}
public void startVibrator() {
Vibrator vibrator =
(Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (null == vibrator) {
return;
}
vibrator.vibrate(VIBRATE_PATTERN, 1);
}
public void stopVibrator() {
Vibrator vibrator =
(Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
if (null == vibrator) {
return;
}
vibrator.cancel();
}
public class LocalBinder
extends Binder
{
public MalarmPlayerService getService() {
return MalarmPlayerService.this;
}
}
@Override
public void onCreate(){
super.onCreate();
listenerList_ = new ArrayList<PlayerStateListener>();
tone_ = null;
currentMusicName_ = null;
loadPlaylist();
currentPlaylist_ = wakeupPlaylist_;
player_ = new MediaPlayer();
player_.setOnCompletionListener(this);
player_.setOnErrorListener(this);
receiver_ = new UnpluggedReceiver();
registerReceiver(receiver_, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mediaButtonReceiver_ = new ComponentName(getPackageName(), UnpluggedReceiver.class.getName());
manager.registerMediaButtonEventReceiver(mediaButtonReceiver_);
}
@Override
public void onDestroy(){
AudioManager manager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
manager.unregisterMediaButtonEventReceiver(mediaButtonReceiver_);
unregisterReceiver(receiver_);
player_ = null;
currentPlaylist_ = null;
wakeupPlaylist_ = null;
sleepPlaylist_ = null;
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return binder_;
}
final static
public class Receiver
extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i(TAG, "onReceive: " + action);
if(null == action){
return;
}
if(WAKEUP_ACTION.equals(action)){
Intent i = new Intent(context, MalarmPlayerService.class);
i.setAction(START_WAKEUP_SERVICE_ACTION);
context.startService(i);
}
else if(SLEEP_ACTION.equals(action)){
//TODO: support native player
Intent i = new Intent(context, MalarmPlayerService.class);
i.setAction(STOP_MUSIC_ACTION);
context.startService(i);
}
}
}
final static
public class UnpluggedReceiver
extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(null == action) {
return;
}
if(Intent.ACTION_HEADSET_PLUG.equals(action)) {
if(intent.getIntExtra("state", 1) == 0){
Intent i = new Intent(context, MalarmPlayerService.class);
i.setAction(UNPLUGGED_ACTION);
context.startService(i);
}
}
else if(Intent.ACTION_MEDIA_BUTTON.equals(action)){
Log.d(TAG, "media button");
KeyEvent event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
if (null == event) {
return;
}
Intent i = new Intent(context, MalarmPlayerService.class);
i.setAction(MEDIA_BUTTON_ACTION);
i.putExtra("event", event);
context.startService(i);
}
}
}
public void addPlayerStateListener(PlayerStateListener listener) {
listenerList_.add(listener);
}
public void removePlayerStateListener(PlayerStateListener listener) {
listenerList_.remove(listener);
}
public interface PlayerStateListener {
public void onStartMusic(String title);
public void onStopMusic();
}
} |
package com.nozomi.fragmentsample2;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
public class MainActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {@link #restoreActionBar()}.
*/
private String[] titleArray = new String[] { "fragment0", "fragment1",
"fragment2" };
private ActionBar actionBar = null;
private boolean isDrawer = false;
private static final String SP_IS_DRAWER = "is_drawer";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initView();
}
private void initView() {
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
isDrawer = sp.getBoolean(SP_IS_DRAWER, false);
actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
if (isDrawer) {
setContentView(R.layout.main_activity_drawer);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
} else {
setContentView(R.layout.main_activity_tab);
MyAdapter pagerAdapter = new MyAdapter(getSupportFragmentManager());
ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(0);
actionBar.setTitle(titleArray[0]);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
actionBar.setTitle(titleArray[position]);
}
@Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pagerTabStrip);
pagerTabStrip.setDrawFullUnderline(true);
}
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.container,
PlaceholderFragment.newInstance(titleArray[position]))
.commit();
actionBar.setTitle(titleArray[position]);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.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();
if (id == R.id.action_settings) {
Toast.makeText(this, "action_settings", Toast.LENGTH_SHORT).show();
return true;
} else if (id == R.id.action_change) {
isDrawer = !isDrawer;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(this);
sp.edit().putBoolean(SP_IS_DRAWER, isDrawer).commit();
finish();
startActivity(getIntent());
return true;
}
return super.onOptionsItemSelected(item);
}
public String[] getTitleArray() {
return titleArray;
}
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
@Override
public CharSequence getPageTitle(int position) {
return titleArray[position];
}
@Override
public int getCount() {
return titleArray.length;
}
@Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(titleArray[position]);
}
}
} |
package jpt.app01;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Deque;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import jpt.app01.data.LanguageProfile;
import jpt.app01.data.LanguagesDatabase;
import jpt.app01.session.Session;
import jpt.app01.session.SessionFilter;
import static jpt.app01.QueryParser.getFirstParameterValue;
/**
* Search a language profile from the database
* @author avm
*/
class LanguageHandler implements HttpHandler {
private static final Logger LOG = Logger.getLogger(LanguageHandler.class.getName());
private static final String HISTORY_ATTNM = "HISTORY";
private final LanguagesDatabase database;
public LanguageHandler() {
database = new LanguagesDatabase();
}
static class LastRequest {
private final String languageName;
private final byte[] importantInfo;
public LastRequest(String languageName) {
this.languageName = languageName;
this.importantInfo = getImportantInfo(); // Keep this, it simulates actual memory usage
}
public String getLanguageName() {
return languageName;
}
public int getSize() {
return importantInfo.length;
}
@Override
public String toString() {
return String.format("%s (%d)", languageName, importantInfo.length);
}
private static final Random random = new Random();
private static byte[] getImportantInfo() {
int randomSize = random.nextInt(10000);
return new byte[randomSize];
}
}
public static Deque<LastRequest> getOrCreateHistory(HttpExchange exchange) {
final Optional<Session> optSession = SessionFilter.getSession(exchange);
if (!optSession.isPresent()) throw new IllegalStateException("Could not retrieve session");
Session session = optSession.get();
return session.getOrCreateAttribute(HISTORY_ATTNM,
() -> new ConcurrentLinkedDeque<>());
}
@Override
public void handle(HttpExchange exchange) throws IOException {
String rawQuery = exchange.getRequestURI().getRawQuery();
String languageName;
try {
languageName = getFirstParameterValue(rawQuery, "name").
orElseThrow(() -> new IllegalArgumentException("Missing parameter 'name'"));
} catch (IllegalArgumentException e) {
ErrorResponder.respond(exchange, ErrorResponder.ERR_BAD_REQUEST, e.getMessage());
return;
}
try {
getOrCreateHistory(exchange).add(new LastRequest(languageName));
} catch (Exception e) {
ErrorResponder.respond(exchange, ErrorResponder.SYS_INTERNAL, "Could not retrieve history");
return;
}
synchronized (database) {
LanguageProfile language = database.getLanguage(languageName);
if (null==language) {
ErrorResponder.respond(exchange, ErrorResponder.ERR_NOT_FOUND, "Language '" + languageName + "' not found in database.");
return;
}
Headers responseHeaders = exchange.getResponseHeaders();
responseHeaders.set("Content-Type", "text/html");
exchange.sendResponseHeaders(200, 0);
if ("HEAD".equals(exchange.getRequestMethod())) return;
try (PrintStream out = new PrintStream(exchange.getResponseBody())) {
HeaderResponse.send(out, SessionFilter.getSession(exchange), languageName);
out.println("<DIV>");
out.printf("<B>%s</B>", languageName);
out.println("<UL>");
for (String attributeName: language.getAttributeNames()) {
out.printf("<LI><U>%s</U>: %s</LI>\n", attributeName, language.getAttributeValue(attributeName));
}
out.println("</UL>");
out.println("</DIV>");
} catch (Exception e) {
LOG.log(Level.SEVERE, "Failed returning HTML page for language '" + languageName + "': ", e);
throw(e);
}
}
}
} |
package com.poomoo.edao.config;
public class eDaoClientConfig {
public static final String BaseLocalUrl = "http://192.168.0.112:8080/yidao/app/";
public static final String BaseRemoteUrl = "http:
public static final String url = BaseRemoteUrl + "call.htm";
// public static final String wxReUrl = BaseUrl +
// "orders/wxPayCallBack.json";
public static final String wxReUrl = "http:
public static final String imageurl = BaseRemoteUrl + "user/uploadUserImage.json";
public static final String uploadStoreurl = BaseRemoteUrl + "shop/add.json";
public static final int timeout = 1 * 30 * 1000;
public static final int advTime = 1 * 5 * 1000;
// public static final String url =
public static final String checkNet = "";
public static final String certificate = "";
public static final String notInstallWX = ",";
public static final String notDevelop = ",...";
public static final String balanceIsNotEnough = "";
public static final String less500 = "500";
public static final String more5000 = "5000";
public static final int freshFlag = 1;
public static String tel = "", web = "", weibo = "", weixin = "";
} |
package com.puzzletimer.scramblers;
import com.puzzletimer.models.Scramble;
import com.puzzletimer.models.ScramblerInfo;
import net.gnehzr.tnoodle.scrambles.Puzzle;
import java.util.Random;
public abstract class WcaScrambler implements Scrambler {
private ScramblerInfo scramblerInfo;
private Puzzle puzzle;
private Random random;
public WcaScrambler(ScramblerInfo scramblerInfo) {
this.scramblerInfo = scramblerInfo;
random = new Random();
}
public void setPuzzle(Puzzle puzzle) {
this.puzzle = puzzle;
}
@Override
public ScramblerInfo getScramblerInfo() {
return scramblerInfo;
}
@Override
public Scramble getNextScramble() {
return new Scramble(
getScramblerInfo().getScramblerId(),
puzzle.generateWcaScramble(random).split("\\s"));
}
@Override
public String toString() {
return getScramblerInfo().getDescription();
}
} |
package com.stromberglabs.jopensurf;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.swing.*;
public class SurfCompare extends JPanel {
private static final long serialVersionUID = 1L;
private static final int BASE_CIRCLE_DIAMETER = 8;
private static final int TARGET_CIRCLE_DIAMETER = 4;
private static final int UNMATCHED_CIRCLE_DIAMETER = 4;
private BufferedImage image;
private BufferedImage imageB;
private float mImageAXScale = 0;
private float mImageAYScale = 0;
private float mImageBXScale = 0;
private float mImageBYScale = 0;
private int mImageAWidth = 0;
private int mImageAHeight = 0;
private int mImageBWidth = 0;
private int mImageBHeight = 0;
private Surf mSurfA;
private Surf mSurfB;
private Map<SURFInterestPoint,SURFInterestPoint> mAMatchingPoints;
private Map<SURFInterestPoint,SURFInterestPoint> mBMatchingPoints;
private boolean mUpright = false;
public SurfCompare(BufferedImage image,BufferedImage imageB){
this.image = image;
this.imageB = imageB;
mSurfA = new Surf(image);
mSurfB = new Surf(imageB);
mImageAXScale = (float)Math.min(image.getWidth(),800)/(float)image.getWidth();
mImageAYScale = (float)Math.min(image.getHeight(),800 * (float)image.getHeight()/(float)image.getWidth())/(float)image.getHeight();
mImageBXScale = (float)Math.min(imageB.getWidth(),800)/(float)imageB.getWidth();
mImageBYScale = (float)Math.min(imageB.getHeight(),800 * (float)imageB.getHeight()/(float)imageB.getWidth())/(float)imageB.getHeight();
mImageAWidth = (int)((float)image.getWidth() * mImageAXScale);
mImageAHeight = (int)((float)image.getHeight() * mImageAYScale);
mImageBWidth = (int)((float)imageB.getWidth() * mImageBXScale);
mImageBHeight = (int)((float)image.getHeight() * mImageBYScale);
mAMatchingPoints = mSurfA.getMatchingPoints(mSurfB, mUpright);
mBMatchingPoints = mSurfB.getMatchingPoints(mSurfA, mUpright);
int numAPoints = mUpright ? mSurfA.getUprightInterestPoints().size() :
mSurfA.getFreeOrientedInterestPoints().size();
System.out.println("Image A has " + numAPoints + " with " + mAMatchingPoints.size()
+ " which match B");
int numBPoints = mUpright ? mSurfB.getUprightInterestPoints().size() :
mSurfB.getFreeOrientedInterestPoints().size();
System.out.println("Image B has " + numBPoints + " with " + mBMatchingPoints.size()
+ " which match A");
}
/**
* Drawing an image can allow for more
* flexibility in processing/editing.
*/
protected void paintComponent(Graphics g) {
// Center image in this component.
g.drawImage(image,0,0,mImageAWidth,mImageAHeight,this);
g.drawImage(imageB,mImageAWidth,0,mImageBWidth,mImageBHeight,Color.WHITE,this);
//if there is a surf descriptor, go ahead and draw the points
if ( mSurfA != null && mSurfB != null ){
drawIpoints(g,mUpright ? mSurfA.getUprightInterestPoints() : mSurfA.getFreeOrientedInterestPoints(),0,mImageAXScale,mImageAYScale);
drawIpoints(g,mUpright ? mSurfB.getUprightInterestPoints() : mSurfB.getFreeOrientedInterestPoints(),mImageAWidth,mImageBXScale,mImageBYScale);
drawConnectingPoints(g);
}
}
private void drawIpoints(Graphics g,List<SURFInterestPoint> points,int offset,float xScale,float yScale){
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.RED);
for ( SURFInterestPoint point : points ){
if ( mAMatchingPoints.containsKey(point) || mBMatchingPoints.containsKey(point) ) continue;
int x = (int)(xScale * point.getX()) + offset;
int y = (int)(yScale * point.getY());
g2d.drawOval(x-UNMATCHED_CIRCLE_DIAMETER/2,y-UNMATCHED_CIRCLE_DIAMETER/2,UNMATCHED_CIRCLE_DIAMETER,UNMATCHED_CIRCLE_DIAMETER);
}
//g2d.setColor(Color.GREEN);
//for ( SURFInterestPoint point : commonPoints ){
// int x = (int)(xScale * point.getX()) + offset;
// int y = (int)(yScale * point.getY());
// g2d.drawOval(x,y,8,8);
}
private void drawConnectingPoints(Graphics g){
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.GREEN);
int offset = mImageAWidth;
for ( SURFInterestPoint point : mAMatchingPoints.keySet() ){
int x = (int)(mImageAXScale * point.getX());
int y = (int)(mImageAYScale * point.getY());
g2d.drawOval(x-BASE_CIRCLE_DIAMETER/2,y-BASE_CIRCLE_DIAMETER/2,BASE_CIRCLE_DIAMETER,BASE_CIRCLE_DIAMETER);
SURFInterestPoint target = mAMatchingPoints.get(point);
int tx = (int)(mImageBXScale * target.getX()) + offset;
int ty = (int)(mImageBYScale * target.getY());
g2d.drawOval(tx-TARGET_CIRCLE_DIAMETER/2,ty-TARGET_CIRCLE_DIAMETER/2,TARGET_CIRCLE_DIAMETER,TARGET_CIRCLE_DIAMETER);
g2d.drawLine(x,y,tx,ty);
}
g2d.setColor(Color.BLUE);
for ( SURFInterestPoint point : mBMatchingPoints.keySet() ){
int x = (int)(mImageBXScale * point.getX()) + offset;
int y = (int)(mImageBYScale * point.getY());
g2d.drawOval(x-BASE_CIRCLE_DIAMETER/2,y-BASE_CIRCLE_DIAMETER/2,BASE_CIRCLE_DIAMETER,BASE_CIRCLE_DIAMETER);
SURFInterestPoint target = mBMatchingPoints.get(point);
int tx = (int)(mImageAXScale * target.getX());
int ty = (int)(mImageAYScale * target.getY());
g2d.drawOval(tx-TARGET_CIRCLE_DIAMETER/2,ty-TARGET_CIRCLE_DIAMETER/2,TARGET_CIRCLE_DIAMETER,TARGET_CIRCLE_DIAMETER);
g2d.drawLine(x,y,tx,ty);
}
}
public void display(){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new JScrollPane(this));
f.setSize(mImageAWidth+mImageBWidth,Math.max(mImageAHeight,mImageBHeight));
f.setLocation(0,0);
f.setVisible(true);
}
public void matchesInfo(){
Map<SURFInterestPoint,SURFInterestPoint> pointsA = mSurfA.getMatchingPoints(mSurfB,true);
Map<SURFInterestPoint,SURFInterestPoint> pointsB = mSurfB.getMatchingPoints(mSurfA,true);
System.out.println("There are: " + pointsA.size() + " matching points of " + mSurfA.getUprightInterestPoints().size());
System.out.println("There are: " + pointsB.size() + " matching points of " + mSurfB.getUprightInterestPoints().size());
}
public static void main(String[] args) throws IOException {
BufferedImage imageA = ImageIO.read(new File(args[0]));
BufferedImage imageB = ImageIO.read(new File(args[1]));
// System.out.println(imageA);
// System.out.println(imageB);
SurfCompare show = new SurfCompare(imageA,imageB);
show.display();
//show.matchesInfo();
}
} |
package com.veggiespam.imagelocationscanner;
import java.io.File;
import java.io.FileInputStream;
//import java.io.FileOutputStream; // Only needed when debugging the code
import java.io.IOException;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Collection;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Metadata;
import com.drew.lang.GeoLocation;
import com.drew.metadata.exif.GpsDirectory;
import com.drew.metadata.iptc.IptcDirectory;
import com.drew.metadata.iptc.IptcDescriptor;
import com.drew.metadata.exif.makernotes.PanasonicMakernoteDirectory;
import com.drew.metadata.exif.makernotes.PanasonicMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.LeicaMakernoteDirectory;
import com.drew.metadata.exif.makernotes.LeicaMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.ReconyxUltraFireMakernoteDirectory;
import com.drew.metadata.exif.makernotes.ReconyxUltraFireMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.ReconyxHyperFireMakernoteDirectory;
import com.drew.metadata.exif.makernotes.ReconyxHyperFireMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.CanonMakernoteDirectory;
import com.drew.metadata.exif.makernotes.CanonMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.SigmaMakernoteDirectory;
import com.drew.metadata.exif.makernotes.SigmaMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.NikonType2MakernoteDirectory;
import com.drew.metadata.exif.makernotes.NikonType2MakernoteDescriptor;
import com.drew.metadata.exif.makernotes.OlympusMakernoteDirectory;
import com.drew.metadata.exif.makernotes.OlympusMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.OlympusEquipmentMakernoteDirectory;
import com.drew.metadata.exif.makernotes.OlympusEquipmentMakernoteDescriptor;
import com.drew.metadata.exif.makernotes.FujifilmMakernoteDirectory;
import com.drew.metadata.exif.makernotes.FujifilmMakernoteDescriptor;
public class ILS {
/** A bunch of static strings that are used by both ZAP and Burp plug-ins. */
public static final String pluginName = "Image Location & Privacy Scanner";
public static final String pluginVersion = "1.1";
public static final String alertTitle = "Image Exposes Location or Privacy Data";
public static final String alertDetailPrefix = "This image embeds a location or leaks privacy-related data: ";
public static final String alertBackground
= "The image was found to contain embedded location information, such as GPS coordinates, or "
+ "another privacy exposure, such as camera serial number. "
+ "Depending on the context of the image in the website, "
+ "this information may expose private details of the users of a site. For example, a site that allows "
+ "users to upload profile pictures taken in the home may expose the home's address. ";
public static final String remediationBackground
= "Before allowing images to be stored on the server and/or transmitted to the browser, strip out the "
+ "embedded location information from image. This could mean removing all Exif data or just the GPS "
+ "component. Other data, like serial numbers, should also be removed.";
public static final String remediationDetail = null;
public static final String referenceURL = "https:
public static final String pluginAuthor = "Jay Ball (veggiespam)";
private static final String EmptyString = "";
private static final String TextSubtypeEnd = ": "; // colon space for plain text results
private static final String HTML_subtype_begin = "<li>";
private static final String HTML_subtype_title_end = "\n\t<ul>\n";
private static final String HTML_subtype_end = "\t</ul></li>\n";
private static final String HTML_finding_begin = "\t<li>";
private static final String HTML_finding_end = "</li>\n";
public ILS() {
// blank constructor
super();
}
public String getAuthor() {
return pluginAuthor;
}
/** Tests a data blob for Location or GPS information and returns the image location
* information as a string. If no location is present or there is an error,
* the function will return an empty string of "".
*
* @param data is a byte array that is an image file to test, such as entire jpeg file.
* @return String containing the Location data or an empty String indicating no GPS data found.
*/
public static String[] scanForLocationInImageBoth(byte[] data) {
String[] results = { EmptyString, EmptyString };
try {
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(data, 0, data.length));
Metadata md = ImageMetadataReader.readMetadata(is);
String[] tmp = { EmptyString, EmptyString };
tmp = scanForLocation(md);
results = scanForPrivacy(md);
if (tmp[0].length() > 0) {
// minor formatting if we have both.
results[0] = tmp[0] + "\n\n" + results[0];
results[1] = "<ul>" + tmp[1] + results[1] + "</ul>";
// AGAIN: this is for extreme debugging
// results[0] = "DBG: " + t[0] + "\n\n" + results[0];
// results[1] = "DBG: " + t[1] + "\n\n" + results[1];
}
} catch (ImageProcessingException e) {
// bad image, just ignore processing exceptions
// DEBUG: return new String("ImageProcessingException " + e.toString());
} catch (IOException e) {
// bad file or something, just ignore
// DEBUG: return new String("IOException " + e.toString());
}
return results;
}
/** Returns ILS information as HTML formatting string.
*
* @see scanForLocationInImageBoth
*/
public static String scanForLocationInImageHTML(byte[] data) {
return scanForLocationInImageBoth(data)[1];
}
/** Returns ILS information as Text formatting string.
*
* @see scanForLocationInImageBoth
*/
public static String scanForLocationInImageText(byte[] data) {
return scanForLocationInImageBoth(data)[0];
}
/**
* @deprecated Use the HTML / Text calls directly or use boolean construct.
*/
@Deprecated
public static String scanForLocationInImage(byte[] data) {
return scanForLocationInImageHTML(data);
}
/** Returns ILS information in Text or HTML depending on usehtml flag.
*
* @param data is a byte array that is an image file to test, such as entire jpeg file.
* @param usehtml output as html (true) or plain txt (false)
* @return String containing the Location data or an empty String indicating no GPS data found.
* @see scanForLocationInImageBoth
*/
public static String scanForLocationInImage(byte[] data, boolean usehtml) {
if (usehtml) {
return scanForLocationInImageHTML(data);
} else {
return scanForLocationInImageText(data);
}
}
private static String[] appendResults(String current[], String bigtype, String subtype, ArrayList<String> exposure) {
String[] tmp = formatResults(bigtype, subtype, exposure);
if (tmp[0].length() > 0) {
current[0] = current[0] + tmp[0];
current[1] = current[1] + tmp[1];
}
return current;
}
/** Theoretical chance of XSS inside of Burp/ZAP, so return properly escaped HTML. */
private static String escapeHTML(String s) {
return s.replace("&","&").replace("<",">");
}
/** Do this for completeness, even if a no-op for now. */
private static String escapeTEXT(String s) {
return s; // might want to do more here someday, like binary data as hex codes, etc...
}
private static String[] formatResults(String bigtype, String subtype, ArrayList<String> exposure) {
StringBuffer ret = new StringBuffer(200);
StringBuffer retHTML = new StringBuffer(200);
String[] retarr = { EmptyString, EmptyString };
if (exposure.size() > 0) {
retHTML.append(HTML_subtype_begin).append(bigtype).append(" / ").append(subtype).append(HTML_subtype_title_end);
for (String finding : exposure) {
ret.append(subtype).append(TextSubtypeEnd).append(escapeTEXT(finding)).append("\n");
retHTML.append(HTML_finding_begin).append(escapeHTML(finding)).append(HTML_finding_end);
}
retHTML.append(HTML_subtype_end);
}
retarr[0] = ret.toString();
retarr[1] = retHTML.toString();
return retarr;
}
public static String[] scanForLocation(Metadata md) {
ArrayList<String> exposure = new ArrayList<String>();
String[] results = { EmptyString, EmptyString };
String bigtype = "Location"; // Overall category type. Location or Privacy
String subtype = EmptyString;
// ** Standard Exif GPS
subtype = "Exif_GPS";
Collection<GpsDirectory> gpsDirColl = md.getDirectoriesOfType(GpsDirectory.class);
if (gpsDirColl != null) {
exposure.clear();
for (GpsDirectory gpsDir : gpsDirColl) {
final GeoLocation geoLocation = gpsDir.getGeoLocation();
if ( ! (geoLocation == null || geoLocation.isZero()) ) {
String finding = geoLocation.toDMSString();
exposure.add(finding);
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
// ** IPTC testing
subtype = "IPTC";
Collection<IptcDirectory> iptcDirColl = md.getDirectoriesOfType(IptcDirectory.class);
int iptc_tag_list[] = {
IptcDirectory.TAG_CITY,
IptcDirectory.TAG_SUB_LOCATION,
IptcDirectory.TAG_PROVINCE_OR_STATE,
IptcDirectory.TAG_CONTENT_LOCATION_CODE,
IptcDirectory.TAG_CONTENT_LOCATION_NAME,
IptcDirectory.TAG_COUNTRY_OR_PRIMARY_LOCATION_CODE,
IptcDirectory.TAG_COUNTRY_OR_PRIMARY_LOCATION_NAME,
IptcDirectory.TAG_DESTINATION,
};
if (iptcDirColl != null) {
exposure.clear();
for (IptcDirectory iptcDir : iptcDirColl) {
IptcDescriptor iptcDesc = new IptcDescriptor(iptcDir);
for (int i=0; i< iptc_tag_list.length; i++) {
String tag = iptcDesc.getDescription(iptc_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add( iptcDir.getTagName(iptc_tag_list[i]) + " = " + tag );
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "Panasonic";
Collection<PanasonicMakernoteDirectory> panasonicDirColl = md.getDirectoriesOfType(PanasonicMakernoteDirectory.class);
int panasonic_tag_list[] = {
PanasonicMakernoteDirectory.TAG_CITY,
PanasonicMakernoteDirectory.TAG_COUNTRY,
PanasonicMakernoteDirectory.TAG_LANDMARK,
PanasonicMakernoteDirectory.TAG_LOCATION,
PanasonicMakernoteDirectory.TAG_STATE
};
if (panasonicDirColl != null) {
exposure.clear();
for (PanasonicMakernoteDirectory panasonicDir : panasonicDirColl) {
PanasonicMakernoteDescriptor descriptor = new PanasonicMakernoteDescriptor(panasonicDir);
for (int i=0; i< panasonic_tag_list.length; i++) {
String tag = descriptor.getDescription(panasonic_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.equals("---") || tag.charAt(0) == '\0' )) {
exposure.add(panasonicDir.getTagName(panasonic_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
// For Text, add the big type in the final entry
if (results[0].length() > 0) {
results[0] = bigtype + ":: " + results[0];
}
return results;
}
public static String[] scanForPrivacy(Metadata md) {
String bigtype = "Privacy"; // Overall category type.
String subtype = EmptyString;
ArrayList<String> exposure = new ArrayList<String>();
String[] results = { EmptyString, EmptyString };
// ** IPTC testing
subtype = "IPTC";
Collection<IptcDirectory> iptcDirColl = md.getDirectoriesOfType(IptcDirectory.class);
int iptc_tag_list[] = {
IptcDirectory.TAG_KEYWORDS,
IptcDirectory.TAG_LOCAL_CAPTION
// what about CREDIT BY_LINE ...
};
if (iptcDirColl != null) {
exposure.clear();
for (IptcDirectory iptcDir : iptcDirColl) {
IptcDescriptor iptcDesc = new IptcDescriptor(iptcDir);
for (int i=0; i< iptc_tag_list.length; i++) {
String tag = iptcDesc.getDescription(iptc_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add( iptcDir.getTagName(iptc_tag_list[i]) + " = " + tag );
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "Panasonic";
Collection<PanasonicMakernoteDirectory> panasonicDirColl = md.getDirectoriesOfType(PanasonicMakernoteDirectory.class);
int panasonic_tag_list[] = {
PanasonicMakernoteDirectory.TAG_BABY_AGE,
PanasonicMakernoteDirectory.TAG_BABY_AGE_1,
PanasonicMakernoteDirectory.TAG_BABY_NAME,
PanasonicMakernoteDirectory.TAG_FACE_RECOGNITION_INFO,
PanasonicMakernoteDirectory.TAG_INTERNAL_SERIAL_NUMBER,
PanasonicMakernoteDirectory.TAG_LENS_SERIAL_NUMBER
// What about TAG_TEXT_STAMP_* TAG_TITLE
};
if (panasonicDirColl != null) {
exposure.clear();
for (PanasonicMakernoteDirectory panasonicDir : panasonicDirColl) {
PanasonicMakernoteDescriptor descriptor = new PanasonicMakernoteDescriptor(panasonicDir);
for (int i=0; i< panasonic_tag_list.length; i++) {
String tag = descriptor.getDescription(panasonic_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.equals("---") || tag.charAt(0) == '\0' )) {
exposure.add(panasonicDir.getTagName(panasonic_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "Leica";
Collection<LeicaMakernoteDirectory> leicaDirColl = md.getDirectoriesOfType(LeicaMakernoteDirectory.class);
int leica_tag_list[] = {
LeicaMakernoteDirectory.TAG_SERIAL_NUMBER
};
if (leicaDirColl != null) {
exposure.clear();
for (LeicaMakernoteDirectory leicaDir : leicaDirColl) {
LeicaMakernoteDescriptor descriptor = new LeicaMakernoteDescriptor(leicaDir);
for (int i=0; i< leica_tag_list.length; i++) {
String tag = descriptor.getDescription(leica_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.equals("---") || tag.charAt(0) == '\0' )) {
exposure.add(leicaDir.getTagName(leica_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "ReconyxHyperFire";
Collection<ReconyxHyperFireMakernoteDirectory> reconyxHyperFireDirColl = md.getDirectoriesOfType(ReconyxHyperFireMakernoteDirectory.class);
int reconyxHyperFire_tag_list[] = {
ReconyxHyperFireMakernoteDirectory.TAG_SERIAL_NUMBER
};
if (reconyxHyperFireDirColl != null) {
exposure.clear();
for (ReconyxHyperFireMakernoteDirectory reconyxHyperFireDir : reconyxHyperFireDirColl) {
ReconyxHyperFireMakernoteDescriptor descriptor = new ReconyxHyperFireMakernoteDescriptor(reconyxHyperFireDir);
for (int i=0; i< reconyxHyperFire_tag_list.length; i++) {
String tag = descriptor.getDescription(reconyxHyperFire_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.equals("---") || tag.charAt(0) == '\0' )) {
exposure.add(reconyxHyperFireDir.getTagName(reconyxHyperFire_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "ReconyxUltraFire";
Collection<ReconyxUltraFireMakernoteDirectory> reconyxUltraFireDirColl = md.getDirectoriesOfType(ReconyxUltraFireMakernoteDirectory.class);
int reconyxUltraFire_tag_list[] = {
ReconyxUltraFireMakernoteDirectory.TAG_SERIAL_NUMBER
};
if (reconyxUltraFireDirColl != null) {
exposure.clear();
for (ReconyxUltraFireMakernoteDirectory reconyxUltraFireDir : reconyxUltraFireDirColl) {
ReconyxUltraFireMakernoteDescriptor descriptor = new ReconyxUltraFireMakernoteDescriptor(reconyxUltraFireDir);
for (int i=0; i< reconyxUltraFire_tag_list.length; i++) {
String tag = descriptor.getDescription(reconyxUltraFire_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.equals("---") || tag.charAt(0) == '\0' )) {
exposure.add(reconyxUltraFireDir.getTagName(reconyxUltraFire_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "Olympus";
Collection<OlympusMakernoteDirectory> olympusDirColl = md.getDirectoriesOfType(OlympusMakernoteDirectory.class);
int olympus_tag_list[] = {
OlympusMakernoteDirectory.TAG_SERIAL_NUMBER_1
};
if (olympusDirColl != null) {
exposure.clear();
for (OlympusMakernoteDirectory olympusDir: olympusDirColl) {
OlympusMakernoteDescriptor descriptor = new OlympusMakernoteDescriptor(olympusDir);
for (int i=0; i< olympus_tag_list.length; i++) {
String tag = descriptor.getDescription(olympus_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add(olympusDir.getTagName(olympus_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "OlympusEquipment";
Collection<OlympusEquipmentMakernoteDirectory> olympusEquipmentDirColl = md.getDirectoriesOfType(OlympusEquipmentMakernoteDirectory.class);
int olympusEquipment_tag_list[] = {
OlympusEquipmentMakernoteDirectory.TAG_SERIAL_NUMBER,
OlympusEquipmentMakernoteDirectory.TAG_INTERNAL_SERIAL_NUMBER,
OlympusEquipmentMakernoteDirectory.TAG_LENS_SERIAL_NUMBER,
OlympusEquipmentMakernoteDirectory.TAG_EXTENDER_SERIAL_NUMBER,
OlympusEquipmentMakernoteDirectory.TAG_FLASH_SERIAL_NUMBER
};
if (olympusEquipmentDirColl != null) {
exposure.clear();
for (OlympusEquipmentMakernoteDirectory olympusEquipmentDir: olympusEquipmentDirColl) {
OlympusEquipmentMakernoteDescriptor descriptor = new OlympusEquipmentMakernoteDescriptor(olympusEquipmentDir);
for (int i=0; i< olympusEquipment_tag_list.length; i++) {
String tag = descriptor.getDescription(olympusEquipment_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add(olympusEquipmentDir.getTagName(olympusEquipment_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "Canon";
Collection<CanonMakernoteDirectory> canonDirColl = md.getDirectoriesOfType(CanonMakernoteDirectory.class);
int canon_tag_list[] = {
CanonMakernoteDirectory.TAG_CANON_OWNER_NAME,
CanonMakernoteDirectory.TAG_CANON_SERIAL_NUMBER
};
if (canonDirColl != null) {
exposure.clear();
for (CanonMakernoteDirectory canonDir: canonDirColl) {
CanonMakernoteDescriptor descriptor = new CanonMakernoteDescriptor(canonDir);
for (int i=0; i< canon_tag_list.length; i++) {
String tag = descriptor.getDescription(canon_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add(canonDir.getTagName(canon_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "Sigma";
Collection<SigmaMakernoteDirectory> sigmaDirColl = md.getDirectoriesOfType(SigmaMakernoteDirectory.class);
int sigma_tag_list[] = {
SigmaMakernoteDirectory.TAG_SERIAL_NUMBER
};
if (sigmaDirColl != null) {
exposure.clear();
for (SigmaMakernoteDirectory sigmaDir: sigmaDirColl) {
SigmaMakernoteDescriptor descriptor = new SigmaMakernoteDescriptor(sigmaDir);
for (int i=0; i< sigma_tag_list.length; i++) {
String tag = descriptor.getDescription(sigma_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add(sigmaDir.getTagName(sigma_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "Nikon";
Collection<NikonType2MakernoteDirectory> nikonDirColl = md.getDirectoriesOfType(NikonType2MakernoteDirectory.class);
int nikon_tag_list[] = {
NikonType2MakernoteDirectory.TAG_CAMERA_SERIAL_NUMBER,
NikonType2MakernoteDirectory.TAG_CAMERA_SERIAL_NUMBER_2
};
if (nikonDirColl != null) {
exposure.clear();
for (NikonType2MakernoteDirectory nikonDir: nikonDirColl) {
NikonType2MakernoteDescriptor descriptor = new NikonType2MakernoteDescriptor(nikonDir);
for (int i=0; i< nikon_tag_list.length; i++) {
String tag = descriptor.getDescription(nikon_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add(nikonDir.getTagName(nikon_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
subtype = "FujiFilm";
Collection<FujifilmMakernoteDirectory> fujifilmDirColl = md.getDirectoriesOfType(FujifilmMakernoteDirectory.class);
int fujifilm_tag_list[] = {
FujifilmMakernoteDirectory.TAG_SERIAL_NUMBER
};
if (fujifilmDirColl != null) {
exposure.clear();
for (FujifilmMakernoteDirectory fujifilmDir: fujifilmDirColl) {
FujifilmMakernoteDescriptor descriptor = new FujifilmMakernoteDescriptor(fujifilmDir);
for (int i=0; i< fujifilm_tag_list.length; i++) {
String tag = descriptor.getDescription(fujifilm_tag_list[i]);
if ( ! ( null == tag || tag.equals(EmptyString) || tag.charAt(0) == '\0' )) {
exposure.add(fujifilmDir.getTagName(fujifilm_tag_list[i]) + " = " + tag);
}
}
}
results = appendResults(results, bigtype, subtype, exposure);
}
if (results[0].length() > 0) {
results[0] = bigtype + ":: " + results[0];
}
return results;
}
public static void main(String[] args) throws Exception {
boolean html = false;
if (args.length == 0){
System.out.println("Java Image Location & Privacy Scanner");
System.out.println("Usage: java ILS.class [-h|-t] file1.jpg file2.png file3.txt [...]");
System.out.println("\t-h : optional specifier to output results in HTML format");
System.out.println("\t-t : optional specifier to output results in plain text format (default)");
return;
}
for (String s: args) {
if (s.equals("-h")) {
html=true;
continue;
}
if (s.equals("-t")) {
html=false;
continue;
}
try {
System.out.print("Processing " + s + " : ");
File f = new File(s);
FileInputStream fis = new FileInputStream(f);
long size = f.length();
byte[] data = new byte[(int) size];
fis.read(data);
fis.close();
String res = scanForLocationInImage(data, html);
if (0 == res.length()) {
res = "None";
}
System.out.println(res);
} catch (IOException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
// vim: autoindent noexpandtab tabstop=4 shiftwidth=4 |
package com.zegoggles.smssync;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import com.fsck.k9.mail.*;
import com.fsck.k9.mail.internet.BinaryTempFileBody;
import org.apache.commons.io.IOUtils;
import java.util.HashSet;
import java.util.Set;
import static com.zegoggles.smssync.CursorToMessage.Headers.*;
import static com.zegoggles.smssync.ServiceBase.SmsSyncState.*;
public class SmsRestoreService extends ServiceBase {
public static final String TAG = "SmsRestoreService";
private static int currentRestoredItems;
private static int itemsToRestoreCount;
private static boolean sIsRunning = false;
private static SmsSyncState sState;
private static boolean sCanceled = false;
public static int restoredCount, duplicateCount;
public static void cancel() {
sCanceled = true;
}
public static boolean isWorking() {
return sIsRunning;
}
public static boolean isCancelling() {
return sCanceled;
}
public static int getCurrentRestoredItems() {
return currentRestoredItems;
}
public static int getItemsToRestoreCount() {
return itemsToRestoreCount;
}
class RestoreTask extends AsyncTask<Integer, Integer, Integer> {
private Set<String> insertedIds = new HashSet<String>();
private Set<String> uids = new HashSet<String>();
private int max;
protected java.lang.Integer doInBackground(Integer... params) {
this.max = params.length > 0 ? params[0] : -1;
try {
acquireWakeLock();
sIsRunning = true;
updateState(LOGIN);
ImapStore.BackupFolder folder = getBackupFolder();
updateState(CALC);
Message[] msgs;
if (max > 0) {
msgs = folder.getMessagesSince(null, max);
} else {
msgs = folder.getMessages(null);
}
itemsToRestoreCount = max == -1 ? msgs.length : max;
long lastPublished = System.currentTimeMillis();
for (int i = 0; i < itemsToRestoreCount; i++) {
if (sCanceled) {
Log.i(TAG, "Restore canceled by user.");
updateState(CANCELED);
updateAllThreads();
return insertedIds.size();
}
importMessage(msgs[i]);
// help GC
msgs[i] = null;
if (System.currentTimeMillis() - lastPublished > 1000) {
// don't publish too often or we get ANRs
publishProgress(i);
lastPublished = System.currentTimeMillis();
}
}
publishProgress(itemsToRestoreCount);
updateAllThreads();
return insertedIds.size();
} catch (AuthenticationErrorException authError) {
Log.e(TAG, "error", authError);
updateState(AUTH_FAILED);
return -1;
} catch (MessagingException e) {
Log.e(TAG, "error", e);
updateState(GENERAL_ERROR);
return -1;
} finally {
releaseWakeLock();
sCanceled = false;
sIsRunning = false;
}
}
@Override
protected void onProgressUpdate(Integer... progress) {
currentRestoredItems = progress[0];
updateState(RESTORE);
}
@Override
protected void onPostExecute(Integer result) {
if (result != -1) {
Log.d(TAG, "finished (" + result + "/" + uids.size() + ")");
restoredCount = result;
duplicateCount = uids.size() - result;
updateState(IDLE);
}
}
private void updateAllThreads() {
// thread dates + states might be wrong, we need to force a full update
// unfortunately there's no direct way to do that in the SDK, but passing a negative conversation
// id to delete will to the trick
if (insertedIds.isEmpty())
return;
// execute in background, might take some time
new Thread() {
@Override
public void run() {
Log.d(TAG, "updating threads");
getContentResolver().delete(Uri.parse("content://sms/conversations/-1"), null, null);
Log.d(TAG, "finished");
}
}.start();
}
private void importMessage(Message message) {
uids.add(message.getUid());
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.BODY);
try {
Log.d(TAG, "fetching message uid " + message.getUid());
message.getFolder().fetch(new Message[]{message}, fp, null);
ContentValues values = messageToContentValues(message);
Integer type = values.getAsInteger(SmsConsts.TYPE);
if (type == null)
return;
// only restore inbox messages and sent messages - otherwise sms might get sent on restore
if ((type == SmsConsts.MESSAGE_TYPE_INBOX || type == SmsConsts.MESSAGE_TYPE_SENT) && !smsExists(values)) {
Uri uri = getContentResolver().insert(SMS_PROVIDER, values);
insertedIds.add(uri.getLastPathSegment());
long timestamp = values.getAsLong(SmsConsts.DATE);
if (getMaxSyncedDate() < timestamp) {
updateMaxSyncedDate(timestamp);
}
Log.d(TAG, "inserted " + uri);
} else {
Log.d(TAG, "ignoring sms");
}
} catch (java.io.IOException e) {
Log.e(TAG, "error", e);
} catch (MessagingException e) {
Log.e(TAG, "error", e);
}
}
}
@Override
public void onCreate() {
BinaryTempFileBody.setTempDirectory(getCacheDir());
}
@Override
public void onStart(final Intent intent, int startId) {
super.onStart(intent, startId);
synchronized (ServiceBase.class) {
if (!sIsRunning) {
new RestoreTask().execute(PrefStore.getMaxItemsPerRestore(this));
}
}
}
private boolean smsExists(ContentValues values) {
// just assume equality on date+address+type
Cursor c = getContentResolver().query(SMS_PROVIDER,
new String[]{"_id"},
"date = ? AND address = ? AND type = ?",
new String[]{values.getAsString(SmsConsts.DATE),
values.getAsString(SmsConsts.ADDRESS), values.getAsString(SmsConsts.TYPE)}, null
);
boolean exists = false;
if (c != null) {
exists = c.getCount() > 0;
c.close();
}
return exists;
}
private ContentValues messageToContentValues(Message message)
throws java.io.IOException, MessagingException {
java.io.InputStream is = message.getBody().getInputStream();
if (is == null) {
throw new MessagingException("body is null");
}
String body = IOUtils.toString(is);
ContentValues values = new ContentValues();
values.put(SmsConsts.BODY, body);
values.put(SmsConsts.ADDRESS, getHeader(message, ADDRESS));
values.put(SmsConsts.TYPE, getHeader(message, TYPE));
values.put(SmsConsts.PROTOCOL, getHeader(message, PROTOCOL));
values.put(SmsConsts.SERVICE_CENTER, getHeader(message, SERVICE_CENTER));
values.put(SmsConsts.DATE, getHeader(message, DATE));
values.put(SmsConsts.STATUS, getHeader(message, STATUS));
values.put(SmsConsts.READ, PrefStore.getMarkAsReadOnRestore(this) ? "1" : getHeader(message, READ));
return values;
}
private static void updateState(SmsSyncState newState) {
SmsSyncState old = sState;
sState = newState;
smsSync.getStatusPreference().stateChanged(old, newState);
}
} |
package org.kohsuke.args4j.spi;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.IllegalAnnotationError;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* {@link Setter} that allows multiple values to be stored into one array field.
*
* <p>
* Because of the {@link CmdLineParser} abstractions of allowing incremental parsing of options,
* this implementation creates a whole new array each time a new value is found.
*
* This is also why we don't support a setter method that takes list/array as arguments.
*
* @author Kohsuke Kawaguchi
*/
final class ArrayFieldSetter implements Setter {
private final Object bean;
private final Field f;
private Object defaultArray;
public ArrayFieldSetter(Object bean, Field f) {
this.bean = bean;
this.f = f;
if(!f.getType().isArray())
throw new IllegalAnnotationError(Messages.ILLEGAL_FIELD_SIGNATURE.format(f.getType()));
trySetDefault(bean);
}
/** Remember default so we throw away the default when adding user values.
*/
private void trySetDefault(Object bean1) throws IllegalAccessError {
try {
doSetDefault(bean1);
} catch (IllegalAccessException ex) {
try {
// try again
f.setAccessible(true);
doSetDefault(bean1);
}catch (IllegalAccessException ex1) {
throw new IllegalAccessError(ex1.getMessage());
}
}
}
private void doSetDefault(Object bean) throws IllegalAccessException {
this.defaultArray = f.get(bean);
}
public FieldSetter asFieldSetter() {
return new FieldSetter(bean,f);
}
public AnnotatedElement asAnnotatedElement() {
return f;
}
public boolean isMultiValued() {
return true;
}
public Class getType() {
return f.getType().getComponentType();
}
public void addValue(Object value) {
try {
doAddValue(bean, value);
} catch (IllegalAccessException _) {
// try again
f.setAccessible(true);
try {
doAddValue(bean,value);
} catch (IllegalAccessException e) {
throw new IllegalAccessError(e.getMessage());
}
}
}
private void doAddValue(Object bean, Object value) throws IllegalAccessException {
Object ary = f.get(bean);
if (ary == null || ary == defaultArray) {
ary = Array.newInstance(getType(), 1);
Array.set(ary, 0, value);
} else {
int len = Array.getLength(ary);
Object newAry = Array.newInstance(ary.getClass().getComponentType(), len +1);
System.arraycopy(ary, 0, newAry, 0, len);
Array.set(newAry, len, value);
ary = newAry;
}
f.set(bean, ary);
}
} |
package io.spine.query;
import io.spine.testing.Tests;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import static com.google.common.truth.Truth.assertThat;
import static io.spine.testing.Tests.nullRef;
import static org.junit.jupiter.api.Assertions.assertThrows;
@DisplayName("`RecordColumn` should")
class RecordColumnTest {
@Test
@DisplayName("allow creating new instances")
void allowCreation() {
String name = "description";
String description = "some description";
RecordColumn<Manufacturer, String> column =
new RecordColumn<>(name, String.class, (r) -> description);
assertThat(column).isNotNull();
assertThat(column.name().value()).isEqualTo(name);
assertThat(column.type()).isEqualTo(String.class);
assertThat(column.valueIn(Manufacturer.getDefaultInstance())).isEqualTo(description);
}
@Nested
@DisplayName("prevent from passing")
final class Prevent {
@Test
@DisplayName("empty or `null` column name into ctor")
void emptyOrNullColumnName() {
assertThrows(IllegalArgumentException.class,
() -> new RecordColumn<>("", String.class, (r) -> ""));
assertThrows(NullPointerException.class,
() -> new RecordColumn<Manufacturer, String>(Tests.<String>nullRef(),
String.class,
(r) -> ""));
}
@Test
@DisplayName("`null` value type into ctor")
void nullValueType() {
assertThrows(NullPointerException.class,
() -> new RecordColumn<Manufacturer, String>("isin",
nullRef(),
(r) -> ""));
}
@Test
@DisplayName("`null` getter into ctor")
void nullGetter() {
assertThrows(NullPointerException.class,
() -> new RecordColumn<Manufacturer, String>("isin",
String.class,
nullRef()));
}
}
} |
package cz.kamenitxan.labelprinter;
import cz.kamenitxan.labelprinter.models.Manufacturer;
import cz.kamenitxan.labelprinter.models.Product;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.util.Matrix;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
public class PdfGenerator {
public static final float pageWidth = 833;
public static final float pageHeight = 586;
public static final float wholePageWidth = 843;
public static final float wholePageHeight = 596;
public static final PDRectangle PAGE_SIZE_A4 = new PDRectangle( wholePageHeight, wholePageWidth);
public static final float lamdaImageWidth = 90;
public static final float lamdaImageHeight = 196;
public static final float labelImageWidth = 15;
public static final float labelImageHeight = 67;
public static final float margin = 5;
public static ArrayList<Manufacturer> manufacturers = new ArrayList<>();
private boolean capacityMove = false;
public PdfGenerator() {
}
public void generatePdf(Product product){
for (Manufacturer manufacturer : manufacturers) {
PDDocument document = new PDDocument();
PDPage page = new PDPage(PAGE_SIZE_A4);
document.addPage(page);
page.setRotation(90);
try {
PDPageContentStream contentStream = new PDPageContentStream(document, page);
PDType0Font font = PDType0Font.load(document, new File("img/OpenSans-Regular.ttf"));
PDType0Font boldFont = PDType0Font.load(document, new File("img/OpenSans-Bold.ttf"));
//obrazky
PDImageXObject lamdaImage = PDImageXObject.createFromFile("img/lamda.jpg", document);
PDImageXObject labelImage = PDImageXObject.createFromFile("img/label.jpg", document);
float firstH = 0;
float secondH = pageHeight/3;
float thirdH = 2*secondH;
contentStream.drawImage(lamdaImage, 0+margin, 25, lamdaImageWidth, lamdaImageHeight);
contentStream.drawImage(lamdaImage, 0+margin, ((6 * pageWidth) / 10)+15, lamdaImageWidth, lamdaImageHeight);
contentStream.drawImage(labelImage, ((pageHeight / 3) - labelImageWidth - 5), ((pageWidth / 3) - (labelImageHeight / 2)), labelImageWidth, labelImageHeight);
contentStream.drawImage(labelImage, ((pageHeight / 3) - labelImageWidth - 5), ((4 * (pageWidth / 5)) - (labelImageHeight / 2)), labelImageWidth, labelImageHeight);
contentStream.drawImage(lamdaImage, (pageHeight / 3)+2, 25, lamdaImageWidth, lamdaImageHeight);
contentStream.drawImage(lamdaImage, (pageHeight / 3)+2, ((6 * pageWidth) / 10)+15, lamdaImageWidth, lamdaImageHeight);
contentStream.drawImage(labelImage, ((2 * (pageHeight / 3)) - labelImageWidth - 5), ((pageWidth / 3) - (labelImageHeight / 2)), labelImageWidth, labelImageHeight);
contentStream.drawImage(labelImage, ((2 * (pageHeight / 3)) - labelImageWidth - 5), ((4 * (pageWidth / 5)) - (labelImageHeight / 2)), labelImageWidth, labelImageHeight);
contentStream.drawImage(lamdaImage, (2 * (pageHeight / 3))+2, 25, lamdaImageWidth, lamdaImageHeight);
contentStream.drawImage(lamdaImage, (2 * (pageHeight / 3))+2, ((6 * pageWidth) / 10)+15, lamdaImageWidth, lamdaImageHeight);
contentStream.drawImage(labelImage, ((pageHeight) - labelImageWidth - 5), ((pageWidth / 3) - (labelImageHeight / 2)), labelImageWidth, labelImageHeight);
contentStream.drawImage(labelImage, ((pageHeight) - labelImageWidth - 5), ((4 * (pageWidth / 5)) - (labelImageHeight / 2)), labelImageWidth, labelImageHeight);
colorRectangle(getProductColor(product.color), contentStream, firstH, false);
colorRectangle(getProductColor(product.color), contentStream, secondH, false);
colorRectangle(getProductColor(product.color), contentStream, thirdH, false);
colorRectangle(getProductColor(product.color), contentStream, firstH, true);
colorRectangle(getProductColor(product.color), contentStream, secondH, true);
colorRectangle(getProductColor(product.color), contentStream, thirdH, true);
//text barvy
contentStream.beginText();
contentStream.setFont(font, 12);
//texty
contentStream.setNonStrokingColor(Color.BLACK);
writeTextMatrix(((pageHeight / 6) + 15), product, manufacturer.code, font, boldFont, contentStream);
writeTextMatrix(((pageHeight / 2) + 15), product, manufacturer.code, font, boldFont, contentStream);
writeTextMatrix(((5 * (pageHeight / 6)) + 15), product, manufacturer.code, font, boldFont, contentStream);
contentStream.endText();
//linka
contentStream.moveTo(0, (6 * pageWidth) / 10);
contentStream.lineTo(wholePageHeight, (6 * pageWidth) / 10);
contentStream.stroke();
contentStream.close();
} catch (IOException ex) {
System.out.println(ex);
}
try {
File file = new File("pdf/" + manufacturer.name + "/" + product.invNum + ".pdf");
file.getParentFile().mkdirs();
document.save(file);
} catch (FileNotFoundException ex) {
System.out.println("Nenalezena složka pro výstup!!!");
} catch (IOException ex) {
System.out.println("IO Exception - nelze uložit.");
}
try {
document.close();
} catch (IOException ex) {
System.out.println("Nelze uzavřít soubor.");
}
}
}
private void writeColorText(float y, String productColor, PDPageContentStream contentStream, PDType0Font font) throws IOException {
if (productColor.isEmpty()) {
productColor = "Black";
}
if (Color.BLACK == getProductColor(productColor)) {
contentStream.setNonStrokingColor(Color.WHITE);
} else {
contentStream.setNonStrokingColor(Color.BLACK);
}
// 12 = fontsize
float titleWidth = font.getStringWidth(productColor) / 1000 * 12;
int productColorLength = productColor.length();
int maxLength = 10;
if(productColorLength<=maxLength){
contentStream.newLineAtOffset(30 -(titleWidth/2), 113);
contentStream.showText(productColor);
contentStream.newLineAtOffset(341, 0);
contentStream.showText(productColor);
} else {
String [] splitColor = productColor.split("\\s+");
float smallFont = 10;
float titleWidth1 = font.getStringWidth(splitColor[0]) / 1000 * smallFont;
float titleWidth2 = font.getStringWidth(splitColor[1]) / 1000 * smallFont;
contentStream.setFont(font, smallFont);
contentStream.newLineAtOffset(30 -(titleWidth1/2), 120);
contentStream.showText(splitColor[0]);
contentStream.newLineAtOffset((titleWidth1/2)-(titleWidth2/2), -10);
contentStream.showText(splitColor[1]);
contentStream.newLineAtOffset((titleWidth2/2)-(titleWidth1/2)+340, 10);
contentStream.showText(splitColor[0]);
contentStream.newLineAtOffset((titleWidth1/2)-(titleWidth2/2), -10);
contentStream.showText(splitColor[1]);
}
}
private void writeTextMatrix(float y, Product product, String manufacturerCode, PDType0Font font, PDType0Font boldFont, PDPageContentStream contentStream) {
Matrix matrix = new Matrix(1, 0, 0, 1, y, 25);
matrix.rotate(Math.toRadians(90));
try {
contentStream.setNonStrokingColor(Color.BLACK);
contentStream.setTextMatrix(matrix);
contentStream.setFont(boldFont, 14);
contentStream.newLineAtOffset(0, 0);
substringProductName(product.name, 54, contentStream);
contentStream.newLineAtOffset(485, 0);
substringProductName(product.name, 35, contentStream);
contentStream.setFont(font, 14);
contentStream.newLineAtOffset(-485, -30);
contentStream.showText("Katalogové číslo: ");
contentStream.setFont(boldFont, 14);
contentStream.showText(product.invNum);
contentStream.setFont(font, 14);
contentStream.newLineAtOffset(485, 0);
contentStream.showText("Katalogové číslo: ");
contentStream.setFont(boldFont, 14);
contentStream.showText(product.invNum);
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(-485, -15);
contentStream.showText("Výrobce: Lamdaprint cz s.r.o.");
contentStream.newLineAtOffset(485, 0);
contentStream.showText("Výrobce: Lamdaprint cz s.r.o.");
contentStream.setFont(font, 14);
//Kapacita vpravo
contentStream.newLineAtOffset(205, 15);
contentStream.showText(product.capacity);
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(0, -15);
substringProductCode(product.productCode, 12, contentStream);
contentStream.newLineAtOffset(0, -15);
contentStream.showText(manufacturerCode);
contentStream.setFont(font, 14);
//Kapacita vlevo
capacityPosition(product.capacity, product.productCode, 11, contentStream);
contentStream.showText(product.capacity);
contentStream.setFont(font, 12);
contentStream.newLineAtOffset(0, -15);
contentStream.showText(product.productCode);
contentStream.newLineAtOffset(0, -15);
contentStream.showText(manufacturerCode);
contentStream.setNonStrokingColor(Color.BLACK);
if (capacityMove){
contentStream.newLineAtOffset(50, 0);
}
writeColorText(50, product.color, contentStream, font);
} catch (IOException ex) {
System.out.println("Nelze nakreslit textovou matici.");
System.out.println("Chyba: " + ex);
}
}
private void substringProductCode(String productCode, int maxLength, PDPageContentStream contentStream){
int length = productCode.length();
try {
if (maxLength>=length){
contentStream.showText(productCode);
} else{
String shortLine = productCode.substring(0, maxLength);
contentStream.showText(shortLine + "...");
}
} catch (IOException ex) {
System.out.println("Nelze napsat kód produktu.");
System.out.println("Chyba: " + ex);
}
}
private void substringProductName(String productName, int maxLength, PDPageContentStream contentStream){
int length = productName.length();
try {
if (maxLength>=length){
contentStream.showText(productName);
} else{
String firstLine = productName.substring(0, maxLength);
String secondLine = productName.substring(maxLength);
contentStream.showText(firstLine);
contentStream.newLineAtOffset(0, -15);
if (secondLine.length()<maxLength) {
contentStream.showText(secondLine);
} else {
String lastLine = secondLine.substring(0, maxLength-3);
contentStream.showText(lastLine + "...");
}
contentStream.newLineAtOffset(0, 15);
}
} catch (IOException ex) {
System.out.println("Nelze napsat název produktu.");
System.out.println("Chyba: " + ex);
}
}
private void capacityPosition (String capacity, String productCode, int maxLength, PDPageContentStream contentStream){
int capacityLength = capacity.length();
int productCodeLength = productCode.length();
try {
if (maxLength>=capacityLength && maxLength>=productCodeLength) {
contentStream.newLineAtOffset(-300, 30);
} else {
contentStream.newLineAtOffset(-350, 30);
capacityMove = true;
}
} catch (IOException ex) {
System.out.println("Nelze dát pozici kapacitě.");
System.out.println("Chyba: " + ex);
}
}
private void colorRectangle(Color color, PDPageContentStream contentStream, float pos, boolean right) throws IOException {
int xp = 410;
int xk = 480;
//final int yh = 40;
//final int yd = 70;
if (right) {
xp += 340;
xk += 340;
}
final float xpr1 = xp + (xk-xp)/3;
final float xpr2= xpr1 + + (xk-xp)/3;
if (color != Color.WHITE) {
contentStream.setNonStrokingColor(color);
contentStream.moveTo(pos + 40, xp+5);
contentStream.lineTo(pos + 40, xp+5);
contentStream.lineTo(pos + 40, xk - 10);
contentStream.curveTo(pos + 40, xk, pos + 40, xk, pos + 50, xk);
contentStream.lineTo(pos + 60, xk);
contentStream.curveTo(pos + 70, xk, pos + 70, xk, pos + 70, xk-10);
contentStream.lineTo(pos + 70, xp + 10);
contentStream.curveTo(pos + 70, xp, pos + 70, xp, pos + 60, xp);
contentStream.lineTo(pos + 50, xp);
contentStream.curveTo(pos + 40, xp, pos+40, xp, pos+40, xp+ 10);
contentStream.fill();
} else {
// levy kus
contentStream.setNonStrokingColor(Color.CYAN);
contentStream.moveTo(pos + 70, xpr1);
contentStream.lineTo(pos + 70, xpr1);
contentStream.lineTo(pos + 70, xp + 10);
contentStream.curveTo(pos + 70, xp, pos + 70, xp, pos + 60, xp);
contentStream.lineTo(pos + 50, xp);
contentStream.curveTo(pos + 40, xp, pos + 40, xp, pos + 40, xp + 10);
contentStream.lineTo(pos + 40, xpr1);
contentStream.fill();
//prostredek
contentStream.setNonStrokingColor(Color.MAGENTA);
contentStream.addRect(pos + 40, xpr1, 30, (xk - xp) / 3);
contentStream.fill();
//pravy kus
contentStream.setNonStrokingColor(Color.YELLOW);
contentStream.moveTo(pos + 40, xpr2);
contentStream.lineTo(pos + 40, xpr2);
contentStream.lineTo(pos + 40, xk - 10);
contentStream.curveTo(pos + 40, xk, pos + 40, xk, pos + 50, xk);
contentStream.lineTo(pos + 60, xk);
contentStream.curveTo(pos + 70, xk, pos + 70, xk, pos + 70, xk - 10);
contentStream.lineTo(pos + 70, xpr2 );
contentStream.fill();
}
contentStream.setNonStrokingColor(Color.BLACK);
}
@Deprecated
private static void paintRectangle(float pos, Color color, PDPageContentStream contentStream) {
try {
if (color != Color.WHITE) {
contentStream.setNonStrokingColor(color);
contentStream.addRect(0, 0, wholePageHeight, 30+margin);
contentStream.fill();
contentStream.addRect(0, wholePageWidth-30-margin, wholePageHeight, 30+margin);
contentStream.fill();
} else {
float part = pageHeight / 9;
contentStream.setNonStrokingColor(Color.CYAN);
contentStream.addRect(pos, 0, pageHeight / 3, 30+margin);
contentStream.addRect(pos, wholePageWidth-30-margin, pageHeight / 3, 30+margin);
contentStream.fill();
contentStream.setNonStrokingColor(Color.MAGENTA);
contentStream.addRect(pos + part, 0, pageHeight / 3, 30+margin);
contentStream.addRect(pos+part, wholePageWidth-30-margin, pageHeight/3, 30+margin);
contentStream.fill();
contentStream.setNonStrokingColor(Color.YELLOW);
contentStream.addRect(pos + (2 * part), 0, pageHeight / 3, 30+margin);
contentStream.addRect(pos+(2*part), wholePageWidth-30-margin, pageHeight/3, 30+margin);
contentStream.fill();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Deprecated
private static void paintColor(float pos, Color color, PDPageContentStream contentStream) {
try {
if (color != Color.WHITE) {
contentStream.setNonStrokingColor(color);
contentStream.addRect(lamdaImageHeight, lamdaImageWidth/2, 20, 50);
contentStream.fill();
contentStream.addRect((2*(pageWidth/3))+lamdaImageHeight, lamdaImageWidth/2, 20, 50);
contentStream.fill();
} else {
float part = pageHeight / 9;
contentStream.setNonStrokingColor(Color.CYAN);
contentStream.addRect(pos, 0, pageHeight / 3, 30+margin);
contentStream.addRect(pos, wholePageWidth-30-margin, pageHeight / 3, 30+margin);
contentStream.fill();
contentStream.setNonStrokingColor(Color.MAGENTA);
contentStream.addRect(pos + part, 0, pageHeight / 3, 30+margin);
contentStream.addRect(pos+part, wholePageWidth-30-margin, pageHeight/3, 30+margin);
contentStream.fill();
contentStream.setNonStrokingColor(Color.YELLOW);
contentStream.addRect(pos + (2 * part), 0, pageHeight / 3, 30+margin);
contentStream.addRect(pos+(2*part), wholePageWidth-30-margin, pageHeight/3, 30+margin);
contentStream.fill();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static Color getProductColor(String color){
Color currentColor;
switch (color){
case "Black" : currentColor = Color.BLACK;
break;
case "Yellow" : currentColor = Color.YELLOW;
break;
case "Cyan" : currentColor = Color.CYAN;
break;
case "Magenta" : currentColor = Color.MAGENTA;
break;
case "Black/Rot" : currentColor = Color.BLACK;
break;
case "CMYK" : currentColor = Color.WHITE;
break;
case "Color" : currentColor = Color.WHITE;
break;
case "Grey" : currentColor = Color.GRAY;
break;
case "Light Cyan" : currentColor = Color.CYAN.brighter();
break;
case "Light Magenta" : currentColor = Color.MAGENTA.brighter();
break;
case "Matte black" : currentColor = Color.BLACK;
break;
case "Photo" : currentColor = Color.WHITE;
break;
case "Photo Black" : currentColor = Color.BLACK;
break;
case "Photo Cyan" : currentColor = Color.CYAN;
break;
case "Photo Magenta" : currentColor = Color.MAGENTA;
break;
case "Red/Black" : currentColor = Color.RED;
break;
case "Violett" : currentColor = Color.magenta.darker();
break;
default : currentColor = Color.BLACK;
break;
}
return currentColor;
}
private static Color switchColor(String currentColor){
if (currentColor.equals("Black")) {
return Color.WHITE;
} else {
return Color.BLACK;
}
}
} |
package org.unipept.xml;
import java.util.Arrays;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* @author Bart Mesuere
*
*/
public class UniprotEntry {
// peptide settings
private static final int MIN_PEPT_SIZE = 5;
private static final int MAX_PEPT_SIZE = 50;
private String uniprotAccessionNumber;
private int version;
private int taxonId;
private String type;
private String recommendedName;
private String submittedName;
private String sequence;
private List<UniprotDbRef> dbReferences;
private List<UniprotGORef> goReferences;
private List<UniprotECRef> ecReferences;
private List<UniprotProteomeRef> protReferences;
private List<String> sequences;
public UniprotEntry(String type) {
this.type = type;
dbReferences = new ArrayList<UniprotDbRef>();
goReferences = new ArrayList<UniprotGORef>();
ecReferences = new ArrayList<UniprotECRef>();
protReferences = new ArrayList<UniprotProteomeRef>();
sequences = new ArrayList<String>();
}
public void reset(String type) {
uniprotAccessionNumber = null;
version = 0;
taxonId = 0;
this.type = type;
recommendedName = null;
submittedName = null;
sequence = null;
dbReferences.clear();
goReferences.clear();
ecReferences.clear();
protReferences.clear();
sequences.clear();
}
public String getUniprotAccessionNumber() {
return uniprotAccessionNumber;
}
public void setUniprotAccessionNumber(String uniprotAccessionNumber) {
if(this.uniprotAccessionNumber == null) {
this.uniprotAccessionNumber = uniprotAccessionNumber;
}
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public int getTaxonId() {
return taxonId;
}
public void setTaxonId(int taxonId) {
this.taxonId = taxonId;
}
public String getType() {
return type;
}
public String getName() {
if(recommendedName != null) return recommendedName;
return submittedName;
}
public void setRecommendedName(String name) {
recommendedName = name;
}
public void setSubmittedName(String name) {
submittedName = name;
}
public String getSequence() {
return sequence;
}
public void setSequence(String sequence) {
this.sequence = sequence;
}
public void addDbRef(UniprotDbRef ref) {
dbReferences.add(ref);
}
public void addGORef(UniprotGORef ref) {
goReferences.add(ref);
}
public void addECRef(UniprotECRef ref) {
ecReferences.add(ref);
}
public void addProtRef(UniprotProteomeRef ref) {
for (UniprotProteomeRef r : protReferences) {
if (ref.equals(r)) {
return;
}
}
protReferences.add(ref);
}
public List<String> digest() {
sequences.clear();
int start = 0;
int length = sequence.length();
for (int i = 0; i < length; i++) {
char x = sequence.charAt(i);
if ((x == 'K' || x == 'R') && (i + 1 < length && sequence.charAt(i + 1) != 'P')) {
if (i + 1 - start >= MIN_PEPT_SIZE && i + 1 - start <= MAX_PEPT_SIZE) {
sequences.add(sequence.substring(start, i + 1));
}
start = i + 1;
}
}
if (length - start >= MIN_PEPT_SIZE && length - start <= MAX_PEPT_SIZE) {
sequences.add(sequence.substring(start, length));
}
return sequences;
}
public List<UniprotDbRef> getDbReferences() {
return dbReferences;
}
public List<UniprotGORef> getGOReferences() {
return goReferences;
}
public List<UniprotECRef> getECReferences() {
return ecReferences;
}
public List<UniprotProteomeRef> getProtReferences() {
return protReferences;
}
@Override
public String toString() {
return uniprotAccessionNumber + ", " + version + ", " + taxonId + ", " + type + ", "
+ sequence;
}
} |
package io.moquette.testclient;
import io.moquette.BrokerConstants;
import io.moquette.server.netty.MessageBuilder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.mqtt.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* Class used just to send and receive MQTT messages without any protocol login in action, just use
* the encoder/decoder part.
*
* @author andrea
*/
public class Client {
public interface ICallback {
void call(MqttMessage msg);
}
private static final Logger LOG = LoggerFactory.getLogger(Client.class);
final ClientNettyMQTTHandler handler = new ClientNettyMQTTHandler();
EventLoopGroup workerGroup;
Channel m_channel;
private boolean m_connectionLost = false;
private ICallback callback;
private String clientId;
private MqttMessage receivedMsg;
public Client(String host) {
this(host, BrokerConstants.PORT);
}
public Client(String host, int port) {
handler.setClient(this);
workerGroup = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(workerGroup);
b.channel(NioSocketChannel.class);
b.option(ChannelOption.SO_KEEPALIVE, true);
b.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("decoder", new MqttDecoder());
pipeline.addLast("encoder", MqttEncoder.INSTANCE);
pipeline.addLast("handler", handler);
}
});
// Start the client.
m_channel = b.connect(host, port).sync().channel();
} catch (Exception ex) {
LOG.error("Error received in client setup", ex);
workerGroup.shutdownGracefully();
}
}
public Client clientId(String clientId) {
this.clientId = clientId;
return this;
}
public void connect(String willTestamentTopic, String willTestamentMsg) {
MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(
MqttMessageType.CONNECT,
false,
MqttQoS.AT_MOST_ONCE,
false,
0);
MqttConnectVariableHeader mqttConnectVariableHeader = new MqttConnectVariableHeader(
MqttVersion.MQTT_3_1.protocolName(),
MqttVersion.MQTT_3_1.protocolLevel(),
false,
false,
false,
MqttQoS.AT_MOST_ONCE.value(),
true,
true,
2);
MqttConnectPayload mqttConnectPayload = new MqttConnectPayload(
this.clientId,
willTestamentTopic,
willTestamentMsg,
null,
null);
MqttConnectMessage connectMessage = new MqttConnectMessage(
mqttFixedHeader,
mqttConnectVariableHeader,
mqttConnectPayload);
/*
* ConnectMessage connectMessage = new ConnectMessage();
* connectMessage.setProtocolVersion((byte) 3); connectMessage.setClientID(this.clientId);
* connectMessage.setKeepAlive(2); //secs connectMessage.setWillFlag(true);
* connectMessage.setWillMessage(willTestamentMsg.getBytes());
* connectMessage.setWillTopic(willTestamentTopic);
* connectMessage.setWillQos(MqttQoS.AT_MOST_ONCE.byteValue());
*/
doConnect(connectMessage);
}
public void connect() {
MqttConnectMessage connectMessage = MessageBuilder.connect().protocolVersion(MqttVersion.MQTT_3_1_1)
.clientId("").keepAlive(2) // secs
.willFlag(false).willQoS(MqttQoS.AT_MOST_ONCE).build();
doConnect(connectMessage);
}
private void doConnect(MqttConnectMessage connectMessage) {
final CountDownLatch latch = new CountDownLatch(1);
this.setCallback(new Client.ICallback() {
public void call(MqttMessage msg) {
receivedMsg = msg;
latch.countDown();
}
});
this.sendMessage(connectMessage);
try {
latch.await(200, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
throw new RuntimeException("Cannot receive message in 200 ms", e);
}
if (!(this.receivedMsg instanceof MqttConnAckMessage)) {
MqttMessageType messageType = this.receivedMsg.fixedHeader().messageType();
throw new RuntimeException("Expected a CONN_ACK message but received " + messageType);
}
}
public void setCallback(ICallback callback) {
this.callback = callback;
}
public void sendMessage(MqttMessage msg) {
m_channel.writeAndFlush(msg);
}
public MqttMessage lastReceivedMessage() {
return this.receivedMsg;
}
void messageReceived(MqttMessage msg) {
LOG.info("Received message {}", msg);
if (this.callback != null) {
this.callback.call(msg);
}
}
void setConnectionLost(boolean status) {
m_connectionLost = status;
}
public boolean isConnectionLost() {
return m_connectionLost;
}
public void close() throws InterruptedException {
// Wait until the connection is closed.
m_channel.closeFuture().sync();
if (workerGroup == null) {
throw new IllegalStateException("Invoked close on an Acceptor that wasn't initialized");
}
workerGroup.shutdownGracefully();
}
} |
package org.royaldev.royalcommands.rcommands;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.royaldev.royalcommands.RUtils;
import org.royaldev.royalcommands.RoyalCommands;
public class CmdPing implements CommandExecutor {
RoyalCommands plugin;
public CmdPing(RoyalCommands instance) {
this.plugin = instance;
}
@Override
public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("ping")) {
if (!plugin.isAuthorized(cs, "rcmds.ping")) {
RUtils.dispNoPerms(cs);
return true;
}
if (!(cs instanceof Player) && args.length < 1) {
cs.sendMessage("Pong!");
return true;
}
if (args.length > 0) {
if (!plugin.isAuthorized(cs, "rcmds.others.ping")) {
RUtils.dispNoPerms(cs);
return true;
}
Player p = plugin.getServer().getPlayer(args[0]);
if (p == null || plugin.isVanished(p, cs)) {
cs.sendMessage(ChatColor.RED + "That player does not exist!");
return true;
}
int ping = ((CraftPlayer) p).getHandle().ping;
String possessive = (p.getName().endsWith("s")) ? "'" : "'s";
p.sendMessage(ChatColor.GRAY + p.getName() + possessive + ChatColor.BLUE + " ping: " + ChatColor.GRAY + ping + "ms");
return true;
}
Player p = (Player) cs;
int ping = ((CraftPlayer) p).getHandle().ping;
p.sendMessage(ChatColor.BLUE + "Your ping: " + ChatColor.GRAY + ping + "ms");
return true;
}
return false;
}
} |
package org.royaldev.royalcommands.rcommands;
import org.apache.commons.lang.ArrayUtils;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.royaldev.royalcommands.RUtils;
import org.royaldev.royalcommands.RoyalCommands;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
public class CmdTime implements CommandExecutor {
static RoyalCommands plugin;
public CmdTime(RoyalCommands instance) {
plugin = instance;
}
public static void smoothTimeChange(long time, final World world) {
if (time > 24000) time = time % 24000L;
final long ftime = time;
final Runnable r = new Runnable() {
@Override
public void run() {
for (long i = world.getTime() + 1; i != ftime; i++) {
if (i == 24001) {
i = 0;
if (ftime == 0) break;
}
world.setTime(i);
}
world.setTime(ftime);
}
};
plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, r);
}
public static Long getValidTime(String time) {
Long vtime;
try {
vtime = Long.valueOf(time);
if (vtime > 24000L) vtime = vtime % 24000L;
} catch (Exception e) {
if (time.equalsIgnoreCase("day")) vtime = 0L;
else if (time.equalsIgnoreCase("midday") || time.equalsIgnoreCase("noon"))
vtime = 6000L;
else if (time.equalsIgnoreCase("sunset") || time.equalsIgnoreCase("sundown") || time.equalsIgnoreCase("dusk"))
vtime = 12000L;
else if (time.equalsIgnoreCase("night") || time.equalsIgnoreCase("dark"))
vtime = 14000L;
else if (time.equalsIgnoreCase("midnight")) vtime = 18000L;
else if (time.equalsIgnoreCase("sunrise") || time.equalsIgnoreCase("sunup") || time.equalsIgnoreCase("dawn"))
vtime = 23000L;
else return null;
}
return vtime;
}
public static Map<String, String> getRealTime(long ticks) {
if (ticks > 24000L) ticks = ticks % 24000L;
DecimalFormat df = new DecimalFormat("00");
df.setRoundingMode(RoundingMode.DOWN);
float thour = 1000F;
float tminute = 16.6666666666666666666666666666666666666666666666666666666666666666666666F;
float hour = (ticks / thour) + 6F;
if (hour >= 24F) hour = hour - 24F;
float minute = (ticks % thour) / tminute;
String meridian = (hour >= 12F) ? "PM" : "AM";
float twelvehour = (hour > 12F) ? hour - 12F : hour;
if (df.format(twelvehour).equals("00")) twelvehour = 12F;
Map<String, String> toRet = new HashMap<String, String>();
toRet.put("24h", df.format(hour) + ":" + df.format(minute));
toRet.put("12h", df.format(twelvehour) + ":" + df.format(minute) + " " + meridian);
return toRet;
}
@Override
public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("time")) {
if (!plugin.isAuthorized(cs, "rcmds.time")) {
RUtils.dispNoPerms(cs);
return true;
}
if (args.length < 1) {
if (!(cs instanceof Player))
for (World w : plugin.getServer().getWorlds()) {
String name = RUtils.getMVWorldName(w);
long ticks = w.getTime();
Map<String, String> times = getRealTime(ticks);
cs.sendMessage(ChatColor.BLUE + "The current time in " + ChatColor.GRAY + name + ChatColor.BLUE + " is " + ChatColor.GRAY + ticks + " ticks" + ChatColor.BLUE + " (" + ChatColor.GRAY + times.get("24h") + ChatColor.BLUE + "/" + ChatColor.GRAY + times.get("12h") + ChatColor.BLUE + ").");
}
else {
Player p = (Player) cs;
World w = p.getWorld();
long ticks = w.getTime();
Map<String, String> times = getRealTime(ticks);
cs.sendMessage(ChatColor.BLUE + "The current time in " + ChatColor.GRAY + RUtils.getMVWorldName(w) + ChatColor.BLUE + " is " + ChatColor.GRAY + ticks + " ticks" + ChatColor.BLUE + " (" + ChatColor.GRAY + times.get("24h") + ChatColor.BLUE + "/" + ChatColor.GRAY + times.get("12h") + ChatColor.BLUE + ").");
}
return true;
}
if (args.length > 0 && args[0].equals("?") || args[0].equalsIgnoreCase("help")) {
cs.sendMessage(cmd.getDescription());
return false;
}
if (args.length > 0 && args[0].equalsIgnoreCase("set"))
ArrayUtils.removeElement(args, "set");
String target = "";
if (!(cs instanceof Player) && args.length < 2) target = "*";
else if ((cs instanceof Player) && args.length < 2)
target = ((Player) cs).getWorld().getName();
if (args.length > 1) target = args[1];
if (target.equalsIgnoreCase("all")) target = "*";
if (RUtils.getWorld(target) == null && !target.equals("*")) {
cs.sendMessage(ChatColor.RED + "No such world!");
return true;
}
World w = (!target.equals("*")) ? RUtils.getWorld(target) : null;
Long ticks = getValidTime(args[0]);
if (ticks == null) {
if (RUtils.getWorld(args[0]) != null) {
w = RUtils.getWorld(args[0]);
ticks = w.getTime();
Map<String, String> times = getRealTime(ticks);
cs.sendMessage(ChatColor.BLUE + "The current time in " + ChatColor.GRAY + RUtils.getMVWorldName(w) + ChatColor.BLUE + " is " + ChatColor.GRAY + ticks + " ticks" + ChatColor.BLUE + " (" + ChatColor.GRAY + times.get("24h") + ChatColor.BLUE + "/" + ChatColor.GRAY + times.get("12h") + ChatColor.BLUE + ").");
return true;
}
cs.sendMessage(ChatColor.RED + "Invalid time specified!");
return true;
}
Map<String, String> times = getRealTime(ticks);
if (w == null) {
for (World ws : plugin.getServer().getWorlds()) {
if (plugin.smoothTime) smoothTimeChange(ticks, ws);
else ws.setTime(ticks);
}
cs.sendMessage(ChatColor.BLUE + "Set time in all worlds to " + ChatColor.GRAY + ticks + " ticks" + ChatColor.BLUE + " (" + ChatColor.GRAY + times.get("24h") + ChatColor.BLUE + "/" + ChatColor.GRAY + times.get("12h") + ChatColor.BLUE + ").");
} else {
if (plugin.smoothTime) smoothTimeChange(ticks, w);
else w.setTime(ticks);
cs.sendMessage(ChatColor.BLUE + "Set time in " + ChatColor.GRAY + RUtils.getMVWorldName(w) + ChatColor.BLUE + " to " + ChatColor.GRAY + ticks + " ticks" + ChatColor.BLUE + " (" + ChatColor.GRAY + times.get("24h") + ChatColor.BLUE + "/" + ChatColor.GRAY + times.get("12h") + ChatColor.BLUE + ").");
}
return true;
}
return false;
}
} |
package etomica.models.nitrogen;
import java.io.Serializable;
import etomica.action.IAction;
import etomica.api.IBox;
import etomica.api.IMoleculeList;
import etomica.api.ISpecies;
import etomica.data.DataTag;
import etomica.data.IData;
import etomica.data.IEtomicaDataInfo;
import etomica.data.IEtomicaDataSource;
import etomica.data.types.DataDoubleArray;
import etomica.data.types.DataGroup;
import etomica.data.types.DataDoubleArray.DataInfoDoubleArray;
import etomica.data.types.DataGroup.DataInfoGroup;
import etomica.normalmode.CoordinateDefinition;
import etomica.normalmode.CoordinateDefinition.BasisCell;
import etomica.units.CompoundDimension;
import etomica.units.Dimension;
import etomica.units.Length;
import etomica.units.Null;
import etomica.util.HistogramExpanding;
/**
* Sample the distribution of the normalized coordinate for the atoms/ molecules
* from coordinate definition, calcU method. They are the quantities of deviation
* in translation and rotation from the atomic/molecular nominal position and
* orientation
*
* Eg. N2 molecule with 5 D.O.F, this class will return 5 distributions of
* 3 translation and 2 rotation motion respectively.
*/
public class MeterNormalizedCoord implements IEtomicaDataSource, IAction, Serializable {
public MeterNormalizedCoord(IBox newBox, CoordinateDefinition coordDef, ISpecies species, boolean isVolFluctuation) {
tag = new DataTag();
this.coordinateDefinition = coordDef;
this.isVolFluctuation = isVolFluctuation;
if (species==null){
throw new RuntimeException("Need to set species in MeterNormalizedCoord class");
}
if(isVolFluctuation){
dof = (coordDef.getCoordinateDim()- 3) /newBox.getNMolecules(species) +3;
} else {
dof = coordDef.getCoordinateDim() /newBox.getNMolecules(species);
}
uDistributions = new DataDoubleArray[dof];
uDistributionsInfo = new DataInfoDoubleArray[dof];
histogramU = new HistogramExpanding[dof];
for (int i=0; i<dof; i++){
histogramU[i] = new HistogramExpanding(0.005);
}
}
public IEtomicaDataInfo getDataInfo() {
return dataInfo;
}
/**
* Assigning the histogram to data
*/
public void actionPerformed() {
BasisCell[] cells = coordinateDefinition.getBasisCells();
for (int iCell = 0; iCell<cells.length; iCell++) {
BasisCell cell = cells[iCell];
IMoleculeList molecules = cell.molecules;
int numMolecules = molecules.getMoleculeCount();
double[] u = coordinateDefinition.calcU(molecules);
if(isVolFluctuation){
for (int i=0; i<(dof-3); i++){
for (int j=0; j<numMolecules; j++){
histogramU[i].addValue(u[i+(dof-3)*j]);
}
}
for (int i=0; i<3; i++){
histogramU[(dof-3)+i].addValue(u[(coordinateDefinition.getCoordinateDim()-(3-i))]);
}
} else {
for (int i=0; i<dof; i++){
for (int j=0; j<numMolecules; j++){
histogramU[i].addValue(u[i+dof*j]);
}
}
}
} //end of cell; there is only 1 cell
}
/**
* Returns the DataGroup of uDistribtion[i]
*/
public IData getData() {
CompoundDimension length = new CompoundDimension(new Dimension[]{Length.DIMENSION}, new double[]{1});
for(int i=0; i<dof; i++){
int nBin = histogramU[i].getNBins();
uDistributions[i] = new DataDoubleArray(new int[] {2, nBin});
uDistributionsInfo[i] = new DataInfoDoubleArray("u", length, new int[]{2, nBin});
uDistributions[i].assignColumnFrom(0, histogramU[i].xValues());
uDistributions[i].assignColumnFrom(1, histogramU[i].getHistogram());
}
data = new DataGroup(uDistributions);
dataInfo = new DataInfoGroup("all uDistributions", Null.DIMENSION, uDistributionsInfo);
return data;
}
/**
* Sets the tensor summation to 0.
*/
public void reset() {
data.E(0);
}
public DataTag getTag() {
return tag;
}
private static final long serialVersionUID = 1L;
protected CoordinateDefinition coordinateDefinition;
private String name;
private final DataTag tag;
private IEtomicaDataInfo dataInfo;
private DataGroup data;
private HistogramExpanding[] histogramU;
private DataDoubleArray[] uDistributions;
private DataInfoDoubleArray[] uDistributionsInfo;
private int dof;
private boolean isVolFluctuation;
} |
package carpentersblocks.renderer.helper;
import net.minecraft.block.Block;
import net.minecraft.block.BlockFluid;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraftforge.common.ForgeDirection;
import net.minecraftforge.fluids.IFluidBlock;
import carpentersblocks.tileentity.TEBase;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class FancyFluidsHelper {
/**
* Renders fancy fluids in block space.
*/
public static boolean render(TEBase TE, LightingHelper lightingHelper, RenderBlocks renderBlocks, int x, int y, int z, int renderPass)
{
Block block_XN = !renderBlocks.blockAccess.isAirBlock(x - 1, y, z) ? Block.blocksList[renderBlocks.blockAccess.getBlockId(x - 1, y, z)] : null;
Block block_XP = !renderBlocks.blockAccess.isAirBlock(x + 1, y, z) ? Block.blocksList[renderBlocks.blockAccess.getBlockId(x + 1, y, z)] : null;
Block block_ZN = !renderBlocks.blockAccess.isAirBlock(x, y, z - 1) ? Block.blocksList[renderBlocks.blockAccess.getBlockId(x, y, z - 1)] : null;
Block block_ZP = !renderBlocks.blockAccess.isAirBlock(x, y, z + 1) ? Block.blocksList[renderBlocks.blockAccess.getBlockId(x, y, z + 1)] : null;
Block block_XZNP = !renderBlocks.blockAccess.isAirBlock(x - 1, y, z + 1) ? Block.blocksList[renderBlocks.blockAccess.getBlockId(x - 1, y, z + 1)] : null;
Block block_XZPP = !renderBlocks.blockAccess.isAirBlock(x + 1, y, z + 1) ? Block.blocksList[renderBlocks.blockAccess.getBlockId(x + 1, y, z + 1)] : null;
Block block_XZNN = !renderBlocks.blockAccess.isAirBlock(x - 1, y, z - 1) ? Block.blocksList[renderBlocks.blockAccess.getBlockId(x - 1, y, z - 1)] : null;
Block block_XZPN = !renderBlocks.blockAccess.isAirBlock(x + 1, y, z - 1) ? Block.blocksList[renderBlocks.blockAccess.getBlockId(x + 1, y, z - 1)] : null;
boolean isFluid_XN = block_XN != null ? block_XN instanceof BlockFluid || block_XN instanceof IFluidBlock : false;
boolean isFluid_XP = block_XP != null ? block_XP instanceof BlockFluid || block_XP instanceof IFluidBlock : false;
boolean isFluid_ZN = block_ZN != null ? block_ZN instanceof BlockFluid || block_ZN instanceof IFluidBlock : false;
boolean isFluid_ZP = block_ZP != null ? block_ZP instanceof BlockFluid || block_ZP instanceof IFluidBlock : false;
boolean isFluid_XZNP = block_XZNP != null ? block_XZNP instanceof BlockFluid || block_XZNP instanceof IFluidBlock : false;
boolean isFluid_XZPP = block_XZPP != null ? block_XZPP instanceof BlockFluid || block_XZPP instanceof IFluidBlock : false;
boolean isFluid_XZNN = block_XZNN != null ? block_XZNN instanceof BlockFluid || block_XZNN instanceof IFluidBlock : false;
boolean isFluid_XZPN = block_XZPN != null ? block_XZPN instanceof BlockFluid || block_XZPN instanceof IFluidBlock : false;
boolean isSolid_XN = renderBlocks.blockAccess.isBlockSolidOnSide(x, y, z, ForgeDirection.WEST, true);
boolean isSolid_XP = renderBlocks.blockAccess.isBlockSolidOnSide(x, y, z, ForgeDirection.EAST, true);
boolean isSolid_ZN = renderBlocks.blockAccess.isBlockSolidOnSide(x, y, z, ForgeDirection.NORTH, true);
boolean isSolid_ZP = renderBlocks.blockAccess.isBlockSolidOnSide(x, y, z, ForgeDirection.SOUTH, true);
int metadata = 0;
int diagMetadata = 0;
Block fluidBlock = null;
Block diagFluidBlock = null;
for (int count = 2; count < 10 && fluidBlock == null; ++count)
{
switch (count) {
case 2:
if (isFluid_ZN && !isSolid_ZN) {
fluidBlock = Block.blocksList[renderBlocks.blockAccess.getBlockId(x, y, z - 1)];
if (metadata < renderBlocks.blockAccess.getBlockMetadata(x, y, z - 1)) {
metadata = renderBlocks.blockAccess.getBlockMetadata(x, y, z - 1);
}
}
break;
case 3:
if (isFluid_ZP && !isSolid_ZP) {
fluidBlock = Block.blocksList[renderBlocks.blockAccess.getBlockId(x, y, z + 1)];
if (metadata < renderBlocks.blockAccess.getBlockMetadata(x, y, z + 1)) {
metadata = renderBlocks.blockAccess.getBlockMetadata(x, y, z + 1);
}
}
break;
case 4:
if (isFluid_XN && !isSolid_XN) {
fluidBlock = Block.blocksList[renderBlocks.blockAccess.getBlockId(x - 1, y, z)];
if (metadata < renderBlocks.blockAccess.getBlockMetadata(x - 1, y, z)) {
metadata = renderBlocks.blockAccess.getBlockMetadata(x - 1, y, z);
}
}
break;
case 5:
if (isFluid_XP && !isSolid_XP) {
fluidBlock = Block.blocksList[renderBlocks.blockAccess.getBlockId(x + 1, y, z)];
if (metadata < renderBlocks.blockAccess.getBlockMetadata(x + 1, y, z)) {
metadata = renderBlocks.blockAccess.getBlockMetadata(x + 1, y, z);
}
}
break;
case 6:
if (isFluid_XZPN) {
diagFluidBlock = Block.blocksList[renderBlocks.blockAccess.getBlockId(x + 1, y, z - 1)];
if (diagMetadata < renderBlocks.blockAccess.getBlockMetadata(x + 1, y, z - 1)) {
diagMetadata = renderBlocks.blockAccess.getBlockMetadata(x + 1, y, z - 1);
}
}
break;
case 7:
if (isFluid_XZPP) {
diagFluidBlock = Block.blocksList[renderBlocks.blockAccess.getBlockId(x + 1, y, z + 1)];
if (diagMetadata < renderBlocks.blockAccess.getBlockMetadata(x + 1, y, z + 1)) {
diagMetadata = renderBlocks.blockAccess.getBlockMetadata(x + 1, y, z + 1);
}
}
break;
case 8:
if (isFluid_XZNN) {
diagFluidBlock = Block.blocksList[renderBlocks.blockAccess.getBlockId(x - 1, y, z - 1)];
if (diagMetadata < renderBlocks.blockAccess.getBlockMetadata(x - 1, y, z - 1)) {
diagMetadata = renderBlocks.blockAccess.getBlockMetadata(x - 1, y, z - 1);
}
}
break;
case 9:
if (isFluid_XZNP) {
diagFluidBlock = Block.blocksList[renderBlocks.blockAccess.getBlockId(x - 1, y, z + 1)];
if (diagMetadata < renderBlocks.blockAccess.getBlockMetadata(x - 1, y, z + 1)) {
diagMetadata = renderBlocks.blockAccess.getBlockMetadata(x - 1, y, z + 1);
}
}
break;
}
}
if (fluidBlock != null && renderPass == fluidBlock.getRenderBlockPass() || diagFluidBlock != null && renderPass == diagFluidBlock.getRenderBlockPass())
{
boolean renderFluid = false;
float minX = 0;
float minZ = 0;
float maxX = 1.0F;
float maxZ = 1.0F;
float offset = 0.01F;
for (int side = 2; side < 6; ++side)
{
switch (side)
{
case 2:
if (
!isSolid_ZP &&
isFluid_ZP || !renderBlocks.blockAccess.isBlockSolidOnSide(x, y, z + 1, ForgeDirection.NORTH, true) &&
(isFluid_XZNP && !renderBlocks.blockAccess.isBlockSolidOnSide(x, y, z + 1, ForgeDirection.WEST, true) || isFluid_XZPP && !renderBlocks.blockAccess.isBlockSolidOnSide(x, y, z + 1, ForgeDirection.EAST, true))
) {
renderFluid = true;
}
break;
case 3:
if (
!isSolid_ZN &&
isFluid_ZN || !renderBlocks.blockAccess.isBlockSolidOnSide(x, y, z - 1, ForgeDirection.SOUTH, true) &&
(isFluid_XZNN && !renderBlocks.blockAccess.isBlockSolidOnSide(x, y, z - 1, ForgeDirection.WEST, true) || isFluid_XZPN && !renderBlocks.blockAccess.isBlockSolidOnSide(x, y, z - 1, ForgeDirection.EAST, true))
) {
renderFluid = true;
}
break;
case 4:
if (
!isSolid_XP &&
isFluid_XP || !renderBlocks.blockAccess.isBlockSolidOnSide(x + 1, y, z, ForgeDirection.WEST, true) &&
(isFluid_XZPP && !renderBlocks.blockAccess.isBlockSolidOnSide(x + 1, y, z, ForgeDirection.SOUTH, true) || isFluid_XZPN && !renderBlocks.blockAccess.isBlockSolidOnSide(x + 1, y, z, ForgeDirection.NORTH, true))
) {
renderFluid = true;
}
break;
case 5:
if (
!isSolid_XN &&
isFluid_XN || !renderBlocks.blockAccess.isBlockSolidOnSide(x - 1, y, z, ForgeDirection.EAST, true) &&
(isFluid_XZNP && !renderBlocks.blockAccess.isBlockSolidOnSide(x - 1, y, z, ForgeDirection.SOUTH, true) || isFluid_XZNN && !renderBlocks.blockAccess.isBlockSolidOnSide(x - 1, y, z, ForgeDirection.NORTH, true))
) {
renderFluid = true;
}
break;
}
}
if (renderFluid)
{
if (isSolid_XN) {
minX += offset;
}
if (isSolid_XP) {
maxX -= offset;
}
if (isSolid_ZP) {
maxZ -= offset;
}
if (isSolid_ZN) {
minZ += offset;
}
if (fluidBlock == null)
{
fluidBlock = diagFluidBlock;
metadata = diagMetadata;
}
if (!fluidBlock.hasTileEntity(metadata) && metadata == 0)
{
double fluidHeight = (fluidBlock instanceof BlockFluid ? 1.0D - 1.0F / 9.0F : 0.875F) - 0.0010000000474974513D;
renderBlocks.setRenderBounds(minX, offset, minZ, maxX, fluidHeight, maxZ);
float rgb[] = lightingHelper.getBlockRGB(fluidBlock, x, y, z);
renderBlocks.renderStandardBlockWithColorMultiplier(fluidBlock, x, y, z, rgb[0], rgb[1], rgb[2]);
return true;
}
}
}
return false;
}
} |
package control;
import boundary.GUIBoundary;
import entity.DiceCup;
import entity.GameBoard;
import entity.Player;
import entity.PlayerList;
import entity.fields.Field;
import entity.language.LanguageHandler;
public class GameController {
private GUIBoundary boundary;
private SetupController setupController;
private GameBoard gameBoard;
private LanguageHandler language;
private PlayerList playerList;
private DiceCup diceCup;
public GameController() {
setupController = new SetupController();
gameBoard = setupController.setupGameBoard();
language = setupController.chooseLanguage();
playerList = setupController.setupPlayers();
boundary = setupController.getBoundary();
diceCup = new DiceCup();
}
/**
* Method to start playing the game
*/
public void runGame() {
if(boundary.getButtonPressed(language.readyToBegin()));
while(!playerList.isThereAWinner()) {
for(int i = 0; i < playerList.getPlayers().length; i++)
if(!playerList.isThereAWinner() && !playerList.isPlayerBroke(i))
playTurn(playerList.getPlayer(i));
}
boundary.getButtonPressed(language.winnerMsg(playerList.whoIsTheWinner()));
}
/**
* Method that receives a player object and posts a message with instructions for the player.
* After the player has pressed "enter" the method will roll the dices, print the result of the roll,
* enforce the landOnField method for the given field and do a win condition check. The method keeps
* running that sequence until the player has no more extra turns or has won the game. If the players
* turn ends and he hasn't won, the method will print a message with the players current score,
* if the player has won, the method will post a message saying that.
* @param player Player
*/
public void playTurn(Player player) {
boundary.getButtonPressed(language.preMsg(player));
diceCup.rollDices();
boundary.setDices(diceCup);
boundary.removeCar(player.getOnField(), player.getName());
player.setLastRoll(diceCup.getSum());
player.movePlayer(diceCup.getSum());
int fieldNumber = player.getOnField();
Field field = gameBoard.getField(fieldNumber);
boundary.setCar(fieldNumber, player.getName());
boundary.getButtonPressed(language.fieldMsg(fieldNumber));
if(field.isOwnable())
{
Player ownerOfField = field.getOwner();
if(ownerOfField == null)
{
int priceOfField = field.getPrice();
if(boundary.getBoolean(language.buyingOfferMsg(priceOfField), language.yes(), language.no()))
{
if(player.getBankAccount().getBalance() > priceOfField)
{
field.buyField(player);
boundary.updateBalance(player.getName(), player.getBankAccount().getBalance());
boundary.setOwner(fieldNumber, player.getName());
boundary.getButtonPressed(language.purchaseConfirmation());
} else
{
boundary.getButtonPressed(language.notEnoughMoney());
}
}
} else
{
if(!field.getOwner().getName().equals(player.getName()))
{
boundary.getButtonPressed(language.landedOnOwnedField(ownerOfField));
int preBalance = player.getBankAccount().getBalance();
field.landOnField(player);
boundary.updateBalance(player.getName(), player.getBankAccount().getBalance());
boundary.updateBalance(ownerOfField.getName(), ownerOfField.getBankAccount().getBalance());
int amountPayed = preBalance - player.getBankAccount().getBalance();
boundary.getButtonPressed(language.youPaidThisMuchToThisPerson(amountPayed, ownerOfField));
} else
{
boundary.getButtonPressed(language.youOwnThisField());
}
}
} else
{
if(fieldNumber == 18)
player.setTaxChoice(boundary.getBoolean(language.getTaxChoice(), language.yes(), language.no()));
else boundary.getButtonPressed(language.nonOwnableFieldEffectMsg(fieldNumber));
field.landOnField(player);
boundary.updateBalance(player.getName(), player.getBankAccount().getBalance());
}
if (player.getBankAccount().getBalance() <= 0)
{
boundary.getButtonPressed(language.youAreBroke());
boundary.removeCar(fieldNumber, player.getName());
boundary.releasePlayersFields(gameBoard, player);
gameBoard.releasePlayersFields(player);
}
}
/**
* Gamemenu shown before the start of each turn. Lets player end game, continue or switch entity.language
* @return
*/
// public void gameMenu() {
// String choice = this.getInput(entity.language.menu());
// switch (choice) {
// // Change dice sides
// case "1":
// String subchoice = this.getInput(entity.language.changeDices());
// if(subchoice.length() > 2) {
// if(diceCup.setDiceSides(Character.getNumericValue(subchoice.charAt(0)), Character.getNumericValue(subchoice.charAt(2))))
// System.out.println(entity.language.printDiceChangeSucces());
// break;
// else System.out.println(entity.language.printDiceChangeNotExecuted());
// break;
// // Change Language
// case "2":
// this.chooseLanguage();
// break;
// // Show Score
// case "3":
// System.out.println(entity.language.printScore(this.players));
// break;
// // End Game
// case "4":
// System.exit(1);
// // Continue game
// case "5":
// break;
// // Default
// default: break;
} |
package cgeo.geocaching;
import butterknife.ButterKnife;
import butterknife.InjectView;
import cgeo.geocaching.activity.AbstractActivity;
import cgeo.geocaching.files.LocalStorage;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.utils.ImageUtils;
import cgeo.geocaching.utils.Log;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.Nullable;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class ImageSelectActivity extends AbstractActivity {
@InjectView(R.id.caption) protected EditText captionView;
@InjectView(R.id.description) protected EditText descriptionView;
@InjectView(R.id.logImageScale) protected Spinner scaleView;
@InjectView(R.id.camera) protected Button cameraButton;
@InjectView(R.id.stored) protected Button storedButton;
@InjectView(R.id.save) protected Button saveButton;
@InjectView(R.id.cancel) protected Button clearButton;
@InjectView(R.id.image_preview) protected ImageView imagePreview;
static final String EXTRAS_CAPTION = "caption";
static final String EXTRAS_DESCRIPTION = "description";
static final String EXTRAS_URI_AS_STRING = "uri";
static final String EXTRAS_SCALE = "scale";
private static final String SAVED_STATE_IMAGE_CAPTION = "cgeo.geocaching.saved_state_image_caption";
private static final String SAVED_STATE_IMAGE_DESCRIPTION = "cgeo.geocaching.saved_state_image_description";
private static final String SAVED_STATE_IMAGE_URI = "cgeo.geocaching.saved_state_image_uri";
private static final String SAVED_STATE_IMAGE_SCALE = "cgeo.geocaching.saved_state_image_scale";
private static final int SELECT_NEW_IMAGE = 1;
private static final int SELECT_STORED_IMAGE = 2;
// Data to be saved while reconfiguring
private String imageCaption;
private String imageDescription;
private int scaleChoiceIndex;
private Uri imageUri;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState, R.layout.imageselect_activity);
ButterKnife.inject(this);
scaleChoiceIndex = Settings.getLogImageScale();
imageCaption = "";
imageDescription = "";
imageUri = Uri.EMPTY;
// Get parameters from intent and basic cache information from database
final Bundle extras = getIntent().getExtras();
if (extras != null) {
imageCaption = extras.getString(EXTRAS_CAPTION);
imageDescription = extras.getString(EXTRAS_DESCRIPTION);
imageUri = Uri.parse(extras.getString(EXTRAS_URI_AS_STRING));
scaleChoiceIndex = extras.getInt(EXTRAS_SCALE, scaleChoiceIndex);
}
// Restore previous state
if (savedInstanceState != null) {
imageCaption = savedInstanceState.getString(SAVED_STATE_IMAGE_CAPTION);
imageDescription = savedInstanceState.getString(SAVED_STATE_IMAGE_DESCRIPTION);
imageUri = Uri.parse(savedInstanceState.getString(SAVED_STATE_IMAGE_URI));
scaleChoiceIndex = savedInstanceState.getInt(SAVED_STATE_IMAGE_SCALE);
}
cameraButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectImageFromCamera();
}
});
storedButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
selectImageFromStorage();
}
});
if (StringUtils.isNotBlank(imageCaption)) {
captionView.setText(imageCaption);
}
if (StringUtils.isNotBlank(imageDescription)) {
descriptionView.setText(imageDescription);
}
scaleView.setSelection(scaleChoiceIndex);
scaleView.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
scaleChoiceIndex = scaleView.getSelectedItemPosition();
Settings.setLogImageScale(scaleChoiceIndex);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveImageInfo(true);
}
});
clearButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveImageInfo(false);
}
});
loadImagePreview();
}
@Override
protected void onSaveInstanceState(final Bundle outState) {
super.onSaveInstanceState(outState);
syncEditTexts();
outState.putString(SAVED_STATE_IMAGE_CAPTION, imageCaption);
outState.putString(SAVED_STATE_IMAGE_DESCRIPTION, imageDescription);
outState.putString(SAVED_STATE_IMAGE_URI, imageUri != null ? imageUri.getPath() : StringUtils.EMPTY);
outState.putInt(SAVED_STATE_IMAGE_SCALE, scaleChoiceIndex);
}
public void saveImageInfo(boolean saveInfo) {
if (saveInfo) {
final String filename = writeScaledImage(imageUri.getPath());
if (filename != null) {
imageUri = Uri.parse(filename);
final Intent intent = new Intent();
syncEditTexts();
intent.putExtra(EXTRAS_CAPTION, imageCaption);
intent.putExtra(EXTRAS_DESCRIPTION, imageDescription);
intent.putExtra(EXTRAS_URI_AS_STRING, imageUri.toString());
intent.putExtra(EXTRAS_SCALE, scaleChoiceIndex);
setResult(RESULT_OK, intent);
} else {
showToast(res.getString(R.string.err_select_logimage_failed));
setResult(RESULT_CANCELED);
}
} else {
setResult(RESULT_CANCELED);
}
finish();
}
private void syncEditTexts() {
imageCaption = captionView.getText().toString();
imageDescription = descriptionView.getText().toString();
scaleChoiceIndex = scaleView.getSelectedItemPosition();
}
private void selectImageFromCamera() {
// create Intent to take a picture and return control to the calling application
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
imageUri = ImageUtils.getOutputImageFileUri(); // create a file to save the image
if (imageUri == null) {
showFailure();
return;
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // set the image file name
// start the image capture Intent
startActivityForResult(intent, SELECT_NEW_IMAGE);
}
private void selectImageFromStorage() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/jpeg");
startActivityForResult(Intent.createChooser(intent, "Select Image"), SELECT_STORED_IMAGE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
showToast(getResources().getString(R.string.info_select_logimage_cancelled));
return;
}
if (resultCode != RESULT_OK) {
// Image capture failed, advise user
showFailure();
return;
}
// null is an acceptable result if the image has been placed in the imageUri file by the
// camera application.
if (data != null) {
final Uri selectedImage = data.getData();
if (Build.VERSION.SDK_INT < VERSION_CODES.KITKAT) {
String[] filePathColumn = { MediaColumns.DATA };
Cursor cursor = null;
try {
cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
if (cursor == null) {
showFailure();
return;
}
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
if (StringUtils.isBlank(filePath)) {
showFailure();
return;
}
imageUri = Uri.parse(filePath);
} catch (Exception e) {
Log.e("ImageSelectActivity.onActivityResult", e);
showFailure();
} finally {
if (cursor != null) {
cursor.close();
}
}
Log.d("SELECT IMAGE data = " + data.toString());
} else {
InputStream input = null;
OutputStream output = null;
try {
input = getContentResolver().openInputStream(selectedImage);
final File outputFile = ImageUtils.getOutputImageFile();
output = new FileOutputStream(outputFile);
LocalStorage.copy(input, output);
imageUri = Uri.fromFile(outputFile);
} catch (FileNotFoundException e) {
Log.e("ImageSelectActivity.onStartResult", e);
} finally {
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(output);
}
}
}
if (requestCode == SELECT_NEW_IMAGE) {
showToast(getResources().getString(R.string.info_stored_image) + "\n" + imageUri);
}
loadImagePreview();
}
/**
* Scales and writes the scaled image.
*
* @param filePath
* @return the scaled image path, or <tt>null</tt> if the image cannot be decoded
*/
@Nullable
private String writeScaledImage(@Nullable final String filePath) {
if (filePath == null) {
return null;
}
scaleChoiceIndex = scaleView.getSelectedItemPosition();
final int maxXY = getResources().getIntArray(R.array.log_image_scale_values)[scaleChoiceIndex];
return ImageUtils.readScaleAndWriteImage(filePath, maxXY);
}
private void showFailure() {
showToast(getResources().getString(R.string.err_acquire_image_failed));
}
private void loadImagePreview() {
if (imageUri == null || imageUri.getPath() == null) {
return;
}
if (!new File(imageUri.getPath()).exists()) {
Log.i("Image does not exist");
return;
}
@SuppressWarnings("null")
final Bitmap bitmap = ImageUtils.readAndScaleImageToFitDisplay(imageUri.getPath());
imagePreview.setImageBitmap(bitmap);
imagePreview.setVisibility(View.VISIBLE);
}
} |
package cgeo.geocaching.ui;
import cgeo.geocaching.ImageViewActivity;
import cgeo.geocaching.R;
import cgeo.geocaching.apps.navi.NavigationAppFactory;
import cgeo.geocaching.databinding.ImageGalleryCategoryBinding;
import cgeo.geocaching.databinding.ImageGalleryImageBinding;
import cgeo.geocaching.databinding.ImagegalleryViewBinding;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.models.Image;
import cgeo.geocaching.models.Waypoint;
import cgeo.geocaching.service.GeocacheChangedBroadcastReceiver;
import cgeo.geocaching.storage.DataStore;
import cgeo.geocaching.ui.dialog.ContextMenuDialog;
import cgeo.geocaching.ui.dialog.SimpleDialog;
import cgeo.geocaching.ui.recyclerview.AbstractRecyclerViewHolder;
import cgeo.geocaching.ui.recyclerview.ManagedListAdapter;
import cgeo.geocaching.utils.CategorizedListHelper;
import cgeo.geocaching.utils.CollectionStream;
import cgeo.geocaching.utils.ImageDataMemoryCache;
import cgeo.geocaching.utils.ImageUtils;
import cgeo.geocaching.utils.LocalizationUtils;
import cgeo.geocaching.utils.MetadataUtils;
import cgeo.geocaching.utils.ShareUtils;
import cgeo.geocaching.utils.UriUtils;
import cgeo.geocaching.utils.functions.Action2;
import cgeo.geocaching.utils.functions.Func1;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
public class ImageGalleryView extends LinearLayout {
private static final int IMAGE_TARGET_WIDTH_DP = 160;
private static final int IMAGE_TARGET_HEIGHT_DP = 200; // without title textview
private Context context;
private Activity activity;
private ImagegalleryViewBinding binding;
private ImageGalleryAdapter adapter;
private final CategorizedListHelper categorizedImageListHelper = new CategorizedListHelper();
private boolean allowOpenViewer = true;
private boolean activityReenterCalled = false;
private ImageActivityHelper imageHelper = null;
private final ImageDataMemoryCache imageDataMemoryCache = new ImageDataMemoryCache(2);
private String geocode;
private int imageCount = 0;
private Action2<ImageGalleryView, Integer> imageCountChangeCallback = null;
private final Map<String, Geopoint> imageCoordMap = new HashMap<>();
private final Map<String, EditableCategoryHandler> editableCategoryHandlerMap = new HashMap<>();
public interface EditableCategoryHandler {
Collection<Image> getAllImages();
Collection<Image> add(Collection<Image> images);
void delete(Image image);
Image setTitle(Image image, String title);
}
public static class ImageGalleryEntryHolder extends AbstractRecyclerViewHolder {
public final ImageGalleryImageBinding imageBinding;
public final ImageGalleryCategoryBinding categoryBinding;
public ImageGalleryEntry entry;
public static ImageGalleryEntryHolder createForImage(final ViewGroup view) {
return new ImageGalleryEntryHolder(ImageGalleryImageBinding.inflate(LayoutInflater.from(view.getContext()), view, false), null);
}
public static ImageGalleryEntryHolder createForCategory(final ViewGroup view) {
return new ImageGalleryEntryHolder(null, ImageGalleryCategoryBinding.inflate(LayoutInflater.from(view.getContext()), view, false));
}
private ImageGalleryEntryHolder(final ImageGalleryImageBinding imageBinding, final ImageGalleryCategoryBinding categoryBinding) {
super(imageBinding == null ? categoryBinding.getRoot() : imageBinding.getRoot());
this.imageBinding = imageBinding;
this.categoryBinding = categoryBinding;
}
}
public class ImageGalleryAdapter extends ManagedListAdapter<ImageGalleryEntry, ImageGalleryEntryHolder> {
protected ImageGalleryAdapter(final RecyclerView recyclerView) {
super(new Config(recyclerView));
}
@NonNull
@Override
public ImageGalleryEntryHolder onCreateViewHolder(@NonNull final ViewGroup parent, final int viewType) {
return viewType == 0 ? ImageGalleryEntryHolder.createForCategory(parent) : ImageGalleryEntryHolder.createForImage(parent);
}
@Override
public void onBindViewHolder(@NonNull final ImageGalleryEntryHolder holder, final int position) {
holder.entry = getItem(position);
if (holder.imageBinding != null) {
fillView(holder, holder.imageBinding);
} else {
fillCategoryView(holder, holder.categoryBinding);
}
}
@Override
public int getItemViewType(final int position) {
return getItem(position).isHeader() ? 0 : 1;
}
}
@Override
protected void onConfigurationChanged(final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
recalculateLayout(newConfig);
}
private void recalculateLayout(final Configuration newConfig) {
final GridLayoutManager manager = (GridLayoutManager) binding.imagegalleryList.getLayoutManager();
final int colCount = Math.max(1, newConfig.screenWidthDp / (IMAGE_TARGET_WIDTH_DP + 10));
manager.setSpanCount(colCount);
manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(final int pos) {
return adapter.getItem(pos).isHeader() ? colCount : 1;
}
});
manager.getSpanSizeLookup().setSpanGroupIndexCacheEnabled(true);
manager.getSpanSizeLookup().setSpanIndexCacheEnabled(true);
}
private void invalidateSpanIndexCaches() {
final GridLayoutManager manager = (GridLayoutManager) binding.imagegalleryList.getLayoutManager();
manager.getSpanSizeLookup().invalidateSpanGroupIndexCache();
manager.getSpanSizeLookup().invalidateSpanIndexCache();
}
private static class ImageGalleryEntry {
public final Image image;
public final String category;
ImageGalleryEntry(final String category) {
this(category, null);
}
ImageGalleryEntry(final String category, final Image image) {
this.image = image;
this.category = category;
}
public boolean isHeader() {
return image == null;
}
}
public void fillView(final ImageGalleryEntryHolder viewHolder, final ImageGalleryImageBinding binding) {
final ImageGalleryEntry imgData = viewHolder.entry;
final Image img = imgData.image;
setImageTitle(binding, img.getTitle());
//setImageLayoutSizes(binding, imageSizeDp);
binding.imageDescriptionMarker.setVisibility(img.hasDescription() ? View.VISIBLE : View.GONE);
if (!img.isImageOrUnknownUri()) {
binding.imageTitle.setText(TextUtils.concat(binding.imageTitle.getText(), " (" + UriUtils.getMimeFileExtension(img.getUri()) + ")"));
binding.imageImage.setImageResource(UriUtils.getMimeTypeIcon(img.getMimeType()));
binding.imageImage.setVisibility(View.VISIBLE);
binding.imageGeoOverlay.setVisibility(View.GONE);
binding.imageProgressBar.setVisibility(View.GONE);
} else {
imageDataMemoryCache.loadImage(img.getUrl(), p -> {
final ImageGalleryEntry currentEntry = viewHolder.entry;
if (!currentEntry.image.getUrl().equals(img.getUrl())) {
//this means that meanwhile in the same ViewHolder another image was place
return;
}
binding.imageImage.setImageDrawable(p.first);
binding.imageImage.setVisibility(View.VISIBLE);
final Geopoint gp = MetadataUtils.getFirstGeopoint(p.second);
if (gp != null) {
binding.imageGeoOverlay.setVisibility(View.VISIBLE);
imageCoordMap.put(img.getUrl(), gp);
} else {
binding.imageGeoOverlay.setVisibility(View.GONE);
}
binding.imageProgressBar.setVisibility(View.GONE);
}, () -> {
binding.imageProgressBar.setVisibility(View.VISIBLE);
binding.imageImage.setImageResource(R.drawable.mark_transparent);
//binding.imageImage.setVisibility(View.GONE);
binding.imageGeoOverlay.setVisibility(View.GONE);
});
}
binding.imageWrapper.setOnClickListener(v -> openImageDetails(imgData, binding));
binding.imageWrapper.setOnLongClickListener(v -> {
showContextOptions(imgData, binding);
return true;
});
}
private void setImageTitle(final ImageGalleryImageBinding binding, final CharSequence text) {
if (!StringUtils.isBlank(text)) {
binding.imageTitle.setText(TextParam.text(text).setHtml(true).getText(getContext()));
binding.imageTitle.setVisibility(View.VISIBLE);
} else {
binding.imageTitle.setVisibility(View.GONE);
}
}
public ImageGalleryView(final Context context) {
super(context);
init();
}
public ImageGalleryView(final Context context, @Nullable final AttributeSet attrs) {
super(context, attrs);
init();
}
public ImageGalleryView(final Context context, @Nullable final AttributeSet attrs, final int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setOrientation(VERTICAL);
this.context = new ContextThemeWrapper(getContext(), R.style.cgeo);
this.activity = ViewUtils.toActivity(this.context);
inflate(this.context, R.layout.imagegallery_view, this);
binding = ImagegalleryViewBinding.bind(this);
this.adapter = new ImageGalleryAdapter(binding.imagegalleryList);
binding.imagegalleryList.setAdapter(this.adapter);
binding.imagegalleryList.setLayoutManager(new GridLayoutManager(this.context, 2));
recalculateLayout(getContext().getResources().getConfiguration());
//enable transitions between gallery and image detail activity
ImageViewActivity.enableViewTransitions(this.activity);
}
/** (re)sets contextual information for gallery */
public void setup(final String geocode) {
this.geocode = geocode;
this.imageDataMemoryCache.setCode(this.geocode);
}
/** gets total number of images currently displayed in this gallery */
public int getImageCount() {
return categorizedImageListHelper.getContentSize();
}
/** adds images for display to this gallery */
public void addImages(final Collection<Image> images) {
addImages(images, i -> i.category == Image.ImageCategory.UNCATEGORIZED ? null : i.category.getI18n());
}
/** adds images for display to this gallery */
public void addImages(final Collection<Image> images, final Func1<Image, String> categoryMapper) {
addImagesInternal(images, categoryMapper, false);
}
private void addImagesInternal(final Collection<Image> images, final Func1<Image, String> categoryMapper, final boolean force) {
//order images by category
final List<String> categories = new ArrayList<>();
final Map<String, List<ImageGalleryEntry>> catImages = new HashMap<>();
for (Image img : images) {
final String category = categoryMapper.call(img);
if (!force && editableCategoryHandlerMap.containsKey(category)) {
continue;
}
if (!catImages.containsKey(category)) {
categories.add(category);
catImages.put(category, new ArrayList<>());
}
catImages.get(category).add(new ImageGalleryEntry(category, img));
}
//add to gallery category-wise
for (String category : categories) {
if (!categorizedImageListHelper.containsCategory(category)) {
createCategory(category, false);
}
adapter.addItems(categorizedImageListHelper.getCategoryInsertPosition(category), catImages.get(category));
categorizedImageListHelper.addToCount(category, catImages.get(category).size());
}
//invalidate caches
invalidateSpanIndexCaches();
}
private void changeImageCount(final int by) {
if (by != 0) {
imageCount += by;
if (imageCountChangeCallback != null) {
imageCountChangeCallback.call(this, imageCount);
}
}
}
private void createCategory(final String category, final boolean atStart) {
if (!categorizedImageListHelper.containsCategory(category)) {
categorizedImageListHelper.addOrMoveCategory(category, atStart);
adapter.addItem(atStart ? 0 : adapter.getItemCount(), new ImageGalleryEntry(category));
}
}
private void fillCategoryView(final ImageGalleryEntryHolder entry, final ImageGalleryCategoryBinding binding) {
final String category = entry.entry.category;
if (StringUtils.isBlank(category)) {
binding.imgGalleryCategoryTitle.setVisibility(View.GONE);
} else {
binding.imgGalleryCategoryTitle.setVisibility(View.VISIBLE);
binding.imgGalleryCategoryTitle.setText(category);
}
final boolean isEditableCat = this.editableCategoryHandlerMap.containsKey(category);
binding.imgGalleryAddButtons.setVisibility(isEditableCat ? View.VISIBLE : View.GONE);
binding.imgGalleryAddMultiImages.setOnClickListener(v -> imageHelper.getMultipleImagesFromStorage(geocode, false, category));
binding.imgGalleryAddCamera.setOnClickListener(v -> imageHelper.getImageFromCamera(geocode, false, category));
binding.imgGalleryAddMultiFiles.setOnClickListener(v -> imageHelper.getMultipleFilesFromStorage(geocode, false, category));
}
/** adds an editable category to this gallery. This is a category where user has options to add/rename/remove images */
public void setEditableCategory(final String category, final EditableCategoryHandler handler) {
if (this.activity == null) {
//not supported if not in context of an activity
return;
}
removeCategory(category);
this.editableCategoryHandlerMap.put(category, handler);
createCategory(category, true);
//fill initially
addImagesInternal(handler.getAllImages(), i -> category, true);
if (imageHelper == null) {
imageHelper = new ImageActivityHelper(activity, (r, imgUris, uk) -> {
final Collection<Image> imgs = CollectionStream.of(imgUris).map(uri -> new Image.Builder().setUrl(uri).build()).toList();
final Collection<Image> addedImgs = editableCategoryHandlerMap.get(uk).add(imgs);
if (r == ImageActivityHelper.REQUEST_CODE_CAMERA) {
//change title of camera photos
final Collection<Image> copy = new ArrayList<>(addedImgs);
addedImgs.clear();
int idx = categorizedImageListHelper.getCategoryCount(uk) + 1;
for (Image i : copy) {
final Image newImage = editableCategoryHandlerMap.get(uk).setTitle(i, LocalizationUtils.getString(R.string.cache_image_title_camera_prefix) + " " + idx);
if (newImage == null) {
addedImgs.add(i);
} else {
addedImgs.add(newImage);
idx++;
}
}
}
addImagesInternal(addedImgs, i -> uk, true);
});
}
}
/** Important: include this method in your activity to support activity-related tasks. Necessary for e.g. editable categories */
public boolean onActivityResult(final int requestCode, final int resultCode, final Intent data) {
allowOpenViewer();
//in some situations "onActivityReenter" is not called. In these cases -> initialize position here
if (!activityReenterCalled) {
onActivityReenter(activity, this, data);
}
activityReenterCalled = false;
if (imageHelper != null) {
return imageHelper.onActivityResult(requestCode, resultCode, data);
}
return false;
}
/** registers a callback which is triggered whenever the count of images displayed in gallery changes */
public void setImageCountChangeCallback(final Action2<ImageGalleryView, Integer> callback) {
this.imageCountChangeCallback = callback;
}
/** scrolls the image gallery to the list index given */
private void scrollTo(final int listIndex) {
final int realIndex = Math.max(0, Math.min(adapter.getItemCount() - 1, listIndex));
final RecyclerView recyclerView = binding.imagegalleryList;
final GridLayoutManager layoutManager = (GridLayoutManager) recyclerView.getLayoutManager();
//check if item is already (completely) visible --> then don't scroll
final View viewAtPosition = layoutManager.findViewByPosition(realIndex);
if (viewAtPosition == null || layoutManager
.isViewPartiallyVisible(viewAtPosition, false, true)) {
//view is either not or only partially visible --> scroll
int offset = 50; //default
//try to calculate an offset such that the image to scroll to ends up in the middle of the gallery view
final int imageHeight = ViewUtils.dpToPixel(IMAGE_TARGET_HEIGHT_DP);
final int height = this.getHeight();
if (height >= imageHeight) {
offset = (height - imageHeight) / 2;
}
//use "scrollToPositionWithOffset" since "scrollToPosition" behaves strange -> see issue #13586
layoutManager.scrollToPositionWithOffset(realIndex, offset);
}
}
/** returns the image view for given image index (or null if index is invalid) */
@Nullable
public View getImageViewForContentIndex(final int contentIndex) {
final int pos = categorizedImageListHelper.getListIndexForContentIndex(contentIndex);
if (pos == -1) {
return null;
}
final ImageGalleryEntryHolder vh = (ImageGalleryEntryHolder) binding.imagegalleryList.findViewHolderForAdapterPosition(pos);
if (vh == null || vh.imageBinding == null) {
return null;
}
return vh.imageBinding.imageImage;
}
/** clears this gallery */
public void clear() {
this.imageDataMemoryCache.clear();
this.adapter.clearList();
this.categorizedImageListHelper.clear();
this.imageCount = 0;
}
/** registers the activity associated with this gallery for image transtions towards image detail view */
public void registerCallerActivity() {
ImageViewActivity.registerCallerActivity(this.activity, this::getImageViewForContentIndex);
}
public void removeCategory(final String category) {
if (!categorizedImageListHelper.containsCategory(category)) {
return;
}
changeImageCount(-categorizedImageListHelper.getCategoryCount(category));
final int titlePos = categorizedImageListHelper.getCategoryTitlePosition(category);
for (int pos = categorizedImageListHelper.getCategoryInsertPosition(category) - 1; pos >= titlePos; pos
adapter.removeItem(pos);
}
categorizedImageListHelper.removeCategory(category);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
//clear image cache
this.imageDataMemoryCache.clear();
}
/** Important: include this in your activity's "onActivityReenter" method.
* Needed e.g. for correct back transition when returning from detail view (e.g. scrolling to image gallery position) */
public static int onActivityReenter(final Activity activity, final ImageGalleryView imageGallery, final Intent data) {
final int pos = data.getExtras() == null ? -1 : data.getExtras().getInt(ImageViewActivity.EXTRA_IMAGEVIEW_POS, -1);
if (pos >= 0) {
activity.postponeEnterTransition();
if (imageGallery != null) {
imageGallery.initializeToPosition(pos);
imageGallery.activityReenterCalled = true;
}
}
return pos;
}
/** initializes gallery to a certain position.
* Use this method directly for gallery recreation if gallery was not available in activity's "onActivityReender" method */
public void initializeToPosition(final int contentIndex) {
final int realPos = Math.max(-1, Math.min(adapter.getItemCount() - 1, contentIndex));
this.allowOpenViewer();
if (realPos >= 0) {
this.scrollTo(categorizedImageListHelper.getListIndexForContentIndex(realPos));
}
this.post(() -> activity.startPostponedEnterTransition());
}
/** allows the gallery to open a image detail view (again) */
private void allowOpenViewer() {
this.allowOpenViewer = true;
}
private void openImageDetails(final ImageGalleryEntry imgData, final ImageGalleryImageBinding binding) {
if (imgData.image.isImageOrUnknownUri()) {
openImageViewer(binding);
} else {
ShareUtils.openContentForView(getContext(), imgData.image.getUrl());
}
}
private void openImageViewer(final ImageGalleryImageBinding binding) {
if (activity == null || !allowOpenViewer) {
return;
}
allowOpenViewer = false;
final int intentPos = this.binding.imagegalleryList.getChildAdapterPosition(binding.getRoot());
final int contentPos = categorizedImageListHelper.getContentIndexForListIndex(intentPos);
final List<Image> images = new ArrayList<>();
for (ImageGalleryEntry item : adapter.getItems()) {
if (!item.isHeader()) {
images.add(item.image);
}
}
ImageViewActivity.openImageView(this.activity, geocode, images, contentPos,
this::getImageViewForContentIndex);
}
// splitting up that method would not help improve readability
@SuppressWarnings({"PMD.NPathComplexity", "PMD.ExcessiveMethodLength"})
private void showContextOptions(final ImageGalleryEntry imgData, final ImageGalleryImageBinding binding) {
if (activity == null || imgData == null || imgData.image == null) {
return;
}
final String category = imgData.category;
final Image img = imgData.image;
final int intentPos = this.binding.imagegalleryList.getChildAdapterPosition(binding.getRoot());
final ContextMenuDialog ctxMenu = new ContextMenuDialog(activity);
ctxMenu.setTitle(LocalizationUtils.getString(R.string.cache_image));
ctxMenu.addItem(LocalizationUtils.getString(R.string.cache_image_open), R.drawable.ic_menu_image,
v -> openImageDetails(imgData, binding));
ctxMenu.addItem(LocalizationUtils.getString(R.string.cache_image_open_file), R.drawable.ic_menu_image,
v -> ImageUtils.viewImageInStandardApp(activity, img.getUri(), geocode));
if (!UriUtils.isFileUri(img.getUri()) && !UriUtils.isContentUri(img.getUri())) {
ctxMenu.addItem(LocalizationUtils.getString(R.string.cache_image_open_browser), R.drawable.ic_menu_open_in_browser,
v -> ShareUtils.openUrl(context, img.getUrl(), false));
}
if (img.hasDescription()) {
ctxMenu.addItem(LocalizationUtils.getString(R.string.cache_image_show_description), R.drawable.ic_menu_hint,
v -> SimpleDialog.ofContext(getContext()).setTitle(R.string.log_image_description)
.setMessage(TextParam.text(img.getDescription()).setHtml(true)).show());
}
final Geopoint gp = imageCoordMap.get(img.getUrl());
if (gp != null && geocode != null) {
ctxMenu.addItem(LocalizationUtils.getString(R.string.cache_image_add_waypoint), R.drawable.ic_menu_myposition, v -> {
final Geocache geocache = DataStore.loadCache(geocode, LoadFlags.LOAD_CACHE_OR_DB);
if (geocache != null) {
final Waypoint waypoint = new Waypoint(img.getTitle(), WaypointType.WAYPOINT, true);
waypoint.setCoords(gp);
geocache.addOrChangeWaypoint(waypoint, true);
GeocacheChangedBroadcastReceiver.sendBroadcast(activity, geocode);
}
});
ctxMenu.addItem(LocalizationUtils.getString(R.string.cache_menu_navigate), R.drawable.ic_menu_navigate,
v -> NavigationAppFactory.showNavigationMenu(activity, null, null, gp));
}
final EditableCategoryHandler editHandler = editableCategoryHandlerMap.get(category);
if (editHandler != null) {
final Image oldImg = adapter.getItem(intentPos).image;
ctxMenu.addItem(LocalizationUtils.getString(R.string.cache_image_rename), R.drawable.ic_menu_edit, v -> SimpleDialog.ofContext(getContext()).setTitle(TextParam.id(R.string.cache_image_rename))
.input(-1, oldImg.getTitle(), null, null, newTitle -> {
if (!StringUtils.isBlank(newTitle)) {
final Image newImg = editHandler.setTitle(oldImg, newTitle);
if (newImg != null) {
final ImageGalleryEntry oldEntry = adapter.getItem(intentPos);
adapter.updateItem(new ImageGalleryEntry(oldEntry.category, newImg), intentPos);
}
}
}));
ctxMenu.addItem(LocalizationUtils.getString(R.string.cache_image_delete), R.drawable.ic_menu_delete, v -> {
final ImageGalleryEntry oldEntry = adapter.getItem(intentPos);
adapter.removeItem(intentPos);
editHandler.delete(img);
categorizedImageListHelper.addToCount(oldEntry.category, -1);
changeImageCount(-1);
});
}
ctxMenu.show();
}
} |
package mockit;
import java.io.*;
import org.junit.*;
import static org.junit.Assert.*;
public final class ClassLoadingAndJREMocksTest
{
static class Foo
{
boolean checkFile(String filePath)
{
File f = new File(filePath);
return f.exists();
}
}
@Test
public void recordExpectationForFileUsingLocalMockField()
{
new Expectations()
{
File file;
{
new File("filePath").exists(); result = true;
}
};
Foo foo = new Foo();
assertTrue(foo.checkFile("filePath"));
}
@Test
public void recordExpectationForFileUsingMockParameter(@Mocked File file)
{
new Expectations()
{
{
new File("filePath").exists(); result = true;
}
};
Foo foo = new Foo();
assertTrue(foo.checkFile("filePath"));
}
@Test
public void mockUpFile()
{
// TODO: this test fails when run alone; mock classes should also support conditional mocking
// for JRE classes
new MockUp<File>()
{
@Mock
boolean exists() { return true; }
};
Foo foo = new Foo();
assertTrue(foo.checkFile("filePath"));
}
@Test
public void mockFileOutputStreamInstantiation() throws Exception
{
new Expectations()
{
@Mocked("helperMethod") TestedUnitUsingIO tested;
FileOutputStream mockOS;
{
invoke(
tested, "helperMethod",
withInstanceOf(FileOutputStream.class) == null ? FileOutputStream.class : null);
}
};
new TestedUnitUsingIO().doSomething();
}
static class TestedUnitUsingIO
{
void doSomething() throws FileNotFoundException
{
helperMethod(new FileOutputStream("test"));
}
private void helperMethod(OutputStream output)
{
// Won't happen:
throw new IllegalStateException(output.toString());
}
}
} |
package us.kbase.userandjobstate.jobstate;
import static us.kbase.common.utils.StringUtils.checkString;
import static us.kbase.common.utils.StringUtils.checkMaxLen;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.jongo.Jongo;
import org.jongo.MongoCollection;
import us.kbase.common.schemamanager.SchemaManager;
import us.kbase.common.schemamanager.exceptions.SchemaException;
import us.kbase.userandjobstate.authorization.AuthorizationStrategy;
import us.kbase.userandjobstate.authorization.DefaultUJSAuthorizer;
import us.kbase.userandjobstate.authorization.UJSAuthorizer;
import us.kbase.userandjobstate.authorization.exceptions.UJSAuthorizationException;
import us.kbase.userandjobstate.exceptions.CommunicationException;
import us.kbase.userandjobstate.jobstate.exceptions.NoSuchJobException;
import us.kbase.workspace.database.WorkspaceUserMetadata;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoException;
import com.mongodb.WriteResult;
public class JobState {
// private final static int JOB_EXPIRES = 180 * 24 * 60 * 60; // 180 days
private final static int MAX_LEN_USER = 100;
private final static int MAX_LEN_SERVICE = 100;
private final static int MAX_LEN_STATUS = 200;
private final static int MAX_LEN_DESC = 1000;
private final static int MAX_LEN_ERR = 100000;
private final static String CREATED = "created";
private final static String USER = "user";
private final static String SERVICE = "service";
private final static String STARTED = "started";
private final static String UPDATED = "updated";
private final static String EST_COMP = "estcompl";
private final static String COMPLETE = "complete";
private final static String ERROR = "error";
// only present if job was canceled
private final static String CANCELEDBY = "canceledby";
private final static String ERROR_MSG = "errormsg";
private final static String DESCRIPTION = "desc";
private final static String PROG_TYPE = "progtype";
private final static String PROG = "prog";
private final static String MAXPROG = "maxprog";
private final static String STATUS = "status";
private final static String RESULT = "results";
private final static String SHARED = "shared";
public static final String AUTH_STRAT = "authstrat";
public static final String AUTH_PARAM = "authparam";
public static final String METADATA = "meta";
public final static String PROG_NONE = "none";
public final static String PROG_TASK = "task";
public final static String PROG_PERC = "percent";
private final static String MONGO_ID = "_id";
public static final String META_KEY = "k";
public static final String META_VALUE = "v";
public static final String SCHEMA_TYPE = "jobstate";
public final static int SCHEMA_VER = 2;
private final DBCollection jobcol;
private final MongoCollection jobjong;
public JobState(final DBCollection jobcol, final SchemaManager sm)
throws SchemaException {
if (jobcol == null) {
throw new NullPointerException("jobcol");
}
this.jobcol = jobcol;
jobjong = new Jongo(jobcol.getDB()).getCollection(jobcol.getName());
ensureIndexes();
sm.checkSchema(SCHEMA_TYPE, SCHEMA_VER);
}
private void ensureIndexes() {
ensureUserIndex(USER);
ensureUserIndex(SHARED);
ensureAuthIndex();
// final DBObject ttlidx = new BasicDBObject(CREATED, 1);
// final DBObject opts = new BasicDBObject("expireAfterSeconds",
// JOB_EXPIRES);
// jobcol.ensureIndex(ttlidx, opts);
}
private void ensureUserIndex(final String userField) {
final DBObject idx = new BasicDBObject();
idx.put(userField, 1);
idx.put(SERVICE, 1);
idx.put(COMPLETE, 1);
jobcol.createIndex(idx);
}
private void ensureAuthIndex() {
final DBObject idx = new BasicDBObject();
idx.put(AUTH_STRAT, 1);
idx.put(AUTH_PARAM, 1);
jobcol.createIndex(idx);
}
public String createJob(final String user)
throws CommunicationException {
try {
return createJob(user, new DefaultUJSAuthorizer(),
UJSAuthorizer.DEFAULT_AUTH_STRAT,
UJSAuthorizer.DEFAULT_AUTH_PARAM,
new WorkspaceUserMetadata());
} catch (UJSAuthorizationException e) {
throw new RuntimeException(
"This should be impossible, but there you go", e);
}
}
public String createJob(
final String user,
final UJSAuthorizer auth,
final AuthorizationStrategy strat,
final String authParam,
//TODO ZZLATER this class should be renamed
final WorkspaceUserMetadata meta)
throws CommunicationException, UJSAuthorizationException {
checkString(user, "user", MAX_LEN_USER);
auth.authorizeCreate(strat, authParam);
if (meta == null) {
throw new NullPointerException("meta");
}
final DBObject job = new BasicDBObject(USER, user);
final Date date = new Date();
job.put(AUTH_STRAT, strat.getStrat());
job.put(AUTH_PARAM, authParam);
job.put(METADATA, metaToMongoArray(meta));
job.put(CREATED, date);
job.put(UPDATED, date);
job.put(EST_COMP, null);
job.put(SERVICE, null);
try {
jobcol.insert(job);
} catch (MongoException me) {
throw new CommunicationException(
"There was a problem communicating with the database", me);
}
return ((ObjectId) job.get(MONGO_ID)).toString();
}
private static List<Map<String, String>> metaToMongoArray(
final WorkspaceUserMetadata wum) {
final List<Map<String, String>> meta =
new ArrayList<Map<String, String>>();
for (String key: wum.getMetadata().keySet()) {
Map<String, String> m = new LinkedHashMap<String, String>(2);
m.put(META_KEY, key);
m.put(META_VALUE, wum.getMetadata().get(key));
meta.add(m);
}
return meta;
}
private static ObjectId checkJobID(final String id) {
checkString(id, "id");
final ObjectId oi;
try {
oi = new ObjectId(id);
} catch (IllegalArgumentException iae) {
throw new IllegalArgumentException(String.format(
"Job ID %s is not a legal ID", id));
}
return oi;
}
public Job getJob(final String user, final String jobID)
throws CommunicationException, NoSuchJobException {
return getJob(user, jobID, new DefaultUJSAuthorizer());
}
public Job getJob(
final String user,
final String jobID,
final UJSAuthorizer auth)
throws CommunicationException, NoSuchJobException {
checkString(user, "user", MAX_LEN_USER);
final ObjectId oi = checkJobID(jobID);
final Job j;
try {
j = getJob(oi);
auth.authorizeRead(user, j);
} catch (NoSuchJobException | UJSAuthorizationException e) {
throw new NoSuchJobException(String.format(
"There is no job %s viewable by user %s", jobID, user));
}
return j;
}
private Job getJob(final ObjectId jobID)
throws CommunicationException, NoSuchJobException {
final Job j;
try {
j = toJob(jobcol.findOne(new BasicDBObject(MONGO_ID, jobID)));
} catch (MongoException me) {
throw new CommunicationException(
"There was a problem communicating with the database", me);
}
if (j == null) {
throw new NoSuchJobException(String.format(
"There is no job %s", jobID));
}
return j;
}
private Job toJob(final DBObject dbo) {
if (dbo == null) {
return null;
}
@SuppressWarnings("unchecked")
final List<String> shared = (List<String>) dbo.get(SHARED);
@SuppressWarnings("unchecked")
final List<DBObject> meta = (List<DBObject>) dbo.get(METADATA);
return new Job(
(ObjectId) dbo.get(MONGO_ID),
(String) dbo.get(USER),
(String) dbo.get(SERVICE),
(String) dbo.get(DESCRIPTION),
(String) dbo.get(PROG_TYPE),
(Integer) dbo.get(PROG),
(Integer) dbo.get(MAXPROG),
(String) dbo.get(STATUS),
(Date) dbo.get(STARTED),
(Date) dbo.get(UPDATED),
(Date) dbo.get(EST_COMP),
(Boolean) dbo.get(COMPLETE),
(Boolean) dbo.get(ERROR),
(String) dbo.get(CANCELEDBY),
(String) dbo.get(ERROR_MSG),
toJobResults((DBObject) dbo.get(RESULT)),
shared == null ? null : shared.stream().collect(Collectors.toList()),
(String) dbo.get(AUTH_STRAT),
(String) dbo.get(AUTH_PARAM),
meta.stream().map(
m -> m.keySet().stream().collect(Collectors.toMap(
k -> k, k -> (String) m.get(k))))
.collect(Collectors.toList()));
}
public void startJob(final String user, final String jobID,
final String service, final String status,
final String description, final Date estComplete)
throws CommunicationException, NoSuchJobException {
startJob(user, jobID, service, status, description, PROG_NONE, null,
estComplete);
}
public void startJob(final String user, final String jobID,
final String service, final String status,
final String description, final int maxProg,
final Date estComplete)
throws CommunicationException, NoSuchJobException {
startJob(user, jobID, service, status, description, PROG_TASK, maxProg,
estComplete);
}
public void startJobWithPercentProg(final String user, final String jobID,
final String service, final String status,
final String description, final Date estComplete)
throws CommunicationException, NoSuchJobException {
startJob(user, jobID, service, status, description, PROG_PERC, null,
estComplete);
}
private void startJob(final String user, final String jobID,
final String service, final String status,
final String description, final String progType,
final Integer maxProg, final Date estComplete)
throws CommunicationException, NoSuchJobException {
checkString(user, "user", MAX_LEN_USER);
final ObjectId oi = checkJobID(jobID);
//this is coming from an auth token so doesn't need much checking
//although if this is every really used as a lib (unlikely) will need better QA
checkString(service, "service", MAX_LEN_SERVICE);
checkMaxLen(status, "status", MAX_LEN_STATUS);
checkMaxLen(description, "description", MAX_LEN_DESC);
checkEstComplete(estComplete);
if (maxProg != null && maxProg < 1) {
throw new IllegalArgumentException(
"The maximum progress for the job must be > 0");
}
final DBObject query = new BasicDBObject(USER, user);
query.put(MONGO_ID, oi);
query.put(SERVICE, null);
final DBObject update = new BasicDBObject(SERVICE, service);
update.put(STATUS, status);
update.put(DESCRIPTION, description);
update.put(PROG_TYPE, progType);
final Date now = new Date();
update.put(STARTED, now);
update.put(UPDATED, now);
update.put(EST_COMP, estComplete);
update.put(COMPLETE, false);
update.put(ERROR, false);
update.put(ERROR_MSG, null);
update.put(RESULT, null);
final Integer prog;
final Integer maxprog;
if (progType == PROG_TASK) {
prog = 0;
maxprog = maxProg;
} else if (progType == PROG_PERC) {
prog = 0;
maxprog = 100;
} else if (progType == PROG_NONE) {
prog = 0;
maxprog = null;
} else {
throw new IllegalArgumentException("Illegal progress type: " +
progType);
}
update.put(PROG, prog);
update.put(MAXPROG, maxprog);
final WriteResult wr;
try {
wr = jobcol.update(query, new BasicDBObject("$set", update));
} catch (MongoException me) {
throw new CommunicationException(
"There was a problem communicating with the database", me);
}
if (wr.getN() != 1) {
throw new NoSuchJobException(String.format(
"There is no unstarted job %s for user %s", jobID, user));
}
}
private void checkEstComplete(final Date estComplete) {
if (estComplete == null) {
return;
}
if (estComplete.compareTo(new Date()) < 1) {
throw new IllegalArgumentException(
"The estimated completion date must be in the future");
}
}
public String createAndStartJob(final String user, final String service,
final String status, final String description,
final Date estComplete)
throws CommunicationException {
return createAndStartJob(user, service, status, description, PROG_NONE,
null, estComplete);
}
public String createAndStartJob(final String user, final String service,
final String status, final String description, final int maxProg,
final Date estComplete)
throws CommunicationException {
return createAndStartJob(user, service, status, description, PROG_TASK,
maxProg, estComplete);
}
public String createAndStartJobWithPercentProg(final String user,
final String service, final String status,
final String description, final Date estComplete)
throws CommunicationException {
return createAndStartJob(user, service, status, description, PROG_PERC,
null, estComplete);
}
private String createAndStartJob(final String user, final String service,
final String status, final String description,
final String progType, final Integer maxProg,
final Date estComplete)
throws CommunicationException {
final String jobid = createJob(user);
try {
startJob(user, jobid, service, status, description, progType,
maxProg, estComplete);
} catch (NoSuchJobException nsje) {
throw new RuntimeException(
"Just created a job and it's already deleted", nsje);
}
return jobid;
}
public void updateJob(final String user, final String jobID,
final String service, final String status, final Integer progress,
final Date estComplete)
throws CommunicationException, NoSuchJobException {
checkMaxLen(status, "status", MAX_LEN_STATUS);
final DBObject query = buildStartedJobQuery(user, jobID, service);
final DBObject set = new BasicDBObject(STATUS, status);
set.put(UPDATED, new Date());
if (estComplete != null) {
checkEstComplete(estComplete);
set.put(EST_COMP, estComplete);
}
final DBObject update = new BasicDBObject("$set", set);
if (progress != null) {
if (progress < 0) {
throw new IllegalArgumentException(
"progress cannot be negative");
}
update.put("$inc", new BasicDBObject(PROG, progress));
}
final WriteResult wr;
try {
wr = jobcol.update(query, update);
} catch (MongoException me) {
throw new CommunicationException(
"There was a problem communicating with the database", me);
}
if (wr.getN() != 1) {
throw new NoSuchJobException(String.format(
"There is no uncompleted job %s for user %s started by service %s",
jobID, user, service));
}
}
public void completeJob(final String user, final String jobID,
final String service, final String status, final String error,
final JobResults results)
throws CommunicationException, NoSuchJobException {
checkMaxLen(status, "status", MAX_LEN_STATUS);
checkMaxLen(error, "error", MAX_LEN_ERR);
final DBObject query = buildStartedJobQuery(user, jobID, service);
final DBObject set = new BasicDBObject(UPDATED, new Date());
set.put(COMPLETE, true);
set.put(ERROR, error != null);
set.put(ERROR_MSG, error);
set.put(STATUS, status);
//if anyone is stupid enough to store 16mb of results will need to
//check size first, or at least catch error and report.
set.put(RESULT, resultsToDBObject(results));
final WriteResult wr;
try {
wr = jobcol.update(query, new BasicDBObject("$set", set));
} catch (MongoException me) {
throw new CommunicationException(
"There was a problem communicating with the database", me);
}
if (wr.getN() != 1) {
throw new NoSuchJobException(String.format(
"There is no uncompleted job %s for user %s started by service %s",
jobID, user, service));
}
}
private static DBObject resultsToDBObject(final JobResults res) {
if (res == null) {
return null;
}
final DBObject ret = new BasicDBObject();
ret.put("shocknodes", res.getShocknodes());
ret.put("shockurl", res.getShockurl());
ret.put("workspaceids", res.getWorkspaceids());
ret.put("workspaceurl", res.getWorkspaceurl());
if (res.getResults() != null) {
final List<DBObject> results = new LinkedList<DBObject>();
ret.put("results", results);
for (final JobResult jr: res.getResults()) {
final DBObject oneres = new BasicDBObject();
results.add(oneres);
oneres.put("servtype", jr.getServtype());
oneres.put("url", jr.getUrl());
oneres.put("id", jr.getId());
oneres.put("desc", jr.getDesc());
}
}
return ret;
}
private JobResults toJobResults(final DBObject dbo) {
if (dbo == null) {
return null;
}
@SuppressWarnings("unchecked")
final List<DBObject> dbresults = (List<DBObject>) dbo.get("results");
final List<JobResult> results;
if (dbresults != null) {
results = new LinkedList<>();
for (final DBObject d: dbresults) {
results.add(new JobResult(
(String) d.get("servtype"),
(String) d.get("url"),
(String) d.get("id"),
(String) d.get("desc")));
}
} else {
results = null;
}
@SuppressWarnings("unchecked")
final List<String> shocknodes = (List<String>) dbo.get("shocknodes");
@SuppressWarnings("unchecked")
final List<String> workspaceids = (List<String>) dbo.get("workspaceids");
return new JobResults(
results,
(String) dbo.get("workspaceurl"),
workspaceids == null ? null : workspaceids.stream().collect(Collectors.toList()),
(String) dbo.get("shockurl"),
shocknodes == null ? null : shocknodes.stream().collect(Collectors.toList()));
}
private DBObject buildStartedJobQuery(
final String user,
final String jobID,
final String service) {
checkString(user, "user", MAX_LEN_USER);
final ObjectId id = checkJobID(jobID);
checkString(service, "service", MAX_LEN_SERVICE);
final DBObject query = new BasicDBObject(USER, user);
query.put(MONGO_ID, id);
query.put(SERVICE, service);
query.put(COMPLETE, false);
return query;
}
public void cancelJob(
final String user,
final String jobID,
final String status)
throws CommunicationException, NoSuchJobException {
cancelJob(user, jobID, status, new DefaultUJSAuthorizer());
}
public void cancelJob(
final String user,
final String jobID,
final String status,
final UJSAuthorizer auth)
throws CommunicationException, NoSuchJobException {
checkString(user, "user", MAX_LEN_USER);
checkMaxLen(status, "status", MAX_LEN_STATUS);
final ObjectId oi = checkJobID(jobID);
final NoSuchJobException nsje = new NoSuchJobException(String.format(
"There is no job %s that may be canceled by user %s",
jobID, user));
final Job j;
try {
j = toJob(jobcol.findOne(new BasicDBObject(MONGO_ID, oi)
.append(COMPLETE, new BasicDBObject("$ne", true))));
} catch (MongoException me) {
throw new CommunicationException(
"There was a problem communicating with the database", me);
}
if (j == null) {
throw nsje;
}
try {
auth.authorizeCancel(user, j);
} catch (UJSAuthorizationException e) {
throw nsje;
}
final DBObject query = new BasicDBObject(MONGO_ID, oi);
query.put(COMPLETE, new BasicDBObject("$ne", true));
final DBObject set = new BasicDBObject(STATUS, status);
set.put(UPDATED, new Date());
set.put(CANCELEDBY, user);
set.put(COMPLETE, true);
set.put(ERROR, false);
final WriteResult wr;
try {
wr = jobcol.update(query, new BasicDBObject("$set", set));
} catch (MongoException me) {
throw new CommunicationException(
"There was a problem communicating with the database", me);
}
// this should only happen if there's a race condition and the job
// is completed/deleted between fetching the job and updating the job
if (wr.getN() != 1) {
throw nsje;
}
}
public void deleteJob(
final String user,
final String jobID,
final UJSAuthorizer auth)
throws NoSuchJobException, CommunicationException {
deleteJob(user, jobID, null, auth);
}
public void deleteJob(final String user, final String jobID,
final String service)
throws NoSuchJobException, CommunicationException {
deleteJob(user, jobID, service, new DefaultUJSAuthorizer());
}
public void deleteJob(final String user, final String jobID,
final String service, final UJSAuthorizer auth)
throws NoSuchJobException, CommunicationException {
checkString(user, "user", MAX_LEN_USER);
final ObjectId id = checkJobID(jobID);
final NoSuchJobException err = new NoSuchJobException(String.format(
"There is no deletable job %s for user %s",
jobID, user +
(service == null ? "" : " and service " + service)));
final BasicDBObject query = new BasicDBObject(MONGO_ID, id);
final Job j;
try {
if (service == null) {
j = toJob(jobcol.findOne(query.append(COMPLETE, true)));
} else {
j = toJob(jobcol.findOne(query.append(SERVICE, service)));
}
} catch (MongoException me) {
throw new CommunicationException(
"There was a problem communicating with the database", me);
}
if (j == null) {
throw err;
}
try {
auth.authorizeDelete(user, j);
} catch (UJSAuthorizationException e) {
throw err;
}
final WriteResult wr;
try {
wr = jobcol.remove(query);
} catch (MongoException me) {
throw new CommunicationException(
"There was a problem communicating with the database", me);
}
// this can only happen if the job was deleted between fetching and now
if (wr.getN() != 1) {
throw err;
}
}
public Set<String> listServices(final String user)
throws CommunicationException {
checkString(user, "user");
final DBObject query = new BasicDBObject("$or", Arrays.asList(
new BasicDBObject(USER, user),
new BasicDBObject(SHARED, user)));
query.put(SERVICE, new BasicDBObject("$ne", null));
final Set<String> services = new HashSet<String>();
try {
@SuppressWarnings("unchecked")
final List<String> servs = jobcol.distinct(SERVICE, query);
services.addAll(servs);
} catch (MongoException me) {
throw new CommunicationException(
"There was a problem communicating with the database", me);
}
return services;
}
public List<Job> listJobs(
final String user,
final List<String> services,
final boolean running,
final boolean complete,
final boolean canceled,
final boolean error,
final boolean shared)
throws CommunicationException {
try {
return listJobs(user, services, running, complete, canceled, error,
shared,
new DefaultUJSAuthorizer(),
UJSAuthorizer.DEFAULT_AUTH_STRAT,
Arrays.asList(UJSAuthorizer.DEFAULT_AUTH_PARAM));
} catch (UJSAuthorizationException e) {
throw new RuntimeException(
"Oh my God reality is crumbling around me", e);
}
}
public List<Job> listJobs(
final String user,
final List<String> services,
final boolean running,
final boolean complete,
final boolean canceled,
final boolean error,
final boolean shared,
final UJSAuthorizer auth,
final AuthorizationStrategy strat,
final List<String> authParams)
throws CommunicationException, UJSAuthorizationException {
/* Currently when specifying a non default auth strat all the
* authparams need to be readable in order to query jobs. Alternately
* this method could allow listing all owned jobs for the auth strat
* regardless of authparam readability. The authorizeRead method would
* need to return a list of readable and/or nonreadable authparameters
* and then query the database for jobs with the specified authstrat
* where the user is an owner or the authparam is readable. This means
* that different users querying with the same authparam & authstrat
* would see different job lists, which seems confusing and not user
* friendly. Futhermore, to understand what's happening the list of
* readable/unreadable auth params needs to be returned as well, which
* makes the API pretty nasty. The all or nothing method currently in
* play seems much less confusing.
*/
checkString(user, "user");
auth.authorizeRead(strat, user, authParams);
String query;
if (strat.equals(UJSAuthorizer.DEFAULT_AUTH_STRAT)) {
if (shared) {
query = String.format("{$or: [{%s: '%s'}, {%s: '%s'}]",
USER, user, SHARED, user);
} else {
query = String.format("{%s: '%s'", USER, user);
}
} else {
query = String.format("{%s: '%s', %s: {$in: ['%s']}",
AUTH_STRAT, strat.getStrat(),
AUTH_PARAM, StringUtils.join(authParams, "', '"));
}
if (services != null && !services.isEmpty()) {
for (final String s: services) {
checkString(s, "service", MAX_LEN_SERVICE);
}
query += String.format(", %s: {$in: ['%s']}", SERVICE,
StringUtils.join(services, "', '"));
} else {
query += String.format(", %s: {$ne: null}", SERVICE);
}
query = completeQuery(query, running, complete, canceled, error);
final List<Job> jobs = new LinkedList<Job>();
try {
final Iterable<Job> j = jobjong.find(query).as(Job.class);
for (final Job job: j) {
jobs.add(job);
}
} catch (MongoException me) {
throw new CommunicationException(
"There was a problem communicating with the database", me);
}
return jobs;
}
private String completeQuery(
String queryPrefix,
final boolean running,
final boolean complete,
final boolean canceled,
final boolean error) {
/* TODO ZZLATER should have a indexed state variable in the job db doc
* that is either created, running, complete, error, or canceled.
* remove error flag.
* requires DB update, but would make this much simpler.
* This is fucking dumb. Live with it for now.
*/
if (running && !complete && !canceled && !error) {
queryPrefix += ", " + COMPLETE + ": false}";
} else if (!running && complete && !canceled && !error) {
queryPrefix += ", " + COMPLETE + ": true, " + ERROR + ": false, " +
CANCELEDBY + ": {$exists: false}}";
} else if (!running && !complete && canceled && !error) {
queryPrefix += ", " + CANCELEDBY + ": {$exists: true}}";
} else if (!running && !complete && !canceled && error) {
queryPrefix += ", " + ERROR + ": true}";
} else if (running && complete && !canceled && !error) {
queryPrefix += ", " + ERROR + ": false, " +
CANCELEDBY + ": {$exists: false}}";
} else if (running && !complete && canceled && !error) {
queryPrefix += ", $or: [{" + COMPLETE + ": false}, {" +
CANCELEDBY + ": {$exists: true}}]}";
} else if (running && !complete && !canceled && error) {
queryPrefix += ", $or: [{" + COMPLETE + ": false}, {" +
ERROR + ": true}]}";
} else if (running && complete && canceled && !error) {
queryPrefix += ", " + ERROR + ": false}";
} else if (running && complete && !canceled && error) {
queryPrefix += ", " + CANCELEDBY + ": {$exists: false}}";
} else if (running && !complete && canceled && error) {
queryPrefix += ", $or: [{ " + COMPLETE + ": false}, {" +
ERROR + ": true}, {" +
CANCELEDBY + ": {$exists: true}}]}";
} else if (!running && complete && canceled && !error) {
queryPrefix += ", " + COMPLETE + ": true, " + ERROR + ": false}";
} else if (!running && complete && !canceled && error) {
queryPrefix += ", " + COMPLETE + ": true, " +
CANCELEDBY + ": {$exists: false}}";
} else if (!running && complete && canceled && error) {
queryPrefix += ", " + COMPLETE + ": true}";
} else if (!running && !complete && canceled && error) {
queryPrefix += ", $or: [{" + ERROR + ": true}, {" +
CANCELEDBY + ": {$exists: true}}]}";
} else {
queryPrefix += "}";
}
return queryPrefix;
}
//note sharing with an already shared user or sharing with the owner has
//no effect
public void shareJob(final String owner, final String jobID,
final List<String> users)
throws CommunicationException, NoSuchJobException {
final ObjectId id = checkShareParams(owner, jobID, users, "owner");
final List<String> us = new LinkedList<String>();
for (final String u: users) {
if (u != owner) {
us.add(u);
}
}
final WriteResult wr;
try {
wr = jobcol.update(
new BasicDBObject(MONGO_ID, id).append(USER, owner)
.append(AUTH_STRAT, UJSAuthorizer.DEFAULT_AUTH_STRAT.getStrat()),
new BasicDBObject("$addToSet", new BasicDBObject(SHARED,
new BasicDBObject("$each", us))));
} catch (MongoException me) {
throw new CommunicationException(
"There was a problem communicating with the database", me);
}
if (wr.getN() != 1) {
throw new NoSuchJobException(String.format(
"There is no job %s with default authorization owned by " +
"user %s", jobID, owner));
}
}
private ObjectId checkShareParams(final String user, final String jobID,
final List<String> users, final String userType) {
checkString(user, userType);
if (users == null) {
throw new IllegalArgumentException(
"The users list cannot be null");
}
if (users.isEmpty()) {
throw new IllegalArgumentException("The users list is empty");
}
for (final String u: users) {
checkString(u, "user");
}
final ObjectId id = checkJobID(jobID);
return id;
}
//removing the owner or an unshared user has no effect
public void unshareJob(final String user, final String jobID,
final List<String> users) throws CommunicationException,
NoSuchJobException {
final NoSuchJobException e = new NoSuchJobException(String.format(
"There is no job %s with default authorization visible to " +
"user %s", jobID, user));
final ObjectId id = checkShareParams(user, jobID, users, "user");
final Job j;
try {
j = getJob(id);
} catch (NoSuchJobException nsje) {
throw e;
}
if (!j.getAuthorizationStrategy().equals(
UJSAuthorizer.DEFAULT_AUTH_STRAT)) {
throw e;
}
if (j.getUser().equals(user)) {
//it's the owner, can do whatever
} else if (j.getShared().contains(user)) {
if (!users.equals(Arrays.asList(user))) {
throw new IllegalArgumentException(String.format(
"User %s may only stop sharing job %s for themselves",
user, jobID));
}
//shared user removing themselves, no prob
} else {
throw e;
}
try {
jobcol.update(
new BasicDBObject(MONGO_ID, id).append(USER, j.getUser())
.append(AUTH_STRAT, UJSAuthorizer.DEFAULT_AUTH_STRAT.getStrat()),
new BasicDBObject("$pullAll", new BasicDBObject(SHARED, users)));
} catch (MongoException me) {
throw new CommunicationException(
"There was a problem communicating with the database", me);
}
}
} |
package imagej.script;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptException;
import org.scijava.plugin.Plugin;
import org.scijava.plugin.SingletonService;
/**
* Interface for service that works with scripting languages. This service
* discovers available scripting languages, and provides convenience methods to
* interact with them.
*
* @author Johannes Schindelin
*/
public interface ScriptService extends SingletonService<ScriptLanguage> {
/**
* The script service puts the current ImageJ context into the engine's
* bindings using this key. That way, scripts can access the context by
* accessing the global variable of that name.
*/
final static String CONTEXT = "IJ";
/** Gets the index of available script languages. */
ScriptLanguageIndex getIndex();
/**
* Gets the available scripting languages, including wrapped
* {@link ScriptEngineFactory} instances available from the Java scripting
* framework itself.
* <p>
* This method is similar to {@link #getInstances()}, except that
* {@link #getInstances()} only returns {@link ScriptLanguage} subclasses
* annotated with @{@link Plugin}.
* </p>
*/
List<ScriptEngineFactory> getLanguages();
/** TODO */
ScriptEngineFactory getByFileExtension(final String fileExtension);
/** TODO */
ScriptEngineFactory getByName(final String name);
/** TODO */
Object eval(final File file) throws FileNotFoundException, ScriptException;
/** TODO */
Object eval(final String filename, final Reader reader) throws IOException,
ScriptException;
/** TODO */
boolean canHandleFile(final File file);
/** TODO */
boolean canHandleFile(final String fileName);
/** TODO */
void initialize(final ScriptEngine engine, final String fileName,
final Writer writer, final Writer errorWriter);
/** TODO */
boolean isCompiledLanguage(ScriptEngineFactory currentLanguage);
} |
package ru.job4j.task63;
/**
*Class Contains checking string origin contains sub.
*@author Dinis Saetgareev (dinis0086@mail.ru)
*@version 1.0
*@since 07.03.2017
*/
public class Contains {
/**
*method boolean contains(String origin, String sub),
*checking String origin contains String sub.
*@param origin - string
*@param sub - string
*@return true or fals
*/
public boolean contains(String origin, String sub) {
char[] arOrigin = origin.toCharArray();
char[] arSub = sub.toCharArray();
int count = 0;
for (int i = 0; i <= arOrigin.length - arSub.length; i++) {
count = 0;
if (arOrigin[i] == (arSub[0])) {
for (int j = 0; j < arSub.length; j++) {
if (arSub[j] == arOrigin[j + i]) {
count++;
}
}
if (arSub.length == count) {
return true;
}
}
}
return false;
}
} |
package com.galvarez.ttw.model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.artemis.Aspect;
import com.artemis.ComponentMapper;
import com.artemis.Entity;
import com.artemis.annotations.Wire;
import com.artemis.systems.EntityProcessingSystem;
import com.galvarez.ttw.model.components.AIControlled;
import com.galvarez.ttw.model.components.Destination;
import com.galvarez.ttw.model.components.InfluenceSource;
import com.galvarez.ttw.model.map.GameMap;
import com.galvarez.ttw.model.map.Influence;
import com.galvarez.ttw.model.map.MapPosition;
import com.galvarez.ttw.model.map.Terrain;
import com.galvarez.ttw.rendering.components.Description;
import com.galvarez.ttw.screens.overworld.OverworldScreen;
@Wire
public final class AIDestinationSystem extends EntityProcessingSystem {
private static final Logger log = LoggerFactory.getLogger(AIDestinationSystem.class);
private final GameMap map;
private ComponentMapper<Destination> destinations;
private ComponentMapper<MapPosition> positions;
private ComponentMapper<AIControlled> intelligences;
private DestinationSystem destinationSystem;
private final OverworldScreen screen;
@SuppressWarnings("unchecked")
public AIDestinationSystem(GameMap gameMap, OverworldScreen screen) {
super(Aspect.getAspectForAll(AIControlled.class, Destination.class, InfluenceSource.class));
this.map = gameMap;
this.screen = screen;
}
@Override
protected boolean checkProcessing() {
return true;
}
@Override
protected void process(Entity e) {
Destination dest = destinations.getSafe(e);
if (dest == null)
return;
AIControlled ai = intelligences.get(e);
if (dest.target == null) {
setNewTarget(e, dest, ai);
} else {
// check we are not stuck
MapPosition current = positions.get(e);
if (current.equals(ai.lastPosition)) {
// are we stuck for 3 turns?
if (screen.getTurnNumber() - ai.lastMove > 3)
setNewTarget(e, dest, ai);
} else {
ai.lastMove = screen.getTurnNumber();
ai.lastPosition = current;
}
}
}
private void setNewTarget(Entity e, Destination dest, AIControlled ai) {
// ...must find another tile to influence
int bestScore = 0;
MapPosition best = null;
for (MapPosition p : destinationSystem.getTargetTiles(e)) {
if (p.equals(dest.target))
// if it fails, do not select it again
continue;
int score = estimate(e, p);
if (score > bestScore) {
bestScore = score;
best = p;
}
}
if (best != null && !best.equals(positions.get(e))) {
destinationSystem.computePath(e, best);
ai.lastMove = screen.getTurnNumber();
ai.lastPosition = positions.get(e);
} else
log.error("Cannot find a destination for {}", e.getComponent(Description.class));
}
private int estimate(Entity e, MapPosition p) {
int score = 0;
for (MapPosition n : map.getNeighbors(p.x, p.y, 2)) {
// worst case when near other city
if (map.getEntityAt(n) != null)
score -= 10;
// some terrains are best
Terrain terrain = map.getTerrainAt(p);
if (terrain == Terrain.GRASSLAND || terrain == Terrain.PLAIN)
score += 1;
// go on the offensive!
Influence inf = map.getInfluenceAt(p);
if (!inf.isMainInfluencer(e))
score += 1;
// favor empty tiles
if (!inf.hasMainInfluence())
score *= 2;
}
return score;
}
} |
package bisq.core.offer;
import bisq.core.btc.wallet.BsqWalletService;
import bisq.core.btc.wallet.BtcWalletService;
import bisq.core.btc.wallet.TradeWalletService;
import bisq.core.dao.DaoFacade;
import bisq.core.exceptions.TradePriceOutOfToleranceException;
import bisq.core.offer.availability.DisputeAgentSelection;
import bisq.core.offer.messages.OfferAvailabilityRequest;
import bisq.core.offer.messages.OfferAvailabilityResponse;
import bisq.core.offer.placeoffer.PlaceOfferModel;
import bisq.core.offer.placeoffer.PlaceOfferProtocol;
import bisq.core.provider.price.PriceFeedService;
import bisq.core.support.dispute.arbitration.arbitrator.ArbitratorManager;
import bisq.core.support.dispute.mediation.mediator.MediatorManager;
import bisq.core.support.dispute.refund.refundagent.RefundAgentManager;
import bisq.core.trade.TradableList;
import bisq.core.trade.closed.ClosedTradableManager;
import bisq.core.trade.handlers.TransactionResultHandler;
import bisq.core.trade.statistics.TradeStatisticsManager;
import bisq.core.user.Preferences;
import bisq.core.user.User;
import bisq.core.util.Validator;
import bisq.network.p2p.AckMessage;
import bisq.network.p2p.AckMessageSourceType;
import bisq.network.p2p.BootstrapListener;
import bisq.network.p2p.DecryptedDirectMessageListener;
import bisq.network.p2p.DecryptedMessageWithPubKey;
import bisq.network.p2p.NodeAddress;
import bisq.network.p2p.P2PService;
import bisq.network.p2p.SendDirectMessageListener;
import bisq.network.p2p.peers.PeerManager;
import bisq.common.Timer;
import bisq.common.UserThread;
import bisq.common.app.Capabilities;
import bisq.common.app.Capability;
import bisq.common.app.Version;
import bisq.common.crypto.KeyRing;
import bisq.common.crypto.PubKeyRing;
import bisq.common.handlers.ErrorMessageHandler;
import bisq.common.handlers.ResultHandler;
import bisq.common.proto.network.NetworkEnvelope;
import bisq.common.proto.persistable.PersistedDataHost;
import bisq.common.storage.Storage;
import org.bitcoinj.core.Coin;
import javax.inject.Inject;
import javafx.collections.ObservableList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.jetbrains.annotations.NotNull;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkNotNull;
public class OpenOfferManager implements PeerManager.Listener, DecryptedDirectMessageListener, PersistedDataHost {
private static final Logger log = LoggerFactory.getLogger(OpenOfferManager.class);
private static final long RETRY_REPUBLISH_DELAY_SEC = 10;
private static final long REPUBLISH_AGAIN_AT_STARTUP_DELAY_SEC = 30;
private static final long REPUBLISH_INTERVAL_MS = TimeUnit.MINUTES.toMillis(40);
private static final long REFRESH_INTERVAL_MS = TimeUnit.MINUTES.toMillis(6);
private final CreateOfferService createOfferService;
private final KeyRing keyRing;
private final User user;
private final P2PService p2PService;
private final BtcWalletService btcWalletService;
private final TradeWalletService tradeWalletService;
private final BsqWalletService bsqWalletService;
private final OfferBookService offerBookService;
private final ClosedTradableManager closedTradableManager;
private final PriceFeedService priceFeedService;
private final Preferences preferences;
private final TradeStatisticsManager tradeStatisticsManager;
private final ArbitratorManager arbitratorManager;
private final MediatorManager mediatorManager;
private final RefundAgentManager refundAgentManager;
private final DaoFacade daoFacade;
private final Storage<TradableList<OpenOffer>> openOfferTradableListStorage;
private final Map<String, OpenOffer> offersToBeEdited = new HashMap<>();
private boolean stopped;
private Timer periodicRepublishOffersTimer, periodicRefreshOffersTimer, retryRepublishOffersTimer;
private TradableList<OpenOffer> openOffers;
// Constructor, Initialization
@Inject
public OpenOfferManager(CreateOfferService createOfferService,
KeyRing keyRing,
User user,
P2PService p2PService,
BtcWalletService btcWalletService,
TradeWalletService tradeWalletService,
BsqWalletService bsqWalletService,
OfferBookService offerBookService,
ClosedTradableManager closedTradableManager,
PriceFeedService priceFeedService,
Preferences preferences,
TradeStatisticsManager tradeStatisticsManager,
ArbitratorManager arbitratorManager,
MediatorManager mediatorManager,
RefundAgentManager refundAgentManager,
DaoFacade daoFacade,
Storage<TradableList<OpenOffer>> storage) {
this.createOfferService = createOfferService;
this.keyRing = keyRing;
this.user = user;
this.p2PService = p2PService;
this.btcWalletService = btcWalletService;
this.tradeWalletService = tradeWalletService;
this.bsqWalletService = bsqWalletService;
this.offerBookService = offerBookService;
this.closedTradableManager = closedTradableManager;
this.priceFeedService = priceFeedService;
this.preferences = preferences;
this.tradeStatisticsManager = tradeStatisticsManager;
this.arbitratorManager = arbitratorManager;
this.mediatorManager = mediatorManager;
this.refundAgentManager = refundAgentManager;
this.daoFacade = daoFacade;
openOfferTradableListStorage = storage;
// In case the app did get killed the shutDown from the modules is not called, so we use a shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
UserThread.execute(OpenOfferManager.this::shutDown);
}, "OpenOfferManager.ShutDownHook"));
}
@Override
public void readPersisted() {
openOffers = new TradableList<>(openOfferTradableListStorage, "OpenOffers");
openOffers.forEach(e -> {
Offer offer = e.getOffer();
offer.setPriceFeedService(priceFeedService);
});
}
public void onAllServicesInitialized() {
p2PService.addDecryptedDirectMessageListener(this);
if (p2PService.isBootstrapped()) {
onBootstrapComplete();
} else {
p2PService.addP2PServiceListener(new BootstrapListener() {
@Override
public void onUpdatedDataReceived() {
onBootstrapComplete();
}
});
}
cleanUpAddressEntries();
}
private void cleanUpAddressEntries() {
Set<String> openOffersIdSet = openOffers.getList().stream().map(OpenOffer::getId).collect(Collectors.toSet());
btcWalletService.getAddressEntriesForOpenOffer().stream()
.filter(e -> !openOffersIdSet.contains(e.getOfferId()))
.forEach(e -> {
log.warn("We found an outdated addressEntry for openOffer {} (openOffers does not contain that " +
"offer), offers.size={}",
e.getOfferId(), openOffers.size());
btcWalletService.resetAddressEntriesForOpenOffer(e.getOfferId());
});
}
private void shutDown() {
shutDown(null);
}
public void shutDown(@Nullable Runnable completeHandler) {
stopped = true;
p2PService.getPeerManager().removeListener(this);
p2PService.removeDecryptedDirectMessageListener(this);
stopPeriodicRefreshOffersTimer();
stopPeriodicRepublishOffersTimer();
stopRetryRepublishOffersTimer();
// we remove own offers from offerbook when we go offline
// Normally we use a delay for broadcasting to the peers, but at shut down we want to get it fast out
int size = openOffers != null ? openOffers.size() : 0;
log.info("Remove open offers at shutDown. Number of open offers: {}", size);
if (offerBookService.isBootstrapped() && size > 0) {
openOffers.forEach(openOffer -> offerBookService.removeOfferAtShutDown(openOffer.getOffer().getOfferPayload()));
if (completeHandler != null)
UserThread.runAfter(completeHandler, size * 200 + 500, TimeUnit.MILLISECONDS);
} else {
if (completeHandler != null)
completeHandler.run();
}
}
public void removeAllOpenOffers(@Nullable Runnable completeHandler) {
removeOpenOffers(getObservableList(), completeHandler);
}
private void removeOpenOffers(List<OpenOffer> openOffers, @Nullable Runnable completeHandler) {
final int size = openOffers.size();
// Copy list as we remove in the loop
List<OpenOffer> openOffersList = new ArrayList<>(openOffers);
openOffersList.forEach(openOffer -> removeOpenOffer(openOffer, () -> {
}, errorMessage -> {
}));
if (completeHandler != null)
UserThread.runAfter(completeHandler, size * 200 + 500, TimeUnit.MILLISECONDS);
}
// DecryptedDirectMessageListener implementation
@Override
public void onDirectMessage(DecryptedMessageWithPubKey decryptedMessageWithPubKey, NodeAddress peerNodeAddress) {
// Handler for incoming offer availability requests
// We get an encrypted message but don't do the signature check as we don't know the peer yet.
// A basic sig check is in done also at decryption time
NetworkEnvelope networkEnvelope = decryptedMessageWithPubKey.getNetworkEnvelope();
if (networkEnvelope instanceof OfferAvailabilityRequest) {
handleOfferAvailabilityRequest((OfferAvailabilityRequest) networkEnvelope, peerNodeAddress);
} else if (networkEnvelope instanceof AckMessage) {
AckMessage ackMessage = (AckMessage) networkEnvelope;
if (ackMessage.getSourceType() == AckMessageSourceType.OFFER_MESSAGE) {
if (ackMessage.isSuccess()) {
log.info("Received AckMessage for {} with offerId {} and uid {}",
ackMessage.getSourceMsgClassName(), ackMessage.getSourceId(), ackMessage.getSourceUid());
} else {
log.warn("Received AckMessage with error state for {} with offerId {} and errorMessage={}",
ackMessage.getSourceMsgClassName(), ackMessage.getSourceId(), ackMessage.getErrorMessage());
}
}
}
}
// BootstrapListener delegate
private void onBootstrapComplete() {
stopped = false;
maybeUpdatePersistedOffers();
// Republish means we send the complete offer object
republishOffers();
startPeriodicRepublishOffersTimer();
// Refresh is started once we get a success from republish
// We republish after a bit as it might be that our connected node still has the offer in the data map
// but other peers have it already removed because of expired TTL.
// Those other not directly connected peers would not get the broadcast of the new offer, as the first
// connected peer (seed node) does not broadcast if it has the data in the map.
// To update quickly to the whole network we repeat the republishOffers call after a few seconds when we
// are better connected to the network. There is no guarantee that all peers will receive it but we also
// have our periodic timer, so after that longer interval the offer should be available to all peers.
if (retryRepublishOffersTimer == null)
retryRepublishOffersTimer = UserThread.runAfter(OpenOfferManager.this::republishOffers,
REPUBLISH_AGAIN_AT_STARTUP_DELAY_SEC);
p2PService.getPeerManager().addListener(this);
}
// PeerManager.Listener implementation
@Override
public void onAllConnectionsLost() {
log.info("onAllConnectionsLost");
stopped = true;
stopPeriodicRefreshOffersTimer();
stopPeriodicRepublishOffersTimer();
stopRetryRepublishOffersTimer();
restart();
}
@Override
public void onNewConnectionAfterAllConnectionsLost() {
log.info("onNewConnectionAfterAllConnectionsLost");
stopped = false;
restart();
}
@Override
public void onAwakeFromStandby() {
log.info("onAwakeFromStandby");
stopped = false;
if (!p2PService.getNetworkNode().getAllConnections().isEmpty())
restart();
}
// API
public void placeOffer(Offer offer,
double buyerSecurityDeposit,
boolean useSavingsWallet,
TransactionResultHandler resultHandler,
ErrorMessageHandler errorMessageHandler) {
checkNotNull(offer.getMakerFee(), "makerFee must not be null");
Coin reservedFundsForOffer = createOfferService.getReservedFundsForOffer(offer.getDirection(),
offer.getAmount(),
buyerSecurityDeposit,
createOfferService.getSellerSecurityDepositAsDouble());
PlaceOfferModel model = new PlaceOfferModel(offer,
reservedFundsForOffer,
useSavingsWallet,
btcWalletService,
tradeWalletService,
bsqWalletService,
offerBookService,
arbitratorManager,
tradeStatisticsManager,
daoFacade,
user);
PlaceOfferProtocol placeOfferProtocol = new PlaceOfferProtocol(
model,
transaction -> {
OpenOffer openOffer = new OpenOffer(offer, openOfferTradableListStorage);
openOffers.add(openOffer);
openOfferTradableListStorage.queueUpForSave();
resultHandler.handleResult(transaction);
if (!stopped) {
startPeriodicRepublishOffersTimer();
startPeriodicRefreshOffersTimer();
} else {
log.debug("We have stopped already. We ignore that placeOfferProtocol.placeOffer.onResult call.");
}
},
errorMessageHandler
);
placeOfferProtocol.placeOffer();
}
// Remove from offerbook
public void removeOffer(Offer offer, ResultHandler resultHandler, ErrorMessageHandler errorMessageHandler) {
Optional<OpenOffer> openOfferOptional = getOpenOfferById(offer.getId());
if (openOfferOptional.isPresent()) {
removeOpenOffer(openOfferOptional.get(), resultHandler, errorMessageHandler);
} else {
log.warn("Offer was not found in our list of open offers. We still try to remove it from the offerbook.");
errorMessageHandler.handleErrorMessage("Offer was not found in our list of open offers. " +
"We still try to remove it from the offerbook.");
offerBookService.removeOffer(offer.getOfferPayload(),
() -> offer.setState(Offer.State.REMOVED),
null);
}
}
public void activateOpenOffer(OpenOffer openOffer,
ResultHandler resultHandler,
ErrorMessageHandler errorMessageHandler) {
if (!offersToBeEdited.containsKey(openOffer.getId())) {
Offer offer = openOffer.getOffer();
openOffer.setStorage(openOfferTradableListStorage);
offerBookService.activateOffer(offer,
() -> {
openOffer.setState(OpenOffer.State.AVAILABLE);
log.debug("activateOpenOffer, offerId={}", offer.getId());
resultHandler.handleResult();
},
errorMessageHandler);
} else {
errorMessageHandler.handleErrorMessage("You can't activate an offer that is currently edited.");
}
}
public void deactivateOpenOffer(OpenOffer openOffer,
ResultHandler resultHandler,
ErrorMessageHandler errorMessageHandler) {
Offer offer = openOffer.getOffer();
openOffer.setStorage(openOfferTradableListStorage);
offerBookService.deactivateOffer(offer.getOfferPayload(),
() -> {
openOffer.setState(OpenOffer.State.DEACTIVATED);
log.debug("deactivateOpenOffer, offerId={}", offer.getId());
resultHandler.handleResult();
},
errorMessageHandler);
}
public void removeOpenOffer(OpenOffer openOffer,
ResultHandler resultHandler,
ErrorMessageHandler errorMessageHandler) {
if (!offersToBeEdited.containsKey(openOffer.getId())) {
Offer offer = openOffer.getOffer();
if (openOffer.isDeactivated()) {
openOffer.setStorage(openOfferTradableListStorage);
onRemoved(openOffer, resultHandler, offer);
} else {
offerBookService.removeOffer(offer.getOfferPayload(),
() -> onRemoved(openOffer, resultHandler, offer),
errorMessageHandler);
}
} else {
errorMessageHandler.handleErrorMessage("You can't remove an offer that is currently edited.");
}
}
public void editOpenOfferStart(OpenOffer openOffer,
ResultHandler resultHandler,
ErrorMessageHandler errorMessageHandler) {
if (offersToBeEdited.containsKey(openOffer.getId())) {
log.warn("editOpenOfferStart called for an offer which is already in edit mode.");
resultHandler.handleResult();
return;
}
offersToBeEdited.put(openOffer.getId(), openOffer);
if (openOffer.isDeactivated()) {
resultHandler.handleResult();
} else {
deactivateOpenOffer(openOffer,
resultHandler,
errorMessage -> {
offersToBeEdited.remove(openOffer.getId());
errorMessageHandler.handleErrorMessage(errorMessage);
});
}
}
public void editOpenOfferPublish(Offer editedOffer,
OpenOffer.State originalState,
ResultHandler resultHandler,
ErrorMessageHandler errorMessageHandler) {
Optional<OpenOffer> openOfferOptional = getOpenOfferById(editedOffer.getId());
if (openOfferOptional.isPresent()) {
final OpenOffer openOffer = openOfferOptional.get();
openOffer.setStorage(openOfferTradableListStorage);
openOffer.getOffer().setState(Offer.State.REMOVED);
openOffer.setState(OpenOffer.State.CANCELED);
openOffers.remove(openOffer);
final OpenOffer editedOpenOffer = new OpenOffer(editedOffer, openOfferTradableListStorage);
editedOpenOffer.setState(originalState);
openOffers.add(editedOpenOffer);
if (!editedOpenOffer.isDeactivated())
republishOffer(editedOpenOffer);
offersToBeEdited.remove(openOffer.getId());
resultHandler.handleResult();
} else {
errorMessageHandler.handleErrorMessage("There is no offer with this id existing to be published.");
}
}
public void editOpenOfferCancel(OpenOffer openOffer,
OpenOffer.State originalState,
ResultHandler resultHandler,
ErrorMessageHandler errorMessageHandler) {
if (offersToBeEdited.containsKey(openOffer.getId())) {
offersToBeEdited.remove(openOffer.getId());
if (originalState.equals(OpenOffer.State.AVAILABLE)) {
activateOpenOffer(openOffer, resultHandler, errorMessageHandler);
} else {
resultHandler.handleResult();
}
} else {
errorMessageHandler.handleErrorMessage("Editing of offer can't be canceled as it is not edited.");
}
}
private void onRemoved(@NotNull OpenOffer openOffer, ResultHandler resultHandler, Offer offer) {
offer.setState(Offer.State.REMOVED);
openOffer.setState(OpenOffer.State.CANCELED);
openOffers.remove(openOffer);
closedTradableManager.add(openOffer);
log.info("onRemoved offerId={}", offer.getId());
btcWalletService.resetAddressEntriesForOpenOffer(offer.getId());
resultHandler.handleResult();
}
// Close openOffer after deposit published
public void closeOpenOffer(Offer offer) {
getOpenOfferById(offer.getId()).ifPresent(openOffer -> {
openOffers.remove(openOffer);
openOffer.setState(OpenOffer.State.CLOSED);
offerBookService.removeOffer(openOffer.getOffer().getOfferPayload(),
() -> log.trace("Successful removed offer"),
log::error);
});
}
public void reserveOpenOffer(OpenOffer openOffer) {
openOffer.setState(OpenOffer.State.RESERVED);
}
// Getters
public boolean isMyOffer(Offer offer) {
return offer.isMyOffer(keyRing);
}
public ObservableList<OpenOffer> getObservableList() {
return openOffers.getList();
}
public Optional<OpenOffer> getOpenOfferById(String offerId) {
return openOffers.stream().filter(e -> e.getId().equals(offerId)).findFirst();
}
// OfferPayload Availability
private void handleOfferAvailabilityRequest(OfferAvailabilityRequest request, NodeAddress peer) {
log.info("Received OfferAvailabilityRequest from {} with offerId {} and uid {}",
peer, request.getOfferId(), request.getUid());
boolean result = false;
String errorMessage = null;
if (!p2PService.isBootstrapped()) {
errorMessage = "We got a handleOfferAvailabilityRequest but we have not bootstrapped yet.";
log.info(errorMessage);
sendAckMessage(request, peer, false, errorMessage);
return;
}
if (stopped) {
errorMessage = "We have stopped already. We ignore that handleOfferAvailabilityRequest call.";
log.debug(errorMessage);
sendAckMessage(request, peer, false, errorMessage);
return;
}
try {
Validator.nonEmptyStringOf(request.offerId);
checkNotNull(request.getPubKeyRing());
} catch (Throwable t) {
errorMessage = "Message validation failed. Error=" + t.toString() + ", Message=" + request.toString();
log.warn(errorMessage);
sendAckMessage(request, peer, false, errorMessage);
return;
}
try {
Optional<OpenOffer> openOfferOptional = getOpenOfferById(request.offerId);
AvailabilityResult availabilityResult;
NodeAddress arbitratorNodeAddress = null;
NodeAddress mediatorNodeAddress = null;
NodeAddress refundAgentNodeAddress = null;
if (openOfferOptional.isPresent()) {
OpenOffer openOffer = openOfferOptional.get();
if (openOffer.getState() == OpenOffer.State.AVAILABLE) {
Offer offer = openOffer.getOffer();
if (preferences.getIgnoreTradersList().stream().noneMatch(fullAddress -> fullAddress.equals(peer.getFullAddress()))) {
availabilityResult = AvailabilityResult.AVAILABLE;
mediatorNodeAddress = DisputeAgentSelection.getLeastUsedMediator(tradeStatisticsManager, mediatorManager).getNodeAddress();
openOffer.setMediatorNodeAddress(mediatorNodeAddress);
refundAgentNodeAddress = DisputeAgentSelection.getLeastUsedRefundAgent(tradeStatisticsManager, refundAgentManager).getNodeAddress();
openOffer.setRefundAgentNodeAddress(refundAgentNodeAddress);
try {
// Check also tradePrice to avoid failures after taker fee is paid caused by a too big difference
// in trade price between the peers. Also here poor connectivity might cause market price API connection
// losses and therefore an outdated market price.
offer.checkTradePriceTolerance(request.getTakersTradePrice());
} catch (TradePriceOutOfToleranceException e) {
log.warn("Trade price check failed because takers price is outside out tolerance.");
availabilityResult = AvailabilityResult.PRICE_OUT_OF_TOLERANCE;
} catch (MarketPriceNotAvailableException e) {
log.warn(e.getMessage());
availabilityResult = AvailabilityResult.MARKET_PRICE_NOT_AVAILABLE;
} catch (Throwable e) {
log.warn("Trade price check failed. " + e.getMessage());
availabilityResult = AvailabilityResult.UNKNOWN_FAILURE;
}
} else {
availabilityResult = AvailabilityResult.USER_IGNORED;
}
} else {
availabilityResult = AvailabilityResult.OFFER_TAKEN;
}
} else {
log.warn("handleOfferAvailabilityRequest: openOffer not found. That should never happen.");
availabilityResult = AvailabilityResult.OFFER_TAKEN;
}
OfferAvailabilityResponse offerAvailabilityResponse = new OfferAvailabilityResponse(request.offerId,
availabilityResult,
arbitratorNodeAddress,
mediatorNodeAddress,
refundAgentNodeAddress);
log.info("Send {} with offerId {} and uid {} to peer {}",
offerAvailabilityResponse.getClass().getSimpleName(), offerAvailabilityResponse.getOfferId(),
offerAvailabilityResponse.getUid(), peer);
p2PService.sendEncryptedDirectMessage(peer,
request.getPubKeyRing(),
offerAvailabilityResponse,
new SendDirectMessageListener() {
@Override
public void onArrived() {
log.info("{} arrived at peer: offerId={}; uid={}",
offerAvailabilityResponse.getClass().getSimpleName(),
offerAvailabilityResponse.getOfferId(),
offerAvailabilityResponse.getUid());
}
@Override
public void onFault(String errorMessage) {
log.error("Sending {} failed: uid={}; peer={}; error={}",
offerAvailabilityResponse.getClass().getSimpleName(),
offerAvailabilityResponse.getUid(),
peer,
errorMessage);
}
});
result = true;
} catch (Throwable t) {
errorMessage = "Exception at handleRequestIsOfferAvailableMessage " + t.getMessage();
log.error(errorMessage);
t.printStackTrace();
} finally {
sendAckMessage(request, peer, result, errorMessage);
}
}
private void sendAckMessage(OfferAvailabilityRequest message,
NodeAddress sender,
boolean result,
String errorMessage) {
String offerId = message.getOfferId();
String sourceUid = message.getUid();
AckMessage ackMessage = new AckMessage(p2PService.getNetworkNode().getNodeAddress(),
AckMessageSourceType.OFFER_MESSAGE,
message.getClass().getSimpleName(),
sourceUid,
offerId,
result,
errorMessage);
final NodeAddress takersNodeAddress = sender;
PubKeyRing takersPubKeyRing = message.getPubKeyRing();
log.info("Send AckMessage for OfferAvailabilityRequest to peer {} with offerId {} and sourceUid {}",
takersNodeAddress, offerId, ackMessage.getSourceUid());
p2PService.sendEncryptedDirectMessage(
takersNodeAddress,
takersPubKeyRing,
ackMessage,
new SendDirectMessageListener() {
@Override
public void onArrived() {
log.info("AckMessage for OfferAvailabilityRequest arrived at takersNodeAddress {}. offerId={}, sourceUid={}",
takersNodeAddress, offerId, ackMessage.getSourceUid());
}
@Override
public void onFault(String errorMessage) {
log.error("AckMessage for OfferAvailabilityRequest failed. AckMessage={}, takersNodeAddress={}, errorMessage={}",
ackMessage, takersNodeAddress, errorMessage);
}
}
);
}
// Update persisted offer if a new capability is required after a software update
private void maybeUpdatePersistedOffers() {
// We need to clone to avoid ConcurrentModificationException
ArrayList<OpenOffer> openOffersClone = new ArrayList<>(openOffers.getList());
openOffersClone.forEach(originalOpenOffer -> {
Offer originalOffer = originalOpenOffer.getOffer();
OfferPayload originalOfferPayload = originalOffer.getOfferPayload();
// We added CAPABILITIES with entry for Capability.MEDIATION in v1.1.6 and
// Capability.REFUND_AGENT in v1.2.0 and want to rewrite a
// persisted offer after the user has updated to 1.2.0 so their offer will be accepted by the network.
if (originalOfferPayload.getProtocolVersion() < Version.TRADE_PROTOCOL_VERSION ||
!OfferRestrictions.hasOfferMandatoryCapability(originalOffer, Capability.MEDIATION) ||
!OfferRestrictions.hasOfferMandatoryCapability(originalOffer, Capability.REFUND_AGENT) ||
!originalOfferPayload.getOwnerNodeAddress().equals(p2PService.getAddress())) {
// - Capabilities changed?
// We rewrite our offer with the additional capabilities entry
Map<String, String> updatedExtraDataMap = new HashMap<>();
if (!OfferRestrictions.hasOfferMandatoryCapability(originalOffer, Capability.MEDIATION) ||
!OfferRestrictions.hasOfferMandatoryCapability(originalOffer, Capability.REFUND_AGENT)) {
Map<String, String> originalExtraDataMap = originalOfferPayload.getExtraDataMap();
if (originalExtraDataMap != null) {
updatedExtraDataMap.putAll(originalExtraDataMap);
}
// We overwrite any entry with our current capabilities
updatedExtraDataMap.put(OfferPayload.CAPABILITIES, Capabilities.app.toStringList());
log.info("Converted offer to support new Capability.MEDIATION and Capability.REFUND_AGENT capability. id={}", originalOffer.getId());
} else {
updatedExtraDataMap = originalOfferPayload.getExtraDataMap();
}
// - Protocol version changed?
int protocolVersion = originalOfferPayload.getProtocolVersion();
if (protocolVersion < Version.TRADE_PROTOCOL_VERSION) {
// We update the trade protocol version
protocolVersion = Version.TRADE_PROTOCOL_VERSION;
log.info("Updated the protocol version of offer id={}", originalOffer.getId());
}
// - node address changed? (due to a faulty tor dir)
NodeAddress ownerNodeAddress = originalOfferPayload.getOwnerNodeAddress();
if (!ownerNodeAddress.equals(p2PService.getAddress())) {
ownerNodeAddress = p2PService.getAddress();
log.info("Updated the owner nodeaddress of offer id={}", originalOffer.getId());
}
OfferPayload updatedPayload = new OfferPayload(originalOfferPayload.getId(),
originalOfferPayload.getDate(),
ownerNodeAddress,
originalOfferPayload.getPubKeyRing(),
originalOfferPayload.getDirection(),
originalOfferPayload.getPrice(),
originalOfferPayload.getMarketPriceMargin(),
originalOfferPayload.isUseMarketBasedPrice(),
originalOfferPayload.getAmount(),
originalOfferPayload.getMinAmount(),
originalOfferPayload.getBaseCurrencyCode(),
originalOfferPayload.getCounterCurrencyCode(),
originalOfferPayload.getArbitratorNodeAddresses(),
originalOfferPayload.getMediatorNodeAddresses(),
originalOfferPayload.getPaymentMethodId(),
originalOfferPayload.getMakerPaymentAccountId(),
originalOfferPayload.getOfferFeePaymentTxId(),
originalOfferPayload.getCountryCode(),
originalOfferPayload.getAcceptedCountryCodes(),
originalOfferPayload.getBankId(),
originalOfferPayload.getAcceptedBankIds(),
originalOfferPayload.getVersionNr(),
originalOfferPayload.getBlockHeightAtOfferCreation(),
originalOfferPayload.getTxFee(),
originalOfferPayload.getMakerFee(),
originalOfferPayload.isCurrencyForMakerFeeBtc(),
originalOfferPayload.getBuyerSecurityDeposit(),
originalOfferPayload.getSellerSecurityDeposit(),
originalOfferPayload.getMaxTradeLimit(),
originalOfferPayload.getMaxTradePeriod(),
originalOfferPayload.isUseAutoClose(),
originalOfferPayload.isUseReOpenAfterAutoClose(),
originalOfferPayload.getLowerClosePrice(),
originalOfferPayload.getUpperClosePrice(),
originalOfferPayload.isPrivateOffer(),
originalOfferPayload.getHashOfChallenge(),
updatedExtraDataMap,
protocolVersion);
// Save states from original data to use for the updated
Offer.State originalOfferState = originalOffer.getState();
OpenOffer.State originalOpenOfferState = originalOpenOffer.getState();
// remove old offer
originalOffer.setState(Offer.State.REMOVED);
originalOpenOffer.setState(OpenOffer.State.CANCELED);
originalOpenOffer.setStorage(openOfferTradableListStorage);
openOffers.remove(originalOpenOffer);
// Create new Offer
Offer updatedOffer = new Offer(updatedPayload);
updatedOffer.setPriceFeedService(priceFeedService);
updatedOffer.setState(originalOfferState);
OpenOffer updatedOpenOffer = new OpenOffer(updatedOffer, openOfferTradableListStorage);
updatedOpenOffer.setState(originalOpenOfferState);
updatedOpenOffer.setStorage(openOfferTradableListStorage);
openOffers.add(updatedOpenOffer);
log.info("Updating offer completed. id={}", originalOffer.getId());
}
});
}
// RepublishOffers, refreshOffers
private void republishOffers() {
int size = openOffers.size();
final ArrayList<OpenOffer> openOffersList = new ArrayList<>(openOffers.getList());
if (!stopped) {
stopPeriodicRefreshOffersTimer();
for (int i = 0; i < size; i++) {
// we delay to avoid reaching throttle limits
long delay = 700;
final long minDelay = (i + 1) * delay;
final long maxDelay = (i + 2) * delay;
final OpenOffer openOffer = openOffersList.get(i);
UserThread.runAfterRandomDelay(() -> {
if (openOffers.contains(openOffer)) {
String id = openOffer.getId();
if (id != null && !openOffer.isDeactivated())
republishOffer(openOffer);
}
}, minDelay, maxDelay, TimeUnit.MILLISECONDS);
}
} else {
log.debug("We have stopped already. We ignore that republishOffers call.");
}
}
private void republishOffer(OpenOffer openOffer) {
offerBookService.addOffer(openOffer.getOffer(),
() -> {
if (!stopped) {
log.debug("Successfully added offer to P2P network.");
// Refresh means we send only the data needed to refresh the TTL (hash, signature and sequence no.)
if (periodicRefreshOffersTimer == null)
startPeriodicRefreshOffersTimer();
} else {
log.debug("We have stopped already. We ignore that offerBookService.republishOffers.onSuccess call.");
}
},
errorMessage -> {
if (!stopped) {
log.error("Adding offer to P2P network failed. " + errorMessage);
stopRetryRepublishOffersTimer();
retryRepublishOffersTimer = UserThread.runAfter(OpenOfferManager.this::republishOffers,
RETRY_REPUBLISH_DELAY_SEC);
} else {
log.debug("We have stopped already. We ignore that offerBookService.republishOffers.onFault call.");
}
});
openOffer.setStorage(openOfferTradableListStorage);
}
private void startPeriodicRepublishOffersTimer() {
stopped = false;
if (periodicRepublishOffersTimer == null)
periodicRepublishOffersTimer = UserThread.runPeriodically(() -> {
if (!stopped) {
republishOffers();
} else {
log.debug("We have stopped already. We ignore that periodicRepublishOffersTimer.run call.");
}
},
REPUBLISH_INTERVAL_MS,
TimeUnit.MILLISECONDS);
else
log.trace("periodicRepublishOffersTimer already stated");
}
private void startPeriodicRefreshOffersTimer() {
stopped = false;
// refresh sufficiently before offer would expire
if (periodicRefreshOffersTimer == null)
periodicRefreshOffersTimer = UserThread.runPeriodically(() -> {
if (!stopped) {
int size = openOffers.size();
//we clone our list as openOffers might change during our delayed call
final ArrayList<OpenOffer> openOffersList = new ArrayList<>(openOffers.getList());
for (int i = 0; i < size; i++) {
// we delay to avoid reaching throttle limits
// roughly 4 offers per second
long delay = 300;
final long minDelay = (i + 1) * delay;
final long maxDelay = (i + 2) * delay;
final OpenOffer openOffer = openOffersList.get(i);
UserThread.runAfterRandomDelay(() -> {
// we need to check if in the meantime the offer has been removed
if (openOffers.contains(openOffer) && !openOffer.isDeactivated())
refreshOffer(openOffer);
}, minDelay, maxDelay, TimeUnit.MILLISECONDS);
}
} else {
log.debug("We have stopped already. We ignore that periodicRefreshOffersTimer.run call.");
}
},
REFRESH_INTERVAL_MS,
TimeUnit.MILLISECONDS);
else
log.trace("periodicRefreshOffersTimer already stated");
}
private void refreshOffer(OpenOffer openOffer) {
offerBookService.refreshTTL(openOffer.getOffer().getOfferPayload(),
() -> log.debug("Successful refreshed TTL for offer"),
log::warn);
}
private void restart() {
log.debug("Restart after connection loss");
if (retryRepublishOffersTimer == null)
retryRepublishOffersTimer = UserThread.runAfter(() -> {
stopped = false;
stopRetryRepublishOffersTimer();
republishOffers();
}, RETRY_REPUBLISH_DELAY_SEC);
startPeriodicRepublishOffersTimer();
}
// Private
private void stopPeriodicRefreshOffersTimer() {
if (periodicRefreshOffersTimer != null) {
periodicRefreshOffersTimer.stop();
periodicRefreshOffersTimer = null;
}
}
private void stopPeriodicRepublishOffersTimer() {
if (periodicRepublishOffersTimer != null) {
periodicRepublishOffersTimer.stop();
periodicRepublishOffersTimer = null;
}
}
private void stopRetryRepublishOffersTimer() {
if (retryRepublishOffersTimer != null) {
retryRepublishOffersTimer.stop();
retryRepublishOffersTimer = null;
}
}
} |
package brooklyn.entity.trait;
import java.beans.PropertyChangeListener;
import brooklyn.util.internal.SerializableObservableList;
import brooklyn.util.internal.SerializableObservableMap;
/**
* A collection of entities that can change.
*/
public interface Changeable {
/**
* Implement this method to add a {@link PropertyChangeListener} on
* some collection of entities.
*
* The entity collection should be a {@link SerializableObservableList}
* or a {@link SerializableObservableMap} wrapper.
*/
public void addEntityChangeListener(PropertyChangeListener listener);
} |
package com.vmware.config;
import com.vmware.scm.Git;
import com.vmware.ServiceLocator;
import com.vmware.action.BaseAction;
import com.vmware.util.ArrayUtils;
import com.vmware.util.CommitConfiguration;
import com.vmware.util.StringUtils;
import com.google.gson.annotations.Expose;
import com.vmware.util.exception.RuntimeReflectiveOperationException;
import com.vmware.util.logging.LogLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeMap;
import static com.vmware.util.ArrayUtils.contains;
/**
* Workflow configuration.
* All configuration is contained in this class.
*/
public class WorkflowConfig {
private static Logger log = LoggerFactory.getLogger(WorkflowConfig.class.getName());
@Expose(serialize = false, deserialize = false)
private Git git = new Git();
@Expose(serialize = false, deserialize = false)
public Map<String, String> overriddenConfigSources = new TreeMap<String, String>();
@Expose(serialize = false, deserialize = false)
public List<Class<? extends BaseAction>> workFlowActions;
@Expose(serialize = false, deserialize = false)
public List<Field> configurableFields = new ArrayList<Field>();
@Expose(serialize = false, deserialize = false)
public String loadedConfigFiles;
@ConfigurableProperty(help = "Label for testing done section")
public String testingDoneLabel;
@ConfigurableProperty(help = "Label for bug number")
public String bugNumberLabel;
@ConfigurableProperty(help = "Label for reviewed by")
public String reviewedByLabel;
@ConfigurableProperty(help = "Label for review url")
public String reviewUrlLabel;
@ConfigurableProperty(help = "Label for no bug number")
public String noBugNumberLabel;
@ConfigurableProperty(help = "Label for trivial reviewer")
public String trivialReviewerLabel;
@ConfigurableProperty(commandLine = "-u,--username", help = "Username to use for jenkins, jira and review board")
public String username;
@ConfigurableProperty(commandLine = "-reviewboardUrl,--reviewboard-url", help = "Url for review board server", gitConfigProperty = "reviewboard.url")
public String reviewboardUrl;
@ConfigurableProperty(commandLine = "-reviewRepo,--review-board-repo", help = "Review board repository")
public String reviewBoardRepository;
@ConfigurableProperty(commandLine = "-rbDateFormat,--review-board-date-format", help = "Date format used by review board. Can change between review board versions")
public String reviewBoardDateFormat;
@ConfigurableProperty(commandLine = "-jenkinsUrl,--jenkins-url", help = "Url for jenkins server")
public String jenkinsUrl;
@ConfigurableProperty(commandLine = "-buildwebUrl,--buildweb-url", help = "Url for buildweb server")
public String buildwebUrl;
@ConfigurableProperty(commandLine = "-buildwebApiUrl,--buildweb-api-url", help = "Api Url for buildweb server")
public String buildwebApiUrl;
@ConfigurableProperty(commandLine = "-jcsrf,--jenkins-uses-csrf", help = "Whether the jenkins server uses CSRF header")
public boolean jenkinsUsesCsrf;
@ConfigurableProperty(commandLine = "-jiraUrl,--jira-url", help = "Url for jira server")
public String jiraUrl;
@ConfigurableProperty(commandLine = "-jiraTestIssue,--jira-test-issue", help = "Issue key to fetch to test user is logged in")
public String jiraTestIssue;
@ConfigurableProperty(commandLine = "-disableJira,--disable-jira", help = "Don't use Jira when checking bug numbers")
public boolean disableJira;
@ConfigurableProperty(commandLine = "-bugzillaUrl,--bugzilla-url", help = "Url for Bugzilla server")
public String bugzillaUrl;
@ConfigurableProperty(commandLine = "-bugzillaTestBug,--bugzilla-test-bug", help = "Bug number to fetch to test user is logged in")
public int bugzillaTestBug;
@ConfigurableProperty(commandLine = "-disableBugzilla,--disable-bugzilla", help = "Don't use Bugzilla when checking bug numbers")
public boolean disableBugzilla;
@ConfigurableProperty(commandLine = "-bugzillaQuery,--bugzilla-query", help = "Named query in bugzilla to execute for loading assigned bugs")
public String bugzillaQuery;
@ConfigurableProperty(commandLine = "-trelloUrl,--trello-url", help = "Url for trello server")
public String trelloUrl;
@ConfigurableProperty(commandLine = "-p4Client,--perforce-client", gitConfigProperty = "git-p4.client", help = "Perforce client to use")
public String perforceClientName;
@ConfigurableProperty(gitConfigProperty = "changesetsync.checkoutdir", help = "Perforce client root directory can be explicitly specified if desired")
public String perforceClientDirectory;
@ConfigurableProperty(commandLine = "-syncToBranchLatest,--sync-to-branch-latest", help = "By default, files to be synced to the latest in perforce, this flag syncs them to the latest changelist known to the git branch")
public boolean syncChangelistToLatestInBranch;
@ConfigurableProperty(commandLine = "-O,--output-file", help = "File to save output to")
public String outputFileForContent;
@ConfigurableProperty(commandLine = "-cId,--changelist-id", help = "ID of changelist to use")
public String changelistId;
@ConfigurableProperty(commandLine = "-gobuildBinPath,--gobuild-bin-path", help = "Path to gobuild bin file, this is a VMware specific tool")
public String goBuildBinPath;
@ConfigurableProperty(commandLine = "-buildwebProject,--buildweb-project", help = "Which buildweb project to use for a gobuild sandbox buikd, this is for a VMware specific tool")
public String buildwebProject;
@ConfigurableProperty(commandLine = "-buildwebBranch,--buildweb-branch", help = "Which branch on buildweb to use for a gobuild sandbox build, this is for a VMware specific tool")
public String buildwebBranch;
@ConfigurableProperty(commandLine = "--include-estimated", help = "Whether to include stories already estimated when loading jira issues for processing")
public boolean includeStoriesWithEstimates;
@ConfigurableProperty(help = "Swimlanes to use for trello. A list of story point values as integers is expected")
public SortedSet<Integer> storyPointValues;
@ConfigurableProperty(help = "Map of user friendly names for jenkins jobs to select from")
public Map<String, String> jenkinsJobsMappings = new HashMap<>();
@ConfigurableProperty(commandLine = "-waitForJenkins,--wait-for-jenkins", help = "Waits for jenkins job to complete, when running multiple jobs, waits for previous one to complete before starting next one")
public boolean waitForJenkinsJobCompletion;
@ConfigurableProperty(commandLine = "-ignoreJobFailure,--ignore-jenkins-job-failure", help = "If wait for Jenkins job result is set, then ignore job failure and run the next build")
public boolean ignoreJenkinsJobFailure;
@ConfigurableProperty(help = "Max number of jenkins jobs to iterate over when checking for latest status of jenkins job")
public int maxJenkinsBuildsToCheck;
@ConfigurableProperty(help = "Map of reviewer groups to select from for reviewed by section. E.g. create a techDebt group and list relevant reviewers")
public LinkedHashMap<String, SortedSet<String>> reviewerGroups;
@ConfigurableProperty(help = "Default value to set for topic if none entered")
public String defaultTopic;
@ConfigurableProperty(help = "Template values for topic, press up to cycle through values when entering topic")
public String[] topicTemplates;
@ConfigurableProperty(help = "Template values for testing done, press up to cycle through values when entering testing done")
public String[] testingDoneTemplates;
@ConfigurableProperty(commandLine = "-g,--groups", help = "Groups to set for the review request or for generating stats")
public String[] targetGroups;
@ConfigurableProperty(commandLine = "-tb,--tracking-branch", help = "Tracking branch to use as base for reviews")
public String trackingBranch;
@ConfigurableProperty(commandLine = "-p,--parent", help = "Parent branch to use for the git diff to upload to review board")
public String parentBranch;
@ConfigurableProperty(commandLine = "-b,--branch", help = "Optional value to set if using the local branch name for review board is not desired")
public String targetBranch;
@ConfigurableProperty(commandLine = "-defaultJiraProject,--default-jira-project", help = "Default Jira project to use")
public String defaultJiraProject;
@ConfigurableProperty(commandLine = "-defaultJiraComponent,--default-jira-component", help = "Default Jira component to use for creating issues")
public String defaultJiraComponent;
@ConfigurableProperty(help = "Order of services to check against for bug number")
public String[] bugNumberSearchOrder;
@ConfigurableProperty(commandLine = "-bugzillaPrefix,--bugzilla-prefix", help = "Represents a bug in bugzilla, only the number part will be stored")
public String bugzillaPrefix;
@ConfigurableProperty(commandLine = "-t,--trace", help = "Sets log level to trace")
public boolean traceLogLevel;
@ConfigurableProperty(commandLine = "-d,--debug", help = "Sets log level to debug")
public boolean debugLogLevel;
@ConfigurableProperty(commandLine = "-l, ,--log, --log-level", help = "Sets log level to any of the following, SEVERE,INFO,FINE,FINER,FINEST")
public String logLevel;
@ConfigurableProperty(commandLine = "-ms,--max-summary", help = "Sets max line length for the one line summary")
public int maxSummaryLength;
@ConfigurableProperty(commandLine = "-md,--max-description", help = "Sets max line length for all other lines in the commit")
public int maxDescriptionLength;
@ConfigurableProperty(commandLine = "-j,--jenkins-jobs", help = "Sets the names and parameters for the jenkins jobs to invoke. Separate jobs by commas and parameters by ampersands")
public String jenkinsJobsToUse;
@ConfigurableProperty(commandLine = "--estimate", help = "Number of hours to set as the estimate for jira tasks.")
public int jiraTaskEstimateInHours;
@ConfigurableProperty(commandLine = "--old-submit", help = "Number of days after which to close old reviews that have been soft submitted")
public int closeOldSubmittedReviewsAfter;
@ConfigurableProperty(commandLine = "--old-ship-it", help = "Number of days after which to close old reviews that have ship its")
public int closeOldShipItReviewsAfter;
@ConfigurableProperty(commandLine = "--disable-jenkins-login", help = "Skips trying to log into jenkins if the server is not using user login module")
public boolean disableJenkinsLogin;
@ConfigurableProperty(help = "Map of remote branches, :username is substituted for the real username.")
public TreeMap<String, String> remoteBranches;
@ConfigurableProperty(commandLine = "-rb, --remote-branch", help = "Remote branch name to use")
public String remoteBranchToUse;
@ConfigurableProperty(help = "A map of workflows that can be configured. A workflow comprises a list of workflow actions.")
public TreeMap<String, String[]> workflows;
@ConfigurableProperty(help = "A list of workflows that are only created for supporting other workflows. Adding them here hides them on initial auto complete")
public List<String> supportingWorkflows;
@ConfigurableProperty(commandLine = "-w,--workflow", help = "Workflows / Actions to run")
public String workflowsToRun;
@ConfigurableProperty(commandLine = "-dr,--dry-run", help = "Shows the workflow actions that would be run")
public boolean dryRun;
@ConfigurableProperty(commandLine = "--set-empty-only", help = "Set values for empty properties only. Ignore properties that already have values")
public boolean setEmptyPropertiesOnly;
@ConfigurableProperty(commandLine = "-pid,--patch", help = "Id of the review request to use for patching")
public int reviewRequestForPatching;
@ConfigurableProperty(commandLine = "--latest-diff", help = "Always use latest diff from review request for patching")
public boolean alwaysUseLatestDiff;
@ConfigurableProperty(commandLine = "--use-label", help = "Whether to use a jira label when creating a trello board")
public boolean useJiraLabel;
@ConfigurableProperty(commandLine = "-kmc,--keep-missing-cards", help = "Whether to not delete existing cards in Trello that do not match a loaded Jira issue")
public boolean keepMissingCards;
@ConfigurableProperty(commandLine = "-obo,--own-boards-only", help = "Disallow using a trello board owned by someone else")
public boolean ownBoardsOnly;
@ConfigurableProperty(commandLine = "--search-by-usernames-only", help = "Search reviewboard for users by username only")
public boolean searchByUsernamesOnly;
@ConfigurableProperty(commandLine = "--file-count-ranges", help = "File count ranges for grouping reviews when generating stats")
public int[] fileCountRanges;
@ConfigurableProperty(commandLine = "--wait-time", help = "Wait time for blocking workflow action to complete.")
public long waitTimeForBlockingWorkflowAction;
@ConfigurableProperty(help = "Variables to use for jenkins jobs, can set specific values re command line as well, e.g. --JVAPP_NAME=test --JUSERNAME=dbiggs")
public Map<String, String> jenkinsJobParameters = new TreeMap<>();
@Expose(serialize = false, deserialize = false)
private ServiceLocator serviceLocator = null;
public WorkflowConfig() {}
public ServiceLocator configuredServiceLocator() {
if (serviceLocator == null) {
serviceLocator = new ServiceLocator(this);
}
return serviceLocator;
}
public void generateConfigurablePropertyList() {
List<String> usedParams = new ArrayList<String>();
for (Field field : WorkflowConfig.class.getFields()) {
ConfigurableProperty configProperty = field.getAnnotation(ConfigurableProperty.class);
if (configProperty == null) {
continue;
}
String[] params = configProperty.commandLine().split(",");
for (String param : params) {
if (param.equals(ConfigurableProperty.NO_COMMAND_LINE_OVERRIDES)) {
continue;
}
if (usedParams.contains(param)) {
throw new RuntimeException(
String.format("Config flag %s has already been set to configure another property", param));
}
usedParams.add(param);
}
configurableFields.add(field);
}
}
public void applyRuntimeArguments(CommandLineArgumentsParser argsParser) {
workFlowActions = new WorkflowActionLister().findWorkflowActions();
List<ConfigurableProperty> commandLineProperties = applyConfigValues(argsParser.getArgumentMap(), "Command Line");
if (argsParser.containsArgument("--possible-workflow")) {
overriddenConfigSources.put("workflowsToRun", "Command Line");
this.workflowsToRun = argsParser.getExpectedArgument("--possible-workflow");
}
argsParser.checkForUnrecognizedArguments(commandLineProperties);
}
public LogLevel determineLogLevel() {
if (traceLogLevel) {
logLevel = LogLevel.TRACE.name();
} else if (debugLogLevel) {
logLevel = LogLevel.DEBUG.name();
}
return LogLevel.valueOf(logLevel);
}
public int getSearchOrderForService(String serviceToCheckFor) {
for (int i = 0; i < bugNumberSearchOrder.length; i ++) {
if (bugNumberSearchOrder[i].equalsIgnoreCase(serviceToCheckFor)) {
return i;
}
}
return -1;
}
public List<Class<? extends BaseAction>> determineActions(String workflowString) {
String[] possibleActions = workflows.get(workflowString);
if (possibleActions != null) {
log.info("Using workflow {}", workflowString);
log.debug("Using workflow values {}", Arrays.toString(possibleActions));
} else {
log.info("Treating workflow argument {} as a custom workflow string as it did not match any existing workflows", workflowString);
possibleActions = workflowString.split(",");
}
log.info("");
WorkflowValuesParser valuesParser = new WorkflowValuesParser(workflows, workFlowActions);
valuesParser.parse(possibleActions);
applyConfigValues(valuesParser.getConfigValues(), "Config in Workflow");
if (!valuesParser.getUnknownActions().isEmpty()) {
throw new UnknownWorkflowValueException(valuesParser.getUnknownActions());
}
return valuesParser.getActionClasses();
}
/**
* Set separate to other git config values as it shouldn't override a specific workflow file configuration.
*/
public void setGitOriginUrlAsReviewBoardRepo() {
String gitOriginValue = git.configValue("remote.origin.url");
if (StringUtils.isBlank(gitOriginValue)) {
return;
}
log.debug("Setting git origin value {} as the reviewboard repository", gitOriginValue);
reviewBoardRepository = gitOriginValue;
}
public void applyGitConfigValues() {
Map<String, String> configValues = git.configValues();
for (Field field : configurableFields) {
ConfigurableProperty configurableProperty = field.getAnnotation(ConfigurableProperty.class);
String configValueName = configurableProperty.gitConfigProperty().isEmpty() ? "workflow." + field.getName().toLowerCase()
: configurableProperty.gitConfigProperty();
String value = configValues.get(configValueName);
setFieldValue(field, value, "Git Config");
}
}
public void overrideValues(WorkflowConfig overriddenConfig, String configFileName) {
for (Field field : configurableFields) {
Object existingValue;
Object value;
try {
existingValue = field.get(this);
value = field.get(overriddenConfig);
} catch (IllegalAccessException e) {
throw new RuntimeReflectiveOperationException(e);
}
if (value == null || String.valueOf(value).equals("0") || (value instanceof Boolean && !((Boolean) value))) {
continue;
}
// copy values to default config map if value is a map
if (existingValue != null && value instanceof Map) {
Map valueMap = (Map) value;
if (valueMap.isEmpty()) {
continue;
}
Map existingValues = (Map) existingValue;
String existingConfigValue = overriddenConfigSources.get(field.getName());
String updatedConfigValue;
if (existingConfigValue == null && !existingValues.isEmpty()) {
updatedConfigValue = "default, " + configFileName;
} else if (existingConfigValue == null) {
updatedConfigValue = configFileName;
} else {
updatedConfigValue = existingConfigValue + ", " + configFileName;
}
overriddenConfigSources.put(field.getName(), updatedConfigValue);
existingValues.putAll(valueMap);
} else {
overriddenConfigSources.put(field.getName(), configFileName);
// override for everything else
try {
field.set(this, value);
} catch (IllegalAccessException e) {
throw new RuntimeReflectiveOperationException(e);
}
}
}
}
public void parseUsernameFromGitEmailIfBlank() {
if (StringUtils.isNotBlank(username)) {
return;
}
String gitUserEmail = git.configValue("user.email");
if (StringUtils.isNotBlank(gitUserEmail) && gitUserEmail.contains("@")) {
this.username = gitUserEmail.substring(0, gitUserEmail.indexOf("@"));
log.info("No username set, parsed username {} from git config user.email {}", username, gitUserEmail);
overriddenConfigSources.put("username", "Git Config");
}
}
public Field getMatchingField(String commandLineProperty) {
for (Field field : configurableFields) {
ConfigurableProperty property = field.getAnnotation(ConfigurableProperty.class);
if (property.commandLine().equals(ConfigurableProperty.NO_COMMAND_LINE_OVERRIDES)) {
continue;
}
if (ArrayUtils.contains(property.commandLine().split(","), commandLineProperty)) {
return field;
}
}
return null;
}
public CommitConfiguration getCommitConfiguration() {
return new CommitConfiguration(reviewboardUrl, buildwebUrl, testingDoneLabel, bugNumberLabel,
reviewedByLabel, reviewUrlLabel);
}
public JenkinsJobsConfig getJenkinsJobsConfig() {
jenkinsJobParameters.put(JenkinsJobsConfig.USERNAME_PARAM, username);
Map<String, String> presetParams = Collections.unmodifiableMap(jenkinsJobParameters);
Map<String, String> jobMappings = Collections.unmodifiableMap(jenkinsJobsMappings);
return new JenkinsJobsConfig(jenkinsJobsToUse, presetParams, jenkinsUrl, jobMappings);
}
public Integer parseBugzillaBugNumber(String bugNumber) {
if (StringUtils.isInteger(bugNumber)) {
return Integer.parseInt(bugNumber);
}
boolean prefixMatches = StringUtils.isNotBlank(bugzillaPrefix)
&& bugNumber.toUpperCase().startsWith(bugzillaPrefix.toUpperCase());
if (!prefixMatches) {
return null;
}
int lengthToStrip = bugzillaPrefix.length();
if (bugNumber.toUpperCase().startsWith(bugzillaPrefix.toUpperCase() + "-")) {
lengthToStrip++;
}
String numberPart = bugNumber.substring(lengthToStrip);
if (StringUtils.isInteger(numberPart)) {
return Integer.parseInt(numberPart);
} else {
return null;
}
}
private void setFieldValue(Field field, String value, String source) {
Object validValue = new WorkflowField(field).determineValue(value);
if (validValue != null) {
overriddenConfigSources.put(field.getName(), source);
try {
field.set(this, validValue);
} catch (IllegalAccessException e) {
throw new RuntimeReflectiveOperationException(e);
}
}
}
private List<ConfigurableProperty> applyConfigValues(Map<String, String> configValues, String source) {
if (configValues.isEmpty()) {
return Collections.emptyList();
}
for (String configValue : configValues.keySet()) {
if (!configValue.startsWith("--J")) {
continue;
}
String parameterName = configValue.substring(3);
String parameterValue = configValues.get(configValue);
jenkinsJobParameters.put(parameterName, parameterValue);
}
List<ConfigurableProperty> propertiesAffected = new ArrayList<>();
for (Field field : configurableFields) {
ConfigurableProperty configurableProperty = field.getAnnotation(ConfigurableProperty.class);
if (configurableProperty.commandLine().equals(ConfigurableProperty.NO_COMMAND_LINE_OVERRIDES)) {
continue;
}
for (String configValue : configValues.keySet()) {
String[] commandLineArguments = configurableProperty.commandLine().split(",");
if (contains(commandLineArguments, configValue)) {
propertiesAffected.add(configurableProperty);
String value = configValues.get(configValue);
if (value == null && (field.getType() == Boolean.class || field.getType() == boolean.class)) {
value = Boolean.TRUE.toString();
}
setFieldValue(field, value, source);
}
}
}
return propertiesAffected;
}
} |
package org.bouncycastle.math.ec;
import java.math.BigInteger;
import org.bouncycastle.asn1.x9.X9IntegerConverter;
/**
* base class for points on elliptic curves.
*/
public abstract class ECPoint
{
protected static ECFieldElement[] EMPTY_ZS = new ECFieldElement[0];
protected static ECFieldElement[] getInitialZCoords(ECCurve curve)
{
int coord = curve.getCoordinateSystem();
if (coord == ECCurve.COORD_AFFINE)
{
return EMPTY_ZS;
}
ECFieldElement one = curve.fromBigInteger(ECConstants.ONE);
switch (coord)
{
case ECCurve.COORD_HOMOGENEOUS:
case ECCurve.COORD_JACOBIAN:
return new ECFieldElement[]{ one };
case ECCurve.COORD_JACOBIAN_CHUDNOVSKY:
return new ECFieldElement[]{ one, one, one };
case ECCurve.COORD_JACOBIAN_MODIFIED:
return new ECFieldElement[]{ one, curve.getA() };
default:
throw new IllegalArgumentException("unknown coordinate system");
}
}
protected ECCurve curve;
protected ECFieldElement x;
protected ECFieldElement y;
protected ECFieldElement[] zs = null;
protected boolean withCompression;
protected PreCompInfo preCompInfo = null;
private static X9IntegerConverter converter = new X9IntegerConverter();
protected ECPoint(ECCurve curve, ECFieldElement x, ECFieldElement y)
{
this(curve, x, y, getInitialZCoords(curve));
}
protected ECPoint(ECCurve curve, ECFieldElement x, ECFieldElement y, ECFieldElement[] zs)
{
this.curve = curve;
this.x = x;
this.y = y;
this.zs = zs;
}
public ECCurve getCurve()
{
return curve;
}
public ECFieldElement getX()
{
return x;
}
public ECFieldElement getY()
{
return y;
}
public ECFieldElement getZ(int index)
{
return (index < 0 || index >= zs.length) ? null : zs[index];
}
public ECFieldElement[] getZs()
{
int zsLen = zs.length;
if (zsLen == 0)
{
return zs;
}
ECFieldElement[] copy = new ECFieldElement[zsLen];
System.arraycopy(zs, 0, copy, 0, zsLen);
return copy;
}
public boolean isInfinity()
{
return x == null && y == null;
}
public boolean isCompressed()
{
return withCompression;
}
public boolean equals(
Object other)
{
if (other == this)
{
return true;
}
if (!(other instanceof ECPoint))
{
return false;
}
ECPoint o = (ECPoint)other;
if (this.isInfinity())
{
return o.isInfinity();
}
return x.equals(o.x) && y.equals(o.y);
}
public int hashCode()
{
if (this.isInfinity())
{
return 0;
}
return x.hashCode() ^ y.hashCode();
}
/**
* Sets the <code>PreCompInfo</code>. Used by <code>ECMultiplier</code>s
* to save the precomputation for this <code>ECPoint</code> to store the
* precomputation result for use by subsequent multiplication.
* @param preCompInfo The values precomputed by the
* <code>ECMultiplier</code>.
*/
void setPreCompInfo(PreCompInfo preCompInfo)
{
this.preCompInfo = preCompInfo;
}
public byte[] getEncoded()
{
return getEncoded(withCompression);
}
/**
* return the field element encoded with point compression. (S 4.3.6)
*/
public byte[] getEncoded(boolean compressed)
{
if (this.isInfinity())
{
return new byte[1];
}
int length = converter.getByteLength(getX());
byte[] X = converter.integerToBytes(getX().toBigInteger(), length);
if (compressed)
{
byte[] PO = new byte[X.length + 1];
PO[0] = (byte)(getCompressionYTilde() ? 0x03 : 0x02);
System.arraycopy(X, 0, PO, 1, X.length);
return PO;
}
byte[] Y = converter.integerToBytes(getY().toBigInteger(), length);
byte[] PO = new byte[X.length + Y.length + 1];
PO[0] = 0x04;
System.arraycopy(X, 0, PO, 1, X.length);
System.arraycopy(Y, 0, PO, X.length + 1, Y.length);
return PO;
}
protected abstract boolean getCompressionYTilde();
public abstract ECPoint add(ECPoint b);
public abstract ECPoint subtract(ECPoint b);
public abstract ECPoint negate();
public abstract ECPoint twice();
public ECPoint twicePlus(ECPoint b)
{
return twice().add(b);
}
public ECPoint threeTimes()
{
return twicePlus(this);
}
/**
* Multiplies this <code>ECPoint</code> by the given number.
* @param k The multiplicator.
* @return <code>k * this</code>.
*/
public ECPoint multiply(BigInteger k)
{
if (k.signum() < 0)
{
throw new IllegalArgumentException("The multiplicator cannot be negative");
}
if (this.isInfinity())
{
return this;
}
if (k.signum() == 0)
{
return getCurve().getInfinity();
}
return getCurve().getMultiplier().multiply(this, k, preCompInfo);
}
/**
* Elliptic curve points over Fp
*/
public static class Fp extends ECPoint
{
/**
* Create a point which encodes with point compression.
*
* @param curve the curve to use
* @param x affine x co-ordinate
* @param y affine y co-ordinate
*
* @deprecated Use ECCurve.createPoint to construct points
*/
public Fp(ECCurve curve, ECFieldElement x, ECFieldElement y)
{
this(curve, x, y, false);
}
/**
* Create a point that encodes with or without point compresion.
*
* @param curve the curve to use
* @param x affine x co-ordinate
* @param y affine y co-ordinate
* @param withCompression if true encode with point compression
*
* @deprecated per-point compression property will be removed, refer {@link #getEncoded(boolean)}
*/
public Fp(ECCurve curve, ECFieldElement x, ECFieldElement y, boolean withCompression)
{
super(curve, x, y);
if ((x != null && y == null) || (x == null && y != null))
{
throw new IllegalArgumentException("Exactly one of the field elements is null");
}
this.withCompression = withCompression;
}
protected boolean getCompressionYTilde()
{
return getY().testBitZero();
}
// B.3 pg 62
public ECPoint add(ECPoint b)
{
if (this.isInfinity())
{
return b;
}
if (b.isInfinity())
{
return this;
}
if (this == b)
{
return twice();
}
ECFieldElement dx = b.x.subtract(this.x), dy = b.y.subtract(this.y);
if (dx.isZero())
{
if (dy.isZero())
{
// this == b, i.e. this must be doubled
return twice();
}
// this == -b, i.e. the result is the point at infinity
return getCurve().getInfinity();
}
ECFieldElement gamma = dy.divide(dx);
ECFieldElement x3 = gamma.square().subtract(this.x).subtract(b.x);
ECFieldElement y3 = gamma.multiply(this.x.subtract(x3)).subtract(this.y);
return new ECPoint.Fp(curve, x3, y3, withCompression);
}
// B.3 pg 62
public ECPoint twice()
{
if (this.isInfinity())
{
// Twice identity element (point at infinity) is identity
return this;
}
if (this.y.isZero())
{
// if y1 == 0, then (x1, y1) == (x1, -y1)
// and hence this = -this and thus 2(x1, y1) == infinity
return getCurve().getInfinity();
}
ECFieldElement X = this.x.square();
ECFieldElement gamma = three(X).add(getCurve().getA()).divide(two(this.y));
ECFieldElement x3 = gamma.square().subtract(two(this.x));
ECFieldElement y3 = gamma.multiply(this.x.subtract(x3)).subtract(this.y);
return new ECPoint.Fp(curve, x3, y3, this.withCompression);
}
public ECPoint twicePlus(ECPoint b)
{
if (this.isInfinity())
{
return b;
}
if (b.isInfinity())
{
return twice();
}
if (this == b)
{
return threeTimes();
}
/*
* Optimized calculation of 2P + Q, as described in "Trading Inversions for
* Multiplications in Elliptic Curve Cryptography", by Ciet, Joye, Lauter, Montgomery.
*/
ECFieldElement dx = b.x.subtract(this.x), dy = b.y.subtract(this.y);
if (dx.isZero())
{
if (dy.isZero())
{
// this == b i.e. the result is 3P
return threeTimes();
}
// this == -b, i.e. the result is P
return this;
}
ECFieldElement X = dx.square(), Y = dy.square();
ECFieldElement d = X.multiply(two(this.x).add(b.x)).subtract(Y);
if (d.isZero())
{
return getCurve().getInfinity();
}
ECFieldElement D = d.multiply(dx);
ECFieldElement I = D.invert();
ECFieldElement lambda1 = d.multiply(I).multiply(dy);
ECFieldElement lambda2 = two(this.y).multiply(X).multiply(dx).multiply(I).subtract(lambda1);
ECFieldElement x4 = (lambda2.subtract(lambda1)).multiply(lambda1.add(lambda2)).add(b.x);
ECFieldElement y4 = (this.x.subtract(x4)).multiply(lambda2).subtract(this.y);
return new ECPoint.Fp(curve, x4, y4, this.withCompression);
}
public ECPoint threeTimes()
{
if (this.isInfinity() || this.y.isZero())
{
return this;
}
ECFieldElement _2y = two(this.y);
ECFieldElement X = _2y.square();
ECFieldElement Z = three(this.x.square()).add(getCurve().getA());
ECFieldElement Y = Z.square();
ECFieldElement d = three(this.x).multiply(X).subtract(Y);
if (d.isZero())
{
return getCurve().getInfinity();
}
ECFieldElement D = d.multiply(_2y);
ECFieldElement I = D.invert();
ECFieldElement lambda1 = d.multiply(I).multiply(Z);
ECFieldElement lambda2 = X.square().multiply(I).subtract(lambda1);
ECFieldElement x4 = (lambda2.subtract(lambda1)).multiply(lambda1.add(lambda2)).add(this.x);
ECFieldElement y4 = (this.x.subtract(x4)).multiply(lambda2).subtract(this.y);
return new ECPoint.Fp(curve, x4, y4, this.withCompression);
}
protected ECFieldElement two(ECFieldElement x)
{
return x.add(x);
}
protected ECFieldElement three(ECFieldElement x)
{
return x.add(x).add(x);
}
// D.3.2 pg 102 (see Note:)
public ECPoint subtract(ECPoint b)
{
if (b.isInfinity())
{
return this;
}
// Add -b
return add(b.negate());
}
public ECPoint negate()
{
if (this.isInfinity())
{
return this;
}
return new ECPoint.Fp(curve, this.x, this.y.negate(), this.withCompression);
}
}
/**
* Elliptic curve points over F2m
*/
public static class F2m extends ECPoint
{
/**
* @param curve base curve
* @param x x point
* @param y y point
*
* @deprecated Use ECCurve.createPoint to construct points
*/
public F2m(ECCurve curve, ECFieldElement x, ECFieldElement y)
{
this(curve, x, y, false);
}
/**
* @param curve base curve
* @param x x point
* @param y y point
* @param withCompression true if encode with point compression.
*
* @deprecated per-point compression property will be removed, refer {@link #getEncoded(boolean)}
*/
public F2m(ECCurve curve, ECFieldElement x, ECFieldElement y, boolean withCompression)
{
super(curve, x, y);
if ((x != null && y == null) || (x == null && y != null))
{
throw new IllegalArgumentException("Exactly one of the field elements is null");
}
if (x != null)
{
// Check if x and y are elements of the same field
ECFieldElement.F2m.checkFieldElements(this.x, this.y);
// Check if x and a are elements of the same field
if (curve != null)
{
ECFieldElement.F2m.checkFieldElements(this.x, this.curve.getA());
}
}
this.withCompression = withCompression;
}
protected boolean getCompressionYTilde()
{
return !getX().isZero() && getY().divide(getX()).testBitZero();
}
private static void checkPoints(ECPoint a, ECPoint b)
{
// Check, if points are on the same curve
if (a.curve != b.curve)
{
throw new IllegalArgumentException("Only points on the same "
+ "curve can be added or subtracted");
}
// ECFieldElement.F2m.checkFieldElements(a.x, b.x);
}
/* (non-Javadoc)
* @see org.bouncycastle.math.ec.ECPoint#add(org.bouncycastle.math.ec.ECPoint)
*/
public ECPoint add(ECPoint b)
{
checkPoints(this, b);
return addSimple((ECPoint.F2m)b);
}
/**
* Adds another <code>ECPoints.F2m</code> to <code>this</code> without
* checking if both points are on the same curve. Used by multiplication
* algorithms, because there all points are a multiple of the same point
* and hence the checks can be omitted.
* @param b The other <code>ECPoints.F2m</code> to add to
* <code>this</code>.
* @return <code>this + b</code>
*/
public ECPoint.F2m addSimple(ECPoint.F2m b)
{
ECPoint.F2m other = b;
if (this.isInfinity())
{
return other;
}
if (other.isInfinity())
{
return this;
}
ECFieldElement.F2m x2 = (ECFieldElement.F2m)other.getX();
ECFieldElement.F2m y2 = (ECFieldElement.F2m)other.getY();
// Check if other = this or other = -this
if (this.x.equals(x2))
{
if (this.y.equals(y2))
{
// this = other, i.e. this must be doubled
return (ECPoint.F2m)this.twice();
}
// this = -other, i.e. the result is the point at infinity
return (ECPoint.F2m)this.curve.getInfinity();
}
ECFieldElement.F2m lambda
= (ECFieldElement.F2m)(this.y.add(y2)).divide(this.x.add(x2));
ECFieldElement.F2m x3
= (ECFieldElement.F2m)lambda.square().add(lambda).add(this.x).add(x2).add(this.curve.getA());
ECFieldElement.F2m y3
= (ECFieldElement.F2m)lambda.multiply(this.x.add(x3)).add(x3).add(this.y);
return new ECPoint.F2m(curve, x3, y3, withCompression);
}
/* (non-Javadoc)
* @see org.bouncycastle.math.ec.ECPoint#subtract(org.bouncycastle.math.ec.ECPoint)
*/
public ECPoint subtract(ECPoint b)
{
checkPoints(this, b);
return subtractSimple((ECPoint.F2m)b);
}
/**
* Subtracts another <code>ECPoints.F2m</code> from <code>this</code>
* without checking if both points are on the same curve. Used by
* multiplication algorithms, because there all points are a multiple
* of the same point and hence the checks can be omitted.
* @param b The other <code>ECPoints.F2m</code> to subtract from
* <code>this</code>.
* @return <code>this - b</code>
*/
public ECPoint.F2m subtractSimple(ECPoint.F2m b)
{
if (b.isInfinity())
{
return this;
}
// Add -b
return addSimple((ECPoint.F2m)b.negate());
}
/* (non-Javadoc)
* @see org.bouncycastle.math.ec.ECPoint#twice()
*/
public ECPoint twice()
{
if (this.isInfinity())
{
// Twice identity element (point at infinity) is identity
return this;
}
if (this.x.isZero())
{
// if x1 == 0, then (x1, y1) == (x1, x1 + y1)
// and hence this = -this and thus 2(x1, y1) == infinity
return this.curve.getInfinity();
}
ECFieldElement.F2m lambda
= (ECFieldElement.F2m)this.x.add(this.y.divide(this.x));
ECFieldElement.F2m x3
= (ECFieldElement.F2m)lambda.square().add(lambda).
add(this.curve.getA());
ECFieldElement ONE = this.curve.fromBigInteger(ECConstants.ONE);
ECFieldElement.F2m y3
= (ECFieldElement.F2m)this.x.square().add(
x3.multiply(lambda.add(ONE)));
return new ECPoint.F2m(this.curve, x3, y3, withCompression);
}
public ECPoint negate()
{
if (this.isInfinity())
{
return this;
}
return new ECPoint.F2m(curve, this.getX(), this.getY().add(this.getX()), withCompression);
}
}
} |
package mapreduce;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
import java.util.Iterator;
public class MediaMapper extends Mapper<LongWritable, Text, Text, DoubleWritable> {
private Text word = new Text();
private DoubleWritable count = null;
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException{
Configuration conf = context.getConfiguration();
String dado = conf.get("dado");
String agregador = conf.get("agregador");
int iniDado = 0;
int fimDado = 0;
if(dado.equals("MedTemp")){
iniDado = 24;
fimDado = 30;
}
if(dado.equals("MedCond")){
iniDado = 35;
fimDado = 41;
}
if(dado.equals("MedMar")){
iniDado = 46;
fimDado = 52;
}
if(dado.equals("MedPressao")){
iniDado = 57;
fimDado = 63;
}
if(dado.equals("MedVento")){
iniDado = 78;
fimDado = 83;
}
if(dado.equals("MaxVento")){
iniDado = 88;
fimDado = 93;
}
if(dado.equals("MaxRajada")){
iniDado = 95;
fimDado = 100;
}
if(dado.equals("MaxTemp")){
iniDado = 102;
fimDado = 108;
}
if(dado.equals("MinTemp")){
iniDado = 110;
fimDado = 116;
}
if(dado.equals("Precip")){
iniDado = 118;
fimDado = 123;
}
if(dado.equals("Neve")){
iniDado = 125;
fimDado = 130;
}
String balde = value.toString();
if(balde.charAt(0) != 'S'){
String valor = "";
valor += preencheData(agregador, balde);
word.set(valor);
valor = "";
while(iniDado < fimDado){
if(balde.charAt(iniDado) != ' '){
valor += balde.charAt(iniDado);
}
iniDado++;
}
try {
if(valorValido(valor)){
count = new DoubleWritable(Double.parseDouble(valor));
context.write(word, count);
}
}
catch (NumberFormatException e) {
}
}
}
private String preencheData(String agregador, String balde) {
int iniAgregador = 0;
int fimAgregador = 0;
String valor = "";
if(agregador.equals("Ano")){
iniAgregador = 14;
fimAgregador = 18;
}
else if(agregador.equals("Mes")){
iniAgregador = 18;
fimAgregador = 20;
}
else if(agregador.equals("Semana")){
iniAgregador = 20;
fimAgregador = 22;
}
while(iniAgregador < fimAgregador){
valor += balde.charAt(iniAgregador);
iniAgregador++;
}
if(agregador.equals("Mes")){
return preencheData("Ano", balde)+"-"+valor;
}
return valor;
}
private boolean valorValido(String valor) {
int indice = 0;
for(indice = 0; indice < valor.length(); indice++){
if(valor.charAt(indice) != ' ' && valor.charAt(indice) != '9' && valor.charAt(indice)!= '.')
return true;
}
return false;
}
} |
package xal.tools.apputils.files;
import xal.tools.StringJoiner;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
/**
* FileFilterFactory generates file filters based on supplied file types.
*
* @author tap
*/
public class FileFilterFactory {
/** wildcard extension */
static public final String WILDCARD_FILE_EXTENSION = "*";
/** Creates a new instance of FileFilterFactory */
protected FileFilterFactory() {}
/**
* Applies the file filters to the file chooser and returns this file chooser.
* Existing file filters are removed from the file chooser and then new file filters
* are added to the file chooser consistent with the specified file types and descriptions.
* @param fileChooser the file chooser to which to add the file filters
* @param fileTypes An array of file types to accept
* @param fileDescriptions An arraz of corresponding file type descriptions
* @return The file chooser that accepts the specified file types (same file chooser as the argument)
*/
static public JFileChooser applyFileFilters( final JFileChooser fileChooser, final String[] fileTypes, final String[] fileDescriptions ) {
for ( int index = 0 ; index < fileTypes.length ; index++ ) {
FileFilter filter = getFileFilter(fileTypes[index], fileDescriptions[index]);
fileChooser.addChoosableFileFilter(filter);
}
final FileFilter aggregateFilter = getSupportedFileFilter( fileTypes );
fileChooser.addChoosableFileFilter( aggregateFilter );
fileChooser.setFileFilter( aggregateFilter );
return fileChooser;
}
/**
* Applies the file filters to the file chooser and returns this file chooser.
* Existing file filters are removed from the file chooser and then new file filters
* are added to the file chooser consistent with the specified file types.
* @param fileChooser the file chooser to which to add the file filters
* @param fileTypes An array of file types to accept
* @return The file chooser that accepts the specified file types (same file chooser as the argument)
*/
static public JFileChooser applyFileFilters( final JFileChooser fileChooser, final String[] fileTypes ) {
applyFileFilters(fileChooser, fileTypes, new String[fileTypes.length]);
return fileChooser;
}
/**
* Create a file filter that accepts files of the specified type. This is
* a supporting method for creating file choosers. A type is identified
* by its filename suffix.
* @param fileType File type to accept
* @param description the description of this file type
* @return The file filter that accepts the specified file type
*/
static public FileFilter getFileFilter( final String fileType, final String description ) {
return new FileFilter() {
final String suffix = "." + fileType.toLowerCase();
public boolean accept( final java.io.File file ) {
if ( file.isDirectory() ) return true;
final String extension = getFileExtension( file );
return isMatch( extension, fileType );
}
/**
* Get the file type as the file filter description.
* @return File filter description.
*/
public String getDescription() {
if (description != null)
return description + " (*." + fileType + ")";
else
return fileType;
}
};
}
/**
* Create a file filter that accepts files of the specified types. This is
* a supporting method for creating file choosers. A type is identified
* by its filename suffix.
* @param fileTypes Array of file types to accept
* @return The file filter that accepts the specified file types
*/
static public FileFilter getSupportedFileFilter( final String[] fileTypes ) {
return new FileFilter() {
public boolean accept( final java.io.File file ) {
if ( file.isDirectory() ) return true;
final String extension = getFileExtension( file );
for ( int index = 0 ; index < fileTypes.length ; index++ ) {
if ( isMatch( extension, fileTypes[index] ) ) {
return true;
}
}
return false;
}
/**
* Description of the file filter which is simply "Supported Files".
* @return Description of the file filter.
*/
public String getDescription() {
return "Supported Files";
}
};
}
/**
* Determine the file's extension.
*
* @param file the file for which to get the extension
* @return the file's extension
*/
static protected String getFileExtension( final java.io.File file ) {
final String name = file.getName().toLowerCase();
final int extensionIndex = name.lastIndexOf('.');
return ( extensionIndex < ( name.length() - 2 ) && extensionIndex >= 0 ) ? name.substring(extensionIndex + 1) : "";
}
/**
* Determine whether the extension matches the file type. If the file type is the wildcard extension, then accept all extensions as matching.
*
* @param extension the file extension to test for matching to the file type.
* @param fileType the file type against which to test for matching the file extension.
* @return true if the extension matches the file type
*/
static protected boolean isMatch( final String extension, final String fileType ) {
return fileType.equals( WILDCARD_FILE_EXTENSION ) || extension.equalsIgnoreCase( fileType );
}
} |
package org.royaldev.royalcommands.rcommands;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.WorldType;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.royaldev.royalcommands.RUtils;
import org.royaldev.royalcommands.RoyalCommands;
import java.io.File;
import java.util.Random;
public class CmdWorldManager implements CommandExecutor {
RoyalCommands plugin;
public CmdWorldManager(RoyalCommands instance) {
plugin = instance;
}
public static boolean deleteDir(File dir) {
// If it is a directory get the child
if (dir.isDirectory()) {
// List all the contents of the directory
File[] fileList = dir.listFiles();
if (fileList == null) return false;
// Loop through the list of files/directories
for (File file : fileList) {
// Get the current file object.
// Call deleteDir function once again for deleting all the directory contents or
// sub directories if any present.
deleteDir(file);
}
}
// Delete the current directory or file.
return dir.delete();
}
public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("worldmanager")) {
if (!plugin.isAuthorized(cs, "rcmds.worldmanager")) {
RUtils.dispNoPerms(cs);
return true;
}
if (args.length < 1) {
cs.sendMessage(cmd.getDescription());
return false;
}
String command = args[0].toLowerCase();
if (command.equals("create")) {
if (args.length < 4) {
cs.sendMessage(ChatColor.RED + "Not enough arguments! Try " + ChatColor.GRAY + "/" + label + " help" + ChatColor.RED + " for help.");
return true;
}
String name = args[1];
for (World w : plugin.getServer().getWorlds()) {
if (w.getName().equals(name)) {
cs.sendMessage(ChatColor.RED + "A world with that name already exists!");
return true;
}
}
WorldType type = WorldType.getByName(args[2].toUpperCase());
if (type == null) {
cs.sendMessage(ChatColor.RED + "Invalid world type!");
String types = "";
for (WorldType t : WorldType.values())
types = (types.equals("")) ? types.concat(ChatColor.GRAY + t.getName() + ChatColor.WHITE) : types.concat(", " + ChatColor.GRAY + t.getName() + ChatColor.WHITE);
cs.sendMessage(types);
return true;
}
World.Environment we;
try {
we = World.Environment.valueOf(args[3].toUpperCase());
} catch (Exception e) {
cs.sendMessage(ChatColor.RED + "Invalid environment!");
String types = "";
for (World.Environment t : World.Environment.values())
types = (types.equals("")) ? types.concat(ChatColor.GRAY + t.name() + ChatColor.WHITE) : types.concat(", " + ChatColor.GRAY + t.name() + ChatColor.WHITE);
cs.sendMessage(types);
return true;
}
cs.sendMessage(ChatColor.BLUE + "Creating world...");
WorldCreator wc = new WorldCreator(name);
wc = wc.type(type);
wc = wc.environment(we);
if (args.length > 4) {
long seed;
try {
seed = Long.valueOf(args[4]);
} catch (Exception e) {
seed = args[4].hashCode();
}
wc = wc.seed(seed);
} else wc = wc.seed(new Random().nextLong());
if (args.length > 5) wc = wc.generator(args[5]);
World w = wc.createWorld();
w.save();
cs.sendMessage(ChatColor.BLUE + "World " + ChatColor.GRAY + w.getName() + ChatColor.BLUE + " created successfully.");
return true;
} else if (command.equals("unload")) {
if (args.length < 2) {
cs.sendMessage(ChatColor.RED + "Not enough arguments! Try " + ChatColor.GRAY + "/" + label + " help" + ChatColor.RED + " for help.");
return true;
}
World w = plugin.getServer().getWorld(args[1]);
if (w == null) {
cs.sendMessage(ChatColor.RED + "No such world!");
return true;
}
cs.sendMessage(ChatColor.BLUE + "Unloading world...");
if (args.length > 2 && Boolean.getBoolean(args[2].toLowerCase()))
for (Player p : w.getPlayers()) p.kickPlayer("Your world is being unloaded!");
boolean success = plugin.getServer().unloadWorld(w, true);
if (success) cs.sendMessage(ChatColor.BLUE + "World unloaded successfully!");
else cs.sendMessage(ChatColor.RED + "Could not unload that world.");
return true;
} else if (command.equals("delete")) {
if (args.length < 2) {
cs.sendMessage(ChatColor.RED + "Not enough arguments! Try " + ChatColor.GRAY + "/" + label + " help" + ChatColor.RED + " for help.");
return true;
}
World w = plugin.getServer().getWorld(args[1]);
if (w == null) {
cs.sendMessage(ChatColor.RED + "No such world!");
return true;
}
cs.sendMessage(ChatColor.BLUE + "Unloading world...");
if (args.length > 2 && Boolean.getBoolean(args[2].toLowerCase()))
for (Player p : w.getPlayers()) p.kickPlayer("Your world is being unloaded!");
boolean success = plugin.getServer().unloadWorld(w, true);
if (success) cs.sendMessage(ChatColor.BLUE + "World unloaded successfully!");
else {
cs.sendMessage(ChatColor.RED + "Could not unload that world.");
return true;
}
cs.sendMessage(ChatColor.BLUE + "Deleting world...");
success = deleteDir(w.getWorldFolder());
if (success) cs.sendMessage(ChatColor.BLUE + "Successfully deleted world!");
else cs.sendMessage(ChatColor.RED + "Could not delete world.");
return true;
} else if (command.equals("list")) {
cs.sendMessage(ChatColor.BLUE + "Worlds:");
String worlds = "";
for (World w : plugin.getServer().getWorlds())
worlds = (worlds.equals("")) ? worlds.concat(ChatColor.GRAY + w.getName()) : worlds.concat(ChatColor.WHITE + ", " + ChatColor.GRAY + w.getName());
cs.sendMessage(worlds);
return true;
} else if (command.equals("help")) {
cs.sendMessage(ChatColor.GREEN + "RoyalCommands WorldManager Help");
cs.sendMessage(ChatColor.GREEN + "===============================");
cs.sendMessage("* " + ChatColor.GRAY + "/" + label + " create [name] [type] [environment] (seed) (generator)" + ChatColor.BLUE + " - Creates a new world.");
cs.sendMessage("* " + ChatColor.GRAY + "/" + label + " load [name]" + ChatColor.BLUE + " - Loads a world.");
cs.sendMessage("* " + ChatColor.GRAY + "/" + label + " unload [name] (true)" + ChatColor.BLUE + " - Unloads a world. If true is specified, will kick all players on the world.");
cs.sendMessage("* " + ChatColor.GRAY + "/" + label + " delete [name] (true)" + ChatColor.BLUE + " - Unloads and deletes a world. If true is specified, will kick all players on the world.");
cs.sendMessage("* " + ChatColor.GRAY + "/" + label + " info" + ChatColor.BLUE + " - Displays available world types and environments; if you are a player, displays information about your world.");
cs.sendMessage("* " + ChatColor.GRAY + "/" + label + " help" + ChatColor.BLUE + " - Displays this help.");
cs.sendMessage("* " + ChatColor.GRAY + "/" + label + " list" + ChatColor.BLUE + " - Lists all the loaded worlds.");
return true;
} else if (command.equals("load")) {
if (args.length < 2) {
cs.sendMessage(ChatColor.RED + "Not enough arguments! Try " + ChatColor.GRAY + "/" + label + " help" + ChatColor.RED + " for help.");
return true;
}
String name = args[1];
boolean contains = false;
for (File f : plugin.getServer().getWorldContainer().listFiles()) {
if (f.getName().equals(name)) contains = true;
}
if (!contains) {
cs.sendMessage(ChatColor.RED + "No such world!");
return true;
}
WorldCreator wc = new WorldCreator(name);
World w = wc.createWorld();
cs.sendMessage(ChatColor.BLUE + "Loaded world " + ChatColor.GRAY + w.getName() + ChatColor.BLUE + ".");
return true;
} else if (command.equals("info")) {
cs.sendMessage(ChatColor.GREEN + "RoyalCommands WorldManager Info");
cs.sendMessage(ChatColor.GREEN + "===============================");
cs.sendMessage(ChatColor.BLUE + "Available world types:");
String types = "";
for (WorldType t : WorldType.values())
types = (types.equals("")) ? types.concat(ChatColor.GRAY + t.getName() + ChatColor.WHITE) : types.concat(", " + ChatColor.GRAY + t.getName() + ChatColor.WHITE);
cs.sendMessage(" " + types);
types = "";
cs.sendMessage(ChatColor.BLUE + "Available world environments:");
for (World.Environment t : World.Environment.values())
types = (types.equals("")) ? types.concat(ChatColor.GRAY + t.name() + ChatColor.WHITE) : types.concat(", " + ChatColor.GRAY + t.name() + ChatColor.WHITE);
cs.sendMessage(" " + types);
if (!(cs instanceof Player)) return true;
Player p = (Player) cs;
World w = p.getWorld();
cs.sendMessage(ChatColor.GREEN + "Information on this world:");
cs.sendMessage(ChatColor.BLUE + "Name: " + ChatColor.GRAY + w.getName());
cs.sendMessage(ChatColor.BLUE + "Environment: " + ChatColor.GRAY + w.getEnvironment().name());
return true;
} else {
cs.sendMessage(ChatColor.RED + "Invalid subcommand!");
return true;
}
}
return false;
}
} |
package com.intellij.ide;
import com.intellij.ide.util.TipAndTrickBean;
import com.intellij.internal.statistic.eventLog.*;
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType;
import com.intellij.internal.statistic.eventLog.validator.rules.EventContext;
import com.intellij.internal.statistic.eventLog.validator.rules.impl.CustomWhiteListRule;
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector;
import com.intellij.internal.statistic.utils.PluginInfo;
import com.intellij.internal.statistic.utils.PluginInfoDetectorKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class TipsOfTheDayUsagesCollector extends CounterUsagesCollector {
private static final EventLogGroup GROUP = new EventLogGroup("ui.tips", 4);
public enum DialogType { automatically, manually }
public static final EventId NEXT_TIP = GROUP.registerEvent("next.tip");
public static final EventId PREVIOUS_TIP = GROUP.registerEvent("previous.tip");
public static final EventId1<DialogType> DIALOG_SHOWN =
GROUP.registerEvent("dialog.shown", EventFields.Enum("type", DialogType.class));
private static final EventId3<String, String, String> TIP_SHOWN =
GROUP.registerEvent("tip.shown",
EventFields.String("filename").withCustomRule("tip_info"),
EventFields.String("algorithm").withCustomEnum("tips_order_algorithm"),
EventFields.Version);
@Override
public EventLogGroup getGroup() {
return GROUP;
}
public static void triggerTipShown(@NotNull TipAndTrickBean tip, @NotNull String algorithm, @Nullable String version) {
TIP_SHOWN.log(tip.fileName, algorithm, version);
}
public static class TipInfoWhiteListRule extends CustomWhiteListRule {
@Override
public boolean acceptRuleId(@Nullable String ruleId) {
return "tip_info".equals(ruleId);
}
@NotNull
@Override
protected ValidationResultType doValidate(@NotNull String data, @NotNull EventContext context) {
PluginInfo info = context.pluginInfo;
if (info != null) {
return info.isSafeToReport() ? ValidationResultType.ACCEPTED : ValidationResultType.THIRD_PARTY;
}
Object filename = context.eventData.get("filename");
if (filename instanceof String) {
TipAndTrickBean tip = TipAndTrickBean.findByFileName((String)filename);
if (tip != null) {
PluginInfo pluginInfo = PluginInfoDetectorKt.getPluginInfoByDescriptor(tip.getPluginDescriptor());
context.setPluginInfo(pluginInfo);
return pluginInfo.isSafeToReport() ? ValidationResultType.ACCEPTED : ValidationResultType.THIRD_PARTY;
}
}
return ValidationResultType.REJECTED;
}
}
} |
package org.royaldev.royalcommands.rcommands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.royaldev.royalcommands.MessageColor;
import org.royaldev.royalcommands.RUtils;
import org.royaldev.royalcommands.RoyalCommands;
import org.royaldev.royalcommands.configuration.PConfManager;
import java.util.HashMap;
@ReflectCommand
public class CmdMessage implements CommandExecutor {
public final static HashMap<String, String> replydb = new HashMap<>();
private final RoyalCommands plugin;
public CmdMessage(RoyalCommands plugin) {
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender cs, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("message")) {
if (!plugin.ah.isAuthorized(cs, "rcmds.message")) {
RUtils.dispNoPerms(cs);
return true;
}
if (args.length < 2) {
return false;
}
Player t = plugin.getServer().getPlayer(args[0]);
String m = RoyalCommands.getFinalArg(args, 1).trim();
if (t == null || t.getName().trim().equals("")) {
cs.sendMessage(MessageColor.NEGATIVE + "That player is not online!");
return true;
}
if (plugin.isVanished(t, cs)) {
cs.sendMessage(MessageColor.NEGATIVE + "That player does not exist!");
return true;
}
synchronized (replydb) {
replydb.put(t.getName(), cs.getName());
replydb.put(cs.getName(), t.getName());
}
if (m.equals("")) {
cs.sendMessage(MessageColor.NEGATIVE + "You entered no message!");
return true;
}
t.sendMessage(MessageColor.NEUTRAL + "[" + MessageColor.POSITIVE + cs.getName() + MessageColor.NEUTRAL + " -> " + MessageColor.POSITIVE + "You" + MessageColor.NEUTRAL + "] " + m);
cs.sendMessage(MessageColor.NEUTRAL + "[" + MessageColor.POSITIVE + "You" + MessageColor.NEUTRAL + " -> " + MessageColor.POSITIVE + t.getName() + MessageColor.NEUTRAL + "] " + m);
if (!this.plugin.ah.isAuthorized(cs, "rcmds.exempt.messagespy")) {
Player[] ps = plugin.getServer().getOnlinePlayers();
for (Player p1 : ps) {
if (PConfManager.getPConfManager(p1).getBoolean("messagespy")) {
if (t == p1 || cs == p1) continue;
p1.sendMessage(MessageColor.NEUTRAL + "[" + MessageColor.POSITIVE + cs.getName() + MessageColor.NEUTRAL + " -> " + MessageColor.POSITIVE + t.getName() + MessageColor.NEUTRAL + "] " + m);
}
}
}
return true;
}
return false;
}
} |
package com.j0rsa.caricyno.application.post.attachment.parser;
import com.j0rsa.caricyno.application.post.attachment.PostAttachment;
import com.j0rsa.caricyno.application.post.attachment.PostAttachmentType;
import com.vk.api.sdk.objects.video.Video;
import com.vk.api.sdk.objects.video.VideoFiles;
import com.vk.api.sdk.objects.wall.WallpostAttachment;
public class VkVideo extends Attachment {
@Override
public PostAttachment getData(WallpostAttachment wallpostAttachment) {
Video video = wallpostAttachment.getVideo();
if (video != null) {
return createAttachment(video);
}
return null;
}
private PostAttachment createAttachment(Video video) {
PostAttachment postAttachment = createAttachment();
postAttachment.setLink(getLink(video.getFiles()));
postAttachment.setPhotoLink(extractPhoto(video));
return postAttachment;
}
private String extractPhoto(Video video) {
if (isNotNull(video.getPhoto800())) {
return video.getPhoto800();
} else if (isNotNull(video.getPhoto320())) {
return video.getPhoto320();
}
return video.getPhoto130();
}
private boolean isNotNull(Object o) {
return o != null;
}
@Override
public PostAttachmentType getType() {
return PostAttachmentType.VK_VIDEO;
}
private String getLink(VideoFiles files) {
if (files != null) {
return files.getExternal();
}
return null;
}
} |
package net.invtweaks.logic;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.TimeoutException;
import java.util.logging.Logger;
import net.invtweaks.Const;
import net.invtweaks.config.InvTweaksConfig;
import net.invtweaks.config.InventoryConfigRule;
import net.invtweaks.library.ContainerManager.ContainerSection;
import net.invtweaks.library.ContainerSectionManager;
import net.invtweaks.library.Obfuscation;
import net.invtweaks.tree.ItemTree;
import net.invtweaks.tree.ItemTreeItem;
import net.minecraft.client.Minecraft;
import net.minecraft.src.ItemStack;
/**
* Core of the sorting behaviour. Allows to move items in a container
* (inventory or chest) with respect to the mod's configuration.
*
* Here are the different layers of functions, from high to low levels:
* moveStack
* |- swapOrMerge
* |- remove
* |- putStackInSlot
* |- put
* |- putStackInSlot
* |- click (SMP only)
*
* @author Jimeo Wan
*
*/
public class SortingHandler extends Obfuscation {
private static final Logger log = Logger.getLogger("InvTweaks");
public static final boolean STACK_NOT_EMPTIED = true;
public static final boolean STACK_EMPTIED = false;
private static int[] DEFAULT_LOCK_PRIORITIES = null;
private static boolean[] DEFAULT_FROZEN_SLOTS = null;
private static final int MAX_CONTAINER_SIZE = 100;
public static final int ALGORITHM_DEFAULT = 0;
public static final int ALGORITHM_VERTICAL = 1;
public static final int ALGORITHM_HORIZONTAL = 2;
public static final int ALGORITHM_INVENTORY = 3;
private ContainerSectionManager containerMgr;
private int algorithm;
private int size;
private ItemTree tree;
private Vector<InventoryConfigRule> rules;
private int[] rulePriority;
private int[] keywordOrder;
private int[] lockPriorities;
private boolean[] frozenSlots;
private boolean isMultiplayer;
public SortingHandler(Minecraft mc, InvTweaksConfig config,
ContainerSection section, int algorithm) throws Exception {
super(mc);
// Init constants
if (DEFAULT_LOCK_PRIORITIES == null) {
DEFAULT_LOCK_PRIORITIES = new int[MAX_CONTAINER_SIZE];
for (int i = 0; i < MAX_CONTAINER_SIZE; i++) {
DEFAULT_LOCK_PRIORITIES[i] = 0;
}
}
if (DEFAULT_FROZEN_SLOTS == null) {
DEFAULT_FROZEN_SLOTS = new boolean[MAX_CONTAINER_SIZE];
for (int i = 0; i < MAX_CONTAINER_SIZE; i++) {
DEFAULT_FROZEN_SLOTS[i] = false;
}
}
// Init attributes
this.containerMgr = new ContainerSectionManager(mc, section);
this.size = containerMgr.getSectionSize();
this.rules = config.getRules();
this.tree = config.getTree();
if (section == ContainerSection.INVENTORY) {
this.lockPriorities = config.getLockPriorities();
this.frozenSlots = config.getFrozenSlots();
this.algorithm = ALGORITHM_INVENTORY;
} else {
this.lockPriorities = DEFAULT_LOCK_PRIORITIES;
this.frozenSlots = DEFAULT_FROZEN_SLOTS;
this.algorithm = algorithm;
if (algorithm != ALGORITHM_DEFAULT) {
computeLineSortingRules(Const.INVENTORY_ROW_SIZE,
algorithm == ALGORITHM_HORIZONTAL);
}
}
this.rulePriority = new int[size];
this.keywordOrder = new int[size];
for (int i = 0; i < size; i++) {
this.rulePriority[i] = -1;
ItemStack stack = containerMgr.getItemStack(i);
if (stack != null) {
this.keywordOrder[i] = getItemOrder(stack);
} else {
this.keywordOrder[i] = -1;
}
}
this.isMultiplayer = isMultiplayerWorld();
}
public void sort() throws TimeoutException {
// Do nothing if the inventory is closed
// if (!mc.hrrentScreen instanceof GuiContainer)
// return;
long timer = System.nanoTime();
//// Empty hand (needed in SMP)
if (isMultiplayerWorld()) {
putHoldItemDown();
}
if (algorithm != ALGORITHM_DEFAULT) {
if (algorithm == ALGORITHM_INVENTORY) {
//// Merge stacks to fill the ones in locked slots
log.info("Merging stacks.");
for (int i = size-1; i >= 0; i
ItemStack from = containerMgr.getItemStack(i);
if (from != null) {
int j = 0;
for (Integer lockPriority : lockPriorities) {
if (lockPriority > 0) {
ItemStack to = containerMgr.getItemStack(j);
if (to != null && from.isItemEqual(to)) {
move(i, j, Integer.MAX_VALUE);
markAsNotMoved(j);
if (containerMgr.getItemStack(i) == null) {
break;
}
}
}
j++;
}
}
}
}
//// Apply rules
log.info("Applying rules.");
// Sorts rule by rule, themselves being already sorted by decreasing priority
Iterator<InventoryConfigRule> rulesIt = rules.iterator();
while (rulesIt.hasNext()) {
InventoryConfigRule rule = rulesIt.next();
int rulePriority = rule.getPriority();
if (log.getLevel() == Const.DEBUG)
log.info("Rule : "+rule.getKeyword()+"("+rulePriority+")");
// For every item in the inventory
for (int i = 0; i < size; i++) {
ItemStack from = containerMgr.getItemStack(i);
// If the rule is strong enough to move the item and it matches the item
if (hasToBeMoved(i) && lockPriorities[i] < rulePriority) {
List<ItemTreeItem> fromItems = tree.getItems(
getItemID(from), getItemDamage(from));
if (tree.matches(fromItems, rule.getKeyword())) {
// Test preffered slots
int[] preferredSlots = rule.getPreferredSlots();
int stackToMove = i;
for (int j = 0; j < preferredSlots.length; j++) {
int k = preferredSlots[j];
int moveResult = move(stackToMove, k, rulePriority);
if (moveResult != -1) {
if (containerMgr.getItemStack(stackToMove) == null ||
moveResult == k) {
break;
}
else {
from = containerMgr.getItemStack(moveResult);
fromItems = tree.getItems(getItemID(from), getItemDamage(from));
if (!tree.matches(fromItems, rule.getKeyword())) {
break;
}
else {
stackToMove = moveResult;
j = -1;
}
}
}
}
}
}
}
}
//// Don't move locked stacks
log.info("Locking stacks.");
for (int i = 0; i < size; i++) {
if (hasToBeMoved(i) && lockPriorities[i] > 0) {
markAsMoved(i, 1);
}
}
}
//// Sort remaining
defaultSorting();
if (log.getLevel() == Const.DEBUG) {
timer = System.nanoTime()-timer;
log.info("Sorting done in " + timer + "ns");
}
}
private void defaultSorting() throws TimeoutException {
log.info("Default sorting.");
Vector<Integer> remaining = new Vector<Integer>(), nextRemaining = new Vector<Integer>();
for (int i = 0; i < size; i++) {
if (hasToBeMoved(i)) {
remaining.add(i);
nextRemaining.add(i);
}
}
int iterations = 0;
while (remaining.size() > 0 && iterations++ < 50) {
for (int i : remaining) {
if (hasToBeMoved(i)) {
for (int j = 0; j < size; j++) {
if (move(i, j, 1) != -1) {
nextRemaining.remove((Object) j);
break;
}
}
}
else {
nextRemaining.remove((Object) i);
}
}
remaining.clear();
remaining.addAll(nextRemaining);
}
if (iterations == 50) {
log.info("Sorting takes too long, aborting.");
}
}
/**
* If an item is in hand (= attached to the cursor), puts it down.
*
* @return -1 if there is no room to put the item, or the hand is not holding anything.
* @throws Exception
*/
private int putHoldItemDown() throws TimeoutException {
ItemStack holdStack = getHoldStack();
if (holdStack != null) {
// Try to find an unlocked slot first, to avoid
// impacting too much the sorting
for (int step = 1; step <= 2; step++) {
for (int i = size - 1; i >= 0; i
if (containerMgr.getItemStack(i) == null
&& (lockPriorities[i] == 0 && !frozenSlots[i])
|| step == 2) {
containerMgr.leftClick(i);
return i;
}
}
}
return -1;
}
return -1;
}
/**
* Tries to move a stack from i to j, and swaps them if j is already
* occupied but i is of greater priority (even if they are of same ID).
*
* @param i from slot
* @param j to slot
* @param priority The rule priority. Use 1 if the stack was not moved using a rule.
* @return -1 if it failed,
* j if the stacks were merged into one,
* n if the j stack has been moved to the n slot.
* @throws TimeoutException
*/
private int move(int i, int j, int priority) throws TimeoutException {
ItemStack from = containerMgr.getItemStack(i);
ItemStack to = containerMgr.getItemStack(j);
if (from == null || frozenSlots[j] || frozenSlots[i]) {
return -1;
}
//log.info("Moving " + i + " (" + from + ") to " + j + " (" + to + ") ");
if (lockPriorities[i] <= priority) {
if (i == j) {
markAsMoved(i, priority);
return j;
}
// Move to empty slot
if (to == null && lockPriorities[j] <= priority && !frozenSlots[j]) {
rulePriority[i] = -1;
keywordOrder[i] = -1;
rulePriority[j] = priority;
keywordOrder[j] = getItemOrder(from);
containerMgr.move(i, j);
return j;
}
// Try to swap/merge
else if (to != null) {
boolean canBeSwapped = false;
if (lockPriorities[j] <= priority) {
if (rulePriority[j] < priority) {
canBeSwapped = true;
} else if (rulePriority[j] == priority) {
if (isOrderedBefore(i, j)) {
canBeSwapped = true;
}
}
}
if (canBeSwapped || from.isItemEqual(to)) {
keywordOrder[j] = keywordOrder[i];
rulePriority[j] = priority;
rulePriority[i] = -1;
rulePriority[i] = -1;
containerMgr.move(i, j);
ItemStack remains = containerMgr.getItemStack(i);
if (remains != null) {
int dropSlot = i;
if (lockPriorities[j] > lockPriorities[i]) {
for (int k = 0; k < size; k++) {
if (containerMgr.getItemStack(k) == null
&& lockPriorities[k] == 0) {
dropSlot = k;
break;
}
}
}
if (dropSlot != i) {
containerMgr.move(i, dropSlot);
}
rulePriority[dropSlot] = -1;
keywordOrder[dropSlot] = getItemOrder(remains);
return dropSlot;
}
else {
return j;
}
}
}
}
return -1;
}
private void markAsMoved(int i, int priority) {
rulePriority[i] = priority;
}
private void markAsNotMoved(int i) {
rulePriority[i] = -1;
}
private boolean hasToBeMoved(int slot) {
return containerMgr.getItemStack(slot) != null
&& rulePriority[slot] == -1;
}
private boolean isOrderedBefore(int i, int j) {
ItemStack iStack = containerMgr.getItemStack(i),
jStack = containerMgr.getItemStack(j);
if (jStack == null) {
return true;
} else if (iStack == null || keywordOrder[i] == -1) {
return false;
} else {
if (keywordOrder[j] == keywordOrder[j]) {
// Items of same keyword orders can have different IDs,
// in the case of categories defined by a range of IDs
if (getItemID(iStack) == getItemID(jStack)) {
if (getStackSize(iStack) == getStackSize(jStack)) {
// Highest damage first for tools, else lowest damage.
// No tool ordering for same ID in multiplayer (cannot
// swap directly)
return (getItemDamage(iStack) > getItemDamage(jStack) && getMaxStackSize(jStack) == 1 && !isMultiplayer)
|| (getItemDamage(iStack) < getItemDamage(jStack) && getMaxStackSize(jStack) > 1);
} else {
return getStackSize(iStack) > getStackSize(jStack);
}
} else {
return getItemID(iStack) > getItemID(jStack);
}
} else {
return keywordOrder[i] < keywordOrder[j];
}
}
}
private int getItemOrder(ItemStack item) {
List<ItemTreeItem> items = tree.getItems(
getItemID(item), getItemDamage(item));
return (items != null && items.size() > 0)
? items.get(0).getOrder()
: Integer.MAX_VALUE;
}
///TODO
/**
* SP: Removes the stack from the given slot.
* SMP: Registers the action without actually doing it.
*
* @param slot
* @return The removed stack
private ItemStack remove(int slot) {
ItemStack removed = getStackInSlot(slot);
if (log.getLevel() == Const.DEBUG) {
try {
log.info("Removed: " + tree.getItems(getItemID(removed), getItemDamage(removed)).get(0) + " from " + slot);
} catch (NullPointerException e) {
log.info("Removed: null from " + slot);
}
}
if (!isMultiplayer) {
putStackInSlot(slot, null);
}
rulePriority[slot] = -1;
keywordOrder[slot] = -1;
return removed;
}
*/
/**
* SP: Puts a stack in the given slot. WARNING: Any existing stack will be overriden!
* SMP: Registers the action without actually doing it.
*
* @param stack
* @param slot
* @param priority
private void put(ItemStack stack, int slot, int priority) {
if (log.getLevel() == Const.DEBUG) {
try {
log.info("Put: " + tree.getItems(getItemID(stack), getItemDamage(stack)).get(0) + " in " + slot);
} catch (NullPointerException e) {
log.info("Removed: null");
}
}
if (!isMultiplayer) {
putStackInSlot(slot, stack);
}
rulePriority[slot] = priority;
keywordOrder[slot] = getItemOrder(getItemID(stack), getItemDamage(stack));
}
*/
private void computeLineSortingRules(int rowSize, boolean horizontal) {
rules = new Vector<InventoryConfigRule>();
Map<ItemTreeItem, Integer> stats = computeContainerStats();
List<ItemTreeItem> itemOrder = new ArrayList<ItemTreeItem>();
int distinctItems = stats.size();
int columnSize = getContainerColumnSize(rowSize);
int spaceWidth;
int spaceHeight;
int availableSlots = size;
int remainingStacks = 0;
for (Integer stacks : stats.values()) {
remainingStacks += stacks;
}
// No need to compute rules for an empty chest
if (distinctItems == 0)
return;
// (Partially) sort stats by decreasing item stack count
List<ItemTreeItem> unorderedItems = new ArrayList<ItemTreeItem>(stats.keySet());
boolean hasStacksToOrderFirst = true;
while (hasStacksToOrderFirst) {
hasStacksToOrderFirst = false;
for (ItemTreeItem item : unorderedItems) {
Integer value = stats.get(item);
if (value > ((horizontal) ? rowSize : columnSize)
&& !itemOrder.contains(item)) {
hasStacksToOrderFirst = true;
itemOrder.add(item);
unorderedItems.remove(item);
break;
}
}
}
Collections.sort(unorderedItems, Collections.reverseOrder());
itemOrder.addAll(unorderedItems);
// Define space size used for each item type.
if (horizontal) {
spaceHeight = 1;
spaceWidth = rowSize/((distinctItems+columnSize-1)/columnSize);
}
else {
spaceWidth = 1;
spaceHeight = columnSize/((distinctItems+rowSize-1)/rowSize);
}
char row = 'a', maxRow = (char) (row - 1 + columnSize);
char column = '1', maxColumn = (char) (column - 1 + rowSize);
// Create rules
Iterator<ItemTreeItem> it = itemOrder.iterator();
while (it.hasNext()) {
ItemTreeItem item = it.next();
// Adapt rule dimensions to fit the amount
int thisSpaceWidth = spaceWidth,
thisSpaceHeight = spaceHeight;
while (stats.get(item) > thisSpaceHeight*thisSpaceWidth) {
if (horizontal) {
if (column + thisSpaceWidth < maxColumn) {
thisSpaceWidth = maxColumn - column + 1;
}
else if (row + thisSpaceHeight < maxRow) {
thisSpaceHeight++;
}
else {
break;
}
}
else {
if (row + thisSpaceHeight < maxRow) {
thisSpaceHeight = maxRow - row + 1;
}
else if (column + thisSpaceWidth < maxColumn) {
thisSpaceWidth++;
}
else {
break;
}
}
}
// Adjust line/column ends to fill empty space
if (horizontal && (column + thisSpaceWidth == maxColumn)) {
thisSpaceWidth++;
}
else if (!horizontal && row + thisSpaceHeight == maxRow) {
thisSpaceHeight++;
}
// Create rule
String constraint = row + "" + column + "-"
+ (char)(row - 1 + thisSpaceHeight)
+ (char)(column - 1 + thisSpaceWidth);
if (!horizontal) {
constraint += 'v';
}
rules.add(new InventoryConfigRule(tree, constraint, item.getName(), size, rowSize));
// Check if ther's still room for more rules
availableSlots -= thisSpaceHeight*thisSpaceWidth;
remainingStacks -= stats.get(item);
if (availableSlots >= remainingStacks) {
// Move origin for next rule
if (horizontal) {
if (column + thisSpaceWidth + spaceWidth <= maxColumn + 1) {
column += thisSpaceWidth;
}
else {
column = '1';
row += thisSpaceHeight;
}
}
else {
if (row + thisSpaceHeight + spaceHeight <= maxRow + 1) {
row += thisSpaceHeight;
}
else {
row = 'a';
column += thisSpaceWidth;
}
}
if (row > maxRow || column > maxColumn)
break;
}
else {
break;
}
}
String defaultRule;
if (horizontal) {
defaultRule = maxRow + "1-a" + maxColumn;
}
else {
defaultRule = "a" + maxColumn + "-" + maxRow + "1v";
}
rules.add(new InventoryConfigRule(tree, defaultRule,
tree.getRootCategory().getName(), size, rowSize));
}
private Map<ItemTreeItem, Integer> computeContainerStats() {
Map<ItemTreeItem, Integer> stats = new HashMap<ItemTreeItem, Integer>();
Map<Integer, ItemTreeItem> itemSearch = new HashMap<Integer, ItemTreeItem>();
for (int i = 0; i < size; i++) {
ItemStack stack = containerMgr.getItemStack(i);
if (stack != null) {
int itemSearchKey = getItemID(stack)*100000 +
((getMaxStackSize(stack) != 1) ? getItemDamage(stack) : 0);
ItemTreeItem item = itemSearch.get(itemSearchKey);
if (item == null) {
item = tree.getItems(getItemID(stack),
getItemDamage(stack)).get(0);
itemSearch.put(itemSearchKey, item);
stats.put(item, 1);
}
else {
stats.put(item, stats.get(item) + 1);
}
}
}
return stats;
}
private int getContainerColumnSize(int rowSize) {
return size / rowSize;
}
} |
package mendel.test;
import mendel.data.Metadata;
import mendel.fs.Block;
import mendel.fs.MendelFileSystem;
import mendel.query.ExactQuery;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;
public class QueryTest {
public static void main(String[] args) throws Exception {
List<Block> blocks = new ArrayList<>();
MendelFileSystem fs =
new MendelFileSystem("C:\\Users\\Ctolooee\\Desktop\\fs");
for (int i = 0; i < 10; i++) {
blocks.add(generateBlock());
}
String seq = "CCCCCCCCC";
String uuid = UUID.nameUUIDFromBytes(seq.getBytes()).toString();
Metadata meta = new Metadata(seq, uuid);
blocks.add(new Block(meta, seq.getBytes()));
/* Insert the blocks */
if (blocks.size() > 0) {
for (Block block : blocks) {
fs.storeBlock(block);
}
}
/* Execute some queries */
ExactQuery q = new ExactQuery("CCCCCCCCC");
System.out.println("Query: " + q);
Block result = fs.query(q);
System.out.println(result.getMetadata().getName());
fs.shutdown();
}
private static Block generateBlock() {
String[] chars = {"A", "C", "T", "G"};
Random rand = new Random();
String sequence = "";
for (int i = 0; i < 9; i++) {
sequence += chars[rand.nextInt(4)];
}
Metadata meta = new Metadata(sequence,
UUID.nameUUIDFromBytes(sequence.getBytes()).toString());
return new Block(meta, sequence.getBytes());
}
} |
package se.somath.publisher;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.LineIterator;
import se.somath.publisher.excpetion.PublishException;
import se.somath.publisher.formatter.HtmlFormatter;
import se.somath.publisher.includer.SourceCodeIncluder;
import java.io.*;
import java.util.LinkedList;
import java.util.List;
public class Main {
public void publish(String sourceDirectory, String targetDirectory) {
String defaultFileName = "index.html";
try {
List<String> content = readSourceFile(sourceDirectory, defaultFileName);
content = formatHtml(content);
content = addIncludes(content);
writeTargetFile(targetDirectory, content, defaultFileName);
} catch (FileNotFoundException e) {
throw new PublishException(e);
} catch (IOException e) {
throw new PublishException(e);
}
}
private List<String> readSourceFile(String sourceDirectory, String fileName) throws FileNotFoundException {
List<String> content = new LinkedList<String>();
String sourceFileName = sourceDirectory + File.separator + fileName;
Reader sourceFileReader = new FileReader(sourceFileName);
LineIterator sourceFileIterator = new LineIterator(sourceFileReader);
while (sourceFileIterator.hasNext()) {
String currentLine = sourceFileIterator.nextLine();
content.add(currentLine);
}
return content;
}
private List<String> formatHtml(List<String> unFormattedContent) {
HtmlFormatter formatter = new HtmlFormatter();
return formatter.format(unFormattedContent);
}
private List<String> addIncludes(List<String> unIncludedContent) {
SourceCodeIncluder includer = new SourceCodeIncluder();
return includer.addIncludes(unIncludedContent);
}
private void writeTargetFile(String targetDirectory, List<String> content, String fileName) throws IOException {
String targetFileName = targetDirectory + File.separator + fileName;
File targetFile = new File(targetFileName);
createTargetDirectory(targetFile);
FileUtils.writeLines(targetFile, content);
}
private void createTargetDirectory(File targetFile) {
File targetDirectory = targetFile.getParentFile();
//noinspection ResultOfMethodCallIgnored
targetDirectory.mkdirs();
}
} |
package org.waterforpeople.mapping.app.web;
import static com.google.appengine.api.labs.taskqueue.TaskOptions.Builder.url;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBException;
import org.apache.commons.lang.StringEscapeUtils;
import org.waterforpeople.mapping.app.web.dto.SurveyAssemblyRequest;
import org.waterforpeople.mapping.dao.SurveyContainerDao;
import com.gallatinsystems.common.domain.UploadStatusContainer;
import com.gallatinsystems.common.util.UploadUtil;
import com.gallatinsystems.common.util.ZipUtil;
import com.gallatinsystems.framework.rest.AbstractRestApiServlet;
import com.gallatinsystems.framework.rest.RestRequest;
import com.gallatinsystems.framework.rest.RestResponse;
import com.gallatinsystems.messaging.dao.MessageDao;
import com.gallatinsystems.messaging.domain.Message;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.dao.QuestionGroupDao;
import com.gallatinsystems.survey.dao.SurveyXMLFragmentDao;
import com.gallatinsystems.survey.domain.Question;
import com.gallatinsystems.survey.domain.QuestionGroup;
import com.gallatinsystems.survey.domain.QuestionHelpMedia;
import com.gallatinsystems.survey.domain.QuestionOption;
import com.gallatinsystems.survey.domain.ScoringRule;
import com.gallatinsystems.survey.domain.SurveyContainer;
import com.gallatinsystems.survey.domain.SurveyXMLFragment;
import com.gallatinsystems.survey.domain.SurveyXMLFragment.FRAGMENT_TYPE;
import com.gallatinsystems.survey.domain.Translation;
import com.gallatinsystems.survey.domain.xml.AltText;
import com.gallatinsystems.survey.domain.xml.Dependency;
import com.gallatinsystems.survey.domain.xml.Help;
import com.gallatinsystems.survey.domain.xml.ObjectFactory;
import com.gallatinsystems.survey.domain.xml.Option;
import com.gallatinsystems.survey.domain.xml.Options;
import com.gallatinsystems.survey.domain.xml.Score;
import com.gallatinsystems.survey.domain.xml.Scoring;
import com.gallatinsystems.survey.domain.xml.ValidationRule;
import com.gallatinsystems.survey.xml.SurveyXMLAdapter;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.labs.taskqueue.Queue;
import com.google.appengine.api.labs.taskqueue.QueueFactory;
import com.google.appengine.api.labs.taskqueue.TaskOptions;
public class SurveyAssemblyServlet extends AbstractRestApiServlet {
private static final Logger log = Logger
.getLogger(SurveyAssemblyServlet.class.getName());
// private static TextConstants CONSTANTS = ;
private static final long serialVersionUID = -6044156962558183224L;
public static final String FREE_QUESTION_TYPE = "free";
public static final String OPTION_QUESTION_TYPE = "option";
public static final String GEO_QUESTION_TYPE = "geo";
public static final String VIDEO_QUESTION_TYPE = "video";
public static final String PHOTO_QUESTION_TYPE = "photo";
public static final String SCAN_QUESTION_TYPE = "scan";
public static final String STRENGTH_QUESTION_TYPE = "strength";
private static final String SURVEY_UPLOAD_URL = "surveyuploadurl";
private static final String SURVEY_UPLOAD_DIR = "surveyuploaddir";
private static final String SURVEY_UPLOAD_SIG = "surveyuploadsig";
private static final String SURVEY_UPLOAD_POLICY = "surveyuploadpolicy";
private static final String S3_ID = "aws_identifier";
@Override
protected RestRequest convertRequest() throws Exception {
HttpServletRequest req = getRequest();
RestRequest restRequest = new SurveyAssemblyRequest();
restRequest.populateFromHttpRequest(req);
return restRequest;
}
@Override
protected RestResponse handleRequest(RestRequest req) throws Exception {
RestResponse response = new RestResponse();
SurveyAssemblyRequest importReq = (SurveyAssemblyRequest) req;
if (SurveyAssemblyRequest.ASSEMBLE_SURVEY.equalsIgnoreCase(importReq
.getAction())) {
// assembleSurvey(importReq.getSurveyId());
assembleSurveyOnePass(importReq.getSurveyId());
} else if (SurveyAssemblyRequest.DISPATCH_ASSEMBLE_QUESTION_GROUP
.equalsIgnoreCase(importReq.getAction())) {
this.dispatchAssembleQuestionGroup(importReq.getSurveyId(),
importReq.getQuestionGroupId(),
importReq.getTransactionId());
} else if (SurveyAssemblyRequest.ASSEMBLE_QUESTION_GROUP
.equalsIgnoreCase(importReq.getAction())) {
assembleQuestionGroups(importReq.getSurveyId(),
importReq.getTransactionId());
} else if (SurveyAssemblyRequest.DISTRIBUTE_SURVEY
.equalsIgnoreCase(importReq.getAction())) {
uploadSurvey(importReq.getSurveyId(), importReq.getTransactionId());
} else if (SurveyAssemblyRequest.CLEANUP.equalsIgnoreCase(importReq
.getAction())) {
cleanupFragments(importReq.getSurveyId(),
importReq.getTransactionId());
}
return response;
}
/**
* uploads full survey XML to S3
*
* @param surveyId
*/
private void uploadSurvey(Long surveyId, Long transactionId) {
SurveyContainerDao scDao = new SurveyContainerDao();
SurveyContainer sc = scDao.findBySurveyId(surveyId);
Properties props = System.getProperties();
String document = sc.getSurveyDocument().getValue();
UploadUtil.sendStringAsFile(sc.getSurveyId() + ".xml", document,
props.getProperty(SURVEY_UPLOAD_DIR),
props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID),
props.getProperty(SURVEY_UPLOAD_POLICY),
props.getProperty(SURVEY_UPLOAD_SIG), "text/xml");
ByteArrayOutputStream os = ZipUtil.generateZip(document,
sc.getSurveyId() + ".xml");
UploadUtil.upload(os, sc.getSurveyId() + ".zip",
props.getProperty(SURVEY_UPLOAD_DIR),
props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID),
props.getProperty(SURVEY_UPLOAD_POLICY),
props.getProperty(SURVEY_UPLOAD_SIG), "application/zip", null);
sendQueueMessage(SurveyAssemblyRequest.CLEANUP, surveyId, null,
transactionId);
}
/**
* deletes fragments for the survey
*
* @param surveyId
*/
private void cleanupFragments(Long surveyId, Long transactionId) {
SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao();
sxmlfDao.deleteFragmentsForSurvey(surveyId, transactionId);
}
@Override
protected void writeOkResponse(RestResponse resp) throws Exception {
// no-op
}
private void assembleSurveyOnePass(Long surveyId) {
/**************
* 1, Select survey based on surveyId 2. Retrieve all question groups
* fire off queue tasks
*/
// Swap with proper UUID
Long transactionId = new Random().nextLong();
String surveyHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><survey>";
String surveyFooter = "</survey>";
QuestionGroupDao qgDao = new QuestionGroupDao();
TreeMap<Integer, QuestionGroup> qgList = qgDao
.listQuestionGroupsBySurvey(surveyId);
if (qgList != null) {
StringBuilder surveyXML = new StringBuilder();
surveyXML.append(surveyHeader);
for (QuestionGroup item : qgList.values()) {
surveyXML.append(buildQuestionGroupXML(item));
}
surveyXML.append(surveyFooter);
UploadStatusContainer uc = uploadSurveyXML(surveyId,
surveyXML.toString());
Message message = new Message();
message.setActionAbout("surveyAssembly");
message.setObjectId(surveyId);
// String messageText = CONSTANTS.surveyPublishOkMessage() + " "
// + url;
if (uc.getUploadedFile() && uc.getUploadedZip()) {
String messageText = "Published. Please check: " + uc.getUrl();
message.setShortMessage(messageText);
if (qgList != null && qgList.size() > 0 && qgList.get(0)!=null) {
message.setObjectTitle(qgList.get(0).getPath());
}
message.setTransactionUUID(transactionId.toString());
MessageDao messageDao = new MessageDao();
messageDao.save(message);
} else {
// String messageText =
// CONSTANTS.surveyPublishErrorMessage();
String messageText = "Failed to publish: " + surveyId + "\n"
+ uc.getMessage();
message.setTransactionUUID(transactionId.toString());
message.setMessage(messageText);
MessageDao messageDao = new MessageDao();
messageDao.save(message);
}
}
}
public UploadStatusContainer uploadSurveyXML(Long surveyId, String surveyXML) {
Properties props = System.getProperties();
String document = surveyXML;
Boolean uploadedFile = UploadUtil.sendStringAsFile(surveyId + ".xml",
document, props.getProperty(SURVEY_UPLOAD_DIR),
props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID),
props.getProperty(SURVEY_UPLOAD_POLICY),
props.getProperty(SURVEY_UPLOAD_SIG), "text/xml");
ByteArrayOutputStream os = ZipUtil.generateZip(document, surveyId
+ ".xml");
UploadStatusContainer uc = new UploadStatusContainer();
Boolean uploadedZip = UploadUtil.upload(os, surveyId + ".zip",
props.getProperty(SURVEY_UPLOAD_DIR),
props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID),
props.getProperty(SURVEY_UPLOAD_POLICY),
props.getProperty(SURVEY_UPLOAD_SIG), "application/zip", uc);
uc.setUploadedFile(uploadedFile);
uc.setUploadedZip(uploadedZip);
uc.setUrl(props.getProperty(SURVEY_UPLOAD_URL)
+ props.getProperty(SURVEY_UPLOAD_DIR) + "/" + surveyId
+ ".xml");
return uc;
}
public String buildQuestionGroupXML(QuestionGroup item) {
QuestionDao questionDao = new QuestionDao();
QuestionGroupDao questionGroupDao = new QuestionGroupDao();
QuestionGroup group = questionGroupDao.getByKey(item.getKey().getId());
TreeMap<Integer, Question> questionList = questionDao
.listQuestionsByQuestionGroup(item.getKey().getId(), true);
StringBuilder sb = new StringBuilder("<questionGroup><heading>")
.append(StringEscapeUtils.escapeXml(group.getCode())).append(
"</heading>");
int count = 0;
if (questionList != null) {
for (Question q : questionList.values()) {
sb.append(marshallQuestion(q));
count++;
}
}
return sb.toString() + "</questionGroup>";
}
private void assembleSurvey(Long surveyId) {
/**************
* 1, Select survey based on surveyId 2. Retrieve all question groups
* fire off queue tasks
*/
QuestionGroupDao qgDao = new QuestionGroupDao();
TreeMap<Integer, QuestionGroup> qgList = qgDao
.listQuestionGroupsBySurvey(surveyId);
if (qgList != null) {
ArrayList<Long> questionGroupIdList = new ArrayList<Long>();
StringBuilder builder = new StringBuilder();
int count = 1;
for (QuestionGroup item : qgList.values()) {
questionGroupIdList.add(item.getKey().getId());
builder.append(item.getKey().getId());
if (count < qgList.size()) {
builder.append(",");
}
count++;
}
count = 0;
Long transactionId = new Random().nextLong();
sendQueueMessage(
SurveyAssemblyRequest.DISPATCH_ASSEMBLE_QUESTION_GROUP,
surveyId, builder.toString(), transactionId);
}
}
/**
* sends a message to the task queue for survey assembly
*
* @param action
* @param surveyId
* @param questionGroups
*/
private void sendQueueMessage(String action, Long surveyId,
String questionGroups, Long transactionId) {
Queue surveyAssemblyQueue = QueueFactory.getQueue("surveyAssembly");
TaskOptions task = url("/app_worker/surveyassembly").param("action",
action).param("surveyId", surveyId.toString());
if (questionGroups != null) {
task.param("questionGroupId", questionGroups);
}
if (transactionId != null) {
task.param("transactionId", transactionId.toString());
}
surveyAssemblyQueue.add(task);
}
private void dispatchAssembleQuestionGroup(Long surveyId,
String questionGroupIds, Long transactionId) {
boolean isLast = true;
String currentId = questionGroupIds;
String remainingIds = null;
if (questionGroupIds.contains(",")) {
isLast = false;
currentId = questionGroupIds.substring(0,
questionGroupIds.indexOf(","));
remainingIds = questionGroupIds.substring(questionGroupIds
.indexOf(",") + 1);
}
QuestionDao questionDao = new QuestionDao();
QuestionGroupDao questionGroupDao = new QuestionGroupDao();
QuestionGroup group = questionGroupDao.getByKey(Long
.parseLong(currentId));
TreeMap<Integer, Question> questionList = questionDao
.listQuestionsByQuestionGroup(Long.parseLong(currentId), true);
StringBuilder sb = new StringBuilder("<questionGroup><heading>")
.append(group.getCode()).append("</heading>");
int count = 0;
if (questionList != null) {
for (Question q : questionList.values()) {
sb.append(marshallQuestion(q));
count++;
}
}
SurveyXMLFragment sxf = new SurveyXMLFragment();
sxf.setSurveyId(surveyId);
sxf.setQuestionGroupId(Long.parseLong(currentId));
sxf.setFragmentOrder(group.getOrder());
sxf.setFragment(new Text(sb.append("</questionGroup>").toString()));
sxf.setTransactionId(transactionId);
sxf.setFragmentType(FRAGMENT_TYPE.QUESTION_GROUP);
SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao();
sxmlfDao.save(sxf);
if (isLast) {
// Assemble the fragments
sendQueueMessage(SurveyAssemblyRequest.ASSEMBLE_QUESTION_GROUP,
surveyId, null, transactionId);
} else {
sendQueueMessage(
SurveyAssemblyRequest.DISPATCH_ASSEMBLE_QUESTION_GROUP,
surveyId, remainingIds, transactionId);
}
}
private String marshallQuestion(Question q) {
SurveyXMLAdapter sax = new SurveyXMLAdapter();
ObjectFactory objFactory = new ObjectFactory();
com.gallatinsystems.survey.domain.xml.Question qXML = objFactory
.createQuestion();
qXML.setId(new String("" + q.getKey().getId() + ""));
// ToDo fix
qXML.setMandatory("false");
if (q.getText() != null) {
com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text();
t.setContent(q.getText());
qXML.setText(t);
}
List<Help> helpList = new ArrayList<Help>();
// this is here for backward compatibility
if (q.getTip() != null) {
Help tip = new Help();
com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text();
t.setContent(q.getTip());
tip.setText(t);
tip.setType("tip");
if (q.getTip() != null && q.getTip().trim().length() > 0
&& !"null".equalsIgnoreCase(q.getTip().trim())) {
helpList.add(tip);
}
}
if (q.getQuestionHelpMediaMap() != null) {
for (QuestionHelpMedia helpItem : q.getQuestionHelpMediaMap()
.values()) {
Help tip = new Help();
com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text();
t.setContent(helpItem.getText());
if (helpItem.getType() == QuestionHelpMedia.Type.TEXT) {
tip.setType("tip");
} else {
tip.setType(helpItem.getType().toString().toLowerCase());
}
if (helpItem.getTranslationMap() != null) {
List<AltText> translationList = new ArrayList<AltText>();
for (Translation trans : helpItem.getTranslationMap()
.values()) {
AltText aText = new AltText();
aText.setContent(trans.getText());
aText.setLanguage(trans.getLanguageCode());
aText.setType("translation");
translationList.add(aText);
}
if (translationList.size() > 0) {
tip.setAltText(translationList);
}
}
helpList.add(tip);
}
}
if (helpList.size() > 0) {
qXML.setHelp(helpList);
}
if (q.getValidationRule() != null) {
ValidationRule validationRule = objFactory.createValidationRule();
// TODO set validation rule xml
// validationRule.setAllowDecimal(value)
}
qXML.setAltText(formAltText(q.getTranslationMap()));
if (q.getType().equals(Question.Type.FREE_TEXT)) {
qXML.setType(FREE_QUESTION_TYPE);
} else if (q.getType().equals(Question.Type.GEO)) {
qXML.setType(GEO_QUESTION_TYPE);
} else if (q.getType().equals(Question.Type.NUMBER)) {
qXML.setType(FREE_QUESTION_TYPE);
ValidationRule vrule = new ValidationRule();
vrule.setValidationType("numeric");
vrule.setSigned("false");
qXML.setValidationRule(vrule);
} else if (q.getType().equals(Question.Type.OPTION)) {
qXML.setType(OPTION_QUESTION_TYPE);
} else if (q.getType().equals(Question.Type.PHOTO)) {
qXML.setType(PHOTO_QUESTION_TYPE);
} else if (q.getType().equals(Question.Type.VIDEO)) {
qXML.setType(VIDEO_QUESTION_TYPE);
} else if (q.getType().equals(Question.Type.SCAN)) {
qXML.setType(SCAN_QUESTION_TYPE);
} else if (q.getType().equals(Question.Type.NAME)) {
qXML.setType(FREE_QUESTION_TYPE);
ValidationRule vrule = new ValidationRule();
vrule.setValidationType("name");
qXML.setValidationRule(vrule);
} else if (q.getType().equals(Question.Type.STRENGTH)) {
qXML.setType(STRENGTH_QUESTION_TYPE);
}
if (q.getOrder() != null) {
qXML.setOrder(q.getOrder().toString());
}
if (q.getMandatoryFlag() != null) {
qXML.setMandatory(q.getMandatoryFlag().toString());
}
Dependency dependency = objFactory.createDependency();
if (q.getDependentQuestionId() != null) {
dependency.setQuestion(q.getDependentQuestionId().toString());
dependency.setAnswerValue(q.getDependentQuestionAnswer());
qXML.setDependency(dependency);
}
if (q.getQuestionOptionMap() != null
&& q.getQuestionOptionMap().size() > 0) {
Options options = objFactory.createOptions();
if (q.getAllowOtherFlag() != null) {
options.setAllowOther(q.getAllowOtherFlag().toString());
}
if (q.getAllowMultipleFlag() != null) {
options.setAllowMultiple(q.getAllowMultipleFlag().toString());
}
ArrayList<Option> optionList = new ArrayList<Option>();
for (QuestionOption qo : q.getQuestionOptionMap().values()) {
Option option = objFactory.createOption();
com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text();
t.setContent(qo.getText());
option.addContent(t);
option.setValue(qo.getCode() != null ? qo.getCode() : qo
.getText());
List<AltText> altTextList = formAltText(qo.getTranslationMap());
if (altTextList != null) {
for (AltText alt : altTextList) {
option.addContent(alt);
}
}
optionList.add(option);
}
options.setOption(optionList);
qXML.setOptions(options);
}
if (q.getScoringRules() != null) {
Scoring scoring = new Scoring();
for (ScoringRule rule : q.getScoringRules()) {
Score score = new Score();
if (scoring.getType() == null) {
scoring.setType(rule.getType().toLowerCase());
}
score.setRangeHigh(rule.getRangeMax());
score.setRangeLow(rule.getRangeMin());
score.setValue(rule.getValue());
scoring.addScore(score);
}
if (scoring.getScore() != null && scoring.getScore().size() > 0) {
qXML.setScoring(scoring);
}
}
String questionDocument = null;
try {
questionDocument = sax.marshal(qXML);
} catch (JAXBException e) {
log.log(Level.SEVERE, "Could not marshal question: " + qXML, e);
}
questionDocument = questionDocument
.replace(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>",
"");
return questionDocument;
}
private List<AltText> formAltText(Map<String, Translation> translationMap) {
List<AltText> altTextList = new ArrayList<AltText>();
if (translationMap != null) {
for (Translation lang : translationMap.values()) {
AltText alt = new AltText();
alt.setContent(lang.getText());
alt.setType("translation");
alt.setLanguage(lang.getLanguageCode());
altTextList.add(alt);
}
}
return altTextList;
}
private void assembleQuestionGroups(Long surveyId, Long transactionId) {
SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao();
List<SurveyXMLFragment> sxmlfList = sxmlfDao.listSurveyFragments(
surveyId, SurveyXMLFragment.FRAGMENT_TYPE.QUESTION_GROUP,
transactionId);
StringBuilder sbQG = new StringBuilder();
for (SurveyXMLFragment item : sxmlfList) {
sbQG.append(item.getFragment().getValue());
}
StringBuilder completeSurvey = new StringBuilder();
String surveyHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><survey>";
String surveyFooter = "</survey>";
completeSurvey.append(surveyHeader);
completeSurvey.append(sbQG.toString());
sbQG = null;
completeSurvey.append(surveyFooter);
SurveyContainerDao scDao = new SurveyContainerDao();
SurveyContainer sc = scDao.findBySurveyId(surveyId);
if (sc == null) {
sc = new SurveyContainer();
}
sc.setSurveyDocument(new Text(completeSurvey.toString()));
sc.setSurveyId(surveyId);
scDao.save(sc);
sendQueueMessage(SurveyAssemblyRequest.DISTRIBUTE_SURVEY, surveyId,
null, transactionId);
}
} |
package org.waterforpeople.mapping.app.web;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.log4j.Logger;
import org.waterforpeople.mapping.app.web.dto.SurveyAssemblyRequest;
import org.waterforpeople.mapping.dao.SurveyContainerDao;
import com.gallatinsystems.common.domain.UploadStatusContainer;
import com.gallatinsystems.common.util.PropertyUtil;
import com.gallatinsystems.common.util.UploadUtil;
import com.gallatinsystems.common.util.ZipUtil;
import com.gallatinsystems.framework.rest.AbstractRestApiServlet;
import com.gallatinsystems.framework.rest.RestRequest;
import com.gallatinsystems.framework.rest.RestResponse;
import com.gallatinsystems.messaging.dao.MessageDao;
import com.gallatinsystems.messaging.domain.Message;
import com.gallatinsystems.survey.dao.QuestionDao;
import com.gallatinsystems.survey.dao.QuestionGroupDao;
import com.gallatinsystems.survey.dao.SurveyDAO;
import com.gallatinsystems.survey.dao.SurveyGroupDAO;
import com.gallatinsystems.survey.dao.SurveyUtils;
import com.gallatinsystems.survey.dao.SurveyXMLFragmentDao;
import com.gallatinsystems.survey.dao.TranslationDao;
import com.gallatinsystems.survey.domain.Question;
import com.gallatinsystems.survey.domain.QuestionGroup;
import com.gallatinsystems.survey.domain.QuestionHelpMedia;
import com.gallatinsystems.survey.domain.QuestionOption;
import com.gallatinsystems.survey.domain.ScoringRule;
import com.gallatinsystems.survey.domain.Survey;
import com.gallatinsystems.survey.domain.SurveyContainer;
import com.gallatinsystems.survey.domain.SurveyGroup;
import com.gallatinsystems.survey.domain.SurveyXMLFragment;
import com.gallatinsystems.survey.domain.SurveyXMLFragment.FRAGMENT_TYPE;
import com.gallatinsystems.survey.domain.Translation;
import com.gallatinsystems.survey.domain.xml.AltText;
import com.gallatinsystems.survey.domain.xml.Dependency;
import com.gallatinsystems.survey.domain.xml.Help;
import com.gallatinsystems.survey.domain.xml.ObjectFactory;
import com.gallatinsystems.survey.domain.xml.Option;
import com.gallatinsystems.survey.domain.xml.Options;
import com.gallatinsystems.survey.domain.xml.Score;
import com.gallatinsystems.survey.domain.xml.Scoring;
import com.gallatinsystems.survey.domain.xml.ValidationRule;
import com.gallatinsystems.survey.xml.SurveyXMLAdapter;
import com.google.appengine.api.backends.BackendServiceFactory;
import com.google.appengine.api.datastore.Text;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;
public class SurveyAssemblyServlet extends AbstractRestApiServlet {
private static final Logger log = Logger
.getLogger(SurveyAssemblyServlet.class.getName());
private static final int BACKEND_QUESTION_THRESHOLD = 80;
private static final String BACKEND_PUBLISH_PROP = "backendpublish";
private static final long serialVersionUID = -6044156962558183224L;
private static final String OPTION_RENDER_MODE_PROP = "optionRenderMode";
public static final String FREE_QUESTION_TYPE = "free";
public static final String OPTION_QUESTION_TYPE = "option";
public static final String GEO_QUESTION_TYPE = "geo";
public static final String VIDEO_QUESTION_TYPE = "video";
public static final String PHOTO_QUESTION_TYPE = "photo";
public static final String SCAN_QUESTION_TYPE = "scan";
public static final String STRENGTH_QUESTION_TYPE = "strength";
public static final String DATE_QUESTION_TYPE = "date";
private static final String SURVEY_UPLOAD_URL = "surveyuploadurl";
private static final String SURVEY_UPLOAD_DIR = "surveyuploaddir";
private static final String SURVEY_UPLOAD_SIG = "surveyuploadsig";
private static final String SURVEY_UPLOAD_POLICY = "surveyuploadpolicy";
private static final String S3_ID = "aws_identifier";
private Random randomNumber = new Random();
@Override
protected RestRequest convertRequest() throws Exception {
HttpServletRequest req = getRequest();
RestRequest restRequest = new SurveyAssemblyRequest();
restRequest.populateFromHttpRequest(req);
return restRequest;
}
@Override
protected RestResponse handleRequest(RestRequest req) throws Exception {
RestResponse response = new RestResponse();
SurveyAssemblyRequest importReq = (SurveyAssemblyRequest) req;
if (SurveyAssemblyRequest.ASSEMBLE_SURVEY.equalsIgnoreCase(importReq
.getAction())) {
QuestionDao questionDao = new QuestionDao();
boolean useBackend = false;
// make sure we're not already running on a backend and that we are
// allowed to use one
if (!importReq.getIsForwarded()
&& "true".equalsIgnoreCase(PropertyUtil
.getProperty(BACKEND_PUBLISH_PROP))) {
// if we're allowed to use a backend, then check to see if we
// need to (based on survey size)
List<Question> questionList = questionDao
.listQuestionsBySurvey(importReq.getSurveyId());
if (questionList != null
&& questionList.size() > BACKEND_QUESTION_THRESHOLD) {
useBackend = true;
}
}
if (useBackend) {
com.google.appengine.api.taskqueue.TaskOptions options = com.google.appengine.api.taskqueue.TaskOptions.Builder
.withUrl("/app_worker/surveyassembly")
.param(SurveyAssemblyRequest.ACTION_PARAM,
SurveyAssemblyRequest.ASSEMBLE_SURVEY)
.param(SurveyAssemblyRequest.IS_FWD_PARAM, "true")
.param(SurveyAssemblyRequest.SURVEY_ID_PARAM,
importReq.getSurveyId().toString());
// change the host so the queue invokes the backend
options = options
.header("Host",
BackendServiceFactory.getBackendService()
.getBackendAddress("dataprocessor"));
com.google.appengine.api.taskqueue.Queue queue = com.google.appengine.api.taskqueue.QueueFactory
.getQueue("surveyAssembly");
queue.add(options);
} else {
// assembleSurvey(importReq.getSurveyId());
assembleSurveyOnePass(importReq.getSurveyId());
}
List<Long> ids = new ArrayList<Long>();
ids.add(importReq.getSurveyId());
SurveyUtils.notifyReportService(ids, "invalidate");
} else if (SurveyAssemblyRequest.DISPATCH_ASSEMBLE_QUESTION_GROUP
.equalsIgnoreCase(importReq.getAction())) {
this.dispatchAssembleQuestionGroup(importReq.getSurveyId(),
importReq.getQuestionGroupId(),
importReq.getTransactionId());
} else if (SurveyAssemblyRequest.ASSEMBLE_QUESTION_GROUP
.equalsIgnoreCase(importReq.getAction())) {
assembleQuestionGroups(importReq.getSurveyId(),
importReq.getTransactionId());
} else if (SurveyAssemblyRequest.DISTRIBUTE_SURVEY
.equalsIgnoreCase(importReq.getAction())) {
uploadSurvey(importReq.getSurveyId(), importReq.getTransactionId());
} else if (SurveyAssemblyRequest.CLEANUP.equalsIgnoreCase(importReq
.getAction())) {
cleanupFragments(importReq.getSurveyId(),
importReq.getTransactionId());
}
return response;
}
/**
* uploads full survey XML to S3
*
* @param surveyId
*/
private void uploadSurvey(Long surveyId, Long transactionId) {
SurveyContainerDao scDao = new SurveyContainerDao();
SurveyContainer sc = scDao.findBySurveyId(surveyId);
Properties props = System.getProperties();
String document = sc.getSurveyDocument().getValue();
boolean uploadedFile = UploadUtil.sendStringAsFile(sc.getSurveyId()
+ ".xml", document, props.getProperty(SURVEY_UPLOAD_DIR),
props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID),
props.getProperty(SURVEY_UPLOAD_POLICY),
props.getProperty(SURVEY_UPLOAD_SIG), "text/xml");
ByteArrayOutputStream os = ZipUtil.generateZip(document,
sc.getSurveyId() + ".xml");
boolean uploadedZip = UploadUtil.upload(os, sc.getSurveyId() + ".zip",
props.getProperty(SURVEY_UPLOAD_DIR),
props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID),
props.getProperty(SURVEY_UPLOAD_POLICY),
props.getProperty(SURVEY_UPLOAD_SIG), "application/zip", null);
sendQueueMessage(SurveyAssemblyRequest.CLEANUP, surveyId, null,
transactionId);
Message message = new Message();
message.setActionAbout("surveyAssembly");
message.setObjectId(surveyId);
// String messageText = CONSTANTS.surveyPublishOkMessage() + " "
// + url;
if (uploadedFile && uploadedZip) {
// increment the version so devices know to pick up the changes
SurveyDAO surveyDao = new SurveyDAO();
surveyDao.incrementVersion(surveyId);
String messageText = "Published. Please check: "
+ props.getProperty(SURVEY_UPLOAD_URL)
+ props.getProperty(SURVEY_UPLOAD_DIR) + "/" + surveyId
+ ".xml";
message.setShortMessage(messageText);
Survey s = surveyDao.getById(surveyId);
if (s != null) {
message.setObjectTitle(s.getPath() + "/" + s.getName());
}
message.setTransactionUUID(transactionId.toString());
MessageDao messageDao = new MessageDao();
messageDao.save(message);
} else {
// String messageText =
// CONSTANTS.surveyPublishErrorMessage();
String messageText = "Failed to publish: " + surveyId + "\n";
message.setTransactionUUID(transactionId.toString());
message.setShortMessage(messageText);
MessageDao messageDao = new MessageDao();
messageDao.save(message);
}
}
/**
* deletes fragments for the survey
*
* @param surveyId
*/
private void cleanupFragments(Long surveyId, Long transactionId) {
SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao();
sxmlfDao.deleteFragmentsForSurvey(surveyId, transactionId);
}
@Override
protected void writeOkResponse(RestResponse resp) throws Exception {
HttpServletResponse httpResp = getResponse();
httpResp.setStatus(HttpServletResponse.SC_OK);
// httpResp.setContentType("text/plain");
httpResp.getWriter().print("OK");
httpResp.flushBuffer();
}
private void assembleSurveyOnePass(Long surveyId) {
/**************
* 1, Select survey based on surveyId 2. Retrieve all question groups fire off queue tasks
*/
log.warn("Starting assembly of " + surveyId);
// Swap with proper UUID
SurveyDAO surveyDao = new SurveyDAO();
Survey s = surveyDao.getById(surveyId);
SurveyGroupDAO surveyGroupDao = new SurveyGroupDAO();
SurveyGroup sg = surveyGroupDao.getByKey(s.getSurveyGroupId());
Long transactionId = randomNumber.nextLong();
String lang = "en";
if (s != null && s.getDefaultLanguageCode() != null) {
lang = s.getDefaultLanguageCode();
}
final String version = s.getVersion() == null ? "" : "version='"
+ s.getVersion() + "'";
String surveyGroupId = "";
String surveyGroupName = "";
if (sg != null) {
surveyGroupId = "surveyGroupId=\"" + sg.getKey().getId() + "\"";
surveyGroupName = "surveyGroupName=\"" + sg.getCode() + "\"";
}
String sourceSurveyId = getSourceSurveyId(surveyId);
String sourceSurveyIdAttr = sourceSurveyId != null ? " sourceSurveyId=\"" + sourceSurveyId
+ "\"" : "";
String surveyHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><survey"
+ " defaultLanguageCode=\"" + lang + "\" " + version
+ " " + surveyGroupId + " " + surveyGroupName + sourceSurveyIdAttr + ">";
String surveyFooter = "</survey>";
QuestionGroupDao qgDao = new QuestionGroupDao();
TreeMap<Integer, QuestionGroup> qgList = qgDao
.listQuestionGroupsBySurvey(surveyId);
if (qgList != null) {
StringBuilder surveyXML = new StringBuilder();
surveyXML.append(surveyHeader);
for (QuestionGroup item : qgList.values()) {
log.warn("Assembling group " + item.getKey().getId()
+ " for survey " + surveyId);
surveyXML.append(buildQuestionGroupXML(item));
}
surveyXML.append(surveyFooter);
log.warn("Uploading " + surveyId);
UploadStatusContainer uc = uploadSurveyXML(surveyId,
surveyXML.toString());
Message message = new Message();
message.setActionAbout("surveyAssembly");
message.setObjectId(surveyId);
message.setObjectTitle(sg.getCode() + " / " + s.getName());
// String messageText = CONSTANTS.surveyPublishOkMessage() + " "
// + url;
if (uc.getUploadedFile() && uc.getUploadedZip()) {
// increment the version so devices know to pick up the changes
log.warn("Finishing assembly of " + surveyId);
surveyDao.incrementVersion(surveyId);
s.setStatus(Survey.Status.PUBLISHED);
surveyDao.save(s);
String messageText = "Published. Please check: " + uc.getUrl();
message.setShortMessage(messageText);
message.setTransactionUUID(transactionId.toString());
MessageDao messageDao = new MessageDao();
messageDao.save(message);
} else {
// String messageText =
// CONSTANTS.surveyPublishErrorMessage();
String messageText = "Failed to publish: " + surveyId + "\n"
+ uc.getMessage();
message.setTransactionUUID(transactionId.toString());
message.setShortMessage(messageText);
MessageDao messageDao = new MessageDao();
messageDao.save(message);
}
log.warn("Completed onepass assembly method for " + surveyId);
}
}
public UploadStatusContainer uploadSurveyXML(Long surveyId, String surveyXML) {
Properties props = System.getProperties();
String document = surveyXML;
Boolean uploadedFile = UploadUtil.sendStringAsFile(surveyId + ".xml",
document, props.getProperty(SURVEY_UPLOAD_DIR),
props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID),
props.getProperty(SURVEY_UPLOAD_POLICY),
props.getProperty(SURVEY_UPLOAD_SIG), "text/xml");
ByteArrayOutputStream os = ZipUtil.generateZip(document, surveyId
+ ".xml");
UploadStatusContainer uc = new UploadStatusContainer();
Boolean uploadedZip = UploadUtil.upload(os, surveyId + ".zip",
props.getProperty(SURVEY_UPLOAD_DIR),
props.getProperty(SURVEY_UPLOAD_URL), props.getProperty(S3_ID),
props.getProperty(SURVEY_UPLOAD_POLICY),
props.getProperty(SURVEY_UPLOAD_SIG), "application/zip", uc);
uc.setUploadedFile(uploadedFile);
uc.setUploadedZip(uploadedZip);
uc.setUrl(props.getProperty(SURVEY_UPLOAD_URL)
+ props.getProperty(SURVEY_UPLOAD_DIR) + "/" + surveyId
+ ".xml");
return uc;
}
public String buildQuestionGroupXML(QuestionGroup item) {
QuestionDao questionDao = new QuestionDao();
QuestionGroupDao questionGroupDao = new QuestionGroupDao();
QuestionGroup group = questionGroupDao.getByKey(item.getKey().getId());
TreeMap<Integer, Question> questionList = questionDao
.listQuestionsByQuestionGroup(item.getKey().getId(), true);
StringBuilder sb = new StringBuilder("<questionGroup><heading>")
.append(StringEscapeUtils.escapeXml(group.getCode())).append(
"</heading>");
if (questionList != null) {
for (Question q : questionList.values()) {
sb.append(marshallQuestion(q));
}
}
return sb.toString() + "</questionGroup>";
}
@SuppressWarnings("unused")
private void assembleSurvey(Long surveyId) {
/**************
* 1, Select survey based on surveyId 2. Retrieve all question groups fire off queue tasks
*/
QuestionGroupDao qgDao = new QuestionGroupDao();
TreeMap<Integer, QuestionGroup> qgList = qgDao
.listQuestionGroupsBySurvey(surveyId);
if (qgList != null) {
ArrayList<Long> questionGroupIdList = new ArrayList<Long>();
StringBuilder builder = new StringBuilder();
int count = 1;
for (QuestionGroup item : qgList.values()) {
questionGroupIdList.add(item.getKey().getId());
builder.append(item.getKey().getId());
if (count < qgList.size()) {
builder.append(",");
}
count++;
}
count = 0;
Long transactionId = randomNumber.nextLong();
sendQueueMessage(
SurveyAssemblyRequest.DISPATCH_ASSEMBLE_QUESTION_GROUP,
surveyId, builder.toString(), transactionId);
}
}
/**
* sends a message to the task queue for survey assembly
*
* @param action
* @param surveyId
* @param questionGroups
*/
private void sendQueueMessage(String action, Long surveyId,
String questionGroups, Long transactionId) {
Queue surveyAssemblyQueue = QueueFactory.getQueue("surveyAssembly");
TaskOptions task = TaskOptions.Builder.withUrl("/app_worker/surveyassembly")
.param("action",
action).param("surveyId", surveyId.toString());
if (questionGroups != null) {
task.param("questionGroupId", questionGroups);
}
if (transactionId != null) {
task.param("transactionId", transactionId.toString());
}
surveyAssemblyQueue.add(task);
}
private void dispatchAssembleQuestionGroup(Long surveyId,
String questionGroupIds, Long transactionId) {
boolean isLast = true;
String currentId = questionGroupIds;
String remainingIds = null;
if (questionGroupIds.contains(",")) {
isLast = false;
currentId = questionGroupIds.substring(0,
questionGroupIds.indexOf(","));
remainingIds = questionGroupIds.substring(questionGroupIds
.indexOf(",") + 1);
}
QuestionDao questionDao = new QuestionDao();
QuestionGroupDao questionGroupDao = new QuestionGroupDao();
QuestionGroup group = questionGroupDao.getByKey(Long
.parseLong(currentId));
TreeMap<Integer, Question> questionList = questionDao
.listQuestionsByQuestionGroup(Long.parseLong(currentId), true);
StringBuilder sb = new StringBuilder("<questionGroup><heading>")
.append(group.getCode()).append("</heading>");
if (questionList != null) {
for (Question q : questionList.values()) {
sb.append(marshallQuestion(q));
}
}
SurveyXMLFragment sxf = new SurveyXMLFragment();
sxf.setSurveyId(surveyId);
sxf.setQuestionGroupId(Long.parseLong(currentId));
sxf.setFragmentOrder(group.getOrder());
sxf.setFragment(new Text(sb.append("</questionGroup>").toString()));
sxf.setTransactionId(transactionId);
sxf.setFragmentType(FRAGMENT_TYPE.QUESTION_GROUP);
SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao();
sxmlfDao.save(sxf);
if (isLast) {
// Assemble the fragments
sendQueueMessage(SurveyAssemblyRequest.ASSEMBLE_QUESTION_GROUP,
surveyId, null, transactionId);
} else {
sendQueueMessage(
SurveyAssemblyRequest.DISPATCH_ASSEMBLE_QUESTION_GROUP,
surveyId, remainingIds, transactionId);
}
}
private String marshallQuestion(Question q) {
SurveyXMLAdapter sax = new SurveyXMLAdapter();
ObjectFactory objFactory = new ObjectFactory();
com.gallatinsystems.survey.domain.xml.Question qXML = objFactory
.createQuestion();
qXML.setId(new String("" + q.getKey().getId() + ""));
// ToDo fix
qXML.setMandatory("false");
if (q.getText() != null) {
com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text();
t.setContent(q.getText());
qXML.setText(t);
}
List<Help> helpList = new ArrayList<Help>();
// this is here for backward compatibility
// however, we don't use the helpMedia at the moment
if (q.getTip() != null) {
Help tip = new Help();
com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text();
t.setContent(q.getTip());
tip.setText(t);
tip.setType("tip");
if (q.getTip() != null && q.getTip().trim().length() > 0
&& !"null".equalsIgnoreCase(q.getTip().trim())) {
TranslationDao tDao = new TranslationDao();
Map<String, Translation> tipTrans = tDao.findTranslations(
Translation.ParentType.QUESTION_TIP, q.getKey().getId());
// any translations for question tooltip?
List<AltText> translationList = new ArrayList<AltText>();
for (Translation trans : tipTrans
.values()) {
AltText aText = new AltText();
aText.setContent(trans.getText());
aText.setLanguage(trans.getLanguageCode());
aText.setType("translation");
translationList.add(aText);
}
if (translationList.size() > 0) {
tip.setAltText(translationList);
}
helpList.add(tip);
}
}
if (q.getQuestionHelpMediaMap() != null) {
for (QuestionHelpMedia helpItem : q.getQuestionHelpMediaMap()
.values()) {
Help tip = new Help();
com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text();
t.setContent(helpItem.getText());
if (helpItem.getType() == QuestionHelpMedia.Type.TEXT) {
tip.setType("tip");
} else {
tip.setType(helpItem.getType().toString().toLowerCase());
tip.setValue(helpItem.getResourceUrl());
}
if (helpItem.getTranslationMap() != null) {
List<AltText> translationList = new ArrayList<AltText>();
for (Translation trans : helpItem.getTranslationMap()
.values()) {
AltText aText = new AltText();
aText.setContent(trans.getText());
aText.setLanguage(trans.getLanguageCode());
aText.setType("translation");
translationList.add(aText);
}
if (translationList.size() > 0) {
tip.setAltText(translationList);
}
}
helpList.add(tip);
}
}
if (helpList.size() > 0) {
qXML.setHelp(helpList);
}
boolean hasValidation = false;
if (q.getIsName() != null && q.getIsName()) {
ValidationRule validationRule = objFactory.createValidationRule();
validationRule.setValidationType("name");
qXML.setValidationRule(validationRule);
hasValidation = true;
} else if (q.getType() == Question.Type.NUMBER
&& (q.getAllowDecimal() != null || q.getAllowSign() != null
|| q.getMinVal() != null || q.getMaxVal() != null)) {
ValidationRule validationRule = objFactory.createValidationRule();
validationRule.setValidationType("numeric");
validationRule.setAllowDecimal(q.getAllowDecimal() != null ? q
.getAllowDecimal().toString().toLowerCase() : "false");
validationRule.setSigned(q.getAllowSign() != null ? q
.getAllowSign().toString().toLowerCase() : "false");
if (q.getMinVal() != null) {
validationRule.setMinVal(q.getMinVal().toString());
}
if (q.getMaxVal() != null) {
validationRule.setMaxVal(q.getMaxVal().toString());
}
qXML.setValidationRule(validationRule);
hasValidation = true;
}
qXML.setAltText(formAltText(q.getTranslationMap()));
if (q.getType().equals(Question.Type.FREE_TEXT)) {
qXML.setType(FREE_QUESTION_TYPE);
// add requireDoubleEntry flag if the field is true in the question
if (q.getRequireDoubleEntry() != null && q.getRequireDoubleEntry()) {
qXML.setRequireDoubleEntry(q.getRequireDoubleEntry().toString());
}
} else if (q.getType().equals(Question.Type.GEO)) {
qXML.setType(GEO_QUESTION_TYPE);
// add locked flag if the geoLocked field is true in the question
if (q.getGeoLocked() != null && q.getGeoLocked()) {
qXML.setLocked(q.getGeoLocked().toString());
}
} else if (q.getType().equals(Question.Type.NUMBER)) {
qXML.setType(FREE_QUESTION_TYPE);
if (!hasValidation) {
ValidationRule vrule = new ValidationRule();
vrule.setValidationType("numeric");
vrule.setSigned("false");
qXML.setValidationRule(vrule);
}
// add requireDoubleEntry flag if the field is true in the question
if (q.getRequireDoubleEntry() != null && q.getRequireDoubleEntry()) {
qXML.setRequireDoubleEntry(q.getRequireDoubleEntry().toString());
}
} else if (q.getType().equals(Question.Type.OPTION)) {
qXML.setType(OPTION_QUESTION_TYPE);
} else if (q.getType().equals(Question.Type.PHOTO)) {
qXML.setType(PHOTO_QUESTION_TYPE);
} else if (q.getType().equals(Question.Type.VIDEO)) {
qXML.setType(VIDEO_QUESTION_TYPE);
} else if (q.getType().equals(Question.Type.SCAN)) {
qXML.setType(SCAN_QUESTION_TYPE);
} else if (q.getType().equals(Question.Type.NAME)) {
qXML.setType(FREE_QUESTION_TYPE);
ValidationRule vrule = new ValidationRule();
vrule.setValidationType("name");
qXML.setValidationRule(vrule);
} else if (q.getType().equals(Question.Type.STRENGTH)) {
qXML.setType(STRENGTH_QUESTION_TYPE);
} else if (q.getType().equals(Question.Type.DATE)) {
qXML.setType(DATE_QUESTION_TYPE);
}
if (q.getOrder() != null) {
qXML.setOrder(q.getOrder().toString());
}
if (q.getMandatoryFlag() != null) {
qXML.setMandatory(q.getMandatoryFlag().toString());
}
qXML.setLocaleNameFlag("false");
if (q.getLocaleNameFlag() != null) {
qXML.setLocaleNameFlag(q.getLocaleNameFlag().toString());
}
if (q.getLocaleLocationFlag() != null) {
if (q.getLocaleLocationFlag()) {
qXML.setLocaleLocationFlag("true");
}
}
Dependency dependency = objFactory.createDependency();
if (q.getDependentQuestionId() != null) {
dependency.setQuestion(q.getDependentQuestionId().toString());
dependency.setAnswerValue(q.getDependentQuestionAnswer());
qXML.setDependency(dependency);
}
if (q.getQuestionOptionMap() != null
&& q.getQuestionOptionMap().size() > 0) {
Options options = objFactory.createOptions();
if (q.getAllowOtherFlag() != null) {
options.setAllowOther(q.getAllowOtherFlag().toString());
}
if (q.getAllowMultipleFlag() != null) {
options.setAllowMultiple(q.getAllowMultipleFlag().toString());
}
if (options.getAllowMultiple() == null
|| "false".equals(options.getAllowMultiple())) {
options.setRenderType(PropertyUtil
.getProperty(OPTION_RENDER_MODE_PROP));
}
ArrayList<Option> optionList = new ArrayList<Option>();
for (QuestionOption qo : q.getQuestionOptionMap().values()) {
Option option = objFactory.createOption();
com.gallatinsystems.survey.domain.xml.Text t = new com.gallatinsystems.survey.domain.xml.Text();
t.setContent(qo.getText());
option.addContent(t);
option.setValue(qo.getCode() != null ? qo.getCode() : qo
.getText());
List<AltText> altTextList = formAltText(qo.getTranslationMap());
if (altTextList != null) {
for (AltText alt : altTextList) {
option.addContent(alt);
}
}
optionList.add(option);
}
options.setOption(optionList);
qXML.setOptions(options);
}
if (q.getScoringRules() != null) {
Scoring scoring = new Scoring();
for (ScoringRule rule : q.getScoringRules()) {
Score score = new Score();
if (scoring.getType() == null) {
scoring.setType(rule.getType().toLowerCase());
}
score.setRangeHigh(rule.getRangeMax());
score.setRangeLow(rule.getRangeMin());
score.setValue(rule.getValue());
scoring.addScore(score);
}
if (scoring.getScore() != null && scoring.getScore().size() > 0) {
qXML.setScoring(scoring);
}
}
if (q.getSourceId() != null) {
qXML.setSourceId(q.getSourceId().toString());
}
String questionDocument = null;
try {
questionDocument = sax.marshal(qXML);
} catch (JAXBException e) {
log.warn("Could not marshal question: " + qXML, e);
}
questionDocument = questionDocument
.replace(
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>",
"");
return questionDocument;
}
private List<AltText> formAltText(Map<String, Translation> translationMap) {
List<AltText> altTextList = new ArrayList<AltText>();
if (translationMap != null) {
for (Translation lang : translationMap.values()) {
AltText alt = new AltText();
alt.setContent(lang.getText());
alt.setType("translation");
alt.setLanguage(lang.getLanguageCode());
altTextList.add(alt);
}
}
return altTextList;
}
private void assembleQuestionGroups(Long surveyId, Long transactionId) {
SurveyXMLFragmentDao sxmlfDao = new SurveyXMLFragmentDao();
List<SurveyXMLFragment> sxmlfList = sxmlfDao.listSurveyFragments(
surveyId, SurveyXMLFragment.FRAGMENT_TYPE.QUESTION_GROUP,
transactionId);
StringBuilder sbQG = new StringBuilder();
for (SurveyXMLFragment item : sxmlfList) {
sbQG.append(item.getFragment().getValue());
}
StringBuilder completeSurvey = new StringBuilder();
String surveyHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><survey>";
String surveyFooter = "</survey>";
completeSurvey.append(surveyHeader);
completeSurvey.append(sbQG.toString());
sbQG = null;
completeSurvey.append(surveyFooter);
SurveyContainerDao scDao = new SurveyContainerDao();
SurveyContainer sc = scDao.findBySurveyId(surveyId);
if (sc == null) {
sc = new SurveyContainer();
}
sc.setSurveyDocument(new Text(completeSurvey.toString()));
sc.setSurveyId(surveyId);
scDao.save(sc);
sendQueueMessage(SurveyAssemblyRequest.DISTRIBUTE_SURVEY, surveyId,
null, transactionId);
}
private String getSourceSurveyId(Long surveyId) {
QuestionDao questionDao = new QuestionDao();
for (Question question : questionDao.listQuestionsBySurvey(surveyId)) {
if (question.getSourceId() != null) {
Question sourceQuestion = questionDao.getByKey(question.getSourceId());
return String.valueOf(sourceQuestion.getSurveyId());
}
}
return null;
}
} |
package org.granitemc.granite.entity;
import org.granitemc.granite.api.entity.Entity;
import org.granitemc.granite.api.entity.item.EntityItem;
import org.granitemc.granite.api.entity.player.Player;
import org.granitemc.granite.api.item.ItemStack;
import org.granitemc.granite.api.utils.Location;
import org.granitemc.granite.api.world.World;
import org.granitemc.granite.entity.player.GranitePlayer;
import org.granitemc.granite.reflect.composite.Composite;
import org.granitemc.granite.utils.MinecraftUtils;
import org.granitemc.granite.world.GraniteWorld;
import java.util.UUID;
public class GraniteEntity extends Composite implements Entity {
public GraniteEntity(Object parent) {
super(parent);
}
public GraniteEntity(Object parent, boolean bool) {
super(parent);
}
public int getEntityId() {
return (Integer) invoke("getEntityID");
}
public void setDead() {
invoke("setDead");
}
public void setSize(float width, float height) {
invoke("setSize", width, height);
}
public void setFire(int seconds) {
invoke("setFire", seconds);
}
public void extinguish() {
invoke("extinguish");
}
public void kill() {
invoke("kill");
}
public void playSound(String soundName, float volume, float pitch) {
invoke("playSound", soundName, volume, pitch);
}
public boolean isImmuneToFire() {
return (boolean) invoke("isImmuneToFire");
}
public boolean isWet() {
return (boolean) invoke("isWet");
}
public boolean isInWater() {
return (boolean) invoke("isInWater");
}
public void resetHeight() {
invoke("resetHeight");
}
// TODO: bof is Material
/*public boolean isInsideOfMaterial(Material var1) {
return (boolean) invoke("isInsideOfMaterial");
}*/
public World getWorld() {
return (World) MinecraftUtils.wrap(invoke("getWorld"));
}
public void setWorld(World world) {
invoke("setWorld", ((GraniteWorld) world).parent);
}
public float getDistanceToEntity(Entity entity) {
return (float) invoke("getDistanceToEntity", entity);
}
public double getDistanceSqToEntity(Entity entity) {
return (double) invoke("getDistanceSqToEntity", entity);
}
public void addVelocity(double x, double y, double z) {
invoke("addVelocity", x, y, z);
}
public boolean canBeCollidedWith() {
return (boolean) invoke("canBeCollidedWith");
}
public boolean canBePushed() {
return (boolean) invoke("canBePushed");
}
public EntityItem entityDropItem(ItemStack itemStack, float yPos) {
return (EntityItem) MinecraftUtils.wrap(invoke("entityDropItem", itemStack, yPos));
}
public boolean isEntityAlive() {
return (boolean) invoke("isEntityAlive");
}
public boolean isEntityInsideOpaqueBlock() {
return (boolean) invoke("isEntityInsideOpaqueBlock");
}
public void mountEntity(Entity entity) {
invoke("mountEntity", entity);
}
public boolean isEating() {
return (boolean) invoke("isEating");
}
public void setEating(boolean eating) {
invoke("setEating", eating);
}
public ItemStack[] getInventory() {
return (ItemStack[]) MinecraftUtils.wrap(invoke("getInventory"));
}
public void setCurrentItemOrArmor(int inventoryIndex, ItemStack itemStack) {
invoke("setCurrentItemOrArmor", inventoryIndex, itemStack);
}
public boolean isBurning() {
return (boolean) invoke("isBurning");
}
public boolean isRiding() {
return (boolean) invoke("isRiding");
}
public boolean isSneaking() {
return (boolean) invoke("isSneaking");
}
public void setSneaking(boolean sneaking) {
invoke("setSneaking", sneaking);
}
public boolean isSprinting() {
return (boolean) invoke("isSprinting");
}
public void setSprinting(boolean sprinting) {
invoke("setSprinting", sprinting);
}
public boolean isInvisible() {
return (boolean) invoke("isInvisible");
}
public void setInvisible(boolean invisible) {
invoke("isInvisible", invisible);
}
public boolean getFlag(int flag) {
return (boolean) invoke("getFlag", flag);
}
public void setFlag(int flag, boolean bool) {
invoke("setFlag", flag, bool);
}
public int getAir() {
return (Integer) invoke("getAir");
}
public void setAir(int amount) {
invoke("setAir", amount);
}
public void setInWeb() {
invoke("setInWeb");
}
public String getCommandSenderName() {
return (String) invoke("getCommandSenderName");
}
public Entity[] getParts() {
Object[] nativeParts = (Object[]) invoke("getParts");
Entity[] parts = new Entity[nativeParts.length];
for (int i = 0; i < nativeParts.length; i++) {
parts[i] = (Entity) MinecraftUtils.wrap(nativeParts[i]);
}
return parts;
}
public boolean isEntityEqual(Entity entity) {
return (boolean) invoke("isEntityEqual", entity);
}
public boolean canAttackWithItem() {
return (boolean) invoke("canAttackWithItem");
}
public int getTeleportDirection() {
return (Integer) invoke("getTeleportDirection");
}
public boolean doesEntityNotTriggerPressurePlate() {
return (boolean) invoke("doesEntityNotTriggerPressurePlate");
}
public UUID getUniqueID() {
return (UUID) invoke("getUniqueID");
}
public boolean isPushedByWater() {
return (boolean) invoke("isPushedByWater");
}
// TODO: wait until IChatComponent has been wrapped
/*public ho getDisplayName() {
return (ho) invoke("getDisplayName");
}*/
public void setCustomNameTag(String name) {
invoke("setCustomNameTag", name);
}
public String getCustomNameTag() {
return (String) invoke("getCustomNameTag");
}
public boolean hasCustomName() {
return (boolean) invoke("hasCustomName");
}
public void setAlwaysRenderNameTag(boolean bool) {
invoke("setAlwaysRenderNameTag", bool);
}
public boolean getAlwaysRenderNameTag() {
return (boolean) invoke("getAlwaysRenderNameTag");
}
public void setPosition(double xPos, double yPos, double zPos) {
invoke("setPosition", xPos, yPos, zPos);
}
public void setPositionAndRotation(double xPos, double yPos, double zPos, float pitch, float yaw) {
invoke("setPositionAndRotation", xPos, yPos, zPos, pitch, yaw);
}
public boolean isOutsideBorder() {
return (boolean) invoke("isOutsideBorder");
}
/**
* Granite Methods
*/
public void teleportToPlayer(Player player) {
GranitePlayer player2 = (GranitePlayer) player;
setLocation(player2.getLocation());
}
public double getDistanceToLocation(Location location) {
if (getLocation().getWorld().equals(location.getWorld())) {
return (double) invoke("getDistanceToLocation", location.getX(), location.getY(), location.getZ());
}
throw new RuntimeException("You cannot get the distance between different worlds");
}
public double getDistanceSqToLocation(Location location) {
if (getLocation().getWorld().equals(location.getWorld())) {
return (double) invoke("getDistanceSqToLocation", location.getX(), location.getY(), location.getZ());
}
throw new RuntimeException("You cannot get the distance between different worlds");
}
public Location getLocation() {
return new Location(getWorld(), getX(), getY(), getZ(), getPitch(), getYaw());
}
public void setLocation(Location location) {
setWorld(location.getWorld());
setX(location.getX());
setY(location.getY());
setZ(location.getZ());
setYaw(location.getYaw());
setPitch(location.getPitch());
}
public double getX() {
return (double) fieldGet("posX");
}
public void setX(double xPos) {
fieldSet("posX", xPos);
}
public double getY() {
return (double) fieldGet("posY");
}
public void setY(double yPos) {
fieldSet("posY", yPos);
}
public double getZ() {
return (double) fieldGet("posZ");
}
public void setZ(double zPos) {
fieldSet("posZ", zPos);
}
public float getPitch() {
return (float) fieldGet("rotationPitch");
}
public void setPitch(float pitch) {
fieldSet("rotationPitch", pitch);
}
public float getYaw() {
return (float) fieldGet("rotationYaw");
}
public void setYaw(float yaw) {
fieldSet("rotationYaw", yaw);
}
public Entity getEntityRidingThis() {
return (Entity) MinecraftUtils.wrap(fieldGet("riddenByEntity"));
}
public Entity getEntityRiddenByThis() {
return (Entity) MinecraftUtils.wrap(fieldGet("ridingEntity"));
}
@Override
public String getType() {
return (String) invoke("getEntityString");
}
} |
package org.unitime.timetable.server.rooms;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import org.hibernate.Transaction;
import org.unitime.localization.impl.Localization;
import org.unitime.timetable.ApplicationProperties;
import org.unitime.timetable.defaults.CommonValues;
import org.unitime.timetable.defaults.UserProperty;
import org.unitime.timetable.gwt.command.client.GwtRpcException;
import org.unitime.timetable.gwt.command.server.GwtRpcImplementation;
import org.unitime.timetable.gwt.command.server.GwtRpcImplements;
import org.unitime.timetable.gwt.resources.GwtConstants;
import org.unitime.timetable.gwt.resources.GwtMessages;
import org.unitime.timetable.gwt.shared.RoomInterface;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomSharingModel;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomSharingOption;
import org.unitime.timetable.gwt.shared.RoomInterface.RoomSharingRequest;
import org.unitime.timetable.model.ChangeLog;
import org.unitime.timetable.model.Department;
import org.unitime.timetable.model.Location;
import org.unitime.timetable.model.RoomDept;
import org.unitime.timetable.model.dao.DepartmentDAO;
import org.unitime.timetable.model.dao.LocationDAO;
import org.unitime.timetable.security.SessionContext;
import org.unitime.timetable.security.qualifiers.SimpleQualifier;
import org.unitime.timetable.security.rights.Right;
import org.unitime.timetable.util.Constants;
import org.unitime.timetable.webutil.RequiredTimeTable;
@GwtRpcImplements(RoomSharingRequest.class)
public class RoomSharingBackend implements GwtRpcImplementation<RoomSharingRequest, RoomSharingModel> {
protected static final GwtConstants CONSTANTS = Localization.create(GwtConstants.class);
protected static final GwtMessages MESSAGES = Localization.create(GwtMessages.class);
@Override
public RoomSharingModel execute(RoomSharingRequest request, SessionContext context) {
switch (request.getOperation()) {
case LOAD:
return (request.isEventAvailability() ? loadEventAvailability(request, context) : loadRoomSharing(request, context));
case SAVE:
return (request.isEventAvailability() ? saveEventAvailability(request, context) : saveRoomSharing(request, context));
default:
return null;
}
}
public RoomSharingModel loadRoomSharing(RoomSharingRequest request, SessionContext context) {
context.checkPermission(request.getLocationId(), "Location", Right.RoomDetailAvailability);
Location location = LocationDAO.getInstance().get(request.getLocationId());
RoomSharingModel model = new RoomSharingModel();
model.setId(location.getUniqueId());
model.setName(location.getLabel());
for (int i = 0; true; i++) {
String mode = ApplicationProperties.getProperty("unitime.room.sharingMode" + (1 + i), i < CONSTANTS.roomSharingModes().length ? CONSTANTS.roomSharingModes()[i] : null);
if (mode == null || mode.isEmpty()) break;
model.addMode(new RoomInterface.RoomSharingDisplayMode(mode));
}
boolean editable = context.hasPermission(location, Right.RoomEditAvailability);
model.setDefaultEditable(editable);
model.addOption(new RoomSharingOption(-1l, "#FFFFFF", MESSAGES.codeFreeForAll(), MESSAGES.legendFreeForAll(), editable));
model.addOption(new RoomSharingOption(-2l, "#696969", MESSAGES.codeNotAvailable(), MESSAGES.legendNotAvailable(), editable));
String defaultGridSize = RequiredTimeTable.getTimeGridSize(context.getUser());
if (defaultGridSize != null)
for (int i = 0; i < model.getModes().size(); i++) {
if (model.getModes().get(i).getName().equals(defaultGridSize)) {
model.setDefaultMode(i); break;
}
}
model.setDefaultHorizontal(CommonValues.HorizontalGrid.eq(context.getUser().getProperty(UserProperty.GridOrientation)));
model.setDefaultOption(model.getOptions().get(0));
model.setNote(location.getShareNote());
model.setNoteEditable(editable);
Set<Department> current = new TreeSet<Department>();
for (RoomDept rd: location.getRoomDepts())
current.add(rd.getDepartment());
for (Department d: current)
model.addOption(new RoomSharingOption(d.getUniqueId(), "#" + d.getRoomSharingColor(current),
d.getDeptCode(), d.getName() + (d.isExternalManager() ? " (EXT: " + d.getExternalMgrLabel() + ")" : ""), editable));
for (Department d: Department.findAllBeingUsed(context.getUser().getCurrentAcademicSessionId()))
model.addOther(new RoomSharingOption(d.getUniqueId(), "#" + d.getRoomSharingColor(current),
d.getDeptCode(), d.getName() + (d.isExternalManager() ? " (EXT: " + d.getExternalMgrLabel() + ")" : ""), editable));
Map<Character, Long> char2dept = new HashMap<Character, Long>(); char pref = '0';
if (location.getManagerIds() != null) {
for (StringTokenizer stk = new StringTokenizer(location.getManagerIds(), ","); stk.hasMoreTokens();) {
Long id = Long.valueOf(stk.nextToken());
char2dept.put(new Character(pref++), id);
}
}
try {
int idx = 0;
for (int d = 0; d < Constants.NR_DAYS; d++)
for (int t = 0; t < Constants.SLOTS_PER_DAY; t++) {
pref = (location.getPattern() != null && idx < location.getPattern().length() ? location.getPattern().charAt(idx) : net.sf.cpsolver.coursett.model.RoomSharingModel.sFreeForAllPrefChar);
idx++;
if (pref == net.sf.cpsolver.coursett.model.RoomSharingModel.sNotAvailablePrefChar) {
model.setOption(d, t, -2l);
} else if (pref == net.sf.cpsolver.coursett.model.RoomSharingModel.sFreeForAllPrefChar) {
model.setOption(d, t, -1l);
} else {
Long deptId = (char2dept == null ? null : char2dept.get(pref));
if (deptId == null) {
try {
deptId = new ArrayList<Department>(current).get(pref - '0').getUniqueId();
} catch (IndexOutOfBoundsException e) {}
}
model.setOption(d, t, deptId);
}
}
} catch (NullPointerException e) {
} catch (IndexOutOfBoundsException e) {
}
if (editable && !context.getUser().getCurrentAuthority().hasRight(Right.DepartmentIndependent)) {
boolean control = false, allDept = true;
for (RoomDept rd: location.getRoomDepts()) {
if (rd.isControl())
control = context.getUser().getCurrentAuthority().hasQualifier(rd.getDepartment());
if (allDept && !context.getUser().getCurrentAuthority().hasQualifier(rd.getDepartment()))
allDept = false;
}
model.setDefaultEditable(control || allDept);
model.setNoteEditable(control || allDept);
if (!control && !allDept) {
for (int d = 0; d < 7; d++)
for (int s = 0; s < 288; s ++) {
RoomSharingOption option = model.getOption(d, s);
model.setEditable(d, s, option != null && context.getUser().getCurrentAuthority().hasQualifier(new SimpleQualifier("Department", option.getId())));
}
}
}
return model;
}
public RoomSharingModel saveRoomSharing(RoomSharingRequest request, SessionContext context) {
context.checkPermission(request.getLocationId(), "Location", Right.RoomEditAvailability);
Map<Long, Character> dept2char = new HashMap<Long, Character>();
dept2char.put(-1l, net.sf.cpsolver.coursett.model.RoomSharingModel.sFreeForAllPrefChar);
dept2char.put(-2l, net.sf.cpsolver.coursett.model.RoomSharingModel.sNotAvailablePrefChar);
String managerIds = ""; char pref = '0';
Set<Long> add = new HashSet<Long>();
for (RoomSharingOption option: request.getModel().getOptions()) {
if (option.getId() >= 0) {
managerIds += (managerIds.isEmpty() ? "" : ",") + option.getId();
dept2char.put(option.getId(), new Character(pref++));
add.add(option.getId());
}
}
String pattern = "";
for (int d = 0; d < 7; d++)
for (int s = 0; s < 288; s ++) {
RoomSharingOption option = request.getModel().getOption(d, s);
pattern += dept2char.get(option.getId());
}
org.hibernate.Session hibSession = LocationDAO.getInstance().getSession();
Transaction tx = hibSession.beginTransaction();
try {
Location location = LocationDAO.getInstance().get(request.getLocationId(), hibSession);
location.setManagerIds(managerIds);
location.setPattern(pattern);
for (Iterator<RoomDept> i = location.getRoomDepts().iterator(); i.hasNext(); ) {
RoomDept rd = (RoomDept)i.next();
if (!add.remove(rd.getDepartment().getUniqueId())) {
rd.getDepartment().getRoomDepts().remove(rd);
i.remove();
hibSession.delete(rd);
}
}
for (Long id: add) {
RoomDept rd = new RoomDept();
rd.setControl(false);
rd.setDepartment(DepartmentDAO.getInstance().get(id, hibSession));
rd.getDepartment().getRoomDepts().add(rd);
rd.setRoom(location);
location.getRoomDepts().add(rd);
hibSession.saveOrUpdate(rd);
}
hibSession.saveOrUpdate(location);
if (request.getModel().isNoteEditable()) {
if (request.getModel().hasNote())
location.setShareNote(request.getModel().getNote().length() > 2048 ? request.getModel().getNote().substring(0, 2048) : request.getModel().getNote());
else
location.setShareNote(null);
}
ChangeLog.addChange(hibSession, context, location, ChangeLog.Source.ROOM_DEPT_EDIT, ChangeLog.Operation.UPDATE, null, location.getControllingDepartment());
tx.commit();
return null;
} catch (Exception ex) {
tx.rollback();
if (ex instanceof GwtRpcException) throw (GwtRpcException)ex;
throw new GwtRpcException(ex.getMessage(), ex);
}
}
public RoomSharingModel loadEventAvailability(RoomSharingRequest request, SessionContext context) {
context.checkPermission(request.getLocationId(), "Location", Right.RoomDetailEventAvailability);
Location location = LocationDAO.getInstance().get(request.getLocationId());
RoomSharingModel model = new RoomSharingModel();
model.setId(location.getUniqueId());
model.setName(location.getLabel());
for (int i = 0; true; i++) {
String mode = ApplicationProperties.getProperty("unitime.room.sharingMode" + (1 + i), i < CONSTANTS.roomSharingModes().length ? CONSTANTS.roomSharingModes()[i] : null);
if (mode == null || mode.isEmpty()) break;
model.addMode(new RoomInterface.RoomSharingDisplayMode(mode));
}
boolean editable = context.hasPermission(location, Right.RoomEditEventAvailability);
model.setDefaultEditable(editable);
model.addOption(new RoomSharingOption(-1l, "#FFFFFF", MESSAGES.codeAvailable(), MESSAGES.legendAvailable(), editable));
model.addOption(new RoomSharingOption(-2l, "#696969", MESSAGES.codeNotAvailable(), MESSAGES.legendNotAvailable(), editable));
String defaultGridSize = RequiredTimeTable.getTimeGridSize(context.getUser());
if (defaultGridSize != null)
for (int i = 0; i < model.getModes().size(); i++) {
if (model.getModes().get(i).getName().equals(defaultGridSize)) {
model.setDefaultMode(i); break;
}
}
model.setDefaultHorizontal(CommonValues.HorizontalGrid.eq(context.getUser().getProperty(UserProperty.GridOrientation)));
model.setDefaultOption(model.getOptions().get(0));
int idx = 0;
for (int d = 0; d < Constants.NR_DAYS; d++)
for (int t = 0; t < Constants.SLOTS_PER_DAY; t++) {
char pref = (location.getEventAvailability() != null && idx < location.getEventAvailability().length() ? location.getEventAvailability().charAt(idx) : '0');
idx++;
model.setOption(d, t, pref == '0' ? -1l : -2l);
}
return model;
}
public RoomSharingModel saveEventAvailability(RoomSharingRequest request, SessionContext context) {
context.checkPermission(request.getLocationId(), "Location", Right.RoomEditEventAvailability);
String availability = "";
for (int d = 0; d < 7; d++)
for (int s = 0; s < 288; s ++) {
RoomSharingOption option = request.getModel().getOption(d, s);
availability += (option.getId() == -1l ? '0' : '1');
}
org.hibernate.Session hibSession = LocationDAO.getInstance().getSession();
Transaction tx = hibSession.beginTransaction();
try {
Location location = LocationDAO.getInstance().get(request.getLocationId(), hibSession);
location.setEventAvailability(availability);
hibSession.save(location);
ChangeLog.addChange(hibSession, context, location, ChangeLog.Source.ROOM_DEPT_EDIT, ChangeLog.Operation.UPDATE, null, location.getControllingDepartment());
tx.commit();
return null;
} catch (Exception ex) {
tx.rollback();
if (ex instanceof GwtRpcException) throw (GwtRpcException)ex;
throw new GwtRpcException(ex.getMessage(), ex);
}
}
} |
package com.kylewbanks.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.kylewbanks.database.orm.PostORM;
import com.kylewbanks.database.orm.TagORM;
public class DatabaseWrapper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseWrapper";
private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "KWB.db";
public DatabaseWrapper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* Called if the database named DATABASE_NAME doesn't exist in order to create it.
*
* @param sqLiteDatabase
*/
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
Log.i(TAG, "Creating database [" + DATABASE_NAME + " v." + DATABASE_VERSION + "]...");
sqLiteDatabase.execSQL(PostORM.SQL_CREATE_TABLE);
sqLiteDatabase.execSQL(TagORM.SQL_CREATE_TABLE);
}
/**
* Called when the DATABASE_VERSION is increased.
*
* @param sqLiteDatabase
* @param oldVersion
* @param newVersion
*/
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
Log.i(TAG, "Upgrading database ["+DATABASE_NAME+" v." + oldVersion+"] to ["+DATABASE_NAME+" v." + newVersion+"]...");
sqLiteDatabase.execSQL(PostORM.SQL_DROP_TABLE);
sqLiteDatabase.execSQL(TagORM.SQL_DROP_TABLE);
onCreate(sqLiteDatabase);
}
} |
package rapture.kernel;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import rapture.common.CallingContext;
import rapture.common.api.EnvironmentApi;
import rapture.common.model.RaptureServerInfo;
import rapture.common.model.RaptureServerInfoStorage;
import rapture.common.model.RaptureServerStatus;
import rapture.common.model.RaptureServerStatusStorage;
import rapture.config.MultiValueConfigLoader;
import rapture.jmx.JmxApp;
import rapture.jmx.JmxAppCache;
public class EnvironmentApiImpl extends KernelBase implements EnvironmentApi {
private static Logger log = Logger.getLogger(EnvironmentApiImpl.class);
public EnvironmentApiImpl(Kernel raptureKernel) {
super(raptureKernel);
Unirest.setTimeouts(2000, 2000);
}
@Override
public RaptureServerInfo getThisServer(CallingContext context) {
String serverId = MultiValueConfigLoader.getConfig("ENVIRONMENT-id");
if (serverId == null) {
log.info("No server id found!");
return null;
} else {
log.info("Loading information for server " + serverId);
return RaptureServerInfoStorage.readByFields(serverId);
}
}
@Override
public List<RaptureServerInfo> getServers(CallingContext context) {
return RaptureServerInfoStorage.readAll();
}
@Override
public RaptureServerInfo setThisServer(CallingContext context, RaptureServerInfo info) {
log.info("Writing server information out id is " + info.getServerId());
MultiValueConfigLoader.writeConfig("ENVIRONMENT-id", info.getServerId());
log.info("Name is " + info.getName() + ", storing");
RaptureServerInfoStorage.add(info, context.getUser(), "Set initial ID");
return info;
}
@Override
public void setApplianceMode(CallingContext context, Boolean mode) {
MultiValueConfigLoader.writeConfig("ENVIRONMENT-appliance", mode.toString());
}
@Override
public Boolean getApplianceMode(CallingContext context) {
return Boolean.valueOf(MultiValueConfigLoader.getConfig("ENVIRONMENT-appliance", "false"));
}
@Override
public List<RaptureServerStatus> getServerStatus(CallingContext context) {
return RaptureServerStatusStorage.readAll();
}
@Override
public Map<String, String> getMemoryInfo(CallingContext context, List<String> appNames) {
return processGetOrPost(appNames, "read/java.lang:type=Memory", null);
}
@Override
public Map<String, String> getOperatingSystemInfo(CallingContext context, List<String> appNames) {
return processGetOrPost(appNames, "read/java.lang:type=OperatingSystem", null);
}
@Override
public Map<String, String> getThreadInfo(CallingContext context, List<String> appNames) {
return processGetOrPost(appNames, "read/java.lang:type=Threading", null);
}
@Override
public Map<String, String> readByPath(CallingContext context, List<String> appNames, String path) {
return processGetOrPost(appNames, "read/" + path, null);
}
@Override
public Map<String, String> writeByPath(CallingContext context, List<String> appNames, String path) {
return processGetOrPost(appNames, "write/" + path, null);
}
@Override
public Map<String, String> execByPath(CallingContext context, List<String> appNames, String path) {
return processGetOrPost(appNames, "exec/" + path, null);
}
@Override
public Map<String, String> readByJson(CallingContext context, List<String> appNames, String json) {
return processJson(appNames, json);
}
@Override
public Map<String, String> writeByJson(CallingContext context, List<String> appNames, String json) {
return processJson(appNames, json);
}
@Override
public Map<String, String> execByJson(CallingContext context, List<String> appNames, String json) {
return processJson(appNames, json);
}
private Map<String, String> processJson(List<String> appNames, String json) {
return processGetOrPost(appNames, null, json);
}
private Map<String, String> processGetOrPost(List<String> appNames, String path, String json) {
Map<String, String> ret = new HashMap<>();
Map<String, JmxApp> apps;
try {
apps = JmxAppCache.getInstance().get();
} catch (ExecutionException e) {
log.error("Failed to update JmxApp cache", e);
return ret;
}
log.debug("Apps are: " + apps.toString());
ExecutorService executor = Executors.newFixedThreadPool(apps.size());
for (Map.Entry<String, JmxApp> entry : apps.entrySet()) {
final String appName = entry.getKey();
executor.execute(new Runnable() {
@Override
public void run() {
log.debug(String.format("Executing for appName [%s]", appName));
if (checkApp(appName, appNames)) {
JmxApp app = entry.getValue();
HttpResponse<JsonNode> res;
try {
if (StringUtils.isNotBlank(json)) {
res = Unirest.post(app.getUrl()).body(json).asJson();
} else {
res = Unirest.get(String.format("%s/%s", app.getUrl(), path)).asJson();
}
ret.put(entry.getKey(), IOUtils.toString(res.getRawBody()));
res.getRawBody().close();
} catch (UnirestException | IOException e) {
log.error(String.format("Error accessing %s/%s", app.getUrl(), path), e);
JmxAppCache.getInstance().invalidate();
}
}
}
});
}
executor.shutdown();
try {
executor.awaitTermination(4, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.error("Could not wait for executor shutdown", e);
}
log.debug("Returned result size is: " + ret.size());
return ret;
}
private boolean checkApp(String app, List<String> appNames) {
return CollectionUtils.isEmpty(appNames) || appNames.contains(app);
}
} |
package com.openxc.sinks;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import android.util.Log;
import com.google.common.base.MoreObjects;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.openxc.NoValueException;
import com.openxc.measurements.BaseMeasurement;
import com.openxc.measurements.Measurement;
import com.openxc.measurements.UnrecognizedMeasurementTypeException;
import com.openxc.messages.KeyMatcher;
import com.openxc.messages.KeyedMessage;
import com.openxc.messages.SimpleVehicleMessage;
import com.openxc.messages.VehicleMessage;
/**
* A data sink that sends new measurements of specific types to listeners.
*
* Applications requesting asynchronous updates for specific signals get their
* values through this sink.
*/
public class MessageListenerSink extends AbstractQueuedCallbackSink {
private final static String TAG = "MessageListenerSink";
// The non-persistent listeners will be removed after they receive their
// first message.
private Map<KeyMatcher, MessageListenerGroup>
mMessageListeners = new HashMap<>();
private Multimap<Class<? extends Measurement>, Measurement.Listener>
mMeasurementTypeListeners = HashMultimap.create();
private Multimap<Class<? extends VehicleMessage>, VehicleMessage.Listener>
mMessageTypeListeners = HashMultimap.create();
private class MessageListenerGroup {
ArrayList<VehicleMessage.Listener> mPersistentListeners = new ArrayList<>();
ArrayList<VehicleMessage.Listener> mListeners = new ArrayList<>();
void add(VehicleMessage.Listener listener, boolean persist) {
if (persist) {
mPersistentListeners.add(listener);
} else {
mListeners.add(listener);
}
}
void removePersistent(VehicleMessage.Listener listener) {
mPersistentListeners.remove(listener);
}
void receive(VehicleMessage message) {
for (VehicleMessage.Listener listener : mPersistentListeners) {
listener.receive(message);
}
for (VehicleMessage.Listener listener : mListeners) {
listener.receive(message);
}
mListeners = new ArrayList<>(); //delete all non-persistent
}
boolean isEmpty() {
return mPersistentListeners.isEmpty() && mListeners.isEmpty();
}
}
public MessageListenerSink() {
super();
}
public synchronized void register(KeyMatcher matcher,
VehicleMessage.Listener listener, boolean persist) {
MessageListenerGroup group = mMessageListeners.get(matcher);
if (group == null) {
group = new MessageListenerGroup();
mMessageListeners.put(matcher, group);
}
group.add(listener, persist);
}
public synchronized void register(KeyMatcher matcher,
VehicleMessage.Listener listener) {
register(matcher, listener, true);
}
public synchronized void register(
Class<? extends VehicleMessage> messageType,
VehicleMessage.Listener listener) {
mMessageTypeListeners.put(messageType, listener);
}
public void register(Class<? extends Measurement> measurementType,
Measurement.Listener listener) {
try {
// A bit of a hack to cache this measurement's ID field so we
// can deserialize incoming measurements of this type. Why don't we
// have a getId() in the Measurement interface? Ah, because it would
// have to be static and you can't have static methods in an
// interface. It would work if we were passed an instance of the
// measurement in this function, but we don't really have that when
// adding a listener.
BaseMeasurement.getKeyForMeasurement(measurementType);
} catch(UnrecognizedMeasurementTypeException e) { }
mMeasurementTypeListeners.put(measurementType, listener);
}
public synchronized void unregister(
Class<? extends Measurement> measurementType,
Measurement.Listener listener) {
mMeasurementTypeListeners.remove(measurementType, listener);
}
public synchronized void unregister(
Class<? extends VehicleMessage> messageType,
VehicleMessage.Listener listener) {
mMessageTypeListeners.remove(messageType, listener);
}
public synchronized void unregister(KeyMatcher matcher,
VehicleMessage.Listener listener) {
MessageListenerGroup group = mMessageListeners.get(matcher);
if (group != null) {
group.removePersistent(listener);
pruneListeners(matcher);
}
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("numMessageListeners", mMessageListeners.size())
.add("numMessageTypeListeners", mMessageTypeListeners.size())
.add("numPersistentMessageListeners", getNumPersistentListeners())
.add("numMeasurementTypeListeners", mMeasurementTypeListeners.size())
.toString();
}
private int getNumPersistentListeners() {
int sum = 0;
for (KeyMatcher matcher : mMessageListeners.keySet()) {
sum += mMessageListeners.get(matcher).mPersistentListeners.size();
}
return sum;
}
private void pruneListeners(KeyMatcher matcher) {
MessageListenerGroup group = mMessageListeners.get(matcher);
if (group != null && group.isEmpty()) {
mMessageListeners.remove(matcher);
}
}
@Override
protected synchronized void propagateMessage(VehicleMessage message) {
if (message instanceof KeyedMessage) {
Set<KeyMatcher> matchedKeys = new HashSet<>();
for (KeyMatcher matcher : mMessageListeners.keySet()) {
if (matcher.matches(message.asKeyedMessage())) {
MessageListenerGroup group = mMessageListeners.get(matcher);
group.receive(message);
matchedKeys.add(matcher);
}
}
for (KeyMatcher matcher : matchedKeys) {
pruneListeners(matcher);
}
if (message instanceof SimpleVehicleMessage) {
propagateMeasurementFromMessage(message.asSimpleMessage());
}
}
if(mMessageTypeListeners.containsKey(message.getClass())) {
for(VehicleMessage.Listener listener :
mMessageTypeListeners.get(message.getClass())) {
listener.receive(message);
}
}
}
private synchronized void propagateMeasurementFromMessage(
SimpleVehicleMessage message) {
try {
Measurement measurement =
BaseMeasurement.getMeasurementFromMessage(message);
if(mMeasurementTypeListeners.containsKey(measurement.getClass())) {
for(Measurement.Listener listener :
mMeasurementTypeListeners.get(measurement.getClass())) {
listener.receive(measurement);
}
}
} catch(UnrecognizedMeasurementTypeException e) {
// The message is not a recognized Measurement, we don't propagate
// it as a Measurement (only as a Message, which is handled
// earlier).
} catch(NoValueException e) {
Log.w(TAG, "Received notification for a blank measurement", e);
}
}
} |
package org.osmdroid.views;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import microsoft.mappoint.TileSystem;
import net.wigle.wigleandroid.ZoomButtonsController;
import net.wigle.wigleandroid.ZoomButtonsController.OnZoomListener;
import org.metalev.multitouch.controller.MultiTouchController;
import org.metalev.multitouch.controller.MultiTouchController.MultiTouchObjectCanvas;
import org.metalev.multitouch.controller.MultiTouchController.PointInfo;
import org.metalev.multitouch.controller.MultiTouchController.PositionAndScale;
import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.api.IMapView;
import org.osmdroid.api.IProjection;
import org.osmdroid.events.MapListener;
import org.osmdroid.events.ScrollEvent;
import org.osmdroid.events.ZoomEvent;
import org.osmdroid.tileprovider.MapTileProviderBase;
import org.osmdroid.tileprovider.MapTileProviderBasic;
import org.osmdroid.tileprovider.tilesource.IStyledTileSource;
import org.osmdroid.tileprovider.tilesource.ITileSource;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.tileprovider.util.SimpleInvalidationHandler;
import org.osmdroid.util.BoundingBoxE6;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.util.constants.GeoConstants;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayManager;
import org.osmdroid.views.overlay.TilesOverlay;
import org.osmdroid.views.util.constants.MapViewConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.widget.Scroller;
public class MapView extends ViewGroup implements IMapView, MapViewConstants,
MultiTouchObjectCanvas<Object> {
// Constants
private static final Logger logger = LoggerFactory.getLogger(MapView.class);
private static final double ZOOM_SENSITIVITY = 1.3;
private static final double ZOOM_LOG_BASE_INV = 1.0 / Math.log(2.0 / ZOOM_SENSITIVITY);
// Fields
/** Current zoom level for map tiles. */
private int mZoomLevel = 0;
private final OverlayManager mOverlayManager;
private Projection mProjection;
private final TilesOverlay mMapOverlay;
private final GestureDetector mGestureDetector;
/** Handles map scrolling */
private final Scroller mScroller;
private final AtomicInteger mTargetZoomLevel = new AtomicInteger();
private final AtomicBoolean mIsAnimating = new AtomicBoolean(false);
private final ScaleAnimation mZoomInAnimation;
private final ScaleAnimation mZoomOutAnimation;
private final MapController mController;
// XXX we can use android.widget.ZoomButtonsController if we upgrade the
// dependency to Android 1.6
private final ZoomButtonsController mZoomController;
private boolean mEnableZoomController = false;
private final ResourceProxy mResourceProxy;
private MultiTouchController<Object> mMultiTouchController;
private float mMultiTouchScale = 1.0f;
protected MapListener mListener;
// for speed (avoiding allocations)
private final Matrix mMatrix = new Matrix();
private final MapTileProviderBase mTileProvider;
private final Handler mTileRequestCompleteHandler;
/* a point that will be reused to design added views */
private final Point mPoint = new Point();
// Constructors
private MapView(final Context context, final int tileSizePixels,
final ResourceProxy resourceProxy, MapTileProviderBase tileProvider,
final Handler tileRequestCompleteHandler, final AttributeSet attrs) {
super(context, attrs);
mResourceProxy = resourceProxy;
this.mController = new MapController(this);
this.mScroller = new Scroller(context);
TileSystem.setTileSize(tileSizePixels);
if (tileProvider == null) {
final ITileSource tileSource = getTileSourceFromAttributes(attrs);
tileProvider = new MapTileProviderBasic(context, tileSource);
}
mTileRequestCompleteHandler = tileRequestCompleteHandler == null ? new SimpleInvalidationHandler(
this) : tileRequestCompleteHandler;
mTileProvider = tileProvider;
mTileProvider.setTileRequestCompleteHandler(mTileRequestCompleteHandler);
this.mMapOverlay = new TilesOverlay(mTileProvider, mResourceProxy);
mOverlayManager = new OverlayManager(mMapOverlay);
this.mZoomController = new ZoomButtonsController(this);
this.mZoomController.setOnZoomListener(new MapViewZoomListener());
mZoomInAnimation = new ScaleAnimation(1, 2, 1, 2, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
mZoomOutAnimation = new ScaleAnimation(1, 0.5f, 1, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
mZoomInAnimation.setDuration(ANIMATION_DURATION_SHORT);
mZoomOutAnimation.setDuration(ANIMATION_DURATION_SHORT);
mGestureDetector = new GestureDetector(context, new MapViewGestureDetectorListener());
mGestureDetector.setOnDoubleTapListener(new MapViewDoubleClickListener());
}
/**
* Constructor used by XML layout resource (uses default tile source).
*/
public MapView(final Context context, final AttributeSet attrs) {
this(context, 256, new DefaultResourceProxyImpl(context), null, null, attrs);
}
/**
* Standard Constructor.
*/
public MapView(final Context context, final int tileSizePixels) {
this(context, tileSizePixels, new DefaultResourceProxyImpl(context));
}
public MapView(final Context context, final int tileSizePixels,
final ResourceProxy resourceProxy) {
this(context, tileSizePixels, resourceProxy, null);
}
public MapView(final Context context, final int tileSizePixels,
final ResourceProxy resourceProxy, final MapTileProviderBase aTileProvider) {
this(context, tileSizePixels, resourceProxy, aTileProvider, null);
}
public MapView(final Context context, final int tileSizePixels,
final ResourceProxy resourceProxy, final MapTileProviderBase aTileProvider,
final Handler tileRequestCompleteHandler) {
this(context, tileSizePixels, resourceProxy, aTileProvider, tileRequestCompleteHandler,
null);
}
// Getter & Setter
@Override
public MapController getController() {
return this.mController;
}
/**
* You can add/remove/reorder your Overlays using the List of {@link Overlay}. The first (index
* 0) Overlay gets drawn first, the one with the highest as the last one.
*/
public List<Overlay> getOverlays() {
return this.getOverlayManager();
}
public OverlayManager getOverlayManager() {
return mOverlayManager;
}
public MapTileProviderBase getTileProvider() {
return mTileProvider;
}
public Scroller getScroller() {
return mScroller;
}
public Handler getTileRequestCompleteHandler() {
return mTileRequestCompleteHandler;
}
@Override
public int getLatitudeSpan() {
return this.getBoundingBox().getLatitudeSpanE6();
}
@Override
public int getLongitudeSpan() {
return this.getBoundingBox().getLongitudeSpanE6();
}
public BoundingBoxE6 getBoundingBox() {
return getBoundingBox(getWidth(), getHeight());
}
public BoundingBoxE6 getBoundingBox(final int pViewWidth, final int pViewHeight) {
final int world_2 = TileSystem.MapSize(mZoomLevel) / 2;
final Rect screenRect = getScreenRect(null);
screenRect.offset(world_2, world_2);
final IGeoPoint neGeoPoint = TileSystem.PixelXYToLatLong(screenRect.right, screenRect.top,
mZoomLevel, null);
final IGeoPoint swGeoPoint = TileSystem.PixelXYToLatLong(screenRect.left,
screenRect.bottom, mZoomLevel, null);
return new BoundingBoxE6(neGeoPoint.getLatitudeE6(), neGeoPoint.getLongitudeE6(),
swGeoPoint.getLatitudeE6(), swGeoPoint.getLongitudeE6());
}
/**
* Gets the current bounds of the screen in <I>screen coordinates</I>.
*/
public Rect getScreenRect(final Rect reuse) {
final Rect out = reuse == null ? new Rect() : reuse;
out.set(getScrollX() - getWidth() / 2, getScrollY() - getHeight() / 2, getScrollX()
+ getWidth() / 2, getScrollY() + getHeight() / 2);
return out;
}
/**
* Get a projection for converting between screen-pixel coordinates and latitude/longitude
* coordinates. You should not hold on to this object for more than one draw, since the
* projection of the map could change.
*
* @return The Projection of the map in its current state. You should not hold on to this object
* for more than one draw, since the projection of the map could change.
*/
@Override
public Projection getProjection() {
if (mProjection == null) {
mProjection = new Projection();
}
return mProjection;
}
void setMapCenter(final IGeoPoint aCenter) {
this.setMapCenter(aCenter.getLatitudeE6(), aCenter.getLongitudeE6());
}
void setMapCenter(final int aLatitudeE6, final int aLongitudeE6) {
final Point coords = TileSystem.LatLongToPixelXY(aLatitudeE6 / 1E6, aLongitudeE6 / 1E6,
getZoomLevel(), null);
final int worldSize_2 = TileSystem.MapSize(mZoomLevel) / 2;
if (getAnimation() == null || getAnimation().hasEnded()) {
logger.debug("StartScroll");
mScroller.startScroll(getScrollX(), getScrollY(),
coords.x - worldSize_2 - getScrollX(), coords.y - worldSize_2 - getScrollY(),
500);
postInvalidate();
}
}
public void setTileSource(final ITileSource aTileSource) {
mTileProvider.setTileSource(aTileSource);
TileSystem.setTileSize(aTileSource.getTileSizePixels());
this.checkZoomButtons();
this.setZoomLevel(mZoomLevel); // revalidate zoom level
postInvalidate();
}
/**
* @param aZoomLevel
* the zoom level bound by the tile source
*/
int setZoomLevel(final int aZoomLevel) {
final int minZoomLevel = getMinZoomLevel();
final int maxZoomLevel = getMaxZoomLevel();
final int newZoomLevel = Math.max(minZoomLevel, Math.min(maxZoomLevel, aZoomLevel));
final int curZoomLevel = this.mZoomLevel;
this.mZoomLevel = newZoomLevel;
this.checkZoomButtons();
if (newZoomLevel > curZoomLevel) {
// We are going from a lower-resolution plane to a higher-resolution plane, so we have
// to do it the hard way.
final int worldSize_current_2 = TileSystem.MapSize(curZoomLevel) / 2;
final int worldSize_new_2 = TileSystem.MapSize(newZoomLevel) / 2;
final IGeoPoint centerGeoPoint = TileSystem.PixelXYToLatLong(getScrollX()
+ worldSize_current_2, getScrollY() + worldSize_current_2, curZoomLevel, null);
final Point centerPoint = TileSystem.LatLongToPixelXY(
centerGeoPoint.getLatitudeE6() / 1E6, centerGeoPoint.getLongitudeE6() / 1E6,
newZoomLevel, null);
scrollTo(centerPoint.x - worldSize_new_2, centerPoint.y - worldSize_new_2);
} else if (newZoomLevel < curZoomLevel) {
// We are going from a higher-resolution plane to a lower-resolution plane, so we can do
// it the easy way.
scrollTo(getScrollX() >> curZoomLevel - newZoomLevel, getScrollY() >> curZoomLevel
- newZoomLevel);
}
// snap for all snappables
final Point snapPoint = new Point();
// XXX why do we need a new projection here?
mProjection = new Projection();
if (this.getOverlayManager().onSnapToItem(getScrollX(), getScrollY(), snapPoint, this)) {
scrollTo(snapPoint.x, snapPoint.y);
}
// do callback on listener
if (newZoomLevel != curZoomLevel && mListener != null) {
final ZoomEvent event = new ZoomEvent(this, newZoomLevel);
mListener.onZoom(event);
}
return this.mZoomLevel;
}
/**
* Get the current ZoomLevel for the map tiles.
*
* @return the current ZoomLevel between 0 (equator) and 18/19(closest), depending on the tile
* source chosen.
*/
@Override
public int getZoomLevel() {
return getZoomLevel(true);
}
/**
* Get the current ZoomLevel for the map tiles.
*
* @param aPending
* if true and we're animating then return the zoom level that we're animating
* towards, otherwise return the current zoom level
* @return the zoom level
*/
public int getZoomLevel(final boolean aPending) {
if (aPending && isAnimating()) {
return mTargetZoomLevel.get();
} else {
return mZoomLevel;
}
}
/**
* Returns the minimum zoom level for the point currently at the center.
*
* @return The minimum zoom level for the map's current center.
*/
public int getMinZoomLevel() {
return mMapOverlay.getMinimumZoomLevel();
}
/**
* Returns the maximum zoom level for the point currently at the center.
*
* @return The maximum zoom level for the map's current center.
*/
@Override
public int getMaxZoomLevel() {
return mMapOverlay.getMaximumZoomLevel();
}
public boolean canZoomIn() {
final int maxZoomLevel = getMaxZoomLevel();
if (mZoomLevel >= maxZoomLevel) {
return false;
}
if (mIsAnimating.get() & mTargetZoomLevel.get() >= maxZoomLevel) {
return false;
}
return true;
}
public boolean canZoomOut() {
final int minZoomLevel = getMinZoomLevel();
if (mZoomLevel <= minZoomLevel) {
return false;
}
if (mIsAnimating.get() && mTargetZoomLevel.get() <= minZoomLevel) {
return false;
}
return true;
}
/**
* Zoom in by one zoom level.
*/
boolean zoomIn() {
if (canZoomIn()) {
if (mIsAnimating.get()) {
// TODO extend zoom (and return true)
return false;
} else {
mTargetZoomLevel.set(mZoomLevel + 1);
mIsAnimating.set(true);
startAnimation(mZoomInAnimation);
return true;
}
} else {
return false;
}
}
boolean zoomInFixing(final IGeoPoint point) {
setMapCenter(point); // TODO should fix on point, not center on it
return zoomIn();
}
boolean zoomInFixing(final int xPixel, final int yPixel) {
setMapCenter(xPixel, yPixel); // TODO should fix on point, not center on it
return zoomIn();
}
/**
* Zoom out by one zoom level.
*/
boolean zoomOut() {
if (canZoomOut()) {
if (mIsAnimating.get()) {
// TODO extend zoom (and return true)
return false;
} else {
mTargetZoomLevel.set(mZoomLevel - 1);
mIsAnimating.set(true);
startAnimation(mZoomOutAnimation);
return true;
}
} else {
return false;
}
}
boolean zoomOutFixing(final IGeoPoint point) {
setMapCenter(point); // TODO should fix on point, not center on it
return zoomOut();
}
boolean zoomOutFixing(final int xPixel, final int yPixel) {
setMapCenter(xPixel, yPixel); // TODO should fix on point, not center on it
return zoomOut();
}
/**
* Returns the current center-point position of the map, as a GeoPoint (latitude and longitude).
*
* @return A GeoPoint of the map's center-point.
*/
@Override
public IGeoPoint getMapCenter() {
final int world_2 = TileSystem.MapSize(mZoomLevel) / 2;
final Rect screenRect = getScreenRect(null);
screenRect.offset(world_2, world_2);
return TileSystem.PixelXYToLatLong(screenRect.centerX(), screenRect.centerY(), mZoomLevel,
null);
}
public ResourceProxy getResourceProxy() {
return mResourceProxy;
}
/**
* Whether to use the network connection if it's available.
*/
public boolean useDataConnection() {
return mMapOverlay.useDataConnection();
}
/**
* Set whether to use the network connection if it's available.
*
* @param aMode
* if true use the network connection if it's available. if false don't use the
* network connection even if it's available.
*/
public void setUseDataConnection(final boolean aMode) {
mMapOverlay.setUseDataConnection(aMode);
}
// Methods from SuperClass/Interfaces
/**
* Returns a set of layout parameters with a width of
* {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT}, a height of
* {@link android.view.ViewGroup.LayoutParams#WRAP_CONTENT} at the {@link GeoPoint} (0, 0) align
* with {@link MapView.LayoutParams#BOTTOM_CENTER}.
*/
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new MapView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, null, MapView.LayoutParams.BOTTOM_CENTER, 0, 0);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(final AttributeSet attrs) {
return new MapView.LayoutParams(getContext(), attrs);
}
// Override to allow type-checking of LayoutParams.
@Override
protected boolean checkLayoutParams(final ViewGroup.LayoutParams p) {
return p instanceof MapView.LayoutParams;
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(final ViewGroup.LayoutParams p) {
return new MapView.LayoutParams(p);
}
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
final int count = getChildCount();
int maxHeight = 0;
int maxWidth = 0;
// Find out how big everyone wants to be
measureChildren(widthMeasureSpec, heightMeasureSpec);
// Find rightmost and bottom-most child
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final MapView.LayoutParams lp = (MapView.LayoutParams) child.getLayoutParams();
final int childHeight = child.getMeasuredHeight();
final int childWidth = child.getMeasuredWidth();
getProjection().toMapPixels(lp.geoPoint, mPoint);
final int x = mPoint.x + getWidth() / 2;
final int y = mPoint.y + getHeight() / 2;
int childRight = x;
int childBottom = y;
switch (lp.alignment) {
case MapView.LayoutParams.TOP_LEFT:
childRight = x + childWidth;
childBottom = y;
break;
case MapView.LayoutParams.TOP_CENTER:
childRight = x + childWidth / 2;
childBottom = y;
break;
case MapView.LayoutParams.TOP_RIGHT:
childRight = x;
childBottom = y;
break;
case MapView.LayoutParams.CENTER_LEFT:
childRight = x + childWidth;
childBottom = y + childHeight / 2;
break;
case MapView.LayoutParams.CENTER:
childRight = x + childWidth / 2;
childBottom = y + childHeight / 2;
break;
case MapView.LayoutParams.CENTER_RIGHT:
childRight = x;
childBottom = y + childHeight / 2;
break;
case MapView.LayoutParams.BOTTOM_LEFT:
childRight = x + childWidth;
childBottom = y + childHeight;
break;
case MapView.LayoutParams.BOTTOM_CENTER:
childRight = x + childWidth / 2;
childBottom = y + childHeight;
break;
case MapView.LayoutParams.BOTTOM_RIGHT:
childRight = x;
childBottom = y + childHeight;
break;
}
childRight += lp.offsetX;
childBottom += lp.offsetY;
maxWidth = Math.max(maxWidth, childRight);
maxHeight = Math.max(maxHeight, childBottom);
}
}
// Account for padding too
maxWidth += getPaddingLeft() + getPaddingRight();
maxHeight += getPaddingTop() + getPaddingBottom();
// Check against minimum height and width
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
resolveSize(maxHeight, heightMeasureSpec));
}
@Override
protected void onLayout(final boolean changed, final int l, final int t, final int r,
final int b) {
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final MapView.LayoutParams lp = (MapView.LayoutParams) child.getLayoutParams();
final int childHeight = child.getMeasuredHeight();
final int childWidth = child.getMeasuredWidth();
getProjection().toMapPixels(lp.geoPoint, mPoint);
final int x = mPoint.x + getWidth() / 2;
final int y = mPoint.y + getHeight() / 2;
int childLeft = x;
int childTop = y;
switch (lp.alignment) {
case MapView.LayoutParams.TOP_LEFT:
childLeft = getPaddingLeft() + x;
childTop = getPaddingTop() + y;
break;
case MapView.LayoutParams.TOP_CENTER:
childLeft = getPaddingLeft() + x - childWidth / 2;
childTop = getPaddingTop() + y;
break;
case MapView.LayoutParams.TOP_RIGHT:
childLeft = getPaddingLeft() + x - childWidth;
childTop = getPaddingTop() + y;
break;
case MapView.LayoutParams.CENTER_LEFT:
childLeft = getPaddingLeft() + x;
childTop = getPaddingTop() + y - childHeight / 2;
break;
case MapView.LayoutParams.CENTER:
childLeft = getPaddingLeft() + x - childWidth / 2;
childTop = getPaddingTop() + y - childHeight / 2;
break;
case MapView.LayoutParams.CENTER_RIGHT:
childLeft = getPaddingLeft() + x - childWidth;
childTop = getPaddingTop() + y - childHeight / 2;
break;
case MapView.LayoutParams.BOTTOM_LEFT:
childLeft = getPaddingLeft() + x;
childTop = getPaddingTop() + y - childHeight;
break;
case MapView.LayoutParams.BOTTOM_CENTER:
childLeft = getPaddingLeft() + x - childWidth / 2;
childTop = getPaddingTop() + y - childHeight;
break;
case MapView.LayoutParams.BOTTOM_RIGHT:
childLeft = getPaddingLeft() + x - childWidth;
childTop = getPaddingTop() + y - childHeight;
break;
}
childLeft += lp.offsetX;
childTop += lp.offsetY;
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight);
}
}
}
public void onDetach() {
this.getOverlayManager().onDetach(this);
}
@Override
public boolean onKeyDown(final int keyCode, final KeyEvent event) {
final boolean result = this.getOverlayManager().onKeyDown(keyCode, event, this);
return result || super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(final int keyCode, final KeyEvent event) {
final boolean result = this.getOverlayManager().onKeyUp(keyCode, event, this);
return result || super.onKeyUp(keyCode, event);
}
@Override
public boolean onTrackballEvent(final MotionEvent event) {
if (this.getOverlayManager().onTrackballEvent(event, this)) {
return true;
}
scrollBy((int) (event.getX() * 25), (int) (event.getY() * 25));
return super.onTrackballEvent(event);
}
@Override
public boolean dispatchTouchEvent(final MotionEvent event) {
if (DEBUGMODE) {
logger.debug("dispatchTouchEvent(" + event + ")");
}
if (mZoomController.isVisible() && mZoomController.onTouch(this, event)) {
return true;
}
if (this.getOverlayManager().onTouchEvent(event, this)) {
return true;
}
if (mMultiTouchController != null && mMultiTouchController.onTouchEvent(event)) {
if (DEBUGMODE) {
logger.debug("mMultiTouchController handled onTouchEvent");
}
return true;
}
final boolean r = super.dispatchTouchEvent(event);
if (mGestureDetector.onTouchEvent(event)) {
if (DEBUGMODE) {
logger.debug("mGestureDetector handled onTouchEvent");
}
return true;
}
if (r) {
if (DEBUGMODE) {
logger.debug("super handled onTouchEvent");
}
} else {
if (DEBUGMODE) {
logger.debug("no-one handled onTouchEvent");
}
}
return r;
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {
if (mScroller.isFinished()) {
// This will facilitate snapping-to any Snappable points.
setZoomLevel(mZoomLevel);
} else {
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
}
postInvalidate(); // Keep on drawing until the animation has
// finished.
}
}
@Override
public void scrollTo(int x, int y) {
final int worldSize_2 = TileSystem.MapSize(mZoomLevel) / 2;
while (x < -worldSize_2) {
x += (worldSize_2 * 2);
}
while (x > worldSize_2) {
x -= (worldSize_2 * 2);
}
while (y < -worldSize_2) {
y += (worldSize_2 * 2);
}
while (y > worldSize_2) {
y -= (worldSize_2 * 2);
}
super.scrollTo(x, y);
// do callback on listener
if (mListener != null) {
final ScrollEvent event = new ScrollEvent(this, x, y);
mListener.onScroll(event);
}
}
@Override
public void setBackgroundColor(final int pColor) {
mMapOverlay.setLoadingBackgroundColor(pColor);
invalidate();
}
@Override
protected void dispatchDraw(final Canvas c) {
final long startMs = System.currentTimeMillis();
mProjection = new Projection();
// Save the current canvas matrix
c.save();
if (mMultiTouchScale == 1.0f) {
c.translate(getWidth() / 2, getHeight() / 2);
} else {
c.getMatrix(mMatrix);
mMatrix.postTranslate(getWidth() / 2, getHeight() / 2);
mMatrix.preScale(mMultiTouchScale, mMultiTouchScale, getScrollX(), getScrollY());
c.setMatrix(mMatrix);
}
/* Draw background */
// c.drawColor(mBackgroundColor);
/* Draw all Overlays. */
this.getOverlayManager().onDraw(c, this);
// Restore the canvas matrix
c.restore();
super.dispatchDraw(c);
final long endMs = System.currentTimeMillis();
if (DEBUGMODE) {
logger.debug("Rendering overall: " + (endMs - startMs) + "ms");
}
}
@Override
protected void onDetachedFromWindow() {
this.mZoomController.setVisible(false);
this.onDetach();
super.onDetachedFromWindow();
}
// Animation
@Override
protected void onAnimationStart() {
mIsAnimating.set(true);
super.onAnimationStart();
}
@Override
protected void onAnimationEnd() {
mIsAnimating.set(false);
clearAnimation();
setZoomLevel(mTargetZoomLevel.get());
super.onAnimationEnd();
}
/**
* Check mAnimationListener.isAnimating() to determine if view is animating. Useful for overlays
* to avoid recalculating during an animation sequence.
*
* @return boolean indicating whether view is animating.
*/
public boolean isAnimating() {
return mIsAnimating.get();
}
// Implementation of MultiTouchObjectCanvas
@Override
public Object getDraggableObjectAtPoint(final PointInfo pt) {
return this;
}
@Override
public void getPositionAndScale(final Object obj, final PositionAndScale objPosAndScaleOut) {
objPosAndScaleOut.set(0, 0, true, mMultiTouchScale, false, 0, 0, false, 0);
}
@Override
public void selectObject(final Object obj, final PointInfo pt) {
// if obj is null it means we released the pointers
// if scale is not 1 it means we pinched
if (obj == null && mMultiTouchScale != 1.0f) {
final float scaleDiffFloat = (float) (Math.log(mMultiTouchScale) * ZOOM_LOG_BASE_INV);
final int scaleDiffInt = Math.round(scaleDiffFloat);
setZoomLevel(mZoomLevel + scaleDiffInt);
// XXX maybe zoom in/out instead of zooming direct to zoom level
// - probably not a good idea because you'll repeat the animation
}
// reset scale
mMultiTouchScale = 1.0f;
}
@Override
public boolean setPositionAndScale(final Object obj, final PositionAndScale aNewObjPosAndScale,
final PointInfo aTouchPoint) {
float multiTouchScale = aNewObjPosAndScale.getScale();
// If we are at the first or last zoom level, prevent pinching/expanding
if ((multiTouchScale > 1) && !canZoomIn()) {
multiTouchScale = 1;
}
if ((multiTouchScale < 1) && !canZoomOut()) {
multiTouchScale = 1;
}
mMultiTouchScale = multiTouchScale;
invalidate(); // redraw
return true;
}
/*
* Set the MapListener for this view
*/
public void setMapListener(final MapListener ml) {
mListener = ml;
}
// Methods
private void checkZoomButtons() {
this.mZoomController.setZoomInEnabled(canZoomIn());
this.mZoomController.setZoomOutEnabled(canZoomOut());
}
public void setBuiltInZoomControls(final boolean on) {
this.mEnableZoomController = on;
this.checkZoomButtons();
}
public void setMultiTouchControls(final boolean on) {
mMultiTouchController = on ? new MultiTouchController<Object>(this, false) : null;
}
private ITileSource getTileSourceFromAttributes(final AttributeSet aAttributeSet) {
ITileSource tileSource = TileSourceFactory.DEFAULT_TILE_SOURCE;
if (aAttributeSet != null) {
final String tileSourceAttr = aAttributeSet.getAttributeValue(null, "tilesource");
if (tileSourceAttr != null) {
try {
final ITileSource r = TileSourceFactory.getTileSource(tileSourceAttr);
logger.info("Using tile source specified in layout attributes: " + r);
tileSource = r;
} catch (final IllegalArgumentException e) {
logger.warn("Invalid tile souce specified in layout attributes: " + tileSource);
}
}
}
if (aAttributeSet != null && tileSource instanceof IStyledTileSource) {
String style = aAttributeSet.getAttributeValue(null, "style");
if (style == null) {
// historic - old attribute name
style = aAttributeSet.getAttributeValue(null, "cloudmadeStyle");
}
if (style == null) {
logger.info("Using default style: 1");
} else {
logger.info("Using style specified in layout attributes: " + style);
((IStyledTileSource<?>) tileSource).setStyle(style);
}
}
logger.info("Using tile source: " + tileSource);
return tileSource;
}
// Inner and Anonymous Classes
/**
* A Projection serves to translate between the coordinate system of x/y on-screen pixel
* coordinates and that of latitude/longitude points on the surface of the earth. You obtain a
* Projection from MapView.getProjection(). You should not hold on to this object for more than
* one draw, since the projection of the map could change. <br />
* <br />
* <I>Screen coordinates</I> are in the coordinate system of the screen's Canvas. The origin is
* in the center of the plane. <I>Screen coordinates</I> are appropriate for using to draw to
* the screen.<br />
* <br />
* <I>Map coordinates</I> are in the coordinate system of the standard Mercator projection. The
* origin is in the upper-left corner of the plane. <I>Map coordinates</I> are appropriate for
* use in the TileSystem class.<br />
* <br />
* <I>Intermediate coordinates</I> are used to cache the computationally heavy part of the
* projection. They aren't suitable for use until translated into <I>screen coordinates</I> or
* <I>map coordinates</I>.
*
* @author Nicolas Gramlich
* @author Manuel Stahl
*/
public class Projection implements IProjection, GeoConstants {
private final int viewWidth_2 = getWidth() / 2;
private final int viewHeight_2 = getHeight() / 2;
private final int worldSize_2 = TileSystem.MapSize(mZoomLevel) / 2;
private final int offsetX = -worldSize_2;
private final int offsetY = -worldSize_2;
private final BoundingBoxE6 mBoundingBoxProjection;
private final int mZoomLevelProjection;
private final Rect mScreenRectProjection;
private Projection() {
/*
* Do some calculations and drag attributes to local variables to save some performance.
*/
mZoomLevelProjection = MapView.this.mZoomLevel;
mBoundingBoxProjection = MapView.this.getBoundingBox();
mScreenRectProjection = MapView.this.getScreenRect(null);
}
public int getZoomLevel() {
return mZoomLevelProjection;
}
public BoundingBoxE6 getBoundingBox() {
return mBoundingBoxProjection;
}
public Rect getScreenRect() {
return mScreenRectProjection;
}
/**
* @deprecated Use TileSystem.getTileSize() instead.
*/
@Deprecated
public int getTileSizePixels() {
return TileSystem.getTileSize();
}
/**
* @deprecated Use
* <code>Point out = TileSystem.PixelXYToTileXY(screenRect.centerX(), screenRect.centerY(), null);</code>
* instead.
*/
@Deprecated
public Point getCenterMapTileCoords() {
final Rect rect = getScreenRect();
return TileSystem.PixelXYToTileXY(rect.centerX(), rect.centerY(), null);
}
/**
* @deprecated Use
* <code>final Point out = TileSystem.TileXYToPixelXY(centerMapTileCoords.x, centerMapTileCoords.y, null);</code>
* instead.
*/
@Deprecated
public Point getUpperLeftCornerOfCenterMapTile() {
final Point centerMapTileCoords = getCenterMapTileCoords();
return TileSystem.TileXYToPixelXY(centerMapTileCoords.x, centerMapTileCoords.y, null);
}
/**
* Converts <I>screen coordinates</I> to the underlying GeoPoint.
*
* @param x
* @param y
* @return GeoPoint under x/y.
*/
public IGeoPoint fromPixels(final float x, final float y) {
final Rect screenRect = getScreenRect();
return TileSystem.PixelXYToLatLong(screenRect.left + (int) x + worldSize_2,
screenRect.top + (int) y + worldSize_2, mZoomLevelProjection, null);
}
public Point fromMapPixels(final int x, final int y, final Point reuse) {
final Point out = reuse != null ? reuse : new Point();
out.set(x - viewWidth_2, y - viewHeight_2);
out.offset(getScrollX(), getScrollY());
return out;
}
/**
* Converts a GeoPoint to its <I>screen coordinates</I>.
*
* @param in
* the GeoPoint you want the <I>screen coordinates</I> of
* @param reuse
* just pass null if you do not have a Point to be 'recycled'.
* @return the Point containing the <I>screen coordinates</I> of the GeoPoint passed.
*/
public Point toMapPixels(final IGeoPoint in, final Point reuse) {
final Point out = reuse != null ? reuse : new Point();
final Point coords = TileSystem.LatLongToPixelXY(in.getLatitudeE6() / 1E6,
in.getLongitudeE6() / 1E6, getZoomLevel(), null);
out.set(coords.x, coords.y);
out.offset(offsetX, offsetY);
return out;
}
/**
* Performs only the first computationally heavy part of the projection. Call
* toMapPixelsTranslated to get the final position.
*
* @param latituteE6
* the latitute of the point
* @param longitudeE6
* the longitude of the point
* @param reuse
* just pass null if you do not have a Point to be 'recycled'.
* @return intermediate value to be stored and passed to toMapPixelsTranslated.
*/
public Point toMapPixelsProjected(final int latituteE6, final int longitudeE6,
final Point reuse) {
final Point out = reuse != null ? reuse : new Point();
TileSystem
.LatLongToPixelXY(latituteE6 / 1E6, longitudeE6 / 1E6, MAXIMUM_ZOOMLEVEL, out);
return out;
}
/**
* Performs the second computationally light part of the projection. Returns results in
* <I>screen coordinates</I>.
*
* @param in
* the Point calculated by the toMapPixelsProjected
* @param reuse
* just pass null if you do not have a Point to be 'recycled'.
* @return the Point containing the <I>Screen coordinates</I> of the initial GeoPoint passed
* to the toMapPixelsProjected.
*/
public Point toMapPixelsTranslated(final Point in, final Point reuse) {
final Point out = reuse != null ? reuse : new Point();
final int zoomDifference = MAXIMUM_ZOOMLEVEL - getZoomLevel();
out.set((in.x >> zoomDifference) + offsetX, (in.y >> zoomDifference) + offsetY);
return out;
}
/**
* Translates a rectangle from <I>screen coordinates</I> to <I>intermediate coordinates</I>.
*
* @param in
* the rectangle in <I>screen coordinates</I>
* @return a rectangle in </I>intermediate coordindates</I>.
*/
public Rect fromPixelsToProjected(final Rect in) {
final Rect result = new Rect();
final int zoomDifference = MAXIMUM_ZOOMLEVEL - getZoomLevel();
final int x0 = in.left - offsetX << zoomDifference;
final int x1 = in.right - offsetX << zoomDifference;
final int y0 = in.bottom - offsetY << zoomDifference;
final int y1 = in.top - offsetY << zoomDifference;
result.set(Math.min(x0, x1), Math.min(y0, y1), Math.max(x0, x1), Math.max(y0, y1));
return result;
}
/**
* @deprecated Use TileSystem.TileXYToPixelXY
*/
@Deprecated
public Point toPixels(final Point tileCoords, final Point reuse) {
return toPixels(tileCoords.x, tileCoords.y, reuse);
}
/**
* @deprecated Use TileSystem.TileXYToPixelXY
*/
@Deprecated
public Point toPixels(final int tileX, final int tileY, final Point reuse) {
return TileSystem.TileXYToPixelXY(tileX, tileY, reuse);
}
// not presently used
public Rect toPixels(final BoundingBoxE6 pBoundingBoxE6) {
final Rect rect = new Rect();
final Point reuse = new Point();
toMapPixels(
new GeoPoint(pBoundingBoxE6.getLatNorthE6(), pBoundingBoxE6.getLonWestE6()),
reuse);
rect.left = reuse.x;
rect.top = reuse.y;
toMapPixels(
new GeoPoint(pBoundingBoxE6.getLatSouthE6(), pBoundingBoxE6.getLonEastE6()),
reuse);
rect.right = reuse.x;
rect.bottom = reuse.y;
return rect;
}
@Override
public float metersToEquatorPixels(final float meters) {
return meters / (float) TileSystem.GroundResolution(0, mZoomLevelProjection);
}
@Override
public Point toPixels(final IGeoPoint in, final Point out) {
return toMapPixels(in, out);
}
@Override
public IGeoPoint fromPixels(final int x, final int y) {
return fromPixels((float) x, (float) y);
}
}
private class MapViewGestureDetectorListener implements OnGestureListener {
@Override
public boolean onDown(final MotionEvent e) {
if (MapView.this.getOverlayManager().onDown(e, MapView.this)) {
return true;
}
mZoomController.setVisible(mEnableZoomController);
return true;
}
@Override
public boolean onFling(final MotionEvent e1, final MotionEvent e2, final float velocityX,
final float velocityY) {
if (MapView.this.getOverlayManager()
.onFling(e1, e2, velocityX, velocityY, MapView.this)) {
return true;
}
final int worldSize = TileSystem.MapSize(mZoomLevel);
mScroller.fling(getScrollX(), getScrollY(), (int) -velocityX, (int) -velocityY,
-worldSize, worldSize, -worldSize, worldSize);
return true;
}
@Override
public void onLongPress(final MotionEvent e) {
MapView.this.getOverlayManager().onLongPress(e, MapView.this);
}
@Override
public boolean onScroll(final MotionEvent e1, final MotionEvent e2, final float distanceX,
final float distanceY) {
if (MapView.this.getOverlayManager().onScroll(e1, e2, distanceX, distanceY,
MapView.this)) {
return true;
}
scrollBy((int) distanceX, (int) distanceY);
return true;
}
@Override
public void onShowPress(final MotionEvent e) {
MapView.this.getOverlayManager().onShowPress(e, MapView.this);
}
@Override
public boolean onSingleTapUp(final MotionEvent e) {
if (MapView.this.getOverlayManager().onSingleTapUp(e, MapView.this)) {
return true;
}
return false;
}
}
private class MapViewDoubleClickListener implements GestureDetector.OnDoubleTapListener {
@Override
public boolean onDoubleTap(final MotionEvent e) {
if (this.getOverlayManager().onDoubleTap(e, MapView.this)) {
return true;
}
final IGeoPoint center = getProjection().fromPixels(e.getX(), e.getY());
return zoomInFixing(center);
}
@Override
public boolean onDoubleTapEvent(final MotionEvent e) {
if (this.getOverlayManager().onDoubleTapEvent(e, MapView.this)) {
return true;
}
return false;
}
@Override
public boolean onSingleTapConfirmed(final MotionEvent e) {
if (this.getOverlayManager().onSingleTapConfirmed(e, MapView.this)) {
return true;
}
return false;
}
}
private class MapViewZoomListener implements OnZoomListener {
@Override
public void onZoom(final boolean zoomIn) {
if (zoomIn) {
getController().zoomIn();
} else {
getController().zoomOut();
}
}
@Override
public void onVisibilityChanged(final boolean visible) {
}
}
// Public Classes
/**
* Per-child layout information associated with OpenStreetMapView.
*/
public static class LayoutParams extends ViewGroup.LayoutParams {
/**
* Special value for the alignment requested by a View. TOP_LEFT means that the location
* will at the top left the View.
*/
public static final int TOP_LEFT = 1;
/**
* Special value for the alignment requested by a View. TOP_RIGHT means that the location
* will be centered at the top of the View.
*/
public static final int TOP_CENTER = 2;
/**
* Special value for the alignment requested by a View. TOP_RIGHT means that the location
* will at the top right the View.
*/
public static final int TOP_RIGHT = 3;
/**
* Special value for the alignment requested by a View. CENTER_LEFT means that the location
* will at the center left the View.
*/
public static final int CENTER_LEFT = 4;
/**
* Special value for the alignment requested by a View. CENTER means that the location will
* be centered at the center of the View.
*/
public static final int CENTER = 5;
/**
* Special value for the alignment requested by a View. CENTER_RIGHT means that the location
* will at the center right the View.
*/
public static final int CENTER_RIGHT = 6;
/**
* Special value for the alignment requested by a View. BOTTOM_LEFT means that the location
* will be at the bottom left of the View.
*/
public static final int BOTTOM_LEFT = 7;
/**
* Special value for the alignment requested by a View. BOTTOM_CENTER means that the
* location will be centered at the bottom of the view.
*/
public static final int BOTTOM_CENTER = 8;
/**
* Special value for the alignment requested by a View. BOTTOM_RIGHT means that the location
* will be at the bottom right of the View.
*/
public static final int BOTTOM_RIGHT = 9;
/**
* The location of the child within the map view.
*/
public GeoPoint geoPoint;
/**
* The alignment the alignment of the view compared to the location.
*/
public int alignment;
public int offsetX;
public int offsetY;
/**
* Creates a new set of layout parameters with the specified width, height and location.
*
* @param width
* the width, either {@link #FILL_PARENT}, {@link #WRAP_CONTENT} or a fixed size
* in pixels
* @param height
* the height, either {@link #FILL_PARENT}, {@link #WRAP_CONTENT} or a fixed size
* in pixels
* @param geoPoint
* the location of the child within the map view
* @param alignment
* the alignment of the view compared to the location {@link #BOTTOM_CENTER},
* {@link #BOTTOM_LEFT}, {@link #BOTTOM_RIGHT} {@link #TOP_CENTER},
* {@link #TOP_LEFT}, {@link #TOP_RIGHT}
* @param offsetX
* the additional X offset from the alignment location to draw the child within
* the map view
* @param offsetY
* the additional Y offset from the alignment location to draw the child within
* the map view
*/
public LayoutParams(final int width, final int height, final GeoPoint geoPoint,
final int alignment, final int offsetX, final int offsetY) {
super(width, height);
if (geoPoint != null) {
this.geoPoint = geoPoint;
} else {
this.geoPoint = new GeoPoint(0, 0);
}
this.alignment = alignment;
this.offsetX = offsetX;
this.offsetY = offsetY;
}
/**
* Since we cannot use XML files in this project this constructor is useless. Creates a new
* set of layout parameters. The values are extracted from the supplied attributes set and
* context.
*
* @param c
* the application environment
* @param attrs
* the set of attributes fom which to extract the layout parameters values
*/
public LayoutParams(final Context c, final AttributeSet attrs) {
super(c, attrs);
this.geoPoint = new GeoPoint(0, 0);
this.alignment = BOTTOM_CENTER;
}
/**
* {@inheritDoc}
*/
public LayoutParams(final ViewGroup.LayoutParams source) {
super(source);
}
}
} |
package jsnpp;
import java.io.PrintWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.Socket;
import java.net.InetSocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
/**
* SNPP Connection Class
*
* @author Don Seiler <don@seiler.us>
* @version $Id$
*/
public class Connection {
private Socket socket = null;
private PrintWriter out = null;
private BufferedReader in = null;
private String host = null;
private int port = 444;
/** Constructor */
public Connection(String host, int port) {
this.host = host;
if (port > 0)
this.port = port;
}
/**
* Connects to host/port of SNPP server.
*
* This method will create the socket to the SNPP server, and return the
* response code. A successful connection will return a String beginning
* with "220", similar to this:
*
* 220 QuickPage v3.3 SNPP server ready at Tue May 17 11:48:12 2005
*
* @return Response of SNPP server to connection.
*/
public String connect() throws UnknownHostException, IOException {
return connect(0, 0);
}
/**
* Connects to host/port of SNPP server, with specified timeout settings.
*
* This method will create the socket to the SNPP server, and return the
* response code. A successful connection will return a String beginning
* with "220", similar to this:
*
* 220 QuickPage v3.3 SNPP server ready at Tue May 17 11:48:12 2005
*
* @param socketConnectTimeout Timeout in milliseconds for connection attempt. A timeout of zero is interpreted as an infinite timeout.
* @param socketInputTimeout Timeout in milliseconds to wait on responses from the SNPP server. A timeout of zero is interpreted as an infinite timeout.
* @return Response of SNPP server to connection.
*/
public String connect(int socketConnectTimeout, int socketInputTimeout)
throws UnknownHostException, IOException, SocketTimeoutException {
socket.connect(new InetSocketAddress(host, port), socketConnectTimeout);
socket.setSoTimeout(socketInputTimeout);
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// This will contain the immediate response
return in.readLine();
}
/**
* Closes connection to SNPP server.
*/
public void close() throws IOException {
out.close();
in.close();
socket.close();
}
/** Sends data to SNPP server */
public String send(String data) throws IOException {
return send(data, true);
}
public String send(String data, boolean wait) throws IOException {
String response = null;
// Send command to server
out.println(data);
//System.out.println(data);
// Read response
if (wait) {
response = in.readLine();
//System.out.println(response);
}
// Return response, or null
return response;
}
} |
import java.io.*;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.control.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import java.util.Arrays;
import java.nio.file.Files;
public abstract class Generador implements Graficable{
protected Palabra[] palabras;
protected String texto;
protected int limite;
protected final int maxFontSize=150;
private final int WIDTH = 1280;
private final int HEIGHT = 1000;
//signos en variables -no entiendo este comment
public Generador(File texto, int limite) {
this.texto=archivoATexto(texto);
this.limite=limite;
}
public String archivoATexto(File input) {
//aqui se recibe el archivo y se regresa una string
try {
return new String(Files.readAllBytes(input.toPath()));
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return "";
}
public Scene iniciar(){
llenarArreglo();
ordenarArreglo();
recortarArreglo();
determinarFontSizePorPalabra();
//ahora iniciar UI y acomodar todas las labels donde deben ir
Scene escena = crearNube();
acomodarPalabras(escena);
return escena;
}
public abstract void llenarArreglo(); //el unico metodo que se queda abstracto es llenarArreglo porque uno tiene lista negra y el otro no
public void determinarFontSizePorPalabra() {
int cantidadPalabras=0;
int frecuenciaMax=palabras[0].getFrecuencia();
for (Palabra palabra:palabras) {
palabra.setFontSize(palabra.getFrecuencia()*maxFontSize/frecuenciaMax);
}
}
public Scene crearNube() {
//crear UI y mostrarala como siempre y regresar la escena con un grupo raiz vacio y ya
Group root = new Group();
Scene scene = new Scene(root, WIDTH, HEIGHT, Color.DEEPSKYBLUE);
return scene;
}
public void acomodarPalabras(Scene escena) {
for (Palabra palabra : palabras) {
System.out.println("La palabra que se acomodara es "+palabra.getContenido()+", ancho: "+palabra.getWidth()+", alto: "+palabra.getHeight());
acomodarPalabra(palabra, escena);
}
}
public void acomodarPalabra(Palabra palabra, Scene escena) {
//checar colosiones primero para y positivos despues para negativos (cuadrantes II (-+), I (++), III(--), IV(+-)), iterar para cada radio del circulo
boolean acomodado=false;
//iterador de radio
for (int r=0; !acomodado; r++) {
//empezar con cuadrantes II y I, probando todas las x entre 0 y |r|
for (int x=-r ; x<=r && !acomodado; x++) {
int y = funcionCirculo(x,r);
x=x+palabra.getWidth()/2;
y=y+palabra.getHeight()/2;
boolean colision = checarColision(palabra, x, y);
System.out.println("loopsigue para "+palabra.getContenido());
if (!colision) {
Label etiqueta = palabra.getLabel();
//agregar etiqueta a escena
//guardar coordenadas relativo a un centro de coordenadas 0|0
palabra.setCoordenadas(x, y);
etiqueta.setTranslateX(x+WIDTH/2);
etiqueta.setTranslateY(y+HEIGHT/2);
System.out.println("x es: " + x + " e y es: " +y);
((Group)escena.getRoot()).getChildren().add(etiqueta);
acomodado=true; //ya se acomodo
}
}
//solo tiene sentido intentar acomodarlo en cuadrantes III y IV si no se ha podido acomodar arriba
for (int x = -r; x <= r && !acomodado; x++) {
int y = -funcionCirculo(x, r);
x=x+palabra.getWidth()/2;
y=y+palabra.getHeight()/2;
System.out.println("loopsiguepara "+palabra.getContenido());
boolean colision = checarColision(palabra, x, y);
if (!colision) {
Label etiqueta = palabra.getLabel();
//agregar etiqueta a escena
//guardar coordenadas relativo a un centro de coordenadas 0|0 y en el centro de la palabra
palabra.setCoordenadas(x, y);
etiqueta.setTranslateX(x+WIDTH/2);
etiqueta.setTranslateY(y+HEIGHT/2);
((Group)escena.getRoot()).getChildren().add(etiqueta);
acomodado=true; //ya se acomodo
System.out.println("x es: " + x + " e y es: " +y);
}
}
}
}
public boolean checarColision(Palabra palabra, int x, int y) {
//checar si no hay una superposicion de la palabra actual y alguna otra palabra en la posicion deseada
// int w = palabra.getWidth();
// int h = palabra.getHeight();
//importante, el centro de coordenadas de las labels es la esquina de arriba izquierda, tomar en cuenta
//la colision ocurre cuando el rectangulo de la palabra actual coincide con el de alguna palabra, es decir, cuando el rango de x && de y de ambos rectangulos coincide para una o mas combinaciones de x && y
for (Palabra actual : palabras){
if (actual.getX()!=-2147483648 && actual.getY()!=-2147483648) { //si no se ha acomodado la palabra actual (x o y == valor minimo de int), no tiene sentido checar colisiones
//if (RectA.Left < RectB.Right && RectA.Right > RectB.Left && RectA.Top < RectB.Bottom && RectA.Bottom > RectB.Top )
System.out.println("no llega aqui"+actual.getWidth());
if (x-palabra.getWidth()/2 < actual.getX()+actual.getWidth()/2 && x+palabra.getWidth()/2 > actual.getX()-actual.getWidth()/2 &&
y+palabra.getHeight()/2 < actual.getY()-actual.getHeight()/2 && y-palabra.getHeight()/2> actual.getY()+actual.getHeight()/2 ) {
return true; //hubo colision
}
}
}
return false;
}
public int funcionCirculo(int x, int r) { //recibe un valor x regresa el valor positivo correspondiente de la funcion x^2 + y^2 = r^2
return (int)Math.sqrt(r*r-x*x);
}
public void agregarPalabra(String nuevaPalabra) {
Label etiqueta = new Label(nuevaPalabra);
palabras = Arrays.copyOf(palabras, palabras.length + 1);
palabras[palabras.length - 1] = new Palabra(nuevaPalabra, etiqueta);
}
public void ordenarArreglo() {
// bubble sort! (ineficiente pero facil de programar)
int n = palabras.length;
Palabra temp;
for(int i=0; i < n; i++){
for(int j=1; j > (n-i); j++){
if(palabras[j-1].getFrecuencia() > palabras[j].getFrecuencia()){
//hacer el cambio
temp = palabras[j-1];
palabras[j-1] = palabras[j];
palabras[j] = temp;
}
}
}
}
public void recortarArreglo() {
if (palabras.length>limite) {
//recortar arreglo
palabras = Arrays.copyOf(palabras, limite);
}
}
public Palabra[] getPalabras(){ return palabras;}
} |
package org.hawk.ui2.dialog;
import java.io.File;
import java.util.Collections;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.List;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.ui.PlatformUI;
import org.hawk.core.IStateListener;
import org.hawk.core.IVcsManager;
import org.hawk.osgiserver.HModel;
import org.hawk.ui2.view.HView;
public class HConfigDialog extends TitleAreaDialog implements IStateListener {
private static final String DEFAULT_MESSAGE = "Manage metamodels, locations and indexed/derived attributes in the indexer.";
static final class ClassNameLabelProvider extends LabelProvider {
@Override
public String getText(Object element) {
return element.getClass().getName();
}
}
HModel hawkModel;
private List metamodelList;
private List derivedAttributeList;
private List indexedAttributeList;
private List indexList;
private ListViewer lstVCSLocations;
private Button indexRefreshButton;
private Button removeDerivedAttributeButton;
private Button addDerivedAttributeButton;
private Button removeIndexedAttributeButton;
private Button addIndexedAttributeButton;
private Button removeMetaModelsButton;
private Button addMetaModelsButton;
private Button addVCSButton;
private Button editVCSButton;
private Button removeVCSButton;
HawkState hawkState;
public HConfigDialog(Shell parentShell, HModel in) {
super(parentShell);
setShellStyle(getShellStyle() & ~SWT.CLOSE);
hawkModel = in;
hawkModel.getHawk().getModelIndexer().addStateListener(this);
}
private Composite allIndexesTab(TabFolder parent) {
final Composite composite = new Composite(parent, SWT.BORDER);
final GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 1;
composite.setLayout(gridLayout);
indexList = new List(composite, SWT.BORDER | SWT.V_SCROLL
| SWT.H_SCROLL);
GridData gridDataQ = new GridData();
gridDataQ.grabExcessHorizontalSpace = true;
gridDataQ.horizontalAlignment = GridData.FILL;
gridDataQ.heightHint = 300;
gridDataQ.widthHint = 600;
gridDataQ.horizontalSpan = 2;
indexList.setLayoutData(gridDataQ);
updateAllIndexesList();
indexRefreshButton = new Button(composite, SWT.NONE);
indexRefreshButton.setText("Refresh");
indexRefreshButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
updateAllIndexesList();
}
});
return composite;
}
private void derivedAttributeAdd() {
Dialog d = new HDerivedAttributeDialog(hawkModel, getShell());
d.setBlockOnOpen(true);
if (d.open() == Window.OK)
updateDerivedAttributeList();
}
private Composite derivedAttributeTab(TabFolder parent) {
final Composite composite = new Composite(parent, SWT.BORDER);
final GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
composite.setLayout(gridLayout);
derivedAttributeList = new List(composite, SWT.BORDER | SWT.MULTI
| SWT.V_SCROLL | SWT.H_SCROLL);
GridData gridDataQ = new GridData();
gridDataQ.grabExcessHorizontalSpace = true;
gridDataQ.horizontalAlignment = GridData.FILL;
gridDataQ.heightHint = 300;
gridDataQ.widthHint = 600;
gridDataQ.horizontalSpan = 2;
derivedAttributeList.setLayoutData(gridDataQ);
derivedAttributeList.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean running = hawkState == HawkState.RUNNING;
removeDerivedAttributeButton.setEnabled(running
&& derivedAttributeList.getSelection().length > 0);
}
});
updateDerivedAttributeList();
removeDerivedAttributeButton = new Button(composite, SWT.PUSH);
removeDerivedAttributeButton.setText("Remove");
removeDerivedAttributeButton
.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
// remove action
String[] selected = null;
if (derivedAttributeList.getSelection().length > 0)
selected = derivedAttributeList.getSelection();
if (selected != null) {
MessageBox messageBox = new MessageBox(getShell(),
SWT.ICON_QUESTION | SWT.YES | SWT.NO);
messageBox
.setMessage("Are you sure you wish to delete the chosen derived attributes?");
messageBox.setText("Indexed Attribute deletion");
int response = messageBox.open();
if (response == SWT.YES) {
hawkModel.removeDerviedAttributes(selected);
updateDerivedAttributeList();
}
}
}
});
addDerivedAttributeButton = new Button(composite, SWT.NONE);
addDerivedAttributeButton.setText("Add...");
addDerivedAttributeButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
derivedAttributeAdd();
}
});
return composite;
}
private void indexedAttributeAdd() {
Dialog d = new HIndexedAttributeDialog(hawkModel, getShell());
d.setBlockOnOpen(true);
if (d.open() == Window.OK)
updateIndexedAttributeList();
}
private Composite indexedAttributeTab(TabFolder parent) {
final Composite composite = new Composite(parent, SWT.BORDER);
final GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
composite.setLayout(gridLayout);
indexedAttributeList = new List(composite, SWT.BORDER | SWT.MULTI
| SWT.V_SCROLL | SWT.H_SCROLL);
GridData gridDataQ = new GridData();
gridDataQ.grabExcessHorizontalSpace = true;
gridDataQ.horizontalAlignment = GridData.FILL;
gridDataQ.heightHint = 300;
gridDataQ.widthHint = 600;
gridDataQ.horizontalSpan = 2;
indexedAttributeList.setLayoutData(gridDataQ);
indexedAttributeList.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean running = hawkState == HawkState.RUNNING;
removeIndexedAttributeButton.setEnabled(running
&& indexedAttributeList.getSelection().length > 0);
}
});
updateIndexedAttributeList();
removeIndexedAttributeButton = new Button(composite, SWT.PUSH);
removeIndexedAttributeButton.setText("Remove");
removeIndexedAttributeButton
.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
// remove action
String[] selected = null;
if (indexedAttributeList.getSelection().length > 0)
selected = indexedAttributeList.getSelection();
if (selected != null) {
MessageBox messageBox = new MessageBox(getShell(),
SWT.ICON_QUESTION | SWT.YES | SWT.NO);
messageBox
.setMessage("Are you sure you wish to delete the chosen indexed attributes?");
messageBox.setText("Indexed Attribute deletion");
int response = messageBox.open();
if (response == SWT.YES) {
hawkModel.removeIndexedAttributes(selected);
updateIndexedAttributeList();
}
}
}
});
addIndexedAttributeButton = new Button(composite, SWT.NONE);
addIndexedAttributeButton.setText("Add...");
addIndexedAttributeButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
indexedAttributeAdd();
}
});
return composite;
}
private void metamodelBrowse() {
FileDialog fd = new FileDialog(getShell(), SWT.MULTI);
fd.setFilterPath(ResourcesPlugin.getWorkspace().getRoot().getLocation()
.toFile().toString());
// TODO: allow selection of only parse-able/known metamodels-file-types
fd.setFilterExtensions(new String[] { "*.ecore", "*.*" });
fd.setText("Select metamodels");
String result = fd.open();
if (result != null) {
String[] metaModels = fd.getFileNames();
File[] metaModelFiles = new File[metaModels.length];
boolean error = false;
for (int i = 0; i < metaModels.length; i++) {
File file = new File(fd.getFilterPath() + File.separator
+ metaModels[i]);
if (!file.exists() || !file.canRead() || !file.isFile())
error = true;
else
metaModelFiles[i] = file;
}
if (!error) {
hawkModel.registerMeta(metaModelFiles);
updateMetamodelList();
}
}
}
private Composite metamodelsTab(TabFolder parent) {
final Composite composite = new Composite(parent, SWT.BORDER);
final GridLayout gridLayout = new GridLayout();
gridLayout.numColumns = 2;
composite.setLayout(gridLayout);
metamodelList = new List(composite, SWT.BORDER | SWT.MULTI
| SWT.V_SCROLL | SWT.H_SCROLL);
GridData gridDataQ = new GridData();
gridDataQ.grabExcessHorizontalSpace = true;
gridDataQ.horizontalAlignment = GridData.FILL;
gridDataQ.heightHint = 300;
gridDataQ.widthHint = 600;
gridDataQ.horizontalSpan = 2;
metamodelList.setLayoutData(gridDataQ);
updateMetamodelList();
removeMetaModelsButton = new Button(composite, SWT.PUSH);
removeMetaModelsButton.setText("Remove");
removeMetaModelsButton.setEnabled(hawkState == HawkState.RUNNING);
removeMetaModelsButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
// remove action
String[] selectedMetamodel = null;
if (metamodelList.getSelection().length > 0)
selectedMetamodel = metamodelList.getSelection();
if (selectedMetamodel != null) {
MessageBox messageBox = new MessageBox(getShell(),
SWT.ICON_QUESTION | SWT.YES | SWT.NO);
messageBox
.setMessage("Are you sure you wish to delete the chosen metamodel(s)? This will also delete any dependant metamodels/models and may take a long time to complete.");
messageBox.setText("Metamodel deletion");
int response = messageBox.open();
if (response == SWT.YES) {
hawkModel.removeMetamodels(selectedMetamodel);
updateMetamodelList();
}
}
}
});
addMetaModelsButton = new Button(composite, SWT.PUSH);
addMetaModelsButton.setText("Add...");
addMetaModelsButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
metamodelBrowse();
}
});
return composite;
}
private void updateAllIndexesList() {
indexList.removeAll();
for (String i : hawkModel.getIndexes()) {
indexList.add(i);
}
String[] items = indexList.getItems();
java.util.Arrays.sort(items);
indexList.setItems(items);
}
private void updateDerivedAttributeList() {
derivedAttributeList.removeAll();
for (String da : hawkModel.getDerivedAttributes()) {
derivedAttributeList.add(da);
}
String[] items = derivedAttributeList.getItems();
java.util.Arrays.sort(items);
derivedAttributeList.setItems(items);
}
private void updateIndexedAttributeList() {
indexedAttributeList.removeAll();
for (String ia : hawkModel.getIndexedAttributes()) {
indexedAttributeList.add(ia);
}
String[] items = indexedAttributeList.getItems();
java.util.Arrays.sort(items);
indexedAttributeList.setItems(items);
}
private void updateMetamodelList() {
metamodelList.removeAll();
final java.util.List<String> mms = hawkModel.getRegisteredMetamodels();
Collections.sort(mms);
for (String mm : mms) {
metamodelList.add(mm);
}
}
private Composite vcsTab(TabFolder parent) {
final Composite composite = new Composite(parent, SWT.BORDER);
final GridLayout layout = new GridLayout();
layout.numColumns = 3;
composite.setLayout(layout);
lstVCSLocations = new ListViewer(composite, SWT.BORDER | SWT.V_SCROLL
| SWT.H_SCROLL);
lstVCSLocations.setLabelProvider(new LabelProvider() {
@Override
public String getText(Object element) {
return ((IVcsManager) element).getLocation();
}
});
lstVCSLocations.setContentProvider(new ArrayContentProvider());
lstVCSLocations.setInput(hawkModel.getRunningVCSManagers().toArray());
final GridData lstVCSLocationsLayoutData = new GridData(SWT.FILL,
SWT.FILL, true, true);
lstVCSLocationsLayoutData.horizontalSpan = 3;
lstVCSLocations.getList().setLayoutData(lstVCSLocationsLayoutData);
editVCSButton = new Button(composite, SWT.NONE);
editVCSButton.setText("Edit...");
editVCSButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
new HVCSDialog(getShell(), hawkModel,
getSelectedExistingVCSManager()).open();
lstVCSLocations.refresh();
}
});
editVCSButton.setEnabled(false);
removeVCSButton = new Button(composite, SWT.NONE);
removeVCSButton.setText("Remove");
removeVCSButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
// remove action
IVcsManager m = getSelectedExistingVCSManager();
if (m != null) {
MessageBox messageBox = new MessageBox(getShell(),
SWT.ICON_QUESTION | SWT.YES | SWT.NO);
messageBox
.setMessage("Are you sure you wish to remove the chosen VCS location? This will also delete all indexed models from it, and may take a long time to complete.");
messageBox.setText("VCS location deletion");
int response = messageBox.open();
if (response == SWT.YES) {
try {
hawkModel.removeRepository(m);
} catch (Exception ee) {
ee.printStackTrace();
}
lstVCSLocations.setInput(hawkModel
.getRunningVCSManagers().toArray());
}
}
}
});
removeVCSButton.setEnabled(false);
addVCSButton = new Button(composite, SWT.NONE);
addVCSButton.setText("Add...");
addVCSButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
new HVCSDialog(getShell(), hawkModel, null).open();
lstVCSLocations.setInput(hawkModel.getRunningVCSManagers()
.toArray());
}
});
lstVCSLocations.getList().addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
boolean running = hawkState == HawkState.RUNNING;
editVCSButton.setEnabled(running
&& getSelectedExistingVCSManager() != null);
removeVCSButton.setEnabled(running
&& getSelectedExistingVCSManager() != null);
}
});
return composite;
}
protected IVcsManager getSelectedExistingVCSManager() {
final IStructuredSelection sel = (IStructuredSelection) lstVCSLocations
.getSelection();
if (sel.isEmpty()) {
return null;
}
return (IVcsManager) sel.getFirstElement();
}
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText("Configure Indexer: " + hawkModel.getName());
}
protected Button createButton(Composite parent, int id, String label,
boolean defaultButton) {
if (id == IDialogConstants.CANCEL_ID) {
return null;
}
return super.createButton(parent, id, label, defaultButton);
}
@Override
protected void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
Button done = getButton(IDialogConstants.OK_ID);
done.setText("Done");
setButtonLayoutData(done);
}
protected Control createDialogArea(Composite parent) {
try {
setDefaultImage(PlatformUI.getWorkbench()
.getActiveWorkbenchWindow().getActivePage()
.findView(HView.ID).getTitleImage());
} catch (Exception e1) {
e1.printStackTrace();
}
TabFolder tabFolder = new TabFolder(parent, SWT.BORDER);
tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
TabItem metamodelTab = new TabItem(tabFolder, SWT.NULL);
metamodelTab.setText("Metamodels");
metamodelTab.setControl(metamodelsTab(tabFolder));
TabItem vcsTab = new TabItem(tabFolder, SWT.NULL);
vcsTab.setText("Indexed Locations");
vcsTab.setControl(vcsTab(tabFolder));
TabItem derivedAttributeTab = new TabItem(tabFolder, SWT.NULL);
derivedAttributeTab.setText("Derived Attributes");
derivedAttributeTab.setControl(derivedAttributeTab(tabFolder));
TabItem indexedAttributeTab = new TabItem(tabFolder, SWT.NULL);
indexedAttributeTab.setText("Indexed Attributes");
indexedAttributeTab.setControl(indexedAttributeTab(tabFolder));
TabItem allIndexesTab = new TabItem(tabFolder, SWT.NULL);
allIndexesTab.setText("All indexes");
allIndexesTab.setControl(allIndexesTab(tabFolder));
tabFolder.pack();
setTitle("Configuration for indexer " + hawkModel.getName());
setMessage(DEFAULT_MESSAGE);
return tabFolder;
}
@Override
public boolean close() {
hawkModel.getHawk().getModelIndexer().removeStateListener(this);
return super.close();
}
@Override
public void state(HawkState state) {
updateAsync(state);
}
@Override
public void info(String s) {
// not used in config dialogs
}
@Override
public void error(String s) {
// not used in config dialogs
}
@Override
public void removed() {
// used for remote message cases
}
public void updateAsync(final HawkState s) {
if (this.hawkState == s) {
return;
}
this.hawkState = s;
Shell shell = getShell();
if (shell == null) {
return;
}
Display display = shell.getDisplay();
if (display == null) {
return;
}
display.asyncExec(new Runnable() {
public void run() {
try {
// primary display buttons
final boolean running = s == HawkState.RUNNING;
indexRefreshButton.setEnabled(running);
removeDerivedAttributeButton.setEnabled(running);
addDerivedAttributeButton.setEnabled(running);
removeIndexedAttributeButton.setEnabled(running);
addIndexedAttributeButton.setEnabled(running);
removeMetaModelsButton.setEnabled(running);
addMetaModelsButton.setEnabled(running);
addVCSButton.setEnabled(running);
editVCSButton.setEnabled(running
&& getSelectedExistingVCSManager() != null);
if (running) {
setErrorMessage(null);
} else {
setErrorMessage(String
.format("The index is %s - some buttons will be disabled",
s.toString().toLowerCase()));
}
} catch (Exception e) {
// suppress
}
}
});
}
} |
package com.aware.plugin.term_collector;
import android.content.ClipboardManager;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;
import com.aware.Aware;
import com.aware.Aware_Preferences;
import com.aware.plugin.term_collector.TermCollector_Provider.TermCollector;
import com.aware.utils.Aware_Plugin;
import java.util.ArrayList;
import io.mingle.v1.Mingle;
import io.mingle.v1.Response;
/**
* Main Plugin for the TERM Collector
*
* @author Wolfgang Lutz
* @email: wolfgang@lutz-wiesent.de
*/
public class Plugin extends Aware_Plugin {
private static final String TAG = "TermCollector Plugin";
public static final String ACTION_AWARE_TERMCOLLECTOR = "ACTION_AWARE_TERMCOLLECTOR";
private static StopList stopList;
private ClipboardManager.OnPrimaryClipChangedListener clipboardListener;
public static final String EXTRA_TERMCONTENT = "termcontent";
public static String lastTermContent = "";
public static Uri clipboardCatcherContentUri;
private static ClipboardCatcherObserver clipboardCatcherObs = null;
public static Uri notificationCatcherContentUri;
private static NotificationCatcherObserver notificationCatcherObs = null;
public static Uri smsReceiverContentUri;
private static SmsReceiverObserver smsReceiverObs = null;
public static Uri locationDissolverContentUri;
private static LocationDissolverObserver locationDissolverObs = null;
/**
* Thread manager
*/
private static HandlerThread threads = null;
@Override
public void onCreate() {
Log.d(TAG, "Plugin Created");
super.onCreate();
stopList = new StopList();
// Share the context back to the framework and other applications
CONTEXT_PRODUCER = new Aware_Plugin.ContextProducer() {
@Override
public void onContext() {
Log.d(TAG, "Putting extra context into intent");
Intent notification = new Intent(ACTION_AWARE_TERMCOLLECTOR);
notification
.putExtra(Plugin.EXTRA_TERMCONTENT, lastTermContent);
sendBroadcast(notification);
}
};
DATABASE_TABLES = TermCollector_Provider.DATABASE_TABLES;
TABLES_FIELDS = TermCollector_Provider.TABLES_FIELDS;
CONTEXT_URIS = new Uri[]{TermCollector.CONTENT_URI};
threads = new HandlerThread(TAG);
threads.start();
// Set the observers, that run in independent threads, for
// responsiveness
clipboardCatcherContentUri = Uri
.parse("content://com.aware.provider.plugin.clipboard_catcher/plugin_clipboard_catcher");
clipboardCatcherObs = new ClipboardCatcherObserver(new Handler(
threads.getLooper()));
getContentResolver().registerContentObserver(
clipboardCatcherContentUri, true, clipboardCatcherObs);
Log.d(TAG, "clipboardCatcherObs registered");
notificationCatcherContentUri = Uri
.parse("content://com.aware.provider.plugin.notification_catcher/plugin_notification_catcher");
notificationCatcherObs = new NotificationCatcherObserver(new Handler(
threads.getLooper()));
getContentResolver().registerContentObserver(
notificationCatcherContentUri, true, notificationCatcherObs);
Log.d(TAG, "notificationCatcherObs registered");
smsReceiverContentUri = Uri
.parse("content://com.aware.provider.plugin.sms_receiver/plugin_sms_receiver");
smsReceiverObs = new SmsReceiverObserver(new Handler(
threads.getLooper()));
getContentResolver().registerContentObserver(
smsReceiverContentUri, true, smsReceiverObs);
Log.d(TAG, "smsReceiverObs registered");
locationDissolverContentUri = Uri
.parse("content://com.aware.provider.plugin.location_dissolver/plugin_location_dissolver");
locationDissolverObs = new LocationDissolverObserver(new Handler(
threads.getLooper()));
getContentResolver().registerContentObserver(
locationDissolverContentUri, true, locationDissolverObs);
Log.d(TAG, "locationDissolverObs registered");
Log.d(TAG, "Plugin Started");
}
@Override
public void onDestroy() {
Log.d(TAG, "Plugin is destroyed");
super.onDestroy();
android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
clipboardManager.removePrimaryClipChangedListener(clipboardListener);
getContentResolver().unregisterContentObserver(clipboardCatcherObs);
getContentResolver().unregisterContentObserver(notificationCatcherObs);
getContentResolver().unregisterContentObserver(smsReceiverObs);
}
protected void saveData(long timestamp, String source, String content) {
Log.d(TAG, "Saving Data");
ContentValues rowData = new ContentValues();
rowData.put(TermCollector.DEVICE_ID, Aware.getSetting(
getContentResolver(), Aware_Preferences.DEVICE_ID));
rowData.put(TermCollector.TIMESTAMP, timestamp);
rowData.put(TermCollector.TERM_SOURCE, source);
rowData.put(TermCollector.TERM_CONTENT, content);
Log.d(TAG, "Saving " + rowData.toString());
getContentResolver().insert(TermCollector.CONTENT_URI, rowData);
}
protected void splitAndFilterAndSaveData(long timestamp, String source, String content) {
Log.wtf(TAG, "Splitting Content");
Log.wtf(TAG, "Content: " + content);
//remove all characters that are not A-Za-z
String[] contentTokens = content.replaceAll("[^A-Za-zÄÖÜäöü]", " ").split("\\s+");
//filter Stopwords
contentTokens = stopList.filteredArray(contentTokens);
ArrayList<String> filteredTokens = new ArrayList<String>();
// filter Lowercase tokens and tokens shorter than 3 characters
for (String token : contentTokens) {
if (Character.isUpperCase(token.charAt(0))) {
if (token.length() > 2) {
filteredTokens.add(token);
} else {
Log.wtf(TAG, "Ignoring " + token + " as it is shorter than 3 characters.");
}
} else {
Log.wtf(TAG, "Ignoring " + token + " as it is not uppercase");
}
}
//classify cities
ArrayList<String> cityTokens = new ArrayList<String>();
ArrayList<String> nonCityTokens = new ArrayList<String>();
for (String token : filteredTokens) {
{
Log.wtf(TAG, "Dissolving " + token);
// dissolve them with mingle
Mingle mingle;
try {
mingle = new Mingle();
if (mingle.geonames().existsPopulatedPlaceWithName(token)) {
Log.wtf(TAG, token + " is a city");
cityTokens.add(token);
} else {
nonCityTokens.add(token);
Log.wtf(TAG, token + " is not a city");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
int tokenIndex = 0;
for (String token : nonCityTokens) {
saveData(timestamp + tokenIndex, source, token);
tokenIndex++;
}
}
public class ClipboardCatcherObserver extends ContentObserver {
public ClipboardCatcherObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.d(TAG, "@onChange");
// set cursor to first item
Cursor cursor = getContentResolver().query(
clipboardCatcherContentUri, null, null, null,
"timestamp" + " DESC LIMIT 1");
if (cursor != null && cursor.moveToFirst()) {
splitAndFilterAndSaveData(cursor.getLong(cursor.getColumnIndex("timestamp")),
clipboardCatcherContentUri.toString(),
cursor.getString(cursor
.getColumnIndex("CLIPBOARDCONTENT")));
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
public class NotificationCatcherObserver extends ContentObserver {
public NotificationCatcherObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.d(TAG, "@onChange");
// set cursor to first item
Cursor cursor = getContentResolver().query(
notificationCatcherContentUri, null, null, null,
"timestamp" + " DESC LIMIT 1");
if (cursor != null && cursor.moveToFirst()) {
splitAndFilterAndSaveData(cursor.getLong(cursor.getColumnIndex("timestamp")),
notificationCatcherContentUri.toString(),
cursor.getString(cursor
.getColumnIndex("TEXT")));
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
public class SmsReceiverObserver extends ContentObserver {
public SmsReceiverObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
// set cursor to first item
Cursor cursor = getContentResolver().query(
smsReceiverContentUri, null, null, null,
"timestamp" + " DESC LIMIT 1");
if (cursor != null && cursor.moveToFirst()) {
splitAndFilterAndSaveData(cursor.getLong(cursor.getColumnIndex("timestamp")),
smsReceiverContentUri.toString(),
cursor.getString(cursor
.getColumnIndex("SMSCONTENT")));
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
public class LocationDissolverObserver extends ContentObserver {
public LocationDissolverObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
// set cursor to first item
Cursor cursor = getContentResolver().query(
locationDissolverContentUri, null, null, null,
"timestamp" + " DESC LIMIT 1");
if (cursor != null && cursor.moveToFirst()) {
saveData(cursor.getLong(cursor.getColumnIndex("timestamp")),
locationDissolverContentUri.toString(),
cursor.getString(cursor
.getColumnIndex("NAME")));
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
} |
package com.aware.plugin.term_collector;
import android.content.ContentValues;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.net.Uri;
import android.os.Handler;
import android.os.HandlerThread;
import android.text.TextUtils;
import android.util.Log;
import com.aware.Aware;
import com.aware.Aware_Preferences;
import com.aware.plugin.term_collector.TermCollector_Provider.TermCollectorGeoData;
import com.aware.plugin.term_collector.TermCollector_Provider.TermCollectorGeoDataCache;
import com.aware.plugin.term_collector.TermCollector_Provider.TermCollectorTermData;
import com.aware.utils.Aware_Plugin;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import de.unipassau.mics.contextopheles.base.ContextophelesConstants;
import de.unipassau.mics.contextopheles.utils.BlacklistedApps;
import de.unipassau.mics.contextopheles.utils.CommonConnectors;
import de.unipassau.mics.contextopheles.utils.CommonSettings;
import de.unipassau.mics.contextopheles.utils.StopWords;
import io.mingle.v1.Mingle;
/**
* Main Plugin for the TERM Collector
*
* @author Wolfgang Lutz
* @email: wolfgang@lutz-wiesent.de
*/
public class Plugin extends Aware_Plugin {
private static final String TAG = ContextophelesConstants.TAG_TERM_COLLECTOR + " Plugin";
public static final String ACTION_AWARE_TERMCOLLECTOR = "ACTION_AWARE_TERMCOLLECTOR";
private static StopWords stopWords;
private static CommonConnectors commonConnectors;
private static BlacklistedApps blacklistedApps;
public static final String EXTRA_TERMCONTENT = "termcontent";
public static String lastTermContent = "";
public static Uri clipboardCatcherContentUri;
private static ClipboardCatcherObserver clipboardCatcherObs = null;
public static Uri notificationCatcherContentUri;
private static NotificationCatcherObserver notificationCatcherObs = null;
public static Uri smsReceiverContentUri;
private static SmsReceiverObserver smsReceiverObs = null;
public static Uri osmpoiResolverContentUri;
private static OSMPoiResolverObserver osmpoiResolverObs = null;
public static Uri uiContentContentUri;
private static UIContentObserver uiContentObs = null;
public static Uri geonameResolverContentUri;
private static GeonameResolverObserver geonameResolverObs = null;
private static String sanitizingString = "[^A-Za-zÄÖÜäöüß\\- ]";
/**
* Thread manager
*/
private static HandlerThread threads = null;
@Override
public void onCreate() {
Log.d(TAG, "Plugin Created");
super.onCreate();
stopWords = new StopWords(getApplicationContext());
commonConnectors = new CommonConnectors(getApplicationContext());
blacklistedApps = new BlacklistedApps(getApplicationContext());
// Share the context back to the framework and other applications
CONTEXT_PRODUCER = new Aware_Plugin.ContextProducer() {
@Override
public void onContext() {
Intent notification = new Intent(ACTION_AWARE_TERMCOLLECTOR);
notification
.putExtra(Plugin.EXTRA_TERMCONTENT, lastTermContent);
sendBroadcast(notification);
}
};
DATABASE_TABLES = TermCollector_Provider.DATABASE_TABLES;
TABLES_FIELDS = TermCollector_Provider.TABLES_FIELDS;
CONTEXT_URIS = new Uri[]{TermCollectorTermData.CONTENT_URI, TermCollectorGeoData.CONTENT_URI};
threads = new HandlerThread(TAG);
threads.start();
// Set the observers, that run in independent threads, for
// responsiveness
clipboardCatcherContentUri = ContextophelesConstants.CLIPBOARD_CATCHER_CONTENT_URI;
clipboardCatcherObs = new ClipboardCatcherObserver(new Handler(
threads.getLooper()));
getContentResolver().registerContentObserver(
clipboardCatcherContentUri, true, clipboardCatcherObs);
Log.d(TAG, "clipboardCatcherObs registered");
notificationCatcherContentUri = ContextophelesConstants.NOTIFICATION_CATCHER_CONTENT_URI;
notificationCatcherObs = new NotificationCatcherObserver(new Handler(
threads.getLooper()));
getContentResolver().registerContentObserver(
notificationCatcherContentUri, true, notificationCatcherObs);
Log.d(TAG, "notificationCatcherObs registered");
smsReceiverContentUri = ContextophelesConstants.SMS_RECEIVER_CONTENT_URI;
smsReceiverObs = new SmsReceiverObserver(new Handler(
threads.getLooper()));
getContentResolver().registerContentObserver(
smsReceiverContentUri, true, smsReceiverObs);
Log.d(TAG, "smsReceiverObs registered");
osmpoiResolverContentUri = ContextophelesConstants.OSMPOI_RESOLVER_CONTENT_URI;
osmpoiResolverObs = new OSMPoiResolverObserver(new Handler(
threads.getLooper()));
getContentResolver().registerContentObserver(
osmpoiResolverContentUri, true, osmpoiResolverObs);
Log.d(TAG, "osmpoiResolverObs registered");
uiContentContentUri = ContextophelesConstants.UI_CONTENT_CONTENT_URI;
uiContentObs = new UIContentObserver(new Handler(
threads.getLooper()));
getContentResolver().registerContentObserver(
uiContentContentUri, true, uiContentObs);
Log.d(TAG, "uiContentObs registered");
geonameResolverContentUri = ContextophelesConstants.GEONAME_RESOLVER_CONTENT_URI;
geonameResolverObs = new GeonameResolverObserver(new Handler(
threads.getLooper()));
getContentResolver().registerContentObserver(
geonameResolverContentUri, true, geonameResolverObs);
Log.d(TAG, "geonameResolverObs registered");
Log.d(TAG, "Plugin Started");
}
@Override
public void onDestroy() {
Log.d(TAG, "Plugin is destroyed");
super.onDestroy();
getContentResolver().unregisterContentObserver(clipboardCatcherObs);
getContentResolver().unregisterContentObserver(notificationCatcherObs);
getContentResolver().unregisterContentObserver(smsReceiverObs);
getContentResolver().unregisterContentObserver(osmpoiResolverObs);
getContentResolver().unregisterContentObserver(uiContentObs);
getContentResolver().unregisterContentObserver(geonameResolverObs);
}
public class ClipboardCatcherObserver extends ContentObserver {
public ClipboardCatcherObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.d(TAG, "@onChange (ClipboardCatcherObserver)");
// set cursor to first item
Cursor cursor = getContentResolver().query(
clipboardCatcherContentUri, null, null, null,
ContextophelesConstants.CLIPBOARD_CATCHER_FIELD_TIMESTAMP + " DESC LIMIT 1");
if (cursor != null && cursor.moveToFirst()) {
String[] tokens = splitAndFilterContent(cursor.getString(cursor
.getColumnIndex(ContextophelesConstants.CLIPBOARD_CATCHER_FIELD_CLIPBOARDCONTENT)));
classifyAndSaveData(cursor.getLong(cursor.getColumnIndex(ContextophelesConstants.CLIPBOARD_CATCHER_FIELD_TIMESTAMP)),
clipboardCatcherContentUri.toString(), tokens);
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
public class NotificationCatcherObserver extends ContentObserver {
public NotificationCatcherObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.d(TAG, "@onChange (NotificationCatcherObserver)");
// set cursor to first item
Cursor cursor = getContentResolver().query(
notificationCatcherContentUri, null, null, null,
ContextophelesConstants.NOTIFICATION_CATCHER_FIELD_TIMESTAMP + " DESC LIMIT 1");
if (cursor != null && cursor.moveToFirst()) {
if (!isApplicationBlacklisted(cursor.getString(cursor
.getColumnIndex(ContextophelesConstants.NOTIFICATION_CATCHER_FIELD_APP_NAME)))) {
// get title and content_text
String[] tokens = splitAndFilterContent(cursor.getString(cursor
.getColumnIndex(ContextophelesConstants.NOTIFICATION_CATCHER_FIELD_TEXT)) + " " + cursor.getString(cursor
.getColumnIndex(ContextophelesConstants.NOTIFICATION_CATCHER_FIELD_TITLE)));
classifyAndSaveData(cursor.getLong(cursor.getColumnIndex(ContextophelesConstants.NOTIFICATION_CATCHER_FIELD_TIMESTAMP)),
notificationCatcherContentUri.toString(), tokens);
} else {
Log.d(TAG, "Notification from Application " + cursor.getString(cursor
.getColumnIndex(ContextophelesConstants.NOTIFICATION_CATCHER_FIELD_APP_NAME)) + " was ignored (Cause: Blacklist)");
}
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
public class SmsReceiverObserver extends ContentObserver {
public SmsReceiverObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
// set cursor to first item
Cursor cursor = getContentResolver().query(
smsReceiverContentUri, null, null, null,
ContextophelesConstants.SMS_RECEIVER_FIELD_TIMESTAMP + " DESC LIMIT 1");
if (cursor != null && cursor.moveToFirst()) {
String[] tokens = splitAndFilterContent(cursor.getString(cursor
.getColumnIndex(ContextophelesConstants.SMS_RECEIVER_FIELD_SMSContent)));
classifyAndSaveData(cursor.getLong(cursor.getColumnIndex(ContextophelesConstants.SMS_RECEIVER_FIELD_TIMESTAMP)),
smsReceiverContentUri.toString(), tokens);
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
public class OSMPoiResolverObserver extends ContentObserver {
public OSMPoiResolverObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.wtf(TAG, "@OSMPoiResolverObs");
// run only, if use of location is allowed
if (CommonSettings.getQueryUseOfLocation(getContentResolver())) {
// set cursor to first item
Cursor cursor = getContentResolver().query(
osmpoiResolverContentUri, null, null, null,
ContextophelesConstants.OSMPOI_RESOLVER_FIELD_TIMESTAMP + " DESC LIMIT 1");
if (cursor != null && cursor.moveToFirst()) {
// POIs come in packages of one, so we do not need to split and filter them, so we package each one in an array
String[] singleTokenArray = new String[]{cursor.getString(cursor
.getColumnIndex(ContextophelesConstants.OSMPOI_RESOLVER_FIELD_NAME))};
classifyAndSaveData(cursor.getLong(cursor.getColumnIndex(ContextophelesConstants.OSMPOI_RESOLVER_FIELD_TIMESTAMP)),
osmpoiResolverContentUri.toString(), singleTokenArray);
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
} else {
Log.d(TAG, "Termcollector ignores input, as useOfLocation is disabled.");
}
}
}
public class GeonameResolverObserver extends ContentObserver {
public GeonameResolverObserver(Handler handler) {
super(handler);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.wtf(TAG, "@GeonameResolverObserver");
// run only, if use of location is allowed
if (CommonSettings.getQueryUseOfLocation(getContentResolver())) {
// set cursor to first item
Cursor cursor = getContentResolver().query(
geonameResolverContentUri, null, null, null,
ContextophelesConstants.GEONAME_RESOLVER_FIELD_TIMESTAMP + " DESC LIMIT 1");
if (cursor != null && cursor.moveToFirst()) {
saveTermData(cursor.getLong(cursor.getColumnIndex(ContextophelesConstants.GEONAME_RESOLVER_FIELD_TIMESTAMP)), geonameResolverContentUri.toString(), cursor.getString(cursor
.getColumnIndex(ContextophelesConstants.GEONAME_RESOLVER_FIELD_NAME)));
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}else {
Log.d(TAG, "GeonameResolver ignores input, as useOfLocation is disabled.");
}
}
}
public class UIContentObserver extends ContentObserver {
long lastId;
public UIContentObserver(Handler handler) {
super(handler);
lastId = -1;
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Log.wtf(TAG, "@UIContentObs");
// set cursor to first item
Cursor cursor = getContentResolver().query(
uiContentContentUri, null, null, null,
ContextophelesConstants.UI_CONTENT_FIELD_TIMESTAMP + " DESC LIMIT 1");
if (cursor != null && cursor.moveToFirst()) {
if (!isApplicationBlacklisted(cursor.getString(cursor
.getColumnIndex(ContextophelesConstants.UI_CONTENT_FIELD_SOURCE_APP)))) {
if (lastId == cursor.getLong(cursor.getColumnIndex(ContextophelesConstants.UI_CONTENT_FIELD_ID))) {
return;
} else {
lastId = cursor.getLong(cursor.getColumnIndex(ContextophelesConstants.UI_CONTENT_FIELD_ID));
}
String[] tokens = splitAndFilterContent(cursor.getString(cursor
.getColumnIndex(ContextophelesConstants.UI_CONTENT_FIELD_TEXT)));
classifyAndSaveData(cursor.getLong(cursor.getColumnIndex(ContextophelesConstants.UI_CONTENT_FIELD_TIMESTAMP)),
uiContentContentUri.toString(), tokens);
} else {
Log.d(TAG, "UIContent from Application " + cursor.getString(cursor
.getColumnIndex(ContextophelesConstants.UI_CONTENT_FIELD_SOURCE_APP)) + " was ignored (Cause: Blacklist)");
}
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
private String[] splitAndReformulateContent(String content) {
Log.wtf(TAG, "Splitting Content: " + content);
String[] tokenArray = content.split("\\s+");
//remove all characters that are not A-Za-z
ArrayList<String> resultList = new ArrayList<String>();
String latex = "\\boxed{" + TextUtils.join("} \\boxed{", tokenArray) + "}";
int chunksize = 1000;
for(int i=0; i< latex.length(); i = i + chunksize){
Log.wtf(TAG, "Reformulating Contentlist: " + latex.substring(i, Math.min(i+chunksize, latex.length())));
}
for (int i = 0; i < tokenArray.length; i++) {
String token = tokenArray[i];
if (tokenIsAllowedNoun(token)) {
resultList.add(token);
//token does not end in a punctuation mark
if (!token.matches(".*[\\p{Punct}]")) {
// there is still another token
if (i + 1 < tokenArray.length) {
//and it is an allowed Noun or a commonConnector
if (tokenIsAllowedNoun(tokenArray[i + 1])) {
// Add the Combination of the two to the List
resultList.add(TextUtils.join(" ", new String[]{token, tokenArray[i + 1]}));
} else {
if (commonConnectors.isCommonConnector(tokenArray[i + 1])) {
// there is yet another token
if (i + 2 < tokenArray.length) {
if (tokenIsAllowedNoun(tokenArray[i + 2])) {
// Add the Combination of the three to the List
resultList.add(token + " " + tokenArray[i + 1] + " " + tokenArray[i + 2]);
}
}
}
}
}
// there are even two more tokens
if (i + 3 < tokenArray.length) {
//it is a common connector with a space
if (commonConnectors.isCommonConnector(tokenArray[i + 1] + " " + tokenArray[i + 2])) {
if (tokenIsAllowedNoun(tokenArray[i + 3])) {
resultList.add(token + " " + tokenArray[i + 1] + " " + tokenArray[i + 2] + " " + tokenArray[i + 3]);
}
}
//it is a common connector without a space
if (commonConnectors.isCommonConnector(tokenArray[i + 1] + tokenArray[i + 2])) {
if (tokenIsAllowedNoun(tokenArray[i + 3])) {
resultList.add(token + " " + tokenArray[i + 1] + tokenArray[i + 2] + " " + tokenArray[i + 3]);
}
}
}
}
}
}
return resultList.toArray(new String[resultList.size()]);
}
private ArrayList<String> sanitizeTokens(String[] tokens) {
ArrayList<String> filteredTokens = new ArrayList<String>();
for (String token : tokens) {
filteredTokens.add(token.replaceAll("[^A-Za-zÄÖÜäöüß\\-]", " "));
filteredTokens.add(token.replaceAll(sanitizingString, ""));
}
return filteredTokens;
}
private String[] splitAndFilterContent(String content) {
String[] contentTokens = splitAndReformulateContent(content);
//filter Stopwords, if set
if(CommonSettings.getTermCollectorApplyStopwords(getContentResolver())){
return stopWords.filteredArray(contentTokens);
} else {
return contentTokens;
}
}
private void classifyAndSaveData(long timestamp, String source, String[] contentTokens) {
//filter Lowercase words and words with less than 3 Characters
ArrayList<String> filteredTokens = sanitizeTokens(contentTokens);
//classify cities
ArrayList<String> cityTokens = new ArrayList<String>();
ArrayList<String> nonCityTokens = new ArrayList<String>();
ArrayList<String> tokensToCheck = new ArrayList<String>();
//defines, if cities are resolved sequential or all at once (WAY FASTER!)
boolean sequential = false;
// check if the token is a known city/geoname from the cache
// if the token is in the cache, get the value and enter it into cityTokens or nonCityTokens
// add it to tokensToCheck otherwise
for (String filteredToken : filteredTokens) {
if (isInCache(filteredToken)) {
if (isCityFromCache(filteredToken)) {
// Add City to both Lists, to use in What and When field
nonCityTokens.add(filteredToken);
cityTokens.add(filteredToken);
} else {
// Use it only in WhatField
nonCityTokens.add(filteredToken);
}
} else {
tokensToCheck.add(filteredToken);
}
}
if (!sequential) { //new, at once check
Set<String> cities = new HashSet<String>();
// Get Cities for filteredTokens
try {
Mingle mingle = new Mingle(getApplicationContext());
cities = mingle.geonames().areCities(tokensToCheck);
} catch (Exception e) {
// e.printStackTrace();
}
// Check, which tokens are in the cities list
for (String token : tokensToCheck) {
if (cities.contains(token)) {
Log.wtf(TAG, token + " is a city (At once)");
// Add City to both Lists, to use in What and When field
nonCityTokens.add(token);
cityTokens.add(token);
saveToCache(System.currentTimeMillis(), true, token);
} else {
nonCityTokens.add(token);
saveToCache(System.currentTimeMillis(), false, token);
Log.wtf(TAG, token + " is not a city (At once)");
}
}
} else { // OLD, sequential check
for (String token : filteredTokens) {
{
Log.wtf(TAG, "Dissolving " + token);
// dissolve them with mingle
Mingle mingle;
try {
mingle = new Mingle(getApplicationContext());
if (mingle.geonames().existsPopulatedPlaceWithName(token)) {
Log.wtf(TAG, token + " is a city (Sequential)");
nonCityTokens.add(token);
cityTokens.add(token);
saveToCache(System.currentTimeMillis(), true, token);
} else {
nonCityTokens.add(token);
saveToCache(System.currentTimeMillis(), false, token);
Log.wtf(TAG, token + " is not a city (Sequential)");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// Save Non-City-Tokens to Term-Database, increase timestamp by 1 everytime
int tokenIndex = 0;
for (String token : nonCityTokens) {
saveTermData(timestamp + tokenIndex, source, token);
tokenIndex++;
}
// Save City-Tokens to Geo-Database, increase timestamp by 1 everytime
tokenIndex = 0;
for (String token : cityTokens) {
saveGeoData(timestamp + tokenIndex, source, token);
tokenIndex++;
}
}
private void saveTermData(long timestamp, String source, String content) {
ContentValues rowData = new ContentValues();
rowData.put(TermCollectorTermData.DEVICE_ID, Aware.getSetting(
getContentResolver(), Aware_Preferences.DEVICE_ID));
rowData.put(TermCollectorTermData.TIMESTAMP, timestamp);
rowData.put(TermCollectorTermData.TERM_SOURCE, source);
rowData.put(TermCollectorTermData.TERM_CONTENT, content);
Log.d(TAG, "Saving " + rowData.toString());
getContentResolver().insert(TermCollectorTermData.CONTENT_URI, rowData);
}
private void saveGeoData(long timestamp, String source, String content) {
ContentValues rowData = new ContentValues();
rowData.put(TermCollectorGeoData.DEVICE_ID, Aware.getSetting(
getContentResolver(), Aware_Preferences.DEVICE_ID));
rowData.put(TermCollectorGeoData.TIMESTAMP, timestamp);
rowData.put(TermCollectorGeoData.TERM_SOURCE, source);
rowData.put(TermCollectorGeoData.TERM_CONTENT, content);
Log.d(TAG, "Saving " + rowData.toString());
getContentResolver().insert(TermCollectorGeoData.CONTENT_URI, rowData);
}
boolean isApplicationBlacklisted(String appName) {
return blacklistedApps.isBlacklistedApp(appName);
}
private boolean isInCache(String token) {
Cursor c = getContentResolver().query(TermCollector_Provider.TermCollectorGeoDataCache.CONTENT_URI, null, TermCollector_Provider.TermCollectorGeoDataCache.TERM_CONTENT + " = " + DatabaseUtils.sqlEscapeString(token), null, null);
boolean result = false;
if (c != null && c.moveToFirst()) {
result = c.getCount() > 0;
}
if (c != null && !c.isClosed()) {
c.close();
}
if (result) {
Log.d(TAG, "Cache hit " + token);
} else {
Log.d(TAG, "Cache miss " + token);
}
return result;
}
private boolean isCityFromCache(String token) {
Cursor c = getContentResolver().query(TermCollectorGeoDataCache.CONTENT_URI, null, TermCollectorGeoDataCache.TERM_CONTENT + " = " + DatabaseUtils.sqlEscapeString(token), null, "timestamp" + " DESC LIMIT 1");
boolean result = false;
if (c != null && c.moveToFirst()) {
result = c.getInt(c.getColumnIndex(TermCollectorGeoDataCache.IS_CITY)) > 0;
}
if (c != null && !c.isClosed()) {
c.close();
}
return result;
}
private void saveToCache(long timestamp, boolean isCity, String token) {
ContentValues rowData = new ContentValues();
rowData.put(TermCollectorGeoDataCache.TIMESTAMP, timestamp);
if (isCity) {
rowData.put(TermCollectorGeoDataCache.IS_CITY, 1);
} else {
rowData.put(TermCollectorGeoDataCache.IS_CITY, 0);
}
rowData.put(TermCollectorGeoDataCache.TERM_CONTENT, token);
Log.d(TAG, "Saving to Cache: " + rowData.toString());
getContentResolver().insert(TermCollectorGeoDataCache.CONTENT_URI, rowData);
}
//Checks, whether the given token does not break a set of rules, e.g. minlength or stopword
private boolean tokenIsAllowedNoun(String token) {
Log.wtf(TAG, "Testing for allowed noun: " + token);
int minLength = CommonSettings.getMinimalTermCollectorTokenLength(getContentResolver());
// Sanitize token temporarily:
token = token.replaceAll(sanitizingString, "");
boolean applyStopWords = CommonSettings.getTermCollectorApplyStopwords(getContentResolver());
// filter tokens shorter than minLength characters
if (token.length() >= minLength) {
//only allow Uppercase tokens, which have no more Uppercase characters (avoids strange CamelCase errors like PassauTown)
if (Character.isUpperCase(token.charAt(0)) &&
token.substring(1).equals(token.substring(1).toLowerCase())
) {
if(applyStopWords) {
if (stopWords.isStopWord(token)) {
Log.wtf(TAG, "Ignoring " + token + " as it is a stopword.");
return false;
} else {
return true;
}
} else {
// Stop Words are not applied
return true;
}
} else {
Log.wtf(TAG, "Ignoring " + token + " as it is not uppercase.");
return false;
}
} else {
Log.wtf(TAG, "Ignoring " + token + " as it is shorter than " + minLength + " characters.");
return false;
}
}
} |
package waffle.jetty;
import java.io.File;
import java.io.FileNotFoundException;
import org.apache.jasper.servlet.JspServlet;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
//import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.webapp.WebAppContext;
/**
* A simple embedded server that lets us run directly within Eclipse
*/
public class StartEmbeddedJetty
{
public static void main(String[] args) throws Exception
{
String path = "../waffle-demo-parent/waffle-filter";
File dir = new File( path );
if(!dir.exists()) {
throw new FileNotFoundException("Can not find webapp: "+dir.getAbsolutePath());
}
Server server = new Server(8080);
//SocketConnector connector = new SocketConnector();
// Set some timeout options to make debugging easier.
// connector.setMaxIdleTime(1000 * 60 * 60);
// connector.setSoLingerTime(-1);
// connector.setPort(8080);
// connector.setRequestHeaderSize(20*1044); // 20K for big request headers
// server.setConnectors(new Connector[] { connector });
WebAppContext context = new WebAppContext();
context.setServer(server);
context.setContextPath("/");
context.setWar(path);
// Try adding JSP
try {
ServletHolder jsp = context.addServlet(JspServlet.class, "*.jsp");
jsp.setInitParameter("classpath", context.getClassPath());
}
catch( Exception ex) {
System.err.println("Error adding JSP Support: "+ex.toString());
}
server.setHandler(context);
try {
System.out.println(">>> STARTING EMBEDDED JETTY SERVER, PRESS ANY KEY TO STOP");
server.start();
System.in.read();
System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
server.stop();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(100);
}
}
} |
/**
* Wrapper class to make com.oreilly.servlet.multipart.FilePart object
* available as a DataSource.
*
* We have to buffer the data stream since the MimePart class will try to
* read the stream several times (??) and we can't rewind the HttpRequest stream.
* <p>
* <b>Note</b>: The clients of this class must explictly call <code>dispose()</code>
* method to release temp files associated with this object.
* </p>
*
* @author George Lindholm, ITServices, UBC
* @version $Revision$
*/
package org.jasig.portal;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileOutputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import javax.activation.DataSource;
import com.oreilly.servlet.multipart.FilePart;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class MultipartDataSource implements DataSource {
private static final Log log = LogFactory.getLog(MultipartDataSource.class);
java.io.File tempfile;
ByteArrayOutputStream buff = null;
String contentType = null;
String filename = null;
String errorMessage = null;
boolean isAvailable = false;
public MultipartDataSource(FilePart filePart) throws IOException {
contentType = filePart.getContentType();
filename = filePart.getFileName();
try{
tempfile = java.io.File.createTempFile("uPdata",null);
tempfile.deleteOnExit();
OutputStream out = new BufferedOutputStream(new FileOutputStream(tempfile));
filePart.writeTo(out);
out.close();
}
catch(IOException ioe){
log.error("MultipartDataSource unable to create temp file", ioe);
if(tempfile!=null){
try{
tempfile.delete();
}
catch(Exception e){}
tempfile = null;
}
buff = new ByteArrayOutputStream();
filePart.writeTo(buff);
}
this.isAvailable = true;
}
public MultipartDataSource (String fileName, String errorMessage){
this.filename = fileName;
this.errorMessage = errorMessage;
this.isAvailable = false;
}
public boolean isAvailable () {
return this.isAvailable;
}
/**
* Releases tempfile associated with this object any memory they consume
* will be returned to the OS.
* @since uPortal 2.5. Prior to uPortal 2.5, tempfile deletion was a side effect
* of the finalizer.
*/
public void dispose() {
buff = null;
if (tempfile != null) {
boolean success = tempfile.delete();
if (! success) {
log.error("Unable to delete temp file [" + tempfile.getPath() + "]");
}
tempfile = null;
}
}
public InputStream getInputStream() throws IOException {
if (!isAvailable())
throw new IOException (this.getErrorMessage());
if(tempfile!=null){
return new BufferedInputStream(new FileInputStream(tempfile));
}
else{
return new ByteArrayInputStream(buff.toByteArray());
}
}
public OutputStream getOutputStream() throws IOException {
throw new IOException("getOutputStream() not implemented");
}
public String getContentType() {
return contentType;
}
public String getName() {
return filename;
}
public String getErrorMessage(){
return errorMessage;
}
public void setFileTypeMap(javax.activation.FileTypeMap p0) throws Exception {
throw new Exception("setFileTypeMap() not implemented");
}
} |
package org.jasig.portal;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;
import org.w3c.dom.Element;
import org.apache.xerces.dom.DocumentImpl;
import org.apache.xerces.parsers.DOMParser;
import java.io.StringWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Vector;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.jasig.portal.utils.DTDResolver;
import org.jasig.portal.services.LogService;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.jasig.portal.utils.DocumentFactory;
import org.jasig.portal.channels.CError;
import org.jasig.portal.security.IPerson;
import org.jasig.portal.security.ISecurityContext;
import org.jasig.portal.utils.ICounterStore;
import org.jasig.portal.utils.CounterStoreFactory;
import org.jasig.portal.utils.ResourceLoader;
/**
* SQL implementation for the 2.x relational database model
* @author George Lindholm
* @version $Revision$
*/
public class RDBMUserLayoutStore implements IUserLayoutStore {
//This class is instantiated ONCE so NO class variables can be used to keep state between calls
static int DEBUG = 0;
protected static final String channelPrefix = "n";
protected static final String folderPrefix = "s";
protected IChannelRegistryStore crsdb;
protected ICounterStore csdb;
/**
* LayoutStructure
* Encapsulate the layout structure
*/
protected final class LayoutStructure {
private class StructureParameter {
String name;
String value;
public StructureParameter(String name, String value) {
this.name = name;
this.value = value;
}
}
int structId;
int nextId;
int childId;
int chanId;
String name;
String type;
boolean hidden;
boolean unremovable;
boolean immutable;
ArrayList parameters;
public LayoutStructure(int structId, int nextId,int childId,int chanId, String hidden, String unremovable, String immutable) {
this.nextId = nextId;
this.childId = childId;
this.chanId = chanId;
this.structId = structId;
this.hidden = RDBMServices.dbFlag(hidden);
this.immutable = RDBMServices.dbFlag(immutable);
this.unremovable = RDBMServices.dbFlag(unremovable);
if (DEBUG > 1) {
System.err.println("New layout: id=" + structId + ", next=" + nextId + ", child=" + childId +", chan=" +chanId);
}
}
public void addFolderData(String name, String type) {
this.name = name;
this.type = type;
}
public boolean isChannel () {return chanId != 0;}
public void addParameter(String name, String value) {
if (parameters == null) {
parameters = new ArrayList(5);
}
parameters.add(new StructureParameter(name, value));
}
public int getNextId () {return nextId;}
public int getChildId () {return childId;}
public int getChanId () {return chanId;}
public Element getStructureDocument(DocumentImpl doc) throws Exception {
Element structure = null;
if (isChannel()) {
structure = crsdb.getChannelXML(chanId, doc, channelPrefix + structId);
if (structure == null) {
// Can't find channel
ChannelDefinition cd = new ChannelDefinition(chanId, "Missing channel");
structure = cd.getDocument(doc, channelPrefix + structId,
"This channel no longer exists. You should remove it from your layout.",
CError.CHANNEL_MISSING_EXCEPTION);
}
} else {
structure = doc.createElement("folder");
doc.putIdentifier(folderPrefix + structId, structure);
structure.setAttribute("ID", folderPrefix + structId);
structure.setAttribute("name", name);
structure.setAttribute("type", (type != null ? type : "regular"));
}
structure.setAttribute("hidden", (hidden ? "true" : "false"));
structure.setAttribute("immutable", (immutable ? "true" : "false"));
structure.setAttribute("unremovable", (unremovable ? "true" : "false"));
if (parameters != null) {
for (int i = 0; i < parameters.size(); i++) {
StructureParameter sp = (StructureParameter)parameters.get(i);
if (!isChannel()) { // Folder
structure.setAttribute(sp.name, sp.value);
} else { // Channel
NodeList nodeListParameters = structure.getElementsByTagName("parameter");
for (int j = 0; j < nodeListParameters.getLength(); j++) {
Element parmElement = (Element)nodeListParameters.item(j);
NamedNodeMap nm = parmElement.getAttributes();
String nodeName = nm.getNamedItem("name").getNodeValue();
if (nodeName.equals(sp.name)) {
Node override = nm.getNamedItem("override");
if (override != null && override.getNodeValue().equals("yes")) {
Node valueNode = nm.getNamedItem("value");
valueNode.setNodeValue(sp.value);
}
}
}
}
}
}
return structure;
}
}
/**
* put your documentation comment here
*/
public RDBMUserLayoutStore () throws Exception {
crsdb = ChannelRegistryStoreFactory.getChannelRegistryStoreImpl();
csdb = CounterStoreFactory.getCounterStoreImpl();
if (RDBMServices.supportsOuterJoins) {
if (RDBMServices.joinQuery instanceof RDBMServices.JdbcDb) {
RDBMServices.joinQuery.addQuery("layout",
"{oj UP_LAYOUT_STRUCT ULS LEFT OUTER JOIN UP_LAYOUT_PARAM USP ON ULS.STRUCT_ID = USP.STRUCT_ID} WHERE");
RDBMServices.joinQuery.addQuery("ss_struct", "{oj UP_SS_STRUCT USS LEFT OUTER JOIN UP_SS_STRUCT_PAR USP ON USS.SS_ID=USP.SS_ID} WHERE");
RDBMServices.joinQuery.addQuery("ss_theme", "{oj UP_SS_THEME UTS LEFT OUTER JOIN UP_SS_THEME_PARM UTP ON UTS.SS_ID=UTP.SS_ID} WHERE");
} else if (RDBMServices.joinQuery instanceof RDBMServices.PostgreSQLDb) {
RDBMServices.joinQuery.addQuery("layout",
"UP_LAYOUT_STRUCT ULS LEFT OUTER JOIN UP_LAYOUT_PARAM USP ON ULS.STRUCT_ID = USP.STRUCT_ID WHERE");
RDBMServices.joinQuery.addQuery("ss_struct", "UP_SS_STRUCT USS LEFT OUTER JOIN UP_SS_STRUCT_PAR USP ON USS.SS_ID=USP.SS_ID WHERE");
RDBMServices.joinQuery.addQuery("ss_theme", "UP_SS_THEME UTS LEFT OUTER JOIN UP_SS_THEME_PARM UTP ON UTS.SS_ID=UTP.SS_ID WHERE");
} else if (RDBMServices.joinQuery instanceof RDBMServices.OracleDb) {
RDBMServices.joinQuery.addQuery("layout",
"UP_LAYOUT_STRUCT ULS, UP_LAYOUT_PARAM USP WHERE ULS.STRUCT_ID = USP.STRUCT_ID(+) AND");
RDBMServices.joinQuery.addQuery("ss_struct", "UP_SS_STRUCT USS, UP_SS_STRUCT_PAR USP WHERE USS.SS_ID=USP.SS_ID(+) AND");
RDBMServices.joinQuery.addQuery("ss_theme", "UP_SS_THEME UTS, UP_SS_THEME_PARM UTP WHERE UTS.SS_ID=UTP.SS_ID(+) AND");
} else {
throw new Exception("Unknown database driver");
}
}
}
/**
* Registers a NEW structure stylesheet with the database.
* @param tsd Stylesheet description object
*/
public Integer addStructureStylesheetDescription (StructureStylesheetDescription ssd) throws Exception {
Connection con = RDBMServices.getConnection();
try {
// Set autocommit false for the connection
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
// we assume that this is a new stylesheet.
int id = csdb.getIncrementIntegerId("UP_SS_STRUCT");
ssd.setId(id);
String sQuery = "INSERT INTO UP_SS_STRUCT (SS_ID,SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT) VALUES ("
+ id + ",'" + ssd.getStylesheetName() + "','" + ssd.getStylesheetURI() + "','" + ssd.getStylesheetDescriptionURI()
+ "','" + ssd.getStylesheetWordDescription() + "')";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
// insert all stylesheet params
for (Enumeration e = ssd.getStylesheetParameterNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id
+ ",'" + pName + "','" + ssd.getStylesheetParameterDefaultValue(pName) + "','" + ssd.getStylesheetParameterWordDescription(pName)
+ "',1)";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
// insert all folder attributes
for (Enumeration e = ssd.getFolderAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id
+ ",'" + pName + "','" + ssd.getFolderAttributeDefaultValue(pName) + "','" + ssd.getFolderAttributeWordDescription(pName)
+ "',2)";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
// insert all channel attributes
for (Enumeration e = ssd.getChannelAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id
+ ",'" + pName + "','" + ssd.getChannelAttributeDefaultValue(pName) + "','" + ssd.getChannelAttributeWordDescription(pName)
+ "',3)";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
// Commit the transaction
RDBMServices.commit(con);
return new Integer(id);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Registers a NEW theme stylesheet with the database.
* @param tsd Stylesheet description object
*/
public Integer addThemeStylesheetDescription (ThemeStylesheetDescription tsd) throws Exception {
Connection con = RDBMServices.getConnection();
try {
// Set autocommit false for the connection
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
// we assume that this is a new stylesheet.
int id = csdb.getIncrementIntegerId("UP_SS_THEME");
tsd.setId(id);
String sQuery = "INSERT INTO UP_SS_THEME (SS_ID,SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT,STRUCT_SS_ID,SAMPLE_URI,SAMPLE_ICON_URI,MIME_TYPE,DEVICE_TYPE,SERIALIZER_NAME,UP_MODULE_CLASS) VALUES ("
+ id + ",'" + tsd.getStylesheetName() + "','" + tsd.getStylesheetURI() + "','" + tsd.getStylesheetDescriptionURI()
+ "','" + tsd.getStylesheetWordDescription() + "'," + tsd.getStructureStylesheetId() + ",'" + tsd.getSamplePictureURI()
+ "','" + tsd.getSampleIconURI() + "','" + tsd.getMimeType() + "','" + tsd.getDeviceType() + "','" + tsd.getSerializerName()
+ "','" + tsd.getCustomUserPreferencesManagerClass() + "')";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
// insert all stylesheet params
for (Enumeration e = tsd.getStylesheetParameterNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
sQuery = "INSERT INTO UP_SS_THEME_PARM (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id +
",'" + pName + "','" + tsd.getStylesheetParameterDefaultValue(pName) + "','" + tsd.getStylesheetParameterWordDescription(pName)
+ "',1)";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
// insert all channel attributes
for (Enumeration e = tsd.getChannelAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
sQuery = "INSERT INTO UP_SS_THEME_PARM (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + id +
",'" + pName + "','" + tsd.getChannelAttributeDefaultValue(pName) + "','" + tsd.getChannelAttributeWordDescription(pName)
+ "',3)";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
// Commit the transaction
RDBMServices.commit(con);
return new Integer(id);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Update the theme stylesheet description.
* @param stylesheetDescriptionURI
* @param stylesheetURI
* @param stylesheetId
* @return true if update succeeded, otherwise false
*/
public boolean updateThemeStylesheetDescription (String stylesheetDescriptionURI, String stylesheetURI, int stylesheetId) {
try {
DOMParser parser = new DOMParser();
parser.parse(new InputSource(ResourceLoader.getResourceAsStream(this.getClass(),stylesheetDescriptionURI)));
Document stylesheetDescriptionXML = parser.getDocument();
String ssName = this.getRootElementTextValue(stylesheetDescriptionXML, "parentStructureStylesheet");
// should thrown an exception
if (ssName == null)
return false;
// determine id of the parent structure stylesheet
Integer ssId = getStructureStylesheetId(ssName);
// stylesheet not found, should thrown an exception here
if (ssId == null)
return false;
ThemeStylesheetDescription sssd = new ThemeStylesheetDescription();
sssd.setId(stylesheetId);
sssd.setStructureStylesheetId(ssId.intValue());
String xmlStylesheetName = this.getName(stylesheetDescriptionXML);
String xmlStylesheetDescriptionText = this.getDescription(stylesheetDescriptionXML);
sssd.setStylesheetName(xmlStylesheetName);
sssd.setStylesheetURI(stylesheetURI);
sssd.setStylesheetDescriptionURI(stylesheetDescriptionURI);
sssd.setStylesheetWordDescription(xmlStylesheetDescriptionText);
sssd.setMimeType(this.getRootElementTextValue(stylesheetDescriptionXML, "mimeType"));
LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getThemeStylesheetDescription() : setting mimetype=\""
+ sssd.getMimeType() + "\"");
sssd.setSerializerName(this.getRootElementTextValue(stylesheetDescriptionXML, "serializer"));
LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getThemeStylesheetDescription() : setting serializerName=\""
+ sssd.getSerializerName() + "\"");
sssd.setCustomUserPreferencesManagerClass(this.getRootElementTextValue(stylesheetDescriptionXML, "userPreferencesModuleClass"));
sssd.setSamplePictureURI(this.getRootElementTextValue(stylesheetDescriptionXML, "samplePictureURI"));
sssd.setSampleIconURI(this.getRootElementTextValue(stylesheetDescriptionXML, "sampleIconURI"));
sssd.setDeviceType(this.getRootElementTextValue(stylesheetDescriptionXML, "deviceType"));
// populate parameter and attriute tables
this.populateParameterTable(stylesheetDescriptionXML, sssd);
this.populateChannelAttributeTable(stylesheetDescriptionXML, sssd);
updateThemeStylesheetDescription(sssd);
} catch (Exception e) {
LogService.instance().log(LogService.DEBUG, e);
return false;
}
return true;
}
/**
* Update the structure stylesheet description
* @param stylesheetDescriptionURI
* @param stylesheetURI
* @param stylesheetId
* @return true if update succeeded, otherwise false
*/
public boolean updateStructureStylesheetDescription (String stylesheetDescriptionURI, String stylesheetURI, int stylesheetId) {
try {
DOMParser parser = new DOMParser();
parser.parse(new InputSource(ResourceLoader.getResourceAsStream(this.getClass(),stylesheetDescriptionURI)));
Document stylesheetDescriptionXML = parser.getDocument();
StructureStylesheetDescription fssd = new StructureStylesheetDescription();
String xmlStylesheetName = this.getName(stylesheetDescriptionXML);
String xmlStylesheetDescriptionText = this.getDescription(stylesheetDescriptionXML);
fssd.setId(stylesheetId);
fssd.setStylesheetName(xmlStylesheetName);
fssd.setStylesheetURI(stylesheetURI);
fssd.setStylesheetDescriptionURI(stylesheetDescriptionURI);
fssd.setStylesheetWordDescription(xmlStylesheetDescriptionText);
// populate parameter and attriute tables
this.populateParameterTable(stylesheetDescriptionXML, fssd);
this.populateFolderAttributeTable(stylesheetDescriptionXML, fssd);
this.populateChannelAttributeTable(stylesheetDescriptionXML, fssd);
// now write out the database record
updateStructureStylesheetDescription(fssd);
} catch (Exception e) {
LogService.instance().log(LogService.DEBUG, e);
return false;
}
return true;
}
/**
* Add a structure stylesheet description
* @param stylesheetDescriptionURI
* @param stylesheetURI
* @return
*/
public Integer addStructureStylesheetDescription (String stylesheetDescriptionURI, String stylesheetURI) {
// need to read in the description file to obtain information such as name, word description and media list
try {
DOMParser parser = new DOMParser();
parser.parse(new InputSource(ResourceLoader.getResourceAsStream(this.getClass(),stylesheetDescriptionURI)));
Document stylesheetDescriptionXML = parser.getDocument();
StructureStylesheetDescription fssd = new StructureStylesheetDescription();
String xmlStylesheetName = this.getName(stylesheetDescriptionXML);
String xmlStylesheetDescriptionText = this.getDescription(stylesheetDescriptionXML);
fssd.setStylesheetName(xmlStylesheetName);
fssd.setStylesheetURI(stylesheetURI);
fssd.setStylesheetDescriptionURI(stylesheetDescriptionURI);
fssd.setStylesheetWordDescription(xmlStylesheetDescriptionText);
// populate parameter and attriute tables
this.populateParameterTable(stylesheetDescriptionXML, fssd);
this.populateFolderAttributeTable(stylesheetDescriptionXML, fssd);
this.populateChannelAttributeTable(stylesheetDescriptionXML, fssd);
// now write out the database record
// first the basic record
//UserLayoutStoreFactory.getUserLayoutStoreImpl().addStructureStylesheetDescription(xmlStylesheetName, stylesheetURI, stylesheetDescriptionURI, xmlStylesheetDescriptionText);
return addStructureStylesheetDescription(fssd);
} catch (Exception e) {
LogService.instance().log(LogService.DEBUG, e);
}
return null;
}
/**
* Add theme stylesheet description
* @param stylesheetDescriptionURI
* @param stylesheetURI
* @return
*/
public Integer addThemeStylesheetDescription (String stylesheetDescriptionURI, String stylesheetURI) {
// need to read iN the description file to obtain information such as name, word description and mime type list
try {
DOMParser parser = new DOMParser();
parser.parse(new InputSource(ResourceLoader.getResourceAsStream(this.getClass(),stylesheetDescriptionURI)));
Document stylesheetDescriptionXML = parser.getDocument();
LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::addThemeStylesheetDescription() : stylesheet name = "
+ this.getName(stylesheetDescriptionXML));
LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::addThemeStylesheetDescription() : stylesheet description = "
+ this.getDescription(stylesheetDescriptionXML));
String ssName = this.getRootElementTextValue(stylesheetDescriptionXML, "parentStructureStylesheet");
// should thrown an exception
if (ssName == null)
return null;
// determine id of the parent structure stylesheet
Integer ssId = getStructureStylesheetId(ssName);
// stylesheet not found, should thrown an exception here
if (ssId == null)
return null;
ThemeStylesheetDescription sssd = new ThemeStylesheetDescription();
sssd.setStructureStylesheetId(ssId.intValue());
String xmlStylesheetName = this.getName(stylesheetDescriptionXML);
String xmlStylesheetDescriptionText = this.getDescription(stylesheetDescriptionXML);
sssd.setStylesheetName(xmlStylesheetName);
sssd.setStylesheetURI(stylesheetURI);
sssd.setStylesheetDescriptionURI(stylesheetDescriptionURI);
sssd.setStylesheetWordDescription(xmlStylesheetDescriptionText);
sssd.setMimeType(this.getRootElementTextValue(stylesheetDescriptionXML, "mimeType"));
LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getThemeStylesheetDescription() : setting mimetype=\""
+ sssd.getMimeType() + "\"");
sssd.setSerializerName(this.getRootElementTextValue(stylesheetDescriptionXML, "serializer"));
LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getThemeStylesheetDescription() : setting serializerName=\""
+ sssd.getSerializerName() + "\"");
sssd.setCustomUserPreferencesManagerClass(this.getRootElementTextValue(stylesheetDescriptionXML, "userPreferencesModuleClass"));
sssd.setSamplePictureURI(this.getRootElementTextValue(stylesheetDescriptionXML, "samplePictureURI"));
sssd.setSampleIconURI(this.getRootElementTextValue(stylesheetDescriptionXML, "sampleIconURI"));
sssd.setDeviceType(this.getRootElementTextValue(stylesheetDescriptionXML, "deviceType"));
// populate parameter and attriute tables
this.populateParameterTable(stylesheetDescriptionXML, sssd);
this.populateChannelAttributeTable(stylesheetDescriptionXML, sssd);
return addThemeStylesheetDescription(sssd);
} catch (Exception e) {
LogService.instance().log(LogService.DEBUG, e);
}
return null;
}
/**
* Add a user profile
* @param person
* @param profile
* @return userProfile
* @exception Exception
*/
public UserProfile addUserProfile (IPerson person, UserProfile profile) throws Exception {
int userId = person.getID();
// generate an id for this profile
Connection con = RDBMServices.getConnection();
try {
int id = csdb.getIncrementIntegerId("UP_USER_PROFILE");
profile.setProfileId(id);
Statement stmt = con.createStatement();
try {
String sQuery = "INSERT INTO UP_USER_PROFILE (USER_ID,PROFILE_ID,PROFILE_NAME,STRUCTURE_SS_ID,THEME_SS_ID,DESCRIPTION) VALUES ("
+ userId + "," + profile.getProfileId() + ",'" + profile.getProfileName() + "'," + profile.getStructureStylesheetId()
+ "," + profile.getThemeStylesheetId() + ",'" + profile.getProfileDescription() + "')";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addUserProfile(): " + sQuery);
stmt.executeUpdate(sQuery);
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return profile;
}
/**
* Checks if a channel has been approved
* @param approved Date
* @return boolean Channel is approved
*/
protected static boolean channelApproved(java.sql.Timestamp approvedDate) {
java.sql.Timestamp rightNow = new java.sql.Timestamp(System.currentTimeMillis());
return (approvedDate != null && rightNow.after(approvedDate));
}
/**
* Create a layout
* @param doc
* @param stmt
* @param root
* @param userId
* @param profileId
* @param layoutId
* @param structId
* @param ap
* @exception java.sql.SQLException
*/
protected final void createLayout (HashMap layoutStructure, DocumentImpl doc,
Element root, int structId) throws java.sql.SQLException, Exception {
while (structId != 0) {
if (DEBUG>1) {
System.err.println("CreateLayout(" + structId + ")");
}
LayoutStructure ls = (LayoutStructure) layoutStructure.get(new Integer(structId));
Element structure = ls.getStructureDocument(doc);
root.appendChild(structure);
if (!ls.isChannel()) { // Folder
createLayout(layoutStructure, doc, structure, ls.getChildId());
}
structId = ls.getNextId();
}
}
/**
* convert true/false into Y/N for database
* @param value to check
* @result boolean
*/
protected static final boolean xmlBool (String value) {
return (value != null && value.equals("true") ? true : false);
}
/**
* put your documentation comment here
* @param person
* @param profileId
* @exception Exception
*/
public void deleteUserProfile (IPerson person, int profileId) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_USER_PROFILE WHERE USER_ID=" + userId + " AND PROFILE_ID=" + Integer.toString(profileId);
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::deleteUserProfile() : " + sQuery);
stmt.executeUpdate(sQuery);
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Dump a document tree structure on stdout
* @param node
* @param indent
*/
public static final void dumpDoc (Node node, String indent) {
if (node == null) {
return;
}
if (node instanceof Element) {
System.err.print(indent + "element: tag=" + ((Element)node).getTagName() + " ");
}
else if (node instanceof Document) {
System.err.print("document:");
}
else {
System.err.print(indent + "node:");
}
System.err.println("name=" + node.getNodeName() + " value=" + node.getNodeValue());
NamedNodeMap nm = node.getAttributes();
if (nm != null) {
for (int i = 0; i < nm.getLength(); i++) {
System.err.println(indent + " " + nm.item(i).getNodeName() + ": '" + nm.item(i).getNodeValue() + "'");
}
System.err.println(indent + "
}
if (node.hasChildNodes()) {
dumpDoc(node.getFirstChild(), indent + " ");
}
dumpDoc(node.getNextSibling(), indent);
}
/**
*
* CoreStyleSheet
*
*/
public Hashtable getMimeTypeList () throws Exception {
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT A.MIME_TYPE, A.MIME_TYPE_DESCRIPTION FROM UP_MIME_TYPE A, UP_SS_MAP B WHERE B.MIME_TYPE=A.MIME_TYPE";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getMimeTypeList() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
Hashtable list = new Hashtable();
while (rs.next()) {
list.put(rs.getString("MIME_TYPE"), rs.getString("MIME_TYPE_DESCRIPTION"));
}
return list;
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Return the next available channel structure id for a user
* @parameter userId
* @result
*/
public String generateNewChannelSubscribeId (IPerson person) throws Exception {
return getNextStructId(person, channelPrefix);
}
/**
* Return the next available folder structure id for a user
* @param person
* @return
* @exception Exception
*/
public String generateNewFolderId (IPerson person) throws Exception {
return getNextStructId(person, folderPrefix);
}
/**
* Return the next available structure id for a user
* @param person
* @param prefix
* @return next free structure ID
* @exception Exception
*/
protected String getNextStructId (IPerson person, String prefix) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID=" + userId;
for (int i = 0; i < 25; i++) {
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getNextStructId(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
int currentStructId;
try {
rs.next();
currentStructId = rs.getInt(1);
} finally {
rs.close();
}
int nextStructId = currentStructId + 1;
try {
String sUpdate = "UPDATE UP_USER SET NEXT_STRUCT_ID=" + nextStructId + " WHERE USER_ID=" + userId + " AND NEXT_STRUCT_ID="
+ currentStructId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getNextStructId(): " + sUpdate);
stmt.executeUpdate(sUpdate);
return prefix + nextStructId;
} catch (SQLException sqle) {
// Assume a concurrent update. Try again after some random amount of milliseconds.
Thread.sleep(java.lang.Math.round(java.lang.Math.random()* 3 * 1000)); // Retry in up to 3 seconds
}
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
throw new SQLException("Unable to generate a new structure id for user " + userId);
}
/**
* Return the Structure ID tag
* @param structId
* @param chanId
* @return ID tag
*/
protected String getStructId(int structId, int chanId) {
if (chanId == 0) {
return folderPrefix + structId;
} else {
return channelPrefix + structId;
}
}
/**
* Obtain structure stylesheet description object for a given structure stylesheet id
* @para id id of the structure stylesheet
* @return structure stylesheet description
*/
public StructureStylesheetDescription getStructureStylesheetDescription (int stylesheetId) throws Exception {
StructureStylesheetDescription ssd = null;
Connection con = RDBMServices.getConnection();
Statement stmt = con.createStatement();
try {
int dbOffset = 0;
String sQuery = "SELECT SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT";
if (RDBMServices.supportsOuterJoins) {
sQuery += ",TYPE,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT FROM " + RDBMServices.joinQuery.getQuery("ss_struct");
dbOffset = 4;
} else {
sQuery += " FROM UP_SS_STRUCT USS WHERE";
}
sQuery += " USS.SS_ID=" + stylesheetId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
if (rs.next()) {
ssd = new StructureStylesheetDescription();
ssd.setId(stylesheetId);
ssd.setStylesheetName(rs.getString(1));
ssd.setStylesheetURI(rs.getString(2));
ssd.setStylesheetDescriptionURI(rs.getString(3));
ssd.setStylesheetWordDescription(rs.getString(4));
}
if (!RDBMServices.supportsOuterJoins) {
rs.close();
// retrieve stylesheet params and attributes
sQuery = "SELECT TYPE,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription(): " + sQuery);
rs = stmt.executeQuery(sQuery);
}
while (true) {
if (!RDBMServices.supportsOuterJoins && !rs.next()) {
break;
}
int type = rs.getInt(dbOffset + 1);
if (rs.wasNull()){
break;
}
if (type == 1) {
// param
ssd.addStylesheetParameter(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4));
}
else if (type == 2) {
// folder attribute
ssd.addFolderAttribute(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4));
}
else if (type == 3) {
// channel attribute
ssd.addChannelAttribute(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4));
}
else {
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription() : encountered param of unknown type! (stylesheetId="
+ stylesheetId + " param_name=\"" + rs.getString(dbOffset + 2) + "\" type=" + rs.getInt(dbOffset + 1) + ").");
}
if (RDBMServices.supportsOuterJoins && !rs.next()) {
break;
}
}
} finally {
rs.close();
}
} finally {
stmt.close();
RDBMServices.releaseConnection(con);
}
return ssd;
}
/**
* Obtain ID for known structure stylesheet name
* @param ssName name of the structure stylesheet
* @return id or null if no stylesheet matches the name given.
*/
public Integer getStructureStylesheetId (String ssName) throws Exception {
Connection con = RDBMServices.getConnection();
try {
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT SS_ID FROM UP_SS_STRUCT WHERE SS_NAME='" + ssName + "'";
ResultSet rs = stmt.executeQuery(sQuery);
if (rs.next()) {
int id = rs.getInt("SS_ID");
if (rs.wasNull()) {
id = 0;
}
return new Integer(id);
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return null;
}
/**
* Obtain a list of structure stylesheet descriptions that have stylesheets for a given
* mime type.
* @param mimeType
* @return a mapping from stylesheet names to structure stylesheet description objects
*/
public Hashtable getStructureStylesheetList (String mimeType) throws Exception {
Connection con = RDBMServices.getConnection();
Hashtable list = new Hashtable();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT A.SS_ID FROM UP_SS_STRUCT A, UP_SS_THEME B WHERE B.MIME_TYPE='" + mimeType + "' AND B.STRUCT_SS_ID=A.SS_ID";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheeInfotList() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
StructureStylesheetDescription ssd = getStructureStylesheetDescription(rs.getInt("SS_ID"));
if (ssd != null)
list.put(new Integer(ssd.getId()), ssd);
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return list;
}
/**
* Obtain a list of strcture stylesheet descriptions registered on the system
* @return a <code>Hashtable</code> mapping stylesheet id (<code>Integer</code> objects) to {@link StructureStylesheetDescription} objects
* @exception Exception
*/
public Hashtable getStructureStylesheetList() throws Exception {
Connection con = RDBMServices.getConnection();
Hashtable list = new Hashtable();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT SS_ID FROM UP_SS_STRUCT";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheeList() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
StructureStylesheetDescription ssd = getStructureStylesheetDescription(rs.getInt("SS_ID"));
if (ssd != null)
list.put(new Integer(ssd.getId()), ssd);
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return list;
}
/**
* put your documentation comment here
* @param person
* @param profileId
* @param stylesheetId
* @return
* @exception Exception
*/
public StructureStylesheetUserPreferences getStructureStylesheetUserPreferences (IPerson person, int profileId, int stylesheetId) throws Exception {
int userId = person.getID();
StructureStylesheetUserPreferences ssup;
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
// get stylesheet description
StructureStylesheetDescription ssd = getStructureStylesheetDescription(stylesheetId);
// get user defined defaults
String subSelectString = "SELECT LAYOUT_ID FROM UP_USER_PROFILE WHERE USER_ID=" + userId + " AND PROFILE_ID=" +
profileId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + subSelectString);
int layoutId;
ResultSet rs = stmt.executeQuery(subSelectString);
try {
rs.next();
layoutId = rs.getInt(1);
if (rs.wasNull()) {
layoutId = 0;
}
} finally {
rs.close();
}
if (layoutId == 0) { // First time, grab the default layout for this user
String sQuery = "SELECT USER_DFLT_USR_ID FROM UP_USER WHERE USER_ID=" + userId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sQuery);
rs = stmt.executeQuery(sQuery);
try {
rs.next();
userId = rs.getInt(1);
} finally {
rs.close();
}
}
String sQuery = "SELECT PARAM_NAME, PARAM_VAL FROM UP_SS_USER_PARM WHERE USER_ID=" + userId + " AND PROFILE_ID="
+ profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences(): " + sQuery);
rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
// stylesheet param
ssd.setStylesheetParameterDefaultValue(rs.getString(1), rs.getString(2));
//LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : read stylesheet param "+rs.getString("PARAM_NAME")+"=\""+rs.getString("PARAM_VAL")+"\"");
}
} finally {
rs.close();
}
ssup = new StructureStylesheetUserPreferences();
ssup.setStylesheetId(stylesheetId);
// fill stylesheet description with defaults
for (Enumeration e = ssd.getStylesheetParameterNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
ssup.putParameterValue(pName, ssd.getStylesheetParameterDefaultValue(pName));
}
for (Enumeration e = ssd.getChannelAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
ssup.addChannelAttribute(pName, ssd.getChannelAttributeDefaultValue(pName));
}
for (Enumeration e = ssd.getFolderAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
ssup.addFolderAttribute(pName, ssd.getFolderAttributeDefaultValue(pName));
}
// get user preferences
sQuery = "SELECT PARAM_NAME, PARAM_VAL, PARAM_TYPE, ULS.STRUCT_ID, CHAN_ID FROM UP_SS_USER_ATTS UUSA, UP_LAYOUT_STRUCT ULS WHERE UUSA.USER_ID=" + userId + " AND PROFILE_ID="
+ profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND UUSA.STRUCT_ID = ULS.STRUCT_ID AND UUSA.USER_ID = ULS.USER_ID";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences(): " + sQuery);
rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
int param_type = rs.getInt(3);
int structId = rs.getInt(4);
if (rs.wasNull()) {
structId = 0;
}
int chanId = rs.getInt(5);
if (rs.wasNull()) {
chanId = 0;
}
if (param_type == 1) {
// stylesheet param
LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : stylesheet global params should be specified in the user defaults table ! UP_SS_USER_ATTS is corrupt. (userId="
+ Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId)
+ ", param_name=\"" + rs.getString(1) + "\", param_type=" + Integer.toString(param_type));
}
else if (param_type == 2) {
// folder attribute
ssup.setFolderAttributeValue(getStructId(structId,chanId), rs.getString(1), rs.getString(2));
//LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : read folder attribute "+rs.getString("PARAM_NAME")+"("+rs.getString("STRUCT_ID")+")=\""+rs.getString("PARAM_VAL")+"\"");
}
else if (param_type == 3) {
// channel attribute
ssup.setChannelAttributeValue(getStructId(structId,chanId), rs.getString(1), rs.getString(2));
//LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : read channel attribute "+rs.getString("PARAM_NAME")+"("+rs.getString("STRUCT_ID")+")=\""+rs.getString("PARAM_VAL")+"\"");
}
else {
// unknown param type
LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getStructureStylesheetUserPreferences() : unknown param type encountered! DB corrupt. (userId="
+ Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId)
+ ", param_name=\"" + rs.getString(1) + "\", param_type=" + Integer.toString(param_type));
}
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return ssup;
}
/**
* Obtain theme stylesheet description object for a given theme stylesheet id
* @para id id of the theme stylesheet
* @return theme stylesheet description
*/
public ThemeStylesheetDescription getThemeStylesheetDescription (int stylesheetId) throws Exception {
ThemeStylesheetDescription tsd = null;
Connection con = RDBMServices.getConnection();
Statement stmt = con.createStatement();
try {
int dbOffset = 0;
String sQuery = "SELECT SS_NAME,SS_URI,SS_DESCRIPTION_URI,SS_DESCRIPTION_TEXT,STRUCT_SS_ID,SAMPLE_ICON_URI,SAMPLE_URI,MIME_TYPE,DEVICE_TYPE,SERIALIZER_NAME,UP_MODULE_CLASS";
if (RDBMServices.supportsOuterJoins) {
sQuery += ",TYPE,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT FROM " + RDBMServices.joinQuery.getQuery("ss_theme");
dbOffset = 11;
} else {
sQuery += " FROM UP_SS_THEME UTS WHERE";
}
sQuery += " UTS.SS_ID=" + stylesheetId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
if (rs.next()) {
tsd = new ThemeStylesheetDescription();
tsd.setId(stylesheetId);
tsd.setStylesheetName(rs.getString(1));
tsd.setStylesheetURI(rs.getString(2));
tsd.setStylesheetDescriptionURI(rs.getString(3));
tsd.setStylesheetWordDescription(rs.getString(4));
int ssId = rs.getInt(5);
if (rs.wasNull()) {
ssId = 0;
}
tsd.setStructureStylesheetId(ssId);
tsd.setSampleIconURI(rs.getString(6));
tsd.setSamplePictureURI(rs.getString(7));
tsd.setMimeType(rs.getString(8));
tsd.setDeviceType(rs.getString(9));
tsd.setSerializerName(rs.getString(10));
tsd.setCustomUserPreferencesManagerClass(rs.getString(11));
}
if (!RDBMServices.supportsOuterJoins) {
rs.close();
// retrieve stylesheet params and attributes
sQuery = "SELECT TYPE,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription(): " + sQuery);
rs = stmt.executeQuery(sQuery);
}
while (true) {
if (!RDBMServices.supportsOuterJoins && !rs.next()) {
break;
}
int type = rs.getInt(dbOffset + 1);
if (rs.wasNull()) {
break;
}
if (type == 1) {
// param
tsd.addStylesheetParameter(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4));
}
else if (type == 3) {
// channel attribute
tsd.addChannelAttribute(rs.getString(dbOffset + 2), rs.getString(dbOffset + 3), rs.getString(dbOffset + 4));
}
else if (type == 2) {
// folder attributes are not allowed here
LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered a folder attribute specified for a theme stylesheet ! Corrupted DB entry. (stylesheetId="
+ stylesheetId + " param_name=\"" + rs.getString(dbOffset + 2) + "\" type=" + type + ").");
}
else {
LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered param of unknown type! (stylesheetId="
+ stylesheetId + " param_name=\"" + rs.getString(dbOffset + 2) + "\" type=" + type + ").");
}
if (RDBMServices.supportsOuterJoins && !rs.next()) {
break;
}
}
} finally {
rs.close();
}
} finally {
stmt.close();
RDBMServices.releaseConnection(con);
}
return tsd;
}
/**
* Obtain ID for known theme stylesheet name
* @param ssName name of the theme stylesheet
* @return id or null if no theme matches the name given.
*/
public Integer getThemeStylesheetId (String tsName) throws Exception {
Integer id = null;
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT SS_ID FROM UP_SS_THEME WHERE SS_NAME='" + tsName + "'";
ResultSet rs = stmt.executeQuery(sQuery);
if (rs.next()) {
id = new Integer(rs.getInt("SS_ID"));
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return id;
}
/**
* Obtain a list of theme stylesheet descriptions for a given structure stylesheet
* @param structureStylesheetName
* @return a map of stylesheet names to theme stylesheet description objects
* @exception Exception
*/
public Hashtable getThemeStylesheetList (int structureStylesheetId) throws Exception {
Connection con = RDBMServices.getConnection();
Hashtable list = new Hashtable();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT SS_ID FROM UP_SS_THEME WHERE STRUCT_SS_ID=" + structureStylesheetId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetList() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
ThemeStylesheetDescription tsd = getThemeStylesheetDescription(rs.getInt("SS_ID"));
if (tsd != null)
list.put(new Integer(tsd.getId()), tsd);
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return list;
}
/**
* Obtain a list of theme stylesheet descriptions registered on the system
* @return a <code>Hashtable</code> mapping stylesheet id (<code>Integer</code> objects) to {@link ThemeStylesheetDescription} objects
* @exception Exception
*/
public Hashtable getThemeStylesheetList() throws Exception {
Connection con = RDBMServices.getConnection();
Hashtable list = new Hashtable();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT SS_ID FROM UP_SS_THEME";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetList() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
ThemeStylesheetDescription tsd = getThemeStylesheetDescription(rs.getInt("SS_ID"));
if (tsd != null)
list.put(new Integer(tsd.getId()), tsd);
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return list;
}
/**
* put your documentation comment here
* @param person
* @param profileId
* @param stylesheetId
* @return
* @exception Exception
*/
public ThemeStylesheetUserPreferences getThemeStylesheetUserPreferences (IPerson person, int profileId, int stylesheetId) throws Exception {
int userId = person.getID();
ThemeStylesheetUserPreferences tsup;
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
// get stylesheet description
ThemeStylesheetDescription tsd = getThemeStylesheetDescription(stylesheetId);
// get user defined defaults
String sQuery = "SELECT PARAM_NAME, PARAM_VAL FROM UP_SS_USER_PARM WHERE USER_ID=" + userId + " AND PROFILE_ID="
+ profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
// stylesheet param
tsd.setStylesheetParameterDefaultValue(rs.getString(1), rs.getString(2));
// LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : read stylesheet param "+rs.getString("PARAM_NAME")+"=\""+rs.getString("PARAM_VAL")+"\"");
}
} finally {
rs.close();
}
tsup = new ThemeStylesheetUserPreferences();
tsup.setStylesheetId(stylesheetId);
// fill stylesheet description with defaults
for (Enumeration e = tsd.getStylesheetParameterNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
tsup.putParameterValue(pName, tsd.getStylesheetParameterDefaultValue(pName));
}
for (Enumeration e = tsd.getChannelAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
tsup.addChannelAttribute(pName, tsd.getChannelAttributeDefaultValue(pName));
}
// get user preferences
sQuery = "SELECT PARAM_TYPE, PARAM_NAME, PARAM_VAL, ULS.STRUCT_ID, CHAN_ID FROM UP_SS_USER_ATTS UUSA, UP_LAYOUT_STRUCT ULS WHERE UUSA.USER_ID=" + userId + " AND PROFILE_ID="
+ profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND UUSA.STRUCT_ID = ULS.STRUCT_ID AND UUSA.USER_ID = ULS.USER_ID";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences(): " + sQuery);
rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
int param_type = rs.getInt(1);
if (rs.wasNull()) {
param_type = 0;
}
int structId = rs.getInt(4);
if (rs.wasNull()) {
structId = 0;
}
int chanId = rs.getInt(5);
if (rs.wasNull()) {
chanId = 0;
}
if (param_type == 1) {
// stylesheet param
LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : stylesheet global params should be specified in the user defaults table ! UP_SS_USER_ATTS is corrupt. (userId="
+ Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId)
+ ", param_name=\"" + rs.getString(2) + "\", param_type=" + Integer.toString(param_type));
}
else if (param_type == 2) {
// folder attribute
LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : folder attribute specified for the theme stylesheet! UP_SS_USER_ATTS corrupt. (userId="
+ Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId)
+ ", param_name=\"" + rs.getString(2) + "\", param_type=" + Integer.toString(param_type));
}
else if (param_type == 3) {
// channel attribute
tsup.setChannelAttributeValue(getStructId(structId,chanId), rs.getString(2), rs.getString(3));
//LogService.instance().log(LogService.DEBUG,"RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : read folder attribute "+rs.getString("PARAM_NAME")+"("+rs.getString("STRUCT_ID")+")=\""+rs.getString("PARAM_VAL")+"\"");
}
else {
// unknown param type
LogService.instance().log(LogService.ERROR, "RDBMUserLayoutStore::getThemeStylesheetUserPreferences() : unknown param type encountered! DB corrupt. (userId="
+ Integer.toString(userId) + ", profileId=" + Integer.toString(profileId) + ", stylesheetId=" + Integer.toString(stylesheetId)
+ ", param_name=\"" + rs.getString(2) + "\", param_type=" + Integer.toString(param_type));
}
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return tsup;
}
// private helper modules that retreive information from the DOM structure of the description files
private String getName (Document descr) {
NodeList names = descr.getElementsByTagName("name");
Node name = null;
for (int i = names.getLength() - 1; i >= 0; i
name = names.item(i);
if (name.getParentNode().getLocalName().equals("stylesheetdescription"))
break;
else
name = null;
}
if (name != null) {
return this.getTextChildNodeValue(name);
;
}
else {
LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getName() : no \"name\" element was found under the \"stylesheetdescription\" node!");
return null;
}
}
/**
* put your documentation comment here
* @param descr
* @param elementName
* @return
*/
private String getRootElementTextValue (Document descr, String elementName) {
NodeList names = descr.getElementsByTagName(elementName);
Node name = null;
for (int i = names.getLength() - 1; i >= 0; i
name = names.item(i);
if (name.getParentNode().getLocalName().equals("stylesheetdescription"))
break;
else
name = null;
}
if (name != null) {
return this.getTextChildNodeValue(name);
;
}
else {
LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getRootElementTextValue() : no \"" + elementName + "\" element was found under the \"stylesheetdescription\" node!");
return null;
}
}
/**
* put your documentation comment here
* @param descr
* @return
*/
private String getDescription (Document descr) {
NodeList descriptions = descr.getElementsByTagName("description");
Node description = null;
for (int i = descriptions.getLength() - 1; i >= 0; i
description = descriptions.item(i);
if (description.getParentNode().getLocalName().equals("stylesheetdescription"))
break;
else
description = null;
}
if (description != null) {
return this.getTextChildNodeValue(description);
}
else {
LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::getName() : no \"description\" element was found under the \"stylesheetdescription\" node!");
return null;
}
}
/**
* put your documentation comment here
* @param descr
* @param csd
*/
private void populateParameterTable (Document descr, CoreStylesheetDescription csd) {
NodeList parametersNodes = descr.getElementsByTagName("parameters");
Node parametersNode = null;
for (int i = parametersNodes.getLength() - 1; i >= 0; i
parametersNode = parametersNodes.item(i);
if (parametersNode.getParentNode().getLocalName().equals("stylesheetdescription"))
break;
else
parametersNode = null;
}
if (parametersNode != null) {
NodeList children = parametersNode.getChildNodes();
for (int i = children.getLength() - 1; i >= 0; i
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE && child.getLocalName().equals("parameter")) {
Element parameter = (Element)children.item(i);
// process a <parameter> node
String name = parameter.getAttribute("name");
String description = null;
String defaultvalue = null;
NodeList pchildren = parameter.getChildNodes();
for (int j = pchildren.getLength() - 1; j >= 0; j
Node pchild = pchildren.item(j);
if (pchild.getNodeType() == Node.ELEMENT_NODE) {
if (pchild.getLocalName().equals("defaultvalue")) {
defaultvalue = this.getTextChildNodeValue(pchild);
}
else if (pchild.getLocalName().equals("description")) {
description = this.getTextChildNodeValue(pchild);
}
}
}
LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::populateParameterTable() : adding a stylesheet parameter : (\""
+ name + "\",\"" + defaultvalue + "\",\"" + description + "\")");
csd.addStylesheetParameter(name, defaultvalue, description);
}
}
}
}
/**
* put your documentation comment here
* @param descr
* @param cxsd
*/
private void populateFolderAttributeTable (Document descr, StructureStylesheetDescription cxsd) {
NodeList parametersNodes = descr.getElementsByTagName("parameters");
NodeList folderattributesNodes = descr.getElementsByTagName("folderattributes");
Node folderattributesNode = null;
for (int i = folderattributesNodes.getLength() - 1; i >= 0; i
folderattributesNode = folderattributesNodes.item(i);
if (folderattributesNode.getParentNode().getLocalName().equals("stylesheetdescription"))
break;
else
folderattributesNode = null;
}
if (folderattributesNode != null) {
NodeList children = folderattributesNode.getChildNodes();
for (int i = children.getLength() - 1; i >= 0; i
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE && child.getLocalName().equals("attribute")) {
Element attribute = (Element)children.item(i);
// process a <attribute> node
String name = attribute.getAttribute("name");
String description = null;
String defaultvalue = null;
NodeList pchildren = attribute.getChildNodes();
for (int j = pchildren.getLength() - 1; j >= 0; j
Node pchild = pchildren.item(j);
if (pchild.getNodeType() == Node.ELEMENT_NODE) {
if (pchild.getLocalName().equals("defaultvalue")) {
defaultvalue = this.getTextChildNodeValue(pchild);
}
else if (pchild.getLocalName().equals("description")) {
description = this.getTextChildNodeValue(pchild);
}
}
}
LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::populateFolderAttributeTable() : adding a stylesheet folder attribute : (\""
+ name + "\",\"" + defaultvalue + "\",\"" + description + "\")");
cxsd.addFolderAttribute(name, defaultvalue, description);
}
}
}
}
/**
* put your documentation comment here
* @param descr
* @param cxsd
*/
private void populateChannelAttributeTable (Document descr, CoreXSLTStylesheetDescription cxsd) {
NodeList channelattributesNodes = descr.getElementsByTagName("channelattributes");
Node channelattributesNode = null;
for (int i = channelattributesNodes.getLength() - 1; i >= 0; i
channelattributesNode = channelattributesNodes.item(i);
if (channelattributesNode.getParentNode().getLocalName().equals("stylesheetdescription"))
break;
else
channelattributesNode = null;
}
if (channelattributesNode != null) {
NodeList children = channelattributesNode.getChildNodes();
for (int i = children.getLength() - 1; i >= 0; i
Node child = children.item(i);
if (child.getNodeType() == Node.ELEMENT_NODE && child.getLocalName().equals("attribute")) {
Element attribute = (Element)children.item(i);
// process a <attribute> node
String name = attribute.getAttribute("name");
String description = null;
String defaultvalue = null;
NodeList pchildren = attribute.getChildNodes();
for (int j = pchildren.getLength() - 1; j >= 0; j
Node pchild = pchildren.item(j);
if (pchild.getNodeType() == Node.ELEMENT_NODE) {
if (pchild.getLocalName().equals("defaultvalue")) {
defaultvalue = this.getTextChildNodeValue(pchild);
}
else if (pchild.getLocalName().equals("description")) {
description = this.getTextChildNodeValue(pchild);
}
}
}
LogService.instance().log(LogService.DEBUG, "RDBMCoreStylesheetDescriptionStore::populateChannelAttributeTable() : adding a stylesheet channel attribute : (\""
+ name + "\",\"" + defaultvalue + "\",\"" + description + "\")");
cxsd.addChannelAttribute(name, defaultvalue, description);
}
}
}
}
/**
* put your documentation comment here
* @param descr
* @param elementName
* @return
*/
private Vector getVectorOfSimpleTextElementValues (Document descr, String elementName) {
Vector v = new Vector();
// find "stylesheetdescription" node, take the first one
Element stylesheetdescriptionElement = (Element)(descr.getElementsByTagName("stylesheetdescription")).item(0);
if (stylesheetdescriptionElement == null) {
LogService.instance().log(LogService.ERROR, "Could not obtain <stylesheetdescription> element");
return null;
}
NodeList elements = stylesheetdescriptionElement.getElementsByTagName(elementName);
for (int i = elements.getLength() - 1; i >= 0; i
v.add(this.getTextChildNodeValue(elements.item(i)));
// LogService.instance().log(LogService.DEBUG,"adding "+this.getTextChildNodeValue(elements.item(i))+" to the \""+elementName+"\" vector.");
}
return v;
}
/**
* put your documentation comment here
* @param node
* @return
*/
private String getTextChildNodeValue (Node node) {
if (node == null)
return null;
NodeList children = node.getChildNodes();
for (int i = children.getLength() - 1; i >= 0; i
Node child = children.item(i);
if (child.getNodeType() == Node.TEXT_NODE)
return child.getNodeValue();
}
return null;
}
/**
* UserPreferences
*/
private int getUserBrowserMapping (IPerson person, String userAgent) throws Exception {
int userId = person.getID();
int profileId = 0;
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT PROFILE_ID, USER_ID FROM UP_USER_UA_MAP WHERE USER_ID=" + userId + " AND USER_AGENT='" +
userAgent + "'";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserBrowserMapping(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
if (rs.next()) {
profileId = rs.getInt("PROFILE_ID");
if (rs.wasNull()) {
profileId = 0;
}
}
else {
return 0;
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return profileId;
}
public Document getUserLayout (IPerson person, UserProfile profile) throws Exception {
int userId = person.getID();
int realUserId = userId;
ResultSet rs;
Connection con = RDBMServices.getConnection();
RDBMServices.setAutoCommit(con, false); // May speed things up, can't hurt
try {
DocumentImpl doc = new DocumentImpl();
Element root = doc.createElement("layout");
Statement stmt = con.createStatement();
try {
long startTime = System.currentTimeMillis();
int layoutId=profile.getLayoutId();
if (layoutId == 0) { // First time, grab the default layout for this user
String sQuery = "SELECT USER_DFLT_USR_ID, USER_DFLT_LAY_ID FROM UP_USER WHERE USER_ID=" + userId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sQuery);
rs = stmt.executeQuery(sQuery);
try {
rs.next();
userId = rs.getInt(1);
layoutId = rs.getInt(2);
} finally {
rs.close();
}
// Make sure the next struct id is set in case the user adds a channel
sQuery = "SELECT NEXT_STRUCT_ID FROM UP_USER WHERE USER_ID=" + userId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery);
int nextStructId;
rs = stmt.executeQuery(sQuery);
try {
rs.next();
nextStructId = rs.getInt(1);
} finally {
rs.close();
}
sQuery = "UPDATE UP_USER SET NEXT_STRUCT_ID=" + nextStructId + " WHERE USER_ID=" + realUserId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery);
stmt.executeUpdate(sQuery);
/* insert row(s) into up_ss_user_atts */
sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE USER_ID=" + realUserId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery);
stmt.executeUpdate(sQuery);
String Insert = "INSERT INTO UP_SS_USER_ATTS (USER_ID, PROFILE_ID, SS_ID, SS_TYPE, STRUCT_ID, PARAM_NAME, PARAM_TYPE, PARAM_VAL) "+
" SELECT "+realUserId+", USUA.PROFILE_ID, USUA.SS_ID, USUA.SS_TYPE, USUA.STRUCT_ID, USUA.PARAM_NAME, USUA.PARAM_TYPE, USUA.PARAM_VAL "+
" FROM UP_SS_USER_ATTS USUA WHERE USUA.USER_ID="+userId;
LogService.log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + Insert);
stmt.executeUpdate(Insert);
RDBMServices.commit(con); // Make sure it appears in the store
}
int firstStructId = -1;
String sQuery = "SELECT INIT_STRUCT_ID FROM UP_USER_LAYOUT WHERE USER_ID=" + userId + " AND LAYOUT_ID = " + layoutId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sQuery);
rs = stmt.executeQuery(sQuery);
try {
rs.next();
firstStructId = rs.getInt(1);
} finally {
rs.close();
}
String sql = "SELECT ULS.STRUCT_ID,ULS.NEXT_STRUCT_ID,ULS.CHLD_STRUCT_ID,ULS.CHAN_ID,ULS.NAME,ULS.TYPE,ULS.HIDDEN,"+
"ULS.UNREMOVABLE,ULS.IMMUTABLE";
if (RDBMServices.supportsOuterJoins) {
sql += ",USP.STRUCT_PARM_NM,USP.STRUCT_PARM_VAL FROM " + RDBMServices.joinQuery.getQuery("layout");
} else {
sql += " FROM UP_LAYOUT_STRUCT ULS WHERE ";
}
sql += " ULS.USER_ID=" + userId + " AND ULS.LAYOUT_ID=" + layoutId + " ORDER BY ULS.STRUCT_ID";
HashMap layoutStructure = new HashMap();
ArrayList chanIds = new ArrayList();
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sql);
StringBuffer structParms = new StringBuffer();
rs = stmt.executeQuery(sql);
try {
int lastStructId = 0;
LayoutStructure ls = null;
String sepChar = "";
if (rs.next()) {
int structId = rs.getInt(1);
if (rs.wasNull()) {
structId = 0;
}
readLayout: while (true) {
if (DEBUG > 1) System.err.println("Found layout structureID " + structId);
int nextId = rs.getInt(2);
if (rs.wasNull()) {
nextId = 0;
}
int childId = rs.getInt(3);
if (rs.wasNull()) {
childId = 0;
}
int chanId = rs.getInt(4);
if (rs.wasNull()) {
chanId = 0;
}
ls = new LayoutStructure(structId, nextId, childId, chanId, rs.getString(7),rs.getString(8),rs.getString(9));
layoutStructure.put(new Integer(structId), ls);
lastStructId = structId;
if (!ls.isChannel()) {
ls.addFolderData(rs.getString(5), rs.getString(6));
} else {
chanIds.add(new Integer(chanId)); // For later
}
if (RDBMServices.supportsOuterJoins) {
do {
String name = rs.getString(10);
String value = rs.getString(11); // Oracle JDBC requires us to do this for longs
if (name != null) { // may not be there because of the join
ls.addParameter(name, value);
}
if (!rs.next()) {
break readLayout;
}
structId = rs.getInt(1);
if (rs.wasNull()) {
structId = 0;
}
} while (structId == lastStructId);
} else { // Do second SELECT later on for structure parameters
if (ls.isChannel()) {
structParms.append(sepChar + ls.chanId);
sepChar = ",";
}
if (rs.next()) {
structId = rs.getInt(1);
if (rs.wasNull()) {
structId = 0;
}
} else {
break readLayout;
}
}
} // while
}
} finally {
rs.close();
}
// We have to retrieve the channel defition after the layout structure
// since retrieving the channel data from the DB may interfere with the
// layout structure ResultSet (in other words, Oracle is a pain to program for)
if (chanIds.size() > 0) {
RDBMServices.PreparedStatement pstmtChannel = crsdb.getChannelPstmt(con);
try {
RDBMServices.PreparedStatement pstmtChannelParm = crsdb.getChannelParmPstmt(con);
try {
// Pre-prime the channel pump
for (int i = 0; i < chanIds.size(); i++) {
int chanId = ((Integer) chanIds.get(i)).intValue();
crsdb.getChannel(chanId, true, pstmtChannel, pstmtChannelParm);
if (DEBUG > 1) {
System.err.println("Precached " + chanId);
}
}
} finally {
if (pstmtChannelParm != null) {
pstmtChannelParm.close();
}
}
} finally {
pstmtChannel.close();
}
chanIds.clear();
}
if (!RDBMServices.supportsOuterJoins) { // Pick up structure parameters
sql = "SELECT STRUCT_ID, STRUCT_PARM_NM,STRUCT_PARM_VAL FROM UP_LAYOUT_PARAM WHERE USER_ID=" + userId + " AND LAYOUT_ID=" + layoutId +
" AND STRUCT_ID IN (" + structParms.toString() + ") ORDER BY STRUCT_ID";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): " + sql);
rs = stmt.executeQuery(sql);
try {
if (rs.next()) {
int structId = rs.getInt(1);
readParm: while(true) {
LayoutStructure ls = (LayoutStructure)layoutStructure.get(new Integer(structId));
int lastStructId = structId;
do {
ls.addParameter(rs.getString(2), rs.getString(3));
if (!rs.next()) {
break readParm;
}
} while ((structId = rs.getInt(1)) == lastStructId);
}
}
} finally {
rs.close();
}
}
if (layoutStructure.size() > 0) { // We have a layout to work with
createLayout(layoutStructure, doc, root, firstStructId);
layoutStructure.clear();
long stopTime = System.currentTimeMillis();
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserLayout(): Layout document for user " + userId + " took " +
(stopTime - startTime) + " milliseconds to create");
doc.appendChild(root);
if (DEBUG > 1) {
System.err.println("--> created document");
dumpDoc(doc, "");
System.err.println("<
}
}
} finally {
stmt.close();
}
return doc;
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* put your documentation comment here
* @param person
* @param profileId
* @return
* @exception Exception
*/
public UserProfile getUserProfileById (IPerson person, int profileId) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT USER_ID, PROFILE_ID, PROFILE_NAME, DESCRIPTION, LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID FROM UP_USER_PROFILE WHERE USER_ID="
+ userId + " AND PROFILE_ID=" + profileId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserProfileId(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
if (rs.next()) {
int layoutId = rs.getInt(5);
if (rs.wasNull()) {
layoutId = 0;
}
int structSsId = rs.getInt(6);
if (rs.wasNull()) {
structSsId = 0;
}
int themeSsId = rs.getInt(7);
if (rs.wasNull()) {
themeSsId = 0;
}
return new UserProfile(profileId, rs.getString(3), rs.getString(4), layoutId,
structSsId, themeSsId);
}
else {
throw new Exception("Unable to find User Profile for user " + userId + " and profile " + profileId);;
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* put your documentation comment here
* @param person
* @return
* @exception Exception
*/
public Hashtable getUserProfileList (IPerson person) throws Exception {
int userId = person.getID();
Hashtable pv = new Hashtable();
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "SELECT USER_ID, PROFILE_ID, PROFILE_NAME, DESCRIPTION, LAYOUT_ID, STRUCTURE_SS_ID, THEME_SS_ID FROM UP_USER_PROFILE WHERE USER_ID="
+ userId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getUserProfileList(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
int layoutId = rs.getInt(5);
if (rs.wasNull()) {
layoutId = 0;
}
int structSsId = rs.getInt(6);
if (rs.wasNull()) {
structSsId = 0;
}
int themeSsId = rs.getInt(7);
if (rs.wasNull()) {
themeSsId = 0;
}
UserProfile upl = new UserProfile(rs.getInt(2), rs.getString(3), rs.getString(4),
layoutId, structSsId, themeSsId);
pv.put(new Integer(upl.getProfileId()), upl);
}
} finally {
rs.close();
}
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
return pv;
}
/**
* Remove (with cleanup) a structure stylesheet channel attribute
* @param stylesheetId id of the structure stylesheet
* @param pName name of the attribute
* @param con active database connection
*/
private void removeStructureChannelAttribute (int stylesheetId, String pName, Connection con) throws java.sql.SQLException {
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId + " AND TYPE=3 AND PARAM_NAME='" + pName
+ "'";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureChannelAttribute() : " + sQuery);
stmt.executeQuery(sQuery);
// clean up user preference tables
sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_TYPE=3 AND PARAM_NAME='"
+ pName + "'";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureChannelAttribute() : " + sQuery);
stmt.executeQuery(sQuery);
} finally {
stmt.close();
}
}
/**
* Remove (with cleanup) a structure stylesheet folder attribute
* @param stylesheetId id of the structure stylesheet
* @param pName name of the attribute
* @param con active database connection
*/
private void removeStructureFolderAttribute (int stylesheetId, String pName, Connection con) throws java.sql.SQLException {
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId + " AND TYPE=2 AND PARAM_NAME='" + pName
+ "'";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureFolderAttribute() : " + sQuery);
stmt.executeQuery(sQuery);
// clean up user preference tables
sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_TYPE=2 AND PARAM_NAME='"
+ pName + "'";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureFolderAttribute() : " + sQuery);
stmt.executeQuery(sQuery);
} finally {
stmt.close();
}
}
/**
* put your documentation comment here
* @param stylesheetName
* @exception Exception
*/
public void removeStructureStylesheetDescription (int stylesheetId) throws Exception {
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
// detele all associated theme stylesheets
String sQuery = "SELECT SS_ID FROM UP_SS_THEME WHERE STRUCT_SS_ID=" + stylesheetId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetDescription() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
while (rs.next()) {
removeThemeStylesheetDescription(rs.getInt("SS_ID"));
}
} finally {
rs.close();
}
sQuery = "DELETE FROM UP_SS_STRUCT WHERE SS_ID=" + stylesheetId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
// delete params
sQuery = "DELETE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
// clean up user preferences
// should we do something about profiles ?
RDBMServices.commit(con);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Remove (with cleanup) a structure stylesheet param
* @param stylesheetId id of the structure stylesheet
* @param pName name of the parameter
* @param con active database connection
*/
private void removeStructureStylesheetParam (int stylesheetId, String pName, Connection con) throws java.sql.SQLException {
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId + " AND TYPE=1 AND PARAM_NAME='" + pName
+ "'";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetParam() : " + sQuery);
stmt.executeQuery(sQuery);
// clean up user preference tables
sQuery = "DELETE FROM UP_SS_USER_PARM WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_TYPE=1 AND PARAM_NAME='"
+ pName + "'";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeStructureStylesheetParam() : " + sQuery);
stmt.executeQuery(sQuery);
} finally {
stmt.close();
}
}
/**
* Remove (with cleanup) a theme stylesheet channel attribute
* @param stylesheetId id of the theme stylesheet
* @param pName name of the attribute
* @param con active database connection
*/
private void removeThemeChannelAttribute (int stylesheetId, String pName, Connection con) throws java.sql.SQLException {
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId + " AND TYPE=3 AND PARAM_NAME='" + pName
+ "'";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeChannelAttribute() : " + sQuery);
stmt.executeQuery(sQuery);
// clean up user preference tables
sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_TYPE=3 AND PARAM_NAME='"
+ pName + "'";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetParam() : " + sQuery);
stmt.executeQuery(sQuery);
} finally {
stmt.close();
}
}
/**
* put your documentation comment here
* @param stylesheetName
* @exception Exception
*/
public void removeThemeStylesheetDescription (int stylesheetId) throws Exception {
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_SS_THEME WHERE SS_ID=" + stylesheetId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
// delete params
sQuery = "DELETE FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
// clean up user preferences
sQuery = "DELETE FROM UP_SS_USER_PARM WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
sQuery = "DELETE FROM UP_SS_USER_ATTS WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
// nuke the profiles as well ?
RDBMServices.commit(con);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Remove (with cleanup) a theme stylesheet param
* @param stylesheetId id of the theme stylesheet
* @param pName name of the parameter
* @param con active database connection
*/
private void removeThemeStylesheetParam (int stylesheetId, String pName, Connection con) throws java.sql.SQLException {
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId + " AND TYPE=1 AND PARAM_NAME='" + pName
+ "'";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetParam() : " + sQuery);
stmt.executeQuery(sQuery);
// clean up user preference tables
sQuery = "DELETE FROM UP_SS_USER_PARM WHERE SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_TYPE=1 AND PARAM_NAME='"
+ pName + "'";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::removeThemeStylesheetParam() : " + sQuery);
stmt.executeQuery(sQuery);
} finally {
stmt.close();
}
}
/**
* put your documentation comment here
* @param person
* @param doc
* @exception Exception
*/
public void saveBookmarkXML (IPerson person, Document doc) throws Exception {
int userId = person.getID();
StringWriter outString = new StringWriter();
XMLSerializer xsl = new XMLSerializer(outString, new OutputFormat(doc));
xsl.serialize(doc);
Connection con = RDBMServices.getConnection();
try {
Statement statem = con.createStatement();
try {
String sQuery = "UPDATE UPC_BOOKMARKS SET BOOKMARK_XML = '" + outString.toString() + "' WHERE PORTAL_USER_ID = "
+ userId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::saveBookmarkXML(): " + sQuery);
statem.executeUpdate(sQuery);
} finally {
statem.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* put your documentation comment here
* @param nodeup
* @param stmt
* @param userId
* @param layoutId
* @param structId
* @return
* @exception java.sql.SQLException
*/
protected final int saveStructure (Node node, RDBMServices.PreparedStatement structStmt, RDBMServices.PreparedStatement parmStmt) throws java.sql.SQLException {
if (node == null || node.getNodeName().equals("parameter")) { // No more or parameter node
return 0;
}
Element structure = (Element)node;
int saveStructId = Integer.parseInt(structure.getAttribute("ID").substring(1));
int nextStructId = 0;
int childStructId = 0;
String sQuery;
if (DEBUG > 0) {
LogService.instance().log(LogService.DEBUG, "-->" + node.getNodeName() + "@" + saveStructId);
}
if (node.hasChildNodes()) {
childStructId = saveStructure(node.getFirstChild(), structStmt, parmStmt);
}
nextStructId = saveStructure(node.getNextSibling(), structStmt, parmStmt);
structStmt.clearParameters();
structStmt.setInt(1, saveStructId);
structStmt.setInt(2, nextStructId);
structStmt.setInt(3, childStructId);
String externalId = structure.getAttribute("external_id");
if (externalId != null && externalId.trim().length() > 0) {
structStmt.setString(4, externalId.trim());
} else {
structStmt.setNull(4, java.sql.Types.VARCHAR);
}
if (node.getNodeName().equals("channel")) {
int chanId = Integer.parseInt(node.getAttributes().getNamedItem("chanID").getNodeValue());
structStmt.setInt(5, chanId);
structStmt.setNull(6,java.sql.Types.VARCHAR);
}
else {
structStmt.setNull(5,java.sql.Types.NUMERIC);
structStmt.setString(6, RDBMServices.sqlEscape(structure.getAttribute("name")));
}
String structType = structure.getAttribute("type");
if (structType.length() > 0) {
structStmt.setString(7, structType);
} else {
structStmt.setNull(7,java.sql.Types.VARCHAR);
}
structStmt.setString(8, RDBMServices.dbFlag(xmlBool(structure.getAttribute("hidden"))));
structStmt.setString(9, RDBMServices.dbFlag(xmlBool(structure.getAttribute("immutable"))));
structStmt.setString(10, RDBMServices.dbFlag(xmlBool(structure.getAttribute("unremovable"))));
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::saveStructure(): " + structStmt);
structStmt.executeUpdate();
NodeList parameters = node.getChildNodes();
if (parameters != null) {
for (int i = 0; i < parameters.getLength(); i++) {
if (parameters.item(i).getNodeName().equals("parameter")) {
Element parmElement = (Element)parameters.item(i);
NamedNodeMap nm = parmElement.getAttributes();
String nodeName = nm.getNamedItem("name").getNodeValue();
String nodeValue = nm.getNamedItem("value").getNodeValue();
Node override = nm.getNamedItem("override");
if (DEBUG > 0) {
System.err.println(nodeName + "=" + nodeValue);
}
if (override == null || !override.getNodeValue().equals("yes")) {
if (DEBUG > 0)
System.err.println("Not saving channel defined parameter value " + nodeName);
}
else {
parmStmt.clearParameters();
parmStmt.setInt(1, saveStructId);
parmStmt.setString(2, nodeName);
parmStmt.setString(3, nodeValue);
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::saveStructure(): " + parmStmt);
parmStmt.executeUpdate();
}
}
}
}
return saveStructId;
}
/**
* put your documentation comment here
* @param person
* @param profileId
* @param ssup
* @exception Exception
*/
public void setStructureStylesheetUserPreferences (IPerson person, int profileId, StructureStylesheetUserPreferences ssup) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
// Set autocommit false for the connection
int stylesheetId = ssup.getStylesheetId();
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
// write out params
for (Enumeration e = ssup.getParameterValues().keys(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
// see if the parameter was already there
String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_PARM WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId
+ " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_NAME='" + pName + "'";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
if (rs.next()) {
// update
sQuery = "UPDATE UP_SS_USER_PARM SET PARAM_VAL='" + ssup.getParameterValue(pName) + "' WHERE USER_ID=" + userId
+ " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND PARAM_NAME='" + pName
+ "'";
}
else {
// insert
sQuery = "INSERT INTO UP_SS_USER_PARM (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,PARAM_NAME,PARAM_VAL) VALUES (" + userId
+ "," + profileId + "," + stylesheetId + ",1,'" + pName + "','" + ssup.getParameterValue(pName) + "')";
}
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery);
stmt.executeUpdate(sQuery);
}
// write out folder attributes
for (Enumeration e = ssup.getFolders(); e.hasMoreElements();) {
String folderId = (String)e.nextElement();
for (Enumeration attre = ssup.getFolderAttributeNames(); attre.hasMoreElements();) {
String pName = (String)attre.nextElement();
String pValue = ssup.getDefinedFolderAttributeValue(folderId, pName);
if (pValue != null) {
// store user preferences
String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_ATTS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId
+ " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID='" + folderId.substring(1) + "' AND PARAM_NAME='" + pName
+ "' AND PARAM_TYPE=2";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
if (rs.next()) {
// update
sQuery = "UPDATE UP_SS_USER_ATTS SET PARAM_VAL='" + pValue + "' WHERE USER_ID=" + userId + " AND PROFILE_ID="
+ profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID='" + folderId.substring(1) + "' AND PARAM_NAME='"
+ pName + "' AND PARAM_TYPE=2";
}
else {
// insert
sQuery = "INSERT INTO UP_SS_USER_ATTS (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,STRUCT_ID,PARAM_NAME,PARAM_TYPE,PARAM_VAL) VALUES ("
+ userId + "," + profileId + "," + stylesheetId + ",1,'" + folderId.substring(1) + "','" + pName + "',2,'" + pValue
+ "')";
}
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
}
// write out channel attributes
for (Enumeration e = ssup.getChannels(); e.hasMoreElements();) {
String channelId = (String)e.nextElement();
for (Enumeration attre = ssup.getChannelAttributeNames(); attre.hasMoreElements();) {
String pName = (String)attre.nextElement();
String pValue = ssup.getDefinedChannelAttributeValue(channelId, pName);
if (pValue != null) {
// store user preferences
String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_ATTS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId
+ " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID='" + channelId.substring(1) + "' AND PARAM_NAME='" + pName
+ "' AND PARAM_TYPE=3";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
if (rs.next()) {
// update
sQuery = "UPDATE UP_SS_USER_ATTS SET PARAM_VAL='" + pValue + "' WHERE USER_ID=" + userId + " AND PROFILE_ID="
+ profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=1 AND STRUCT_ID='" + channelId.substring(1) + "' AND PARAM_NAME='"
+ pName + "' AND PARAM_TYPE=3";
}
else {
// insert
sQuery = "INSERT INTO UP_SS_USER_ATTS (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,STRUCT_ID,PARAM_NAME,PARAM_TYPE,PARAM_VAL) VALUES ("
+ userId + "," + profileId + "," + stylesheetId + ",1,'" + channelId.substring(1) + "','" + pName + "',3,'" + pValue
+ "')";
}
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setStructureStylesheetUserPreferences(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
}
// Commit the transaction
RDBMServices.commit(con);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* put your documentation comment here
* @param person
* @param profileId
* @param tsup
* @exception Exception
*/
public void setThemeStylesheetUserPreferences (IPerson person, int profileId, ThemeStylesheetUserPreferences tsup) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
// Set autocommit false for the connection
int stylesheetId = tsup.getStylesheetId();
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
// write out params
for (Enumeration e = tsup.getParameterValues().keys(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
// see if the parameter was already there
String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_PARM WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId
+ " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_NAME='" + pName + "'";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
if (rs.next()) {
// update
sQuery = "UPDATE UP_SS_USER_PARM SET PARAM_VAL='" + tsup.getParameterValue(pName) + "' WHERE USER_ID=" + userId
+ " AND PROFILE_ID=" + profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND PARAM_NAME='" + pName
+ "'";
}
else {
// insert
sQuery = "INSERT INTO UP_SS_USER_PARM (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,PARAM_NAME,PARAM_VAL) VALUES (" + userId
+ "," + profileId + "," + stylesheetId + ",2,'" + pName + "','" + tsup.getParameterValue(pName) + "')";
}
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery);
stmt.executeUpdate(sQuery);
}
// write out channel attributes
for (Enumeration e = tsup.getChannels(); e.hasMoreElements();) {
String channelId = (String)e.nextElement();
for (Enumeration attre = tsup.getChannelAttributeNames(); attre.hasMoreElements();) {
String pName = (String)attre.nextElement();
String pValue = tsup.getDefinedChannelAttributeValue(channelId, pName);
if (pValue != null) {
// store user preferences
String sQuery = "SELECT PARAM_VAL FROM UP_SS_USER_ATTS WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId
+ " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND STRUCT_ID='" + channelId.substring(1) + "' AND PARAM_NAME='" + pName
+ "' AND PARAM_TYPE=3";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
if (rs.next()) {
// update
sQuery = "UPDATE UP_SS_USER_ATTS SET PARAM_VAL='" + pValue + "' WHERE USER_ID=" + userId + " AND PROFILE_ID="
+ profileId + " AND SS_ID=" + stylesheetId + " AND SS_TYPE=2 AND STRUCT_ID='" + channelId.substring(1) + "' AND PARAM_NAME='"
+ pName + "' AND PARAM_TYPE=3";
}
else {
// insert
sQuery = "INSERT INTO UP_SS_USER_ATTS (USER_ID,PROFILE_ID,SS_ID,SS_TYPE,STRUCT_ID,PARAM_NAME,PARAM_TYPE,PARAM_VAL) VALUES ("
+ userId + "," + profileId + "," + stylesheetId + ",2,'" + channelId.substring(1) + "','" + pName + "',3,'" + pValue
+ "')";
}
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setThemeStylesheetUserPreferences(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
}
// Commit the transaction
RDBMServices.commit(con);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* put your documentation comment here
* @param person
* @param userAgent
* @param profileId
* @exception Exception
*/
public void setUserBrowserMapping (IPerson person, String userAgent, int profileId) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
// Set autocommit false for the connection
RDBMServices.setAutoCommit(con, false);
// remove the old mapping and add the new one
Statement stmt = con.createStatement();
try {
String sQuery = "DELETE FROM UP_USER_UA_MAP WHERE USER_ID=" + userId + " AND USER_AGENT='" + userAgent + "'";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserBrowserMapping(): " + sQuery);
stmt.executeUpdate(sQuery);
sQuery = "INSERT INTO UP_USER_UA_MAP (USER_ID,USER_AGENT,PROFILE_ID) VALUES (" + userId + ",'" + userAgent + "',"
+ profileId + ")";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserBrowserMapping(): " + sQuery);
stmt.executeUpdate(sQuery);
// Commit the transaction
RDBMServices.commit(con);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Save the user layout
* @param person
* @param profileId
* @param layoutXML
* @throws Exception
*/
public void setUserLayout (IPerson person, UserProfile profile, Document layoutXML, boolean channelsAdded) throws Exception {
int userId = person.getID();
int layoutId=profile.getLayoutId();
int profileId=profile.getProfileId();
ResultSet rs;
Connection con = RDBMServices.getConnection();
try {
RDBMServices.setAutoCommit(con, false); // Need an atomic update here
Statement stmt = con.createStatement();
try {
long startTime = System.currentTimeMillis();
boolean firstLayout = false;
if (layoutId == 0) { // First personal layout for this user/profile
layoutId = 1;
firstLayout = true;
}
String selectString = "USER_ID=" + userId + " AND LAYOUT_ID=" + layoutId;
String sSql = "DELETE FROM UP_LAYOUT_PARAM WHERE " + selectString;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sSql);
stmt.executeUpdate(sSql);
sSql = "DELETE FROM UP_LAYOUT_STRUCT WHERE " + selectString;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sSql);
stmt.executeUpdate(sSql);
if (DEBUG > 1) {
System.err.println("--> saving document");
dumpDoc(layoutXML.getFirstChild().getFirstChild(), "");
System.err.println("<
}
RDBMServices.PreparedStatement structStmt = new RDBMServices.PreparedStatement(con,
"INSERT INTO UP_LAYOUT_STRUCT " +
"(USER_ID, LAYOUT_ID, STRUCT_ID, NEXT_STRUCT_ID, CHLD_STRUCT_ID,EXTERNAL_ID,CHAN_ID,NAME,TYPE,HIDDEN,IMMUTABLE,UNREMOVABLE) " +
"VALUES ("+ userId + "," + layoutId + ",?,?,?,?,?,?,?,?,?,?)");
try {
RDBMServices.PreparedStatement parmStmt = new RDBMServices.PreparedStatement(con,
"INSERT INTO UP_LAYOUT_PARAM " +
"(USER_ID, LAYOUT_ID, STRUCT_ID, STRUCT_PARM_NM, STRUCT_PARM_VAL) " +
"VALUES ("+ userId + "," + layoutId + ",?,?,?)");
try {
int firstStructId = saveStructure(layoutXML.getFirstChild().getFirstChild(), structStmt, parmStmt);
sSql = "UPDATE UP_USER_LAYOUT SET INIT_STRUCT_ID=" + firstStructId + " WHERE " + selectString;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sSql);
stmt.executeUpdate(sSql);
// Update the last time the user saw the list of available channels
if (channelsAdded) {
sSql = "UPDATE UP_USER SET LST_CHAN_UPDT_DT=" + RDBMServices.sqlTimeStamp() +
" WHERE USER_ID=" + userId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sSql);
stmt.executeUpdate(sSql);
}
if (firstLayout) {
int defaultUserId;
int defaultLayoutId;
// Have to copy some of data over from the default user
String sQuery = "SELECT USER_DFLT_USR_ID,USER_DFLT_LAY_ID FROM UP_USER WHERE USER_ID=" + userId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery);
rs = stmt.executeQuery(sQuery);
try {
rs.next();
defaultUserId = rs.getInt(1);
defaultLayoutId = rs.getInt(2);
} finally {
rs.close();
}
sQuery = "UPDATE UP_USER SET CURR_LAY_ID=" + layoutId + " WHERE USER_ID=" + userId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery);
stmt.executeUpdate(sQuery);
sQuery = "UPDATE UP_USER_PROFILE SET LAYOUT_ID=1 WHERE USER_ID=" + userId + " AND PROFILE_ID=" + profileId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): " + sQuery);
stmt.executeUpdate(sQuery);
}
long stopTime = System.currentTimeMillis();
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserLayout(): Layout document for user " + userId + " took " +
(stopTime - startTime) + " milliseconds to save");
} finally {
parmStmt.close();
}
} finally {
structStmt.close();
}
} finally {
stmt.close();
}
RDBMServices.commit(con);
} catch (Exception e) {
RDBMServices.rollback(con);
throw e;
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* put your documentation comment here
* @param person
* @param profile
* @exception Exception
*/
public void setUserProfile (IPerson person, UserProfile profile) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
// this is ugly, but we have to know wether to do INSERT or UPDATE
String sQuery = "SELECT USER_ID, PROFILE_NAME FROM UP_USER_PROFILE WHERE USER_ID=" + userId + " AND PROFILE_ID="
+ profile.getProfileId();
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserProfile() : " + sQuery);
ResultSet rs = stmt.executeQuery(sQuery);
try {
if (rs.next()) {
sQuery = "UPDATE UP_USER_PROFILE SET THEME_SS_ID=" + profile.getThemeStylesheetId() + ", STRUCTURE_SS_ID=" +
profile.getStructureStylesheetId() + ", DESCRIPTION='" + profile.getProfileDescription() + "', PROFILE_NAME='"
+ profile.getProfileName() + "' WHERE USER_ID = " + userId + " AND PROFILE_ID=" + profile.getProfileId();
}
else {
sQuery = "INSERT INTO UP_USER_PROFILE (USER_ID,PROFILE_ID,PROFILE_NAME,STRUCTURE_SS_ID,THEME_SS_ID,DESCRIPTION) VALUES ("
+ userId + "," + profile.getProfileId() + ",'" + profile.getProfileName() + "'," + profile.getStructureStylesheetId()
+ "," + profile.getThemeStylesheetId() + ",'" + profile.getProfileDescription() + "')";
}
} finally {
rs.close();
}
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::setUserProfile(): " + sQuery);
stmt.executeUpdate(sQuery);
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Updates an existing structure stylesheet description with a new one. Old stylesheet
* description is found based on the Id provided in the parameter structure.
* @param ssd new stylesheet description
*/
public void updateStructureStylesheetDescription (StructureStylesheetDescription ssd) throws Exception {
Connection con = RDBMServices.getConnection();
try {
// Set autocommit false for the connection
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
int stylesheetId = ssd.getId();
String sQuery = "UPDATE UP_SS_STRUCT SET SS_NAME='" + ssd.getStylesheetName() + "',SS_URI='" + ssd.getStylesheetURI()
+ "',SS_DESCRIPTION_URI='" + ssd.getStylesheetDescriptionURI() + "',SS_DESCRIPTION_TEXT='" + ssd.getStylesheetWordDescription()
+ "' WHERE SS_ID=" + stylesheetId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
// first, see what was there before
HashSet oparams = new HashSet();
HashSet ofattrs = new HashSet();
HashSet ocattrs = new HashSet();
sQuery = "SELECT PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE FROM UP_SS_STRUCT_PAR WHERE SS_ID=" + stylesheetId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery);
Statement stmtOld = con.createStatement();
ResultSet rsOld = stmtOld.executeQuery(sQuery);
try {
while (rsOld.next()) {
int type = rsOld.getInt("TYPE");
if (type == 1) {
// stylesheet param
String pName = rsOld.getString("PARAM_NAME");
oparams.add(pName);
if (!ssd.containsParameterName(pName)) {
// delete param
removeStructureStylesheetParam(stylesheetId, pName, con);
}
else {
// update param
sQuery = "UPDATE UP_SS_STRUCT_PAR SET PARAM_DEFAULT_VAL='" + ssd.getStylesheetParameterDefaultValue(pName)
+ "',PARAM_DESCRIPT='" + ssd.getStylesheetParameterWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId
+ " AND PARAM_NAME='" + pName + "' AND TYPE=1";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
}
}
else if (type == 2) {
// folder attribute
String pName = rsOld.getString("PARAM_NAME");
ofattrs.add(pName);
if (!ssd.containsFolderAttribute(pName)) {
// delete folder attribute
removeStructureFolderAttribute(stylesheetId, pName, con);
}
else {
// update folder attribute
sQuery = "UPDATE UP_SS_STRUCT_PAR SET PARAM_DEFAULT_VAL='" + ssd.getFolderAttributeDefaultValue(pName) +
"',PARAM_DESCRIPT='" + ssd.getFolderAttributeWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId
+ " AND PARAM_NAME='" + pName + "'AND TYPE=2";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
}
}
else if (type == 3) {
// channel attribute
String pName = rsOld.getString("PARAM_NAME");
ocattrs.add(pName);
if (!ssd.containsChannelAttribute(pName)) {
// delete channel attribute
removeStructureChannelAttribute(stylesheetId, pName, con);
}
else {
// update channel attribute
sQuery = "UPDATE UP_SS_STRUCT_PAR SET PARAM_DEFAULT_VAL='" + ssd.getChannelAttributeDefaultValue(pName) +
"',PARAM_DESCRIPT='" + ssd.getChannelAttributeWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId
+ " AND PARAM_NAME='" + pName + "' AND TYPE=3";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateStructureStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
}
}
else {
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getStructureStylesheetDescription() : encountered param of unknown type! (stylesheetId="
+ stylesheetId + " param_name=\"" + rsOld.getString("PARAM_NAME") + "\" type=" + type +
").");
}
}
} finally {
rsOld.close();
stmtOld.close();
}
// look for new attributes/parameters
// insert all stylesheet params
for (Enumeration e = ssd.getStylesheetParameterNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
if (!oparams.contains(pName)) {
sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" +
stylesheetId + ",'" + pName + "','" + ssd.getStylesheetParameterDefaultValue(pName) + "','" + ssd.getStylesheetParameterWordDescription(pName)
+ "',1)";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
// insert all folder attributes
for (Enumeration e = ssd.getFolderAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
if (!ofattrs.contains(pName)) {
sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" +
stylesheetId + ",'" + pName + "','" + ssd.getFolderAttributeDefaultValue(pName) + "','" + ssd.getFolderAttributeWordDescription(pName)
+ "',2)";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
// insert all channel attributes
for (Enumeration e = ssd.getChannelAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
if (!ocattrs.contains(pName)) {
sQuery = "INSERT INTO UP_SS_STRUCT_PAR (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" +
stylesheetId + ",'" + pName + "','" + ssd.getChannelAttributeDefaultValue(pName) + "','" + ssd.getChannelAttributeWordDescription(pName)
+ "',3)";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
// Commit the transaction
RDBMServices.commit(con);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* Updates an existing structure stylesheet description with a new one. Old stylesheet
* description is found based on the Id provided in the parameter structure.
* @param ssd new stylesheet description
*/
public void updateThemeStylesheetDescription (ThemeStylesheetDescription tsd) throws Exception {
Connection con = RDBMServices.getConnection();
try {
// Set autocommit false for the connection
RDBMServices.setAutoCommit(con, false);
Statement stmt = con.createStatement();
try {
int stylesheetId = tsd.getId();
String sQuery = "UPDATE UP_SS_THEME SET SS_NAME='" + tsd.getStylesheetName() + "',SS_URI='" + tsd.getStylesheetURI()
+ "',SS_DESCRIPTION_URI='" + tsd.getStylesheetDescriptionURI() + "',SS_DESCRIPTION_TEXT='" + tsd.getStylesheetWordDescription()
+ "' WHERE SS_ID=" + stylesheetId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
// first, see what was there before
HashSet oparams = new HashSet();
HashSet ocattrs = new HashSet();
sQuery = "SELECT PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE FROM UP_SS_THEME_PARM WHERE SS_ID=" + stylesheetId;
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery);
Statement stmtOld = con.createStatement();
ResultSet rsOld = stmtOld.executeQuery(sQuery);
try {
while (rsOld.next()) {
int type = rsOld.getInt("TYPE");
if (type == 1) {
// stylesheet param
String pName = rsOld.getString("PARAM_NAME");
oparams.add(pName);
if (!tsd.containsParameterName(pName)) {
// delete param
removeThemeStylesheetParam(stylesheetId, pName, con);
}
else {
// update param
sQuery = "UPDATE UP_SS_THEME_PARM SET PARAM_DEFAULT_VAL='" + tsd.getStylesheetParameterDefaultValue(pName)
+ "',PARAM_DESCRIPT='" + tsd.getStylesheetParameterWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId
+ " AND PARAM_NAME='" + pName + "' AND TYPE=1";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
}
}
else if (type == 2) {
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered a folder attribute specified for a theme stylesheet ! DB is corrupt. (stylesheetId="
+ stylesheetId + " param_name=\"" + rsOld.getString("PARAM_NAME") + "\" type=" + type +
").");
}
else if (type == 3) {
// channel attribute
String pName = rsOld.getString("PARAM_NAME");
ocattrs.add(pName);
if (!tsd.containsChannelAttribute(pName)) {
// delete channel attribute
removeThemeChannelAttribute(stylesheetId, pName, con);
}
else {
// update channel attribute
sQuery = "UPDATE UP_SS_THEME_PARM SET PARAM_DEFAULT_VAL='" + tsd.getChannelAttributeDefaultValue(pName) +
"',PARAM_DESCRIPT='" + tsd.getChannelAttributeWordDescription(pName) + "' WHERE SS_ID=" + stylesheetId
+ " AND PARAM_NAME='" + pName + "' AND TYPE=3";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateThemeStylesheetDescription() : " + sQuery);
stmt.executeUpdate(sQuery);
}
}
else {
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::getThemeStylesheetDescription() : encountered param of unknown type! (stylesheetId="
+ stylesheetId + " param_name=\"" + rsOld.getString("PARAM_NAME") + "\" type=" + type +
").");
}
}
} finally {
rsOld.close();
stmtOld.close();
}
// look for new attributes/parameters
// insert all stylesheet params
for (Enumeration e = tsd.getStylesheetParameterNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
if (!oparams.contains(pName)) {
sQuery = "INSERT INTO UP_SS_THEME_PARM (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + stylesheetId
+ ",'" + pName + "','" + tsd.getStylesheetParameterDefaultValue(pName) + "','" + tsd.getStylesheetParameterWordDescription(pName)
+ "',1)";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
// insert all channel attributes
for (Enumeration e = tsd.getChannelAttributeNames(); e.hasMoreElements();) {
String pName = (String)e.nextElement();
if (!ocattrs.contains(pName)) {
sQuery = "INSERT INTO UP_SS_THEME_PARM (SS_ID,PARAM_NAME,PARAM_DEFAULT_VAL,PARAM_DESCRIPT,TYPE) VALUES (" + stylesheetId
+ ",'" + pName + "','" + tsd.getChannelAttributeDefaultValue(pName) + "','" + tsd.getChannelAttributeWordDescription(pName)
+ "',3)";
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::addThemeStylesheetDescription(): " + sQuery);
stmt.executeUpdate(sQuery);
}
}
// Commit the transaction
RDBMServices.commit(con);
} catch (Exception e) {
// Roll back the transaction
RDBMServices.rollback(con);
throw e;
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* put your documentation comment here
* @param person
* @param profile
* @exception Exception
*/
public void updateUserProfile (IPerson person, UserProfile profile) throws Exception {
int userId = person.getID();
Connection con = RDBMServices.getConnection();
try {
Statement stmt = con.createStatement();
try {
String sQuery = "UPDATE UP_USER_PROFILE SET THEME_SS_ID=" + profile.getThemeStylesheetId() + ", STRUCTURE_SS_ID="
+ profile.getStructureStylesheetId() + ", DESCRIPTION='" + profile.getProfileDescription() + "', PROFILE_NAME='"
+ profile.getProfileName() + "' WHERE USER_ID = " + userId + " AND PROFILE_ID=" + profile.getProfileId();
LogService.instance().log(LogService.DEBUG, "RDBMUserLayoutStore::updateUserProfile() : " + sQuery);
stmt.executeUpdate(sQuery);
} finally {
stmt.close();
}
} finally {
RDBMServices.releaseConnection(con);
}
}
/**
* put your documentation comment here
* @param userAgent
* @param profileId
*/
public void setSystemBrowserMapping (String userAgent, int profileId) throws Exception {
this.setUserBrowserMapping(systemUser, userAgent, profileId);
}
/**
* put your documentation comment here
* @param userAgent
* @return
*/
private int getSystemBrowserMapping (String userAgent) throws Exception {
return getUserBrowserMapping(systemUser, userAgent);
}
/**
* put your documentation comment here
* @param person
* @param userAgent
* @return
*/
public UserProfile getUserProfile (IPerson person, String userAgent) throws Exception {
int profileId = getUserBrowserMapping(person, userAgent);
if (profileId == 0)
return null;
return this.getUserProfileById(person, profileId);
}
/**
* put your documentation comment here
* @param userAgent
* @return
*/
public UserProfile getSystemProfile (String userAgent) throws Exception {
int profileId = getSystemBrowserMapping(userAgent);
if (profileId == 0)
return null;
UserProfile up = this.getUserProfileById(systemUser, profileId);
up.setSystemProfile(true);
return up;
}
/**
* put your documentation comment here
* @param profileId
* @return
*/
public UserProfile getSystemProfileById (int profileId) throws Exception {
UserProfile up = this.getUserProfileById(systemUser, profileId);
up.setSystemProfile(true);
return up;
}
/**
* put your documentation comment here
* @return
*/
public Hashtable getSystemProfileList () throws Exception {
Hashtable pl = this.getUserProfileList(systemUser);
for (Enumeration e = pl.elements(); e.hasMoreElements();) {
UserProfile up = (UserProfile)e.nextElement();
up.setSystemProfile(true);
}
return pl;
}
/**
* put your documentation comment here
* @param profile
*/
public void updateSystemProfile (UserProfile profile) throws Exception {
this.updateUserProfile(systemUser, profile);
}
/**
* put your documentation comment here
* @param profile
* @return
*/
public UserProfile addSystemProfile (UserProfile profile) throws Exception {
return addUserProfile(systemUser, profile);
}
/**
* put your documentation comment here
* @param profileId
*/
public void deleteSystemProfile (int profileId) throws Exception {
this.deleteUserProfile(systemUser, profileId);
}
private class SystemUser implements IPerson {
public void setID(int sID) {}
public int getID() {return 0;}
public void setFullName(String sFullName) {}
public String getFullName() {return "uPortal System Account";}
public Object getAttribute (String key) {return null;}
public void setAttribute (String key, Object value) {}
public Enumeration getAttributes () {return null;}
public Enumeration getAttributeNames () {return null;}
public boolean isGuest() {return(false);}
public ISecurityContext getSecurityContext() { return(null); }
public void setSecurityContext(ISecurityContext context) {}
}
private IPerson systemUser = new SystemUser(); // We should be getting this from the uPortal
/**
* put your documentation comment here
* @param person
* @param profileId
* @return
*/
public UserPreferences getUserPreferences (IPerson person, int profileId) throws Exception {
UserPreferences up = null;
UserProfile profile = this.getUserProfileById(person, profileId);
if (profile != null) {
up = getUserPreferences(person, profile);
}
return (up);
}
/**
* put your documentation comment here
* @param person
* @param profile
* @return
*/
public UserPreferences getUserPreferences (IPerson person, UserProfile profile) throws Exception {
int profileId = profile.getProfileId();
UserPreferences up = new UserPreferences(profile);
up.setStructureStylesheetUserPreferences(getStructureStylesheetUserPreferences(person, profileId, profile.getStructureStylesheetId()));
up.setThemeStylesheetUserPreferences(getThemeStylesheetUserPreferences(person, profileId, profile.getThemeStylesheetId()));
return up;
}
/**
* Put user preferences
* @param person
* @param up
* @throws Exception
*/
public void putUserPreferences (IPerson person, UserPreferences up) throws Exception {
// store profile
UserProfile profile = up.getProfile();
this.updateUserProfile(person, profile);
this.setStructureStylesheetUserPreferences(person, profile.getProfileId(), up.getStructureStylesheetUserPreferences());
this.setThemeStylesheetUserPreferences(person, profile.getProfileId(), up.getThemeStylesheetUserPreferences());
}
} |
package jolie.lang.parse.ast;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import jolie.lang.parse.ParsingContext;
public abstract class PortInfo extends OLSyntaxNode implements OperationCollector
{
private final String id;
private final Map< String, OperationDeclaration > operationsMap =
new HashMap< String, OperationDeclaration > ();
public PortInfo( ParsingContext context, String id )
{
super( context );
this.id = id;
}
public String id()
{
return id;
}
public Collection< OperationDeclaration > operations()
{
return operationsMap.values();
}
public Map< String, OperationDeclaration > operationsMap()
{
return operationsMap;
}
public void addOperation( OperationDeclaration decl )
{
operationsMap.put( decl.id(), decl );
}
} |
package etomica;
import etomica.units.Dimension;
/**
* Basic square-well potential.
* Energy is infinite if spheres overlap, is -epsilon if less than lambda*sigma and not overlapping,
* and is zero otherwise. Core diameter describes size of hard core; lambda is multiplier to get range of well.
* Suitable for use in space of any dimension.
*/
public class P2SquareWell extends Potential2 implements PotentialHard {
protected double coreDiameter, coreDiameterSquared;
protected double wellDiameter, wellDiameterSquared;
protected double lambda; //wellDiameter = coreDiameter * lambda
protected double epsilon;
protected double lastCollisionVirial, lastCollisionVirialr2;
protected Space.Tensor lastCollisionVirialTensor;
private double lastEnergyChange;
protected Space.Vector dr;
public P2SquareWell() {
this(Simulation.getDefault().space);
}
public P2SquareWell(Space space) {
this(space,Default.ATOM_SIZE, Default.POTENTIAL_CUTOFF_FACTOR, Default.POTENTIAL_WELL);
}
public P2SquareWell(double coreDiameter, double lambda, double epsilon) {
this(Simulation.getDefault().space, coreDiameter, lambda, epsilon);
}
public P2SquareWell(Space space, double coreDiameter, double lambda, double epsilon) {
super(space);
setCoreDiameter(coreDiameter);
setLambda(lambda);
setEpsilon(epsilon);
dr = space.makeVector();
lastCollisionVirialTensor = space.makeTensor();
}
public static EtomicaInfo getEtomicaInfo() {
EtomicaInfo info = new EtomicaInfo("Simple hard repulsive core with a square-well region of attraction");
return info;
}
/**
* Returns true if separation of pair is less than core diameter, false otherwise
*/
public boolean overlap(Atom[] pair, double falseTime) {
cPair.trueReset(pair[0].coord,pair[1].coord,falseTime);
return cPair.r2() < coreDiameterSquared;
}
/**
* Implements collision dynamics between two square-well atoms.
* Includes all possibilities involving collision of hard cores, and collision of wells
* both approaching and diverging
*/
public void bump(Atom[] pair, double falseTime) {
cPair.trueReset(pair[0].coord,pair[1].coord,falseTime);
double eps = 1.0e-10;
double r2 = cPair.r2();
double bij = cPair.vDotr();
double reduced_m = 1.0/(pair[0].coord.rm() + pair[1].coord.rm());
double nudge = 0;
if(2*r2 < (coreDiameterSquared+wellDiameterSquared)) { // Hard-core collision
if (Debug.ON && Math.abs(r2 - coreDiameterSquared)/coreDiameterSquared > 1.e-9) {
throw new RuntimeException("atoms "+pair[0]+" "+pair[1]+" not at the right distance "+r2+" "+coreDiameterSquared);
}
lastCollisionVirial = 2.0*reduced_m*bij;
lastEnergyChange = 0.0;
}
else { // Well collision
// ke is kinetic energy due to components of velocity
double ke = bij*bij*reduced_m/(2.0*r2);
if(bij > 0.0) { // Separating
if(ke < epsilon) { // Not enough kinetic energy to escape
if (Debug.ON && Math.abs(r2 - wellDiameterSquared)/wellDiameterSquared > 1.e-9) {
throw new RuntimeException("atoms "+pair[0]+" "+pair[1]+" not at the right distance "+r2+" "+wellDiameterSquared);
}
lastCollisionVirial = 2.0*reduced_m*bij;
nudge = -eps;
lastEnergyChange = 0.0;
}
else { // Escape
if (Debug.ON && Math.abs(r2 - wellDiameterSquared)/wellDiameterSquared > 1.e-9) {
throw new RuntimeException("atoms "+pair[0]+" "+pair[1]+" not at the right distance "+r2+" "+wellDiameterSquared);
}
lastCollisionVirial = reduced_m*(bij - Math.sqrt(bij*bij - 2.0*r2*epsilon/reduced_m));
nudge = eps;
lastEnergyChange = epsilon;
}
}
else { // Approaching
if (Debug.ON && Math.abs(r2 - wellDiameterSquared)/wellDiameterSquared > 1.e-9) {
throw new RuntimeException("atoms "+pair[0]+" "+pair[1]+" not at the right distance "+r2+" "+wellDiameterSquared);
}
lastCollisionVirial = reduced_m*(bij +Math.sqrt(bij*bij+2.0*r2*epsilon/reduced_m));
nudge = -eps;
lastEnergyChange = -epsilon;
}
}
lastCollisionVirialr2 = lastCollisionVirial/r2;
dr.Ea1Tv1(lastCollisionVirialr2,cPair.dr());
cPair.truePush(dr,falseTime);
if(nudge != 0) cPair.nudge(nudge);
}//end of bump method
public double lastCollisionVirial() {
return lastCollisionVirial;
}
public Space.Tensor lastCollisionVirialTensor() {
lastCollisionVirialTensor.E(dr, dr);
lastCollisionVirialTensor.TE(lastCollisionVirialr2);
return lastCollisionVirialTensor;
}
/**
* Computes next time of collision of two square-well atoms, assuming free-flight kinematics.
* Collision may occur when cores collides, or when wells first encounter each other on
* approach, or when they edge of the wells are reached as atoms diverge.
*/
public double collisionTime(Atom[] pair, double falseTime) {
cPair.trueReset(pair[0].coord,pair[1].coord,falseTime);
double discr = 0.0;
double bij = cPair.vDotr();
double r2 = cPair.r2();
double v2 = cPair.v2();
double tij = Double.MAX_VALUE;
if(r2 < wellDiameterSquared) { // Already inside wells
if(bij < 0.0) { // Check for hard-core collision
if(Default.FIX_OVERLAP && r2 < coreDiameterSquared) { // Inside core; collision now
return 0.0;
}
discr = bij*bij - v2 * ( r2 - coreDiameterSquared );
if(discr > 0) { // Hard cores collide next
tij = (-bij - Math.sqrt(discr))/v2;
}
else { // Moving toward each other, but wells collide next
discr = bij*bij - v2 * ( r2 - wellDiameterSquared );
tij = (-bij + Math.sqrt(discr))/v2;
}
}
else { // Moving away from each other, wells collide next
discr = bij*bij - v2 * ( r2 - wellDiameterSquared ); // This is always > 0
tij = (-bij + Math.sqrt(discr))/v2;
}
}
else { // Outside wells; look for collision at well
if(bij < 0.0) {
discr = bij*bij - v2 * ( r2 - wellDiameterSquared );
if(discr > 0) {
tij = (-bij - Math.sqrt(discr))/v2;
}
}
}
return tij + falseTime;
}
/**
* Returns infinity if overlapping, -epsilon if otherwise less than well diameter, or zero if neither.
*/
public double energy(Atom[] pair) {
cPair.reset(pair[0].coord,pair[1].coord);
double r2 = cPair.r2();
return ( r2 < wellDiameterSquared) ?
((r2 < coreDiameterSquared) ? Double.MAX_VALUE : -epsilon) : 0.0;
}
public double energyChange() {return lastEnergyChange;}
/**
* Accessor method for core diameter.
*/
public double getCoreDiameter() {return coreDiameter;}
/**
* Accessor method for core diameter.
* Well diameter is defined as a multiple (lambda) of this, and is updated when core diameter is changed
*/
public void setCoreDiameter(double c) {
coreDiameter = c;
coreDiameterSquared = c*c;
wellDiameter = coreDiameter*lambda;
wellDiameterSquared = wellDiameter*wellDiameter;
}
public Dimension getCoreDiameterDimension() {return Dimension.LENGTH;}
/**
* Accessor method for well-diameter multiplier.
*/
public double getLambda() {return lambda;}
/**
* Accessor method for well-diameter multiplier.
* Well diameter is defined as this multiple of core diameter, and is updated when
* this is changed
*/
public void setLambda(double lam) {
if (lam <= 1.0) throw new IllegalArgumentException("Square-well lambda must be greater than 1.0");
lambda = lam;
wellDiameter = coreDiameter*lambda;
wellDiameterSquared = wellDiameter*wellDiameter;
}
public Dimension getLambdaDimension() {return Dimension.NULL;}
/**
* Accessor method for depth of well
*/
public double getEpsilon() {return epsilon;}
/**
* Accessor method for depth of well
*/
public void setEpsilon(double eps) {
epsilon = eps;
}
public Dimension getEpsilonDimension() {return Dimension.ENERGY;}
} |
package com.bugsnag;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Set;
import java.util.WeakHashMap;
class ExceptionHandler implements UncaughtExceptionHandler {
private final UncaughtExceptionHandler originalHandler;
private final WeakHashMap<Bugsnag, Boolean> clientMap = new WeakHashMap<Bugsnag, Boolean>();
Set<Bugsnag> uncaughtExceptionClients() {
return clientMap.keySet();
}
static void enable(Bugsnag bugsnag) {
UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
// Find or create the Bugsnag ExceptionHandler
ExceptionHandler bugsnagHandler;
if (currentHandler instanceof ExceptionHandler) {
bugsnagHandler = (ExceptionHandler) currentHandler;
} else {
bugsnagHandler = new ExceptionHandler(currentHandler);
Thread.setDefaultUncaughtExceptionHandler(bugsnagHandler);
}
// Subscribe this bugsnag to uncaught exceptions
bugsnagHandler.clientMap.put(bugsnag, true);
}
static void disable(Bugsnag bugsnag) {
// Find the Bugsnag ExceptionHandler
UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
if (currentHandler instanceof ExceptionHandler) {
// Unsubscribe this bugsnag from uncaught exceptions
ExceptionHandler bugsnagHandler = (ExceptionHandler) currentHandler;
bugsnagHandler.clientMap.remove(bugsnag);
// Remove the Bugsnag ExceptionHandler if no clients are subscribed
if (bugsnagHandler.clientMap.size() == 0) {
Thread.setDefaultUncaughtExceptionHandler(bugsnagHandler.originalHandler);
}
}
}
ExceptionHandler(UncaughtExceptionHandler originalHandler) {
this.originalHandler = originalHandler;
}
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
// Notify any subscribed clients of the uncaught exception
for (Bugsnag bugsnag : clientMap.keySet()) {
if (bugsnag.getConfig().shouldSendUncaughtExceptions()) {
HandledState handledState = HandledState.newInstance(
HandledState.SeverityReasonType.REASON_UNHANDLED_EXCEPTION, Severity.ERROR);
bugsnag.notify(throwable, handledState, thread);
}
}
// Pass exception on to original exception handler
if (originalHandler != null) {
originalHandler.uncaughtException(thread, throwable);
} else {
// Emulate the java exception print style
System.err.printf("Exception in thread \"%s\" ", thread.getName());
throwable.printStackTrace(System.err);
}
}
} |
package fm.libre.droid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URI;
import java.net.URL;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class LibreService extends Service implements OnBufferingUpdateListener, OnCompletionListener {
private LibreServiceBinder serviceBinder = new LibreServiceBinder();
private Playlist playlist;
private String sessionKey;
private String scrobbleKey;
private String serviceToken;
private String stationName;
private int currentSong;
private int currentPage = 0;
private boolean loggedIn = false;
private boolean playing = false;
private boolean buffering = false;
private MediaPlayer mp;
@Override
public void onCreate() {
super.onCreate();
this.mp = new MediaPlayer();
this.currentSong = 0;
this.playlist = new Playlist();
this.sessionKey = "";
}
@Override
public IBinder onBind(Intent intent) {
return serviceBinder;
}
@Override
public void onDestroy() {
this.mp.release();
}
public String httpGet(String url) throws URISyntaxException, ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
URI uri = new URI(url);
HttpGet method = new HttpGet(uri);
HttpResponse res = client.execute(method);
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
res.getEntity().writeTo(outstream);
return outstream.toString();
}
public String httpPost(String url, String... params) throws URISyntaxException, ClientProtocolException, IOException {
DefaultHttpClient client = new DefaultHttpClient();
URI uri = new URI(url);
HttpPost method = new HttpPost(uri);
List<NameValuePair> paramPairs = new ArrayList<NameValuePair>(2);
for (int i = 0; i < params.length; i+=2) {
paramPairs.add(new BasicNameValuePair(params[i], params[i+1]));
}
method.setEntity(new UrlEncodedFormEntity(paramPairs));
method.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); // Disable expect-continue, caching server doesn't like this
HttpResponse res = client.execute(method);
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
res.getEntity().writeTo(outstream);
return outstream.toString();
}
public boolean login(String username, String password) {
loggedIn = false;
String passMD5 = "";
String token = "";
String wsToken = "";
long timestamp = new Date().getTime() / 1000;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes(), 0, password.length());
passMD5 = new BigInteger(1, md.digest()).toString(16);
if (passMD5.length() == 31) {
passMD5 = "0" + passMD5;
}
token = passMD5 + Long.toString(timestamp);
md.update(token.getBytes(), 0, token.length());
token = new BigInteger(1, md.digest()).toString(16);
if (token.length() == 31) {
token = "0" + token;
}
wsToken = username + passMD5;
md.update(wsToken.getBytes(), 0, wsToken.length());
wsToken = new BigInteger(1, md.digest()).toString(16);
if (wsToken.length() == 31) {
wsToken = "0" + wsToken;
}
} catch (NoSuchAlgorithmException ex) {
Toast.makeText(this, "MD5 hashing unavailable, unable to login.", Toast.LENGTH_LONG);
}
try {
// Login for streaming
String output = this.httpGet("http://alpha.libre.fm/radio/handshake.php?username=" + username + "&passwordmd5=" + passMD5);
if (output.trim().equals("BADAUTH")) {
Toast.makeText(this, "Incorrect username or password", Toast.LENGTH_SHORT).show();
} else {
String[] result = output.split("[=\n]");
for (int x=0; x<result.length; x++) {
if (result[x].trim().equals("session")) {
this.sessionKey = result[x+1].trim();
}
}
loggedIn = true;
}
// Login for scrobbling
output = this.httpGet("http://turtle.libre.fm/?hs=true&p=1.2&u=" + username + "&t=" + Long.toString(timestamp) + "&a=" + token + "&c=ldr" );
if (output.split("\n")[0].equals("OK")) {
this.scrobbleKey = output.split("\n")[1].trim();
}
// Login for web services
output = this.httpGet("http://alpha.libre.fm/2.0/?method=auth.getmobilesession&username=" + username + "&authToken=" + wsToken);
WSParser wsp = new WSParser();
wsp.parse(output);
this.serviceToken = wsp.getKey();
} catch (Exception ex) {
Toast.makeText(this, "Unable to connect to libre.fm server: " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
return loggedIn;
}
public boolean isLoggedIn() {
return loggedIn;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
if (percent > 2 && !mp.isPlaying() && this.playing) {
this.mp.start();
}
if (percent > 99) {
this.buffering = false;
}
}
public void onCompletion(MediaPlayer mp) {
if(!this.buffering) { // We get spurious complete messages if we're still buffering
// Scrobble
Song song = this.playlist.getSong(this.currentSong);
try {
String time = Long.toString(new Date().getTime() / 1000);
this.httpPost("http://turtle.libre.fm/submissions/1.2/", "s", this.scrobbleKey, "a[0]", song.artist, "t[0]", song.title, "b[0]", song.album, "i[0]", time);
} catch (Exception ex) {
Log.d("libredroid", "Couldn't scrobble: " + ex.getMessage());
}
this.next();
}
}
public void play() {
if (this.currentSong >= this.playlist.size()) {
this.getPlaylist();
}
this.playing = true;
this.buffering = true;
Song song = this.playlist.getSong(currentSong);
Log.d("libredroid", "Song: " + this.playlist);
try {
this.mp.reset();
// Hack to get Jamendo MP3 stream instead of OGG because MediaPlayer
// doesn't support streaming OGG at the moment.
URL url = new URL(song.location.replace("ogg2", "mp31"));
// Hack2: Froyo's new streaming mechanism is massively broken and fails
// when presented with a HTTP redirection message so we have to resolve
// it first.
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setInstanceFollowRedirects(false);
conn.connect();
if(conn.getResponseCode() == 307) {
Log.d("libredroid", "Got a HTTP redirection for " + url.toString() + ". Resolves to: " + conn.getHeaderField("Location") + " (resolving it ourselves to avoid Froyo's incomplete HTTP streaming implementation)");
this.mp.setDataSource(conn.getHeaderField("Location"));
} else {
this.mp.setDataSource(url.toString());
}
conn.disconnect();
this.mp.setOnBufferingUpdateListener(this);
this.mp.setOnCompletionListener(this);
this.mp.prepareAsync();
// Send now playing data
this.httpPost("http://turtle.libre.fm/nowplaying/1.2/", "s", this.scrobbleKey, "a", song.artist, "t", song.title);
} catch (Exception ex) {
Log.d("libredroid", "Couldn't play " + song.title + ": " + ex.getMessage());
this.next();
}
this.sendBroadcast(new Intent("LibreDroidNewSong"));
}
public void next() {
mp.stop();
this.currentSong++;
this.play();
}
public void prev() {
if (this.currentSong > 0) {
mp.stop();
this.currentSong
this.play();
}
}
public void stop() {
mp.stop();
}
public void love() {
Song song = this.getSong();
try {
this.httpPost("http://alpha.libre.fm/2.0/", "method", "track.love", "sk", this.serviceToken, "artist", song.artist, "track", song.title);
Toast.makeText(this, "Loved", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
Log.d("libredroid", "Couldn't love " + song.title + ": " + ex.getMessage());
}
}
public void ban() {
Song song = this.getSong();
try {
this.httpPost("http://alpha.libre.fm/2.0/", "method", "track.ban", "sk", this.serviceToken, "artist", song.artist, "track", song.title);
Toast.makeText(this, "Banned", Toast.LENGTH_SHORT).show();
} catch (Exception ex) {
Log.d("libredroid", "Couldn't ban " + song.title + ": " + ex.getMessage());
}
this.next();
}
public Song getSong() {
return this.getSong(this.currentSong);
}
public Song getSong(int songNumber) {
return this.playlist.getSong(songNumber);
}
public void togglePause() {
if(this.playing) {
mp.pause();
} else {
mp.start();
}
this.playing = !this.playing;
}
public void getPlaylist() {
try {
String xspf = this.httpGet("http://alpha.libre.fm/radio/xspf.php?sk=" + this.sessionKey + "&desktop=1.0");
this.playlist.parse(xspf);
} catch (Exception ex) {
Log.w("libredroid", "Unable to process playlist: " + ex.getMessage());
Toast.makeText(this, "Unable to process playlist: " + ex.getMessage(), Toast.LENGTH_LONG).show();
}
}
public boolean isPlaying() {
return this.playing;
}
public void tuneStation(String type, String station) {
Toast.makeText(this, "Tuning in...", Toast.LENGTH_LONG).show();
new TuneStationTask().execute(type, station);
}
private class TuneStationTask extends AsyncTask<String,String,String> {
protected String doInBackground(String... params) {
String type = params[0];
String station = params[1];
String result = "";
try {
result = LibreService.this.httpGet("http://alpha.libre.fm/radio/adjust.php?session=" + LibreService.this.sessionKey + "&url=librefm://" + type + "/" + station);
} catch (Exception ex) {
Log.w("libredroid", "Unable to tune station: " + ex.getMessage());
}
return result;
}
protected void onPostExecute(String output) {
if (output.length() == 0) {
return;
}
LibreService.this.playlist = new Playlist();
if (output.split(" ")[0].equals("FAILED")) {
Toast.makeText(LibreService.this, output.substring(7), Toast.LENGTH_LONG).show();
} else {
String[] result = output.split("[=\n]");
for (int x=0; x<result.length; x++) {
if (result[x].trim().equals("stationname")) {
LibreService.this.stationName = result[x+1].trim();
}
}
LibreService.this.play();
}
}
}
public String getStationName() {
return LibreService.this.stationName;
}
public class LibreServiceBinder extends Binder implements ILibreService {
public boolean login(String username, String password) {
return LibreService.this.login(username, password);
}
public boolean isLoggedIn() {
return LibreService.this.isLoggedIn();
}
public boolean isPlaying() {
return LibreService.this.isPlaying();
}
public void stop() {
LibreService.this.stop();
}
public void play() {
LibreService.this.play();
}
public void next() {
LibreService.this.next();
}
public void prev() {
LibreService.this.prev();
}
public void love() {
LibreService.this.love();
}
public void ban() {
LibreService.this.ban();
}
public Song getSong() {
return LibreService.this.getSong();
}
public Song getSong(int songNumber) {
return LibreService.this.getSong(songNumber);
}
public void tuneStation(String type, String station) {
LibreService.this.tuneStation(type, station);
}
public void setCurrentPage(int page) {
LibreService.this.currentPage = page;
}
public int getCurrentPage() {
return LibreService.this.currentPage;
}
public void togglePause() {
LibreService.this.togglePause();
}
public String getStationName() {
return LibreService.this.getStationName();
}
}
} |
package org.jetel.util.string;
import java.text.CollationElementIterator;
import java.text.RuleBasedCollator;
/**
* Miscelaneous comparison utilities
*
* @author David Pavlis
* @since 18.11.2005
*
*/
public class Compare {
/**
* Compares two sequences lexicographically
*
* @param a
* @param b
* @return -1;0;1 if (a>b); (a==b); (a<b)
*/
final static public int compare(CharSequence a,CharSequence b){
int aLength = a.length();
int bLength = b.length();
int compLength = (aLength< bLength ? aLength : bLength );
for (int i = 0; i < compLength; i++) {
if (a.charAt(i) > b.charAt(i)) {
return 1;
} else if (a.charAt(i) < b.charAt(i)) {
return -1;
}
}
// strings seem to be the same (so far), decide according to the length
if (aLength == bLength) {
return 0;
} else if (aLength > bLength) {
return 1;
} else {
return -1;
}
}
final static public int compare(CharSequence a,CharSequence b,RuleBasedCollator col){
CollationElementIterator iterA = col.getCollationElementIterator(
new CharSequenceCharacterIterator(a));
CollationElementIterator iterB = col.getCollationElementIterator(
new CharSequenceCharacterIterator(b));
int elementA,elementB;
int orderA,orderB;
while ((elementA = iterA.next()) != CollationElementIterator.NULLORDER) {
elementB=iterB.next();
if (elementB != CollationElementIterator.NULLORDER){
// check primary order
orderA=CollationElementIterator.primaryOrder(elementA);
orderB=CollationElementIterator.primaryOrder(elementB);
if (orderA!=orderB){
return orderA-orderB;
}
orderA=CollationElementIterator.secondaryOrder(elementA);
orderB=CollationElementIterator.secondaryOrder(elementB);
if (orderA!=orderB){
return orderA-orderB;
}
orderA=CollationElementIterator.tertiaryOrder(elementA);
orderB=CollationElementIterator.tertiaryOrder(elementB);
if (orderA!=orderB){
return orderA-orderB;
}
}else{
return 1; // first sequence seems to be longer than second
}
}
elementB = iterB.next();
if (elementB != CollationElementIterator.NULLORDER){
return -1; // second sequence seems to be longer than first
}else{
return 0; // equal
}
}
} |
package edu.umd.cs.findbugs.detect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.EnumMap;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.CodeException;
import org.apache.bcel.classfile.JavaClass;
import edu.umd.cs.findbugs.BugAccumulator;
import edu.umd.cs.findbugs.BugAnnotation;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.FieldAnnotation;
import edu.umd.cs.findbugs.IntAnnotation;
import edu.umd.cs.findbugs.LocalVariableAnnotation;
import edu.umd.cs.findbugs.MethodAnnotation;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.OpcodeStack.Item;
import edu.umd.cs.findbugs.Priorities;
import edu.umd.cs.findbugs.SourceLineAnnotation;
import edu.umd.cs.findbugs.StringAnnotation;
import edu.umd.cs.findbugs.SystemProperties;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.ba.XMethod;
import edu.umd.cs.findbugs.ba.ch.Subtypes2;
import edu.umd.cs.findbugs.bcel.OpcodeStackDetector;
import edu.umd.cs.findbugs.classfile.ClassDescriptor;
import edu.umd.cs.findbugs.classfile.DescriptorFactory;
import edu.umd.cs.findbugs.classfile.FieldDescriptor;
import edu.umd.cs.findbugs.visitclass.Util;
public class FindPuzzlers extends OpcodeStackDetector {
static FieldDescriptor SYSTEM_OUT = new FieldDescriptor("java/lang/System", "out", "Ljava/io/PrintStream;", true);
static FieldDescriptor SYSTEM_ERR = new FieldDescriptor("java/lang/System", "err", "Ljava/io/PrintStream;", true);
final BugReporter bugReporter;
final BugAccumulator bugAccumulator;
private final boolean testingEnabled;
public FindPuzzlers(BugReporter bugReporter) {
this.bugReporter = bugReporter;
this.bugAccumulator = new BugAccumulator(bugReporter);
testingEnabled = SystemProperties.getBoolean("report_TESTING_pattern_in_standard_detectors");
}
@Override
public void visit(Code obj) {
prevOpcodeIncrementedRegister = -1;
best_priority_for_ICAST_INTEGER_MULTIPLY_CAST_TO_LONG = LOW_PRIORITY + 1;
prevOpCode = NOP;
previousMethodInvocation = null;
badlyComputingOddState = 0;
resetIMulCastLong();
imul_distance = 10000;
ternaryConversionState = 0;
becameTop = -1;
super.visit(obj);
bugAccumulator.reportAccumulatedBugs();
pendingUnreachableBranch = null;
}
int becameTop;
int imul_constant;
int imul_distance;
boolean imul_operand_is_parameter;
int prevOpcodeIncrementedRegister;
int valueOfConstantArgumentToShift;
int best_priority_for_ICAST_INTEGER_MULTIPLY_CAST_TO_LONG;
boolean constantArgumentToShift;
boolean shiftOfNonnegativeValue;
int ternaryConversionState = 0;
int badlyComputingOddState;
int prevOpCode;
XMethod previousMethodInvocation;
boolean isTigerOrHigher;
static ClassDescriptor ITERATOR = DescriptorFactory.createClassDescriptor(Iterator.class);
static ClassDescriptor MAP_ENTRY = DescriptorFactory.createClassDescriptor(Map.Entry.class);
@Override
public void visit(JavaClass obj) {
isTigerOrHigher = obj.getMajor() >= MAJOR_1_5;
try {
Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2();
ClassDescriptor me = getClassDescriptor();
if (subtypes2.isSubtype(me, MAP_ENTRY) && subtypes2.isSubtype(me, ITERATOR)) {
bugReporter.reportBug(new BugInstance(this, "PZ_DONT_REUSE_ENTRY_OBJECTS_IN_ITERATORS", NORMAL_PRIORITY)
.addClass(this).addString("shouldn't reuse Iterator as a Map.Entry"));
}
} catch (ClassNotFoundException e) {
AnalysisContext.reportMissingClass(e);
}
}
private void resetIMulCastLong() {
imul_constant = 1;
imul_operand_is_parameter = false;
}
private int adjustPriority(int factor, int priority) {
if (factor <= 4) {
return LOW_PRIORITY + 2;
}
if (factor <= 10000) {
return priority + 1;
}
if (factor <= 60 * 60 * 1000) {
return priority;
}
return priority - 1;
}
private int adjustMultiplier(Object constant, int mul) {
if (!(constant instanceof Integer)) {
return mul;
}
return Math.abs(((Integer) constant).intValue()) * mul;
}
@Override
public boolean beforeOpcode(int seen) {
super.beforeOpcode(seen);
return true;
}
BugInstance pendingUnreachableBranch;
@Override
public void sawOpcode(int seen) {
if (stack.isTop()) {
pendingUnreachableBranch = null;
if (becameTop == -1) {
becameTop = getPC();
}
if (testingEnabled && seen == GOTO && getBranchTarget() < becameTop) {
pendingUnreachableBranch = new BugInstance(this, "TESTING", NORMAL_PRIORITY)
.addClassAndMethod(this).addString("Unreachable loop body").addSourceLineRange(this, becameTop, getPC());
}
return;
}
if (pendingUnreachableBranch != null) {
bugReporter.reportBug(pendingUnreachableBranch);
pendingUnreachableBranch = null;
}
becameTop = -1;
if (seen == INVOKESPECIAL && "<init>".equals(getNameConstantOperand()) && "(Ljava/util/Collection;)V".equals(getSigConstantOperand())
&& getClassConstantOperand().contains("Set")
|| (seen == INVOKEVIRTUAL || seen == INVOKEINTERFACE) && "addAll".equals(getNameConstantOperand()) && "(Ljava/util/Collection;)Z".equals(getSigConstantOperand())) {
OpcodeStack.Item top = stack.getStackItem(0);
XMethod returnValueOf = top.getReturnValueOf();
if (returnValueOf != null && "entrySet".equals(returnValueOf.getName())) {
String name = returnValueOf.getClassName();
int priority = Priorities.LOW_PRIORITY;
if ("java.util.Map".equals(name)) {
priority = Priorities.NORMAL_PRIORITY;
} else if (name.equals(EnumMap.class.getName())
|| name.equals(IdentityHashMap.class.getName())) {
priority = Priorities.HIGH_PRIORITY;
}
bugReporter.reportBug(new BugInstance(this, "DMI_ENTRY_SETS_MAY_REUSE_ENTRY_OBJECTS", priority)
.addClassAndMethod(this).addCalledMethod(returnValueOf).addCalledMethod(this).addValueSource(top, this).addSourceLine(this));
}
}
if (seen == INVOKEVIRTUAL && "hashCode".equals(getNameConstantOperand()) && "()I".equals(getSigConstantOperand())
&& stack.getStackDepth() > 0) {
OpcodeStack.Item item0 = stack.getStackItem(0);
if (item0.getSignature().charAt(0) == '[') {
bugReporter.reportBug(new BugInstance(this, "DMI_INVOKING_HASHCODE_ON_ARRAY", NORMAL_PRIORITY)
.addClassAndMethod(this).addValueSource(item0, this).addSourceLine(this));
}
}
if (seen != RETURN && isReturn(seen) && isRegisterStore(getPrevOpcode(1))) {
int priority = Priorities.NORMAL_PRIORITY;
if (getMethodSig().endsWith(")Z")) {
priority = Priorities.HIGH_PRIORITY;
} else {
if (getMethodSig().endsWith(")Ljava/lang/String;")) {
priority = Priorities.LOW_PRIORITY;
}
if (getPC() == getCode().getCode().length - 1) {
priority++;
}
}
bugReporter.reportBug(new BugInstance(this, "DLS_DEAD_LOCAL_STORE_IN_RETURN", priority).addClassAndMethod(this)
.addSourceLine(this));
}
// System.out.println(getPC() + " " + OPCODE_NAMES[seen] + " " +
// ternaryConversionState);
if (seen == IMUL) {
if (imul_distance != 1) {
resetIMulCastLong();
}
imul_distance = 0;
if (stack.getStackDepth() > 1) {
OpcodeStack.Item item0 = stack.getStackItem(0);
OpcodeStack.Item item1 = stack.getStackItem(1);
imul_constant = adjustMultiplier(item0.getConstant(), imul_constant);
imul_constant = adjustMultiplier(item1.getConstant(), imul_constant);
if (item0.isInitialParameter() || item1.isInitialParameter()) {
imul_operand_is_parameter = true;
}
}
} else {
imul_distance++;
}
if (prevOpCode == IMUL && seen == I2L) {
int priority = adjustPriority(imul_constant, NORMAL_PRIORITY);
if (priority >= LOW_PRIORITY && imul_constant != 1000 && imul_constant != 60 && imul_operand_is_parameter) {
priority = NORMAL_PRIORITY;
}
if (priority <= best_priority_for_ICAST_INTEGER_MULTIPLY_CAST_TO_LONG) {
best_priority_for_ICAST_INTEGER_MULTIPLY_CAST_TO_LONG = priority;
bugAccumulator.accumulateBug(
new BugInstance(this, "ICAST_INTEGER_MULTIPLY_CAST_TO_LONG", priority).addClassAndMethod(this), this);
}
}
if ("<clinit>".equals(getMethodName()) && (seen == PUTSTATIC || seen == GETSTATIC || seen == INVOKESTATIC)) {
String clazz = getClassConstantOperand();
if (!clazz.equals(getClassName())) {
try {
JavaClass targetClass = Repository.lookupClass(clazz);
if (Repository.instanceOf(targetClass, getThisClass())) {
int priority = NORMAL_PRIORITY;
if (seen == GETSTATIC) {
priority
}
if (!targetClass.isPublic()) {
priority++;
}
bugAccumulator.accumulateBug(new BugInstance(this, "IC_SUPERCLASS_USES_SUBCLASS_DURING_INITIALIZATION",
priority).addClassAndMethod(this).addClass(getClassConstantOperand()), this);
}
} catch (ClassNotFoundException e) {
// ignore it
}
}
}
/*
if (false && (seen == INVOKEVIRTUAL) && getNameConstantOperand().equals("equals")
&& getSigConstantOperand().equals("(Ljava/lang/Object;)Z") && stack.getStackDepth() > 1) {
OpcodeStack.Item item0 = stack.getStackItem(0);
OpcodeStack.Item item1 = stack.getStackItem(1);
if (item0.isArray() || item1.isArray()) {
bugAccumulator.accumulateBug(
new BugInstance(this, "EC_BAD_ARRAY_COMPARE", NORMAL_PRIORITY).addClassAndMethod(this), this);
}
}
*/
if (seen >= IALOAD && seen <= SALOAD || seen >= IASTORE && seen <= SASTORE) {
Item index = stack.getStackItem(0);
if (index.getSpecialKind() == Item.AVERAGE_COMPUTED_USING_DIVISION) {
SourceLineAnnotation where;
if (index.getPC() >= 0) {
where = SourceLineAnnotation.fromVisitedInstruction(this, index.getPC());
} else {
where = SourceLineAnnotation.fromVisitedInstruction(this);
}
bugAccumulator.accumulateBug(
new BugInstance(this, "IM_AVERAGE_COMPUTATION_COULD_OVERFLOW", NORMAL_PRIORITY).addClassAndMethod(this),
where);
}
}
if ((seen == IFEQ || seen == IFNE) && getPrevOpcode(1) == IMUL
&& (getPrevOpcode(2) == SIPUSH || getPrevOpcode(2) == BIPUSH) && getPrevOpcode(3) == IREM) {
bugAccumulator.accumulateBug(
new BugInstance(this, "IM_MULTIPLYING_RESULT_OF_IREM", LOW_PRIORITY).addClassAndMethod(this), this);
}
if (seen == I2S && getPrevOpcode(1) == IUSHR && !shiftOfNonnegativeValue
&& (!constantArgumentToShift || valueOfConstantArgumentToShift % 16 != 0) || seen == I2B
&& getPrevOpcode(1) == IUSHR && !shiftOfNonnegativeValue
&& (!constantArgumentToShift || valueOfConstantArgumentToShift % 8 != 0)) {
bugAccumulator.accumulateBug(
new BugInstance(this, "ICAST_QUESTIONABLE_UNSIGNED_RIGHT_SHIFT", NORMAL_PRIORITY).addClassAndMethod(this),
this);
}
if (seen == IADD && (getNextOpcode() == ISHL || getNextOpcode() == LSHL) && stack.getStackDepth() >=3) {
OpcodeStack.Item l = stack.getStackItem(2);
OpcodeStack.Item v = stack.getStackItem(1);
Object constantValue = v.getConstant();
// Ignore 1 << (const + var) as it's usually intended
if (constantValue instanceof Integer && !Integer.valueOf(1).equals(l.getConstant())) {
int c = ((Integer) constantValue).intValue();
int priority = LOW_PRIORITY;
// If (foo << 32 + var) encountered, then ((foo << 32) + var) is absolutely meaningless,
// but (foo << (32 + var)) can be meaningful for negative var values
if (c < 32 || (c < 64 && getNextOpcode() == LSHL)) {
if (c == 8) {
priority
}
if (getPrevOpcode(1) == IAND) {
priority
}
if (getMethodName().equals("hashCode") && getMethodSig().equals("()I")
&& (getCode().getCode()[getNextPC() + 1] & 0xFF) == IRETURN) {
// commonly observed error is hashCode body like "return foo << 16 + bar;"
priority = HIGH_PRIORITY;
}
bugAccumulator.accumulateBug(new BugInstance(this, "TESTING", priority)
.addClassAndMethod(this)
.addString("Possible bad parsing of shift operation; shift operator has lower precedence than +").describe(StringAnnotation.STRING_MESSAGE)
.addInt(c).describe(IntAnnotation.INT_SHIFT)
.addValueSource(stack.getStackItem(2), this)
.addValueSource(stack.getStackItem(1), this)
.addValueSource(stack.getStackItem(0), this)
, this);
}
}
}
constantArgumentToShift = false;
shiftOfNonnegativeValue = false;
if ((seen == IUSHR || seen == ISHR || seen == ISHL)) {
if (stack.getStackDepth() <= 1) {
// don't understand; lie so other detectors won't get concerned
constantArgumentToShift = true;
valueOfConstantArgumentToShift = 8;
} else {
Object rightHandSide = stack.getStackItem(0).getConstant();
Object leftHandSide = stack.getStackItem(1).getConstant();
shiftOfNonnegativeValue = stack.getStackItem(1).isNonNegative();
if (rightHandSide instanceof Integer) {
constantArgumentToShift = true;
valueOfConstantArgumentToShift = ((Integer) rightHandSide);
if (valueOfConstantArgumentToShift < 0 || valueOfConstantArgumentToShift >= 32) {
bugAccumulator.accumulateBug(new BugInstance(this, "ICAST_BAD_SHIFT_AMOUNT",
valueOfConstantArgumentToShift < 0 ? LOW_PRIORITY : (valueOfConstantArgumentToShift == 32
&& "hashCode".equals(getMethodName()) ? NORMAL_PRIORITY : HIGH_PRIORITY))
.addClassAndMethod(this).addInt(valueOfConstantArgumentToShift).describe(IntAnnotation.INT_SHIFT)
.addValueSource(stack.getStackItem(1), this), this);
}
}
if (leftHandSide != null && leftHandSide instanceof Integer && ((Integer) leftHandSide) > 0) {
// boring; lie so other detectors won't get concerned
constantArgumentToShift = true;
valueOfConstantArgumentToShift = 8;
}
}
}
if (seen == INVOKEVIRTUAL && stack.getStackDepth() > 0
&& ("java/util/Date".equals(getClassConstantOperand()) || "java/sql/Date".equals(getClassConstantOperand()))
&& "setMonth".equals(getNameConstantOperand()) && "(I)V".equals(getSigConstantOperand())) {
OpcodeStack.Item item = stack.getStackItem(0);
Object o = item.getConstant();
if (o != null && o instanceof Integer) {
int v = (Integer) o;
if (v < 0 || v > 11) {
bugReporter.reportBug(new BugInstance(this, "DMI_BAD_MONTH", HIGH_PRIORITY).addClassAndMethod(this).addInt(v)
.describe(IntAnnotation.INT_VALUE).addCalledMethod(this).addSourceLine(this));
}
}
}
if (seen == INVOKEVIRTUAL && stack.getStackDepth() > 1 && "java/util/Calendar".equals(getClassConstantOperand())
&& "set".equals(getNameConstantOperand())
|| seen == INVOKESPECIAL && stack.getStackDepth() > 1
&& "java/util/GregorianCalendar".equals(getClassConstantOperand()) && "<init>".equals(getNameConstantOperand())
) {
String sig = getSigConstantOperand();
if (sig.startsWith("(III")) {
int pos = sig.length() - 5;
OpcodeStack.Item item = stack.getStackItem(pos);
Object o = item.getConstant();
if (o != null && o instanceof Integer) {
int v = (Integer) o;
if (v < 0 || v > 11) {
bugReporter.reportBug(new BugInstance(this, "DMI_BAD_MONTH", NORMAL_PRIORITY).addClassAndMethod(this)
.addInt(v).describe(IntAnnotation.INT_VALUE).addCalledMethod(this).addSourceLine(this));
}
}
}
}
if (isRegisterStore() && (seen == ISTORE || seen == ISTORE_0 || seen == ISTORE_1 || seen == ISTORE_2 || seen == ISTORE_3)
&& getRegisterOperand() == prevOpcodeIncrementedRegister) {
bugAccumulator.accumulateBug(
new BugInstance(this, "DLS_OVERWRITTEN_INCREMENT", HIGH_PRIORITY).addClassAndMethod(this), this);
}
if (seen == IINC) {
prevOpcodeIncrementedRegister = getRegisterOperand();
} else {
prevOpcodeIncrementedRegister = -1;
}
// Java Puzzlers, Chapter 2, puzzle 1
// Look for ICONST_2 IREM ICONST_1 IF_ICMPNE L1
switch (badlyComputingOddState) {
case 0:
if (seen == ICONST_2) {
badlyComputingOddState++;
}
break;
case 1:
if (seen == IREM) {
OpcodeStack.Item item = stack.getStackItem(1);
if (!item.isNonNegative() && item.getSpecialKind() != OpcodeStack.Item.MATH_ABS) {
badlyComputingOddState++;
} else {
badlyComputingOddState = 0;
}
} else {
badlyComputingOddState = 0;
}
break;
case 2:
if (seen == ICONST_1) {
badlyComputingOddState++;
} else {
badlyComputingOddState = 0;
}
break;
case 3:
if (seen == IF_ICMPEQ || seen == IF_ICMPNE) {
bugAccumulator.accumulateBug(
new BugInstance(this, "IM_BAD_CHECK_FOR_ODD", NORMAL_PRIORITY).addClassAndMethod(this), this);
}
badlyComputingOddState = 0;
break;
default:
break;
}
// Java Puzzlers, chapter 3, puzzle 12
if (seen == INVOKEVIRTUAL
&& stack.getStackDepth() > 0
&& ("toString".equals(getNameConstantOperand()) && "()Ljava/lang/String;".equals(getSigConstantOperand())
|| "append".equals(getNameConstantOperand())
&& "(Ljava/lang/Object;)Ljava/lang/StringBuilder;".equals(getSigConstantOperand())
&& "java/lang/StringBuilder".equals(getClassConstantOperand())
|| "append".equals(getNameConstantOperand())
&& "(Ljava/lang/Object;)Ljava/lang/StringBuffer;".equals(getSigConstantOperand())
&& "java/lang/StringBuffer".equals(getClassConstantOperand()) || ("print".equals(getNameConstantOperand()) || "println".equals(getNameConstantOperand()))
&& "(Ljava/lang/Object;)V".equals(getSigConstantOperand()))) {
OpcodeStack.Item item = stack.getStackItem(0);
String signature = item.getSignature();
if (signature != null && signature.startsWith("[")) {
boolean debuggingContext = "[Ljava/lang/StackTraceElement;".equals(signature);
if (!debuggingContext) {
for (CodeException e : getCode().getExceptionTable()) {
if (e.getHandlerPC() <= getPC() && e.getHandlerPC() + 30 >= getPC()) {
debuggingContext = true;
}
}
for (int i = 1; !debuggingContext && i < stack.getStackDepth(); i++) {
OpcodeStack.Item e = stack.getStackItem(i);
if (e.getSignature().indexOf("Logger") >= 0 || e.getSignature().indexOf("Exception") >= 0) {
debuggingContext = true;
}
XField f = e.getXField();
if (f != null && (SYSTEM_ERR.equals(f.getFieldDescriptor()) || SYSTEM_OUT.equals(f.getFieldDescriptor()))) {
debuggingContext = true;
}
}
}
// String name = null;
int reg = item.getRegisterNumber();
Collection<BugAnnotation> as = new ArrayList<BugAnnotation>();
XField field = item.getXField();
FieldAnnotation fieldAnnotation = null;
if (field != null) {
fieldAnnotation = FieldAnnotation.fromXField(field);
fieldAnnotation.setDescription(FieldAnnotation.LOADED_FROM_ROLE);
}
if (reg != -1) {
LocalVariableAnnotation lva = LocalVariableAnnotation.getLocalVariableAnnotation(getMethod(), reg, getPC(),
getPC() - 1);
if (lva.isNamed()) {
as.add(lva);
if (fieldAnnotation != null) {
as.add(fieldAnnotation);
}
} else {
if (fieldAnnotation != null) {
as.add(fieldAnnotation);
}
as.add(lva);
}
} else if (fieldAnnotation != null) {
as.add(fieldAnnotation);
} else {
XMethod m = item.getReturnValueOf();
if (m != null) {
MethodAnnotation methodAnnotation = MethodAnnotation.fromXMethod(m);
methodAnnotation.setDescription(MethodAnnotation.METHOD_RETURN_VALUE_OF);
as.add(methodAnnotation);
}
}
int priority = debuggingContext ? NORMAL_PRIORITY : HIGH_PRIORITY;
if (!as.isEmpty()) {
bugAccumulator.accumulateBug(new BugInstance(this, "DMI_INVOKING_TOSTRING_ON_ARRAY", priority)
.addClassAndMethod(this).addAnnotations(as), this);
} else {
bugAccumulator.accumulateBug(
new BugInstance(this, "DMI_INVOKING_TOSTRING_ON_ANONYMOUS_ARRAY", priority).addClassAndMethod(this),
this);
}
}
}
if (isTigerOrHigher) {
if (previousMethodInvocation != null && prevOpCode == INVOKEVIRTUAL && seen == INVOKESTATIC) {
String classNameForPreviousMethod = previousMethodInvocation.getClassName();
String classNameForThisMethod = getClassConstantOperand();
if (classNameForPreviousMethod.startsWith("java.lang.")
&& classNameForPreviousMethod.equals(classNameForThisMethod.replace('/', '.'))
&& previousMethodInvocation.getName().endsWith("Value")
&& previousMethodInvocation.getSignature().length() == 3
&& "valueOf".equals(getNameConstantOperand())
&& getSigConstantOperand().charAt(1) == previousMethodInvocation.getSignature().charAt(2)) {
bugAccumulator.accumulateBug(
new BugInstance(this, "BX_UNBOXING_IMMEDIATELY_REBOXED", NORMAL_PRIORITY).addClassAndMethod(this)
.addCalledMethod(this),
this);
}
}
if (previousMethodInvocation != null && prevOpCode == INVOKESPECIAL && seen == INVOKEVIRTUAL) {
String classNameForPreviousMethod = previousMethodInvocation.getClassName();
String classNameForThisMethod = getClassConstantOperand();
if (classNameForPreviousMethod.startsWith("java.lang.")
&& classNameForPreviousMethod.equals(classNameForThisMethod.replace('/', '.'))
&& getNameConstantOperand().endsWith("Value") && getSigConstantOperand().length() == 3) {
if (getSigConstantOperand().charAt(2) == previousMethodInvocation.getSignature().charAt(1)) {
bugAccumulator.accumulateBug(
new BugInstance(this, "BX_BOXING_IMMEDIATELY_UNBOXED", NORMAL_PRIORITY).addClassAndMethod(this),
this);
} else {
bugAccumulator.accumulateBug(new BugInstance(this, "BX_BOXING_IMMEDIATELY_UNBOXED_TO_PERFORM_COERCION",
NORMAL_PRIORITY).addClassAndMethod(this), this);
}
ternaryConversionState = 1;
} else {
ternaryConversionState = 0;
}
} else if (seen == INVOKEVIRTUAL) {
if (getClassConstantOperand().startsWith("java/lang") && getNameConstantOperand().endsWith("Value")
&& getSigConstantOperand().length() == 3) {
ternaryConversionState = 1;
} else {
ternaryConversionState = 0;
}
} else if (ternaryConversionState == 1) {
if (I2L < seen && seen <= I2S) {
ternaryConversionState = 2;
} else {
ternaryConversionState = 0;
}
} else if (ternaryConversionState == 2) {
ternaryConversionState = 0;
if (seen == GOTO) {
bugReporter.reportBug(new BugInstance(this, "BX_UNBOXED_AND_COERCED_FOR_TERNARY_OPERATOR", NORMAL_PRIORITY)
.addClassAndMethod(this).addSourceLine(this));
}
} else {
ternaryConversionState = 0;
}
}
AssertInvokedFromRun: if (seen == INVOKESTATIC) {
if ((getNameConstantOperand().startsWith("assert") || getNameConstantOperand().startsWith("fail"))
&& "run".equals(getMethodName()) && implementsRunnable(getThisClass())) {
int size1 = Util.getSizeOfSurroundingTryBlock(getConstantPool(), getMethod().getCode(), "java/lang/Throwable",
getPC());
int size2 = Util.getSizeOfSurroundingTryBlock(getConstantPool(), getMethod().getCode(), "java/lang/Error",
getPC());
int size3 = Util.getSizeOfSurroundingTryBlock(getConstantPool(), getMethod().getCode(),
"java/lang/AssertionFailureError", getPC());
int size = Math.min(Math.min(size1, size2), size3);
if (size == Integer.MAX_VALUE) {
String dottedClassName = getClassConstantOperand().replace('/', '.');
if (!dottedClassName.startsWith("junit")) {
try {
JavaClass targetClass = AnalysisContext.currentAnalysisContext().lookupClass(dottedClassName);
if (!targetClass.getSuperclassName().startsWith("junit")) {
break AssertInvokedFromRun;
}
} catch (ClassNotFoundException e) {
AnalysisContext.reportMissingClass(e);
break AssertInvokedFromRun;
}
}
bugAccumulator.accumulateBug(new BugInstance(this, "IJU_ASSERT_METHOD_INVOKED_FROM_RUN_METHOD",
extendsThread(getThisClass()) ? NORMAL_PRIORITY : LOW_PRIORITY).addClassAndMethod(this), this);
}
}
}
if (seen == INVOKESPECIAL && getClassConstantOperand().startsWith("java/lang/")
&& "<init>".equals(getNameConstantOperand()) && getSigConstantOperand().length() == 4) {
previousMethodInvocation = XFactory.createReferencedXMethod(this);
} else if (seen == INVOKESTATIC && getClassConstantOperand().startsWith("java/lang/")
&& "valueOf".equals(getNameConstantOperand()) && getSigConstantOperand().length() == 4) {
previousMethodInvocation = XFactory.createReferencedXMethod(this);
} else if (seen == INVOKEVIRTUAL && getClassConstantOperand().startsWith("java/lang/")
&& getNameConstantOperand().endsWith("Value")
&& getSigConstantOperand().length() == 3) {
previousMethodInvocation = XFactory.createReferencedXMethod(this);
} else {
previousMethodInvocation = null;
}
if (testingEnabled && seen == IAND || seen == LAND) {
OpcodeStack.Item rhs = stack.getStackItem(0);
OpcodeStack.Item lhs = stack.getStackItem(1);
Object constant = rhs.getConstant();
OpcodeStack.Item value = lhs;
if (constant == null) {
constant = lhs.getConstant();
value = rhs;
}
if (constant instanceof Number && (seen == LAND || value.getSpecialKind() == OpcodeStack.Item.RESULT_OF_L2I)) {
long constantValue = ((Number) constant).longValue();
if ((constantValue == 0xEFFFFFFFL || constantValue == 0xEFFFFFFFFFFFFFFFL || seen == IAND
&& constantValue == 0xEFFFFFFF)) {
bugAccumulator.accumulateBug(new BugInstance(this, "TESTING", seen == LAND ? HIGH_PRIORITY : NORMAL_PRIORITY)
.addClassAndMethod(this).addString("Possible failed attempt to mask lower 31 bits of an int")
.addValueSource(value, this), this);
}
}
}
if (seen == INEG) {
OpcodeStack.Item top = stack.getStackItem(0);
XMethod m = top.getReturnValueOf();
if (m != null) {
if ("compareTo".equals(m.getName()) || "compare".equals(m.getName())) {
bugAccumulator.accumulateBug(new BugInstance(this, "RV_NEGATING_RESULT_OF_COMPARETO", NORMAL_PRIORITY)
.addClassAndMethod(this)
.addCalledMethod(m).addValueSource(top, this), this);
}
}
}
if (seen == IRETURN && ("compareTo".equals(getMethod().getName()) || "compare".equals(getMethod().getName()))) {
OpcodeStack.Item top = stack.getStackItem(0);
Object o = top.getConstant();
if (o instanceof Integer && ((Integer)o).intValue() == Integer.MIN_VALUE) {
bugAccumulator.accumulateBug(new BugInstance(this, "CO_COMPARETO_RESULTS_MIN_VALUE", NORMAL_PRIORITY)
.addClassAndMethod(this), this);
}
}
prevOpCode = seen;
}
boolean implementsRunnable(JavaClass obj) {
return Subtypes2.instanceOf(obj, "java.lang.Runnable");
}
boolean extendsThread(JavaClass obj) {
return Subtypes2.instanceOf(obj, "java.lang.Thread");
}
} |
package edu.umd.cs.findbugs.detect;
import edu.umd.cs.findbugs.*;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.XFactory;
import edu.umd.cs.findbugs.ba.XField;
import edu.umd.cs.findbugs.visitclass.PreorderVisitor;
import java.util.*;
import java.util.regex.Pattern;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.*;
import org.apache.bcel.generic.Type;
public class UnreadFields extends BytecodeScanningDetector {
private static final boolean DEBUG = SystemProperties.getBoolean("unreadfields.debug");
static class ProgramPoint {
ProgramPoint(BytecodeScanningDetector v) {
method = MethodAnnotation.fromVisitedMethod(v);
sourceLine = SourceLineAnnotation
.fromVisitedInstruction(v,v.getPC());
}
MethodAnnotation method;
SourceLineAnnotation sourceLine;
}
Map<XField,HashSet<ProgramPoint> >
assumedNonNull = new HashMap<XField,HashSet<ProgramPoint>>();
Set<XField> nullTested = new HashSet<XField>();
Set<XField> staticFields = new HashSet<XField>();
Set<XField> declaredFields = new TreeSet<XField>();
Set<XField> containerFields = new TreeSet<XField>();
Set<XField> fieldsOfNativeClassed
= new HashSet<XField>();
Set<XField> fieldsOfSerializableOrNativeClassed
= new HashSet<XField>();
Set<XField> staticFieldsReadInThisMethod = new HashSet<XField>();
Set<XField> allMyFields = new TreeSet<XField>();
Set<XField> myFields = new TreeSet<XField>();
Set<XField> writtenFields = new HashSet<XField>();
Set<XField> writtenNonNullFields = new HashSet<XField>();
Set<String> calledFromConstructors = new HashSet<String>();
Set<XField> writtenInConstructorFields = new HashSet<XField>();
Set<XField> readFields = new HashSet<XField>();
Set<XField> constantFields = new HashSet<XField>();
Set<XField> finalFields = new HashSet<XField>();
Set<String> needsOuterObjectInConstructor = new HashSet<String>();
Set<String> innerClassCannotBeStatic = new HashSet<String>();
boolean hasNativeMethods;
boolean isSerializable;
boolean sawSelfCallInConstructor;
private BugReporter bugReporter;
boolean publicOrProtectedConstructor;
private XFactory xFactory = AnalysisContext.currentXFactory();
static final int doNotConsider = ACC_PUBLIC | ACC_PROTECTED;
public UnreadFields(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
@Override
public void visit(JavaClass obj) {
calledFromConstructors.clear();
hasNativeMethods = false;
sawSelfCallInConstructor = false;
publicOrProtectedConstructor = false;
isSerializable = false;
if (getSuperclassName().indexOf("$") >= 0
|| getSuperclassName().indexOf("+") >= 0) {
// System.out.println("hicfsc: " + betterClassName);
innerClassCannotBeStatic.add(getDottedClassName());
// System.out.println("hicfsc: " + betterSuperclassName);
innerClassCannotBeStatic.add(getDottedSuperclassName());
}
// Does this class directly implement Serializable?
String[] interface_names = obj.getInterfaceNames();
for (String interface_name : interface_names) {
if (interface_name.equals("java.io.Externalizable")) {
isSerializable = true;
} else if (interface_name.equals("java.io.Serializable")) {
isSerializable = true;
break;
}
}
// Does this class indirectly implement Serializable?
if (!isSerializable) {
try {
if (Repository.instanceOf(obj, "java.io.Externalizable"))
isSerializable = true;
if (Repository.instanceOf(obj, "java.io.Serializable"))
isSerializable = true;
if (Repository.instanceOf(obj, "java.rmi.Remote")) {
isSerializable = true;
}
} catch (ClassNotFoundException e) {
bugReporter.reportMissingClass(e);
}
}
// System.out.println(getDottedClassName() + " is serializable: " + isSerializable);
super.visit(obj);
}
@Override
public void visitAfter(JavaClass obj) {
declaredFields.addAll(myFields);
if (hasNativeMethods) {
fieldsOfSerializableOrNativeClassed.addAll(myFields);
fieldsOfNativeClassed.addAll(myFields);
}
if (isSerializable) {
fieldsOfSerializableOrNativeClassed.addAll(myFields);
}
if (sawSelfCallInConstructor)
writtenInConstructorFields.addAll(myFields);
myFields.clear();
allMyFields.clear();
calledFromConstructors.clear();
}
@Override
public void visit(Field obj) {
super.visit(obj);
XField f = XFactory.createXField(this);
allMyFields.add(f);
int flags = obj.getAccessFlags();
if ((flags & doNotConsider) == 0
&& !getFieldName().equals("serialVersionUID")) {
myFields.add(f);
if (obj.isFinal()) finalFields.add(f);
if (obj.isStatic()) staticFields.add(f);
}
}
@Override
public void visitAnnotation(String annotationClass,
Map<String, Object> map, boolean runtimeVisible) {
if (!visitingField()) return;
if (annotationClass.startsWith("javax.annotation.") || annotationClass.startsWith("javax.ejb") || annotationClass.startsWith("javax.persistence")) {
containerFields.add(XFactory.createXField(this));
}
}
@Override
public void visit(ConstantValue obj) {
// ConstantValue is an attribute of a field, so the instance variables
// set during visitation of the Field are still valid here
XField f = XFactory.createXField(this);
constantFields.add(f);
}
int count_aload_1;
private OpcodeStack opcodeStack = new OpcodeStack();
private int previousOpcode;
private int previousPreviousOpcode;
@Override
public void visit(Code obj) {
count_aload_1 = 0;
previousOpcode = -1;
previousPreviousOpcode = -1;
nullTested.clear();
seenInvokeStatic = false;
opcodeStack.resetForMethodEntry(this);
staticFieldsReadInThisMethod.clear();
super.visit(obj);
if (getMethodName().equals("<init>") && count_aload_1 > 1
&& (getClassName().indexOf('$') >= 0
|| getClassName().indexOf('+') >= 0)) {
needsOuterObjectInConstructor.add(getDottedClassName());
// System.out.println(betterClassName + " needs outer object in constructor");
}
}
@Override
public void visit(Method obj) {
if (DEBUG) System.out.println("Checking " + getClassName() + "." + obj.getName());
if (getMethodName().equals("<init>")
&& (obj.isPublic()
|| obj.isProtected() ))
publicOrProtectedConstructor = true;
super.visit(obj);
int flags = obj.getAccessFlags();
if ((flags & ACC_NATIVE) != 0)
hasNativeMethods = true;
}
boolean seenInvokeStatic;
@Override
public void sawOpcode(int seen) {
opcodeStack.mergeJumps(this);
if (seen == GETSTATIC) {
XField f = XFactory.createReferencedXField(this);
staticFieldsReadInThisMethod.add(f);
}
else if (seen == INVOKESTATIC) {
seenInvokeStatic = true;
}
else if (seen == PUTSTATIC
&& !getMethod().isStatic()) {
XField f = XFactory.createReferencedXField(this);
if (!staticFieldsReadInThisMethod.contains(f)) {
int priority = LOW_PRIORITY;
if (!publicOrProtectedConstructor)
priority
if (!seenInvokeStatic
&& staticFieldsReadInThisMethod.isEmpty())
priority
if (getThisClass().isPublic()
&& getMethod().isPublic())
priority
if (getThisClass().isPrivate()
|| getMethod().isPrivate())
priority++;
if (getClassName().indexOf('$') != -1)
priority++;
bugReporter.reportBug(new BugInstance(this,
"ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD",
priority
)
.addClassAndMethod(this)
.addField(f)
.addSourceLine(this)
);
}
}
if (seen == INVOKEVIRTUAL || seen == INVOKEINTERFACE
|| seen == INVOKESPECIAL || seen==INVOKESTATIC ) {
String sig = getSigConstantOperand();
String invokedClassName = getClassConstantOperand();
if (invokedClassName.equals(getClassName())
&& (getMethodName().equals("<init>") || getMethodName().equals("<clinit>"))) {
calledFromConstructors.add(getNameConstantOperand()+":"+sig);
}
int pos = PreorderVisitor.getNumberArguments(sig);
if (opcodeStack.getStackDepth() > pos) {
OpcodeStack.Item item = opcodeStack.getStackItem(pos);
boolean superCall = seen == INVOKESPECIAL
&& !invokedClassName .equals(getClassName());
if (DEBUG)
System.out.println("In " + getFullyQualifiedMethodName()
+ " saw call on " + item);
boolean selfCall = item.getRegisterNumber() == 0
&& !superCall;
if (selfCall && getMethodName().equals("<init>")) {
sawSelfCallInConstructor = true;
if (DEBUG)
System.out.println("Saw self call in " + getFullyQualifiedMethodName() + " to " + invokedClassName + "." + getNameConstantOperand()
);
}
}
}
if ((seen == IFNULL || seen == IFNONNULL)
&& opcodeStack.getStackDepth() > 0) {
OpcodeStack.Item item = opcodeStack.getStackItem(0);
XField f = item.getXField();
if (f != null) {
nullTested.add(f);
if (DEBUG)
System.out.println(f + " null checked in " +
getFullyQualifiedMethodName());
}
}
if (seen == GETFIELD || seen == INVOKEVIRTUAL
|| seen == INVOKEINTERFACE
|| seen == INVOKESPECIAL || seen == PUTFIELD
|| seen == IALOAD || seen == AALOAD || seen == BALOAD || seen == CALOAD || seen == SALOAD
|| seen == IASTORE || seen == AASTORE || seen == BASTORE || seen == CASTORE || seen == SASTORE
|| seen == ARRAYLENGTH) {
int pos = 0;
switch(seen) {
case ARRAYLENGTH:
case GETFIELD :
pos = 0;
break;
case INVOKEVIRTUAL :
case INVOKEINTERFACE:
case INVOKESPECIAL:
String sig = getSigConstantOperand();
pos = PreorderVisitor.getNumberArguments(sig);
break;
case PUTFIELD :
case IALOAD :
case AALOAD:
case BALOAD:
case CALOAD:
case SALOAD:
pos = 1;
break;
case IASTORE :
case AASTORE:
case BASTORE:
case CASTORE:
case SASTORE:
pos = 2;
break;
default: throw new RuntimeException("Impossible");
}
if (opcodeStack.getStackDepth() >= pos) {
OpcodeStack.Item item = opcodeStack.getStackItem(pos);
XField f = item.getXField();
if (DEBUG) System.out.println("RRR: " + f + " " + nullTested.contains(f) + " " + writtenInConstructorFields.contains(f) + " " + writtenNonNullFields.contains(f));
if (f != null && !nullTested.contains(f)
&& ! (writtenInConstructorFields.contains(f)
&& writtenNonNullFields.contains(f))
) {
ProgramPoint p = new ProgramPoint(this);
HashSet <ProgramPoint> s = assumedNonNull.get(f);
if (s == null) {
s = new HashSet<ProgramPoint>();
assumedNonNull.put(f,s);
}
s.add(p);
if (DEBUG)
System.out.println(f + " assumed non-null in " +
getFullyQualifiedMethodName());
}
}
}
if (seen == ALOAD_1) {
count_aload_1++;
} else if (seen == GETFIELD || seen == GETSTATIC) {
XField f = XFactory.createReferencedXField(this);
if (DEBUG) System.out.println("get: " + f);
readFields.add(f);
} else if (seen == PUTFIELD || seen == PUTSTATIC) {
XField f = XFactory.createReferencedXField(this);
OpcodeStack.Item item = null;
if (opcodeStack.getStackDepth() > 0) {
item = opcodeStack.getStackItem(0);
if (!item.isNull()) nullTested.add(f);
}
writtenFields.add(f);
if (previousOpcode != ACONST_NULL || previousPreviousOpcode == GOTO ) {
writtenNonNullFields.add(f);
if (DEBUG) System.out.println("put nn: " + f);
}
else if (DEBUG) System.out.println("put: " + f);
if ( getMethod().isStatic() == f.isStatic() && (
calledFromConstructors.contains(getMethodName()+":"+getMethodSig())
|| getMethodName().equals("<init>")
|| getMethodName().equals("init")
|| getMethodName().equals("init")
|| getMethodName().equals("initialize")
|| getMethodName().equals("<clinit>")
|| getMethod().isPrivate())) {
writtenInConstructorFields.add(f);
if (previousOpcode != ACONST_NULL || previousPreviousOpcode == GOTO )
assumedNonNull.remove(f);
}
}
opcodeStack.sawOpcode(this, seen);
previousPreviousOpcode = previousOpcode;
previousOpcode = seen;
if (false && DEBUG) {
System.out.println("After " + OPCODE_NAMES[seen] + " opcode stack is");
System.out.println(opcodeStack);
}
}
Pattern dontComplainAbout = Pattern.compile("class[$]");
@Override
public void report() {
if (DEBUG) {
System.out.println("read fields:" );
for(XField f : readFields)
System.out.println(" " + f);
if (!containerFields.isEmpty()) {
System.out.println("ejb3 fields:" );
for(XField f : containerFields)
System.out.println(" " + f);
}
System.out.println("written fields:" );
for (XField f : writtenFields)
System.out.println(" " + f);
System.out.println("written nonnull fields:" );
for (XField f : writtenNonNullFields)
System.out.println(" " + f);
System.out.println("assumed nonnull fields:" );
for (XField f : assumedNonNull.keySet())
System.out.println(" " + f);
}
// Don't report anything about ejb3Fields
declaredFields.removeAll(containerFields);
TreeSet<XField> notInitializedInConstructors =
new TreeSet<XField>(declaredFields);
notInitializedInConstructors.retainAll(readFields);
notInitializedInConstructors.retainAll(writtenFields);
notInitializedInConstructors.retainAll(assumedNonNull.keySet());
notInitializedInConstructors.removeAll(writtenInConstructorFields);
// notInitializedInConstructors.removeAll(staticFields);
TreeSet<XField> readOnlyFields =
new TreeSet<XField>(declaredFields);
readOnlyFields.removeAll(writtenFields);
readOnlyFields.retainAll(readFields);
TreeSet<XField> nullOnlyFields =
new TreeSet<XField>(declaredFields);
nullOnlyFields.removeAll(writtenNonNullFields);
nullOnlyFields.retainAll(readFields);
Set<XField> writeOnlyFields = declaredFields;
writeOnlyFields.removeAll(readFields);
for (XField f : notInitializedInConstructors) {
String fieldName = f.getName();
String className = f.getClassName();
String fieldSignature = f.getSignature();
if (f.isResolved()
&& !fieldsOfNativeClassed.contains(f)
&& (fieldSignature.charAt(0) == 'L' || fieldSignature.charAt(0) == '[')
) {
int priority = LOW_PRIORITY;
// if (assumedNonNull.containsKey(f)) priority--;
bugReporter.reportBug(new BugInstance(this,
"UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR",
priority)
.addClass(className)
.addField(f));
}
}
for (XField f : readOnlyFields) {
String fieldName = f.getName();
String className = f.getClassName();
String fieldSignature = f.getSignature();
if (f.isResolved()
&& !fieldsOfNativeClassed.contains(f)) {
int priority = NORMAL_PRIORITY;
if (!(fieldSignature.charAt(0) == 'L' || fieldSignature.charAt(0) == '['))
priority++;
bugReporter.reportBug(new BugInstance(this,
"UWF_UNWRITTEN_FIELD",
priority)
.addClass(className)
.addField(f));
}
}
for (XField f : nullOnlyFields) {
String fieldName = f.getName();
String className = f.getClassName();
String fieldSignature = f.getSignature();
if (DEBUG) {
System.out.println("Null only: " + f);
System.out.println(" : " + assumedNonNull.containsKey(f));
System.out.println(" : " + fieldsOfSerializableOrNativeClassed.contains(f));
System.out.println(" : " + f.isResolved());
}
if (!f.isResolved()) continue;
if (fieldsOfNativeClassed.contains(f)) continue;
if (DEBUG) {
System.out.println("Ready to report");
}
int priority = NORMAL_PRIORITY;
if (assumedNonNull.containsKey(f)) {
priority = HIGH_PRIORITY;
for (ProgramPoint p : assumedNonNull.get(f))
bugReporter.reportBug(new BugInstance(this,
"NP_UNWRITTEN_FIELD",
NORMAL_PRIORITY)
.addClassAndMethod(p.method)
.addField(f)
.addSourceLine(p.sourceLine)
);
} else {
if (f.isStatic()) priority++;
if (finalFields.contains(f)) priority++;
if (fieldsOfSerializableOrNativeClassed.contains(f)) priority++;
}
if (!readOnlyFields.contains(f))
bugReporter.reportBug(new BugInstance(this,
"UWF_NULL_FIELD",
priority)
.addClass(className)
.addField(f));
}
for (XField f : writeOnlyFields) {
String fieldName = f.getName();
String className = f.getClassName();
int lastDollar =
Math.max(className.lastIndexOf('$'),
className.lastIndexOf('+'));
boolean isAnonymousInnerClass =
(lastDollar > 0)
&& (lastDollar < className.length() - 1)
&& Character.isDigit(className.charAt(className.length() - 1));
if (DEBUG) {
System.out.println("Checking write only field " + className
+ "." + fieldName
+ "\t" + constantFields.contains(f)
+ "\t" + f.isStatic()
);
}
if (!f.isResolved()) continue;
if (dontComplainAbout.matcher(fieldName).find()) continue;
if (fieldName.startsWith("this$")
|| fieldName.startsWith("this+")) {
if (!innerClassCannotBeStatic.contains(className)) {
boolean easyChange = !needsOuterObjectInConstructor.contains(className);
if (easyChange || !isAnonymousInnerClass) {
// easyChange isAnonymousInnerClass
// true false medium, SIC
// true true low, SIC_ANON
// false true not reported
// false false low, SIC_THIS
int priority = LOW_PRIORITY;
if (easyChange && !isAnonymousInnerClass)
priority = NORMAL_PRIORITY;
String bug = "SIC_INNER_SHOULD_BE_STATIC";
if (isAnonymousInnerClass)
bug = "SIC_INNER_SHOULD_BE_STATIC_ANON";
else if (!easyChange)
bug = "SIC_INNER_SHOULD_BE_STATIC_NEEDS_THIS";
bugReporter.reportBug(new BugInstance(this, bug, priority)
.addClass(className));
}
}
} else {
if (constantFields.contains(f)) {
if (!f.isStatic())
bugReporter.reportBug(new BugInstance(this,
"SS_SHOULD_BE_STATIC",
NORMAL_PRIORITY)
.addClass(className)
.addField(f));
} else if (fieldsOfSerializableOrNativeClassed.contains(f)) {
// ignore it
} else if (!writtenFields.contains(f) && f.isResolved())
bugReporter.reportBug(new BugInstance(this, "UUF_UNUSED_FIELD", NORMAL_PRIORITY)
.addClass(className)
.addField(f));
else if (!f.isStatic() || !finalFields.contains(f))
bugReporter.reportBug(new BugInstance(this, "URF_UNREAD_FIELD", NORMAL_PRIORITY)
.addClass(className)
.addField(f));
}
}
}
} |
package control;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import javafx.event.EventHandler;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.control.DialogEvent;
import javafx.scene.input.InputEvent;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
/**
* Handles all events triggered by the user
* @author ivan
*/
public class MainHandler {
private static Set<String> unreleasedKeys = new HashSet<String>();
/**
* Handle a key press event
* @param event
*/
public static void handleKeyPressed(KeyEvent event) {
// letter key
if (event.getCode().isLetterKey()) {
// forward to slice handler if just pressed
if (!unreleasedKeys.contains(event.getCode().toString())) {
SliceHandler.handleLetterKey(event.getCode().toString());
}
// remember that key has been pressed
unreleasedKeys.add(event.getCode().toString());
}
// space key
if (event.getCode().equals(KeyCode.SPACE)) {
// pause
SliceHandler.toggleBreak();
}
// backspace key
if (event.getCode().equals(KeyCode.BACK_SPACE)) {
// ask user to confirm reset
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Confirm Reset");
alert.setHeaderText("Do you really want to reset all timers?");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK){
// User says OK, so reset measurement
SliceHandler.resetSlices();
} else {
// Cancel, do nothing
}
}
// enter key
if (event.getCode().equals(KeyCode.ENTER)) {
// save data
SliceHandler.exportData();
}
// escape key
if (event.getCode().equals(KeyCode.ESCAPE)) {
// ask user to confirm exit
// Alert alert = new Alert(AlertType.CONFIRMATION);
// alert.setOnCloseRequest(new EventHandler<DialogEvent>() {
// public void handle(DialogEvent event) {
// System.out.println(event.getEventType().toString());
// event.consume();
// alert.setTitle("Confirm Exit");
// alert.setHeaderText("Do you really want to exit the application?");
// Optional<ButtonType> result = alert.showAndWait();
// if (result.get() == ButtonType.OK){
// // User says OK, so exit application
// System.exit(0);
// } else {
// // Cancel, do nothing
}
}
/**
* Handle a key release event
* @param event
*/
public static void handleKeyReleased(KeyEvent event) {
// remember that key has been released
if (event.getCode().isLetterKey()) {
unreleasedKeys.remove(event.getCode().toString());
}
}
} |
package com.planet_ink.coffee_mud.Abilities.Common;
import com.planet_ink.coffee_mud.interfaces.*;
import com.planet_ink.coffee_mud.common.*;
import com.planet_ink.coffee_mud.utils.*;
import java.io.File;
import java.util.*;
public class Cooking extends CommonSkill
{
public String ID() { return "Cooking"; }
public String name(){ return "Cooking";}
private static final String[] triggerStrings = {"COOK","COOKING"};
public String[] triggerStrings(){return triggerStrings;}
public String cookWordShort(){return "cook";};
public String cookWord(){return "cooking";};
public boolean honorHerbs(){return true;}
public static int RCP_FINALFOOD=0;
public static int RCP_FOODDRINK=1;
public static int RCP_BONUSSPELL=2;
public static int RCP_LEVEL=3;
public static int RCP_MAININGR=4;
public static int RCP_MAINAMNT=5;
private Container cooking=null;
private Item fire=null;
private Item finalDish=null;
private String finalDishName=null;
private int finalAmount=0;
private Vector finalRecipe=null;
private boolean burnt=false;
private Hashtable oldContents=null;
private static boolean mapped=false;
public Cooking()
{
super();
displayText="You are "+cookWord()+"...";
verb=cookWord();
if(ID().equals("Cooking")&&(!mapped))
{mapped=true; CMAble.addCharAbilityMapping("All",1,ID(),false);}
}
public Environmental newInstance(){ return new Cooking();}
public boolean isMineForCooking(MOB mob, Item cooking)
{
if(mob.isMine(cooking)) return true;
if((mob.location()==cooking.owner())
&&(cooking.container()!=null)
&&(Sense.isOnFire(cooking.container())))
return true;
return false;
}
public boolean tick(Tickable ticking, int tickID)
{
if((affected!=null)&&(affected instanceof MOB)&&(tickID==Host.MOB_TICK))
{
MOB mob=(MOB)affected;
if((cooking==null)
||(fire==null)
||(finalDish==null)
||(finalRecipe==null)
||(finalAmount<=0)
||(!isMineForCooking(mob,cooking))
||(!contentsSame(potContents(cooking),oldContents))
||(!Sense.isOnFire(fire))
||(!mob.location().isContent(fire))
||(mob.isMine(fire)))
{
aborted=true;
unInvoke();
}
else
if(tickUp==0)
{
commonTell(mob,"You start "+cookWord()+" up some "+finalDishName+".");
displayText="You are "+cookWord()+" "+finalDishName;
verb=cookWord()+" "+finalDishName;
}
}
return super.tick(ticking,tickID);
}
protected synchronized Vector loadRecipes()
{
Vector V=(Vector)Resources.getResource("COOKING RECIPES");
if(V==null)
{
StringBuffer str=Resources.getFile("resources"+File.separatorChar+"skills"+File.separatorChar+"recipes.txt");
V=loadList(str);
if(V.size()==0)
Log.errOut("Cook","Recipes not found!");
Resources.submitResource("COOKING RECIPES",V);
}
return V;
}
public void unInvoke()
{
if(canBeUninvoked())
{
if((affected!=null)&&(affected instanceof MOB))
{
if((cooking!=null)&&(!aborted)&&(finalRecipe!=null)&&(finalDish!=null))
{
Vector V=cooking.getContents();
for(int v=0;v<V.size();v++)
((Item)V.elementAt(v)).destroy();
if((cooking instanceof Drink)&&(finalDish instanceof Drink))
((Drink)cooking).setLiquidRemaining(0);
for(int i=0;i<finalAmount*(abilityCode());i++)
{
Item food=((Item)finalDish.copyOf());
food.setMiscText(finalDish.text());
food.recoverEnvStats();
if(cooking.owner() instanceof Room)
((Room)cooking.owner()).addItemRefuse(food,Item.REFUSE_PLAYER_DROP);
else
if(cooking.owner() instanceof MOB)
((MOB)cooking.owner()).addInventory(food);
food.setContainer(cooking);
}
}
}
}
super.unInvoke();
}
public boolean contentsSame(Hashtable h1, Hashtable h2)
{
if(h1.size()!=h2.size()) return false;
for(Enumeration e=h1.keys();e.hasMoreElements();)
{
String key=(String)e.nextElement();
Integer INT1=(Integer)h1.get(key);
Integer INT2=(Integer)h2.get(key);
if((INT1==null)||(INT2==null)) return false;
if(INT1.intValue()!=INT2.intValue()) return false;
}
return true;
}
public Hashtable potContents(Container pot)
{
Hashtable h=new Hashtable();
if((pot instanceof Drink)&&(((Drink)pot).containsDrink()))
{
if(pot instanceof EnvResource)
h.put(EnvResource.RESOURCE_DESCS[((EnvResource)pot).material()&EnvResource.RESOURCE_MASK]+"/",new Integer(((Drink)pot).liquidRemaining()/10));
else
h.put(EnvResource.RESOURCE_DESCS[((Drink)pot).liquidType()&EnvResource.RESOURCE_MASK]+"/",new Integer(((Drink)pot).liquidRemaining()/10));
}
if(pot.owner()==null) return h;
Vector V=pot.getContents();
for(int v=0;v<V.size();v++)
{
Item I=(Item)V.elementAt(v);
String ing="Unknown";
if(I instanceof EnvResource)
ing=EnvResource.RESOURCE_DESCS[I.material()&EnvResource.RESOURCE_MASK];
else
if((((I.material()&EnvResource.MATERIAL_VEGETATION)>0)
||((I.material()&EnvResource.MATERIAL_LIQUID)>0)
||((I.material()&EnvResource.MATERIAL_FLESH)>0))
&&(Util.parse(I.name()).size()>0))
ing=((String)Util.parse(I.name()).lastElement()).toUpperCase();
else
ing=I.name();
Integer INT=(Integer)h.get(ing+"/"+I.Name().toUpperCase());
if(INT==null) INT=new Integer(0);
INT=new Integer(INT.intValue()+1);
h.put(ing+"/"+I.Name().toUpperCase(),INT);
}
return h;
}
public Vector countIngredients(Vector Vr)
{
String[] contents=new String[oldContents.size()];
int[] amounts=new int[oldContents.size()];
int numIngredients=0;
for(Enumeration e=oldContents.keys();e.hasMoreElements();)
{
contents[numIngredients]=(String)e.nextElement();
amounts[numIngredients]=((Integer)oldContents.get(contents[numIngredients])).intValue();
numIngredients++;
}
int amountMade=0;
Vector codedList=new Vector();
boolean RanOutOfSomething=false;
boolean NotEnoughForThisRun=false;
while((!RanOutOfSomething)&&(!NotEnoughForThisRun))
{
for(int vr=RCP_MAININGR;vr<Vr.size();vr+=2)
{
String ingredient=((String)Vr.elementAt(vr)).toUpperCase();
if(ingredient.length()>0)
{
int amount=1;
if(vr<Vr.size()-1)amount=Util.s_int((String)Vr.elementAt(vr+1));
if(amount==0) amount=1;
if(amount<0) amount=amount*-1;
if(ingredient.equalsIgnoreCase("water"))
amount=amount*10;
boolean found=false;
for(int i=0;i<contents.length;i++)
{
String ingredient2=((String)contents[i]).toUpperCase();
int amount2=amounts[i];
if((ingredient2.startsWith(ingredient+"/"))
||(ingredient2.endsWith("/"+ingredient)))
{
found=true;
amounts[i]=amount2-amount;
if(amounts[i]<0) NotEnoughForThisRun=true;
if(amounts[i]==0) RanOutOfSomething=true;
}
}
}
}
if(!NotEnoughForThisRun) amountMade++;
}
if(NotEnoughForThisRun)
{
codedList.addElement(new Integer(-amountMade));
for(int i=0;i<contents.length;i++)
if(amounts[i]<0)
{
String content=contents[i];
if(content.indexOf("/")>=0)
content=content.substring(0,content.indexOf("/"));
codedList.addElement(content);
}
}
else
{
codedList.addElement(new Integer(amountMade));
for(int i=0;i<contents.length;i++)
{
String ingredient2=(String)contents[i];
int amount2=amounts[i];
if((amount2>0)
&&((!honorHerbs())||(!ingredient2.toUpperCase().startsWith("HERBS/")))
&&(!ingredient2.toUpperCase().startsWith("WATER/")))
{
String content=contents[i];
if(content.indexOf("/")>=0)
content=content.substring(0,content.indexOf("/"));
codedList.addElement(content);
}
}
}
return codedList;
}
public Vector extraIngredientsInOldContents(Vector Vr)
{
Vector extra=new Vector();
for(Enumeration e=oldContents.keys();e.hasMoreElements();)
{
boolean found=false;
String ingredient=(String)e.nextElement();
if(honorHerbs()&&ingredient.toUpperCase().startsWith("HERBS/")) // herbs exception
found=true;
else
for(int vr=RCP_MAININGR;vr<Vr.size();vr+=2)
{
String ingredient2=((String)Vr.elementAt(vr)).toUpperCase();
if((ingredient2.length()>0)
&&((ingredient.toUpperCase().startsWith(ingredient2+"/"))
||(ingredient.toUpperCase().endsWith("/"+ingredient2))))
found=true;
}
if(!found)
{
String content=ingredient;
if(content.indexOf("/")>=0)
content=content.substring(0,content.indexOf("/"));
extra.addElement(content);
}
}
return extra;
}
public Vector missingIngredientsFromOldContents(Vector Vr)
{
Vector missing=new Vector();
String possiblyMissing=null;
boolean foundOptional=false;
boolean hasOptional=false;
for(int vr=RCP_MAININGR;vr<Vr.size();vr+=2)
{
String ingredient=(String)Vr.elementAt(vr);
if(ingredient.length()>0)
{
int amount=1;
if(vr<Vr.size()-1)amount=Util.s_int((String)Vr.elementAt(vr+1));
if(amount>=0)
{
boolean found=false;
for(Enumeration e=oldContents.keys();e.hasMoreElements();)
{
String ingredient2=((String)e.nextElement()).toUpperCase();
if((ingredient2.startsWith(ingredient.toUpperCase()+"/"))
||(ingredient2.endsWith("/"+ingredient.toUpperCase())))
{ found=true; break;}
}
if(!found)
missing.addElement(ingredient);
}
else
if(amount<0){
foundOptional=true;
if(oldContents.containsKey(ingredient.toUpperCase()))
hasOptional=true;
else
possiblyMissing=ingredient;
}
}
}
if((foundOptional)&&(!hasOptional))
missing.addElement(possiblyMissing);
return missing;
}
public boolean invoke(MOB mob, Vector commands, Environmental givenTarget, boolean auto)
{
verb=cookWord();
cooking=null;
fire=null;
finalRecipe=null;
finalAmount=0;
Vector allRecipes=loadRecipes();
if(Util.combine(commands,0).equalsIgnoreCase("list"))
{
StringBuffer buf=new StringBuffer(Util.padRight("Recipe",16)+" ingredients required\n\r");
for(int r=0;r<allRecipes.size();r++)
{
Vector Vr=(Vector)allRecipes.elementAt(r);
if(Vr.size()>0)
{
String item=(String)Vr.elementAt(RCP_FINALFOOD);
if(item.length()==0) continue;
int level=Util.s_int((String)Vr.elementAt(RCP_LEVEL));
if(level<=mob.envStats().level())
{
buf.append(Util.padRight(Util.capitalize(replacePercent(item,"")),16)+" ");
for(int vr=RCP_MAININGR;vr<Vr.size();vr+=2)
{
String ingredient=(String)Vr.elementAt(vr);
if(ingredient.length()>0)
{
int amount=1;
if(vr<Vr.size()-1)amount=Util.s_int((String)Vr.elementAt(vr+1));
if(amount==0) amount=1;
if(amount<0) amount=amount*-1;
if(ingredient.equalsIgnoreCase("water"))
amount=amount*10;
buf.append(ingredient.toLowerCase()+"("+amount+") ");
}
}
buf.append("\n\r");
}
}
}
commonTell(mob,buf.toString());
return true;
}
Item possibleContainer=possibleContainer(mob,commands,true,Item.WORN_REQ_UNWORNONLY);
Item target=getTarget(mob,mob.location(),givenTarget,possibleContainer,commands,Item.WORN_REQ_UNWORNONLY);
if(target==null) return false;
if(!isMineForCooking(mob,target))
{
commonTell(mob,"You probably need to pick that up first.");
return false;
}
if(!(target instanceof Container))
{
commonTell(mob,"There's nothing in "+target.name()+" to "+cookWordShort()+"!");
return false;
}
switch(target.material()&EnvResource.MATERIAL_MASK)
{
case EnvResource.MATERIAL_GLASS:
case EnvResource.MATERIAL_METAL:
case EnvResource.MATERIAL_MITHRIL:
case EnvResource.MATERIAL_ROCK:
case EnvResource.MATERIAL_PRECIOUS:
break;
default:
commonTell(mob,target.name()+" is not suitable to "+cookWordShort()+" in.");
return false;
}
fire=getRequiredFire(mob);
if(fire==null) return false;
burnt=!profficiencyCheck(0,auto);
int duration=40-mob.envStats().level();
if(duration<15) duration=15;
cooking=(Container)target;
oldContents=potContents(cooking); |
package net.minecraftforge.common;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multiset;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.collect.TreeMultiset;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import net.minecraft.src.Chunk;
import net.minecraft.src.ChunkCoordIntPair;
import net.minecraft.src.CompressedStreamTools;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.MathHelper;
import net.minecraft.src.NBTBase;
import net.minecraft.src.NBTTagCompound;
import net.minecraft.src.NBTTagList;
import net.minecraft.src.World;
import net.minecraft.src.WorldServer;
import net.minecraftforge.common.ForgeChunkManager.Ticket;
/**
* Manages chunkloading for mods.
*
* The basic principle is a ticket based system.
* 1. Mods register a callback {@link #setForcedChunkLoadingCallback(Object, LoadingCallback)}
* 2. Mods ask for a ticket {@link #requestTicket(Object, World, Type)} and then hold on to that ticket.
* 3. Mods request chunks to stay loaded {@link #forceChunk(Ticket, ChunkCoordIntPair)} or remove chunks from force loading {@link #unforceChunk(Ticket, ChunkCoordIntPair)}.
* 4. When a world unloads, the tickets associated with that world are saved by the chunk manager.
* 5. When a world loads, saved tickets are offered to the mods associated with the tickets. The {@link Ticket#getModData()} that is set by the mod should be used to re-register
* chunks to stay loaded (and maybe take other actions).
*
* The chunkloading is configurable at runtime. The file "config/forgeChunkLoading.cfg" contains both default configuration for chunkloading, and a sample individual mod
* specific override section.
*
* @author cpw
*
*/
public class ForgeChunkManager
{
private static int defaultMaxCount;
private static int defaultMaxChunks;
private static boolean overridesEnabled;
private static Map<World, Multimap<String, Ticket>> tickets = new MapMaker().weakKeys().makeMap();
private static Map<String, Integer> ticketConstraints = Maps.newHashMap();
private static Map<String, Integer> chunkConstraints = Maps.newHashMap();
private static SetMultimap<String, Ticket> playerTickets = HashMultimap.create();
private static Map<String, LoadingCallback> callbacks = Maps.newHashMap();
private static Map<World, SetMultimap<ChunkCoordIntPair,Ticket>> forcedChunks = new MapMaker().weakKeys().makeMap();
private static BiMap<UUID,Ticket> pendingEntities = HashBiMap.create();
private static Map<World,Cache<Long, Chunk>> dormantChunkCache = new MapMaker().weakKeys().makeMap();
private static File cfgFile;
private static Configuration config;
private static int playerTicketLength;
private static int dormantChunkCacheSize;
/**
* All mods requiring chunkloading need to implement this to handle the
* re-registration of chunk tickets at world loading time
*
* @author cpw
*
*/
public interface LoadingCallback
{
/**
* Called back when tickets are loaded from the world to allow the
* mod to re-register the chunks associated with those tickets. The list supplied
* here is truncated to length prior to use. Tickets unwanted by the
* mod must be disposed of manually unless the mod is an OrderedLoadingCallback instance
* in which case, they will have been disposed of by the earlier callback.
*
* @param tickets The tickets to re-register. The list is immutable and cannot be manipulated directly. Copy it first.
* @param world the world
*/
public void ticketsLoaded(List<Ticket> tickets, World world);
}
/**
* This is a special LoadingCallback that can be implemented as well as the
* LoadingCallback to provide access to additional behaviour.
* Specifically, this callback will fire prior to Forge dropping excess
* tickets. Tickets in the returned list are presumed ordered and excess will
* be truncated from the returned list.
* This allows the mod to control not only if they actually <em>want</em> a ticket but
* also their preferred ticket ordering.
*
* @author cpw
*
*/
public interface OrderedLoadingCallback extends LoadingCallback
{
/**
* Called back when tickets are loaded from the world to allow the
* mod to decide if it wants the ticket still, and prioritise overflow
* based on the ticket count.
* WARNING: You cannot force chunks in this callback, it is strictly for allowing the mod
* to be more selective in which tickets it wishes to preserve in an overflow situation
*
* @param tickets The tickets that you will want to select from. The list is immutable and cannot be manipulated directly. Copy it first.
* @param world The world
* @param maxTicketCount The maximum number of tickets that will be allowed.
* @return A list of the tickets this mod wishes to continue using. This list will be truncated
* to "maxTicketCount" size after the call returns and then offered to the other callback
* method
*/
public List<Ticket> ticketsLoaded(List<Ticket> tickets, World world, int maxTicketCount);
}
public enum Type
{
/**
* For non-entity registrations
*/
NORMAL,
/**
* For entity registrations
*/
ENTITY
}
public static class Ticket
{
private String modId;
private Type ticketType;
private LinkedHashSet<ChunkCoordIntPair> requestedChunks;
private NBTTagCompound modData;
private World world;
private int maxDepth;
private String entityClazz;
private int entityChunkX;
private int entityChunkZ;
private Entity entity;
private String player;
Ticket(String modId, Type type, World world)
{
this.modId = modId;
this.ticketType = type;
this.world = world;
this.maxDepth = getMaxChunkDepthFor(modId);
this.requestedChunks = Sets.newLinkedHashSet();
}
Ticket(String modId, Type type, World world, EntityPlayer player)
{
this(modId, type, world);
if (player != null)
{
this.player = player.getEntityName();
}
else
{
FMLLog.log(Level.SEVERE, "Attempt to create a player ticket without a valid player");
throw new RuntimeException();
}
}
/**
* The chunk list depth can be manipulated up to the maximal grant allowed for the mod. This value is configurable. Once the maximum is reached,
* the least recently forced chunk, by original registration time, is removed from the forced chunk list.
*
* @param depth The new depth to set
*/
public void setChunkListDepth(int depth)
{
if (depth > getMaxChunkDepthFor(modId) || (depth <= 0 && getMaxChunkDepthFor(modId) > 0))
{
FMLLog.warning("The mod %s tried to modify the chunk ticket depth to: %d, its allowed maximum is: %d", modId, depth, getMaxChunkDepthFor(modId));
}
else
{
this.maxDepth = depth;
}
}
/**
* Gets the current max depth for this ticket.
* Should be the same as getMaxChunkListDepth()
* unless setChunkListDepth has been called.
*
* @return Current max depth
*/
public int getChunkListDepth()
{
return maxDepth;
}
/**
* Get the maximum chunk depth size
*
* @return The maximum chunk depth size
*/
public int getMaxChunkListDepth()
{
return getMaxChunkDepthFor(modId);
}
/**
* Bind the entity to the ticket for {@link Type#ENTITY} type tickets. Other types will throw a runtime exception.
*
* @param entity The entity to bind
*/
public void bindEntity(Entity entity)
{
if (ticketType!=Type.ENTITY)
{
throw new RuntimeException("Cannot bind an entity to a non-entity ticket");
}
this.entity = entity;
}
/**
* Retrieve the {@link NBTTagCompound} that stores mod specific data for the chunk ticket.
* Example data to store would be a TileEntity or Block location. This is persisted with the ticket and
* provided to the {@link LoadingCallback} for the mod. It is recommended to use this to recover
* useful state information for the forced chunks.
*
* @return The custom compound tag for mods to store additional chunkloading data
*/
public NBTTagCompound getModData()
{
if (this.modData == null)
{
this.modData = new NBTTagCompound();
}
return modData;
}
/**
* Get the entity associated with this {@link Type#ENTITY} type ticket
* @return
*/
public Entity getEntity()
{
return entity;
}
/**
* Is this a player associated ticket rather than a mod associated ticket?
*/
public boolean isPlayerTicket()
{
return player != null;
}
/**
* Get the player associated with this ticket
*/
public String getPlayerName()
{
return player;
}
/**
* Get the associated mod id
*/
public String getModId()
{
return modId;
}
/**
* Gets the ticket type
*/
public Type getType()
{
return ticketType;
}
/**
* Gets a list of requested chunks for this ticket.
*/
public ImmutableSet getChunkList()
{
return ImmutableSet.copyOf(requestedChunks);
}
}
static void loadWorld(World world)
{
ArrayListMultimap<String, Ticket> newTickets = ArrayListMultimap.<String, Ticket>create();
tickets.put(world, newTickets);
SetMultimap<ChunkCoordIntPair,Ticket> forcedChunkMap = LinkedHashMultimap.create();
forcedChunks.put(world, forcedChunkMap);
if (!(world instanceof WorldServer))
{
return;
}
dormantChunkCache.put(world, CacheBuilder.newBuilder().maximumSize(dormantChunkCacheSize).<Long, Chunk>build());
WorldServer worldServer = (WorldServer) world;
File chunkDir = worldServer.getChunkSaveLocation();
File chunkLoaderData = new File(chunkDir, "forcedchunks.dat");
if (chunkLoaderData.exists() && chunkLoaderData.isFile())
{
ArrayListMultimap<String, Ticket> loadedTickets = ArrayListMultimap.<String, Ticket>create();
ArrayListMultimap<String, Ticket> playerLoadedTickets = ArrayListMultimap.<String, Ticket>create();
NBTTagCompound forcedChunkData;
try
{
forcedChunkData = CompressedStreamTools.read(chunkLoaderData);
}
catch (IOException e)
{
FMLLog.log(Level.WARNING, e, "Unable to read forced chunk data at %s - it will be ignored", chunkLoaderData.getAbsolutePath());
return;
}
NBTTagList ticketList = forcedChunkData.getTagList("TicketList");
for (int i = 0; i < ticketList.tagCount(); i++)
{
NBTTagCompound ticketHolder = (NBTTagCompound) ticketList.tagAt(i);
String modId = ticketHolder.getString("Owner");
boolean isPlayer = "Forge".equals(modId);
if (!isPlayer && !Loader.isModLoaded(modId))
{
FMLLog.warning("Found chunkloading data for mod %s which is currently not available or active - it will be removed from the world save", modId);
continue;
}
if (!isPlayer && !callbacks.containsKey(modId))
{
FMLLog.warning("The mod %s has registered persistent chunkloading data but doesn't seem to want to be called back with it - it will be removed from the world save", modId);
continue;
}
NBTTagList tickets = ticketHolder.getTagList("Tickets");
for (int j = 0; j < tickets.tagCount(); j++)
{
NBTTagCompound ticket = (NBTTagCompound) tickets.tagAt(j);
modId = ticket.hasKey("ModId") ? ticket.getString("ModId") : modId;
Type type = Type.values()[ticket.getByte("Type")];
byte ticketChunkDepth = ticket.getByte("ChunkListDepth");
Ticket tick = new Ticket(modId, type, world);
if (ticket.hasKey("ModData"))
{
tick.modData = ticket.getCompoundTag("ModData");
}
if (ticket.hasKey("Player"))
{
tick.player = ticket.getString("Player");
playerLoadedTickets.put(tick.modId, tick);
playerTickets.put(tick.player, tick);
}
else
{
loadedTickets.put(modId, tick);
}
if (type == Type.ENTITY)
{
tick.entityChunkX = ticket.getInteger("chunkX");
tick.entityChunkZ = ticket.getInteger("chunkZ");
UUID uuid = new UUID(ticket.getLong("PersistentIDMSB"), ticket.getLong("PersistentIDLSB"));
// add the ticket to the "pending entity" list
pendingEntities.put(uuid, tick);
}
}
}
for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values()))
{
if (tick.ticketType == Type.ENTITY && tick.entity == null)
{
// force the world to load the entity's chunk
// the load will come back through the loadEntity method and attach the entity
// to the ticket
world.getChunkFromChunkCoords(tick.entityChunkX, tick.entityChunkZ);
}
}
for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values()))
{
if (tick.ticketType == Type.ENTITY && tick.entity == null)
{
FMLLog.warning("Failed to load persistent chunkloading entity %s from store.", pendingEntities.inverse().get(tick));
loadedTickets.remove(tick.modId, tick);
}
}
pendingEntities.clear();
// send callbacks
for (String modId : loadedTickets.keySet())
{
LoadingCallback loadingCallback = callbacks.get(modId);
int maxTicketLength = getMaxTicketLengthFor(modId);
List<Ticket> tickets = loadedTickets.get(modId);
if (loadingCallback instanceof OrderedLoadingCallback)
{
OrderedLoadingCallback orderedLoadingCallback = (OrderedLoadingCallback) loadingCallback;
tickets = orderedLoadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world, maxTicketLength);
}
if (tickets.size() > maxTicketLength)
{
FMLLog.warning("The mod %s has too many open chunkloading tickets %d. Excess will be dropped", modId, tickets.size());
tickets.subList(maxTicketLength, tickets.size()).clear();
}
ForgeChunkManager.tickets.get(world).putAll(modId, tickets);
loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world);
}
for (String modId : playerLoadedTickets.keySet())
{
LoadingCallback loadingCallback = callbacks.get(modId);
List<Ticket> tickets = playerLoadedTickets.get(modId);
ForgeChunkManager.tickets.get(world).putAll("Forge", tickets);
loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world);
}
}
}
/**
* Set a chunkloading callback for the supplied mod object
*
* @param mod The mod instance registering the callback
* @param callback The code to call back when forced chunks are loaded
*/
public static void setForcedChunkLoadingCallback(Object mod, LoadingCallback callback)
{
ModContainer container = getContainer(mod);
if (container == null)
{
FMLLog.warning("Unable to register a callback for an unknown mod %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod));
return;
}
callbacks.put(container.getModId(), callback);
}
/**
* Discover the available tickets for the mod in the world
*
* @param mod The mod that will own the tickets
* @param world The world
* @return The count of tickets left for the mod in the supplied world
*/
public static int ticketCountAvailableFor(Object mod, World world)
{
ModContainer container = getContainer(mod);
if (container!=null)
{
String modId = container.getModId();
int allowedCount = getMaxTicketLengthFor(modId);
return allowedCount - tickets.get(world).get(modId).size();
}
else
{
return 0;
}
}
private static ModContainer getContainer(Object mod)
{
ModContainer container = Loader.instance().getModObjectList().inverse().get(mod);
return container;
}
private static int getMaxTicketLengthFor(String modId)
{
int allowedCount = ticketConstraints.containsKey(modId) && overridesEnabled ? ticketConstraints.get(modId) : defaultMaxCount;
return allowedCount;
}
private static int getMaxChunkDepthFor(String modId)
{
int allowedCount = chunkConstraints.containsKey(modId) && overridesEnabled ? chunkConstraints.get(modId) : defaultMaxChunks;
return allowedCount;
}
public static Ticket requestPlayerTicket(Object mod, EntityPlayer player, World world, Type type)
{
ModContainer mc = getContainer(mod);
if (mc == null)
{
FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod));
return null;
}
if (playerTickets.get(player.getEntityName()).size()>playerTicketLength)
{
FMLLog.warning("Unable to assign further chunkloading tickets to player %s (on behalf of mod %s)", player.getEntityName(), mc.getModId());
return null;
}
Ticket ticket = new Ticket(mc.getModId(),type,world,player);
playerTickets.put(player.getEntityName(), ticket);
tickets.get(world).put("Forge", ticket);
return ticket;
}
/**
* Request a chunkloading ticket of the appropriate type for the supplied mod
*
* @param mod The mod requesting a ticket
* @param world The world in which it is requesting the ticket
* @param type The type of ticket
* @return A ticket with which to register chunks for loading, or null if no further tickets are available
*/
public static Ticket requestTicket(Object mod, World world, Type type)
{
ModContainer container = getContainer(mod);
if (container == null)
{
FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod));
return null;
}
String modId = container.getModId();
if (!callbacks.containsKey(modId))
{
FMLLog.severe("The mod %s has attempted to request a ticket without a listener in place", modId);
throw new RuntimeException("Invalid ticket request");
}
int allowedCount = ticketConstraints.containsKey(modId) ? ticketConstraints.get(modId) : defaultMaxCount;
if (tickets.get(world).get(modId).size() >= allowedCount)
{
FMLLog.info("The mod %s has attempted to allocate a chunkloading ticket beyond it's currently allocated maximum : %d", modId, allowedCount);
return null;
}
Ticket ticket = new Ticket(modId, type, world);
tickets.get(world).put(modId, ticket);
return ticket;
}
/**
* Release the ticket back to the system. This will also unforce any chunks held by the ticket so that they can be unloaded and/or stop ticking.
*
* @param ticket The ticket to release
*/
public static void releaseTicket(Ticket ticket)
{
if (ticket == null)
{
return;
}
if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket))
{
return;
}
if (ticket.requestedChunks!=null)
{
for (ChunkCoordIntPair chunk : ImmutableSet.copyOf(ticket.requestedChunks))
{
unforceChunk(ticket, chunk);
}
}
if (ticket.isPlayerTicket())
{
playerTickets.remove(ticket.player, ticket);
tickets.get(ticket.world).remove("Forge",ticket);
}
else
{
tickets.get(ticket.world).remove(ticket.modId, ticket);
}
}
/**
* Force the supplied chunk coordinate to be loaded by the supplied ticket. If the ticket's {@link Ticket#maxDepth} is exceeded, the least
* recently registered chunk is unforced and may be unloaded.
* It is safe to force the chunk several times for a ticket, it will not generate duplication or change the ordering.
*
* @param ticket The ticket registering the chunk
* @param chunk The chunk to force
*/
public static void forceChunk(Ticket ticket, ChunkCoordIntPair chunk)
{
if (ticket == null || chunk == null)
{
return;
}
if (ticket.ticketType == Type.ENTITY && ticket.entity == null)
{
throw new RuntimeException("Attempted to use an entity ticket to force a chunk, without an entity");
}
if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket))
{
FMLLog.severe("The mod %s attempted to force load a chunk with an invalid ticket. This is not permitted.", ticket.modId);
return;
}
ticket.requestedChunks.add(chunk);
forcedChunks.get(ticket.world).put(chunk, ticket);
if (ticket.maxDepth > 0 && ticket.requestedChunks.size() > ticket.maxDepth)
{
ChunkCoordIntPair removed = ticket.requestedChunks.iterator().next();
unforceChunk(ticket,removed);
}
}
/**
* Reorganize the internal chunk list so that the chunk supplied is at the *end* of the list
* This helps if you wish to guarantee a certain "automatic unload ordering" for the chunks
* in the ticket list
*
* @param ticket The ticket holding the chunk list
* @param chunk The chunk you wish to push to the end (so that it would be unloaded last)
*/
public static void reorderChunk(Ticket ticket, ChunkCoordIntPair chunk)
{
if (ticket == null || chunk == null || !ticket.requestedChunks.contains(chunk))
{
return;
}
ticket.requestedChunks.remove(chunk);
ticket.requestedChunks.add(chunk);
}
/**
* Unforce the supplied chunk, allowing it to be unloaded and stop ticking.
*
* @param ticket The ticket holding the chunk
* @param chunk The chunk to unforce
*/
public static void unforceChunk(Ticket ticket, ChunkCoordIntPair chunk)
{
if (ticket == null || chunk == null)
{
return;
}
ticket.requestedChunks.remove(chunk);
forcedChunks.get(ticket.world).remove(chunk, ticket);
}
static void loadConfiguration()
{
for (String mod : config.categories.keySet())
{
if (mod.equals("Forge") || mod.equals("defaults"))
{
continue;
}
Property modTC = config.get(mod, "maximumTicketCount", 200);
Property modCPT = config.get(mod, "maximumChunksPerTicket", 25);
ticketConstraints.put(mod, modTC.getInt(200));
chunkConstraints.put(mod, modCPT.getInt(25));
}
config.save();
}
/**
* The list of persistent chunks in the world. This set is immutable.
* @param world
* @return
*/
public static SetMultimap<ChunkCoordIntPair, Ticket> getPersistentChunksFor(World world)
{
return forcedChunks.containsKey(world) ? ImmutableSetMultimap.copyOf(forcedChunks.get(world)) : ImmutableSetMultimap.<ChunkCoordIntPair,Ticket>of();
}
static void saveWorld(World world)
{
// only persist persistent worlds
if (!(world instanceof WorldServer)) { return; }
WorldServer worldServer = (WorldServer) world;
File chunkDir = worldServer.getChunkSaveLocation();
File chunkLoaderData = new File(chunkDir, "forcedchunks.dat");
NBTTagCompound forcedChunkData = new NBTTagCompound();
NBTTagList ticketList = new NBTTagList();
forcedChunkData.setTag("TicketList", ticketList);
Multimap<String, Ticket> ticketSet = tickets.get(worldServer);
for (String modId : ticketSet.keySet())
{
NBTTagCompound ticketHolder = new NBTTagCompound();
ticketList.appendTag(ticketHolder);
ticketHolder.setString("Owner", modId);
NBTTagList tickets = new NBTTagList();
ticketHolder.setTag("Tickets", tickets);
for (Ticket tick : ticketSet.get(modId))
{
NBTTagCompound ticket = new NBTTagCompound();
ticket.setByte("Type", (byte) tick.ticketType.ordinal());
ticket.setByte("ChunkListDepth", (byte) tick.maxDepth);
if (tick.isPlayerTicket())
{
ticket.setString("ModId", tick.modId);
ticket.setString("Player", tick.player);
}
if (tick.modData != null)
{
ticket.setCompoundTag("ModData", tick.modData);
}
if (tick.ticketType == Type.ENTITY && tick.entity != null)
{
ticket.setInteger("chunkX", MathHelper.floor_double(tick.entity.chunkCoordX));
ticket.setInteger("chunkZ", MathHelper.floor_double(tick.entity.chunkCoordZ));
ticket.setLong("PersistentIDMSB", tick.entity.getPersistentID().getMostSignificantBits());
ticket.setLong("PersistentIDLSB", tick.entity.getPersistentID().getLeastSignificantBits());
tickets.appendTag(ticket);
}
else if (tick.ticketType != Type.ENTITY)
{
tickets.appendTag(ticket);
}
}
}
try
{
CompressedStreamTools.write(forcedChunkData, chunkLoaderData);
}
catch (IOException e)
{
FMLLog.log(Level.WARNING, e, "Unable to write forced chunk data to %s - chunkloading won't work", chunkLoaderData.getAbsolutePath());
return;
}
}
static void loadEntity(Entity entity)
{
UUID id = entity.getPersistentID();
Ticket tick = pendingEntities.get(id);
if (tick != null)
{
tick.bindEntity(entity);
pendingEntities.remove(id);
}
}
public static void putDormantChunk(long coords, Chunk chunk)
{
Cache<Long, Chunk> cache = dormantChunkCache.get(chunk.worldObj);
if (cache != null)
{
cache.put(coords, chunk);
}
}
public static Chunk fetchDormantChunk(long coords, World world)
{
Cache<Long, Chunk> cache = dormantChunkCache.get(world);
return cache == null ? null : cache.getIfPresent(coords);
}
static void captureConfig(File configDir)
{
cfgFile = new File(configDir,"forgeChunkLoading.cfg");
config = new Configuration(cfgFile, true);
config.categories.clear();
try
{
config.load();
}
catch (Exception e)
{
File dest = new File(cfgFile.getParentFile(),"forgeChunkLoading.cfg.bak");
if (dest.exists())
{
dest.delete();
}
cfgFile.renameTo(dest);
FMLLog.log(Level.SEVERE, e, "A critical error occured reading the forgeChunkLoading.cfg file, defaults will be used - the invalid file is backed up at forgeChunkLoading.cfg.bak");
}
config.addCustomCategoryComment("defaults", "Default configuration for forge chunk loading control");
Property maxTicketCount = config.get("defaults", "maximumTicketCount", 200);
maxTicketCount.comment = "The default maximum ticket count for a mod which does not have an override\n" +
"in this file. This is the number of chunk loading requests a mod is allowed to make.";
defaultMaxCount = maxTicketCount.getInt(200);
Property maxChunks = config.get("defaults", "maximumChunksPerTicket", 25);
maxChunks.comment = "The default maximum number of chunks a mod can force, per ticket, \n" +
"for a mod without an override. This is the maximum number of chunks a single ticket can force.";
defaultMaxChunks = maxChunks.getInt(25);
Property playerTicketCount = config.get("defaults", "playetTicketCount", 500);
playerTicketCount.comment = "The number of tickets a player can be assigned instead of a mod. This is shared across all mods and it is up to the mods to use it.";
playerTicketLength = playerTicketCount.getInt(500);
Property dormantChunkCacheSizeProperty = config.get("defaults", "dormantChunkCacheSize", 0);
dormantChunkCacheSizeProperty.comment = "Unloaded chunks can first be kept in a dormant cache for quicker\n" +
"loading times. Specify the size of that cache here";
dormantChunkCacheSize = dormantChunkCacheSizeProperty.getInt(0);
FMLLog.info("Configured a dormant chunk cache size of %d", dormantChunkCacheSizeProperty.getInt(0));
Property modOverridesEnabled = config.get("defaults", "enabled", true);
modOverridesEnabled.comment = "Are mod overrides enabled?";
overridesEnabled = modOverridesEnabled.getBoolean(true);
config.addCustomCategoryComment("Forge", "Sample mod specific control section.\n" +
"Copy this section and rename the with the modid for the mod you wish to override.\n" +
"A value of zero in either entry effectively disables any chunkloading capabilities\n" +
"for that mod");
Property sampleTC = config.get("Forge", "maximumTicketCount", 200);
sampleTC.comment = "Maximum ticket count for the mod. Zero disables chunkloading capabilities.";
sampleTC = config.get("Forge", "maximumChunksPerTicket", 25);
sampleTC.comment = "Maximum chunks per ticket for the mod.";
for (String mod : config.categories.keySet())
{
if (mod.equals("Forge") || mod.equals("defaults"))
{
continue;
}
Property modTC = config.get(mod, "maximumTicketCount", 200);
Property modCPT = config.get(mod, "maximumChunksPerTicket", 25);
}
}
public static Map<String,Property> getConfigMapFor(Object mod)
{
ModContainer container = getContainer(mod);
if (container != null)
{
Map<String, Property> map = config.categories.get(container.getModId());
if (map == null)
{
map = Maps.newHashMap();
config.categories.put(container.getModId(), map);
}
return map;
}
return null;
}
public static void addConfigProperty(Object mod, String propertyName, String value, Property.Type type)
{
ModContainer container = getContainer(mod);
if (container != null)
{
Map<String, Property> props = config.categories.get(container.getModId());
props.put(propertyName, new Property(propertyName, value, type));
}
}
} |
package org.neo4j.server;
import java.io.File;
import org.apache.commons.configuration.Configuration;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.server.configuration.Configurator;
import org.neo4j.server.configuration.validation.DatabaseLocationMustBeSpecifiedRule;
import org.neo4j.server.configuration.validation.Validator;
import org.neo4j.server.database.Database;
import org.neo4j.server.logging.Logger;
import org.neo4j.server.startup.healthcheck.StartupHealthCheckFailedException;
import org.neo4j.server.startup.healthcheck.ConfigFileMustBePresentRule;
import org.neo4j.server.startup.healthcheck.StartupHealthCheck;
import org.neo4j.server.web.JettyWebServer;
import org.neo4j.server.web.WebServer;
import org.tanukisoftware.wrapper.WrapperListener;
/**
* Application entry point for the Neo4j Server.
*/
public class NeoServer implements WrapperListener {
public static final Logger log = Logger.getLogger(NeoServer.class);
public static final String NEO_CONFIGDIR_PROPERTY = "org.neo4j.server.properties";
public static final String DEFAULT_NEO_CONFIGDIR = File.separator + "etc" + File.separator + "neo";
private static final String WEBSERVICE_PACKAGES = "org.neo4j.webservice.packages";
private static final String DATABASE_LOCATION = "org.neo4j.database.location";
private static final String WEBSERVER_PORT = "org.neo4j.webserver.port";
private static final int DEFAULT_WEBSERVER_PORT = 7474;
private Configurator configurator;
private Database database;
private WebServer webServer;
/**
* For test purposes only.
*/
NeoServer(Configurator configurator, Database db, WebServer ws) {
this.configurator = configurator;
this.database = db;
this.webServer = ws;
}
public NeoServer() {
StartupHealthCheck healthCheck = new StartupHealthCheck(new ConfigFileMustBePresentRule());
if(!healthCheck.run()) {
throw new StartupHealthCheckFailedException("Startup healthcheck failed, server is not properly configured. Check logs for details.");
}
Validator validator = new Validator(new DatabaseLocationMustBeSpecifiedRule());
this.configurator = new Configurator(validator, getConfigFile());
this.webServer = new JettyWebServer();
this.database = new Database(configurator.configuration().getString(DATABASE_LOCATION));
}
public Integer start(String[] args) {
try {
webServer.setPort(configurator.configuration().getInt(WEBSERVER_PORT, DEFAULT_WEBSERVER_PORT));
webServer.addPackages(convertPropertiesToSingleString(configurator.configuration().getStringArray(WEBSERVICE_PACKAGES)));
webServer.start();
log.info("Started Neo Server on port [%s]", webServer.getPort());
return 0;
} catch (Exception e) {
log.error("Failed to start Neo Server on port [%s]", webServer.getPort());
return 1;
}
}
protected void stop() {
stop(0);
}
public int stop(int stopArg) {
int portNo = -1;
String location = "unknown";
try {
if (database != null) {
location = database.getLocation();
database.shutdown();
database = null;
}
if (webServer != null) {
portNo = webServer.getPort();
webServer.shutdown();
webServer = null;
}
configurator = null;
log.info("Successfully shutdown Neo Server on port [%d], database [%s]", portNo, location);
return 0;
} catch (Exception e) {
log.error("Failed to cleanly shutdown Neo Server on port [%d], database [%s]. Reason [%s] ", portNo, location, e.getMessage());
return 1;
}
}
public GraphDatabaseService database() {
return database.db;
}
public WebServer webServer() {
return webServer;
}
public Configuration configuration() {
return configurator.configuration();
}
public void controlEvent(int controlArg) {
// Do nothing for now, this is needed by the WrapperListener interface
}
private static File getConfigFile() {
return new File(System.getProperty(NEO_CONFIGDIR_PROPERTY, DEFAULT_NEO_CONFIGDIR));
}
private static String convertPropertiesToSingleString(String[] properties) {
if(properties == null || properties.length < 1) {
return null;
}
StringBuilder sb = new StringBuilder();
// Nasty string hacks - commons config gives us nice-ish collections, but Jetty wants to load with stringified properties
for(String s : properties) {
sb.append(s);
sb.append(", ");
}
String str = sb.toString();
return str.substring(0, str.length() -2);
}
public static void main(String args[]) {
final NeoServer neo = new NeoServer();
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
log.info("Neo Server shutdown initiated by kill signal");
neo.stop();
}
});
neo.start(args);
}
} |
import com.github.abola.crawler.CrawlerPack;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.util.ArrayList;
import java.util.List;
class PttGossiping {
final static String gossipMainPage = "https:
final static String gossipIndexPage = "https:
static Integer loadLastPosts = 50;
public static void main(String[] argv){
String prevPage =
CrawlerPack.start()
.addCookie("over18","1") // cookie
.getFromHtml(gossipMainPage) // HTML
.select(".action-bar .pull-right > a")
.get(1).attr("href")
.replaceAll("/bbs/Gossiping/index([0-9]+).html", "$1");
// index
Integer lastPage = Integer.valueOf(prevPage)+1;
List<String> lastPostsLink = new ArrayList<String>();
while ( loadLastPosts > lastPostsLink.size() ){
String currPage = String.format(gossipIndexPage, lastPage
Elements links =
CrawlerPack.start()
.addCookie("over18", "1")
.getFromHtml(currPage)
.select(".title > a");
for( Element link: links) lastPostsLink.add( link.attr("href") );
}
for(String url : lastPostsLink){
System.out.println(url);
}
}
} |
package deploy;
import actuator.GRTVictor;
import com.sun.squawk.pragma.ForceInlinedPragma;
import controller.PrimaryDriveController;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import logger.GRTLogger;
import mechanism.GRTDriveTrain;
import mechanism.GRTRobotBase;
import sensor.GRTAttack3Joystick;
import sensor.GRTBatterySensor;
import sensor.base.*;
/**
* Constructor for the main robot. Put all robot components here.
*
* @author ajc
*/
public class MainRobot extends GRTRobot {
//Teleop Controllers
private PrimaryDriveController driveControl;
private GRTDriverStation driverStation;
private GRTRobotBase robotBase;
private GRTLogger logger = GRTLogger.getLogger();
/**
* Initializer for the robot.
*/
public MainRobot() {
//Init the logging files.
Date d = new Date();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
String dateStr = "" + cal.get(Calendar.YEAR) + "-" + cal.get(Calendar.MONTH)+1 + "T" + cal.get(Calendar.HOUR_OF_DAY)+cal.get(Calendar.MINUTE) + cal.get(Calendar.SECOND);
logger.logInfo("Date string = " + dateStr);
String loggingFiles[] = new String[] { "/logs/" + dateStr + "_info.log", "/logs/" + dateStr + "_success.log", "/logs/" + dateStr + "_error.log", "/logs/" + dateStr + "_all.log" } ;
logger.setLoggingFiles(loggingFiles);
logger.enableFileLogging();
logger.logInfo("GRTFramework v6 starting up.");
//Driver station components
GRTAttack3Joystick primary = new GRTAttack3Joystick(1, 12, "primary");
GRTAttack3Joystick secondary = new GRTAttack3Joystick(2, 12, "secondary");
primary.startPolling();
secondary.startPolling();
primary.enable();
secondary.enable();
logger.logInfo("Joysticks initialized");
//Battery Sensor
GRTBatterySensor batterySensor = new GRTBatterySensor(10, "battery");
batterySensor.startPolling();
batterySensor.enable();
// PWM outputs
GRTVictor leftDT1 = new GRTVictor(2, "leftDT1");
GRTVictor leftDT2 = new GRTVictor(3, "leftDT2");
GRTVictor rightDT1 = new GRTVictor(8, "rightDT1");
GRTVictor rightDT2 = new GRTVictor(9, "rightDT2");
leftDT1.enable();
leftDT2.enable();
rightDT1.enable();
rightDT2.enable();
logger.logInfo("Motors initialized");
//Mechanisms
GRTDriveTrain dt = new GRTDriveTrain(leftDT1, leftDT2, rightDT1, rightDT2);
robotBase = new GRTRobotBase(dt, batterySensor);
driverStation = new GRTAttack3DriverStation(primary, secondary, "driverStation");
driverStation.enable();
logger.logInfo("Mechanisms initialized");
//Controllers
driveControl = new PrimaryDriveController(robotBase, driverStation, "driveControl");
logger.logInfo("Controllers Initialized");
addTeleopController(driveControl);
logger.logSuccess("Ready to drive.");
}
public void disabled() {
logger.logInfo("Disabling robot. Halting drivetrain");
robotBase.tankDrive(0.0, 0.0);
}
} |
package com.psddev.dari.db;
import com.jolbox.bonecp.BoneCPDataSource;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.PaginatedResult;
import com.psddev.dari.util.PeriodicValue;
import com.psddev.dari.util.Profiler;
import com.psddev.dari.util.PullThroughValue;
import com.psddev.dari.util.Settings;
import com.psddev.dari.util.SettingsException;
import com.psddev.dari.util.Stats;
import com.psddev.dari.util.StringUtils;
import com.psddev.dari.util.TypeDefinition;
import java.io.ByteArrayInputStream;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.ref.WeakReference;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLTimeoutException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import javax.sql.DataSource;
import org.iq80.snappy.Snappy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Database backed by a SQL engine. */
public class SqlDatabase extends AbstractDatabase<Connection> {
public static final String DATA_SOURCE_SETTING = "dataSource";
public static final String JDBC_DRIVER_CLASS_SETTING = "jdbcDriverClass";
public static final String JDBC_URL_SETTING = "jdbcUrl";
public static final String JDBC_USER_SETTING = "jdbcUser";
public static final String JDBC_PASSWORD_SETTING = "jdbcPassword";
public static final String JDBC_POOL_SIZE_SETTING = "jdbcPoolSize";
public static final String READ_DATA_SOURCE_SETTING = "readDataSource";
public static final String READ_JDBC_DRIVER_CLASS_SETTING = "readJdbcDriverClass";
public static final String READ_JDBC_URL_SETTING = "readJdbcUrl";
public static final String READ_JDBC_USER_SETTING = "readJdbcUser";
public static final String READ_JDBC_PASSWORD_SETTING = "readJdbcPassword";
public static final String READ_JDBC_POOL_SIZE_SETTING = "readJdbcPoolSize";
public static final String VENDOR_CLASS_SETTING = "vendorClass";
public static final String COMPRESS_DATA_SUB_SETTING = "compressData";
public static final String RECORD_TABLE = "Record";
public static final String RECORD_UPDATE_TABLE = "RecordUpdate";
public static final String SYMBOL_TABLE = "Symbol";
public static final String ID_COLUMN = "id";
public static final String TYPE_ID_COLUMN = "typeId";
public static final String IN_ROW_INDEX_COLUMN = "inRowIndex";
public static final String DATA_COLUMN = "data";
public static final String SYMBOL_ID_COLUMN = "symbolId";
public static final String UPDATE_DATE_COLUMN = "updateDate";
public static final String VALUE_COLUMN = "value";
public static final String EXTRA_COLUMNS_QUERY_OPTION = "sql.extraColumns";
public static final String EXTRA_JOINS_QUERY_OPTION = "sql.extraJoins";
public static final String EXTRA_WHERE_QUERY_OPTION = "sql.extraWhere";
public static final String EXTRA_HAVING_QUERY_OPTION = "sql.extraHaving";
public static final String MYSQL_INDEX_HINT_QUERY_OPTION = "sql.mysqlIndexHint";
public static final String RETURN_ORIGINAL_DATA_QUERY_OPTION = "sql.returnOriginalData";
public static final String USE_JDBC_FETCH_SIZE_QUERY_OPTION = "sql.useJdbcFetchSize";
public static final String USE_READ_DATA_SOURCE_QUERY_OPTION = "sql.useReadDataSource";
public static final String SKIP_INDEX_STATE_EXTRA = "sql.skipIndex";
public static final String INDEX_TABLE_INDEX_OPTION = "sql.indexTable";
public static final String INDEX_TABLE_USE_COLUMN_NAMES_OPTION = "sql.indexTableUseColumnNames";
public static final String INDEX_TABLE_IS_SOURCE_OPTION = "sql.indexTableIsSource";
public static final String INDEX_TABLE_IS_READONLY_OPTION = "sql.indexTableIsReadonly";
public static final String INDEX_TABLE_SOURCE_TABLES_OPTION = "sql.indexTableSources";
public static final String EXTRA_COLUMN_EXTRA_PREFIX = "sql.extraColumn.";
public static final String ORIGINAL_DATA_EXTRA = "sql.originalData";
private static final Logger LOGGER = LoggerFactory.getLogger(SqlDatabase.class);
private static final String SHORT_NAME = "SQL";
private static final Stats STATS = new Stats(SHORT_NAME);
private static final String QUERY_STATS_OPERATION = "Query";
private static final String UPDATE_STATS_OPERATION = "Update";
private static final String QUERY_PROFILER_EVENT = SHORT_NAME + " " + QUERY_STATS_OPERATION;
private static final String UPDATE_PROFILER_EVENT = SHORT_NAME + " " + UPDATE_STATS_OPERATION;
private final static List<SqlDatabase> INSTANCES = new ArrayList<SqlDatabase>();
{
INSTANCES.add(this);
}
private volatile DataSource dataSource;
private volatile DataSource readDataSource;
private volatile SqlVendor vendor;
private volatile boolean compressData;
/**
* Quotes the given {@code identifier} so that it's safe to use
* in a SQL query.
*/
public static String quoteIdentifier(String identifier) {
return "\"" + StringUtils.replaceAll(identifier, "\\\\", "\\\\\\\\", "\"", "\"\"") + "\"";
}
/**
* Quotes the given {@code value} so that it's safe to use
* in a SQL query.
*/
public static String quoteValue(Object value) {
if (value == null) {
return "NULL";
} else if (value instanceof Number) {
return value.toString();
} else if (value instanceof byte[]) {
return "X'" + StringUtils.hex((byte[]) value) + "'";
} else {
return "'" + value.toString().replace("'", "''").replace("\\", "\\\\") + "'";
}
}
/** Closes all resources used by all instances. */
public static void closeAll() {
for (SqlDatabase database : INSTANCES) {
database.close();
}
INSTANCES.clear();
}
/**
* Creates an {@link SqlDatabaseException} that occurred during
* an execution of a query.
*/
private SqlDatabaseException createQueryException(
SQLException error,
String sqlQuery,
Query<?> query) {
String message = error.getMessage();
if (error instanceof SQLTimeoutException || message.contains("timeout")) {
return new SqlDatabaseException.ReadTimeout(this, error, sqlQuery, query);
} else {
return new SqlDatabaseException(this, error, sqlQuery, query);
}
}
/** Returns the JDBC data source used for general database operations. */
public DataSource getDataSource() {
return dataSource;
}
private static final Map<String, Class<? extends SqlVendor>> VENDOR_CLASSES; static {
Map<String, Class<? extends SqlVendor>> m = new HashMap<String, Class<? extends SqlVendor>>();
m.put("H2", SqlVendor.H2.class);
m.put("MySQL", SqlVendor.MySQL.class);
m.put("PostgreSQL", SqlVendor.PostgreSQL.class);
m.put("Oracle", SqlVendor.Oracle.class);
VENDOR_CLASSES = m;
}
/** Sets the JDBC data source used for general database operations. */
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
if (dataSource == null) {
return;
}
synchronized (this) {
try {
boolean writable = false;
if (vendor == null) {
Connection connection;
try {
connection = openConnection();
writable = true;
} catch (DatabaseException error) {
LOGGER.debug("Can't read vendor information from the writable server!", error);
connection = openReadConnection();
}
try {
DatabaseMetaData meta = connection.getMetaData();
String vendorName = meta.getDatabaseProductName();
Class<? extends SqlVendor> vendorClass = VENDOR_CLASSES.get(vendorName);
LOGGER.info(
"Initializing SQL vendor for [{}]: [{}] -> [{}]",
new Object[] { getName(), vendorName, vendorClass });
vendor = vendorClass != null ? TypeDefinition.getInstance(vendorClass).newInstance() : new SqlVendor();
vendor.setDatabase(this);
} finally {
closeConnection(connection);
}
}
tableNames.refresh();
symbols.invalidate();
if (writable) {
vendor.createRecord(this);
vendor.createRecordUpdate(this);
vendor.createSymbol(this);
for (SqlIndex index : SqlIndex.values()) {
if (index != SqlIndex.CUSTOM) {
vendor.createRecordIndex(
this,
index.getReadTable(this, null).getName(this, null),
index);
}
}
tableNames.refresh();
symbols.invalidate();
}
} catch (SQLException ex) {
throw new SqlDatabaseException(this, "Can't check for required tables!", ex);
}
}
}
/** Returns the JDBC data source used exclusively for read operations. */
public DataSource getReadDataSource() {
return this.readDataSource;
}
/** Sets the JDBC data source used exclusively for read operations. */
public void setReadDataSource(DataSource readDataSource) {
this.readDataSource = readDataSource;
}
/** Returns the vendor-specific SQL engine information. */
public SqlVendor getVendor() {
return vendor;
}
/** Sets the vendor-specific SQL engine information. */
public void setVendor(SqlVendor vendor) {
this.vendor = vendor;
}
/** Returns {@code true} if the data should be compressed. */
public boolean isCompressData() {
return compressData;
}
/** Sets whether the data should be compressed. */
public void setCompressData(boolean compressData) {
this.compressData = compressData;
}
/**
* Returns {@code true} if the {@link #RECORD_TABLE} in this database
* has the {@link #IN_ROW_INDEX_COLUMN}.
*/
public boolean hasInRowIndex() {
return hasInRowIndex;
}
/**
* Returns {@code true} if all comparisons executed in this database
* should ignore case by default.
*/
public boolean comparesIgnoreCase() {
return comparesIgnoreCase;
}
/**
* Returns {@code true} if this database contains a table with
* the given {@code name}.
*/
public boolean hasTable(String name) {
if (name == null) {
return false;
} else {
Set<String> names = tableNames.get();
return names != null && names.contains(name.toLowerCase());
}
}
private transient volatile boolean hasInRowIndex;
private transient volatile boolean comparesIgnoreCase;
private final transient PeriodicValue<Set<String>> tableNames = new PeriodicValue<Set<String>>(0.0, 60.0) {
@Override
protected Set<String> update() {
if (getDataSource() == null) {
return Collections.emptySet();
}
Connection connection;
try {
connection = openConnection();
} catch (DatabaseException error) {
LOGGER.debug("Can't read table names from the writable server!", error);
connection = openReadConnection();
}
try {
SqlVendor vendor = getVendor();
String recordTable = null;
int maxStringVersion = 0;
Set<String> loweredNames = new HashSet<String>();
for (String name : vendor.getTables(connection)) {
String loweredName = name.toLowerCase();
loweredNames.add(loweredName);
if ("record".equals(loweredName)) {
recordTable = name;
} else if (loweredName.startsWith("recordstring")) {
int version = ObjectUtils.to(int.class, loweredName.substring(12));
if (version > maxStringVersion) {
maxStringVersion = version;
}
}
}
if (recordTable != null) {
hasInRowIndex = vendor.hasInRowIndex(connection, recordTable);
}
comparesIgnoreCase = maxStringVersion >= 3;
return loweredNames;
} catch (SQLException error) {
LOGGER.error("Can't query table names!", error);
return get();
} finally {
closeConnection(connection);
}
}
};
/**
* Returns an unique numeric ID for the given {@code symbol}.
*/
public int getSymbolId(String symbol) {
Integer id = symbols.get().get(symbol);
if (id == null) {
SqlVendor vendor = getVendor();
Connection connection = openConnection();
try {
List<Object> parameters = new ArrayList<Object>();
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.append("INSERT /*! IGNORE */ INTO ");
vendor.appendIdentifier(insertBuilder, SYMBOL_TABLE);
insertBuilder.append(" (");
vendor.appendIdentifier(insertBuilder, VALUE_COLUMN);
insertBuilder.append(") VALUES (");
vendor.appendBindValue(insertBuilder, symbol, parameters);
insertBuilder.append(")");
String insertSql = insertBuilder.toString();
try {
Static.executeUpdateWithList(connection, insertSql, parameters);
} catch (SQLException ex) {
if (!Static.isIntegrityConstraintViolation(ex)) {
throw createQueryException(ex, insertSql, null);
}
}
StringBuilder selectBuilder = new StringBuilder();
selectBuilder.append("SELECT ");
vendor.appendIdentifier(selectBuilder, SYMBOL_ID_COLUMN);
selectBuilder.append(" FROM ");
vendor.appendIdentifier(selectBuilder, SYMBOL_TABLE);
selectBuilder.append(" WHERE ");
vendor.appendIdentifier(selectBuilder, VALUE_COLUMN);
selectBuilder.append("=");
vendor.appendValue(selectBuilder, symbol);
String selectSql = selectBuilder.toString();
Statement statement = null;
ResultSet result = null;
try {
statement = connection.createStatement();
result = statement.executeQuery(selectSql);
result.next();
id = result.getInt(1);
symbols.get().put(symbol, id);
} catch (SQLException ex) {
throw createQueryException(ex, selectSql, null);
} finally {
closeResources(null, statement, result);
}
} finally {
closeConnection(connection);
}
}
return id;
}
// Cache of all internal symbols.
private transient PullThroughValue<Map<String, Integer>> symbols = new PullThroughValue<Map<String, Integer>>() {
@Override
protected Map<String, Integer> produce() {
SqlVendor vendor = getVendor();
StringBuilder selectBuilder = new StringBuilder();
selectBuilder.append("SELECT ");
vendor.appendIdentifier(selectBuilder, SYMBOL_ID_COLUMN);
selectBuilder.append(",");
vendor.appendIdentifier(selectBuilder, VALUE_COLUMN);
selectBuilder.append(" FROM ");
vendor.appendIdentifier(selectBuilder, SYMBOL_TABLE);
String selectSql = selectBuilder.toString();
Connection connection;
Statement statement = null;
ResultSet result = null;
try {
connection = openConnection();
} catch (DatabaseException error) {
LOGGER.debug("Can't read symbols from the writable server!", error);
connection = openReadConnection();
}
try {
statement = connection.createStatement();
result = statement.executeQuery(selectSql);
Map<String, Integer> symbols = new ConcurrentHashMap<String, Integer>();
while (result.next()) {
symbols.put(new String(result.getBytes(2), StringUtils.UTF_8), result.getInt(1));
}
return symbols;
} catch (SQLException ex) {
throw createQueryException(ex, selectSql, null);
} finally {
closeResources(connection, statement, result);
}
}
};
/**
* Returns the underlying JDBC connection.
*
* @deprecated Use {@link #openConnection} instead.
*/
@Deprecated
public Connection getConnection() {
return openConnection();
}
/** Closes any resources used by this database. */
public void close() {
DataSource dataSource = getDataSource();
if (dataSource instanceof BoneCPDataSource) {
LOGGER.info("Closing BoneCP data source in {}", getName());
((BoneCPDataSource) dataSource).close();
}
DataSource readDataSource = getReadDataSource();
if (readDataSource instanceof BoneCPDataSource) {
LOGGER.info("Closing BoneCP read data source in {}", getName());
((BoneCPDataSource) readDataSource).close();
}
setDataSource(null);
setReadDataSource(null);
}
/**
* Builds an SQL statement that can be used to get a count of all
* objects matching the given {@code query}.
*/
public String buildCountStatement(Query<?> query) {
return new SqlQuery(this, query).countStatement();
}
/**
* Builds an SQL statement that can be used to delete all rows
* matching the given {@code query}.
*/
public String buildDeleteStatement(Query<?> query) {
return new SqlQuery(this, query).deleteStatement();
}
/**
* Builds an SQL statement that can be used to get all objects
* grouped by the values of the given {@code groupFields}.
*/
public String buildGroupStatement(Query<?> query, String... groupFields) {
return new SqlQuery(this, query).groupStatement(groupFields);
}
/**
* Builds an SQL statement that can be used to get when the objects
* matching the given {@code query} were last updated.
*/
public String buildLastUpdateStatement(Query<?> query) {
return new SqlQuery(this, query).lastUpdateStatement();
}
/**
* Builds an SQL statement that can be used to list all rows
* matching the given {@code query}.
*/
public String buildSelectStatement(Query<?> query) {
return new SqlQuery(this, query).selectStatement();
}
/** Closes all the given SQL resources safely. */
private void closeResources(Connection connection, Statement statement, ResultSet result) {
if (result != null) {
try {
result.close();
} catch (SQLException ex) {
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
}
}
if (connection != null &&
connection != readConnection.get()) {
try {
connection.close();
} catch (SQLException ex) {
}
}
}
private byte[] serializeData(State state) {
Map<String, Object> values = state.getSimpleValues();
Iterator<Map.Entry<String, Object>> iter = values.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, Object> entry = iter.next();
ObjectField field = state.getField(entry.getKey());
if (field != null) {
if (Static.getIndexTableIsSource(field) || Static.isExtraFieldOfSourceIndexTable(field)) {
iter.remove();
}
}
}
return serializeData(values);
}
private byte[] serializeData(Map<String, Object> dataMap) {
byte[] dataBytes = ObjectUtils.toJson(dataMap).getBytes(StringUtils.UTF_8);
if (isCompressData()) {
byte[] compressed = new byte[Snappy.maxCompressedLength(dataBytes.length)];
int compressedLength = Snappy.compress(dataBytes, 0, dataBytes.length, compressed, 0);
dataBytes = new byte[compressedLength + 1];
dataBytes[0] = 's';
System.arraycopy(compressed, 0, dataBytes, 1, compressedLength);
}
return dataBytes;
}
@SuppressWarnings("unchecked")
private Map<String, Object> unserializeData(byte[] dataBytes) {
char format = '\0';
while (true) {
format = (char) dataBytes[0];
if (format == 's') {
dataBytes = Snappy.uncompress(dataBytes, 1, dataBytes.length - 1);
} else if (format == '{') {
return (Map<String, Object>) ObjectUtils.fromJson(new String(dataBytes, StringUtils.UTF_8));
} else {
break;
}
}
throw new IllegalStateException(String.format(
"Unknown format! ([%s])", format));
}
/**
* Creates a previously saved object using the given {@code resultSet}.
*/
private <T> T createSavedObjectWithResultSet(ResultSet resultSet, Query<T> query) throws SQLException {
T object = createSavedObject(resultSet.getObject(2), resultSet.getObject(1), query);
State objectState = State.getInstance(object);
if (!objectState.isReferenceOnly()) {
byte[] data = resultSet.getBytes(3);
if (data != null) {
objectState.putAll(unserializeData(data));
Boolean returnOriginal = ObjectUtils.to(Boolean.class, query.getOptions().get(RETURN_ORIGINAL_DATA_QUERY_OPTION));
if (returnOriginal == null) {
returnOriginal = Boolean.FALSE;
}
if (returnOriginal) {
objectState.getExtras().put(ORIGINAL_DATA_EXTRA, data);
}
}
}
ResultSetMetaData meta = resultSet.getMetaData();
for (int i = 4, count = meta.getColumnCount(); i <= count; ++ i) {
String columnName = meta.getColumnLabel(i);
if (query.getExtraSourceColumns().contains(columnName)) {
objectState.put(columnName, resultSet.getObject(i));
} else {
objectState.getExtras().put(EXTRA_COLUMN_EXTRA_PREFIX + meta.getColumnLabel(i), resultSet.getObject(i));
}
}
return swapObjectType(query, object);
}
/**
* Executes the given read {@code statement} (created from the given
* {@code sqlQuery}) before the given {@code timeout} (in seconds).
*/
private ResultSet executeQueryBeforeTimeout(
Statement statement,
String sqlQuery,
int timeout)
throws SQLException {
if (timeout > 0 && !(vendor instanceof SqlVendor.PostgreSQL)) {
statement.setQueryTimeout(timeout);
}
Stats.Timer timer = STATS.startTimer();
Profiler.Static.startThreadEvent(QUERY_PROFILER_EVENT);
try {
return statement.executeQuery(sqlQuery);
} finally {
double duration = timer.stop(QUERY_STATS_OPERATION);
Profiler.Static.stopThreadEvent(sqlQuery);
LOGGER.debug(
"Read from the SQL database using [{}] in [{}]ms",
sqlQuery, duration);
}
}
/**
* Selects the first object that matches the given {@code sqlQuery}
* with options from the given {@code query}.
*/
public <T> T selectFirstWithOptions(String sqlQuery, Query<T> query) {
sqlQuery = vendor.rewriteQueryWithLimitClause(sqlQuery, 1, 0);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
return result.next() ? createSavedObjectWithResultSet(result, query) : null;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(connection, statement, result);
}
}
/**
* Selects the first object that matches the given {@code sqlQuery}
* without a timeout.
*/
public Object selectFirst(String sqlQuery) {
return selectFirstWithOptions(sqlQuery, null);
}
/**
* Selects a list of objects that match the given {@code sqlQuery}
* with options from the given {@code query}.
*/
public <T> List<T> selectListWithOptions(String sqlQuery, Query<T> query) {
Connection connection = null;
Statement statement = null;
ResultSet result = null;
List<T> objects = new ArrayList<T>();
int timeout = getQueryReadTimeout(query);
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, timeout);
while (result.next()) {
objects.add(createSavedObjectWithResultSet(result, query));
}
return objects;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(connection, statement, result);
}
}
/**
* Selects a list of objects that match the given {@code sqlQuery}
* without a timeout.
*/
public List<Object> selectList(String sqlQuery) {
return selectListWithOptions(sqlQuery, null);
}
/**
* Returns an iterable that selects all objects matching the given
* {@code sqlQuery} with options from the given {@code query}.
*/
public <T> Iterable<T> selectIterableWithOptions(
final String sqlQuery,
final int fetchSize,
final Query<T> query) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new SqlIterator<T>(sqlQuery, fetchSize, query);
}
};
}
private class SqlIterator<T> implements Iterator<T> {
private final String sqlQuery;
private final Query<T> query;
private final Connection connection;
private final Statement statement;
private final ResultSet result;
private boolean hasNext = true;
public SqlIterator(String initialSqlQuery, int fetchSize, Query<T> initialQuery) {
sqlQuery = initialSqlQuery;
query = initialQuery;
try {
connection = openReadConnection();
statement = connection.createStatement();
statement.setFetchSize(
getVendor() instanceof SqlVendor.MySQL ? Integer.MIN_VALUE :
fetchSize <= 0 ? 200 :
fetchSize);
result = statement.executeQuery(sqlQuery);
moveToNext();
} catch (SQLException ex) {
close();
throw createQueryException(ex, sqlQuery, query);
}
}
private void moveToNext() throws SQLException {
if (hasNext) {
hasNext = result.next();
if (!hasNext) {
close();
}
}
}
public void close() {
hasNext = false;
closeResources(connection, statement, result);
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public T next() {
if (!hasNext) {
throw new NoSuchElementException();
}
try {
T object = createSavedObjectWithResultSet(result, query);
moveToNext();
return object;
} catch (SQLException ex) {
close();
throw createQueryException(ex, sqlQuery, query);
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
protected void finalize() {
close();
}
}
/**
* Fills the placeholders in the given {@code sqlQuery} with the given
* {@code parameters}.
*/
private static String fillPlaceholders(String sqlQuery, Object... parameters) {
StringBuilder filled = new StringBuilder();
int prevPh = 0;
for (int ph, index = 0; (ph = sqlQuery.indexOf('?', prevPh)) > -1; ++ index) {
filled.append(sqlQuery.substring(prevPh, ph));
prevPh = ph + 1;
filled.append(quoteValue(parameters[index]));
}
filled.append(sqlQuery.substring(prevPh));
return filled.toString();
}
/**
* Executes the given write {@code sqlQuery} with the given
* {@code parameters}.
*
* @deprecated Use {@link Static#executeUpdate} instead.
*/
@Deprecated
public int executeUpdate(String sqlQuery, Object... parameters) {
try {
return Static.executeUpdateWithArray(getConnection(), sqlQuery, parameters);
} catch (SQLException ex) {
throw createQueryException(ex, fillPlaceholders(sqlQuery, parameters), null);
}
}
/**
* Reads the given {@code resultSet} into a list of maps
* and closes it.
*/
public List<Map<String, Object>> readResultSet(ResultSet resultSet) throws SQLException {
try {
ResultSetMetaData meta = resultSet.getMetaData();
List<String> columnNames = new ArrayList<String>();
for (int i = 1, count = meta.getColumnCount(); i < count; ++ i) {
columnNames.add(meta.getColumnName(i));
}
List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
while (resultSet.next()) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
maps.add(map);
for (int i = 0, size = columnNames.size(); i < size; ++ i) {
map.put(columnNames.get(i), resultSet.getObject(i + 1));
}
}
return maps;
} finally {
resultSet.close();
}
}
@Override
public Connection openConnection() {
DataSource dataSource = getDataSource();
if (dataSource == null) {
throw new SqlDatabaseException(this, "No SQL data source!");
}
try {
return dataSource.getConnection();
} catch (SQLException ex) {
throw new SqlDatabaseException(this, "Can't connect to the SQL engine!", ex);
}
}
@Override
protected Connection doOpenReadConnection() {
Connection connection = readConnection.get();
if (connection != null) {
return connection;
}
DataSource readDataSource = getReadDataSource();
if (readDataSource == null) {
readDataSource = getDataSource();
}
if (readDataSource == null) {
throw new SqlDatabaseException(this, "No SQL data source!");
}
try {
return readDataSource.getConnection();
} catch (SQLException ex) {
throw new SqlDatabaseException(this, "Can't connect to the SQL engine!", ex);
}
}
// Opens a connection that should be used to execute the given query.
private Connection openQueryConnection(Query<?> query) {
if (query != null) {
Boolean useRead = ObjectUtils.to(Boolean.class, query.getOptions().get(USE_READ_DATA_SOURCE_QUERY_OPTION));
if (useRead == null) {
useRead = Boolean.TRUE;
}
if (!useRead) {
return openConnection();
}
}
return openReadConnection();
}
@Override
public void closeConnection(Connection connection) {
if (connection != null &&
connection != readConnection.get()) {
try {
connection.close();
} catch (SQLException ex) {
}
}
}
@Override
protected boolean isRecoverableError(Exception error) {
if (error instanceof SQLException) {
SQLException sqlError = (SQLException) error;
return "40001".equals(sqlError.getSQLState());
}
return false;
}
private final ThreadLocal<Connection> readConnection = new ThreadLocal<Connection>();
public void beginThreadLocalReadConnection() {
Connection connection = readConnection.get();
if (connection == null) {
connection = openReadConnection();
readConnection.set(connection);
}
}
public void endThreadLocalReadConnection() {
Connection connection = readConnection.get();
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
} finally {
readConnection.remove();
}
}
}
@Override
protected void doInitialize(String settingsKey, Map<String, Object> settings) {
close();
setReadDataSource(createDataSource(
settings,
READ_DATA_SOURCE_SETTING,
READ_JDBC_DRIVER_CLASS_SETTING,
READ_JDBC_URL_SETTING,
READ_JDBC_USER_SETTING,
READ_JDBC_PASSWORD_SETTING,
READ_JDBC_POOL_SIZE_SETTING));
setDataSource(createDataSource(
settings,
DATA_SOURCE_SETTING,
JDBC_DRIVER_CLASS_SETTING,
JDBC_URL_SETTING,
JDBC_USER_SETTING,
JDBC_PASSWORD_SETTING,
JDBC_POOL_SIZE_SETTING));
String vendorClassName = ObjectUtils.to(String.class, settings.get(VENDOR_CLASS_SETTING));
Class<?> vendorClass = null;
if (vendorClassName != null) {
vendorClass = ObjectUtils.getClassByName(vendorClassName);
if (vendorClass == null) {
throw new SettingsException(
VENDOR_CLASS_SETTING,
String.format("Can't find [%s]!",
vendorClassName));
} else if (!SqlVendor.class.isAssignableFrom(vendorClass)) {
throw new SettingsException(
VENDOR_CLASS_SETTING,
String.format("[%s] doesn't implement [%s]!",
vendorClass, Driver.class));
}
}
if (vendorClass != null) {
setVendor((SqlVendor) TypeDefinition.getInstance(vendorClass).newInstance());
}
Boolean compressData = ObjectUtils.coalesce(
ObjectUtils.to(Boolean.class, settings.get(COMPRESS_DATA_SUB_SETTING)),
Settings.get(Boolean.class, "dari/isCompressSqlData"));
if (compressData != null) {
setCompressData(compressData);
}
}
private static final Map<String, String> DRIVER_CLASS_NAMES; static {
Map<String, String> m = new HashMap<String, String>();
m.put("h2", "org.h2.Driver");
m.put("jtds", "net.sourceforge.jtds.jdbc.Driver");
m.put("mysql", "com.mysql.jdbc.Driver");
m.put("postgresql", "org.postgresql.Driver");
DRIVER_CLASS_NAMES = m;
}
private static final Set<WeakReference<Driver>> REGISTERED_DRIVERS = new HashSet<WeakReference<Driver>>();
private DataSource createDataSource(
Map<String, Object> settings,
String dataSourceSetting,
String jdbcDriverClassSetting,
String jdbcUrlSetting,
String jdbcUserSetting,
String jdbcPasswordSetting,
String jdbcPoolSizeSetting) {
Object dataSourceObject = settings.get(dataSourceSetting);
if (dataSourceObject instanceof DataSource) {
return (DataSource) dataSourceObject;
} else {
String url = ObjectUtils.to(String.class, settings.get(jdbcUrlSetting));
if (ObjectUtils.isBlank(url)) {
return null;
} else {
String driverClassName = ObjectUtils.to(String.class, settings.get(jdbcDriverClassSetting));
Class<?> driverClass = null;
if (driverClassName != null) {
driverClass = ObjectUtils.getClassByName(driverClassName);
if (driverClass == null) {
throw new SettingsException(
jdbcDriverClassSetting,
String.format("Can't find [%s]!",
driverClassName));
} else if (!Driver.class.isAssignableFrom(driverClass)) {
throw new SettingsException(
jdbcDriverClassSetting,
String.format("[%s] doesn't implement [%s]!",
driverClass, Driver.class));
}
} else {
int firstColonAt = url.indexOf(':');
if (firstColonAt > -1) {
++ firstColonAt;
int secondColonAt = url.indexOf(':', firstColonAt);
if (secondColonAt > -1) {
driverClass = ObjectUtils.getClassByName(DRIVER_CLASS_NAMES.get(url.substring(firstColonAt, secondColonAt)));
}
}
}
if (driverClass != null) {
Driver driver = null;
for (Enumeration<Driver> e = DriverManager.getDrivers(); e.hasMoreElements(); ) {
Driver d = e.nextElement();
if (driverClass.isInstance(d)) {
driver = d;
break;
}
}
if (driver == null) {
driver = (Driver) TypeDefinition.getInstance(driverClass).newInstance();
try {
LOGGER.info("Registering [{}]", driver);
DriverManager.registerDriver(driver);
} catch (SQLException ex) {
LOGGER.warn("Can't register [{}]!", driver);
}
}
if (driver != null) {
REGISTERED_DRIVERS.add(new WeakReference<Driver>(driver));
}
}
String user = ObjectUtils.to(String.class, settings.get(jdbcUserSetting));
String password = ObjectUtils.to(String.class, settings.get(jdbcPasswordSetting));
Integer poolSize = ObjectUtils.to(Integer.class, settings.get(jdbcPoolSizeSetting));
if (poolSize == null || poolSize <= 0) {
poolSize = 24;
}
int partitionCount = 3;
int connectionsPerPartition = poolSize / partitionCount;
LOGGER.info("Automatically creating BoneCP data source:" +
"\n\turl={}" +
"\n\tusername={}" +
"\n\tpoolSize={}" +
"\n\tconnectionsPerPartition={}" +
"\n\tpartitionCount={}", new Object[] {
url,
user,
poolSize,
connectionsPerPartition,
partitionCount
});
BoneCPDataSource bone = new BoneCPDataSource();
bone.setJdbcUrl(url);
bone.setUsername(user);
bone.setPassword(password);
bone.setMinConnectionsPerPartition(connectionsPerPartition);
bone.setMaxConnectionsPerPartition(connectionsPerPartition);
bone.setPartitionCount(partitionCount);
return bone;
}
}
}
/** Returns the read timeout associated with the given {@code query}. */
private int getQueryReadTimeout(Query<?> query) {
if (query != null) {
Double timeout = query.getTimeout();
if (timeout == null) {
timeout = getReadTimeout();
}
if (timeout > 0.0) {
return (int) Math.round(timeout);
}
}
return 0;
}
@Override
public <T> List<T> readAll(Query<T> query) {
return selectListWithOptions(buildSelectStatement(query), query);
}
@Override
public long readCount(Query<?> query) {
String sqlQuery = buildCountStatement(query);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
if (result.next()) {
Object countObj = result.getObject(1);
if (countObj instanceof Number) {
return ((Number) countObj).longValue();
}
}
return 0;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(connection, statement, result);
}
}
@Override
public <T> T readFirst(Query<T> query) {
if (query.getSorters().isEmpty()) {
Predicate predicate = query.getPredicate();
if (predicate instanceof CompoundPredicate) {
CompoundPredicate compoundPredicate = (CompoundPredicate) predicate;
if (PredicateParser.OR_OPERATOR.equals(compoundPredicate.getOperator())) {
for (Predicate child : compoundPredicate.getChildren()) {
Query<T> childQuery = query.clone();
childQuery.setPredicate(child);
T first = readFirst(childQuery);
if (first != null) {
return first;
}
}
return null;
}
}
}
return selectFirstWithOptions(buildSelectStatement(query), query);
}
@Override
public <T> Iterable<T> readIterable(Query<T> query, int fetchSize) {
Boolean useJdbc = ObjectUtils.to(Boolean.class, query.getOptions().get(USE_JDBC_FETCH_SIZE_QUERY_OPTION));
if (useJdbc == null) {
useJdbc = Boolean.TRUE;
}
if (useJdbc) {
return selectIterableWithOptions(buildSelectStatement(query), fetchSize, query);
} else {
return new ByIdIterable<T>(query, fetchSize);
}
}
private static class ByIdIterable<T> implements Iterable<T> {
private final Query<T> query;
private final int fetchSize;
public ByIdIterable(Query<T> query, int fetchSize) {
this.query = query;
this.fetchSize = fetchSize;
}
@Override
public Iterator<T> iterator() {
return new ByIdIterator<T>(query, fetchSize);
}
}
private static class ByIdIterator<T> implements Iterator<T> {
private final Query<T> query;
private final int fetchSize;
private UUID lastTypeId;
private UUID lastId;
private List<T> items;
private int index;
public ByIdIterator(Query<T> query, int fetchSize) {
if (!query.getSorters().isEmpty()) {
throw new IllegalArgumentException("Can't iterate over a query that has sorters!");
}
this.query = query.clone().timeout(0.0).sortAscending("_type").sortAscending("_id");
this.fetchSize = fetchSize > 0 ? fetchSize : 200;
}
@Override
public boolean hasNext() {
if (items != null && items.isEmpty()) {
return false;
}
if (items == null || index >= items.size()) {
Query<T> nextQuery = query.clone();
if (lastTypeId != null) {
nextQuery.and("_type = ? and _id > ?", lastTypeId, lastId);
}
items = nextQuery.select(0, fetchSize).getItems();
int size = items.size();
if (size < 1) {
if (lastTypeId == null) {
return false;
} else {
nextQuery = query.clone().and("_type > ?", lastTypeId);
items = nextQuery.select(0, fetchSize).getItems();
size = items.size();
if (size < 1) {
return false;
}
}
}
State lastState = State.getInstance(items.get(size - 1));
lastTypeId = lastState.getTypeId();
lastId = lastState.getId();
index = 0;
}
return true;
}
@Override
public T next() {
if (hasNext()) {
T object = items.get(index);
++ index;
return object;
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
@Override
public Date readLastUpdate(Query<?> query) {
String sqlQuery = buildLastUpdateStatement(query);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
if (result.next()) {
Double date = result.getDouble(1);
if (date != null) {
return new Date((long) (date * 1000L));
}
}
return null;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(connection, statement, result);
}
}
@Override
public <T> PaginatedResult<T> readPartial(final Query<T> query, long offset, int limit) {
List<T> objects = selectListWithOptions(
vendor.rewriteQueryWithLimitClause(buildSelectStatement(query), limit + 1, offset),
query);
int size = objects.size();
if (size <= limit) {
return new PaginatedResult<T>(offset, limit, offset + size, objects);
} else {
objects.remove(size - 1);
return new PaginatedResult<T>(offset, limit, 0, objects) {
private Long count;
@Override
public long getCount() {
if (count == null) {
count = readCount(query);
}
return count;
}
@Override
public boolean hasNext() {
return true;
}
};
}
}
@Override
public <T> PaginatedResult<Grouping<T>> readPartialGrouped(Query<T> query, long offset, int limit, String... fields) {
List<Grouping<T>> groupings = new ArrayList<Grouping<T>>();
String sqlQuery = buildGroupStatement(query, fields);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
int fieldsLength = fields.length;
int groupingsCount = 0;
for (int i = 0, last = (int) offset + limit; result.next(); ++ i, ++ groupingsCount) {
if (i < offset || i >= last) {
continue;
}
long count = ObjectUtils.to(long.class, result.getObject(1));
List<Object> keys = new ArrayList<Object>();
for (int j = 0; j < fieldsLength; ++ j) {
keys.add(result.getObject(j + 2));
}
groupings.add(new SqlGrouping<T>(keys, query, fields, count));
}
int groupingsSize = groupings.size();
for (int i = 0; i < fieldsLength; ++ i) {
ObjectField field = query.mapEmbeddedKey(getEnvironment(), fields[i]).getField();
if (field != null) {
Map<String, Object> rawKeys = new HashMap<String, Object>();
for (int j = 0; j < groupingsSize; ++ j) {
rawKeys.put(String.valueOf(j), groupings.get(j).getKeys().get(i));
}
String itemType = field.getInternalItemType();
if (ObjectField.RECORD_TYPE.equals(itemType)) {
for (Map.Entry<String, Object> entry : rawKeys.entrySet()) {
Map<String, Object> ref = new HashMap<String, Object>();
ref.put(StateValueUtils.REFERENCE_KEY, entry.getValue());
entry.setValue(ref);
}
}
Map<?, ?> convertedKeys = (Map<?, ?>) StateValueUtils.toJavaValue(query.getDatabase(), null, field, "map/" + itemType, rawKeys);
for (int j = 0; j < groupingsSize; ++ j) {
groupings.get(j).getKeys().set(i, convertedKeys.get(String.valueOf(j)));
}
}
}
return new PaginatedResult<Grouping<T>>(offset, limit, groupingsCount, groupings);
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(connection, statement, result);
}
}
/** SQL-specific implementation of {@link Grouping}. */
private class SqlGrouping<T> extends AbstractGrouping<T> {
private long count;
public SqlGrouping(List<Object> keys, Query<T> query, String[] fields, long count) {
super(keys, query, fields);
this.count = count;
}
@Override
protected Aggregate createAggregate(String field) {
throw new UnsupportedOperationException();
}
@Override
public long getCount() {
return count;
}
}
@Override
protected void beginTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.setAutoCommit(false);
}
@Override
protected void commitTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.commit();
}
@Override
protected void rollbackTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.rollback();
}
@Override
protected void endTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.setAutoCommit(true);
}
@Override
protected void doSaves(Connection connection, boolean isImmediate, List<State> states) throws SQLException {
List<State> indexStates = null;
for (State state1 : states) {
if (Boolean.TRUE.equals(state1.getExtra(SKIP_INDEX_STATE_EXTRA))) {
indexStates = new ArrayList<State>();
for (State state2 : states) {
if (!Boolean.TRUE.equals(state2.getExtra(SKIP_INDEX_STATE_EXTRA))) {
indexStates.add(state2);
}
}
break;
}
}
if (indexStates == null) {
indexStates = states;
}
SqlIndex.Static.deleteByStates(this, connection, indexStates);
Map<State, String> inRowIndexes = SqlIndex.Static.insertByStates(this, connection, indexStates);
boolean hasInRowIndex = hasInRowIndex();
SqlVendor vendor = getVendor();
double now = System.currentTimeMillis() / 1000.0;
for (State state : states) {
boolean isNew = state.isNew();
boolean saveInRowIndex = hasInRowIndex && !Boolean.TRUE.equals(state.getExtra(SKIP_INDEX_STATE_EXTRA));
UUID id = state.getId();
UUID typeId = state.getTypeId();
byte[] dataBytes = null;
String inRowIndex = inRowIndexes.get(state);
byte[] inRowIndexBytes = inRowIndex != null ? inRowIndex.getBytes(StringUtils.UTF_8) : new byte[0];
while (true) {
if (isNew) {
try {
if (dataBytes == null) {
dataBytes = serializeData(state);
}
List<Object> parameters = new ArrayList<Object>();
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.append("INSERT INTO ");
vendor.appendIdentifier(insertBuilder, RECORD_TABLE);
insertBuilder.append(" (");
vendor.appendIdentifier(insertBuilder, ID_COLUMN);
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, TYPE_ID_COLUMN);
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, DATA_COLUMN);
if (saveInRowIndex) {
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, IN_ROW_INDEX_COLUMN);
}
insertBuilder.append(") VALUES (");
vendor.appendBindValue(insertBuilder, id, parameters);
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, typeId, parameters);
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, dataBytes, parameters);
if (saveInRowIndex) {
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, inRowIndexBytes, parameters);
}
insertBuilder.append(")");
Static.executeUpdateWithList(connection, insertBuilder.toString(), parameters);
} catch (SQLException ex) {
if (Static.isIntegrityConstraintViolation(ex)) {
isNew = false;
continue;
} else {
throw ex;
}
}
} else {
List<AtomicOperation> atomicOperations = state.getAtomicOperations();
if (atomicOperations.isEmpty()) {
if (dataBytes == null) {
dataBytes = serializeData(state);
}
List<Object> parameters = new ArrayList<Object>();
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, typeId, parameters);
updateBuilder.append(",");
if (saveInRowIndex) {
vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, inRowIndexBytes, parameters);
updateBuilder.append(",");
}
vendor.appendIdentifier(updateBuilder, DATA_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, dataBytes, parameters);
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, id, parameters);
if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) {
isNew = true;
continue;
}
} else {
Object oldObject = Query.
from(Object.class).
where("_id = ?", id).
using(this).
resolveToReferenceOnly().
option(RETURN_ORIGINAL_DATA_QUERY_OPTION, Boolean.TRUE).
option(USE_READ_DATA_SOURCE_QUERY_OPTION, Boolean.FALSE).
first();
if (oldObject == null) {
isNew = true;
continue;
}
State oldState = State.getInstance(oldObject);
UUID oldTypeId = oldState.getTypeId();
byte[] oldData = Static.getOriginalData(oldObject);
for (AtomicOperation operation : atomicOperations) {
String field = operation.getField();
state.putValue(field, oldState.getValue(field));
}
for (AtomicOperation operation : atomicOperations) {
operation.execute(state);
}
dataBytes = serializeData(state);
List<Object> parameters = new ArrayList<Object>();
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, typeId, parameters);
if (saveInRowIndex) {
updateBuilder.append(",");
vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, inRowIndexBytes, parameters);
}
updateBuilder.append(",");
vendor.appendIdentifier(updateBuilder, DATA_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, dataBytes, parameters);
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, id, parameters);
updateBuilder.append(" AND ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, oldTypeId, parameters);
updateBuilder.append(" AND ");
vendor.appendIdentifier(updateBuilder, DATA_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, oldData, parameters);
if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) {
continue;
}
}
}
break;
}
while (true) {
if (isNew) {
List<Object> parameters = new ArrayList<Object>();
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.append("INSERT INTO ");
vendor.appendIdentifier(insertBuilder, RECORD_UPDATE_TABLE);
insertBuilder.append(" (");
vendor.appendIdentifier(insertBuilder, ID_COLUMN);
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, TYPE_ID_COLUMN);
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, UPDATE_DATE_COLUMN);
insertBuilder.append(") VALUES (");
vendor.appendBindValue(insertBuilder, id, parameters);
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, typeId, parameters);
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, now, parameters);
insertBuilder.append(")");
try {
Static.executeUpdateWithList(connection, insertBuilder.toString(), parameters);
} catch (SQLException ex) {
if (Static.isIntegrityConstraintViolation(ex)) {
isNew = false;
continue;
} else {
throw ex;
}
}
} else {
List<Object> parameters = new ArrayList<Object>();
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_UPDATE_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, typeId, parameters);
updateBuilder.append(",");
vendor.appendIdentifier(updateBuilder, UPDATE_DATE_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, now, parameters);
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, id, parameters);
if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) {
isNew = true;
continue;
}
}
break;
}
}
}
@Override
protected void doIndexes(Connection connection, boolean isImmediate, List<State> states) throws SQLException {
SqlIndex.Static.deleteByStates(this, connection, states);
Map<State, String> inRowIndexes = SqlIndex.Static.insertByStates(this, connection, states);
if (!hasInRowIndex()) {
return;
}
SqlVendor vendor = getVendor();
for (Map.Entry<State, String> entry : inRowIndexes.entrySet()) {
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN);
updateBuilder.append("=");
vendor.appendValue(updateBuilder, entry.getValue());
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append("=");
vendor.appendValue(updateBuilder, entry.getKey().getId());
Static.executeUpdateWithArray(connection, updateBuilder.toString());
}
}
/** @deprecated Use {@link #index} instead. */
@Deprecated
public void fixIndexes(List<State> states) {
Connection connection = openConnection();
try {
doIndexes(connection, true, states);
} catch (SQLException ex) {
List<UUID> ids = new ArrayList<UUID>();
for (State state : states) {
ids.add(state.getId());
}
throw new SqlDatabaseException(this, String.format(
"Can't index states! (%s)", ids));
} finally {
closeConnection(connection);
}
}
@Override
protected void doDeletes(Connection connection, boolean isImmediate, List<State> states) throws SQLException {
SqlVendor vendor = getVendor();
StringBuilder whereBuilder = new StringBuilder();
whereBuilder.append(" WHERE ");
vendor.appendIdentifier(whereBuilder, ID_COLUMN);
whereBuilder.append(" IN (");
for (State state : states) {
vendor.appendValue(whereBuilder, state.getId());
whereBuilder.append(",");
}
whereBuilder.setCharAt(whereBuilder.length() - 1, ')');
StringBuilder deleteBuilder = new StringBuilder();
deleteBuilder.append("DELETE FROM ");
vendor.appendIdentifier(deleteBuilder, RECORD_TABLE);
deleteBuilder.append(whereBuilder);
Static.executeUpdateWithArray(connection, deleteBuilder.toString());
SqlIndex.Static.deleteByStates(this, connection, states);
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_UPDATE_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, UPDATE_DATE_COLUMN);
updateBuilder.append("=");
vendor.appendValue(updateBuilder, System.currentTimeMillis() / 1000.0);
updateBuilder.append(whereBuilder);
Static.executeUpdateWithArray(connection, updateBuilder.toString());
}
/** Specifies the name of the table for storing target field values. */
@Documented
@ObjectField.AnnotationProcessorClass(FieldIndexTableProcessor.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FieldIndexTable {
String value();
boolean names() default false;
boolean source() default false;
boolean readonly() default false;
}
private static class FieldIndexTableProcessor implements ObjectField.AnnotationProcessor<FieldIndexTable> {
@Override
public void process(ObjectType type, ObjectField field, FieldIndexTable annotation) {
if (annotation.source()) {
HashMap<String, ObjectField> tables = (HashMap<String, ObjectField>) type.getOptions().get(INDEX_TABLE_SOURCE_TABLES_OPTION);
if (tables == null) {
tables = new HashMap<String, ObjectField>();
}
if (!tables.containsKey(annotation.value())) {
tables.put(annotation.value(), field);
type.getOptions().put(INDEX_TABLE_SOURCE_TABLES_OPTION, tables);
} else {
//throw new Exception("Only one field per @FieldIndexTable!");
}
}
field.getOptions().put(INDEX_TABLE_INDEX_OPTION, annotation.value());
field.getOptions().put(INDEX_TABLE_USE_COLUMN_NAMES_OPTION, annotation.names());
field.getOptions().put(INDEX_TABLE_IS_SOURCE_OPTION, annotation.source());
field.getOptions().put(INDEX_TABLE_IS_READONLY_OPTION, annotation.readonly());
}
}
/** {@link SqlDatabase} utility methods. */
public static final class Static {
private Static() {
}
public static List<SqlDatabase> getAll() {
return INSTANCES;
}
public static void deregisterAllDrivers() {
for (WeakReference<Driver> driverRef : REGISTERED_DRIVERS) {
Driver driver = driverRef.get();
if (driver != null) {
LOGGER.info("Deregistering [{}]", driver);
try {
DriverManager.deregisterDriver(driver);
} catch (SQLException ex) {
LOGGER.warn("Can't deregister [{}]!", driver);
}
}
}
}
/**
* Log a batch update exception with values.
*/
static void logBatchUpdateException(BatchUpdateException bue, String sqlQuery, List<? extends List<?>> parameters) {
int i = 0;
int failureOffset = bue.getUpdateCounts().length;
List<?> rowData = parameters.get(failureOffset);
StringBuilder errorBuilder = new StringBuilder();
errorBuilder.append("Batch update failed with query '");
errorBuilder.append(sqlQuery);
errorBuilder.append("' with values (");
for (Object value : rowData) {
if (i++ != 0) {
errorBuilder.append(", ");
}
if (value instanceof byte[]) {
errorBuilder.append(StringUtils.hex((byte[]) value));
} else {
errorBuilder.append(value);
}
}
errorBuilder.append(")");
Exception ex = bue.getNextException() != null ? bue.getNextException() : bue;
LOGGER.error(errorBuilder.toString(), ex);
}
static void logUpdateException(String sqlQuery, List<?> parameters) {
int i = 0;
StringBuilder errorBuilder = new StringBuilder();
errorBuilder.append("Batch update failed with query '");
errorBuilder.append(sqlQuery);
errorBuilder.append("' with values (");
for (Object value : parameters) {
if (i++ != 0) {
errorBuilder.append(", ");
}
if (value instanceof byte[]) {
errorBuilder.append(StringUtils.hex((byte[]) value));
} else {
errorBuilder.append(value);
}
}
errorBuilder.append(")");
LOGGER.error(errorBuilder.toString());
}
// Safely binds the given parameter to the given statement at the
// given index.
private static void bindParameter(PreparedStatement statement, int index, Object parameter) throws SQLException {
if (parameter instanceof String) {
parameter = ((String) parameter).getBytes(StringUtils.UTF_8);
}
if (parameter instanceof byte[]) {
byte[] parameterBytes = (byte[]) parameter;
int parameterBytesLength = parameterBytes.length;
if (parameterBytesLength > 2000) {
statement.setBinaryStream(index, new ByteArrayInputStream(parameterBytes), parameterBytesLength);
return;
}
}
statement.setObject(index, parameter);
}
/**
* Executes the given batch update {@code sqlQuery} with the given
* list of {@code parameters} within the given {@code connection}.
*
* @return Array of number of rows affected by the update query.
*/
public static int[] executeBatchUpdate(
Connection connection,
String sqlQuery,
List<? extends List<?>> parameters) throws SQLException {
PreparedStatement prepared = connection.prepareStatement(sqlQuery);
List<?> currentRow = null;
try {
for (List<?> row : parameters) {
currentRow = row;
int columnIndex = 1;
for (Object parameter : row) {
bindParameter(prepared, columnIndex, parameter);
columnIndex++;
}
prepared.addBatch();
}
int[] affected = null;
Stats.Timer timer = STATS.startTimer();
Profiler.Static.startThreadEvent(UPDATE_PROFILER_EVENT);
try {
return (affected = prepared.executeBatch());
} finally {
double time = timer.stop(UPDATE_STATS_OPERATION);
Profiler.Static.stopThreadEvent(sqlQuery);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"SQL batch update: [{}], Parameters: {}, Affected: {}, Time: [{}]ms",
new Object[] { sqlQuery, parameters, affected != null ? Arrays.toString(affected) : "[]", time });
}
}
} catch (SQLException error) {
logUpdateException(sqlQuery, currentRow);
throw error;
} finally {
try {
prepared.close();
} catch (SQLException error) {
}
}
}
/**
* Executes the given update {@code sqlQuery} with the given
* {@code parameters} within the given {@code connection}.
*
* @return Number of rows affected by the update query.
*/
public static int executeUpdateWithList(
Connection connection,
String sqlQuery,
List<?> parameters)
throws SQLException {
if (parameters == null) {
return executeUpdateWithArray(connection, sqlQuery);
} else {
Object[] array = parameters.toArray(new Object[parameters.size()]);
return executeUpdateWithArray(connection, sqlQuery, array);
}
}
/**
* Executes the given update {@code sqlQuery} with the given
* {@code parameters} within the given {@code connection}.
*
* @return Number of rows affected by the update query.
*/
public static int executeUpdateWithArray(
Connection connection,
String sqlQuery,
Object... parameters)
throws SQLException {
boolean hasParameters = parameters != null && parameters.length > 0;
PreparedStatement prepared;
Statement statement;
if (hasParameters) {
prepared = connection.prepareStatement(sqlQuery);
statement = prepared;
} else {
prepared = null;
statement = connection.createStatement();
}
try {
if (hasParameters) {
for (int i = 0; i < parameters.length; i++) {
bindParameter(prepared, i + 1, parameters[i]);
}
}
Integer affected = null;
Stats.Timer timer = STATS.startTimer();
Profiler.Static.startThreadEvent(UPDATE_PROFILER_EVENT);
try {
return (affected = hasParameters ?
prepared.executeUpdate() :
statement.executeUpdate(sqlQuery));
} finally {
double time = timer.stop(UPDATE_STATS_OPERATION);
Profiler.Static.stopThreadEvent(sqlQuery);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"SQL update: [{}], Affected: [{}], Time: [{}]ms",
new Object[] { fillPlaceholders(sqlQuery, parameters), affected, time });
}
}
} finally {
try {
statement.close();
} catch (SQLException ex) {
}
}
}
/**
* Returns {@code true} if the given {@code error} looks like a
* {@link SQLIntegrityConstraintViolationException}.
*/
public static boolean isIntegrityConstraintViolation(SQLException error) {
if (error instanceof SQLIntegrityConstraintViolationException) {
return true;
} else {
String state = error.getSQLState();
return state != null && state.startsWith("23");
}
}
/**
* Returns the name of the table for storing the values of the
* given {@code index}.
*/
public static String getIndexTable(ObjectIndex index) {
return ObjectUtils.to(String.class, index.getOptions().get(INDEX_TABLE_INDEX_OPTION));
}
/**
* Sets the name of the table for storing the values of the
* given {@code index}.
*/
public static void setIndexTable(ObjectIndex index, String table) {
index.getOptions().put(INDEX_TABLE_INDEX_OPTION, table);
}
public static boolean getIndexTableUseColumnNames(ObjectField field) {
return ObjectUtils.to(boolean.class, field.getOptions().get(INDEX_TABLE_USE_COLUMN_NAMES_OPTION));
}
public static void setIndexTableUseColumnNames(ObjectField field, boolean names) {
field.getOptions().put(INDEX_TABLE_USE_COLUMN_NAMES_OPTION, names);
}
public static boolean getIndexTableUseColumnNames(ObjectIndex index) {
return getIndexTableUseColumnNames(index.getParent().getField(index.getField()));
}
public static boolean getIndexTableIsSource(ObjectField field) {
return ObjectUtils.to(boolean.class, field.getOptions().get(INDEX_TABLE_IS_SOURCE_OPTION));
}
public static void setIndexTableIsSource(ObjectField field, boolean source) {
field.getOptions().put(INDEX_TABLE_IS_SOURCE_OPTION, source);
}
public static boolean isExtraFieldOfSourceIndexTable(ObjectField field) {
for (ObjectIndex index : field.getParent().getIndexes()) {
if (index.getFields().contains(field.getInternalName()) && index.getFields().get(0) != field.getInternalName()) {
// this field is an extraField of another field's index - find out if that field's IndexTable is annotated as source=true
return getIndexTableIsSource(field.getParent().getField(index.getFields().get(0)));
}
}
return false;
}
public static boolean getIndexTableIsReadOnly(ObjectField field) {
return ObjectUtils.to(boolean.class, field.getOptions().get(INDEX_TABLE_IS_READONLY_OPTION));
}
public static void setIndexTableIsReadOnly(ObjectField field, boolean readonly) {
field.getOptions().put(INDEX_TABLE_IS_READONLY_OPTION, readonly);
}
public static boolean getIndexTableIsReadOnly(ObjectIndex index) {
return getIndexTableIsReadOnly(index.getParent().getField(index.getField()));
}
public static Object getExtraColumn(Object object, String name) {
return State.getInstance(object).getExtra(EXTRA_COLUMN_EXTRA_PREFIX + name);
}
public static byte[] getOriginalData(Object object) {
return (byte[]) State.getInstance(object).getExtra(ORIGINAL_DATA_EXTRA);
}
/** @deprecated Use {@link #executeUpdateWithArray} instead. */
@Deprecated
public static int executeUpdate(
Connection connection,
String sqlQuery,
Object... parameters)
throws SQLException {
return executeUpdateWithArray(connection, sqlQuery, parameters);
}
}
} |
package com.psddev.dari.db;
import java.io.ByteArrayInputStream;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.ref.WeakReference;
import java.sql.BatchUpdateException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.SQLTimeoutException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import javax.sql.DataSource;
import org.iq80.snappy.Snappy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.jolbox.bonecp.BoneCPDataSource;
import com.psddev.dari.util.ObjectUtils;
import com.psddev.dari.util.PaginatedResult;
import com.psddev.dari.util.PeriodicValue;
import com.psddev.dari.util.Profiler;
import com.psddev.dari.util.PullThroughValue;
import com.psddev.dari.util.Settings;
import com.psddev.dari.util.SettingsException;
import com.psddev.dari.util.Stats;
import com.psddev.dari.util.StringUtils;
import com.psddev.dari.util.TypeDefinition;
/** Database backed by a SQL engine. */
public class SqlDatabase extends AbstractDatabase<Connection> {
public static final String DATA_SOURCE_SETTING = "dataSource";
public static final String JDBC_DRIVER_CLASS_SETTING = "jdbcDriverClass";
public static final String JDBC_URL_SETTING = "jdbcUrl";
public static final String JDBC_USER_SETTING = "jdbcUser";
public static final String JDBC_PASSWORD_SETTING = "jdbcPassword";
public static final String JDBC_POOL_SIZE_SETTING = "jdbcPoolSize";
public static final String READ_DATA_SOURCE_SETTING = "readDataSource";
public static final String READ_JDBC_DRIVER_CLASS_SETTING = "readJdbcDriverClass";
public static final String READ_JDBC_URL_SETTING = "readJdbcUrl";
public static final String READ_JDBC_USER_SETTING = "readJdbcUser";
public static final String READ_JDBC_PASSWORD_SETTING = "readJdbcPassword";
public static final String READ_JDBC_POOL_SIZE_SETTING = "readJdbcPoolSize";
public static final String VENDOR_CLASS_SETTING = "vendorClass";
public static final String COMPRESS_DATA_SUB_SETTING = "compressData";
public static final String CACHE_DATA_SUB_SETTING = "cacheData";
public static final String RECORD_TABLE = "Record";
public static final String RECORD_UPDATE_TABLE = "RecordUpdate";
public static final String SYMBOL_TABLE = "Symbol";
public static final String ID_COLUMN = "id";
public static final String TYPE_ID_COLUMN = "typeId";
public static final String IN_ROW_INDEX_COLUMN = "inRowIndex";
public static final String DATA_COLUMN = "data";
public static final String SYMBOL_ID_COLUMN = "symbolId";
public static final String UPDATE_DATE_COLUMN = "updateDate";
public static final String VALUE_COLUMN = "value";
public static final String CONNECTION_QUERY_OPTION = "sql.connection";
public static final String EXTRA_COLUMNS_QUERY_OPTION = "sql.extraColumns";
public static final String EXTRA_JOINS_QUERY_OPTION = "sql.extraJoins";
public static final String EXTRA_WHERE_QUERY_OPTION = "sql.extraWhere";
public static final String EXTRA_HAVING_QUERY_OPTION = "sql.extraHaving";
public static final String MYSQL_INDEX_HINT_QUERY_OPTION = "sql.mysqlIndexHint";
public static final String RETURN_ORIGINAL_DATA_QUERY_OPTION = "sql.returnOriginalData";
public static final String USE_JDBC_FETCH_SIZE_QUERY_OPTION = "sql.useJdbcFetchSize";
public static final String USE_READ_DATA_SOURCE_QUERY_OPTION = "sql.useReadDataSource";
public static final String SKIP_INDEX_STATE_EXTRA = "sql.skipIndex";
public static final String INDEX_TABLE_INDEX_OPTION = "sql.indexTable";
public static final String EXTRA_COLUMN_EXTRA_PREFIX = "sql.extraColumn.";
public static final String ORIGINAL_DATA_EXTRA = "sql.originalData";
private static final Logger LOGGER = LoggerFactory.getLogger(SqlDatabase.class);
private static final String SHORT_NAME = "SQL";
private static final Stats STATS = new Stats(SHORT_NAME);
private static final String QUERY_STATS_OPERATION = "Query";
private static final String UPDATE_STATS_OPERATION = "Update";
private static final String QUERY_PROFILER_EVENT = SHORT_NAME + " " + QUERY_STATS_OPERATION;
private static final String UPDATE_PROFILER_EVENT = SHORT_NAME + " " + UPDATE_STATS_OPERATION;
private final static List<SqlDatabase> INSTANCES = new ArrayList<SqlDatabase>();
{
INSTANCES.add(this);
}
private volatile DataSource dataSource;
private volatile DataSource readDataSource;
private volatile SqlVendor vendor;
private volatile boolean compressData;
private volatile boolean cacheData;
/**
* Quotes the given {@code identifier} so that it's safe to use
* in a SQL query.
*/
public static String quoteIdentifier(String identifier) {
return "\"" + StringUtils.replaceAll(identifier, "\\\\", "\\\\\\\\", "\"", "\"\"") + "\"";
}
/**
* Quotes the given {@code value} so that it's safe to use
* in a SQL query.
*/
public static String quoteValue(Object value) {
if (value == null) {
return "NULL";
} else if (value instanceof Number) {
return value.toString();
} else if (value instanceof byte[]) {
return "X'" + StringUtils.hex((byte[]) value) + "'";
} else {
return "'" + value.toString().replace("'", "''").replace("\\", "\\\\") + "'";
}
}
/** Closes all resources used by all instances. */
public static void closeAll() {
for (SqlDatabase database : INSTANCES) {
database.close();
}
INSTANCES.clear();
}
/**
* Creates an {@link SqlDatabaseException} that occurred during
* an execution of a query.
*/
private SqlDatabaseException createQueryException(
SQLException error,
String sqlQuery,
Query<?> query) {
String message = error.getMessage();
if (error instanceof SQLTimeoutException || message.contains("timeout")) {
return new SqlDatabaseException.ReadTimeout(this, error, sqlQuery, query);
} else {
return new SqlDatabaseException(this, error, sqlQuery, query);
}
}
/** Returns the JDBC data source used for general database operations. */
public DataSource getDataSource() {
return dataSource;
}
private static final Map<String, Class<? extends SqlVendor>> VENDOR_CLASSES; static {
Map<String, Class<? extends SqlVendor>> m = new HashMap<String, Class<? extends SqlVendor>>();
m.put("H2", SqlVendor.H2.class);
m.put("MySQL", SqlVendor.MySQL.class);
m.put("PostgreSQL", SqlVendor.PostgreSQL.class);
m.put("Oracle", SqlVendor.Oracle.class);
VENDOR_CLASSES = m;
}
/** Sets the JDBC data source used for general database operations. */
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
if (dataSource == null) {
return;
}
synchronized (this) {
try {
boolean writable = false;
if (vendor == null) {
Connection connection;
try {
connection = openConnection();
writable = true;
} catch (DatabaseException error) {
LOGGER.debug("Can't read vendor information from the writable server!", error);
connection = openReadConnection();
}
try {
DatabaseMetaData meta = connection.getMetaData();
String vendorName = meta.getDatabaseProductName();
Class<? extends SqlVendor> vendorClass = VENDOR_CLASSES.get(vendorName);
LOGGER.info(
"Initializing SQL vendor for [{}]: [{}] -> [{}]",
new Object[] { getName(), vendorName, vendorClass });
vendor = vendorClass != null ? TypeDefinition.getInstance(vendorClass).newInstance() : new SqlVendor();
vendor.setDatabase(this);
} finally {
closeConnection(connection);
}
}
tableNames.refresh();
symbols.invalidate();
if (writable) {
vendor.createRecord(this);
vendor.createRecordUpdate(this);
vendor.createSymbol(this);
for (SqlIndex index : SqlIndex.values()) {
if (index != SqlIndex.CUSTOM) {
vendor.createRecordIndex(
this,
index.getReadTable(this, null).getName(this, null),
index);
}
}
tableNames.refresh();
symbols.invalidate();
}
} catch (SQLException ex) {
throw new SqlDatabaseException(this, "Can't check for required tables!", ex);
}
}
}
/** Returns the JDBC data source used exclusively for read operations. */
public DataSource getReadDataSource() {
return this.readDataSource;
}
/** Sets the JDBC data source used exclusively for read operations. */
public void setReadDataSource(DataSource readDataSource) {
this.readDataSource = readDataSource;
}
/** Returns the vendor-specific SQL engine information. */
public SqlVendor getVendor() {
return vendor;
}
/** Sets the vendor-specific SQL engine information. */
public void setVendor(SqlVendor vendor) {
this.vendor = vendor;
}
/** Returns {@code true} if the data should be compressed. */
public boolean isCompressData() {
return compressData;
}
/** Sets whether the data should be compressed. */
public void setCompressData(boolean compressData) {
this.compressData = compressData;
}
public boolean isCacheData() {
return cacheData;
}
public void setCacheData(boolean cacheData) {
this.cacheData = cacheData;
}
/**
* Returns {@code true} if the {@link #RECORD_TABLE} in this database
* has the {@link #IN_ROW_INDEX_COLUMN}.
*/
public boolean hasInRowIndex() {
return hasInRowIndex;
}
/**
* Returns {@code true} if all comparisons executed in this database
* should ignore case by default.
*/
public boolean comparesIgnoreCase() {
return comparesIgnoreCase;
}
/**
* Returns {@code true} if this database contains a table with
* the given {@code name}.
*/
public boolean hasTable(String name) {
if (name == null) {
return false;
} else {
Set<String> names = tableNames.get();
return names != null && names.contains(name.toLowerCase());
}
}
private transient volatile boolean hasInRowIndex;
private transient volatile boolean comparesIgnoreCase;
private final transient PeriodicValue<Set<String>> tableNames = new PeriodicValue<Set<String>>(0.0, 60.0) {
@Override
protected Set<String> update() {
if (getDataSource() == null) {
return Collections.emptySet();
}
Connection connection;
try {
connection = openConnection();
} catch (DatabaseException error) {
LOGGER.debug("Can't read table names from the writable server!", error);
connection = openReadConnection();
}
try {
SqlVendor vendor = getVendor();
String recordTable = null;
int maxStringVersion = 0;
Set<String> loweredNames = new HashSet<String>();
for (String name : vendor.getTables(connection)) {
String loweredName = name.toLowerCase();
loweredNames.add(loweredName);
if ("record".equals(loweredName)) {
recordTable = name;
} else if (loweredName.startsWith("recordstring")) {
int version = ObjectUtils.to(int.class, loweredName.substring(12));
if (version > maxStringVersion) {
maxStringVersion = version;
}
}
}
if (recordTable != null) {
hasInRowIndex = vendor.hasInRowIndex(connection, recordTable);
}
comparesIgnoreCase = maxStringVersion >= 3;
return loweredNames;
} catch (SQLException error) {
LOGGER.error("Can't query table names!", error);
return get();
} finally {
closeConnection(connection);
}
}
};
/**
* Returns an unique numeric ID for the given {@code symbol}.
*/
public int getSymbolId(String symbol) {
Integer id = symbols.get().get(symbol);
if (id == null) {
SqlVendor vendor = getVendor();
Connection connection = openConnection();
try {
List<Object> parameters = new ArrayList<Object>();
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.append("INSERT /*! IGNORE */ INTO ");
vendor.appendIdentifier(insertBuilder, SYMBOL_TABLE);
insertBuilder.append(" (");
vendor.appendIdentifier(insertBuilder, VALUE_COLUMN);
insertBuilder.append(") VALUES (");
vendor.appendBindValue(insertBuilder, symbol, parameters);
insertBuilder.append(")");
String insertSql = insertBuilder.toString();
try {
Static.executeUpdateWithList(connection, insertSql, parameters);
} catch (SQLException ex) {
if (!Static.isIntegrityConstraintViolation(ex)) {
throw createQueryException(ex, insertSql, null);
}
}
StringBuilder selectBuilder = new StringBuilder();
selectBuilder.append("SELECT ");
vendor.appendIdentifier(selectBuilder, SYMBOL_ID_COLUMN);
selectBuilder.append(" FROM ");
vendor.appendIdentifier(selectBuilder, SYMBOL_TABLE);
selectBuilder.append(" WHERE ");
vendor.appendIdentifier(selectBuilder, VALUE_COLUMN);
selectBuilder.append("=");
vendor.appendValue(selectBuilder, symbol);
String selectSql = selectBuilder.toString();
Statement statement = null;
ResultSet result = null;
try {
statement = connection.createStatement();
result = statement.executeQuery(selectSql);
result.next();
id = result.getInt(1);
symbols.get().put(symbol, id);
} catch (SQLException ex) {
throw createQueryException(ex, selectSql, null);
} finally {
closeResources(null, null, statement, result);
}
} finally {
closeConnection(connection);
}
}
return id;
}
// Cache of all internal symbols.
private transient PullThroughValue<Map<String, Integer>> symbols = new PullThroughValue<Map<String, Integer>>() {
@Override
protected Map<String, Integer> produce() {
SqlVendor vendor = getVendor();
StringBuilder selectBuilder = new StringBuilder();
selectBuilder.append("SELECT ");
vendor.appendIdentifier(selectBuilder, SYMBOL_ID_COLUMN);
selectBuilder.append(",");
vendor.appendIdentifier(selectBuilder, VALUE_COLUMN);
selectBuilder.append(" FROM ");
vendor.appendIdentifier(selectBuilder, SYMBOL_TABLE);
String selectSql = selectBuilder.toString();
Connection connection;
Statement statement = null;
ResultSet result = null;
try {
connection = openConnection();
} catch (DatabaseException error) {
LOGGER.debug("Can't read symbols from the writable server!", error);
connection = openReadConnection();
}
try {
statement = connection.createStatement();
result = statement.executeQuery(selectSql);
Map<String, Integer> symbols = new ConcurrentHashMap<String, Integer>();
while (result.next()) {
symbols.put(new String(result.getBytes(2), StringUtils.UTF_8), result.getInt(1));
}
return symbols;
} catch (SQLException ex) {
throw createQueryException(ex, selectSql, null);
} finally {
closeResources(null, connection, statement, result);
}
}
};
/**
* Returns the underlying JDBC connection.
*
* @deprecated Use {@link #openConnection} instead.
*/
@Deprecated
public Connection getConnection() {
return openConnection();
}
/** Closes any resources used by this database. */
public void close() {
DataSource dataSource = getDataSource();
if (dataSource instanceof BoneCPDataSource) {
LOGGER.info("Closing BoneCP data source in {}", getName());
((BoneCPDataSource) dataSource).close();
}
DataSource readDataSource = getReadDataSource();
if (readDataSource instanceof BoneCPDataSource) {
LOGGER.info("Closing BoneCP read data source in {}", getName());
((BoneCPDataSource) readDataSource).close();
}
setDataSource(null);
setReadDataSource(null);
}
/**
* Builds an SQL statement that can be used to get a count of all
* objects matching the given {@code query}.
*/
public String buildCountStatement(Query<?> query) {
return new SqlQuery(this, query).countStatement();
}
/**
* Builds an SQL statement that can be used to delete all rows
* matching the given {@code query}.
*/
public String buildDeleteStatement(Query<?> query) {
return new SqlQuery(this, query).deleteStatement();
}
/**
* Builds an SQL statement that can be used to get all objects
* grouped by the values of the given {@code groupFields}.
*/
public String buildGroupStatement(Query<?> query, String... groupFields) {
return new SqlQuery(this, query).groupStatement(groupFields);
}
public String buildGroupedMetricStatement(Query<?> query, String metricFieldName, String... groupFields) {
return new SqlQuery(this, query).groupedMetricSql(metricFieldName, groupFields);
}
/**
* Builds an SQL statement that can be used to get when the objects
* matching the given {@code query} were last updated.
*/
public String buildLastUpdateStatement(Query<?> query) {
return new SqlQuery(this, query).lastUpdateStatement();
}
/**
* Builds an SQL statement that can be used to list all rows
* matching the given {@code query}.
*/
public String buildSelectStatement(Query<?> query) {
return new SqlQuery(this, query).selectStatement();
}
/** Closes all the given SQL resources safely. */
private void closeResources(Query<?> query, Connection connection, Statement statement, ResultSet result) {
if (result != null) {
try {
result.close();
} catch (SQLException ex) {
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
}
}
if (connection != null &&
(query == null ||
!connection.equals(query.getOptions().get(CONNECTION_QUERY_OPTION)))) {
try {
connection.close();
} catch (SQLException ex) {
}
}
}
private byte[] serializeState(State state) {
Map<String, Object> values = state.getSimpleValues();
for (Iterator<Map.Entry<String, Object>> i = values.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<String, Object> entry = i.next();
ObjectField field = state.getField(entry.getKey());
if (field != null) {
if (field.as(FieldData.class).isIndexTableSourceFromAnywhere()) {
i.remove();
}
}
}
byte[] dataBytes = ObjectUtils.toJson(values).getBytes(StringUtils.UTF_8);
if (isCompressData()) {
byte[] compressed = new byte[Snappy.maxCompressedLength(dataBytes.length)];
int compressedLength = Snappy.compress(dataBytes, 0, dataBytes.length, compressed, 0);
dataBytes = new byte[compressedLength + 1];
dataBytes[0] = 's';
System.arraycopy(compressed, 0, dataBytes, 1, compressedLength);
}
return dataBytes;
}
@SuppressWarnings("unchecked")
private Map<String, Object> unserializeData(byte[] dataBytes) {
char format = '\0';
while (true) {
format = (char) dataBytes[0];
if (format == 's') {
dataBytes = Snappy.uncompress(dataBytes, 1, dataBytes.length - 1);
} else if (format == '{') {
return (Map<String, Object>) ObjectUtils.fromJson(new String(dataBytes, StringUtils.UTF_8));
} else {
break;
}
}
throw new IllegalStateException(String.format(
"Unknown format! ([%s])", format));
}
private final transient Cache<String, byte[]> dataCache = CacheBuilder.newBuilder().maximumSize(10000).build();
/**
* Creates a previously saved object using the given {@code resultSet}.
*/
private <T> T createSavedObjectWithResultSet(ResultSet resultSet, Query<T> query) throws SQLException {
T object = createSavedObject(resultSet.getObject(2), resultSet.getObject(1), query);
State objectState = State.getInstance(object);
if (!objectState.isReferenceOnly()) {
byte[] data = null;
if (isCacheData()) {
UUID id = objectState.getId();
String key = id + "/" + resultSet.getDouble(3);
data = dataCache.getIfPresent(key);
if (data == null) {
SqlVendor vendor = getVendor();
StringBuilder sqlQuery = new StringBuilder();
sqlQuery.append("SELECT r.");
vendor.appendIdentifier(sqlQuery, "data");
sqlQuery.append(", ru.");
vendor.appendIdentifier(sqlQuery, "updateDate");
sqlQuery.append(" FROM ");
vendor.appendIdentifier(sqlQuery, "Record");
sqlQuery.append(" AS r LEFT OUTER JOIN ");
vendor.appendIdentifier(sqlQuery, "RecordUpdate");
sqlQuery.append(" AS ru ON r.");
vendor.appendIdentifier(sqlQuery, "id");
sqlQuery.append(" = ru.");
vendor.appendIdentifier(sqlQuery, "id");
sqlQuery.append(" WHERE r.");
vendor.appendIdentifier(sqlQuery, "id");
sqlQuery.append(" = ");
vendor.appendUuid(sqlQuery, id);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = super.openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery.toString(), 0);
if (result.next()) {
data = result.getBytes(1);
dataCache.put(id + "/" + result.getDouble(2), data);
}
} catch (SQLException error) {
throw createQueryException(error, sqlQuery.toString(), query);
} finally {
closeResources(null, connection, statement, result);
}
}
} else {
data = resultSet.getBytes(3);
}
if (data != null) {
objectState.putAll(unserializeData(data));
Boolean returnOriginal = ObjectUtils.to(Boolean.class, query.getOptions().get(RETURN_ORIGINAL_DATA_QUERY_OPTION));
if (returnOriginal == null) {
returnOriginal = Boolean.FALSE;
}
if (returnOriginal) {
objectState.getExtras().put(ORIGINAL_DATA_EXTRA, data);
}
}
}
ResultSetMetaData meta = resultSet.getMetaData();
for (int i = 4, count = meta.getColumnCount(); i <= count; ++ i) {
String columnName = meta.getColumnLabel(i);
if (query.getExtraSourceColumns().containsKey(columnName)) {
objectState.put(query.getExtraSourceColumns().get(columnName), resultSet.getObject(i));
} else {
objectState.getExtras().put(EXTRA_COLUMN_EXTRA_PREFIX + meta.getColumnLabel(i), resultSet.getObject(i));
}
}
// Load some extra column from source index tables.
@SuppressWarnings("unchecked")
Set<UUID> unresolvedTypeIds = (Set<UUID>) query.getOptions().get(State.UNRESOLVED_TYPE_IDS_QUERY_OPTION);
Set<ObjectType> queryTypes = query.getConcreteTypes(getEnvironment());
ObjectType type = objectState.getType();
HashSet<ObjectField> loadExtraFields = new HashSet<ObjectField>();
// Set up Metric fields
for (ObjectField field : getEnvironment().getFields()) {
if (field.as(MetricDatabase.FieldData.class).isMetricValue()) {
objectState.putByPath(field.getInternalName(), new Metric(objectState, field));
}
}
if (type != null) {
for (ObjectField field : type.getFields()) {
if (field.as(MetricDatabase.FieldData.class).isMetricValue()) {
objectState.putByPath(field.getInternalName(), new Metric(objectState, field));
}
}
if ((unresolvedTypeIds == null || !unresolvedTypeIds.contains(type.getId())) &&
!queryTypes.contains(type)) {
for (ObjectField field : type.getFields()) {
SqlDatabase.FieldData fieldData = field.as(SqlDatabase.FieldData.class);
MetricDatabase.FieldData metricFieldData = field.as(MetricDatabase.FieldData.class);
if (fieldData.isIndexTableSource() && ! metricFieldData.isMetricValue()) {
loadExtraFields.add(field);
}
}
}
}
if (loadExtraFields != null) {
Connection connection = openQueryConnection(query);
try {
for (ObjectField field : loadExtraFields) {
Statement extraStatement = null;
ResultSet extraResult = null;
try {
extraStatement = connection.createStatement();
extraResult = executeQueryBeforeTimeout(
extraStatement,
extraSourceSelectStatementById(field, objectState.getId(), objectState.getTypeId()),
getQueryReadTimeout(query));
if (extraResult.next()) {
meta = extraResult.getMetaData();
for (int i = 1, count = meta.getColumnCount(); i <= count; ++ i) {
objectState.put(meta.getColumnLabel(i), extraResult.getObject(i));
}
}
} finally {
closeResources(null, null, extraStatement, extraResult);
}
}
} finally {
closeResources(query, connection, null, null);
}
}
return swapObjectType(query, object);
}
// Creates an SQL statement to return a single row from a FieldIndexTable
// used as a source table.
// Maybe: move this to SqlQuery and use initializeClauses() and
// needsRecordTable=false instead of passing id to this method. Needs
// countperformance branch to do this.
private String extraSourceSelectStatementById(ObjectField field, UUID id, UUID typeId) {
FieldData fieldData = field.as(FieldData.class);
ObjectType parentType = field.getParentType();
StringBuilder keyName = new StringBuilder(parentType.getInternalName());
keyName.append("/");
keyName.append(field.getInternalName());
Query<?> query = Query.fromType(parentType);
Query.MappedKey key = query.mapEmbeddedKey(getEnvironment(), keyName.toString());
ObjectIndex useIndex = null;
for (ObjectIndex index : key.getIndexes()) {
if (field.getInternalName().equals(index.getFields().get(0))) {
useIndex = index;
break;
}
}
SqlIndex useSqlIndex = SqlIndex.Static.getByIndex(useIndex);
SqlIndex.Table indexTable = useSqlIndex.getReadTable(this, useIndex);
String sourceTableName = fieldData.getIndexTable();
int symbolId = getSymbolId(key.getIndexKey(useIndex));
StringBuilder sql = new StringBuilder();
int fieldIndex = 0;
sql.append("SELECT ");
for (String indexFieldName : useIndex.getFields()) {
String indexColumnName = indexTable.getValueField(this, useIndex, fieldIndex);
++ fieldIndex;
vendor.appendIdentifier(sql, indexColumnName);
sql.append(" AS ");
vendor.appendIdentifier(sql, indexFieldName);
sql.append(", ");
}
sql.setLength(sql.length() - 2);
sql.append(" FROM ");
vendor.appendIdentifier(sql, sourceTableName);
sql.append(" WHERE ");
vendor.appendIdentifier(sql, "id");
sql.append(" = ");
vendor.appendValue(sql, id);
sql.append(" AND ");
vendor.appendIdentifier(sql, "symbolId");
sql.append(" = ");
sql.append(symbolId);
return sql.toString();
}
/**
* Executes the given read {@code statement} (created from the given
* {@code sqlQuery}) before the given {@code timeout} (in seconds).
*/
ResultSet executeQueryBeforeTimeout(
Statement statement,
String sqlQuery,
int timeout)
throws SQLException {
if (timeout > 0 && !(vendor instanceof SqlVendor.PostgreSQL)) {
statement.setQueryTimeout(timeout);
}
Stats.Timer timer = STATS.startTimer();
Profiler.Static.startThreadEvent(QUERY_PROFILER_EVENT);
try {
return statement.executeQuery(sqlQuery);
} finally {
double duration = timer.stop(QUERY_STATS_OPERATION);
Profiler.Static.stopThreadEvent(sqlQuery);
LOGGER.debug(
"Read from the SQL database using [{}] in [{}]ms",
sqlQuery, duration);
}
}
/**
* Selects the first object that matches the given {@code sqlQuery}
* with options from the given {@code query}.
*/
public <T> T selectFirstWithOptions(String sqlQuery, Query<T> query) {
sqlQuery = vendor.rewriteQueryWithLimitClause(sqlQuery, 1, 0);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
return result.next() ? createSavedObjectWithResultSet(result, query) : null;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
/**
* Selects the first object that matches the given {@code sqlQuery}
* without a timeout.
*/
public Object selectFirst(String sqlQuery) {
return selectFirstWithOptions(sqlQuery, null);
}
/**
* Selects a list of objects that match the given {@code sqlQuery}
* with options from the given {@code query}.
*/
public <T> List<T> selectListWithOptions(String sqlQuery, Query<T> query) {
Connection connection = null;
Statement statement = null;
ResultSet result = null;
List<T> objects = new ArrayList<T>();
int timeout = getQueryReadTimeout(query);
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, timeout);
while (result.next()) {
objects.add(createSavedObjectWithResultSet(result, query));
}
return objects;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
/**
* Selects a list of objects that match the given {@code sqlQuery}
* without a timeout.
*/
public List<Object> selectList(String sqlQuery) {
return selectListWithOptions(sqlQuery, null);
}
/**
* Returns an iterable that selects all objects matching the given
* {@code sqlQuery} with options from the given {@code query}.
*/
public <T> Iterable<T> selectIterableWithOptions(
final String sqlQuery,
final int fetchSize,
final Query<T> query) {
return new Iterable<T>() {
@Override
public Iterator<T> iterator() {
return new SqlIterator<T>(sqlQuery, fetchSize, query);
}
};
}
private class SqlIterator<T> implements java.io.Closeable, Iterator<T> {
private final String sqlQuery;
private final Query<T> query;
private final Connection connection;
private final Statement statement;
private final ResultSet result;
private boolean hasNext = true;
public SqlIterator(String initialSqlQuery, int fetchSize, Query<T> initialQuery) {
sqlQuery = initialSqlQuery;
query = initialQuery;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
statement.setFetchSize(
getVendor() instanceof SqlVendor.MySQL ? Integer.MIN_VALUE :
fetchSize <= 0 ? 200 :
fetchSize);
result = statement.executeQuery(sqlQuery);
moveToNext();
} catch (SQLException ex) {
close();
throw createQueryException(ex, sqlQuery, query);
}
}
private void moveToNext() throws SQLException {
if (hasNext) {
hasNext = result.next();
if (!hasNext) {
close();
}
}
}
public void close() {
hasNext = false;
closeResources(query, connection, statement, result);
}
@Override
public boolean hasNext() {
return hasNext;
}
@Override
public T next() {
if (!hasNext) {
throw new NoSuchElementException();
}
try {
T object = createSavedObjectWithResultSet(result, query);
moveToNext();
return object;
} catch (SQLException ex) {
close();
throw createQueryException(ex, sqlQuery, query);
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
protected void finalize() {
close();
}
}
/**
* Fills the placeholders in the given {@code sqlQuery} with the given
* {@code parameters}.
*/
private static String fillPlaceholders(String sqlQuery, Object... parameters) {
StringBuilder filled = new StringBuilder();
int prevPh = 0;
for (int ph, index = 0; (ph = sqlQuery.indexOf('?', prevPh)) > -1; ++ index) {
filled.append(sqlQuery.substring(prevPh, ph));
prevPh = ph + 1;
filled.append(quoteValue(parameters[index]));
}
filled.append(sqlQuery.substring(prevPh));
return filled.toString();
}
/**
* Executes the given write {@code sqlQuery} with the given
* {@code parameters}.
*
* @deprecated Use {@link Static#executeUpdate} instead.
*/
@Deprecated
public int executeUpdate(String sqlQuery, Object... parameters) {
try {
return Static.executeUpdateWithArray(getConnection(), sqlQuery, parameters);
} catch (SQLException ex) {
throw createQueryException(ex, fillPlaceholders(sqlQuery, parameters), null);
}
}
/**
* Reads the given {@code resultSet} into a list of maps
* and closes it.
*/
public List<Map<String, Object>> readResultSet(ResultSet resultSet) throws SQLException {
try {
ResultSetMetaData meta = resultSet.getMetaData();
List<String> columnNames = new ArrayList<String>();
for (int i = 1, count = meta.getColumnCount(); i < count; ++ i) {
columnNames.add(meta.getColumnName(i));
}
List<Map<String, Object>> maps = new ArrayList<Map<String, Object>>();
while (resultSet.next()) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
maps.add(map);
for (int i = 0, size = columnNames.size(); i < size; ++ i) {
map.put(columnNames.get(i), resultSet.getObject(i + 1));
}
}
return maps;
} finally {
resultSet.close();
}
}
@Override
public Connection openConnection() {
DataSource dataSource = getDataSource();
if (dataSource == null) {
throw new SqlDatabaseException(this, "No SQL data source!");
}
try {
Connection connection = dataSource.getConnection();
connection.setReadOnly(false);
return connection;
} catch (SQLException error) {
throw new SqlDatabaseException(this, "Can't connect to the SQL engine!", error);
}
}
@Override
protected Connection doOpenReadConnection() {
DataSource readDataSource = getReadDataSource();
if (readDataSource == null) {
readDataSource = getDataSource();
}
if (readDataSource == null) {
throw new SqlDatabaseException(this, "No SQL data source!");
}
try {
Connection connection = readDataSource.getConnection();
connection.setReadOnly(true);
return connection;
} catch (SQLException error) {
throw new SqlDatabaseException(this, "Can't connect to the SQL engine!", error);
}
}
@Override
public Connection openQueryConnection(Query<?> query) {
if (query != null) {
Connection connection = (Connection) query.getOptions().get(CONNECTION_QUERY_OPTION);
if (connection != null) {
return connection;
}
Boolean useRead = ObjectUtils.to(Boolean.class, query.getOptions().get(USE_READ_DATA_SOURCE_QUERY_OPTION));
if (useRead == null) {
useRead = Boolean.TRUE;
}
if (!useRead) {
return openConnection();
}
}
return super.openQueryConnection(query);
}
@Override
public void closeConnection(Connection connection) {
if (connection != null) {
try {
connection.close();
} catch (SQLException ex) {
}
}
}
@Override
protected boolean isRecoverableError(Exception error) {
if (error instanceof SQLException) {
SQLException sqlError = (SQLException) error;
return "40001".equals(sqlError.getSQLState());
}
return false;
}
@Override
protected void doInitialize(String settingsKey, Map<String, Object> settings) {
close();
setReadDataSource(createDataSource(
settings,
READ_DATA_SOURCE_SETTING,
READ_JDBC_DRIVER_CLASS_SETTING,
READ_JDBC_URL_SETTING,
READ_JDBC_USER_SETTING,
READ_JDBC_PASSWORD_SETTING,
READ_JDBC_POOL_SIZE_SETTING));
setDataSource(createDataSource(
settings,
DATA_SOURCE_SETTING,
JDBC_DRIVER_CLASS_SETTING,
JDBC_URL_SETTING,
JDBC_USER_SETTING,
JDBC_PASSWORD_SETTING,
JDBC_POOL_SIZE_SETTING));
String vendorClassName = ObjectUtils.to(String.class, settings.get(VENDOR_CLASS_SETTING));
Class<?> vendorClass = null;
if (vendorClassName != null) {
vendorClass = ObjectUtils.getClassByName(vendorClassName);
if (vendorClass == null) {
throw new SettingsException(
VENDOR_CLASS_SETTING,
String.format("Can't find [%s]!",
vendorClassName));
} else if (!SqlVendor.class.isAssignableFrom(vendorClass)) {
throw new SettingsException(
VENDOR_CLASS_SETTING,
String.format("[%s] doesn't implement [%s]!",
vendorClass, Driver.class));
}
}
if (vendorClass != null) {
setVendor((SqlVendor) TypeDefinition.getInstance(vendorClass).newInstance());
}
Boolean compressData = ObjectUtils.coalesce(
ObjectUtils.to(Boolean.class, settings.get(COMPRESS_DATA_SUB_SETTING)),
Settings.get(Boolean.class, "dari/isCompressSqlData"));
if (compressData != null) {
setCompressData(compressData);
}
setCacheData(ObjectUtils.to(boolean.class, settings.get(CACHE_DATA_SUB_SETTING)));
}
private static final Map<String, String> DRIVER_CLASS_NAMES; static {
Map<String, String> m = new HashMap<String, String>();
m.put("h2", "org.h2.Driver");
m.put("jtds", "net.sourceforge.jtds.jdbc.Driver");
m.put("mysql", "com.mysql.jdbc.Driver");
m.put("postgresql", "org.postgresql.Driver");
DRIVER_CLASS_NAMES = m;
}
private static final Set<WeakReference<Driver>> REGISTERED_DRIVERS = new HashSet<WeakReference<Driver>>();
private DataSource createDataSource(
Map<String, Object> settings,
String dataSourceSetting,
String jdbcDriverClassSetting,
String jdbcUrlSetting,
String jdbcUserSetting,
String jdbcPasswordSetting,
String jdbcPoolSizeSetting) {
Object dataSourceObject = settings.get(dataSourceSetting);
if (dataSourceObject instanceof DataSource) {
return (DataSource) dataSourceObject;
} else {
String url = ObjectUtils.to(String.class, settings.get(jdbcUrlSetting));
if (ObjectUtils.isBlank(url)) {
return null;
} else {
String driverClassName = ObjectUtils.to(String.class, settings.get(jdbcDriverClassSetting));
Class<?> driverClass = null;
if (driverClassName != null) {
driverClass = ObjectUtils.getClassByName(driverClassName);
if (driverClass == null) {
throw new SettingsException(
jdbcDriverClassSetting,
String.format("Can't find [%s]!",
driverClassName));
} else if (!Driver.class.isAssignableFrom(driverClass)) {
throw new SettingsException(
jdbcDriverClassSetting,
String.format("[%s] doesn't implement [%s]!",
driverClass, Driver.class));
}
} else {
int firstColonAt = url.indexOf(':');
if (firstColonAt > -1) {
++ firstColonAt;
int secondColonAt = url.indexOf(':', firstColonAt);
if (secondColonAt > -1) {
driverClass = ObjectUtils.getClassByName(DRIVER_CLASS_NAMES.get(url.substring(firstColonAt, secondColonAt)));
}
}
}
if (driverClass != null) {
Driver driver = null;
for (Enumeration<Driver> e = DriverManager.getDrivers(); e.hasMoreElements(); ) {
Driver d = e.nextElement();
if (driverClass.isInstance(d)) {
driver = d;
break;
}
}
if (driver == null) {
driver = (Driver) TypeDefinition.getInstance(driverClass).newInstance();
try {
LOGGER.info("Registering [{}]", driver);
DriverManager.registerDriver(driver);
} catch (SQLException ex) {
LOGGER.warn("Can't register [{}]!", driver);
}
}
if (driver != null) {
REGISTERED_DRIVERS.add(new WeakReference<Driver>(driver));
}
}
String user = ObjectUtils.to(String.class, settings.get(jdbcUserSetting));
String password = ObjectUtils.to(String.class, settings.get(jdbcPasswordSetting));
Integer poolSize = ObjectUtils.to(Integer.class, settings.get(jdbcPoolSizeSetting));
if (poolSize == null || poolSize <= 0) {
poolSize = 24;
}
int partitionCount = 3;
int connectionsPerPartition = poolSize / partitionCount;
LOGGER.info("Automatically creating BoneCP data source:" +
"\n\turl={}" +
"\n\tusername={}" +
"\n\tpoolSize={}" +
"\n\tconnectionsPerPartition={}" +
"\n\tpartitionCount={}", new Object[] {
url,
user,
poolSize,
connectionsPerPartition,
partitionCount
});
BoneCPDataSource bone = new BoneCPDataSource();
bone.setJdbcUrl(url);
bone.setUsername(user);
bone.setPassword(password);
bone.setMinConnectionsPerPartition(connectionsPerPartition);
bone.setMaxConnectionsPerPartition(connectionsPerPartition);
bone.setPartitionCount(partitionCount);
bone.setConnectionTimeoutInMs(5000L);
return bone;
}
}
}
/** Returns the read timeout associated with the given {@code query}. */
private int getQueryReadTimeout(Query<?> query) {
if (query != null) {
Double timeout = query.getTimeout();
if (timeout == null) {
timeout = getReadTimeout();
}
if (timeout > 0.0) {
return (int) Math.round(timeout);
}
}
return 0;
}
@Override
public <T> List<T> readAll(Query<T> query) {
return selectListWithOptions(buildSelectStatement(query), query);
}
@Override
public long readCount(Query<?> query) {
String sqlQuery = buildCountStatement(query);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
if (result.next()) {
Object countObj = result.getObject(1);
if (countObj instanceof Number) {
return ((Number) countObj).longValue();
}
}
return 0;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
@Override
public <T> T readFirst(Query<T> query) {
if (query.getSorters().isEmpty()) {
Predicate predicate = query.getPredicate();
if (predicate instanceof CompoundPredicate) {
CompoundPredicate compoundPredicate = (CompoundPredicate) predicate;
if (PredicateParser.OR_OPERATOR.equals(compoundPredicate.getOperator())) {
for (Predicate child : compoundPredicate.getChildren()) {
Query<T> childQuery = query.clone();
childQuery.setPredicate(child);
T first = readFirst(childQuery);
if (first != null) {
return first;
}
}
return null;
}
}
}
return selectFirstWithOptions(buildSelectStatement(query), query);
}
@Override
public <T> Iterable<T> readIterable(Query<T> query, int fetchSize) {
Boolean useJdbc = ObjectUtils.to(Boolean.class, query.getOptions().get(USE_JDBC_FETCH_SIZE_QUERY_OPTION));
if (useJdbc == null) {
useJdbc = Boolean.TRUE;
}
if (useJdbc) {
return selectIterableWithOptions(buildSelectStatement(query), fetchSize, query);
} else {
return new ByIdIterable<T>(query, fetchSize);
}
}
private static class ByIdIterable<T> implements Iterable<T> {
private final Query<T> query;
private final int fetchSize;
public ByIdIterable(Query<T> query, int fetchSize) {
this.query = query;
this.fetchSize = fetchSize;
}
@Override
public Iterator<T> iterator() {
return new ByIdIterator<T>(query, fetchSize);
}
}
private static class ByIdIterator<T> implements Iterator<T> {
private final Query<T> query;
private final int fetchSize;
private UUID lastTypeId;
private UUID lastId;
private List<T> items;
private int index;
public ByIdIterator(Query<T> query, int fetchSize) {
if (!query.getSorters().isEmpty()) {
throw new IllegalArgumentException("Can't iterate over a query that has sorters!");
}
this.query = query.clone().timeout(0.0).sortAscending("_type").sortAscending("_id");
this.fetchSize = fetchSize > 0 ? fetchSize : 200;
}
@Override
public boolean hasNext() {
if (items != null && items.isEmpty()) {
return false;
}
if (items == null || index >= items.size()) {
Query<T> nextQuery = query.clone();
if (lastTypeId != null) {
nextQuery.and("_type = ? and _id > ?", lastTypeId, lastId);
}
items = nextQuery.select(0, fetchSize).getItems();
int size = items.size();
if (size < 1) {
if (lastTypeId == null) {
return false;
} else {
nextQuery = query.clone().and("_type > ?", lastTypeId);
items = nextQuery.select(0, fetchSize).getItems();
size = items.size();
if (size < 1) {
return false;
}
}
}
State lastState = State.getInstance(items.get(size - 1));
lastTypeId = lastState.getTypeId();
lastId = lastState.getId();
index = 0;
}
return true;
}
@Override
public T next() {
if (hasNext()) {
T object = items.get(index);
++ index;
return object;
} else {
throw new NoSuchElementException();
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
@Override
public Date readLastUpdate(Query<?> query) {
String sqlQuery = buildLastUpdateStatement(query);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
if (result.next()) {
Double date = result.getDouble(1);
if (date != null) {
return new Date((long) (date * 1000L));
}
}
return null;
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
@Override
public <T> PaginatedResult<T> readPartial(final Query<T> query, long offset, int limit) {
List<T> objects = selectListWithOptions(
vendor.rewriteQueryWithLimitClause(buildSelectStatement(query), limit + 1, offset),
query);
int size = objects.size();
if (size <= limit) {
return new PaginatedResult<T>(offset, limit, offset + size, objects);
} else {
objects.remove(size - 1);
return new PaginatedResult<T>(offset, limit, 0, objects) {
private Long count;
@Override
public long getCount() {
if (count == null) {
count = readCount(query);
}
return count;
}
@Override
public boolean hasNext() {
return true;
}
};
}
}
@Override
public <T> PaginatedResult<Grouping<T>> readPartialGrouped(Query<T> query, long offset, int limit, String... fields) {
List<Grouping<T>> groupings = new ArrayList<Grouping<T>>();
String sqlQuery = buildGroupStatement(query, fields);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
int fieldsLength = fields.length;
int groupingsCount = 0;
for (int i = 0, last = (int) offset + limit; result.next(); ++ i, ++ groupingsCount) {
if (i < offset || i >= last) {
continue;
}
List<Object> keys = new ArrayList<Object>();
SqlGrouping<T> grouping;
ResultSetMetaData meta = result.getMetaData();
String aggregateColumnName = meta.getColumnName(1);
if (aggregateColumnName.equals("_count")) {
long count = ObjectUtils.to(long.class, result.getObject(1));
for (int j = 0; j < fieldsLength; ++ j) {
keys.add(result.getObject(j + 2));
}
grouping = new SqlGrouping<T>(keys, query, fields, count, groupings);
} else {
Double amount = ObjectUtils.to(Double.class, result.getObject(1));
for (int j = 0; j < fieldsLength; ++ j) {
keys.add(result.getObject(j + 3));
}
long count = 0L;
if (meta.getColumnName(2).equals("_count")) {
count = ObjectUtils.to(long.class, result.getObject(2));
}
grouping = new SqlGrouping<T>(keys, query, fields, count, groupings);
if (amount == null) amount = 0d;
grouping.setSum(aggregateColumnName, amount);
}
groupings.add(grouping);
}
int groupingsSize = groupings.size();
for (int i = 0; i < fieldsLength; ++ i) {
ObjectField field = query.mapEmbeddedKey(getEnvironment(), fields[i]).getField();
if (field != null) {
Map<String, Object> rawKeys = new HashMap<String, Object>();
for (int j = 0; j < groupingsSize; ++ j) {
rawKeys.put(String.valueOf(j), groupings.get(j).getKeys().get(i));
}
String itemType = field.getInternalItemType();
if (ObjectField.RECORD_TYPE.equals(itemType)) {
for (Map.Entry<String, Object> entry : rawKeys.entrySet()) {
Map<String, Object> ref = new HashMap<String, Object>();
ref.put(StateValueUtils.REFERENCE_KEY, entry.getValue());
entry.setValue(ref);
}
}
Map<?, ?> convertedKeys = (Map<?, ?>) StateValueUtils.toJavaValue(query.getDatabase(), null, field, "map/" + itemType, rawKeys);
for (int j = 0; j < groupingsSize; ++ j) {
groupings.get(j).getKeys().set(i, convertedKeys.get(String.valueOf(j)));
}
}
}
return new PaginatedResult<Grouping<T>>(offset, limit, groupingsCount, groupings);
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
/** SQL-specific implementation of {@link Grouping}. */
private class SqlGrouping<T> extends AbstractGrouping<T> {
private long count;
private final Map<String,Double> metricSums = new HashMap<String,Double>();
private final List<Grouping<T>> groupings;
public SqlGrouping(List<Object> keys, Query<T> query, String[] fields, long count, List<Grouping<T>> groupings) {
super(keys, query, fields);
this.count = count;
this.groupings = groupings;
}
@Override
public double getSum(String field) {
Query.MappedKey mappedKey = this.query.mapEmbeddedKey(getEnvironment(), field);
ObjectField sumField = mappedKey.getField();
if (sumField.as(MetricDatabase.FieldData.class).isMetricValue()) {
if (! metricSums.containsKey(field)) {
String sqlQuery = buildGroupedMetricStatement(query, field, fields);
Connection connection = null;
Statement statement = null;
ResultSet result = null;
try {
connection = openQueryConnection(query);
statement = connection.createStatement();
result = executeQueryBeforeTimeout(statement, sqlQuery, getQueryReadTimeout(query));
if (this.getKeys().size() == 0) {
// Special case for .groupby() without any fields
if (this.groupings.size() != 1) throw new RuntimeException("There should only be one grouping when grouping by nothing. Something went wrong internally.");
if (result.next() && result.getBytes(1) != null) {
this.setSum(field, result.getDouble(1));
} else {
this.setSum(field, 0);
}
} else {
// Find the ObjectFields for the specified fields
List<ObjectField> objectFields = new ArrayList<ObjectField>();
for (String fieldName : fields) {
objectFields.add(query.mapEmbeddedKey(getEnvironment(), fieldName).getField());
}
// index the groupings by their keys
Map<List<Object>, SqlGrouping<T>> groupingMap = new HashMap<List<Object>, SqlGrouping<T>>();
for (Grouping<T> grouping : groupings) {
if (grouping instanceof SqlGrouping) {
((SqlGrouping<T>) grouping).setSum(field, 0);
groupingMap.put(grouping.getKeys(), (SqlGrouping<T>) grouping);
}
}
// Find the sums and set them on each grouping
while (result.next()) {
// TODO: limit/offset
List<Object> keys = new ArrayList<Object>();
for (int j = 0; j < objectFields.size(); ++ j) {
keys.add(StateValueUtils.toJavaValue(query.getDatabase(), null, objectFields.get(j), objectFields.get(j).getInternalItemType(), result.getObject(j+3))); // 3 because _count and amount
}
if (groupingMap.containsKey(keys)) {
if (result.getBytes(1) != null) {
groupingMap.get(keys).setSum(field, result.getDouble(1));
} else {
groupingMap.get(keys).setSum(field, 0);
}
}
}
}
} catch (SQLException ex) {
throw createQueryException(ex, sqlQuery, query);
} finally {
closeResources(query, connection, statement, result);
}
}
if (metricSums.containsKey(field))
return metricSums.get(field);
else
return 0;
} else {
// If it's not a MetricValue, we don't need to override it.
return super.getSum(field);
}
}
private void setSum(String field, double sum) {
metricSums.put(field, sum);
}
@Override
protected Aggregate createAggregate(String field) {
throw new UnsupportedOperationException();
}
@Override
public long getCount() {
return count;
}
}
@Override
protected void beginTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.setAutoCommit(false);
}
@Override
protected void commitTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.commit();
}
@Override
protected void rollbackTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.rollback();
}
@Override
protected void endTransaction(Connection connection, boolean isImmediate) throws SQLException {
connection.setAutoCommit(true);
}
@Override
protected void doSaves(Connection connection, boolean isImmediate, List<State> states) throws SQLException {
List<State> indexStates = null;
for (State state1 : states) {
if (Boolean.TRUE.equals(state1.getExtra(SKIP_INDEX_STATE_EXTRA))) {
indexStates = new ArrayList<State>();
for (State state2 : states) {
if (!Boolean.TRUE.equals(state2.getExtra(SKIP_INDEX_STATE_EXTRA))) {
indexStates.add(state2);
}
}
break;
}
}
if (indexStates == null) {
indexStates = states;
}
SqlIndex.Static.deleteByStates(this, connection, indexStates);
Map<State, String> inRowIndexes = SqlIndex.Static.insertByStates(this, connection, indexStates);
boolean hasInRowIndex = hasInRowIndex();
SqlVendor vendor = getVendor();
double now = System.currentTimeMillis() / 1000.0;
for (State state : states) {
boolean isNew = state.isNew();
boolean saveInRowIndex = hasInRowIndex && !Boolean.TRUE.equals(state.getExtra(SKIP_INDEX_STATE_EXTRA));
UUID id = state.getId();
UUID typeId = state.getVisibilityAwareTypeId();
byte[] dataBytes = null;
String inRowIndex = inRowIndexes.get(state);
byte[] inRowIndexBytes = inRowIndex != null ? inRowIndex.getBytes(StringUtils.UTF_8) : new byte[0];
while (true) {
if (isNew) {
try {
if (dataBytes == null) {
dataBytes = serializeState(state);
}
List<Object> parameters = new ArrayList<Object>();
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.append("INSERT INTO ");
vendor.appendIdentifier(insertBuilder, RECORD_TABLE);
insertBuilder.append(" (");
vendor.appendIdentifier(insertBuilder, ID_COLUMN);
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, TYPE_ID_COLUMN);
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, DATA_COLUMN);
if (saveInRowIndex) {
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, IN_ROW_INDEX_COLUMN);
}
insertBuilder.append(") VALUES (");
vendor.appendBindValue(insertBuilder, id, parameters);
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, typeId, parameters);
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, dataBytes, parameters);
if (saveInRowIndex) {
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, inRowIndexBytes, parameters);
}
insertBuilder.append(")");
Static.executeUpdateWithList(connection, insertBuilder.toString(), parameters);
} catch (SQLException ex) {
if (Static.isIntegrityConstraintViolation(ex)) {
isNew = false;
continue;
} else {
throw ex;
}
}
} else {
List<AtomicOperation> atomicOperations = state.getAtomicOperations();
if (atomicOperations.isEmpty()) {
if (dataBytes == null) {
dataBytes = serializeState(state);
}
List<Object> parameters = new ArrayList<Object>();
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, typeId, parameters);
updateBuilder.append(",");
if (saveInRowIndex) {
vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, inRowIndexBytes, parameters);
updateBuilder.append(",");
}
vendor.appendIdentifier(updateBuilder, DATA_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, dataBytes, parameters);
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, id, parameters);
if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) {
isNew = true;
continue;
}
} else {
Object oldObject = Query.
from(Object.class).
where("_id = ?", id).
using(this).
option(CONNECTION_QUERY_OPTION, connection).
option(RETURN_ORIGINAL_DATA_QUERY_OPTION, Boolean.TRUE).
option(USE_READ_DATA_SOURCE_QUERY_OPTION, Boolean.FALSE).
first();
if (oldObject == null) {
retryWrites();
break;
}
State oldState = State.getInstance(oldObject);
UUID oldTypeId = oldState.getVisibilityAwareTypeId();
byte[] oldData = Static.getOriginalData(oldObject);
state.setValues(oldState.getValues());
for (AtomicOperation operation : atomicOperations) {
String field = operation.getField();
state.putValue(field, oldState.getValue(field));
}
for (AtomicOperation operation : atomicOperations) {
operation.execute(state);
}
dataBytes = serializeState(state);
List<Object> parameters = new ArrayList<Object>();
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, typeId, parameters);
if (saveInRowIndex) {
updateBuilder.append(",");
vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, inRowIndexBytes, parameters);
}
updateBuilder.append(",");
vendor.appendIdentifier(updateBuilder, DATA_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, dataBytes, parameters);
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, id, parameters);
updateBuilder.append(" AND ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, oldTypeId, parameters);
updateBuilder.append(" AND ");
vendor.appendIdentifier(updateBuilder, DATA_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, oldData, parameters);
if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) {
retryWrites();
break;
}
}
}
break;
}
while (true) {
if (isNew) {
List<Object> parameters = new ArrayList<Object>();
StringBuilder insertBuilder = new StringBuilder();
insertBuilder.append("INSERT INTO ");
vendor.appendIdentifier(insertBuilder, RECORD_UPDATE_TABLE);
insertBuilder.append(" (");
vendor.appendIdentifier(insertBuilder, ID_COLUMN);
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, TYPE_ID_COLUMN);
insertBuilder.append(",");
vendor.appendIdentifier(insertBuilder, UPDATE_DATE_COLUMN);
insertBuilder.append(") VALUES (");
vendor.appendBindValue(insertBuilder, id, parameters);
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, typeId, parameters);
insertBuilder.append(",");
vendor.appendBindValue(insertBuilder, now, parameters);
insertBuilder.append(")");
try {
Static.executeUpdateWithList(connection, insertBuilder.toString(), parameters);
} catch (SQLException ex) {
if (Static.isIntegrityConstraintViolation(ex)) {
isNew = false;
continue;
} else {
throw ex;
}
}
} else {
List<Object> parameters = new ArrayList<Object>();
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_UPDATE_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, TYPE_ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, typeId, parameters);
updateBuilder.append(",");
vendor.appendIdentifier(updateBuilder, UPDATE_DATE_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, now, parameters);
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append("=");
vendor.appendBindValue(updateBuilder, id, parameters);
if (Static.executeUpdateWithList(connection, updateBuilder.toString(), parameters) < 1) {
isNew = true;
continue;
}
}
break;
}
}
}
@Override
protected void doIndexes(Connection connection, boolean isImmediate, List<State> states) throws SQLException {
SqlIndex.Static.deleteByStates(this, connection, states);
Map<State, String> inRowIndexes = SqlIndex.Static.insertByStates(this, connection, states);
if (!hasInRowIndex()) {
return;
}
SqlVendor vendor = getVendor();
for (Map.Entry<State, String> entry : inRowIndexes.entrySet()) {
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, IN_ROW_INDEX_COLUMN);
updateBuilder.append("=");
vendor.appendValue(updateBuilder, entry.getValue());
updateBuilder.append(" WHERE ");
vendor.appendIdentifier(updateBuilder, ID_COLUMN);
updateBuilder.append("=");
vendor.appendValue(updateBuilder, entry.getKey().getId());
Static.executeUpdateWithArray(connection, updateBuilder.toString());
}
}
/** @deprecated Use {@link #index} instead. */
@Deprecated
public void fixIndexes(List<State> states) {
Connection connection = openConnection();
try {
doIndexes(connection, true, states);
} catch (SQLException ex) {
List<UUID> ids = new ArrayList<UUID>();
for (State state : states) {
ids.add(state.getId());
}
throw new SqlDatabaseException(this, String.format(
"Can't index states! (%s)", ids));
} finally {
closeConnection(connection);
}
}
@Override
protected void doDeletes(Connection connection, boolean isImmediate, List<State> states) throws SQLException {
SqlVendor vendor = getVendor();
StringBuilder whereBuilder = new StringBuilder();
whereBuilder.append(" WHERE ");
vendor.appendIdentifier(whereBuilder, ID_COLUMN);
whereBuilder.append(" IN (");
for (State state : states) {
vendor.appendValue(whereBuilder, state.getId());
whereBuilder.append(",");
}
whereBuilder.setCharAt(whereBuilder.length() - 1, ')');
StringBuilder deleteBuilder = new StringBuilder();
deleteBuilder.append("DELETE FROM ");
vendor.appendIdentifier(deleteBuilder, RECORD_TABLE);
deleteBuilder.append(whereBuilder);
Static.executeUpdateWithArray(connection, deleteBuilder.toString());
SqlIndex.Static.deleteByStates(this, connection, states);
StringBuilder updateBuilder = new StringBuilder();
updateBuilder.append("UPDATE ");
vendor.appendIdentifier(updateBuilder, RECORD_UPDATE_TABLE);
updateBuilder.append(" SET ");
vendor.appendIdentifier(updateBuilder, UPDATE_DATE_COLUMN);
updateBuilder.append("=");
vendor.appendValue(updateBuilder, System.currentTimeMillis() / 1000.0);
updateBuilder.append(whereBuilder);
Static.executeUpdateWithArray(connection, updateBuilder.toString());
}
@FieldData.FieldInternalNamePrefix("sql.")
public static class FieldData extends Modification<ObjectField> {
private String indexTable;
private String indexTableColumnName;
private boolean indexTableReadOnly;
private boolean indexTableSameColumnNames;
private boolean indexTableSource;
public String getIndexTable() {
return indexTable;
}
public void setIndexTable(String indexTable) {
this.indexTable = indexTable;
}
public boolean isIndexTableReadOnly() {
return indexTableReadOnly;
}
public void setIndexTableReadOnly(boolean indexTableReadOnly) {
this.indexTableReadOnly = indexTableReadOnly;
}
public boolean isIndexTableSameColumnNames() {
return indexTableSameColumnNames;
}
public void setIndexTableSameColumnNames(boolean indexTableSameColumnNames) {
this.indexTableSameColumnNames = indexTableSameColumnNames;
}
public void setIndexTableColumnName(String indexTableColumnName) {
this.indexTableColumnName = indexTableColumnName;
}
public String getIndexTableColumnName() {
return this.indexTableColumnName;
}
public boolean isIndexTableSource() {
return indexTableSource;
}
public void setIndexTableSource(boolean indexTableSource) {
this.indexTableSource = indexTableSource;
}
public boolean isIndexTableSourceFromAnywhere() {
if (isIndexTableSource()) {
return true;
}
ObjectField field = getOriginalObject();
ObjectStruct parent = field.getParent();
String fieldName = field.getInternalName();
for (ObjectIndex index : parent.getIndexes()) {
List<String> indexFieldNames = index.getFields();
if (!indexFieldNames.isEmpty() &&
indexFieldNames.contains(fieldName)) {
String firstIndexFieldName = indexFieldNames.get(0);
if (!fieldName.equals(firstIndexFieldName)) {
ObjectField firstIndexField = parent.getField(firstIndexFieldName);
if (firstIndexField != null) {
return firstIndexField.as(FieldData.class).isIndexTableSource();
}
}
}
}
return false;
}
}
/** Specifies the name of the table for storing target field values. */
@Documented
@ObjectField.AnnotationProcessorClass(FieldIndexTableProcessor.class)
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface FieldIndexTable {
String value();
boolean readOnly() default false;
boolean sameColumnNames() default false;
boolean source() default false;
}
private static class FieldIndexTableProcessor implements ObjectField.AnnotationProcessor<FieldIndexTable> {
@Override
public void process(ObjectType type, ObjectField field, FieldIndexTable annotation) {
FieldData data = field.as(FieldData.class);
data.setIndexTable(annotation.value());
data.setIndexTableSameColumnNames(annotation.sameColumnNames());
data.setIndexTableSource(annotation.source());
data.setIndexTableReadOnly(annotation.readOnly());
}
}
/** {@link SqlDatabase} utility methods. */
public static final class Static {
private Static() {
}
public static List<SqlDatabase> getAll() {
return INSTANCES;
}
public static void deregisterAllDrivers() {
for (WeakReference<Driver> driverRef : REGISTERED_DRIVERS) {
Driver driver = driverRef.get();
if (driver != null) {
LOGGER.info("Deregistering [{}]", driver);
try {
DriverManager.deregisterDriver(driver);
} catch (SQLException ex) {
LOGGER.warn("Can't deregister [{}]!", driver);
}
}
}
}
/**
* Log a batch update exception with values.
*/
static void logBatchUpdateException(BatchUpdateException bue, String sqlQuery, List<? extends List<?>> parameters) {
int i = 0;
int failureOffset = bue.getUpdateCounts().length;
List<?> rowData = parameters.get(failureOffset);
StringBuilder errorBuilder = new StringBuilder();
errorBuilder.append("Batch update failed with query '");
errorBuilder.append(sqlQuery);
errorBuilder.append("' with values (");
for (Object value : rowData) {
if (i++ != 0) {
errorBuilder.append(", ");
}
if (value instanceof byte[]) {
errorBuilder.append(StringUtils.hex((byte[]) value));
} else {
errorBuilder.append(value);
}
}
errorBuilder.append(")");
Exception ex = bue.getNextException() != null ? bue.getNextException() : bue;
LOGGER.error(errorBuilder.toString(), ex);
}
static void logUpdateException(String sqlQuery, List<?> parameters) {
int i = 0;
StringBuilder errorBuilder = new StringBuilder();
errorBuilder.append("Batch update failed with query '");
errorBuilder.append(sqlQuery);
errorBuilder.append("' with values (");
for (Object value : parameters) {
if (i++ != 0) {
errorBuilder.append(", ");
}
if (value instanceof byte[]) {
errorBuilder.append(StringUtils.hex((byte[]) value));
} else {
errorBuilder.append(value);
}
}
errorBuilder.append(")");
LOGGER.error(errorBuilder.toString());
}
// Safely binds the given parameter to the given statement at the
// given index.
private static void bindParameter(PreparedStatement statement, int index, Object parameter) throws SQLException {
if (parameter instanceof String) {
parameter = ((String) parameter).getBytes(StringUtils.UTF_8);
}
if (parameter instanceof byte[]) {
byte[] parameterBytes = (byte[]) parameter;
int parameterBytesLength = parameterBytes.length;
if (parameterBytesLength > 2000) {
statement.setBinaryStream(index, new ByteArrayInputStream(parameterBytes), parameterBytesLength);
return;
}
}
statement.setObject(index, parameter);
}
/**
* Executes the given batch update {@code sqlQuery} with the given
* list of {@code parameters} within the given {@code connection}.
*
* @return Array of number of rows affected by the update query.
*/
public static int[] executeBatchUpdate(
Connection connection,
String sqlQuery,
List<? extends List<?>> parameters) throws SQLException {
PreparedStatement prepared = connection.prepareStatement(sqlQuery);
List<?> currentRow = null;
try {
for (List<?> row : parameters) {
currentRow = row;
int columnIndex = 1;
for (Object parameter : row) {
bindParameter(prepared, columnIndex, parameter);
columnIndex++;
}
prepared.addBatch();
}
int[] affected = null;
Stats.Timer timer = STATS.startTimer();
Profiler.Static.startThreadEvent(UPDATE_PROFILER_EVENT);
try {
return (affected = prepared.executeBatch());
} finally {
double time = timer.stop(UPDATE_STATS_OPERATION);
Profiler.Static.stopThreadEvent(sqlQuery);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"SQL batch update: [{}], Parameters: {}, Affected: {}, Time: [{}]ms",
new Object[] { sqlQuery, parameters, affected != null ? Arrays.toString(affected) : "[]", time });
}
}
} catch (SQLException error) {
logUpdateException(sqlQuery, currentRow);
throw error;
} finally {
try {
prepared.close();
} catch (SQLException error) {
}
}
}
/**
* Executes the given update {@code sqlQuery} with the given
* {@code parameters} within the given {@code connection}.
*
* @return Number of rows affected by the update query.
*/
public static int executeUpdateWithList(
Connection connection,
String sqlQuery,
List<?> parameters)
throws SQLException {
if (parameters == null) {
return executeUpdateWithArray(connection, sqlQuery);
} else {
Object[] array = parameters.toArray(new Object[parameters.size()]);
return executeUpdateWithArray(connection, sqlQuery, array);
}
}
/**
* Executes the given update {@code sqlQuery} with the given
* {@code parameters} within the given {@code connection}.
*
* @return Number of rows affected by the update query.
*/
public static int executeUpdateWithArray(
Connection connection,
String sqlQuery,
Object... parameters)
throws SQLException {
boolean hasParameters = parameters != null && parameters.length > 0;
PreparedStatement prepared;
Statement statement;
if (hasParameters) {
prepared = connection.prepareStatement(sqlQuery);
statement = prepared;
} else {
prepared = null;
statement = connection.createStatement();
}
try {
if (hasParameters) {
for (int i = 0; i < parameters.length; i++) {
bindParameter(prepared, i + 1, parameters[i]);
}
}
Integer affected = null;
Stats.Timer timer = STATS.startTimer();
Profiler.Static.startThreadEvent(UPDATE_PROFILER_EVENT);
try {
return (affected = hasParameters ?
prepared.executeUpdate() :
statement.executeUpdate(sqlQuery));
} finally {
double time = timer.stop(UPDATE_STATS_OPERATION);
Profiler.Static.stopThreadEvent(sqlQuery);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
"SQL update: [{}], Affected: [{}], Time: [{}]ms",
new Object[] { fillPlaceholders(sqlQuery, parameters), affected, time });
}
}
} finally {
try {
statement.close();
} catch (SQLException ex) {
}
}
}
/**
* Returns {@code true} if the given {@code error} looks like a
* {@link SQLIntegrityConstraintViolationException}.
*/
public static boolean isIntegrityConstraintViolation(SQLException error) {
if (error instanceof SQLIntegrityConstraintViolationException) {
return true;
} else {
String state = error.getSQLState();
return state != null && state.startsWith("23");
}
}
/**
* Returns the name of the table for storing the values of the
* given {@code index}.
*/
public static String getIndexTable(ObjectIndex index) {
return ObjectUtils.to(String.class, index.getOptions().get(INDEX_TABLE_INDEX_OPTION));
}
/**
* Sets the name of the table for storing the values of the
* given {@code index}.
*/
public static void setIndexTable(ObjectIndex index, String table) {
index.getOptions().put(INDEX_TABLE_INDEX_OPTION, table);
}
public static Object getExtraColumn(Object object, String name) {
return State.getInstance(object).getExtra(EXTRA_COLUMN_EXTRA_PREFIX + name);
}
public static byte[] getOriginalData(Object object) {
return (byte[]) State.getInstance(object).getExtra(ORIGINAL_DATA_EXTRA);
}
/** @deprecated Use {@link #executeUpdateWithArray} instead. */
@Deprecated
public static int executeUpdate(
Connection connection,
String sqlQuery,
Object... parameters)
throws SQLException {
return executeUpdateWithArray(connection, sqlQuery, parameters);
}
}
/** @deprecated No replacement. */
@Deprecated
public void beginThreadLocalReadConnection() {
}
/** @deprecated No replacement. */
@Deprecated
public void endThreadLocalReadConnection() {
}
} |
package com.galvarez.ttw.screens;
import static com.galvarez.ttw.utils.Colors.markup;
import java.util.ArrayList;
import java.util.List;
import com.artemis.World;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.galvarez.ttw.ThingsThatWereGame;
import com.galvarez.ttw.model.ScoreSystem;
import com.galvarez.ttw.model.ScoreSystem.Item;
import com.galvarez.ttw.rendering.components.Description;
import com.galvarez.ttw.rendering.ui.FramedMenu;
import com.galvarez.ttw.screens.overworld.OverworldScreen;
/**
* This screen appears when user tries to pause or escape from the main game
* screen.
*
* @author Guillaume Alvarez
*/
public final class ScoresMenuScreen extends AbstractPausedScreen<OverworldScreen> {
private final FramedMenu topMenu, ladderMenu;
private final ScoreSystem scoreSystem;
public ScoresMenuScreen(ThingsThatWereGame game, World world, SpriteBatch batch, OverworldScreen gameScreen,
ScoreSystem scoreSystem) {
super(game, world, batch, gameScreen);
this.scoreSystem = scoreSystem;
topMenu = new FramedMenu(skin, 800, 600);
ladderMenu = new FramedMenu(skin, 800, 600);
}
@Override
protected void initMenu() {
topMenu.clear();
topMenu.addButton("Resume game", this::resumeGame);
topMenu.addToStage(stage, 30, stage.getHeight() - 30, false);
ladderMenu.clear();
ladderMenu.nbColumns(3).addLabel(
"One point per influenced tile, \n\thalf the score from tributary, \n\ta quarter of the score from allies.");
ladderMenu.addLabel("
int rank = 1;
List<Object[]> ladder = new ArrayList<>();
ladder.add(new Object[] { "[BLACK]Rank", "[BLACK]Empire", "[BLACK]Score (progress)" });
for (Item i : scoreSystem.getScores())
ladder.add(new Object[] { "[BLACK]" + rank++, markup(i.empire) + i.empire.getComponent(Description.class).desc,
"[BLACK]" + shorten(i.score.totalScore) + " (+" + i.score.lastTurnPoints + ")" });
LabelStyle style = ladderMenu.getSkin().get("colored", LabelStyle.class);
style.font.setMarkupEnabled(true);
ladderMenu.addTable(style, ladder.toArray(new Object[0][]));
ladderMenu.addToStage(stage, 30, topMenu.getY() - 30, true);
}
private static final int KILO = 1000;
private static final int MEGA = 1000 * KILO;
private static final int GIGA = 1000 * MEGA;
private static String shorten(int score) {
if (score >= 2 * GIGA)
return score / GIGA + "G";
else if (score >= 2 * MEGA)
return score / MEGA + "M";
if (score >= 2 * KILO)
return score / KILO + "K";
return String.valueOf(score);
}
} |
package com.ray3k.skincomposer.dialog;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.BitmapFont.BitmapFontData;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.EventListener;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.Touchable;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.Dialog;
import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton;
import com.badlogic.gdx.scenes.scene2d.ui.ImageTextButton.ImageTextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.SelectBox;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.Sort;
import com.kotcrab.vis.ui.widget.file.FileChooserAdapter;
import com.kotcrab.vis.ui.widget.file.FileTypeFilter;
import com.ray3k.skincomposer.FilesDroppedListener;
import com.ray3k.skincomposer.IbeamListener;
import com.ray3k.skincomposer.Main;
import com.ray3k.skincomposer.data.AtlasData;
import com.ray3k.skincomposer.data.ColorData;
import com.ray3k.skincomposer.data.DrawableData;
import com.ray3k.skincomposer.data.FontData;
import com.ray3k.skincomposer.data.JsonData;
import com.ray3k.skincomposer.data.ProjectData;
import com.ray3k.skincomposer.data.StyleData;
import com.ray3k.skincomposer.data.StyleProperty;
import com.ray3k.skincomposer.panel.PanelClassBar;
import com.ray3k.skincomposer.panel.PanelMenuBar;
import com.ray3k.skincomposer.panel.PanelPreviewProperties;
import com.ray3k.skincomposer.panel.PanelStatusBar;
import com.ray3k.skincomposer.panel.PanelStyleProperties;
import com.ray3k.skincomposer.utils.SynchronousJFXFileChooser;
import com.ray3k.skincomposer.utils.Utils;
import java.io.File;
import java.util.Iterator;
import java.util.List;
import javafx.stage.FileChooser;
public class DialogFonts extends Dialog {
private Skin skin;
private StyleProperty styleProperty;
private Array<FontData> fonts;
private Array<DrawableData> drawables;
private Table fontsTable;
private SelectBox<String> selectBox;
private ObjectMap<FontData, BitmapFont> fontMap;
private TextureAtlas atlas;
private EventListener listener;
private FilesDroppedListener filesDroppedListener;
private ScrollPane scrollPane;
public DialogFonts(Skin skin, StyleProperty styleProperty, EventListener listener) {
this(skin, "default", styleProperty, listener);
}
public DialogFonts(final Skin skin, String styleName, StyleProperty styleProperty, EventListener listener) {
super("", skin, styleName);
Main.instance.setListeningForKeys(false);
this.listener = listener;
this.skin = skin;
this.styleProperty = styleProperty;
fonts = JsonData.getInstance().getFonts();
drawables = AtlasData.getInstance().getDrawables();
fontMap = new ObjectMap<>();
produceAtlas();
filesDroppedListener = (Array<FileHandle> files) -> {
Iterator<FileHandle> iter = files.iterator();
while (iter.hasNext()) {
FileHandle file = iter.next();
if (file.isDirectory() || !file.name().toLowerCase().endsWith(".fnt")) {
iter.remove();
}
}
if (files.size > 0) {
fontNameDialog(files, 0);
}
};
Main.instance.getDesktopWorker().addFilesDroppedListener(filesDroppedListener);
setFillParent(true);
if (styleProperty != null) {
getContentTable().add(new Label("Select a Font...", skin, "title"));
getContentTable().row();
} else {
getContentTable().add(new Label("Fonts", skin, "title"));
getContentTable().row();
}
Table table = new Table();
table.defaults().pad(2.0f);
table.add(new Label("Sort by: ", skin)).padLeft(20.0f);
selectBox = new SelectBox<>(skin);
selectBox.setItems(new String[]{"A-Z", "Z-A", "Oldest", "Newest"});
selectBox.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
sortBySelectedMode();
}
});
table.add(selectBox);
ImageTextButtonStyle imageButtonStyle = new ImageTextButtonStyle();
imageButtonStyle.imageUp = skin.getDrawable("image-plus");
imageButtonStyle.imageDown = skin.getDrawable("image-plus-down");
imageButtonStyle.up = skin.getDrawable("button-orange");
imageButtonStyle.down = skin.getDrawable("button-orange-down");
imageButtonStyle.over = skin.getDrawable("button-orange-over");
imageButtonStyle.font = skin.getFont("font");
imageButtonStyle.fontColor = skin.getColor("white");
imageButtonStyle.downFontColor = skin.getColor("maroon");
ImageTextButton imageButton = new ImageTextButton(" New Font", imageButtonStyle);
imageButton.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
newFontDialog();
}
});
table.add(imageButton).expandX();
getContentTable().add(table).expandX().left();
getContentTable().row();
key(Keys.ESCAPE, false);
if (styleProperty != null) {
button("Clear Font", true);
button("Cancel", false);
} else {
button("Close", false);
}
fontsTable = new Table();
table = new Table();
table.add(fontsTable).pad(5.0f);
scrollPane = new ScrollPane(table, skin, "no-bg");
scrollPane.setFadeScrollBars(false);
getContentTable().add(scrollPane).grow();
}
@Override
public Dialog show(Stage stage) {
Dialog dialog = super.show(stage);
stage.setScrollFocus(scrollPane);
return dialog;
}
private boolean addFont(String name, FileHandle file) {
if (FontData.validate(name)) {
try {
ProjectData.instance().setChangesSaved(false);
FontData font = new FontData(name, file);
//remove any existing FontData that shares the same name.
if (fonts.contains(font, false)) {
FontData deleteFont = fonts.get(fonts.indexOf(font, false));
BitmapFontData deleteFontData = new BitmapFontData(deleteFont.file, false);
for (String path : deleteFontData.imagePaths) {
FileHandle imagefile = new FileHandle(path);
drawables.removeValue(new DrawableData(imagefile), false);
}
fonts.removeValue(font, false);
}
BitmapFontData bitmapFontData = new BitmapFontData(file, false);
for (String path : bitmapFontData.imagePaths) {
DrawableData drawable = new DrawableData(new FileHandle(path));
drawable.visible = false;
if (!drawables.contains(drawable, false)) {
AtlasData.getInstance().atlasCurrent = false;
drawables.add(drawable);
}
}
produceAtlas();
fonts.add(font);
Array<TextureRegion> regions = new Array<>();
for (String path : bitmapFontData.imagePaths) {
FileHandle imageFile = new FileHandle(path);
regions.add(atlas.findRegion(imageFile.nameWithoutExtension()));
}
fontMap.put(font, new BitmapFont(bitmapFontData, regions, true));
sortBySelectedMode();
populate();
} catch (Exception e) {
Gdx.app.error(getClass().getName(), "Error creating font from file", e);
showAddFontErrorMessage();
}
return true;
} else {
return false;
}
}
public void populate() {
fontsTable.clear();
fontsTable.defaults().growX().pad(5.0f);
if (fonts.size == 0) {
fontsTable.add(new Label("No fonts have been set!", skin));
} else {
for (FontData font : fonts) {
Button button = new Button(skin);
Label label = new Label(font.getName(), skin, "white");
label.setTouchable(Touchable.disabled);
button.add(label).left();
Button renameButton = new Button(skin, "name");
renameButton.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
renameDialog(font);
event.setBubbles(false);
}
});
renameButton.addListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
event.setBubbles(false);
return true;
}
});
button.add(renameButton).padLeft(15.0f);
LabelStyle style = new LabelStyle();
style.font = fontMap.get(font);
style.fontColor = Color.WHITE;
label = new Label("Lorem Ipsum", style);
label.setAlignment(Align.center);
label.setTouchable(Touchable.disabled);
Table bg = new Table(skin);
bg.setBackground("white");
BitmapFontData bf = new BitmapFontData(font.file, false);
if (bf.imagePaths.length > 0) {
FileHandle file = new FileHandle(bf.imagePaths[0]);
if (!file.exists()) {
file = bf.fontFile.sibling(bf.fontFile.nameWithoutExtension() + ".png");
}
if (Utils.brightness(Utils.averageEdgeColor(file)) < .5f) {
bg.setColor(Color.WHITE);
} else {
bg.setColor(Color.BLACK);
}
}
bg.add(label).pad(5.0f).grow();
button.add(bg).padLeft(15).growX();
Button closeButton = new Button(skin, "close");
final FontData deleteFont = font;
closeButton.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
fonts.removeValue(deleteFont, true);
BitmapFontData bitmapFontData = new BitmapFontData(deleteFont.file, false);
for (String path : bitmapFontData.imagePaths) {
FileHandle imagefile = new FileHandle(path);
drawables.removeValue(new DrawableData(imagefile), false);
}
for (Array<StyleData> datas : JsonData.getInstance().getClassStyleMap().values()) {
for (StyleData data : datas) {
for (StyleProperty property : data.properties.values()) {
if (property != null && property.type.equals(BitmapFont.class) && property.value != null && property.value.equals(deleteFont.getName())) {
property.value = null;
}
}
}
}
Main.instance.clearUndoables();
PanelStyleProperties.instance.populate(PanelClassBar.instance.getStyleSelectBox().getSelected());
PanelPreviewProperties.instance.render();
event.setBubbles(false);
populate();
}
});
closeButton.addListener(new InputListener() {
@Override
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {
event.setBubbles(false);
return true;
}
});
button.add(closeButton).padLeft(5.0f).right();
if (styleProperty == null) {
button.setTouchable(Touchable.childrenOnly);
} else {
final FontData fontResult = font;
button.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
result(fontResult);
hide();
}
});
}
fontsTable.add(button);
fontsTable.row();
}
}
}
private void renameDialog(FontData font) {
TextField textField = new TextField("", skin);
TextButton okButton;
Dialog dialog = new Dialog("Rename Font?", skin) {
@Override
protected void result(Object object) {
if ((boolean) object) {
renameFont(font, textField.getText());
}
}
@Override
public Dialog show(Stage stage) {
Dialog dialog = super.show(stage);
Main.instance.getStage().setKeyboardFocus(textField);
return dialog;
}
};
Table bg = new Table(skin);
bg.setBackground("white");
bg.setColor(Color.WHITE);
dialog.getContentTable().add(bg);
Label label = new Label(font.getName(), skin, "white");
label.setColor(Color.BLACK);
bg.add(label).pad(10);
dialog.getContentTable().row();
label = new Label("What do you want to rename the font to?", skin);
dialog.getContentTable().add(label);
dialog.getContentTable().row();
textField.setText(font.getName());
textField.selectAll();
dialog.getContentTable().add(textField);
dialog.button("OK", true);
dialog.button("Cancel", false).key(Keys.ESCAPE, false);
okButton = (TextButton) dialog.getButtonTable().getCells().first().getActor();
okButton.setDisabled(true);
textField.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
boolean disable = !FontData.validate(textField.getText());
if (!disable) {
for (ColorData data : JsonData.getInstance().getColors()) {
if (data.getName().equals(textField.getText())) {
disable = true;
break;
}
}
}
okButton.setDisabled(disable);
}
});
textField.setTextFieldListener(new TextField.TextFieldListener() {
@Override
public void keyTyped(TextField textField, char c) {
if (c == '\n') {
if (!okButton.isDisabled()) {
renameFont(font, textField.getText());
dialog.hide();
}
}
}
});
dialog.show(getStage());
}
private void renameFont(FontData font, String newName) {
for (Array<StyleData> datas : JsonData.getInstance().getClassStyleMap().values()) {
for (StyleData data : datas) {
for (StyleProperty property : data.properties.values()) {
if (property != null && property.type.equals(BitmapFont.class) && property.value != null && property.value.equals(font.getName())) {
property.value = newName;
}
}
}
}
try {
font.setName(newName);
} catch (FontData.NameFormatException ex) {
Gdx.app.error(getClass().getName(), "Error trying to rename a font.", ex);
}
Main.instance.clearUndoables();
PanelStyleProperties.instance.populate(PanelClassBar.instance.getStyleSelectBox().getSelected());
PanelPreviewProperties.instance.render();
ProjectData.instance().setChangesSaved(false);
populate();
}
@Override
protected void result(Object object) {
if (styleProperty != null) {
if (object instanceof FontData) {
ProjectData.instance().setChangesSaved(false);
FontData font = (FontData) object;
PanelStatusBar.instance.message("Selected Font: " + font.getName() + " for \"" + styleProperty.name + "\"");
styleProperty.value = font.getName();
PanelStyleProperties.instance.populate(PanelClassBar.instance.getStyleSelectBox().getSelected());
} else if (object instanceof Boolean) {
if ((boolean) object) {
styleProperty.value = null;
ProjectData.instance().setChangesSaved(false);
PanelStatusBar.instance.message("Drawable emptied for \"" + styleProperty.name + "\"");
PanelStyleProperties.instance.populate(PanelClassBar.instance.getStyleSelectBox().getSelected());
} else {
boolean hasFont = false;
for (FontData font : JsonData.getInstance().getFonts()) {
if (font.getName().equals(styleProperty.value)) {
hasFont = true;
break;
}
}
if (!hasFont) {
styleProperty.value = null;
ProjectData.instance().setChangesSaved(false);
PanelStatusBar.instance.message("Drawable deleted for \"" + styleProperty.name + "\"");
PanelStyleProperties.instance.populate(PanelClassBar.instance.getStyleSelectBox().getSelected());
}
}
}
}
if (listener != null) {
listener.handle(null);
}
}
private void sortBySelectedMode() {
switch (selectBox.getSelectedIndex()) {
case 0:
sortFontsAZ();
break;
case 1:
sortFontsZA();
break;
case 2:
sortFontsOldest();
break;
case 3:
sortFontsNewest();
break;
}
}
private void sortFontsAZ() {
Sort.instance().sort(fonts, (FontData o1, FontData o2) -> o1.toString().compareToIgnoreCase(o2.toString()));
populate();
}
private void sortFontsZA() {
Sort.instance().sort(fonts, (FontData o1, FontData o2) -> o1.toString().compareToIgnoreCase(o2.toString()) * -1);
populate();
}
private void sortFontsOldest() {
Sort.instance().sort(fonts, (FontData o1, FontData o2) -> {
if (o1.file.lastModified() < o2.file.lastModified()) {
return -1;
} else if (o1.file.lastModified() > o2.file.lastModified()) {
return 1;
} else {
return 0;
}
});
populate();
}
private void sortFontsNewest() {
Sort.instance().sort(fonts, (FontData o1, FontData o2) -> {
if (o1.file.lastModified() < o2.file.lastModified()) {
return 1;
} else if (o1.file.lastModified() > o2.file.lastModified()) {
return -1;
} else {
return 0;
}
});
populate();
}
@Override
public boolean remove() {
Main.instance.setListeningForKeys(true);
Main.instance.getDesktopWorker().removeFilesDroppedListener(filesDroppedListener);
produceAtlas();
for (BitmapFont font : fontMap.values()) {
font.dispose();
}
fontMap.clear();
return super.remove();
}
private boolean produceAtlas() {
try {
if (atlas != null) {
atlas.dispose();
atlas = null;
}
if (!AtlasData.getInstance().atlasCurrent) {
AtlasData.getInstance().writeAtlas();
AtlasData.getInstance().atlasCurrent = true;
}
atlas = AtlasData.getInstance().getAtlas();
for (FontData font : fonts) {
BitmapFontData fontData = new BitmapFontData(font.file, false);
Array<TextureRegion> regions = new Array<>();
for (String path : fontData.imagePaths) {
FileHandle file = new FileHandle(path);
if (!file.exists()) {
file = fontData.fontFile.sibling(fontData.fontFile.nameWithoutExtension() + ".png");
}
TextureRegion region = atlas.findRegion(file.nameWithoutExtension());
if (region != null) {
regions.add(region);
}
}
fontMap.put(font, new BitmapFont(fontData, regions, true));
}
return true;
} catch (Exception e) {
Gdx.app.error(getClass().getName(), "Error while attempting to generate drawables.", e);
return false;
}
}
private void newFontDialog() {
if (Utils.isWindows()) {
newFontDialogWindows();
} else {
newFontDialogVisUI();
}
}
private void newFontDialogWindows() {
SynchronousJFXFileChooser chooser = new SynchronousJFXFileChooser(() -> {
FileChooser ch = new FileChooser();
FileChooser.ExtensionFilter ex = new FileChooser.ExtensionFilter("Font files (*.fnt)", "*.fnt");
ch.getExtensionFilters().add(ex);
ch.setTitle("Choose font file(s)...");
if (ProjectData.instance().getLastDirectory() != null) {
File file = new File(ProjectData.instance().getLastDirectory());
if (file.exists()) {
ch.setInitialDirectory(file);
}
}
return ch;
});
List<File> files = chooser.showOpenMultipleDialog();
if (files != null && files.size() > 0) {
ProjectData.instance().setLastDirectory(files.get(0).getParentFile().getPath());
fontNameDialog(files, 0);
}
}
private void newFontDialogVisUI() {
com.kotcrab.vis.ui.widget.file.FileChooser fileChooser = PanelMenuBar.instance().getFileChooser();
fileChooser.setMode(com.kotcrab.vis.ui.widget.file.FileChooser.Mode.OPEN);
fileChooser.setMultiSelectionEnabled(true);
FileHandle defaultFile = new FileHandle(ProjectData.instance().getLastDirectory());
if (defaultFile.exists()) {
if (defaultFile.isDirectory()) {
fileChooser.setDirectory(defaultFile);
} else {
fileChooser.setDirectory(defaultFile.parent());
}
}
FileTypeFilter typeFilter = new FileTypeFilter(false);
typeFilter.addRule("Font files (*.fnt)", "fnt");
typeFilter.setAllTypesAllowed(false);
fileChooser.setFileTypeFilter(typeFilter);
fileChooser.setViewMode(com.kotcrab.vis.ui.widget.file.FileChooser.ViewMode.DETAILS);
fileChooser.setViewModeButtonVisible(true);
fileChooser.setWatchingFilesEnabled(true);
fileChooser.getTitleLabel().setText("Choose font file(s)...");
fileChooser.setListener(new FileChooserAdapter() {
@Override
public void selected(Array<FileHandle> files) {
if (files.size > 0) {
ProjectData.instance().setLastDirectory(files.get(0).parent().path());
fontNameDialog(files, 0);
}
}
});
getStage().addActor(fileChooser.fadeIn());
}
private void fontNameDialog(List<File> files, int index) {
Array<FileHandle> handles = new Array<>();
for (File file : files) {
handles.add(new FileHandle(file));
}
fontNameDialog(handles, index);
}
private void fontNameDialog(Array<FileHandle> files, int index) {
if (index < files.size) {
try {
final FileHandle fileHandle = files.get(index);
final TextField textField = new TextField(FontData.filter(fileHandle.nameWithoutExtension()), skin);
final Dialog nameDialog = new Dialog("Enter a name...", skin, "dialog") {
@Override
protected void result(Object object) {
if ((Boolean) object) {
String name = textField.getText();
addFont(name, fileHandle);
}
}
@Override
public boolean remove() {
fontNameDialog(files, index + 1);
return super.remove();
}
};
nameDialog.button("OK", true);
nameDialog.button("Cancel", false);
final TextButton button = (TextButton) nameDialog.getButtonTable().getCells().first().getActor();
textField.setTextFieldListener((TextField textField1, char c) -> {
if (c == '\n') {
if (!button.isDisabled()) {
String name1 = textField1.getText();
if (addFont(name1, fileHandle)) {
nameDialog.hide();
}
}
Main.instance.getStage().setKeyboardFocus(textField1);
}
});
textField.addListener(IbeamListener.get());
nameDialog.getContentTable().defaults().padLeft(10.0f).padRight(10.0f);
nameDialog.text("Please enter a name for the new font: ");
nameDialog.getContentTable().row();
nameDialog.getContentTable().add(textField).growX();
nameDialog.getContentTable().row();
nameDialog.text("Preview:");
nameDialog.getContentTable().row();
LabelStyle previewStyle = new LabelStyle();
previewStyle.font = new BitmapFont(fileHandle);
Table table = new Table(skin);
table.setBackground("white");
BitmapFontData bitmapFontData = new BitmapFontData(fileHandle, false);
if (Utils.brightness(Utils.averageEdgeColor(new FileHandle(bitmapFontData.imagePaths[0]))) > .5f) {
table.setColor(Color.BLACK);
} else {
table.setColor(Color.WHITE);
}
table.add(new Label("Lorem Ipsum", previewStyle)).pad(5.0f);
nameDialog.getContentTable().add(table);
nameDialog.key(Keys.ESCAPE, false);
button.setDisabled(!FontData.validate(textField.getText()));
textField.addListener(new ChangeListener() {
@Override
public void changed(ChangeListener.ChangeEvent event, Actor actor) {
boolean disable = !FontData.validate(textField.getText());
if (!disable) {
for (FontData data : JsonData.getInstance().getFonts()) {
if (data.getName().equals(textField.getText())) {
disable = true;
break;
}
}
}
button.setDisabled(disable);
}
});
nameDialog.setColor(1.0f, 1.0f, 1.0f, 0.0f);
if (!Utils.doesImageFitBox(new FileHandle(bitmapFontData.imagePaths[0]), ProjectData.instance().getMaxTextureWidth(), ProjectData.instance().getMaxTextureHeight())) {
showAddFontSizeError(fileHandle.nameWithoutExtension());
} else {
nameDialog.show(getStage());
getStage().setKeyboardFocus(textField);
textField.selectAll();
}
} catch (Exception e) {
Gdx.app.error(getClass().getName(), "Error creating preview font from file", e);
showAddFontErrorMessage();
}
}
}
private void showAddFontErrorMessage() {
Dialog dialog = new Dialog("Error adding font...", skin, "dialog");
dialog.text("Unable to add font. Check file paths.");
dialog.button("Ok");
dialog.show(getStage());
}
private void showAddFontSizeError(String name) {
Dialog dialog = new Dialog("Error adding font...", skin, "dialog");
dialog.text("Unable to add font \"" + name +
"\". Ensure image dimensions\nare less than max texture dimensions (" +
ProjectData.instance().getMaxTextureWidth() + "x" +
ProjectData.instance().getMaxTextureHeight() + ").\nSee project settings.");
dialog.button("Ok");
dialog.show(getStage());
}
} |
package bisq.core.api;
import bisq.core.monetary.Altcoin;
import bisq.core.monetary.Price;
import bisq.core.offer.CreateOfferService;
import bisq.core.offer.Offer;
import bisq.core.offer.OfferBookService;
import bisq.core.offer.OpenOfferManager;
import bisq.core.payment.PaymentAccount;
import bisq.core.trade.handlers.TransactionResultHandler;
import bisq.core.user.User;
import org.bitcoinj.core.Coin;
import org.bitcoinj.utils.Fiat;
import javax.inject.Inject;
import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import static bisq.common.util.MathUtils.exactMultiply;
import static bisq.common.util.MathUtils.roundDoubleToLong;
import static bisq.common.util.MathUtils.scaleUpByPowerOf10;
import static bisq.core.locale.CurrencyUtil.isCryptoCurrency;
import static bisq.core.offer.OfferPayload.Direction;
import static bisq.core.offer.OfferPayload.Direction.BUY;
@Slf4j
class CoreOffersService {
private final CreateOfferService createOfferService;
private final OfferBookService offerBookService;
private final OpenOfferManager openOfferManager;
private final User user;
@Inject
public CoreOffersService(CreateOfferService createOfferService,
OfferBookService offerBookService,
OpenOfferManager openOfferManager,
User user) {
this.createOfferService = createOfferService;
this.offerBookService = offerBookService;
this.openOfferManager = openOfferManager;
this.user = user;
}
List<Offer> getOffers(String direction, String currencyCode) {
List<Offer> offers = offerBookService.getOffers().stream()
.filter(o -> {
var offerOfWantedDirection = o.getDirection().name().equalsIgnoreCase(direction);
var offerInWantedCurrency = o.getOfferPayload().getCounterCurrencyCode()
.equalsIgnoreCase(currencyCode);
return offerOfWantedDirection && offerInWantedCurrency;
})
.collect(Collectors.toList());
// A buyer probably wants to see sell orders in price ascending order.
// A seller probably wants to see buy orders in price descending order.
if (direction.equalsIgnoreCase(BUY.name()))
offers.sort(Comparator.comparing(Offer::getPrice).reversed());
else
offers.sort(Comparator.comparing(Offer::getPrice));
return offers;
}
// Create offer with a random offer id.
Offer createOffer(String currencyCode,
String directionAsString,
String priceAsString,
boolean useMarketBasedPrice,
double marketPriceMargin,
long amountAsLong,
long minAmountAsLong,
double buyerSecurityDeposit,
String paymentAccountId,
TransactionResultHandler resultHandler) {
String upperCaseCurrencyCode = currencyCode.toUpperCase();
String offerId = createOfferService.getRandomOfferId();
Direction direction = Direction.valueOf(directionAsString.toUpperCase());
Price price = Price.valueOf(upperCaseCurrencyCode, priceStringToLong(priceAsString, upperCaseCurrencyCode));
Coin amount = Coin.valueOf(amountAsLong);
Coin minAmount = Coin.valueOf(minAmountAsLong);
PaymentAccount paymentAccount = user.getPaymentAccount(paymentAccountId);
// We don't support atm funding from external wallet to keep it simple
boolean useSavingsWallet = true;
//noinspection ConstantConditions
return createAndPlaceOffer(offerId,
upperCaseCurrencyCode,
direction,
price,
useMarketBasedPrice,
marketPriceMargin,
amount,
minAmount,
buyerSecurityDeposit,
paymentAccount,
useSavingsWallet,
resultHandler);
}
// Create offer for given offer id.
Offer createOffer(String offerId,
String currencyCode,
Direction direction,
Price price,
boolean useMarketBasedPrice,
double marketPriceMargin,
Coin amount,
Coin minAmount,
double buyerSecurityDeposit,
PaymentAccount paymentAccount,
boolean useSavingsWallet,
TransactionResultHandler resultHandler) {
Coin useDefaultTxFee = Coin.ZERO;
Offer offer = createOfferService.createAndGetOffer(offerId,
direction,
currencyCode.toUpperCase(),
amount,
minAmount,
price,
useDefaultTxFee,
useMarketBasedPrice,
exactMultiply(marketPriceMargin, 0.01),
buyerSecurityDeposit,
paymentAccount);
openOfferManager.placeOffer(offer,
buyerSecurityDeposit,
useSavingsWallet,
resultHandler,
log::error);
return offer;
}
private Offer createAndPlaceOffer(String offerId,
String currencyCode,
Direction direction,
Price price,
boolean useMarketBasedPrice,
double marketPriceMargin,
Coin amount,
Coin minAmount,
double buyerSecurityDeposit,
PaymentAccount paymentAccount,
boolean useSavingsWallet,
TransactionResultHandler resultHandler) {
Coin useDefaultTxFee = Coin.ZERO;
Offer offer = createOfferService.createAndGetOffer(offerId,
direction,
currencyCode,
amount,
minAmount,
price,
useDefaultTxFee,
useMarketBasedPrice,
exactMultiply(marketPriceMargin, 0.01),
buyerSecurityDeposit,
paymentAccount);
// TODO give user chance to examine offer before placing it (placeoffer)
openOfferManager.placeOffer(offer,
buyerSecurityDeposit,
useSavingsWallet,
resultHandler,
log::error);
return offer;
}
private long priceStringToLong(String priceAsString, String currencyCode) {
int precision = isCryptoCurrency(currencyCode) ? Altcoin.SMALLEST_UNIT_EXPONENT : Fiat.SMALLEST_UNIT_EXPONENT;
double priceAsDouble = new BigDecimal(priceAsString).doubleValue();
double scaled = scaleUpByPowerOf10(priceAsDouble, precision);
return roundDoubleToLong(scaled);
}
} |
package io.grpc.internal;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static io.grpc.internal.GrpcUtil.ACCEPT_ENCODING_SPLITER;
import static io.grpc.internal.GrpcUtil.MESSAGE_ACCEPT_ENCODING_KEY;
import static io.grpc.internal.GrpcUtil.MESSAGE_ENCODING_KEY;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import io.grpc.Attributes;
import io.grpc.Codec;
import io.grpc.Compressor;
import io.grpc.CompressorRegistry;
import io.grpc.Context;
import io.grpc.Decompressor;
import io.grpc.DecompressorRegistry;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.MethodDescriptor.MethodType;
import io.grpc.ServerCall;
import io.grpc.Status;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
final class ServerCallImpl<ReqT, RespT> extends ServerCall<ReqT, RespT> {
private final ServerStream stream;
private final MethodDescriptor<ReqT, RespT> method;
private final Context.CancellableContext context;
private final String messageAcceptEncoding;
private final DecompressorRegistry decompressorRegistry;
private final CompressorRegistry compressorRegistry;
// state
private volatile boolean cancelled;
private boolean sendHeadersCalled;
private boolean closeCalled;
private Compressor compressor;
ServerCallImpl(ServerStream stream, MethodDescriptor<ReqT, RespT> method,
Metadata inboundHeaders, Context.CancellableContext context,
DecompressorRegistry decompressorRegistry, CompressorRegistry compressorRegistry) {
this.stream = stream;
this.method = method;
this.context = context;
this.messageAcceptEncoding = inboundHeaders.get(MESSAGE_ACCEPT_ENCODING_KEY);
this.decompressorRegistry = decompressorRegistry;
this.compressorRegistry = compressorRegistry;
if (inboundHeaders.containsKey(MESSAGE_ENCODING_KEY)) {
String encoding = inboundHeaders.get(MESSAGE_ENCODING_KEY);
Decompressor decompressor = decompressorRegistry.lookupDecompressor(encoding);
if (decompressor == null) {
throw Status.UNIMPLEMENTED
.withDescription(String.format("Can't find decompressor for %s", encoding))
.asRuntimeException();
}
stream.setDecompressor(decompressor);
}
}
@Override
public void request(int numMessages) {
stream.request(numMessages);
}
@Override
public void sendHeaders(Metadata headers) {
checkState(!sendHeadersCalled, "sendHeaders has already been called");
checkState(!closeCalled, "call is closed");
headers.removeAll(MESSAGE_ENCODING_KEY);
if (compressor == null) {
compressor = Codec.Identity.NONE;
} else {
if (messageAcceptEncoding != null) {
List<String> acceptedEncodingsList =
ACCEPT_ENCODING_SPLITER.splitToList(messageAcceptEncoding);
if (!acceptedEncodingsList.contains(compressor.getMessageEncoding())) {
// resort to using no compression.
compressor = Codec.Identity.NONE;
}
} else {
compressor = Codec.Identity.NONE;
}
}
// Always put compressor, even if it's identity.
headers.put(MESSAGE_ENCODING_KEY, compressor.getMessageEncoding());
stream.setCompressor(compressor);
headers.removeAll(MESSAGE_ACCEPT_ENCODING_KEY);
String advertisedEncodings = decompressorRegistry.getRawAdvertisedMessageEncodings();
if (!advertisedEncodings.isEmpty()) {
headers.put(MESSAGE_ACCEPT_ENCODING_KEY, advertisedEncodings);
}
// Don't check if sendMessage has been called, since it requires that sendHeaders was already
// called.
sendHeadersCalled = true;
stream.writeHeaders(headers);
}
@Override
public void sendMessage(RespT message) {
checkState(sendHeadersCalled, "sendHeaders has not been called");
checkState(!closeCalled, "call is closed");
try {
InputStream resp = method.streamResponse(message);
stream.writeMessage(resp);
stream.flush();
} catch (RuntimeException e) {
close(Status.fromThrowable(e), new Metadata());
throw e;
} catch (Throwable t) {
close(Status.fromThrowable(t), new Metadata());
throw new RuntimeException(t);
}
}
@Override
public void setMessageCompression(boolean enable) {
stream.setMessageCompression(enable);
}
@Override
public void setCompression(String compressorName) {
// Added here to give a better error message.
checkState(!sendHeadersCalled, "sendHeaders has been called");
compressor = compressorRegistry.lookupCompressor(compressorName);
checkArgument(compressor != null, "Unable to find compressor by name %s", compressorName);
}
@Override
public boolean isReady() {
return stream.isReady();
}
@Override
public void close(Status status, Metadata trailers) {
checkState(!closeCalled, "call already closed");
closeCalled = true;
stream.close(status, trailers);
}
@Override
public boolean isCancelled() {
return cancelled;
}
ServerStreamListener newServerStreamListener(ServerCall.Listener<ReqT> listener) {
return new ServerStreamListenerImpl<ReqT>(this, listener, context);
}
@Override
public Attributes attributes() {
return stream.attributes();
}
@Override
public MethodDescriptor<ReqT, RespT> getMethodDescriptor() {
return method;
}
/**
* All of these callbacks are assumed to called on an application thread, and the caller is
* responsible for handling thrown exceptions.
*/
@VisibleForTesting
static final class ServerStreamListenerImpl<ReqT> implements ServerStreamListener {
private final ServerCallImpl<ReqT, ?> call;
private final ServerCall.Listener<ReqT> listener;
private final Context.CancellableContext context;
private boolean messageReceived;
public ServerStreamListenerImpl(
ServerCallImpl<ReqT, ?> call, ServerCall.Listener<ReqT> listener,
Context.CancellableContext context) {
this.call = checkNotNull(call, "call");
this.listener = checkNotNull(listener, "listener must not be null");
this.context = checkNotNull(context, "context");
}
@Override
public void messageRead(final InputStream message) {
Throwable t = null;
try {
if (call.cancelled) {
return;
}
// Special case for unary calls.
if (messageReceived && call.method.getType() == MethodType.UNARY) {
call.stream.close(Status.INTERNAL.withDescription(
"More than one request messages for unary call or server streaming call"),
new Metadata());
return;
}
messageReceived = true;
listener.onMessage(call.method.parseRequest(message));
} catch (Throwable e) {
t = e;
} finally {
try {
message.close();
} catch (IOException e) {
if (t != null) {
// TODO(carl-mastrangelo): Maybe log e here.
Throwables.propagateIfPossible(t);
throw new RuntimeException(t);
}
throw new RuntimeException(e);
}
}
}
@Override
public void halfClosed() {
if (call.cancelled) {
return;
}
listener.onHalfClose();
}
@Override
public void closed(Status status) {
try {
if (status.isOk()) {
listener.onComplete();
} else {
call.cancelled = true;
listener.onCancel();
}
} finally {
// Cancel context after delivering RPC closure notification to allow the application to
// clean up and update any state based on whether onComplete or onCancel was called.
context.cancel(null);
}
}
@Override
public void onReady() {
if (call.cancelled) {
return;
}
listener.onReady();
}
}
} |
package net.time4j.tz;
import net.time4j.base.GregorianDate;
import net.time4j.base.UnixTime;
import net.time4j.base.WallTime;
import java.util.List;
/**
* <p>Keeps all offset transitions and rules of a timezone. </p>
*
* <p>Note: This interface can be considered as stable since version v2.2.
* Preliminary experimental versions of this interface existed since v1.0
* but there was originally not any useable implementation. </p>
*
* @author Meno Hochschild
* @spec All implementations must be immutable, thread-safe and serializable.
*/
/*[deutsch]
* <p>Hält alle Übergänge und Regeln einer Zeitzone. </p>
*
* <p>Hinweis: Dieses Interface kann als stabil seit Version 2.2 gelten.
* Davor existierten experimentelle Versionen des Interface schon seit v1.0,
* aber es gab ursprünglich keine nutzbare Implementierung. </p>
*
* @author Meno Hochschild
* @spec All implementations must be immutable, thread-safe and serializable.
*/
public interface TransitionHistory {
/**
* <p>Return the initial offset no matter if there are any
* transitions defined or not. </p>
*
* <p>If any transition is defined then the initial offset
* is identical to the shift {@code getPreviousOffset()} of
* the first defined transition in history. </p>
*
* @return fixed initial shift
*/
/*[deutsch]
* <p>Ermittelt die initiale Verschiebung unabhängig davon, ob es
* Übergänge gibt oder nicht. </p>
*
* <p>Falls es Übergänge gibt, muß die initiale
* Verschiebung mit der Verschiebung {@code getPreviousOffset()}
* des ersten definierten Übergangs identisch sein. </p>
*
* @return fixed initial shift
*/
ZonalOffset getInitialOffset();
/**
* <p>Queries the last transition which defines the offset
* for given global timestamp. </p>
*
* @param ut unix reference time
* @return {@code ZonalTransition} or {@code null} if given reference time
* is before first defined transition
*/
/*[deutsch]
* <p>Ermittelt den letzten Übergang, der die zur angegebenen
* Referenzzeit zugehörige Verschiebung definiert. </p>
*
* @param ut unix reference time
* @return {@code ZonalTransition} or {@code null} if given reference time
* is before first defined transition
*/
ZonalTransition getStartTransition(UnixTime ut);
/**
* <p>Queries the next transition after given global timestamp. </p>
*
* @param ut unix reference time
* @return {@code ZonalTransition} or {@code null} if given reference time
* is after any defined transition
*/
/*[deutsch]
* <p>Ermittelt den nächsten Übergang nach der angegebenen
* Referenzzeit. </p>
*
* @param ut unix reference time
* @return {@code ZonalTransition} or {@code null} if given reference time
* is after any defined transition
*/
ZonalTransition getNextTransition(UnixTime ut);
/**
* <p>Returns the conflict transition where given local timestamp
* falls either in a gap or in an overlap on the local timeline. </p>
*
* <p>Note that only the expression {@code localDate.getYear()} is used
* to determine the daylight saving rules to be applied in calculation.
* This is particularly important if there is a wall time of 24:00. Here
* only the date before merging to next day matters, not the date of the
* whole timestamp. </p>
*
* @param localDate local date in timezone
* @param localTime local wall time in timezone
* @return conflict transition on the local time axis for gaps or
* overlaps else {@code null}
* @see #getValidOffsets(GregorianDate,WallTime)
*/
/*[deutsch]
* <p>Bestimmt den passenden Übergang, wenn die angegebene lokale
* Zeit in eine Lücke oder eine Überlappung auf dem lokalen
* Zeitstrahl fällt. </p>
*
* <p>Zu beachten: Nur der Ausdruck {@code localDate.getYear()} wird
* in der Ermittlung der passenden DST-Regeln benutzt. Das ist insbesondere
* von Bedeutung, wenn die Uhrzeit 24:00 vorliegt. Hier zählt nur
* das Jahr des angegebenen Datums, nicht das des Zeitstempels, der
* wegen der Uhrzeit evtl. im Folgejahr liegt. </p>
*
* @param localDate local date in timezone
* @param localTime local wall time in timezone
* @return conflict transition on the local time axis for gaps or
* overlaps else {@code null}
* @see #getValidOffsets(GregorianDate,WallTime)
*/
ZonalTransition getConflictTransition(
GregorianDate localDate,
WallTime localTime
);
/**
* <p>Determines the suitable offsets at given local timestamp.. </p>
*
* <p>The offset list is empty if the local timestamp falls in a gap
* on the local timeline. The list has exactly two offsets if the
* local timestamp belongs to two different timepoints on the
* POSIX timescale due to an overlap. Otherwise the offset list
* will contain exactly one suitable offset. </p>
*
* <p>Note that only the expression {@code localDate.getYear()} is used
* to determine the daylight saving rules to be applied in calculation.
* This is particularly important if there is a wall time of 24:00. Here
* only the date before merging to next day matters, not the date of the
* whole timestamp. </p>
*
* @param localDate local date in timezone
* @param localTime local wall time in timezone
* @return unmodifiable list of shifts which fits the given local time
* @see #getConflictTransition(GregorianDate,WallTime)
*/
/*[deutsch]
* <p>Bestimmt die zur angegebenen lokalen Zeit passenden
* zonalen Verschiebungen. </p>
*
* <p>Die Liste ist leer, wenn die lokale Zeit in eine Lücke auf
* dem lokalen Zeitstrahl fällt. Die Liste hat genau zwei
* Verschiebungen, wenn die lokale Zeit wegen einer Überlappung
* zu zwei verschiedenen Zeitpunkten auf der POSIX-Zeitskala gehört.
* Ansonsten wird die Liste genau eine passende Verschiebung enthalten. </p>
*
* <p>Zu beachten: Nur der Ausdruck {@code localDate.getYear()} wird
* in der Ermittlung der passenden DST-Regeln benutzt. Das ist insbesondere
* von Bedeutung, wenn die Uhrzeit 24:00 vorliegt. Hier zählt nur
* das Jahr des angegebenen Datums, nicht das des Zeitstempels, der
* wegen der Uhrzeit evtl. im Folgejahr liegt. </p>
*
* @param localDate local date in timezone
* @param localTime local wall time in timezone
* @return unmodifiable list of shifts which fits the given local time
* @see #getConflictTransition(GregorianDate,WallTime)
*/
List<ZonalOffset> getValidOffsets(
GregorianDate localDate,
WallTime localTime
);
/**
* <p>Return the offset transitions from UNIX epoch [1970-01-01T00:00Z]
* until about one year after the current timestamp. </p>
*
* <p>Indeed, a potentially bigger interval is obtainable by
* {@link #getTransitions(UnixTime,UnixTime)}, but earlier or
* later timepoints are usually not reliable. For example the
* wide-spread IANA/Olson-repository is only designed for times
* since UNIX epoch and offers some selected older data to the
* best of our knowledge. Users must be aware that even older
* data can be changed as side effect of data corrections. Generally
* the timezone concept was invented in 19th century. And future
* transitions are even less reliable due to political arbitrariness. </p>
*
* @return unmodifiable list of standard transitions (after 1970-01-01)
* maybe empty
*/
/*[deutsch]
* <p>Bestimmt alle vorhandenen zonalen Übergänge ab der
* UNIX-Epoche [1970-01-01T00:00Z] bis zirka ein Jahr nach dem aktuellen
* heutigen Zeitpunkt. </p>
*
* <p>Zwar kann mittels {@link #getTransitions(UnixTime,UnixTime)}
* auch ein potentiell größeres Intervall abgefragt werden,
* jedoch sind frühere oder spätere Zeitpunkte in aller Regel
* mit großen Unsicherheiten verknüpft. Zum Beispiel ist die
* weithin verwendete IANA/Olson-Zeitzonendatenbank nur für Zeiten
* ab der UNIX-Epoche gedacht und bietet ausgewählte ältere
* Zeitzonendaten lediglich nach bestem Wissen und Gewissen an. Anwender
* müssen beachten, daß sich sogar historische alte Daten
* nachträglich ändern können. Generell existiert das
* Zeitzonenkonzept erst ab ca. dem 19. Jahrhundert. Und in der Zukunft
* liegende Zeitzonenänderungen sind wegen politischer Willkür
* sogar noch unsicherer. </p>
*
* @return unmodifiable list of standard transitions (after 1970-01-01)
* maybe empty
*/
List<ZonalTransition> getStdTransitions();
List<ZonalTransition> getTransitions(
UnixTime startInclusive,
UnixTime endExclusive
);
/**
* <p>Determines if this history does not have any transitions. </p>
*
* @return {@code true} if there are no transitions else {@code false}
*/
/*[deutsch]
* <p>Ermittelt ob diese Historie keine Übergänge kennt. </p>
*
* @return {@code true} if there are no transitions else {@code false}
*/
boolean isEmpty();
} |
package org.soluvas.scrape.core;
import com.github.rholder.retry.*;
import org.apache.camel.Body;
import org.apache.camel.Handler;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpStatus;
import org.apache.http.client.cache.HttpCacheContext;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.soluvas.json.JsonUtils;
import org.soluvas.json.LowerEnumSerializer;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import java.io.IOException;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@Service
@Profile("scraper")
public class Fetcher {
private static final Logger log = LoggerFactory.getLogger(Fetcher.class);
@Inject
private CloseableHttpClient httpClient;
@Handler
public FetchData fetch(ScrapeTemplate template,
Map<String, Object> actualParams) {
LowerEnumSerializer.LOWER = false;
final String uri = template.getUri();
log.info("Fetching {} {} {} ...", template.getProtocol(), template.getProtocolVersion(),
template.getUri());
try {
// FIXME: Use Retryer (with limit) when: Caused by: java.net.SocketException: Connection reset
// at java.net.SocketInputStream.read(SocketInputStream.java:209)
switch (template.getProtocol()) {
case JSONRPC:
return fetchJsonRpc(uri, template, actualParams);
case HTTP:
throw new UnsupportedOperationException("no HTTP support yet");
default:
throw new UnsupportedOperationException("Unsupported protocol: " + template.getProtocol());
}
} catch (Exception e) {
throw new ScrapeException(e, "Cannot fetch %s", uri);
}
}
protected FetchData fetchJsonRpc(String uri, ScrapeTemplate template, Map<String, Object> actualParams) throws IOException, ExecutionException, RetryException {
final FetchData fetchData = new FetchData();
fetchData.setUri(uri);
fetchData.setProtocol(template.getProtocol());
fetchData.setProtocolVersion(template.getProtocolVersion());
fetchData.getRequestParams().putAll(actualParams);
final HttpCacheContext context = HttpCacheContext.create();
final HttpPost postReq = new HttpPost(uri);
final JsonRpc2MethodCall methodCall = new JsonRpc2MethodCall();
methodCall.setMethod(template.getRpcMethod());
methodCall.getParams().putAll(actualParams);
postReq.setEntity(
new StringEntity(JsonUtils.mapper.writeValueAsString(methodCall), ContentType.APPLICATION_JSON)
);
final Retryer<JsonRpc2MethodResult> retryer = RetryerBuilder.<JsonRpc2MethodResult>newBuilder()
.retryIfExceptionOfType(HttpStatusNotOkException.class)
.retryIfExceptionOfType(SocketException.class)
.withStopStrategy(StopStrategies.stopAfterAttempt(10))
.withWaitStrategy(WaitStrategies.fixedWait(30, TimeUnit.SECONDS))
.build();
fetchData.setJsonRpcResult(retryer.call(() -> {
log.info("Trying fetch {} {} {} {} {} ...",
template.getProtocol(), template.getProtocolVersion(), uri, template.getRpcMethod(), actualParams);
try (CloseableHttpResponse resp = httpClient.execute(postReq, context)) {
log.info("Received {} {} {} bytes {}", context.getCacheResponseStatus(),
resp.getEntity().getContentType(), resp.getEntity().getContentLength(),
resp.getFirstHeader("Content-Encoding"));
final String entityBody = IOUtils.toString(resp.getEntity().getContent(), StandardCharsets.UTF_8);
if (resp.getStatusLine().getStatusCode() < 200 || resp.getStatusLine().getStatusCode() >= 300) {
log.warn("{} {} {} {} {} HTTP Error {} {}: {}",
template.getProtocol(), template.getProtocolVersion(), uri, template.getRpcMethod(), actualParams,
resp.getStatusLine().getStatusCode(),
resp.getStatusLine().getReasonPhrase(), entityBody);
throw new HttpStatusNotOkException(String.format("%s %s %s %s %s HTTP Error %s %s: %s",
template.getProtocol(), template.getProtocolVersion(), uri, template.getRpcMethod(), actualParams,
resp.getStatusLine().getStatusCode(),
resp.getStatusLine().getReasonPhrase(), entityBody));
}
try {
final JsonRpc2MethodResult methodResult = JsonUtils.mapper.readValue(entityBody, JsonRpc2MethodResult.class);
log.trace("JSON-RPC Method result: {}", methodResult);
if (methodResult.getError() != null) {
throw new ScrapeException(methodResult.getError(), "Error fetching %s: %s", uri, methodResult.getError());
}
return methodResult;
} catch (Exception e) {
log.error(String.format("Error converting %s %s %s %s %s to JSON: %s",
template.getProtocol(), template.getProtocolVersion(), uri, template.getRpcMethod(), actualParams,
entityBody), e);
throw new ScrapeException(e, "Error converting %s %s %s %s %s to JSON (see previous log)",
template.getProtocol(), template.getProtocolVersion(), uri, template.getRpcMethod(), actualParams);
}
}
}));
return fetchData;
}
private class HttpStatusNotOkException extends Exception {
public HttpStatusNotOkException() {
}
public HttpStatusNotOkException(String message) {
super(message);
}
public HttpStatusNotOkException(String message, Throwable cause) {
super(message, cause);
}
public HttpStatusNotOkException(Throwable cause) {
super(cause);
}
public HttpStatusNotOkException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
} |
package uk.gov.dvla.core;
import junit.framework.Assert;
import org.junit.Test;
public class TestValidators {
@Test
public void testDlnValidators() {
String validDlns[] = {
"LEESH702100C99DP", "KITSO802192GT2BD", "T9999812208B99DG",
"TONY9810121MS2DB", "TYPEO606158A99QQ", "EXXXX811260EA9RE",
"e9999811260EA9Re", "JAM99711268KA9OP" };
String invalidDlns[] = {
"LEE999702100C99DP", "KITSO802192GT1BD", "99999812208B99DG",
"TON9810121MS2DB", "TYPE9O606158A99QQ", "EXXXX81T260EA9RE",
"e9999811260E89Re", "JAM98711268KA90P" };
for (String dln : validDlns) {
Assert.assertTrue(
String.format("DLN [%s] incorrectly considered invalid", dln),
Validators.validateDln(dln));
}
for (String dln : invalidDlns) {
Assert.assertFalse(
String.format("DLN [%s] incorrectly considered valid", dln),
Validators.validateDln(dln));
}
}
} |
package at.aau.game.desktop;
import com.badlogic.gdx.Files;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import at.aau.game.PixieSmack;
public class DesktopLauncher {
public static void main(String[] arg) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.width = 1024;//(int) PixieSmack.MENU_GAME_WIDTH;
config.height = 768;//(int) PixieSmack.MENU_GAME_HEIGHT;
config.addIcon("menu/ic_launcher_32.png", Files.FileType.Internal);
config.fullscreen = true;
config.resizable = false;
config.vSyncEnabled = true;
new LwjglApplication(new PixieSmack(), config);
}
} |
package ru.job4j.simpleTree;
import java.util.*;
public class Tree<E extends Comparable<E>> implements SimpleTree<E> {
private Node<E> root;
public Tree() {
}
public Tree(E value) {
this.root = new Node<>(value);
}
public boolean isBinary() {
boolean rsl = true;
Queue<Node<E>> data = new LinkedList<>();
data.offer(this.root);
while (!data.isEmpty()) {
Node<E> el = data.poll();
if (el.leaves().size() > 2) {
rsl = false;
break;
}
for (Node<E> child : el.leaves()) {
data.offer(child);
}
}
return rsl;
}
@Override
public Optional<Node<E>> findBy(E value) {
Optional<Node<E>> rsl = Optional.empty();
Queue<Node<E>> data = new LinkedList<>();
data.offer(this.root);
while (!data.isEmpty()) {
Node<E> el = data.poll();
if (el.eqValue(value)) {
rsl = Optional.of(el);
break;
}
for (Node<E> child : el.leaves()) {
data.offer(child);
}
}
return rsl;
}
@Override
public boolean add(E parent, E child) {
Optional<Node<E>> aParent = findBy(parent);
Optional<Node<E>> aChild = findBy(child);
if (!aChild.isPresent() && aParent.isPresent()) {
if (aParent.get().leaves().add(new Node<>(child))) {
return true;
}
}
return false;
}
@Override
public Iterator<E> iterator() {
Queue<Node<E>> data = new LinkedList<>();
data.add(root);
return new Iterator<E>() {
@Override
public boolean hasNext() {
return !data.isEmpty();
}
@Override
public E next() {
if (!hasNext())
throw new NoSuchElementException();
Node<E> current = data.poll();
if (!current.leaves().isEmpty()) {
data.addAll(current.leaves());
}
return current.getValue();
}
};
}
} |
package yaplstack;
import yaplstack.ast.AST;
import yaplstack.ast.Generator;
import java.io.*;
import java.util.ArrayList;
import static yaplstack.ast.AST.Factory.*;
public class Main {
public static void main(String[] args) throws NoSuchMethodException, NoSuchFieldException {
/*
What primivites are necessary to simulate tradition fn calls?
// Three registers:
// Operand frame
// Call frame
// Current environment
// Store all registers:
// [..., operand frame, visitApply frame, environment]
// storeEnvironment
// [..., operand frame, visitApply frame]
// storeCallFrame
// [..., operand frame]
// storeOperandFrame
// [...']
*/
/*
Create reader:
{
inputStream = ...
atEnd() => inputStream.available() <= 0;
next() => inputStream.read();
}
*/
// push nth element in stack
/*
{
var currentChar = null;
peek = function() {
return currentChar;
}
consume = function() {
if(inputStream.hasMore())
currentChar = inputStream.nextChar();
else
currentChar = '\0';
}
nextToken = function() {
ignore();
if(Character.isDigit(peek())) {
StringBuilder digits = new StringBuilder();
digits.append(peek());
consume();
while(Character.isDigit(peek())) {
StringBuilder digits = new StringBuilder();
digits.append(peek());
consume();
return {
type = "Integer";
value = Integer.parseInt(digits.toString());
};
}
} else if(peek() == '(') {
return {
type = "OpenPar";
};
} else if(peek() == ')') {
return {
type = "ClosePar";
};
}
return null;
}
}
or:
tokens = function(inputStream) {
var currentChar = null;
peek = function() {
return currentChar;
}
consume = function() {
if(inputStream.hasMore())
currentChar = inputStream.nextChar();
else
currentChar = '\0';
}
ignore = ...
ignore();
while(inputStream.hasMore()) {
if(Character.isDigit(peek())) {
StringBuilder digits = new StringBuilder();
digits.append(peek());
consume();
while(Character.isDigit(peek())) {
StringBuilder digits = new StringBuilder();
digits.append(peek());
consume();
return {
type = "Integer";
value = Integer.parseInt(digits.toString());
};
}
} else if(peek() == '(') {
yield {
type = "OpenPar";
};
} else if(peek() == ')') {
return {
type = "ClosePar";
};
}
}
}
defun threeNumbers(m) {
m.yield(1);
m.yield(2);
m.yield(3);
}
defun generate(producer) {
{
var producer = producer;
var hasNext = false;
var atEnd = () -> {!hasNext};
var next = () -> {
var res = current;
hasNext = false;
yielder.returnFrame = frame;
resume(yielder.yieldFrame, nil);
return res;
};
var yielder = producer({
var returnFrame = nil;
var yieldFrame = nil;
yield = value -> {
hasNext = true;
current = value;
yieldFrame = frame;
resume(returnFrame, nil);
}
};
yielder.returnFrame = frame;
var current;
() -> {
producer(yielder);
resume(yielder.returnFrame, nil);
}()
}
}
var generator1 = generate(threeNumbers);
while(!generator1.atEnd()) {
println(generator1.next());
}
*/
/*AST program = program(block(
defun("println", new String[]{"str"},
invoke(fieldGet(System.class.getField("out")), PrintStream.class.getMethod("println", String.class), invoke(load("str"), Object.class.getMethod("toString")))
),
defun("myMsg", block(
local("str", literal("Hello2")),
send(env(), "println", load("str")),
literal("Hurray")
)),
call("println", literal("Hello")),
send(env(), "myMsg")
));*/
/*AST program = program(block(
defun("println", new String[]{"str"},
invoke(fieldGet(System.class.getField("out")), PrintStream.class.getMethod("println", String.class), invoke(load("str"), Object.class.getMethod("toString")))
),
defun("numbers", new String[]{"m"}, block(
local("i", literal(0)),
loop(lti(load("i"), literal(100)), block(
send(load("m"), "yield", load("i")),
store("i", addi(load("i"), literal(1)))
))
)),
defun("generate", new String[]{"producer"}, block(
local("generator", object(block(
local("producer", load("producer")),
local("hasNext", literal(false)),
defun("atEnd", not(load("hasNext"))),
defun("next", block(
local("res", load("current")),
store("hasNext", literal(false)),
store("returnFrame", frame),
resume(load("yieldFrame"), literal(null)),
load("res")
)),
local("returnFrame", literal(false)),
local("yieldFrame", literal(false)),
defun("yield", new String[]{"value"}, block(
store("hasNext", literal(true)),
store("current", load("value")),
store("yieldFrame", frame),
resume(load("returnFrame"), literal(null))
)),
local("current", literal(false)),
local("returnFrame", frame)
))),
apply(fn(new String[]{"producer", "generator"}, block(
call("producer", load("generator")),
resume(load(load("generator"), "returnFrame"), literal(null))
)), load("producer"), load("generator")),
load("generator")
)),
local("gen", call("generate", load("numbers"))),
loop(not(send(load("gen"), "atEnd")), block(
call("println", send(load("gen"), "next"))
))
));*/
/*
tokens(input) {
return m -> {
// input = <frame-load-var: 0>
var current = null;
while(input.hasNext()) {
current = input.next();
if(isDigit(current)) {
}
}
}
}
*/
/*AST program = program(block(
local("point", object(
field("x", literal(7)),
field("y", literal(9)),
method("area", muli(load("x"), load("y"))),
method("area", new String[]{"z"}, muli(muli(load("x"), load("y")), load("z")))
)),
//send(load("point"), "area")
//send(load("point"), "area", literal(11))
load("point")
));*/
/*
defun newClosure(x) {
var y = 5;
return {
f = frame,
call:z => {
frameload(f, 0) * frameload(f, 1) * z;
}
};
}
(x, y) -> {x * y}
=>
{
call:x, y => {x * y}
}
function = (x, y) -> {x * y}
function(2, 3)
=>
function.call(2, 3)
*/
// Add support for store for closures
// Test 2+ levels of closure'ing
/*AST program = program(block(
defun("newClosure", new String[]{"x"}, block(
local("y", literal(10)),
fn(new String[]{"z"}, muli(muli(load("x"), load("y")), load("z")))
)),
local("closure", call("newClosure", literal(7))),
apply(load("closure"), literal(8))
defun("println", new String[]{"str"},
invoke(fieldGet(System.class.getField("out")), PrintStream.class.getMethod("println", String.class), invoke(load("str"), Object.class.getMethod("toString")))
),
defun("newClosure", new String[]{"x"}, block(
local("y", literal(0)),
fn(new String[]{}, block(
store("y", addi(load("y"), load("x")))
))
)),
local("closure", call("newClosure", literal(5))),
call("println", apply(load("closure"))),
call("println", apply(load("closure"))),
call("println", apply(load("closure")))
));*/
/*AST program = program(block(
local("obj0", object(
method("mth0", block(
local("x", literal(7)),
object(
method("mth1", fn(
//load("x")
store("x", addi(load("x"), literal(3)))
))
)
))
)),
local("closure", send(send(load("obj0"), "mth0"), "mth1")),
apply(load("closure")),
apply(load("closure")),
apply(load("closure"))
));*/
/*AST program = program(block(
defun("myFunction", literal("Hello World")),
call("myFunction"),
defun("newClosure", new String[]{"x"}, block(
local("y", literal(5)),
object(
field("f", frame),
method("call", new String[]{"z"}, muli(frameLoad(load("f"), 1), muli(frameLoad(load("f"), 2), load("z"))))
)
)),
local("closure", call("newClosure", literal(7))),
apply(load("closure"), literal(9)),
apply(fn(new String[]{"x", "y"}, muli(load("x"), load("y"))), literal(7), literal(9))
));*/
/*AST program = program(block(
defun("myFunction", block(
local("i", literal(2)),
defun("innerFunc", new String[]{"x"}, addi(load("x"), load("i"))),
call("innerFunc", literal(7))
)),
call("myFunction")
));*/
/*AST program = program(block(
local("obj", object(
method("atEnd", literal(true))
)),
local("j", literal(false)),
loop(
and(
not(send(load("obj"), "atEnd")),
invoke(Character.class.getMethod("isWhitespace", char.class), literal('H'))
),
block(
store("j", literal(true))
)
)
));*/
String sourceCode = " ( 12) )";
InputStream sourceCodeInputStream = new ByteArrayInputStream(sourceCode.getBytes());
Reader sourceCodeInputStreamReader = new InputStreamReader(sourceCodeInputStream);
AST program = program(block(
defun("println", new String[]{"str"},
invoke(fieldGet(System.class.getField("out")), PrintStream.class.getMethod("println", String.class), invoke(load("str"), Object.class.getMethod("toString")))
),
defun("generate", new String[]{"producer"}, block(
local("generator", object(
field("producer", load("producer")),
field("hasNext", literal(false)),
method("atEnd", not(load("hasNext"))),
method("next", block(
local("res", load("current")),
store("hasNext", literal(false)),
store("returnFrame", frame),
resume(load("yieldFrame"), literal(null)),
load("res")
)),
field("returnFrame", literal(false)),
field("yieldFrame", literal(false)),
method("yield", new String[]{"value"}, block(
store("hasNext", literal(true)),
store("current", load("value")),
store("yieldFrame", frame),
resume(load("returnFrame"), literal(null))
)),
field("current", literal(false)),
field("returnFrame", frame)
)),
apply(fn(new String[]{"producer", "generator"}, block(
apply(load("producer"), load("generator")),
resume(load(load("generator"), "returnFrame"), literal(null))
)), load("producer"), load("generator")),
load("generator")
)),
defun("chars", new String[]{"reader"}, fn(new String[]{"m"}, block(
local("b", literal(0)),
loop(
not(eqi(store("b", invoke(load("reader"), Reader.class.getMethod("read"))), literal(-1))),
block(
local("ch", load("b")),
send(load("m"), "yield", itoc(load("ch")))
)
)))
),
defun("tokens", new String[]{"chars"}, fn(new String[]{"m"}, block(
local("ch", literal(false)),
local("ch1", literal(false)),
local("atEnd", literal(false)),
local("atEnd1", literal(false)),
test(not(send(load("chars"), "atEnd")), store("ch1", send(load("chars"), "next")), store("atEnd1", literal(true))),
defun("consume", block(
store("ch", load("ch1")),
store("atEnd", load("atEnd1")),
test(not(send(load("chars"), "atEnd")), store("ch1", send(load("chars"), "next")), store("atEnd1", literal(true)))
)),
defun("ignore", block(
loop(
and(
not(load("atEnd")),
invoke(Character.class.getMethod("isWhitespace", char.class), load("ch"))
),
block(
call("consume")
)
)
)),
call("consume"),
call("ignore"),
loop(not(load("atEnd")), block(
local("token", literal(false)),
test(
eqc(load("ch"), literal('(')),
block(
store("token", object(field("type", literal("OPEN_PAR")))),
call("consume")
),
test(
eqc(load("ch"), literal(')')),
block(
store("token", object(field("type", literal("CLOSE_PAR")))),
call("consume")
),
test(
invoke(Character.class.getMethod("isDigit", char.class), load("ch")),
block(
local("digits", newInstance(StringBuilder.class.getConstructor())),
invoke(load("digits"), StringBuilder.class.getMethod("append", char.class), load("ch")),
call("consume"),
loop(
and(
not(load("atEnd")),
invoke(Character.class.getMethod("isDigit", char.class), load("ch"))
),
block(
invoke(load("digits"), StringBuilder.class.getMethod("append", char.class), load("ch")),
call("consume")
)
),
store("token", object(
field("type", literal("INT")),
field("value", invoke(Integer.class.getMethod("parseInt", String.class), invoke(load("digits"), StringBuilder.class.getMethod("toString"))))
))
)
)
)
),
send(load("m"), "yield", load("token")),
call("ignore")
))
))),
local("charsGen", call("generate", call("chars", literal(sourceCodeInputStreamReader)))),
local("tokensGen", call("generate", call("tokens", load("charsGen")))),
loop(not(send(load("tokensGen"), "atEnd")), block(
call("println", send(load("tokensGen"), "next"))
))
));
/*AST program = program(block(
defun("println", new String[]{"str"},
invoke(fieldGet(System.class.getField("out")), PrintStream.class.getMethod("println", String.class), invoke(load("str"), Object.class.getMethod("toString")))
),
local("numbers", fn(new String[]{"m"}, block(
local("i", literal(0)),
loop(lti(load("i"), literal(100)), block(
send(load("m"), "yield", load("i")),
store("i", addi(load("i"), literal(1)))
))
))),
defun("generate", new String[]{"producer"}, block(
local("generator", object(
field("producer", load("producer")),
field("hasNext", literal(false)),
method("atEnd", not(load("hasNext"))),
method("next", block(
local("res", load("current")),
store("hasNext", literal(false)),
store("returnFrame", frame),
resume(load("yieldFrame"), literal(null)),
load("res")
)),
field("returnFrame", literal(false)),
field("yieldFrame", literal(false)),
method("yield", new String[]{"value"}, block(
store("hasNext", literal(true)),
store("current", load("value")),
store("yieldFrame", frame),
resume(load("returnFrame"), literal(null))
)),
field("current", literal(false)),
field("returnFrame", frame)
)),
apply(fn(new String[]{"producer", "generator"}, block(
apply(load("producer"), load("generator")),
resume(load(load("generator"), "returnFrame"), literal(null))
)), load("producer"), load("generator")),
load("generator")
)),
local("gen", call("generate", load("numbers"))),
loop(not(send(load("gen"), "atEnd")), block(
call("println", send(load("gen"), "next"))
))
));*/
/*AST program = program(block(
defun("println", new String[]{"str"},
invoke(fieldGet(System.class.getField("out")), PrintStream.class.getMethod("println", String.class), invoke(load("str"), Object.class.getMethod("toString")))
),
defun("tokens", new String[]{"m"}, block(
local("i", literal(0)),
loop(lti(load("i"), literal(100)), block(
// Load closed locals in side by side of arguments
send(load("m"), "yield", load("i")),
store("i", addi(load("i"), literal(1)))
))
)),
defun("generate", new String[]{"producer"}, block(
local("generator", object(block(
local("producer", load("producer")),
local("hasNext", literal(false)),
defun("atEnd", not(load("hasNext"))),
defun("next", block(
local("res", load("current")),
store("hasNext", literal(false)),
store("returnFrame", frame),
resume(load("yieldFrame"), literal(null)),
load("res")
)),
local("returnFrame", literal(false)),
local("yieldFrame", literal(false)),
defun("yield", new String[]{"value"}, block(
store("hasNext", literal(true)),
store("current", load("value")),
store("yieldFrame", frame),
resume(load("returnFrame"), literal(null))
)),
local("current", literal(false)),
local("returnFrame", frame)
))),
apply(fn(new String[]{"producer", "generator"}, block(
call("producer", load("generator")),
resume(load(load("generator"), "returnFrame"), literal(null))
)), load("producer"), load("generator")),
load("generator")
)),
local("gen", call("generate", load("numbers"))),
loop(not(send(load("gen"), "atEnd")), block(
call("println", send(load("gen"), "next"))
))
));*/
/*String sourceCode = "( 1 ) 34";
AST program = program(block(
defun("println", new String[]{"str"},
invoke(fieldGet(System.class.getField("out")), PrintStream.class.getMethod("println", String.class), invoke(load("str"), Object.class.getMethod("toString")))
),
call("println", literal("Hello World")),
local("inputStream", object(block(
local("input", literal(new ByteArrayInputStream(sourceCode.getBytes()))),
defun("next", invoke(load("input"), InputStream.class.getMethod("read"))),
defun("nextChar", itoc(call("next"))),
defun("hasMore", gti(invoke(load("input"), InputStream.class.getMethod("available")), literal(0)))
))),
local("scanner", object(block(
defun("nextToken", invoke(load("inputStream"), InputStream.class.getMethod("read"))),
defun("hasMoreTokens", gti(invoke(load("input"), InputStream.class.getMethod("available")), literal(0)))
))),
loop(send(load("inputStream"), "hasMore"),
call("println", send(load("inputStream"), "nextChar"))
)
));*/
/*AST program = program(block(
local("myPoint", object(block(
local("x", literal(3)),
local("y", literal(5)),
defun("someFunc", new String[]{}, muli(load("x"), load("y"))),
defun("setX", new String[]{"x"}, store(outerEnv(env()), "x", load("x"))),
defun("setX2", new String[]{"x"}, block(
local("tmpX", addi(load("x"), literal(1))),
store(env(), "x", load("tmpX"))
))
))),
defun("strconcat", new String[]{"x", "y"}, invoke(load("x"), String.class.getMethod("concat", String.class), load("y"))),
defun("exclamator", new String[]{"x"}, call("strconcat", load("x"), literal("!!!"))),
call("exclamator", literal("Hello world")),
on(load("myPoint"), call("setX2", literal(77))),
on(load("myPoint"), load("x"))
));*/
/*AST program = program(block(
local("myFunc", fn(new String[]{"x", "y"},
addi(load("x"), load("y"))
)),
local("sq", fn(new String[]{"x"},
muli(load("x"), literal(2))
)),
pushCallFrame(load("myFunc"), pushCallFrame(load("sq"), literal(5)), literal(6))
));*/
/*AST program = program(block(
local("x", literal(5)),
local("y", literal(9)),
test(lti(load("x"), load("y")),
invoke(fieldGet(System.class.getField("out")), PrintStream.class.getMethod("println", String.class), literal("YES!!!")),
invoke(fieldGet(System.class.getField("out")), PrintStream.class.getMethod("println", String.class), literal("No..."))
)
));*/
/*AST program = program(block(
local("x", literal(0)),
loop(lti(load("x"), literal(10)),
store("x", addi(load("x"), literal(1)))
),
load("x")
));*/
Instruction[] instructions = Generator.toInstructions(program);
Thread thread = new Thread(new CallFrame(instructions));
/*Thread thread = new Thread(new CallFrame(new Instruction[] {
loadEnvironment,
newInstance(ArrayList.class.getConstructor()),
local("list"),
loadEnvironment,
load("list"),
loadConst(5),
invoke(ArrayList.class.getMethod("add", Object.class)),
loadEnvironment,
load("list"),
loadConst(7),
invoke(ArrayList.class.getMethod("add", Object.class)),
loadEnvironment,
load("list"),
finish
}));*/
/*Thread thread = new Thread(new CallFrame(new Instruction[] {
loadEnvironment,
loadConst(0),
local("i"),
loadEnvironment,
load("i"),
loadConst(10),
lti,
not,
jumpIfTrue(17),
loadEnvironment,
loadEnvironment,
load("i"),
loadConst(1),
addi,
store("i"),
loadConst(true),
jumpIfTrue(3),
loadEnvironment,
load("i"),
finish
}));*/
/*Thread thread = new Thread(new CallFrame(new Instruction[] {
loadEnvironment,
dup,
loadConst(new Instruction[]{
loadEnvironment,
extendEnvironment,
storeEnvironment,
pushOperandFrame(0),
loadEnvironment,
loadConst(5),
local("x"),
loadConst(7),
loadEnvironment,
load("x"),
addi,
popOperandFrame(1),
loadEnvironment,
outerEnvironment,
storeEnvironment,
popCallFrame
}),
local("myFunc"),
load("myFunc"),
visitApply,
finish
}));*/
thread.evalAll();
Object result = thread.callFrame.pop();
System.out.println(result);
}
} |
package act.fsa.jobs;
import act.job.Cron;
import act.job.Every;
import act.job.InvokeAfter;
import act.job.OnAppStart;
import org.osgl.util.S;
/**
* This class demonstrate how to use annotation to schedule jobs
* in an ActFramework application
*/
public class SomeService {
public String foo() {
return S.random();
}
/**
* This method will get called every 5 seconds
*/
@Every("5s")
public void checkStatus() {
JobLog.log("SomeService.checkStatus");
}
/**
* This method will get started along with Application start up
*/
@OnAppStart
public void prepare() {
JobLog.log("SomeService.prepare");
}
/**
* This method will get invoked after {@link #prepare()} method is invoked.
* <p>Note the method name {@code afterPrepare} doesn't matter, it could be any
* other name.</p>
*/
@InvokeAfter("act.fsa.jobs.SomeService.prepare")
public void afterPrepare() {
JobLog.log("SomeService.afterPrepare");
}
/**
* This method is scheduled to run every minute
*/
@Cron("0 * * * * ?")
public void backup() {
JobLog.log("SomeService.backup");
}
/**
* This method is scheduled to run as per value of {@code cron.passwordReminder}
* configuration. See {@code /resources/conf/cron.properties}
*/
@Cron("cron.passwordReminder")
public void checkAndSendOutPasswordReminder() {
JobLog.log("checking password expiration and sending out password reminder");
}
} |
package acceptance;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.CharSource;
import io.digdag.client.DigdagClient;
import io.digdag.client.api.Id;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.commons.lang3.RandomUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import utils.CommandStatus;
import utils.TemporaryDigdagServer;
import utils.TestUtils;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import static java.nio.charset.StandardCharsets.US_ASCII;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertThat;
import static utils.TestUtils.addWorkflow;
import static utils.TestUtils.attemptFailure;
import static utils.TestUtils.attemptSuccess;
import static utils.TestUtils.copyResource;
import static utils.TestUtils.expect;
import static utils.TestUtils.getAttemptLogs;
import static utils.TestUtils.main;
import static utils.TestUtils.pushProject;
import static utils.TestUtils.startWorkflow;
public class SecretsIT
{
@Rule
public TemporaryFolder folder = new TemporaryFolder();
private TemporaryDigdagServer server;
private Path config;
private Path projectDir;
private DigdagClient client;
@Before
public void setUp()
throws Exception
{
projectDir = folder.newFolder().toPath().toAbsolutePath().normalize();
config = folder.newFile().toPath();
}
@After
public void tearDownClient()
throws Exception
{
if (client != null) {
client.close();
client = null;
}
}
@After
public void tearDownServer()
throws Exception
{
if (server != null) {
server.close();
server = null;
}
}
private void startServer()
throws Exception
{
server = TemporaryDigdagServer.builder()
.configuration("digdag.secret-encryption-key = " + Base64.getEncoder().encodeToString(RandomUtils.nextBytes(16)))
.build();
server.start();
client = DigdagClient.builder()
.host(server.host())
.port(server.port())
.build();
}
@Test
public void testSetListDeleteProjectSecrets()
throws Exception
{
startServer();
String projectName = "test";
// Push the project
CommandStatus pushStatus = main("push",
"--project", projectDir.toString(),
projectName,
"-c", config.toString(),
"-e", server.endpoint());
assertThat(pushStatus.errUtf8(), pushStatus.code(), is(0));
// Command line args
String key1 = "key1";
String value1 = "value1";
String key2 = "key2";
String value2 = "value2";
// Single file value
String key3 = "key3";
String value3 = "value3";
// Single stdin value
String key4 = "key4";
String value4 = "value4";
// Multiple stdin values
String key5 = "key5";
String value5 = "value5";
String key6 = "key6";
String value6 = "value6";
// Multiple file values
String key7 = "key7";
String value7 = "value7";
String key8 = "key8";
String value8 = "value8";
Path value3File = folder.newFile().toPath();
Files.write(value3File, ImmutableList.of(value3));
// Set secrets on command line and from file
{
CommandStatus setStatus = main("secrets",
"-c", config.toString(),
"-e", server.endpoint(),
"--project", projectName,
"--set",
key1 + '=' + value1,
key2 + '=' + value2,
key3 + "=@" + value3File.toString());
assertThat(setStatus.errUtf8(), setStatus.code(), is(0));
assertThat(setStatus.errUtf8(), containsString("Secret '" + key1 + "' set"));
assertThat(setStatus.errUtf8(), containsString("Secret '" + key2 + "' set"));
assertThat(setStatus.errUtf8(), containsString("Secret '" + key3 + "' set"));
}
// Set secret from stdin
{
InputStream in = new ByteArrayInputStream(value4.getBytes(US_ASCII));
CommandStatus setStatus = main(
in,
"secrets",
"-c", config.toString(),
"-e", server.endpoint(),
"--project", projectName,
"--set",
key4 + "=-");
assertThat(setStatus.errUtf8(), setStatus.code(), is(0));
assertThat(setStatus.errUtf8(), containsString("Secret '" + key4 + "' set"));
}
YAMLFactory yamlFactory = new YAMLFactory();
// Set secrets from stdin
{
ByteArrayOutputStream yaml = new ByteArrayOutputStream();
YAMLGenerator generator = yamlFactory.createGenerator(yaml);
TestUtils.objectMapper().writeValue(generator, ImmutableMap.of(key5, value5, key6, value6));
InputStream in = new ByteArrayInputStream(yaml.toByteArray());
CommandStatus setStatus = main(
in,
"secrets",
"-c", config.toString(),
"-e", server.endpoint(),
"--project", projectName,
"--set", "@-");
assertThat(setStatus.errUtf8(), setStatus.code(), is(0));
assertThat(setStatus.errUtf8(), containsString("Secret '" + key5 + "' set"));
assertThat(setStatus.errUtf8(), containsString("Secret '" + key6 + "' set"));
}
// Set secrets from file
Path secretsFileYaml = folder.newFolder().toPath().resolve("secrets.yaml");
try (OutputStream o = Files.newOutputStream(secretsFileYaml)) {
YAMLGenerator generator = yamlFactory.createGenerator(o);
TestUtils.objectMapper().writeValue(generator, ImmutableMap.of(key7, value7, key8, value8));
CommandStatus setStatus = main(
"secrets",
"-c", config.toString(),
"-e", server.endpoint(),
"--project", projectName,
"--set", "@" + secretsFileYaml);
assertThat(setStatus.errUtf8(), setStatus.code(), is(0));
assertThat(setStatus.errUtf8(), containsString("Secret '" + key7 + "' set"));
assertThat(setStatus.errUtf8(), containsString("Secret '" + key8 + "' set"));
}
// List secrets
CommandStatus listStatus = main("secrets",
"-c", config.toString(),
"-e", server.endpoint(),
"--project", projectName);
assertThat(listStatus.errUtf8(), listStatus.code(), is(0));
List<String> listedKeys = CharSource.wrap(listStatus.outUtf8()).readLines();
assertThat(listedKeys, containsInAnyOrder(key1, key2, key3, key4, key5, key6, key7, key8));
// Delete secrets
CommandStatus deleteStatus = main("secrets",
"-c", config.toString(),
"-e", server.endpoint(),
"--project", projectName,
"--delete", key1,
"--delete", key2, key3);
assertThat(deleteStatus.errUtf8(), deleteStatus.code(), is(0));
assertThat(deleteStatus.errUtf8(), containsString("Secret 'key1' deleted"));
assertThat(deleteStatus.errUtf8(), containsString("Secret 'key2' deleted"));
assertThat(deleteStatus.errUtf8(), containsString("Secret 'key3' deleted"));
// List secrets after deletion
CommandStatus listStatus2 = main("secrets",
"-c", config.toString(),
"-e", server.endpoint(),
"--project", projectName);
assertThat(listStatus2.errUtf8(), listStatus2.code(), is(0));
List<String> listedKeys2 = CharSource.wrap(listStatus2.outUtf8()).readLines();
assertThat(listedKeys2, containsInAnyOrder(key4, key5, key6, key7, key8));
}
@Test
public void testUseProjectSecret()
throws Exception
{
startServer();
String projectName = "test";
// Push the project
{
copyResource("acceptance/secrets/echo_secret.dig", projectDir);
copyResource("acceptance/secrets/echo_secret_parameterized.dig", projectDir);
pushProject(server.endpoint(), projectDir, projectName);
}
String key1 = "key1";
String key2 = "key2";
String value1 = "value1";
String value2 = "value2";
// Set secrets
{
CommandStatus setStatus = main("secrets",
"-c", config.toString(),
"-e", server.endpoint(),
"--project", projectName,
"--set", key1 + '=' + value1, key2 + '=' + value2);
assertThat(setStatus.errUtf8(), setStatus.code(), is(0));
}
// Start workflows using secrets
{
Path outfile = folder.newFolder().toPath().toAbsolutePath().normalize().resolve("out");
Path outfileParameterized = folder.newFolder().toPath().toAbsolutePath().normalize().resolve("out-parameterized");
Id attemptId = startWorkflow(
server.endpoint(), projectName, "echo_secret",
ImmutableMap.of("OUTFILE", outfile.toString()));
Id attemptIdParameterized = startWorkflow(
server.endpoint(), projectName, "echo_secret_parameterized",
ImmutableMap.of("secret_key", "key2",
"OUTFILE", outfileParameterized.toString()));
expect(Duration.ofMinutes(5), attemptSuccess(server.endpoint(), attemptId));
expect(Duration.ofMinutes(5), attemptSuccess(server.endpoint(), attemptIdParameterized));
List<String> output = Files.readAllLines(outfile);
assertThat(output, contains(value1));
List<String> outputParameterized = Files.readAllLines(outfileParameterized);
assertThat(outputParameterized, contains(value2));
}
// Delete a secret
{
CommandStatus deleteStatus = main("secrets",
"-c", config.toString(),
"-e", server.endpoint(),
"--project", projectName,
"--delete", key1);
assertThat(deleteStatus.errUtf8(), deleteStatus.code(), is(0));
assertThat(deleteStatus.errUtf8(), containsString("Secret 'key1' deleted"));
}
// Attempt to run a workflow that uses the deleted secret
{
Path outfile = folder.newFolder().toPath().toAbsolutePath().normalize().resolve("out");
Id attemptId = startWorkflow(
server.endpoint(), projectName, "echo_secret",
ImmutableMap.of("OUTFILE", outfile.toString()));
expect(Duration.ofMinutes(5), attemptFailure(server.endpoint(), attemptId));
String logs = getAttemptLogs(client, attemptId);
assertThat(logs, containsString("Secret not found for key: 'key1'"));
}
}
@Test
public void testUseLocalSecret()
throws Exception
{
addWorkflow(projectDir, "acceptance/secrets/echo_secret.dig");
String key1 = "key1";
String value1 = "value1";
String key2 = "key2";
String value2 = "value2";
Map<String, String> env = ImmutableMap.of("DIGDAG_CONFIG_HOME", folder.newFolder().toPath().toString());
// Set secrets
{
CommandStatus status = main(env, "secrets",
"-c", config.toString(),
"--local",
"--set", key1 + '=' + value1, key2 + '=' + value2);
assertThat(status.errUtf8(), status.code(), is(0));
assertThat(status.errUtf8(), containsString("Secret 'key1' set"));
assertThat(status.errUtf8(), containsString("Secret 'key2' set"));
}
// List secrets
{
CommandStatus status = main(env, "secrets",
"-c", config.toString(),
"--local");
assertThat(status.errUtf8(), status.code(), is(0));
assertThat(status.outUtf8(), containsString("key1"));
assertThat(status.outUtf8(), containsString("key2"));
assertThat(status.outUtf8(), not(containsString("value1")));
assertThat(status.outUtf8(), not(containsString("value2")));
}
// Run workflows using secrets
{
Path outfile = folder.newFolder().toPath().toAbsolutePath().normalize().resolve("out");
CommandStatus status = TestUtils.main(env, "run",
"-c", config.toString(),
"-o", folder.newFolder().toString(),
"--project", projectDir.toString(),
"-p", "OUTFILE=" + outfile.toString(),
"echo_secret");
assertThat(status.errUtf8(), status.code(), is(0));
List<String> output = Files.readAllLines(outfile);
assertThat(output, contains(value1));
}
// Delete a secret
{
CommandStatus deleteStatus = main(env, "secrets",
"-c", config.toString(),
"--local",
"--delete", key1);
assertThat(deleteStatus.errUtf8(), deleteStatus.code(), is(0));
assertThat(deleteStatus.errUtf8(), containsString("Secret 'key1' deleted"));
}
// List secrets
{
CommandStatus status = main(env, "secrets",
"-c", config.toString(),
"--local");
assertThat(status.errUtf8(), status.code(), is(0));
assertThat(status.outUtf8(), not(containsString("key1")));
assertThat(status.outUtf8(), containsString("key2"));
assertThat(status.outUtf8(), not(containsString("value1")));
assertThat(status.outUtf8(), not(containsString("value2")));
}
// Attempt to run a workflow that uses the deleted secret
{
Path outfile = folder.newFolder().toPath().toAbsolutePath().normalize().resolve("out");
CommandStatus status = main(env, "run",
"-c", config.toString(),
"-o", folder.newFolder().toString(),
"--project", projectDir.toString(),
"-p", "OUTFILE=" + outfile.toString(),
"echo_secret");
assertThat(status.errUtf8(), status.code(), not(is(0)));
assertThat(status.errUtf8(), containsString("Secret not found for key: 'key1'"));
}
}
@Test
public void verifyInvalidSecretUseFails()
throws Exception
{
startServer();
String projectName = "test";
// Push the project
copyResource("acceptance/secrets/invalid_secret_use.dig", projectDir);
copyResource("acceptance/secrets/echo_secret_parameterized.dig", projectDir);
pushProject(server.endpoint(), projectDir, projectName);
String key1 = "key1";
String key2 = "key2";
String value1 = "value1";
String value2 = "value2";
// Set secrets
CommandStatus setStatus = main("secrets",
"-c", config.toString(),
"-e", server.endpoint(),
"--project", projectName,
"--set", key1 + '=' + value1, key2 + '=' + value2);
assertThat(setStatus.errUtf8(), setStatus.code(), is(0));
Id attemptId = startWorkflow(server.endpoint(), projectName, "invalid_secret_use", ImmutableMap.of());
expect(Duration.ofMinutes(5), attemptFailure(server.endpoint(), attemptId));
String logs = getAttemptLogs(client, attemptId);
assertThat(logs, containsString("\"key1\" is not defined"));
}
@Test
public void verifyAccessIsGrantedToUserSecretTemplateKeys()
throws Exception
{
startServer();
String projectName = "test";
// Push the project
copyResource("acceptance/secrets/user_secret_template.dig", projectDir);
pushProject(server.endpoint(), projectDir, projectName);
// Set secrets
CommandStatus setStatus = main("secrets",
"-c", config.toString(),
"-e", server.endpoint(),
"--project", projectName,
"--set", "foo=foo_value", "nested.bar=bar_value");
assertThat(setStatus.errUtf8(), setStatus.code(), is(0));
Path outfile = folder.newFolder().toPath().toAbsolutePath().normalize().resolve("out");
Id attemptId = startWorkflow(server.endpoint(), projectName, "user_secret_template", ImmutableMap.of(
"OUTFILE", outfile.toString()
));
expect(Duration.ofMinutes(5), attemptSuccess(server.endpoint(), attemptId));
List<String> output = Files.readAllLines(outfile);
assertThat(output, contains("foo=foo_value bar=bar_value"));
}
} |
package csfg;
import gate.Annotation;
import gate.AnnotationSet;
import gate.Corpus;
import gate.CorpusController;
import gate.Document;
import gate.Factory;
import gate.Gate;
import gate.creole.ExecutionException;
import gate.creole.ResourceInstantiationException;
import gate.util.GateException;
import gate.util.persistence.PersistenceManager;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import org.wikifier.MapList;
public class TextMiningPipeline {
private String encoding = null;
Corpus corpus;
CorpusController application;
private String docResult;
private MapList mapResult;
static AnnotationConfig annoConfig = new AnnotationConfig();
/**
*
* When run standalone, uses arg 1 properties file to process arg 2, outputting in /tmp/sample.html
**/
public static void main(String[] args) throws GateException, IOException, InterruptedException {
TextMiningPipeline g = new TextMiningPipeline();
System.out.println(args.length);
g.init(args[0]);
g.processFile(args[1]);
String doc = g.getDocResult();
System.out.println(g.getMapResult());
writeFile(doc, "/tmp/sample.html");
}
/**
*
* initialize wtih properties file
*
**/
public void init(String config) throws GateException, IOException {
System.out.println("init from " + System.getProperty("user.dir"));
File gateHome = null, xgappHome = null, xgappPluginsHome = null, siteConfigFile = null;
try {
Properties properties = new Properties();
InputStream input = new FileInputStream(config);
properties.load(input);
gateHome = new File(properties.getProperty("libs.home"));
xgappHome = new File(properties.getProperty("xgapp.location"));
xgappPluginsHome = new File(properties.getProperty("xgapp.plugins.location"));
siteConfigFile = new File(properties.getProperty("gate.site.config.location"));
} catch (IOException ex) {
System.err.println("could not read properties file " + config);
throw ex;
}
System.out.println("initializing with gate.home: " + gateHome + " -- xgapp.location: " + xgappHome + " -- xgapp.plugins.location: " + xgappPluginsHome + " -- gate.site.config.location: " + siteConfigFile + "\n" + System.getProperty("gate.home"));
Gate.setGateHome(gateHome);
Gate.setPluginsHome(xgappPluginsHome);
Gate.setSiteConfigFile(siteConfigFile);
Gate.init();
application = (CorpusController) PersistenceManager.loadObjectFromFile(xgappHome);
corpus = Factory.newCorpus("BatchProcessApp Corpus");
application.setCorpus(corpus);
}
/**
*
* process an HTML file adding all annotations
*
**/
public void processFile(String fileName) throws ResourceInstantiationException, ExecutionException, IOException {
System.out.println("Processing document " + fileName);
File docFile = new File(fileName);
Document doc = addAnnotations(docFile);
String text = doc.getContent().toString();
mapResult = new MapList();
Set<Annotation> docAnnos = new HashSet<Annotation>();
for (String type : doc.getAnnotations().getAllTypes()) {
if (type != null) {
AnnotationSet as = doc.getAnnotations().get(type);
for (Annotation a : as) {
String t = text.substring((int) (long) a.getStartNode().getOffset(), (int) (long) a.getEndNode().getOffset());
docAnnos.add(a);
mapResult.put(type, t);
}
}
}
docResult = doc.toXml(docAnnos, true);
corpus.remove(doc);
Factory.deleteResource(doc);
}
/**
*
* Retrieve the HTML document result with inline annotations
*
**/
public String getDocResult() {
return docResult;
}
/**
*
* Get a map of annotations
*
**/
public MapList getMapResult() {
return mapResult;
}
/**
*
* Actually add the annotations
*
**/
Document addAnnotations(File docFile) throws ResourceInstantiationException, MalformedURLException, ExecutionException {
Document doc = Factory.newDocument(docFile.toURL(), encoding);
//doc.setPreserveOriginalContent(true);
doc.setMarkupAware(true);
corpus.add(doc);
application.execute();
corpus.clear();
return doc;
}
/**
*
* Prepare an html snippet for annotation
*
**/
public void processText(String text) throws ResourceInstantiationException, ExecutionException, IOException {
File docFile = File.createTempFile("sample", ".html");
//f.deleteOnExit();
String tmp = docFile.toString();
writeFile("<html><body>" +text + "</body></html>", tmp);
processFile(tmp);
}
/**
*
* Helper to write a file
*
**/
public static void writeFile(String txt, String outfile) throws IOException {
FileWriter fw = new FileWriter(outfile);
BufferedWriter out = new BufferedWriter(fw);
out.write(txt);
out.close();
}
} |
package lista2;
import java.util.Scanner;
/**
*
* @author wilson.neto
*/
public class Exec_3 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
System.out.print("Informe o primeiro numero: ");
int num1 = sc.nextInt();
System.out.print("Informe o segundo numero: ");
int num2 = sc.nextInt();
System.out.print("Informe o terceiro numero: ");
int num3 = sc.nextInt();
if(num1>=num2){
if(num2>=num3){
System.out.println(num1+", "+num2+", "+num3);
}else{
if(num1>=num3){
System.out.println(num1+", "+num3+", "+num2);
}else{
System.out.println(num3+", "+num1+", "+num2);
}
}
}else{
if(num1>=num3){
System.out.println(num2+", "+num1+", "+num3);
}else{
if(num2>=num3){
System.out.println(num2+", "+num3+", "+num1);
}else{
System.out.println(num3+", "+num2+", "+num1);
}
}
}
}
} |
package graph;
import gcm.parser.GCMFile;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.LinkedList;
import java.util.Properties;
import java.util.Scanner;
import java.util.concurrent.locks.ReentrantLock;
import java.util.prefs.Preferences;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.plaf.metal.MetalButtonUI;
import javax.swing.plaf.metal.MetalIconFactory;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import lpn.parser.LhpnFile;
import main.Gui;
import main.Log;
import org.apache.batik.dom.GenericDOMImplementation;
import org.apache.batik.svggen.SVGGraphics2D;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.LogarithmicAxis;
import org.jfree.chart.axis.NumberTickUnit;
import org.jfree.chart.axis.StandardTickUnitSource;
import org.jfree.chart.event.ChartProgressEvent;
import org.jfree.chart.event.ChartProgressListener;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.GradientBarPainter;
import org.jfree.chart.renderer.category.StandardBarPainter;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.LegendTitle;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYDataItem;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jibble.epsgraphics.EpsGraphics2D;
import org.sbml.libsbml.ListOf;
import org.sbml.libsbml.Model;
import org.sbml.libsbml.SBMLDocument;
import org.sbml.libsbml.Species;
import org.w3c.dom.DOMImplementation;
import parser.TSDParser;
import reb2sac.Reb2Sac;
import util.Utility;
import com.lowagie.text.Document;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.DefaultFontMapper;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
/**
* This is the Graph class. It takes in data and draws a graph of that data. The
* Graph class implements the ActionListener class, the ChartProgressListener
* class, and the MouseListener class. This allows the Graph class to perform
* actions when buttons are pressed, when the chart is drawn, or when the chart
* is clicked.
*
* @author Curtis Madsen
*/
public class Graph extends JPanel implements ActionListener, MouseListener, ChartProgressListener {
private static final long serialVersionUID = 4350596002373546900L;
private JFreeChart chart; // Graph of the output data
private XYSeriesCollection curData; // Data in the current graph
private String outDir; // output directory
private String printer_id; // printer id
/*
* Text fields used to change the graph window
*/
private JTextField XMin, XMax, XScale, YMin, YMax, YScale;
private ArrayList<String> graphSpecies; // names of species in the graph
private Gui biomodelsim; // tstubd gui
private JButton save, run, saveAs;
private JButton export, refresh; // buttons
// private JButton exportJPeg, exportPng, exportPdf, exportEps, exportSvg,
// exportCsv; // buttons
private HashMap<String, Paint> colors;
private HashMap<String, Shape> shapes;
private String selected, lastSelected;
private LinkedList<GraphSpecies> graphed;
private LinkedList<GraphProbs> probGraphed;
private JCheckBox resize;
private JComboBox XVariable;
private JCheckBox LogX, LogY;
private JCheckBox visibleLegend;
private LegendTitle legend;
private Log log;
private ArrayList<JCheckBox> boxes;
private ArrayList<JTextField> series;
private ArrayList<JComboBox> colorsCombo;
private ArrayList<JButton> colorsButtons;
private ArrayList<JComboBox> shapesCombo;
private ArrayList<JCheckBox> connected;
private ArrayList<JCheckBox> visible;
private ArrayList<JCheckBox> filled;
private JCheckBox use;
private JCheckBox connectedLabel;
private JCheckBox visibleLabel;
private JCheckBox filledLabel;
private String graphName;
private String separator;
private boolean change;
private boolean timeSeries;
private boolean topLevel;
private ArrayList<String> graphProbs;
private JTree tree;
private IconNode node, simDir;
private Reb2Sac reb2sac; // reb2sac options
private ArrayList<String> learnSpecs;
private boolean warn;
private ArrayList<String> averageOrder;
private JPopupMenu popup; // popup menu
private ArrayList<String> directories;
private JPanel specPanel;
private JScrollPane scrollpane;
private JPanel all;
private JPanel titlePanel;
private JScrollPane scroll;
private boolean updateXNumber;
private final ReentrantLock lock;
/**
* Creates a Graph Object from the data given and calls the private graph
* helper method.
*/
public Graph(Reb2Sac reb2sac, String printer_track_quantity, String label, String printer_id,
String outDir, String time, Gui biomodelsim, String open, Log log, String graphName,
boolean timeSeries, boolean learnGraph) {
lock = new ReentrantLock(true);
this.reb2sac = reb2sac;
averageOrder = null;
popup = new JPopupMenu();
warn = false;
if (File.separator.equals("\\")) {
separator = "\\\\";
}
else {
separator = File.separator;
}
// initializes member variables
this.log = log;
this.timeSeries = timeSeries;
if (graphName != null) {
this.graphName = graphName;
topLevel = true;
}
else {
if (timeSeries) {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1]
+ ".grf";
}
else {
this.graphName = outDir.split(separator)[outDir.split(separator).length - 1]
+ ".prb";
}
topLevel = false;
}
this.outDir = outDir;
this.printer_id = printer_id;
this.biomodelsim = biomodelsim;
XYSeriesCollection data = new XYSeriesCollection();
if (learnGraph) {
updateSpecies();
}
else {
learnSpecs = null;
}
// graph the output data
if (timeSeries) {
setUpShapesAndColors();
graphed = new LinkedList<GraphSpecies>();
selected = "";
lastSelected = "";
graph(printer_track_quantity, label, data, time);
if (open != null) {
open(open);
}
}
else {
setUpShapesAndColors();
probGraphed = new LinkedList<GraphProbs>();
selected = "";
lastSelected = "";
probGraph(label);
if (open != null) {
open(open);
}
}
}
/**
* This private helper method calls the private readData method, sets up a
* graph frame, and graphs the data.
*
* @param dataset
* @param time
*/
private void graph(String printer_track_quantity, String label, XYSeriesCollection dataset,
String time) {
chart = ChartFactory.createXYLineChart(label, time, printer_track_quantity, dataset,
PlotOrientation.VERTICAL, true, true, false);
chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
chart.addProgressListener(this);
legend = chart.getLegend();
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates text fields for changing the graph's dimensions
resize = new JCheckBox("Auto Resize");
resize.setSelected(true);
XVariable = new JComboBox();
updateXNumber = false;
XVariable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (updateXNumber && node != null) {
String curDir = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent())
.getName()
+ separator + ((IconNode) node.getParent()).getName())) {
curDir = ((IconNode) node.getParent().getParent()).getName() + separator
+ ((IconNode) node.getParent()).getName();
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
curDir = ((IconNode) node.getParent()).getName();
}
else {
curDir = "";
}
for (int i = 0; i < graphed.size(); i++) {
if (graphed.get(i).getDirectory().equals(curDir)) {
graphed.get(i).setXNumber(XVariable.getSelectedIndex());
}
}
}
}
});
LogX = new JCheckBox("LogX");
LogX.setSelected(false);
LogY = new JCheckBox("LogY");
LogY.setSelected(false);
visibleLegend = new JCheckBox("Visible Legend");
visibleLegend.setSelected(true);
XMin = new JTextField();
XMax = new JTextField();
XScale = new JTextField();
YMin = new JTextField();
YMax = new JTextField();
YScale = new JTextField();
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
export = new JButton("Export");
refresh = new JButton("Refresh");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
run.addActionListener(this);
save.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// puts all the components of the graph gui into a display panel
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
// determines maximum and minimum values and resizes
resize(dataset);
this.revalidate();
}
private void readGraphSpecies(String file) {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
graphSpecies = new TSDParser(file, true).getSpecies();
Gui.frame.setCursor(null);
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
i
}
}
}
}
/**
* This public helper method parses the output file of ODE, monte carlo, and
* markov abstractions.
*/
public ArrayList<ArrayList<Double>> readData(String file, String label, String directory,
boolean warning) {
warn = warning;
String[] s = file.split(separator);
String getLast = s[s.length - 1];
String stem = "";
int t = 0;
try {
while (!Character.isDigit(getLast.charAt(t))) {
stem += getLast.charAt(t);
t++;
}
}
catch (Exception e) {
}
if ((label.contains("average") && file.contains("mean"))
|| (label.contains("variance") && file.contains("variance"))
|| (label.contains("deviation") && file.contains("standard_deviation"))) {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
TSDParser p = new TSDParser(file, warn);
Gui.frame.setCursor(null);
warn = p.getWarning();
graphSpecies = p.getSpecies();
ArrayList<ArrayList<Double>> data = p.getData();
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
else if (averageOrder != null) {
for (String spec : averageOrder) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!averageOrder.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
return data;
}
if (label.contains("average") || label.contains("variance") || label.contains("deviation")) {
int counter = 1;
while (!(new File(file).exists())) {
file = file.substring(0, file.length() - getLast.length());
file += stem;
file += counter + "";
file += "." + printer_id.substring(0, printer_id.length() - 8);
counter++;
}
}
if (label.contains("average")) {
return calculateAverageVarianceDeviation(file, stem, 0, directory, warn);
}
else if (label.contains("variance")) {
return calculateAverageVarianceDeviation(file, stem, 1, directory, warn);
}
else if (label.contains("deviation")) {
return calculateAverageVarianceDeviation(file, stem, 2, directory, warn);
}
else {
Gui.frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
TSDParser p = new TSDParser(file, warn);
Gui.frame.setCursor(null);
warn = p.getWarning();
graphSpecies = p.getSpecies();
ArrayList<ArrayList<Double>> data = p.getData();
if (learnSpecs != null) {
for (String spec : learnSpecs) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!learnSpecs.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
else if (averageOrder != null) {
for (String spec : averageOrder) {
if (!graphSpecies.contains(spec)) {
graphSpecies.add(spec);
ArrayList<Double> d = new ArrayList<Double>();
for (int i = 0; i < data.get(0).size(); i++) {
d.add(0.0);
}
data.add(d);
}
}
for (int i = 1; i < graphSpecies.size(); i++) {
if (!averageOrder.contains(graphSpecies.get(i))) {
graphSpecies.remove(i);
data.remove(i);
i
}
}
}
return data;
}
}
/**
* This method adds and removes plots from the graph depending on what check
* boxes are selected.
*/
public void actionPerformed(ActionEvent e) {
// if the save button is clicked
if (e.getSource() == run) {
reb2sac.getRunButton().doClick();
}
if (e.getSource() == save) {
save();
}
// if the save as button is clicked
if (e.getSource() == saveAs) {
saveAs();
}
// if the export button is clicked
else if (e.getSource() == export) {
export();
}
else if (e.getSource() == refresh) {
refresh();
}
else if (e.getActionCommand().equals("rename")) {
String rename = JOptionPane.showInputDialog(Gui.frame, "Enter A New Filename:",
"Rename", JOptionPane.PLAIN_MESSAGE);
if (rename != null) {
rename = rename.trim();
}
else {
return;
}
if (!rename.equals("")) {
boolean write = true;
if (rename.equals(node.getName())) {
write = false;
}
else if (new File(outDir + separator + rename).exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
File dir = new File(outDir + separator + rename);
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() > 0
&& ((IconNode) simDir.getChildAt(i)).getName().equals(rename)) {
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals(
"" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
for (int i = 0; i < graphed.size(); i++) {
if (graphed.get(i).getDirectory().equals(rename)) {
graphed.remove(i);
i
}
}
}
else {
write = false;
}
}
if (write) {
String getFile = node.getName();
IconNode s = node;
while (s.getParent().getParent() != null) {
getFile = s.getName() + separator + getFile;
s = (IconNode) s.getParent();
}
getFile = outDir + separator + getFile;
new File(getFile).renameTo(new File(outDir + separator + rename));
for (GraphSpecies spec : graphed) {
if (spec.getDirectory().equals(node.getName())) {
spec.setDirectory(rename);
}
}
directories.remove(node.getName());
directories.add(rename);
node.setUserObject(rename);
node.setName(rename);
simDir.remove(node);
int i;
for (i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
if (((IconNode) simDir.getChildAt(i)).getName().compareToIgnoreCase(
rename) > 0) {
simDir.insert(node, i);
break;
}
}
else {
break;
}
}
simDir.insert(node, i);
ArrayList<String> rows = new ArrayList<String>();
for (i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
int select = 0;
for (i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
if (rename.equals(node.getName())) {
select = i;
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
tree.setSelectionRow(select);
}
}
}
else if (e.getActionCommand().equals("delete")) {
TreePath[] selected = tree.getSelectionPaths();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
for (TreeSelectionListener listen : tree.getTreeSelectionListeners()) {
tree.removeTreeSelectionListener(listen);
}
tree.addTreeSelectionListener(t);
for (TreePath select : selected) {
tree.setSelectionPath(select);
if (!((IconNode) select.getLastPathComponent()).getName().equals("Average")
&& !((IconNode) select.getLastPathComponent()).getName().equals("Variance")
&& !((IconNode) select.getLastPathComponent()).getName().equals(
"Standard Deviation")
&& ((IconNode) select.getLastPathComponent()).getParent() != null) {
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)) == ((IconNode) select
.getLastPathComponent())) {
if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
simDir.remove(i);
File dir = new File(outDir + separator
+ ((IconNode) select.getLastPathComponent()).getName());
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
directories.remove(((IconNode) select.getLastPathComponent())
.getName());
for (int j = 0; j < graphed.size(); j++) {
if (graphed.get(j).getDirectory().equals(
((IconNode) select.getLastPathComponent()).getName())) {
graphed.remove(j);
j
}
}
}
else {
simDir.remove(i);
File dir = new File(outDir + separator
+ ((IconNode) select.getLastPathComponent()).getName()
+ "." + printer_id.substring(0, printer_id.length() - 8));
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
int count = 0;
for (int j = 0; j < simDir.getChildCount(); j++) {
if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) {
count++;
}
}
if (count == 3) {
for (int j = 0; j < simDir.getChildCount(); j++) {
if (((IconNode) simDir.getChildAt(j)).getChildCount() == 0) {
simDir.remove(j);
j
}
}
}
}
}
else if (((IconNode) simDir.getChildAt(i)).getChildCount() != 0) {
for (int j = 0; j < simDir.getChildAt(i).getChildCount(); j++) {
if (((IconNode) ((IconNode) simDir.getChildAt(i)).getChildAt(j)) == ((IconNode) select
.getLastPathComponent())) {
((IconNode) simDir.getChildAt(i)).remove(j);
File dir = new File(outDir + separator
+ ((IconNode) simDir.getChildAt(i)).getName()
+ separator
+ ((IconNode) select.getLastPathComponent()).getName()
+ "."
+ printer_id.substring(0, printer_id.length() - 8));
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
boolean checked = false;
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k))
.getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
((IconNode) simDir.getChildAt(i)).setIcon(MetalIconFactory
.getTreeFolderIcon());
((IconNode) simDir.getChildAt(i)).setIconName("");
}
int count = 0;
for (int k = 0; k < simDir.getChildAt(i).getChildCount(); k++) {
if (((IconNode) simDir.getChildAt(i).getChildAt(k))
.getChildCount() == 0) {
count++;
}
}
if (count == 3) {
File dir2 = new File(outDir + separator
+ ((IconNode) simDir.getChildAt(i)).getName());
if (dir2.isDirectory()) {
biomodelsim.deleteDir(dir2);
}
else {
dir2.delete();
}
directories.remove(((IconNode) simDir.getChildAt(i))
.getName());
for (int k = 0; k < graphed.size(); k++) {
if (graphed.get(k).getDirectory().equals(
((IconNode) simDir.getChildAt(i)).getName())) {
graphed.remove(k);
k
}
}
simDir.remove(i);
}
}
}
}
}
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
else if (e.getActionCommand().equals("delete runs")) {
for (int i = simDir.getChildCount() - 1; i >= 0; i
if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) {
if (!((IconNode) simDir.getChildAt(i)).getName().equals("Average")
&& !((IconNode) simDir.getChildAt(i)).getName().equals("Variance")
&& !((IconNode) simDir.getChildAt(i)).getName().equals(
"Standard Deviation")) {
File dir = new File(outDir + separator
+ ((IconNode) simDir.getChildAt(i)).getName() + "."
+ printer_id.substring(0, printer_id.length() - 8));
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
}
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
else if (e.getActionCommand().equals("delete all")) {
for (int i = simDir.getChildCount() - 1; i >= 0; i
if (((IconNode) simDir.getChildAt(i)).getChildCount() == 0) {
if (!((IconNode) simDir.getChildAt(i)).getName().equals("Average")
&& !((IconNode) simDir.getChildAt(i)).getName().equals("Variance")
&& !((IconNode) simDir.getChildAt(i)).getName().equals(
"Standard Deviation")) {
File dir = new File(outDir + separator
+ ((IconNode) simDir.getChildAt(i)).getName() + "."
+ printer_id.substring(0, printer_id.length() - 8));
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
}
simDir.remove(i);
}
else {
File dir = new File(outDir + separator
+ ((IconNode) simDir.getChildAt(i)).getName());
if (dir.isDirectory()) {
biomodelsim.deleteDir(dir);
}
else {
dir.delete();
}
simDir.remove(i);
}
}
boolean checked = false;
for (int i = 0; i < simDir.getChildCount(); i++) {
if (((IconNode) simDir.getChildAt(i)).getIconName().equals("" + (char) 10003)) {
checked = true;
}
}
if (!checked) {
simDir.setIcon(MetalIconFactory.getTreeFolderIcon());
simDir.setIconName("");
}
ArrayList<String> rows = new ArrayList<String>();
for (int i = 0; i < tree.getRowCount(); i++) {
if (tree.isExpanded(i)) {
tree.setSelectionRow(i);
rows.add(node.getName());
}
}
scrollpane = new JScrollPane();
refreshTree();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
TreeSelectionListener t = new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
}
};
tree.addTreeSelectionListener(t);
for (int i = 0; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (rows.contains(node.getName())) {
tree.expandRow(i);
}
}
tree.removeTreeSelectionListener(t);
addTreeListener();
}
// // if the export as jpeg button is clicked
// else if (e.getSource() == exportJPeg) {
// export(0);
// // if the export as png button is clicked
// else if (e.getSource() == exportPng) {
// export(1);
// // if the export as pdf button is clicked
// else if (e.getSource() == exportPdf) {
// export(2);
// // if the export as eps button is clicked
// else if (e.getSource() == exportEps) {
// export(3);
// // if the export as svg button is clicked
// else if (e.getSource() == exportSvg) {
// export(4);
// } else if (e.getSource() == exportCsv) {
// export(5);
}
/**
* Private method used to auto resize the graph.
*/
private void resize(XYSeriesCollection dataset) {
NumberFormat num = NumberFormat.getInstance();
num.setMaximumFractionDigits(4);
num.setGroupingUsed(false);
XYPlot plot = chart.getXYPlot();
XYItemRenderer rend = plot.getRenderer();
double minY = Double.MAX_VALUE;
double maxY = Double.MIN_VALUE;
double minX = Double.MAX_VALUE;
double maxX = Double.MIN_VALUE;
for (int j = 0; j < dataset.getSeriesCount(); j++) {
XYSeries series = dataset.getSeries(j);
double[][] seriesArray = series.toArray();
Boolean visible = rend.getSeriesVisible(j);
if (visible == null || visible.equals(true)) {
for (int k = 0; k < series.getItemCount(); k++) {
maxY = Math.max(seriesArray[1][k], maxY);
minY = Math.min(seriesArray[1][k], minY);
maxX = Math.max(seriesArray[0][k], maxX);
minX = Math.min(seriesArray[0][k], minX);
}
}
}
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
if (minY == Double.MAX_VALUE || maxY == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
// else if ((maxY - minY) < .001) {
// axis.setRange(minY - 1, maxY + 1);
else {
/*
* axis.setRange(Double.parseDouble(num.format(minY -
* (Math.abs(minY) .1))), Double .parseDouble(num.format(maxY +
* (Math.abs(maxY) .1))));
*/
if ((maxY - minY) < .001) {
axis.setStandardTickUnits(new StandardTickUnitSource());
}
else {
axis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
}
axis.setRange(minY - (Math.abs(minY) * .1), maxY + (Math.abs(maxY) * .1));
}
axis.setAutoTickUnitSelection(true);
if (LogY.isSelected()) {
try {
LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot().getRangeAxis()
.getLabel());
rangeAxis.setStrictValuesFlag(false);
plot.setRangeAxis(rangeAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame,
"Log plots are not allowed with data\nvalues less than or equal to zero.",
"Error", JOptionPane.ERROR_MESSAGE);
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis().getLabel());
plot.setRangeAxis(rangeAxis);
LogY.setSelected(false);
}
}
if (visibleLegend.isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
axis = (NumberAxis) plot.getDomainAxis();
if (minX == Double.MAX_VALUE || maxX == Double.MIN_VALUE) {
axis.setRange(-1, 1);
}
// else if ((maxX - minX) < .001) {
// axis.setRange(minX - 1, maxX + 1);
else {
if ((maxX - minX) < .001) {
axis.setStandardTickUnits(new StandardTickUnitSource());
}
else {
axis.setStandardTickUnits(NumberAxis.createStandardTickUnits());
}
axis.setRange(minX, maxX);
}
axis.setAutoTickUnitSelection(true);
if (LogX.isSelected()) {
try {
LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot().getDomainAxis()
.getLabel());
domainAxis.setStrictValuesFlag(false);
plot.setDomainAxis(domainAxis);
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame,
"Log plots are not allowed with data\nvalues less than or equal to zero.",
"Error", JOptionPane.ERROR_MESSAGE);
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis().getLabel());
plot.setRangeAxis(domainAxis);
LogX.setSelected(false);
}
}
}
/**
* After the chart is redrawn, this method calculates the x and y scale and
* updates those text fields.
*/
public void chartProgress(ChartProgressEvent e) {
// if the chart drawing is started
if (e.getType() == ChartProgressEvent.DRAWING_STARTED) {
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
// if the chart drawing is finished
else if (e.getType() == ChartProgressEvent.DRAWING_FINISHED) {
this.setCursor(null);
JFreeChart chart = e.getChart();
XYPlot plot = (XYPlot) chart.getXYPlot();
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
YMin.setText("" + axis.getLowerBound());
YMax.setText("" + axis.getUpperBound());
YScale.setText("" + axis.getTickUnit().getSize());
axis = (NumberAxis) plot.getDomainAxis();
XMin.setText("" + axis.getLowerBound());
XMax.setText("" + axis.getUpperBound());
XScale.setText("" + axis.getTickUnit().getSize());
}
}
/**
* Invoked when the mouse is clicked on the chart. Allows the user to edit
* the title and labels of the chart.
*/
public void mouseClicked(MouseEvent e) {
if (e.getSource() != tree) {
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
if (timeSeries) {
editGraph();
}
else {
editProbGraph();
}
}
}
}
public void mousePressed(MouseEvent e) {
if (e.getSource() == tree) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
if (selRow < 0)
return;
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
boolean set = true;
for (TreePath p : tree.getSelectionPaths()) {
if (p.equals(selPath)) {
tree.addSelectionPath(selPath);
set = false;
}
}
if (set) {
tree.setSelectionPath(selPath);
}
if (e.isPopupTrigger()) {
popup.removeAll();
if (node.getChildCount() != 0 && node.getParent() != null) {
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.setActionCommand("rename");
popup.add(rename);
}
if (node.getParent() != null) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.setActionCommand("delete");
popup.add(delete);
}
else {
JMenuItem delete = new JMenuItem("Delete All Runs");
delete.addActionListener(this);
delete.setActionCommand("delete runs");
popup.add(delete);
JMenuItem deleteAll = new JMenuItem("Delete Recursive");
deleteAll.addActionListener(this);
deleteAll.setActionCommand("delete all");
popup.add(deleteAll);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
public void mouseReleased(MouseEvent e) {
if (e.getSource() == tree) {
int selRow = tree.getRowForLocation(e.getX(), e.getY());
if (selRow < 0)
return;
TreePath selPath = tree.getPathForLocation(e.getX(), e.getY());
boolean set = true;
for (TreePath p : tree.getSelectionPaths()) {
if (p.equals(selPath)) {
tree.addSelectionPath(selPath);
set = false;
}
}
if (set) {
tree.setSelectionPath(selPath);
}
if (e.isPopupTrigger()) {
popup.removeAll();
if (node.getChildCount() != 0 && node.getParent() != null) {
JMenuItem rename = new JMenuItem("Rename");
rename.addActionListener(this);
rename.setActionCommand("rename");
popup.add(rename);
}
if (node.getParent() != null) {
JMenuItem delete = new JMenuItem("Delete");
delete.addActionListener(this);
delete.setActionCommand("delete");
popup.add(delete);
}
else {
JMenuItem delete = new JMenuItem("Delete All Runs");
delete.addActionListener(this);
delete.setActionCommand("delete runs");
popup.add(delete);
JMenuItem deleteAll = new JMenuItem("Delete Recursive");
deleteAll.addActionListener(this);
deleteAll.setActionCommand("delete all");
popup.add(deleteAll);
}
if (popup.getComponentCount() != 0) {
popup.show(e.getComponent(), e.getX(), e.getY());
}
}
}
}
/**
* This method currently does nothing.
*/
public void mouseEntered(MouseEvent e) {
}
/**
* This method currently does nothing.
*/
public void mouseExited(MouseEvent e) {
}
private void setUpShapesAndColors() {
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
colors = new HashMap<String, Paint>();
shapes = new HashMap<String, Shape>();
colors.put("Red", draw.getNextPaint());
colors.put("Blue", draw.getNextPaint());
colors.put("Green", draw.getNextPaint());
colors.put("Yellow", draw.getNextPaint());
colors.put("Magenta", draw.getNextPaint());
colors.put("Cyan", draw.getNextPaint());
colors.put("Tan", draw.getNextPaint());
colors.put("Gray (Dark)", draw.getNextPaint());
colors.put("Red (Dark)", draw.getNextPaint());
colors.put("Blue (Dark)", draw.getNextPaint());
colors.put("Green (Dark)", draw.getNextPaint());
colors.put("Yellow (Dark)", draw.getNextPaint());
colors.put("Magenta (Dark)", draw.getNextPaint());
colors.put("Cyan (Dark)", draw.getNextPaint());
colors.put("Black", draw.getNextPaint());
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
draw.getNextPaint();
// colors.put("Red ", draw.getNextPaint());
// colors.put("Blue ", draw.getNextPaint());
// colors.put("Green ", draw.getNextPaint());
// colors.put("Yellow ", draw.getNextPaint());
// colors.put("Magenta ", draw.getNextPaint());
// colors.put("Cyan ", draw.getNextPaint());
colors.put("Gray", draw.getNextPaint());
colors.put("Red (Extra Dark)", draw.getNextPaint());
colors.put("Blue (Extra Dark)", draw.getNextPaint());
colors.put("Green (Extra Dark)", draw.getNextPaint());
colors.put("Yellow (Extra Dark)", draw.getNextPaint());
colors.put("Magenta (Extra Dark)", draw.getNextPaint());
colors.put("Cyan (Extra Dark)", draw.getNextPaint());
colors.put("Red (Light)", draw.getNextPaint());
colors.put("Blue (Light)", draw.getNextPaint());
colors.put("Green (Light)", draw.getNextPaint());
colors.put("Yellow (Light)", draw.getNextPaint());
colors.put("Magenta (Light)", draw.getNextPaint());
colors.put("Cyan (Light)", draw.getNextPaint());
colors.put("Gray (Light)", new java.awt.Color(238, 238, 238));
shapes.put("Square", draw.getNextShape());
shapes.put("Circle", draw.getNextShape());
shapes.put("Triangle", draw.getNextShape());
shapes.put("Diamond", draw.getNextShape());
shapes.put("Rectangle (Horizontal)", draw.getNextShape());
shapes.put("Triangle (Upside Down)", draw.getNextShape());
shapes.put("Circle (Half)", draw.getNextShape());
shapes.put("Arrow", draw.getNextShape());
shapes.put("Rectangle (Vertical)", draw.getNextShape());
shapes.put("Arrow (Backwards)", draw.getNextShape());
}
public void editGraph() {
final ArrayList<GraphSpecies> old = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
old.add(g);
}
titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getXYPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getXYPlot().getRangeAxis().getLabel(), 5);
final JLabel xMin = new JLabel("X-Min:");
final JLabel xMax = new JLabel("X-Max:");
final JLabel xScale = new JLabel("X-Step:");
final JLabel yMin = new JLabel("Y-Min:");
final JLabel yMax = new JLabel("Y-Max:");
final JLabel yScale = new JLabel("Y-Step:");
LogX.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
XYPlot plot = (XYPlot) chart.getXYPlot();
try {
LogarithmicAxis domainAxis = new LogarithmicAxis(chart.getXYPlot()
.getDomainAxis().getLabel());
domainAxis.setStrictValuesFlag(false);
plot.setRangeAxis(domainAxis);
}
catch (Exception e1) {
JOptionPane
.showMessageDialog(
Gui.frame,
"Log plots are not allowed with data\nvalues less than or equal to zero.",
"Error", JOptionPane.ERROR_MESSAGE);
NumberAxis domainAxis = new NumberAxis(chart.getXYPlot().getDomainAxis()
.getLabel());
plot.setRangeAxis(domainAxis);
LogX.setSelected(false);
}
}
}
});
LogY.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
XYPlot plot = (XYPlot) chart.getXYPlot();
try {
LogarithmicAxis rangeAxis = new LogarithmicAxis(chart.getXYPlot()
.getRangeAxis().getLabel());
rangeAxis.setStrictValuesFlag(false);
plot.setRangeAxis(rangeAxis);
}
catch (Exception e1) {
JOptionPane
.showMessageDialog(
Gui.frame,
"Semilog plots are not allowed with data\nvalues less than or equal to zero.",
"Error", JOptionPane.ERROR_MESSAGE);
NumberAxis rangeAxis = new NumberAxis(chart.getXYPlot().getRangeAxis()
.getLabel());
plot.setRangeAxis(rangeAxis);
LogY.setSelected(false);
}
}
}
});
visibleLegend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
}
});
resize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
}
});
if (resize.isSelected()) {
xMin.setEnabled(false);
XMin.setEnabled(false);
xMax.setEnabled(false);
XMax.setEnabled(false);
xScale.setEnabled(false);
XScale.setEnabled(false);
yMin.setEnabled(false);
YMin.setEnabled(false);
yMax.setEnabled(false);
YMax.setEnabled(false);
yScale.setEnabled(false);
YScale.setEnabled(false);
}
else {
xMin.setEnabled(true);
XMin.setEnabled(true);
xMax.setEnabled(true);
XMax.setEnabled(true);
xScale.setEnabled(true);
XScale.setEnabled(true);
yMin.setEnabled(true);
YMin.setEnabled(true);
yMax.setEnabled(true);
YMax.setEnabled(true);
yScale.setEnabled(true);
YScale.setEnabled(true);
}
Properties p = null;
if (learnSpecs != null) {
try {
String[] split = outDir.split(separator);
p = new Properties();
FileInputStream load = new FileInputStream(new File(outDir + separator
+ split[split.length - 1] + ".lrn"));
p.load(load);
load.close();
}
catch (Exception e) {
}
}
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
simDir = new IconNode(simDirString, simDirString);
simDir.setIconName("");
String[] files = new File(outDir).list();
// for (int i = 1; i < files.length; i++) {
// String index = files[i];
// int j = i;
// while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
// files[j] = files[j - 1];
// j = j - 1;
// files[j] = index;
boolean add = false;
boolean addTerm = false;
boolean addPercent = false;
boolean addConst = false;
directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3
&& file.substring(file.length() - 4).equals(
"." + printer_id.substring(0, printer_id.length() - 8))) {
if (file.contains("run-") || file.contains("mean") || file.contains("variance")
|| file.contains("standard_deviation")) {
add = true;
}
else if (file.startsWith("term-time")) {
addTerm = true;
}
else if (file.contains("percent-term-time")) {
addPercent = true;
}
else if (file.contains("sim-rep")) {
addConst = true;
}
else {
IconNode n = new IconNode(file.substring(0, file.length() - 4), file.substring(
0, file.length() - 4));
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if (simDir.getChildAt(j).toString().compareToIgnoreCase(n.toString()) > 0) {
simDir.insert(n, j);
added = true;
break;
}
}
if (!added) {
simDir.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(file.substring(0, file.length() - 4))
&& g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
String[] files3 = new File(outDir + separator + file).list();
// for (int i = 1; i < files3.length; i++) {
// String index = files3[i];
// int j = i;
// while ((j > 0) && files3[j - 1].compareToIgnoreCase(index) >
// files3[j] = files3[j - 1];
// j = j - 1;
// files3[j] = index;
for (String getFile : files3) {
if (getFile.length() > 3
&& getFile.substring(getFile.length() - 4).equals(
"." + printer_id.substring(0, printer_id.length() - 8))) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile)
.isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator
+ getFile).list()) {
if (getFile2.length() > 3
&& getFile2.substring(getFile2.length() - 4).equals(
"." + printer_id.substring(0, printer_id.length() - 8))) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
IconNode d = new IconNode(file, file);
d.setIconName("");
boolean add2 = false;
boolean addTerm2 = false;
boolean addPercent2 = false;
boolean addConst2 = false;
for (String f : files3) {
if (f.contains(printer_id.substring(0, printer_id.length() - 8))) {
if (f.contains("run-") || f.contains("mean") || f.contains("variance")
|| f.contains("standard_deviation")) {
add2 = true;
}
else if (f.startsWith("term-time")) {
addTerm2 = true;
}
else if (f.contains("percent-term-time")) {
addPercent2 = true;
}
else if (f.contains("sim-rep")) {
addConst2 = true;
}
else {
IconNode n = new IconNode(f.substring(0, f.length() - 4), f
.substring(0, f.length() - 4));
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if (d.getChildAt(j).toString()
.compareToIgnoreCase(n.toString()) > 0) {
d.insert(n, j);
added = true;
break;
}
}
if (!added) {
d.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(f.substring(0, f.length() - 4))
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
String[] files2 = new File(outDir + separator + file + separator + f)
.list();
// for (int i = 1; i < files2.length; i++) {
// String index = files2[i];
// int j = i;
// while ((j > 0) && files2[j -
// 1].compareToIgnoreCase(index) > 0) {
// files2[j] = files2[j - 1];
// j = j - 1;
// files2[j] = index;
for (String getFile2 : files2) {
if (getFile2.length() > 3
&& getFile2.substring(getFile2.length() - 4).equals(
"."
+ printer_id.substring(0, printer_id
.length() - 8))) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
IconNode d2 = new IconNode(f, f);
d2.setIconName("");
boolean add3 = false;
boolean addTerm3 = false;
boolean addPercent3 = false;
boolean addConst3 = false;
for (String f2 : files2) {
if (f2.contains(printer_id
.substring(0, printer_id.length() - 8))) {
if (f2.contains("run-") || f2.contains("mean")
|| f2.contains("variance")
|| f2.contains("standard_deviation")) {
add3 = true;
}
else if (f2.startsWith("term-time")) {
addTerm3 = true;
}
else if (f2.contains("percent-term-time")) {
addPercent3 = true;
}
else if (f2.contains("sim-rep")) {
addConst3 = true;
}
else {
IconNode n = new IconNode(f2.substring(0,
f2.length() - 4), f2.substring(0,
f2.length() - 4));
boolean added = false;
for (int j = 0; j < d2.getChildCount(); j++) {
if (d2.getChildAt(j).toString()
.compareToIgnoreCase(n.toString()) > 0) {
d2.insert(n, j);
added = true;
break;
}
}
if (!added) {
d2.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(
f2.substring(0, f2.length() - 4))
&& g.getDirectory().equals(
d.getName() + separator
+ d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
if (add3) {
IconNode n = new IconNode("Average", "Average");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average")
&& g.getDirectory().equals(
d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d
.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Standard Deviation", "Standard Deviation");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation")
&& g.getDirectory().equals(
d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d
.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Variance", "Variance");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance")
&& g.getDirectory().equals(
d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d
.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm3) {
IconNode n = new IconNode("Termination Time",
"Termination Time");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time")
&& g.getDirectory().equals(
d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d
.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent3) {
IconNode n = new IconNode("Percent Termination",
"Percent Termination");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination")
&& g.getDirectory().equals(
d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d
.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst3) {
IconNode n = new IconNode("Constraint Termination",
"Constraint Termination");
d2.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination")
&& g.getDirectory().equals(
d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d
.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String r2 = null;
for (String s : files2) {
if (s.contains("run-")) {
r2 = s;
}
}
if (r2 != null) {
for (String s : files2) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat")
|| end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer
.parseInt(s.substring(4, s.length()
- end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + f
+ separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-"
+ (i + 1)
+ "."
+ printer_id.substring(0, printer_id
.length() - 8)), "run-" + (i + 1));
if (d2.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < d2.getChildCount(); j++) {
if (d2
.getChildAt(j)
.toString()
.compareToIgnoreCase(
(String) p
.get("run-"
+ (i + 1)
+ "."
+ printer_id
.substring(
0,
printer_id
.length() - 8))) > 0) {
d2.insert(n, j);
added = true;
break;
}
}
if (!added) {
d2.add(n);
}
}
else {
d2.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
d2.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1))
&& g.getDirectory().equals(
d.getName() + separator
+ d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if ((d.getChildAt(j).toString().compareToIgnoreCase(
d2.toString()) > 0)
|| new File(
outDir
+ separator
+ d.toString()
+ separator
+ (d.getChildAt(j).toString() + "." + printer_id
.substring(0, printer_id
.length() - 8)))
.isFile()) {
d.insert(d2, j);
added = true;
break;
}
}
if (!added) {
d.add(d2);
}
}
}
}
if (add2) {
IconNode n = new IconNode("Average", "Average");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average")
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Standard Deviation", "Standard Deviation");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation")
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Variance", "Variance");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance")
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm2) {
IconNode n = new IconNode("Termination Time", "Termination Time");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time")
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent2) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination")
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst2) {
IconNode n = new IconNode("Constraint Termination",
"Constraint Termination");
d.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination")
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String r = null;
for (String s : files3) {
if (s.contains("run-")) {
r = s;
}
}
if (r != null) {
for (String s : files3) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s
.length()
- end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + file + separator + "run-" + (i + 1)
+ "." + printer_id.substring(0, printer_id.length() - 8))
.exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)),
"run-" + (i + 1));
if (d.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < d.getChildCount(); j++) {
if (d.getChildAt(j).toString().compareToIgnoreCase(
(String) p.get("run-"
+ (i + 1)
+ "."
+ printer_id.substring(0, printer_id
.length() - 8))) > 0) {
d.insert(n, j);
added = true;
break;
}
}
if (!added) {
d.add(n);
}
}
else {
d.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
d.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1))
&& g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0)
|| new File(outDir
+ separator
+ (simDir.getChildAt(j).toString() + "." + printer_id
.substring(0, printer_id.length() - 8))).isFile()) {
simDir.insert(d, j);
added = true;
break;
}
}
if (!added) {
simDir.add(d);
}
}
}
}
if (add) {
IconNode n = new IconNode("Average", "Average");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Average") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Standard Deviation", "Standard Deviation");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Standard Deviation") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
n = new IconNode("Variance", "Variance");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Variance") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addTerm) {
IconNode n = new IconNode("Termination Time", "Termination Time");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Termination Time") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addPercent) {
IconNode n = new IconNode("Percent Termination", "Percent Termination");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Percent Termination") && g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (addConst) {
IconNode n = new IconNode("Constraint Termination", "Constraint Termination");
simDir.add(n);
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("Constraint Termination")
&& g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
int run = 1;
String runs = null;
for (String s : new File(outDir).list()) {
if (s.contains("run-")) {
runs = s;
}
}
if (runs != null) {
for (String s : new File(outDir).list()) {
if (s.length() > 4) {
String end = "";
for (int j = 1; j < 5; j++) {
end = s.charAt(s.length() - j) + end;
}
if (end.equals(".tsd") || end.equals(".dat") || end.equals(".csv")) {
if (s.contains("run-")) {
run = Math.max(run, Integer.parseInt(s.substring(4, s.length()
- end.length())));
}
}
}
}
for (int i = 0; i < run; i++) {
if (new File(outDir + separator + "run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
IconNode n;
if (learnSpecs != null) {
n = new IconNode(p.get("run-" + (i + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)), "run-"
+ (i + 1));
if (simDir.getChildCount() > 3) {
boolean added = false;
for (int j = 3; j < simDir.getChildCount(); j++) {
if (simDir.getChildAt(j).toString()
.compareToIgnoreCase(
(String) p.get("run-"
+ (i + 1)
+ "."
+ printer_id.substring(0, printer_id
.length() - 8))) > 0) {
simDir.insert(n, j);
added = true;
break;
}
}
if (!added) {
simDir.add(n);
}
}
else {
simDir.add(n);
}
}
else {
n = new IconNode("run-" + (i + 1), "run-" + (i + 1));
simDir.add(n);
}
n.setIconName("");
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals("run-" + (i + 1))
&& g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "No data to graph."
+ "\nPerform some simulations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
all = new JPanel(new BorderLayout());
specPanel = new JPanel();
scrollpane = new JScrollPane();
refreshTree();
addTreeListener();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
scroll = new JScrollPane();
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
// JButton ok = new JButton("Ok");
/*
* ok.addActionListener(new ActionListener() { public void
* actionPerformed(ActionEvent e) { double minY; double maxY; double
* scaleY; double minX; double maxX; double scaleX; change = true;
* try { minY = Double.parseDouble(YMin.getText().trim()); maxY =
* Double.parseDouble(YMax.getText().trim()); scaleY =
* Double.parseDouble(YScale.getText().trim()); minX =
* Double.parseDouble(XMin.getText().trim()); maxX =
* Double.parseDouble(XMax.getText().trim()); scaleX =
* Double.parseDouble(XScale.getText().trim()); NumberFormat num =
* NumberFormat.getInstance(); num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX)); } catch (Exception e1) {
* JOptionPane.showMessageDialog(BioSim.frame, "Must enter doubles
* into the inputs " + "to change the graph's dimensions!", "Error",
* JOptionPane.ERROR_MESSAGE); return; } lastSelected = selected;
* selected = ""; ArrayList<XYSeries> graphData = new
* ArrayList<XYSeries>(); XYLineAndShapeRenderer rend =
* (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); int
* thisOne = -1; for (int i = 1; i < graphed.size(); i++) {
* GraphSpecies index = graphed.get(i); int j = i; while ((j > 0) &&
* (graphed.get(j -
* 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
* graphed.set(j, graphed.get(j - 1)); j = j - 1; } graphed.set(j,
* index); } ArrayList<GraphSpecies> unableToGraph = new
* ArrayList<GraphSpecies>(); HashMap<String,
* ArrayList<ArrayList<Double>>> allData = new HashMap<String,
* ArrayList<ArrayList<Double>>>(); for (GraphSpecies g : graphed) {
* if (g.getDirectory().equals("")) { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new
* File(outDir + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8)).exists()) {
* readGraphSpecies(outDir + separator + g.getRunNumber() + "." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getRunNumber() +
* "." + printer_id.substring(0, printer_id.length() - 8),
* BioSim.frame, y.getText().trim(), g.getRunNumber(), null); for
* (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir).list()) { if
* (s.length() > 3 && s.substring(0, 4).equals("run-")) {
* ableToGraph = true; } } } catch (Exception e1) { ableToGraph =
* false; } if (ableToGraph) { int next = 1; while (!new File(outDir
* + separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + "run-" + next + "." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + "run-1." +
* printer_id.substring(0, printer_id.length() - 8), BioSim.frame,
* y.getText().trim(), g.getRunNumber().toLowerCase(), null); for
* (int i = 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } else { thisOne++;
* rend.setSeriesVisible(thisOne, true);
* rend.setSeriesLinesVisible(thisOne, g.getConnected());
* rend.setSeriesShapesFilled(thisOne, g.getFilled());
* rend.setSeriesShapesVisible(thisOne, g.getVisible());
* rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
* rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape()); if
* (!g.getRunNumber().equals("Average") &&
* !g.getRunNumber().equals("Variance") &&
* !g.getRunNumber().equals("Standard Deviation")) { if (new
* File(outDir + separator + g.getDirectory() + separator +
* g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { readGraphSpecies( outDir +
* separator + g.getDirectory() + separator + g.getRunNumber() + "."
* + printer_id.substring(0, printer_id.length() - 8),
* BioSim.frame); ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getDirectory() +
* separator + g.getRunNumber() + "." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame, y.getText().trim(),
* g.getRunNumber(), g.getDirectory()); for (int i = 2; i <
* graphSpecies.size(); i++) { String index = graphSpecies.get(i);
* ArrayList<Double> index2 = data.get(i); int j = i; while ((j > 1)
* && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
* graphSpecies.set(j, graphSpecies.get(j - 1)); data.set(j,
* data.get(j - 1)); j = j - 1; } graphSpecies.set(j, index);
* data.set(j, index2); } allData.put(g.getRunNumber() + " " +
* g.getDirectory(), data); } graphData.add(new
* XYSeries(g.getSpecies())); if (data.size() != 0) { for (int i =
* 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } else { boolean ableToGraph =
* false; try { for (String s : new File(outDir + separator +
* g.getDirectory()).list()) { if (s.length() > 3 && s.substring(0,
* 4).equals("run-")) { ableToGraph = true; } } } catch (Exception
* e1) { ableToGraph = false; } if (ableToGraph) { int next = 1;
* while (!new File(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8)).exists()) { next++; }
* readGraphSpecies(outDir + separator + g.getDirectory() +
* separator + "run-" + next + "." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame);
* ArrayList<ArrayList<Double>> data; if
* (allData.containsKey(g.getRunNumber() + " " + g.getDirectory()))
* { data = allData.get(g.getRunNumber() + " " + g.getDirectory());
* } else { data = readData(outDir + separator + g.getDirectory() +
* separator + "run-1." + printer_id.substring(0,
* printer_id.length() - 8), BioSim.frame, y.getText().trim(),
* g.getRunNumber().toLowerCase(), g.getDirectory()); for (int i =
* 2; i < graphSpecies.size(); i++) { String index =
* graphSpecies.get(i); ArrayList<Double> index2 = data.get(i); int
* j = i; while ((j > 1) && graphSpecies.get(j -
* 1).compareToIgnoreCase(index) > 0) { graphSpecies.set(j,
* graphSpecies.get(j - 1)); data.set(j, data.get(j - 1)); j = j -
* 1; } graphSpecies.set(j, index); data.set(j, index2); }
* allData.put(g.getRunNumber() + " " + g.getDirectory(), data); }
* graphData.add(new XYSeries(g.getSpecies())); if (data.size() !=
* 0) { for (int i = 0; i < (data.get(0)).size(); i++) {
* graphData.get(graphData.size() - 1).add((data.get(0)).get(i),
* (data.get(g.getNumber() + 1)).get(i)); } } } else {
* unableToGraph.add(g); thisOne--; } } } } for (GraphSpecies g :
* unableToGraph) { graphed.remove(g); } XYSeriesCollection dataset
* = new XYSeriesCollection(); for (int i = 0; i < graphData.size();
* i++) { dataset.addSeries(graphData.get(i)); }
* fixGraph(title.getText().trim(), x.getText().trim(),
* y.getText().trim(), dataset);
* chart.getXYPlot().setRenderer(rend); XYPlot plot =
* chart.getXYPlot(); if (resize.isSelected()) { resize(dataset); }
* else { NumberAxis axis = (NumberAxis) plot.getRangeAxis();
* axis.setAutoTickUnitSelection(false); axis.setRange(minY, maxY);
* axis.setTickUnit(new NumberTickUnit(scaleY)); axis = (NumberAxis)
* plot.getDomainAxis(); axis.setAutoTickUnitSelection(false);
* axis.setRange(minX, maxX); axis.setTickUnit(new
* NumberTickUnit(scaleX)); } //f.dispose(); } });
*/
// final JButton cancel = new JButton("Cancel");
// cancel.addActionListener(new ActionListener() {
// public void actionPerformed(ActionEvent e) {
// selected = "";
// int size = graphed.size();
// for (int i = 0; i < size; i++) {
// graphed.remove();
// for (GraphSpecies g : old) {
// graphed.add(g);
// f.dispose();
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
IconNode n = simDir;
while (n != null) {
if (n.isLeaf()) {
n.setIcon(MetalIconFactory.getTreeLeafIcon());
n.setIconName("");
IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent())
.getChildAfter(n);
if (check == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n
.getParent()).getChildAfter(n);
if (check2 == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
n = (IconNode) ((DefaultMutableTreeNode) n.getParent())
.getChildAfter(n);
}
}
else {
n = check2;
}
}
}
else {
n = check;
}
}
else {
n.setIcon(MetalIconFactory.getTreeFolderIcon());
n.setIconName("");
n = (IconNode) n.getChildAt(0);
}
}
tree.revalidate();
tree.repaint();
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(3, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xMin);
titlePanel1.add(XMin);
titlePanel1.add(yMin);
titlePanel1.add(YMin);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(xMax);
titlePanel1.add(XMax);
titlePanel1.add(yMax);
titlePanel1.add(YMax);
titlePanel1.add(yLabel);
titlePanel1.add(y);
titlePanel1.add(xScale);
titlePanel1.add(XScale);
titlePanel1.add(yScale);
titlePanel1.add(YScale);
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(resize);
titlePanel2.add(XVariable);
titlePanel2.add(LogX);
titlePanel2.add(LogY);
titlePanel2.add(visibleLegend);
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
// JPanel buttonPanel = new JPanel();
// buttonPanel.add(ok);
// buttonPanel.add(deselect);
// buttonPanel.add(cancel);
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
// all.add(buttonPanel, "South");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane
.showOptionDialog(Gui.frame, all, "Edit Graph", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
if (value == JOptionPane.YES_OPTION) {
double minY;
double maxY;
double scaleY;
double minX;
double maxX;
double scaleX;
change = true;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
/*
* NumberFormat num = NumberFormat.getInstance();
* num.setMaximumFractionDigits(4);
* num.setGroupingUsed(false); minY =
* Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX));
*/
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Must enter doubles into the inputs "
+ "to change the graph's dimensions!", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
lastSelected = selected;
selected = "";
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot()
.getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0)
&& (graphed.get(j - 1).getSpecies().compareToIgnoreCase(
index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average")
&& !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
next++;
}
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " "
+ g.getDirectory())) {
data = allData.get(g.getRunNumber() + " "
+ g.getDirectory());
}
else {
data = readData(outDir + separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8),
g.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData
.put(g.getRunNumber() + " " + g.getDirectory(),
data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average")
&& !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber(), g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator
+ "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator
+ "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator
+ "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator
+ "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator
+ "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator
+ "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory())
.list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e1) {
ableToGraph = false;
}
if (ableToGraph) {
int next = 1;
while (!new File(outDir + separator + g.getDirectory()
+ separator + "run-" + next + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
next++;
}
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " "
+ g.getDirectory())) {
data = allData.get(g.getRunNumber() + " "
+ g.getDirectory());
}
else {
data = readData(outDir + separator + g.getDirectory()
+ separator + "run-1."
+ printer_id.substring(0, printer_id.length() - 8),
g.getRunNumber().toLowerCase(), g.getDirectory(),
false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(
index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData
.put(g.getRunNumber() + " " + g.getDirectory(),
data);
}
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
else {
selected = "";
int size = graphed.size();
for (int i = 0; i < size; i++) {
graphed.remove();
}
for (GraphSpecies g : old) {
graphed.add(g);
}
}
// WindowListener w = new WindowListener() {
// public void windowClosing(WindowEvent arg0) {
// cancel.doClick();
// public void windowOpened(WindowEvent arg0) {
// public void windowClosed(WindowEvent arg0) {
// public void windowIconified(WindowEvent arg0) {
// public void windowDeiconified(WindowEvent arg0) {
// public void windowActivated(WindowEvent arg0) {
// public void windowDeactivated(WindowEvent arg0) {
// f.addWindowListener(w);
// f.setContentPane(all);
// f.pack();
// Dimension screenSize;
// try {
// Toolkit tk = Toolkit.getDefaultToolkit();
// screenSize = tk.getScreenSize();
// catch (AWTError awe) {
// screenSize = new Dimension(640, 480);
// Dimension frameSize = f.getSize();
// if (frameSize.height > screenSize.height) {
// frameSize.height = screenSize.height;
// if (frameSize.width > screenSize.width) {
// frameSize.width = screenSize.width;
// int xx = screenSize.width / 2 - frameSize.width / 2;
// int yy = screenSize.height / 2 - frameSize.height / 2;
// f.setLocation(xx, yy);
// f.setVisible(true);
}
}
private void refreshTree() {
tree = new JTree(simDir);
if (!topLevel && learnSpecs == null) {
tree.addMouseListener(this);
}
tree.putClientProperty("JTree.icons", makeIcons());
tree.setCellRenderer(new IconNodeRenderer());
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon());
renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon());
renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon());
}
private void addTreeListener() {
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.getName())
&& node.getParent() != null
&& !directories.contains(((IconNode) node.getParent()).getName()
+ separator + node.getName())) {
selected = node.getName();
int select;
if (selected.equals("Average")) {
select = 0;
}
else if (selected.equals("Variance")) {
select = 1;
}
else if (selected.equals("Standard Deviation")) {
select = 2;
}
else if (selected.contains("-run")) {
select = 0;
}
else if (selected.equals("Termination Time")) {
select = 0;
}
else if (selected.equals("Percent Termination")) {
select = 0;
}
else if (selected.equals("Constraint Termination")) {
select = 0;
}
else {
try {
if (selected.contains("run-")) {
select = Integer.parseInt(selected.substring(4)) + 2;
}
else {
select = -1;
}
}
catch (Exception e1) {
select = -1;
}
}
if (select != -1) {
specPanel.removeAll();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent())
.getName()
+ separator + ((IconNode) node.getParent()).getName())) {
specPanel.add(fixGraphChoices(((IconNode) node.getParent().getParent())
.getName()
+ separator + ((IconNode) node.getParent()).getName()));
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
specPanel.add(fixGraphChoices(((IconNode) node.getParent()).getName()));
}
else {
specPanel.add(fixGraphChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphSpecies.get(i + 1));
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent().getParent())
.getName()
+ separator + ((IconNode) node.getParent()).getName())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals(
((IconNode) node.getParent().getParent()).getName()
+ separator
+ ((IconNode) node.getParent()).getName())) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground(
(Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground(
(Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals(
((IconNode) node.getParent()).getName())) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground(
(Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground(
(Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected)
&& g.getDirectory().equals("")) {
XVariable.setSelectedIndex(g.getXNumber());
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground(
(Color) g.getShapeAndPaint().getPaint());
colorsButtons.get(g.getNumber()).setForeground(
(Color) g.getShapeAndPaint().getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getPaintName().split("_")[0]);
shapesCombo.get(g.getNumber()).setSelectedItem(
g.getShapeAndPaint().getShapeName());
connected.get(g.getNumber()).setSelected(g.getConnected());
visible.get(g.getNumber()).setSelected(g.getVisible());
filled.get(g.getNumber()).setSelected(g.getFilled());
}
}
}
boolean allChecked = true;
boolean allCheckedVisible = true;
boolean allCheckedFilled = true;
boolean allCheckedConnected = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
s = ((IconNode) e.getPath().getLastPathComponent()).toString();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent()
.getParent()).getName()
+ separator
+ ((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ s + ")";
}
}
else if (directories.contains(((IconNode) node.getParent())
.getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = graphSpecies.get(i + 1);
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
series.get(i).setText(text);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colors.get("Black"));
colorsButtons.get(i).setForeground((Color) colors.get("Black"));
shapesCombo.get(i).setSelectedIndex(0);
}
else {
String s = "";
s = ((IconNode) e.getPath().getLastPathComponent()).toString();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent()
.getParent()).getName()
+ separator
+ ((IconNode) node.getParent()).getName())) {
if (s.equals("Average")) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ", "
+ s + ")";
}
}
else if (directories.contains(((IconNode) node.getParent())
.getName())) {
if (s.equals("Average")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + ((IconNode) node.getParent()).getName() + ", "
+ s + ")";
}
}
else {
if (s.equals("Average")) {
s = "(" + (char) 967 + ")";
}
else if (s.equals("Variance")) {
s = "(" + (char) 948 + (char) 178 + ")";
}
else if (s.equals("Standard Deviation")) {
s = "(" + (char) 948 + ")";
}
else {
if (s.endsWith("-run")) {
s = s.substring(0, s.length() - 4);
}
else if (s.startsWith("run-")) {
s = s.substring(4);
}
s = "(" + s + ")";
}
}
String text = series.get(i).getText();
String end = "";
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
boxes.get(i).setName(text);
}
if (!visible.get(i).isSelected()) {
allCheckedVisible = false;
}
if (!connected.get(i).isSelected()) {
allCheckedConnected = false;
}
if (!filled.get(i).isSelected()) {
allCheckedFilled = false;
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
if (allCheckedVisible) {
visibleLabel.setSelected(true);
}
else {
visibleLabel.setSelected(false);
}
if (allCheckedFilled) {
filledLabel.setSelected(true);
}
else {
filledLabel.setSelected(false);
}
if (allCheckedConnected) {
connectedLabel.setSelected(true);
}
else {
connectedLabel.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
}
private JPanel fixGraphChoices(final String directory) {
if (directory.equals("")) {
if (selected.equals("Average") || selected.equals("Variance")
|| selected.equals("Standard Deviation") || selected.equals("Termination Time")
|| selected.equals("Percent Termination")
|| selected.equals("Constraint Termination")) {
if (selected.equals("Average")
&& new File(outDir + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Variance")
&& new File(outDir + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Termination Time")
&& new File(outDir + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else {
int nextOne = 1;
while (!new File(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
}
else {
readGraphSpecies(outDir + separator + selected + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
}
else {
if (selected.equals("Average") || selected.equals("Variance")
|| selected.equals("Standard Deviation") || selected.equals("Termination Time")
|| selected.equals("Percent Termination")
|| selected.equals("Constraint Termination")) {
if (selected.equals("Average")
&& new File(outDir + separator + directory + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Variance")
&& new File(outDir + separator + directory + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Standard Deviation")
&& new File(outDir + separator + directory + separator
+ "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator
+ "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Termination Time")
&& new File(outDir + separator + directory + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Percent Termination")
&& new File(outDir + separator + directory + separator
+ "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator
+ "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (selected.equals("Constraint Termination")
&& new File(outDir + separator + directory + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
readGraphSpecies(outDir + separator + directory + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else {
int nextOne = 1;
while (!new File(outDir + separator + directory + separator + "run-" + nextOne
+ "." + printer_id.substring(0, printer_id.length() - 8)).exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + directory + separator + "run-" + nextOne
+ "." + printer_id.substring(0, printer_id.length() - 8));
}
}
else {
readGraphSpecies(outDir + separator + directory + separator + selected + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1) && graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
JPanel speciesPanel1 = new JPanel(new GridLayout(graphSpecies.size(), 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphSpecies.size(), 3));
JPanel speciesPanel3 = new JPanel(new GridLayout(graphSpecies.size(), 3));
use = new JCheckBox("Use");
JLabel specs;
if (biomodelsim.lema || biomodelsim.atacs) {
specs = new JLabel("Variables");
}
else {
specs = new JLabel("Species");
}
JLabel color = new JLabel("Color");
JLabel shape = new JLabel("Shape");
connectedLabel = new JCheckBox("Connect");
visibleLabel = new JCheckBox("Visible");
filledLabel = new JCheckBox("Fill");
connectedLabel.setSelected(true);
visibleLabel.setSelected(true);
filledLabel.setSelected(true);
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
colorsButtons = new ArrayList<JButton>();
shapesCombo = new ArrayList<JComboBox>();
connected = new ArrayList<JCheckBox>();
visible = new ArrayList<JCheckBox>();
filled = new ArrayList<JCheckBox>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
connectedLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (connectedLabel.isSelected()) {
for (JCheckBox box : connected) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : connected) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
visibleLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (visibleLabel.isSelected()) {
for (JCheckBox box : visible) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : visible) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
filledLabel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (filledLabel.isSelected()) {
for (JCheckBox box : filled) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : filled) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
speciesPanel2.add(shape);
speciesPanel3.add(connectedLabel);
speciesPanel3.add(visibleLabel);
speciesPanel3.add(filledLabel);
final HashMap<String, Shape> shapey = this.shapes;
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphSpecies.size() - 1; i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
node.setIcon(TextIcons.getIcon("g"));
node.setIconName("" + (char) 10003);
IconNode n = ((IconNode) node.getParent());
while (n != null) {
n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
n.setIconName("" + (char) 10003);
if (n.getParent() == null) {
n = null;
}
else {
n = ((IconNode) n.getParent());
}
}
tree.revalidate();
tree.repaint();
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[35];
int[] shaps = new int[10];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red"));
colorsButtons.get(k).setForeground((Color) colory.get("Red"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green"));
colorsButtons.get(k).setForeground((Color) colory.get("Green"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
colorsButtons.get(k)
.setBackground((Color) colory.get("Yellow"));
colorsButtons.get(k)
.setForeground((Color) colory.get("Yellow"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
colorsButtons.get(k).setBackground((Color) colory.get("Tan"));
colorsButtons.get(k).setForeground((Color) colory.get("Tan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Gray (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Gray (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Red (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Red (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Blue (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Blue (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Green (Dark)")) {
cols[10]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Green (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Green (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Yellow (Dark)")) {
cols[11]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Yellow (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Yellow (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Magenta (Dark)")) {
cols[12]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Cyan (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Cyan (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
colorsButtons.get(k).setBackground((Color) colory.get("Black"));
colorsButtons.get(k).setForeground((Color) colory.get("Black"));
}
/*
* else if
* (colorsCombo.get(k).getSelectedItem().
* equals("Red ")) { cols[15]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Blue ")) {
* cols[16]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Green ")) { cols[17]++; } else if
* (colorsCombo.get(k).getSelectedItem().equals(
* "Yellow ")) { cols[18]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Magenta "))
* { cols[19]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) {
cols[21]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Red (Extra Dark)")) {
cols[22]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Red (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Red (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Blue (Extra Dark)")) {
cols[23]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Blue (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Blue (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Green (Extra Dark)")) {
cols[24]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Green (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Green (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Yellow (Extra Dark)")) {
cols[25]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Yellow (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Yellow (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Magenta (Extra Dark)")) {
cols[26]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Cyan (Extra Dark)")) {
cols[27]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Cyan (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Cyan (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Red (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Red (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Blue (Light)")) {
cols[29]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Blue (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Blue (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Green (Light)")) {
cols[30]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Green (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Green (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Yellow (Light)")) {
cols[31]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Yellow (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Yellow (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Magenta (Light)")) {
cols[32]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Cyan (Light)")) {
cols[33]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Cyan (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Cyan (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Gray (Light)")) {
cols[34]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Gray (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Gray (Light)"));
}
if (shapesCombo.get(k).getSelectedItem().equals("Square")) {
shaps[0]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Circle")) {
shaps[1]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Triangle")) {
shaps[2]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Diamond")) {
shaps[3]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals(
"Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals(
"Triangle (Upside Down)")) {
shaps[5]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals(
"Circle (Half)")) {
shaps[6]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals("Arrow")) {
shaps[7]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals(
"Rectangle (Vertical)")) {
shaps[8]++;
}
else if (shapesCombo.get(k).getSelectedItem().equals(
"Arrow (Backwards)")) {
shaps[9]++;
}
}
}
for (GraphSpecies graph : graphed) {
if (graph.getShapeAndPaint().getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getShapeAndPaint().getPaintName()
.equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Black")) {
cols[14]++;
}
/*
* else if
* (graph.getShapeAndPaint().getPaintName().equals
* ("Red ")) { cols[15]++; } else if
* (graph.getShapeAndPaint
* ().getPaintName().equals("Blue ")) { cols[16]++;
* } else if
* (graph.getShapeAndPaint().getPaintName()
* .equals("Green ")) { cols[17]++; } else if
* (graph.
* getShapeAndPaint().getPaintName().equals("Yellow "
* )) { cols[18]++; } else if
* (graph.getShapeAndPaint
* ().getPaintName().equals("Magenta ")) {
* cols[19]++; } else if
* (graph.getShapeAndPaint().getPaintName
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (graph.getShapeAndPaint().getPaintName().equals("Gray")) {
cols[21]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getShapeAndPaint().getPaintName()
.equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Yellow (Light)")) {
cols[31]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals(
"Magenta (Light)")) {
cols[32]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
else if (graph.getShapeAndPaint().getPaintName().equals("Gray (Light)")) {
cols[34]++;
}
if (graph.getShapeAndPaint().getShapeName().equals("Square")) {
shaps[0]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Circle")) {
shaps[1]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Triangle")) {
shaps[2]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Diamond")) {
shaps[3]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals(
"Rectangle (Horizontal)")) {
shaps[4]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals(
"Triangle (Upside Down)")) {
shaps[5]++;
}
else if (graph.getShapeAndPaint().getShapeName()
.equals("Circle (Half)")) {
shaps[6]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals("Arrow")) {
shaps[7]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals(
"Rectangle (Vertical)")) {
shaps[8]++;
}
else if (graph.getShapeAndPaint().getShapeName().equals(
"Arrow (Backwards)")) {
shaps[9]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) {
colorSet = j;
}
}
int shapeSet = 0;
for (int j = 1; j < shaps.length; j++) {
if (shaps[j] < shaps[shapeSet]) {
shapeSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
Paint paint;
if (colorSet == 34) {
paint = colors.get("Gray (Light)");
}
else {
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
paint = draw.getNextPaint();
}
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
colorsButtons.get(i).setBackground((Color) paint);
colorsButtons.get(i).setForeground((Color) paint);
}
}
for (int j = 0; j < shapeSet; j++) {
draw.getNextShape();
}
Shape shape = draw.getNextShape();
set = shapey.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (shape == shapey.get(set[j])) {
shapesCombo.get(i).setSelectedItem(set[j]);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
String color = (String) colorsCombo.get(i).getSelectedItem();
if (color.equals("Custom")) {
color += "_" + colorsButtons.get(i).getBackground().getRGB();
}
graphed.add(new GraphSpecies(shapey.get(shapesCombo.get(i)
.getSelectedItem()), color, filled.get(i).isSelected(), visible
.get(i).isSelected(), connected.get(i).isSelected(), selected,
boxes.get(i).getName(), series.get(i).getText().trim(), XVariable
.getSelectedIndex(), i, directory));
}
else {
boolean check = false;
for (JCheckBox b : boxes) {
if (b.isSelected()) {
check = true;
}
}
if (!check) {
node.setIcon(MetalIconFactory.getTreeLeafIcon());
node.setIconName("");
boolean check2 = false;
IconNode parent = ((IconNode) node.getParent());
while (parent != null) {
for (int j = 0; j < parent.getChildCount(); j++) {
if (((IconNode) parent.getChildAt(j)).getIconName().equals(
"" + (char) 10003)) {
check2 = true;
}
}
if (!check2) {
parent.setIcon(MetalIconFactory.getTreeFolderIcon());
parent.setIconName("");
}
check2 = false;
if (parent.getParent() == null) {
parent = null;
}
else {
parent = ((IconNode) parent.getParent());
}
}
tree.revalidate();
tree.repaint();
}
ArrayList<GraphSpecies> remove = new ArrayList<GraphSpecies>();
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphSpecies g : remove) {
graphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colory.get("Black"));
colorsButtons.get(i).setForeground((Color) colory.get("Black"));
shapesCombo.get(i).setSelectedIndex(0);
}
}
});
boxes.add(temp);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : visible) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
visibleLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setVisible(true);
}
}
}
else {
visibleLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setVisible(false);
}
}
}
}
});
visible.add(temp);
visible.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : filled) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
filledLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setFilled(true);
}
}
}
else {
filledLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setFilled(false);
}
}
}
}
});
filled.add(temp);
filled.get(i).setSelected(true);
temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
boolean allChecked = true;
for (JCheckBox temp : connected) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
connectedLabel.setSelected(true);
}
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setConnected(true);
}
}
}
else {
connectedLabel.setSelected(false);
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setConnected(false);
}
}
}
}
});
connected.add(temp);
connected.get(i).setSelected(true);
JTextField seriesName = new JTextField(graphSpecies.get(i + 1), 20);
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
ArrayList<String> allColors = new ArrayList<String>();
for (String c : this.colors.keySet()) {
allColors.add(c);
}
allColors.add("Custom");
Object[] col = allColors.toArray();
Arrays.sort(col);
Object[] shap = this.shapes.keySet().toArray();
Arrays.sort(shap);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) {
colorsButtons.get(i)
.setBackground(
(Color) colors.get(((JComboBox) (e.getSource()))
.getSelectedItem()));
colorsButtons.get(i)
.setForeground(
(Color) colors.get(((JComboBox) (e.getSource()))
.getSelectedItem()));
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setPaint((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
else {
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setPaint("Custom_"
+ colorsButtons.get(i).getBackground().getRGB());
}
}
}
}
});
JComboBox shapBox = new JComboBox(shap);
shapBox.setActionCommand("" + i);
shapBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
for (GraphSpecies g : graphed) {
if (g.getRunNumber().equals(selected) && g.getNumber() == i
&& g.getDirectory().equals(directory)) {
g.setShape((String) ((JComboBox) e.getSource()).getSelectedItem());
}
}
}
});
colorsCombo.add(colBox);
JButton colorButton = new JButton();
colorButton.setPreferredSize(new Dimension(30, 20));
colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray));
colorButton.setBackground((Color) colory.get("Black"));
colorButton.setForeground((Color) colory.get("Black"));
colorButton.setUI(new MetalButtonUI());
colorButton.setActionCommand("" + i);
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color",
((JButton) e.getSource()).getBackground());
if (newColor != null) {
((JButton) e.getSource()).setBackground(newColor);
((JButton) e.getSource()).setForeground(newColor);
colorsCombo.get(i).setSelectedItem("Custom");
}
}
});
colorsButtons.add(colorButton);
JPanel colorPanel = new JPanel(new BorderLayout());
colorPanel.add(colorsCombo.get(i), "Center");
colorPanel.add(colorsButtons.get(i), "East");
shapesCombo.add(shapBox);
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorPanel);
speciesPanel2.add(shapesCombo.get(i));
speciesPanel3.add(connected.get(i));
speciesPanel3.add(visible.get(i));
speciesPanel3.add(filled.get(i));
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
speciesPanel.add(speciesPanel3, "East");
return speciesPanel;
}
private void fixGraph(String title, String x, String y, XYSeriesCollection dataset) {
curData = dataset;
// chart = ChartFactory.createXYLineChart(title, x, y, dataset,
// PlotOrientation.VERTICAL,
// true, true, false);
chart.getXYPlot().setDataset(dataset);
chart.setTitle(title);
chart.getXYPlot().getDomainAxis().setLabel(x);
chart.getXYPlot().getRangeAxis().setLabel(y);
// chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
// chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
// chart.getXYPlot().setDomainGridlinePaint(java.awt.Color.LIGHT_GRAY);
// chart.getXYPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
// chart.addProgressListener(this);
ChartPanel graph = new ChartPanel(chart);
if (graphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
saveAs.addActionListener(this);
export = new JButton("Export");
refresh = new JButton("Refresh");
// exportJPeg = new JButton("Export As JPEG");
// exportPng = new JButton("Export As PNG");
// exportPdf = new JButton("Export As PDF");
// exportEps = new JButton("Export As EPS");
// exportSvg = new JButton("Export As SVG");
// exportCsv = new JButton("Export As CSV");
run.addActionListener(this);
save.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
// exportJPeg.addActionListener(this);
// exportPng.addActionListener(this);
// exportPdf.addActionListener(this);
// exportEps.addActionListener(this);
// exportSvg.addActionListener(this);
// exportCsv.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// ButtonHolder.add(exportJPeg);
// ButtonHolder.add(exportPng);
// ButtonHolder.add(exportPdf);
// ButtonHolder.add(exportEps);
// ButtonHolder.add(exportSvg);
// ButtonHolder.add(exportCsv);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
this.revalidate();
}
/**
* This method saves the graph as a jpeg or as a png file.
*/
public void export() {
try {
int output = 2; /* Default is currently pdf */
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
String export = "Export";
if (timeSeries) {
export += " TSD";
}
else {
export += " Probability";
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY,
export, output);
if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".jpg"))) {
output = 0;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".png"))) {
output = 1;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".pdf"))) {
output = 2;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".eps"))) {
output = 3;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".svg"))) {
output = 4;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".csv"))) {
output = 5;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".dat"))) {
output = 6;
}
else if ((filename.length() > 4)
&& (filename.substring((filename.length() - 4), filename.length())
.equals(".tsd"))) {
output = 7;
}
if (!filename.equals("")) {
file = new File(filename);
biosimrc.put("biosim.general.export_dir", filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(Gui.frame, "File already exists."
+ " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(Gui.frame,
"Width and height must be positive integers!",
"Error", JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2,
options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(Gui.frame,
"Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void export(int output) {
// jpg = 0
// png = 1
// pdf = 2
// eps = 3
// svg = 4
// csv = 5 (data)
// dat = 6 (data)
// tsd = 7 (data)
try {
int width = -1;
int height = -1;
JPanel sizePanel = new JPanel(new GridLayout(2, 2));
JLabel heightLabel = new JLabel("Desired pixel height:");
JLabel widthLabel = new JLabel("Desired pixel width:");
JTextField heightField = new JTextField("400");
JTextField widthField = new JTextField("650");
sizePanel.add(widthLabel);
sizePanel.add(widthField);
sizePanel.add(heightLabel);
sizePanel.add(heightField);
Object[] options2 = { "Export", "Cancel" };
int value;
String export = "Export";
if (timeSeries) {
export += " TSD";
}
else {
export += " Probability";
}
File file;
Preferences biosimrc = Preferences.userRoot();
if (biosimrc.get("biosim.general.export_dir", "").equals("")) {
file = null;
}
else {
file = new File(biosimrc.get("biosim.general.export_dir", ""));
}
String filename = Utility.browse(Gui.frame, file, null, JFileChooser.FILES_ONLY,
export, output);
if (!filename.equals("")) {
file = new File(filename);
biosimrc.put("biosim.general.export_dir", filename);
boolean exportIt = true;
if (file.exists()) {
Object[] options = { "Overwrite", "Cancel" };
value = JOptionPane.showOptionDialog(Gui.frame, "File already exists."
+ " Overwrite?", "File Already Exists", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options, options[0]);
exportIt = false;
if (value == JOptionPane.YES_OPTION) {
exportIt = true;
}
}
if (exportIt) {
if ((output != 5) && (output != 6) && (output != 7)) {
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
if (value == JOptionPane.YES_OPTION) {
while (value == JOptionPane.YES_OPTION && (width == -1 || height == -1))
try {
width = Integer.parseInt(widthField.getText().trim());
height = Integer.parseInt(heightField.getText().trim());
if (width < 1 || height < 1) {
JOptionPane.showMessageDialog(Gui.frame,
"Width and height must be positive integers!",
"Error", JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2,
options2[0]);
}
}
catch (Exception e2) {
JOptionPane.showMessageDialog(Gui.frame,
"Width and height must be positive integers!", "Error",
JOptionPane.ERROR_MESSAGE);
width = -1;
height = -1;
value = JOptionPane.showOptionDialog(Gui.frame, sizePanel,
"Enter Size Of File", JOptionPane.YES_NO_OPTION,
JOptionPane.PLAIN_MESSAGE, null, options2, options2[0]);
}
}
if (value == JOptionPane.NO_OPTION) {
return;
}
}
if (output == 0) {
ChartUtilities.saveChartAsJPEG(file, chart, width, height);
}
else if (output == 1) {
ChartUtilities.saveChartAsPNG(file, chart, width, height);
}
else if (output == 2) {
Rectangle pagesize = new Rectangle(width, height);
Document document = new Document(pagesize, 50, 50, 50, 50);
FileOutputStream out = new FileOutputStream(file);
PdfWriter writer = PdfWriter.getInstance(document, out);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate(width, height);
Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());
chart.draw(g2, new java.awt.Rectangle(width, height));
g2.dispose();
cb.addTemplate(tp, 0, 0);
document.close();
out.close();
}
else if (output == 3) {
Graphics2D g = new EpsGraphics2D();
chart.draw(g, new java.awt.Rectangle(width, height));
Writer out = new FileWriter(file);
out.write(g.toString());
out.close();
}
else if (output == 4) {
DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
chart.draw(svgGenerator, new java.awt.Rectangle(width, height));
boolean useCSS = true;
FileOutputStream outStream = new FileOutputStream(file);
Writer out = new OutputStreamWriter(outStream, "UTF-8");
svgGenerator.stream(out, useCSS);
out.close();
outStream.close();
}
else if ((output == 5) || (output == 6) || (output == 7)) {
exportDataFile(file, output);
}
}
}
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
public void exportDataFile(File file, int output) {
try {
int count = curData.getSeries(0).getItemCount();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (curData.getSeries(i).getItemCount() != count) {
JOptionPane.showMessageDialog(Gui.frame,
"Data series do not have the same number of points!",
"Unable to Export Data File", JOptionPane.ERROR_MESSAGE);
return;
}
}
for (int j = 0; j < count; j++) {
Number Xval = curData.getSeries(0).getDataItem(j).getX();
for (int i = 1; i < curData.getSeriesCount(); i++) {
if (!curData.getSeries(i).getDataItem(j).getX().equals(Xval)) {
JOptionPane.showMessageDialog(Gui.frame,
"Data series time points are not the same!",
"Unable to Export Data File", JOptionPane.ERROR_MESSAGE);
return;
}
}
}
FileOutputStream csvFile = new FileOutputStream(file);
PrintWriter csvWriter = new PrintWriter(csvFile);
if (output == 7) {
csvWriter.print("((");
}
else if (output == 6) {
csvWriter.print("
}
csvWriter.print("\"Time\"");
count = curData.getSeries(0).getItemCount();
int pos = 0;
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print("\"" + curData.getSeriesKey(i) + "\"");
if (curData.getSeries(i).getItemCount() > count) {
count = curData.getSeries(i).getItemCount();
pos = i;
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
for (int j = 0; j < count; j++) {
if (output == 7) {
csvWriter.print(",");
}
for (int i = 0; i < curData.getSeriesCount(); i++) {
if (i == 0) {
if (output == 7) {
csvWriter.print("(");
}
csvWriter.print(curData.getSeries(pos).getDataItem(j).getX());
}
XYSeries data = curData.getSeries(i);
if (j < data.getItemCount()) {
XYDataItem item = data.getDataItem(j);
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
csvWriter.print(item.getY());
}
else {
if (output == 6) {
csvWriter.print(" ");
}
else {
csvWriter.print(",");
}
}
}
if (output == 7) {
csvWriter.print(")");
}
else {
csvWriter.println("");
}
}
if (output == 7) {
csvWriter.println(")");
}
csvWriter.close();
csvFile.close();
}
catch (Exception e1) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Export File!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
private ArrayList<ArrayList<Double>> calculateAverageVarianceDeviation(String startFile,
String fileStem, int choice, String directory, boolean warning) {
ArrayList<ArrayList<Double>> average = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> variance = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> deviation = new ArrayList<ArrayList<Double>>();
lock.lock();
try {
warn = warning;
// TSDParser p = new TSDParser(startFile, biomodelsim, false);
ArrayList<ArrayList<Double>> data = readData(startFile, "", directory, warn);
averageOrder = graphSpecies;
boolean first = true;
int runsToMake = 1;
String[] findNum = startFile.split(separator);
String search = findNum[findNum.length - 1];
int firstOne = Integer.parseInt(search.substring(4, search.length() - 4));
if (directory == null) {
for (String f : new File(outDir).list()) {
if (f.contains(fileStem)) {
try {
int tempNum = Integer.parseInt(f.substring(fileStem.length(), f
.length() - 4));
if (tempNum > runsToMake) {
runsToMake = tempNum;
}
}
catch (Exception e) {
}
}
}
}
else {
for (String f : new File(outDir + separator + directory).list()) {
if (f.contains(fileStem)) {
try {
int tempNum = Integer.parseInt(f.substring(fileStem.length(), f
.length() - 4));
if (tempNum > runsToMake) {
runsToMake = tempNum;
}
}
catch (Exception e) {
}
}
}
}
for (int i = 0; i < graphSpecies.size(); i++) {
average.add(new ArrayList<Double>());
variance.add(new ArrayList<Double>());
}
HashMap<Double, Integer> dataCounts = new HashMap<Double, Integer>();
// int count = 0;
int skip = firstOne;
for (int j = 0; j < runsToMake; j++) {
if (!first) {
if (firstOne != 1) {
j
firstOne = 1;
}
boolean loop = true;
while (loop && j < runsToMake && (j + 1) != skip) {
if (directory == null) {
if (new File(outDir + separator + fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> newData = readData(outDir + separator
+ fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8), "",
directory, warn);
data = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < averageOrder.size(); i++) {
for (int k = 0; k < graphSpecies.size(); k++) {
if (averageOrder.get(i).equals(graphSpecies.get(k))) {
data.add(newData.get(k));
break;
}
}
}
loop = false;
// count++;
}
else {
j++;
}
}
else {
if (new File(outDir + separator + directory + separator + fileStem
+ (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> newData = readData(outDir + separator
+ directory + separator + fileStem + (j + 1) + "."
+ printer_id.substring(0, printer_id.length() - 8), "",
directory, warn);
data = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < averageOrder.size(); i++) {
for (int k = 0; k < graphSpecies.size(); k++) {
if (averageOrder.get(i).equals(graphSpecies.get(k))) {
data.add(newData.get(k));
break;
}
}
}
loop = false;
// count++;
}
else {
j++;
}
}
}
}
// ArrayList<ArrayList<Double>> data = p.getData();
for (int k = 0; k < data.get(0).size(); k++) {
if (first) {
double put;
if (k == data.get(0).size() - 1 && k >= 2) {
if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(
k - 1)
- data.get(0).get(k - 2)) {
put = data.get(0).get(k - 1)
+ (data.get(0).get(k - 1) - data.get(0).get(k - 2));
dataCounts.put(put, 1);
}
else {
put = (data.get(0)).get(k);
dataCounts.put(put, 1);
}
}
else {
put = (data.get(0)).get(k);
dataCounts.put(put, 1);
}
for (int i = 0; i < data.size(); i++) {
if (i == 0) {
variance.get(i).add((data.get(i)).get(k));
average.get(i).add(put);
}
else {
variance.get(i).add(0.0);
average.get(i).add((data.get(i)).get(k));
}
}
}
else {
int index = -1;
double put;
if (k == data.get(0).size() - 1 && k >= 2) {
if (data.get(0).get(k) - data.get(0).get(k - 1) != data.get(0).get(
k - 1)
- data.get(0).get(k - 2)) {
put = data.get(0).get(k - 1)
+ (data.get(0).get(k - 1) - data.get(0).get(k - 2));
}
else {
put = (data.get(0)).get(k);
}
}
else if (k == data.get(0).size() - 1 && k == 1) {
if (average.get(0).size() > 1) {
put = (average.get(0)).get(k);
}
else {
put = (data.get(0)).get(k);
}
}
else {
put = (data.get(0)).get(k);
}
if (average.get(0).contains(put)) {
index = average.get(0).indexOf(put);
int count = dataCounts.get(put);
dataCounts.put(put, count + 1);
for (int i = 1; i < data.size(); i++) {
double old = (average.get(i)).get(index);
(average.get(i)).set(index, old
+ (((data.get(i)).get(k) - old) / (count + 1)));
double newMean = (average.get(i)).get(index);
double vary = (((count - 1) * (variance.get(i)).get(index)) + ((data
.get(i)).get(k) - newMean)
* ((data.get(i)).get(k) - old))
/ count;
(variance.get(i)).set(index, vary);
}
}
else {
dataCounts.put(put, 1);
for (int a = 0; a < average.get(0).size(); a++) {
if (average.get(0).get(a) > put) {
index = a;
break;
}
}
if (index == -1) {
index = average.get(0).size() - 1;
}
average.get(0).add(put);
variance.get(0).add(put);
for (int a = 1; a < average.size(); a++) {
average.get(a).add(data.get(a).get(k));
variance.get(a).add(0.0);
}
if (index != average.get(0).size() - 1) {
for (int a = average.get(0).size() - 2; a >= 0; a
if (average.get(0).get(a) > average.get(0).get(a + 1)) {
for (int b = 0; b < average.size(); b++) {
double temp = average.get(b).get(a);
average.get(b).set(a, average.get(b).get(a + 1));
average.get(b).set(a + 1, temp);
temp = variance.get(b).get(a);
variance.get(b).set(a, variance.get(b).get(a + 1));
variance.get(b).set(a + 1, temp);
}
}
else {
break;
}
}
}
}
}
}
first = false;
}
deviation = new ArrayList<ArrayList<Double>>();
for (int i = 0; i < variance.size(); i++) {
deviation.add(new ArrayList<Double>());
for (int j = 0; j < variance.get(i).size(); j++) {
deviation.get(i).add(variance.get(i).get(j));
}
}
for (int i = 1; i < deviation.size(); i++) {
for (int j = 0; j < deviation.get(i).size(); j++) {
deviation.get(i).set(j, Math.sqrt(deviation.get(i).get(j)));
}
}
averageOrder = null;
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame,
"Unable to output average, variance, and standard deviation!", "Error",
JOptionPane.ERROR_MESSAGE);
}
lock.unlock();
if (choice == 0) {
return average;
}
else if (choice == 1) {
return variance;
}
else {
return deviation;
}
}
public void run() {
reb2sac.getRunButton().doClick();
}
public void save() {
if (timeSeries) {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("chart.background.paint", ""
+ ((Color) chart.getBackgroundPaint()).getRGB());
graph.setProperty("plot.background.paint", ""
+ ((Color) chart.getPlot().getBackgroundPaint()).getRGB());
graph.setProperty("plot.domain.grid.line.paint", ""
+ ((Color) chart.getXYPlot().getDomainGridlinePaint()).getRGB());
graph.setProperty("plot.range.grid.line.paint", ""
+ ((Color) chart.getXYPlot().getRangeGridlinePaint()).getRGB());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
graph.setProperty("LogX", "" + LogX.isSelected());
graph.setProperty("LogY", "" + LogY.isSelected());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.xnumber." + i, "" + graphed.get(i).getXNumber());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint()
.getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint()
.getShapeName());
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator
+ graphName));
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("chart.background.paint", ""
+ ((Color) chart.getBackgroundPaint()).getRGB());
graph.setProperty("plot.background.paint", ""
+ ((Color) chart.getPlot().getBackgroundPaint()).getRGB());
graph.setProperty("plot.range.grid.line.paint", ""
+ ((Color) chart.getCategoryPlot().getRangeGridlinePaint()).getRGB());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
graph.setProperty("gradient",
""
+ (((BarRenderer) chart.getCategoryPlot().getRenderer())
.getBarPainter() instanceof GradientBarPainter));
graph.setProperty("shadow", ""
+ ((BarRenderer) chart.getCategoryPlot().getRenderer()).getShadowsVisible());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
graph.setProperty("species.directory." + i, probGraphed.get(i).getDirectory());
}
try {
FileOutputStream store = new FileOutputStream(new File(outDir + separator
+ graphName));
graph.store(store, "Probability Data");
store.close();
log.addText("Creating graph file:\n" + outDir + separator + graphName + "\n");
change = false;
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
public void saveAs() {
if (timeSeries) {
String graphName = JOptionPane.showInputDialog(Gui.frame, "Enter Graph Name:",
"Graph Name", JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".grf")) {
graphName += ".grf";
}
}
else {
graphName += ".grf";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length()
- outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(outDir.substring(0, outDir.length()
- outDir.split(separator)[outDir.split(separator).length - 1]
.length())
+ separator + graphName);
}
if (del.isDirectory()) {
biomodelsim.deleteDir(del);
}
else {
del.delete();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) {
biomodelsim.getTab().remove(i);
}
}
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getXYPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getXYPlot().getRangeAxis().getLabel());
graph.setProperty("x.min", XMin.getText());
graph.setProperty("x.max", XMax.getText());
graph.setProperty("x.scale", XScale.getText());
graph.setProperty("y.min", YMin.getText());
graph.setProperty("y.max", YMax.getText());
graph.setProperty("y.scale", YScale.getText());
graph.setProperty("auto.resize", "" + resize.isSelected());
graph.setProperty("LogX", "" + LogX.isSelected());
graph.setProperty("LogY", "" + LogY.isSelected());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < graphed.size(); i++) {
graph.setProperty("species.connected." + i, "" + graphed.get(i).getConnected());
graph.setProperty("species.filled." + i, "" + graphed.get(i).getFilled());
graph.setProperty("species.number." + i, "" + graphed.get(i).getNumber());
graph.setProperty("species.run.number." + i, graphed.get(i).getRunNumber());
graph.setProperty("species.name." + i, graphed.get(i).getSpecies());
graph.setProperty("species.id." + i, graphed.get(i).getID());
graph.setProperty("species.visible." + i, "" + graphed.get(i).getVisible());
graph.setProperty("species.paint." + i, graphed.get(i).getShapeAndPaint()
.getPaintName());
graph.setProperty("species.shape." + i, graphed.get(i).getShapeAndPaint()
.getShapeName());
if (topLevel) {
graph.setProperty("species.directory." + i, graphed.get(i).getDirectory());
}
else {
if (graphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i,
outDir.split(separator)[outDir.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i,
outDir.split(separator)[outDir.split(separator).length - 1]
+ "/" + graphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Graph Data");
store.close();
log.addText("Creating graph file:\n" + f.getAbsolutePath() + "\n");
change = false;
biomodelsim.addToTree(f.getName());
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
else {
String graphName = JOptionPane.showInputDialog(Gui.frame,
"Enter Probability Graph Name:", "Probability Graph Name",
JOptionPane.PLAIN_MESSAGE);
if (graphName != null && !graphName.trim().equals("")) {
graphName = graphName.trim();
if (graphName.length() > 3) {
if (!graphName.substring(graphName.length() - 4).equals(".prb")) {
graphName += ".prb";
}
}
else {
graphName += ".prb";
}
File f;
if (topLevel) {
f = new File(outDir + separator + graphName);
}
else {
f = new File(outDir.substring(0, outDir.length()
- outDir.split(separator)[outDir.split(separator).length - 1].length())
+ separator + graphName);
}
if (f.exists()) {
Object[] options = { "Overwrite", "Cancel" };
int value = JOptionPane.showOptionDialog(Gui.frame, "File already exists."
+ "\nDo you want to overwrite?", "Overwrite",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
File del;
if (topLevel) {
del = new File(outDir + separator + graphName);
}
else {
del = new File(outDir.substring(0, outDir.length()
- outDir.split(separator)[outDir.split(separator).length - 1]
.length())
+ separator + graphName);
}
if (del.isDirectory()) {
biomodelsim.deleteDir(del);
}
else {
del.delete();
}
for (int i = 0; i < biomodelsim.getTab().getTabCount(); i++) {
if (biomodelsim.getTab().getTitleAt(i).equals(graphName)) {
biomodelsim.getTab().remove(i);
}
}
}
else {
return;
}
}
Properties graph = new Properties();
graph.setProperty("title", chart.getTitle().getText());
graph.setProperty("x.axis", chart.getCategoryPlot().getDomainAxis().getLabel());
graph.setProperty("y.axis", chart.getCategoryPlot().getRangeAxis().getLabel());
graph.setProperty("gradient",
""
+ (((BarRenderer) chart.getCategoryPlot().getRenderer())
.getBarPainter() instanceof GradientBarPainter));
graph
.setProperty("shadow", ""
+ ((BarRenderer) chart.getCategoryPlot().getRenderer())
.getShadowsVisible());
graph.setProperty("visibleLegend", "" + visibleLegend.isSelected());
for (int i = 0; i < probGraphed.size(); i++) {
graph.setProperty("species.number." + i, "" + probGraphed.get(i).getNumber());
graph.setProperty("species.name." + i, probGraphed.get(i).getSpecies());
graph.setProperty("species.id." + i, probGraphed.get(i).getID());
graph.setProperty("species.paint." + i, probGraphed.get(i).getPaintName());
if (topLevel) {
graph.setProperty("species.directory." + i, probGraphed.get(i)
.getDirectory());
}
else {
if (probGraphed.get(i).getDirectory().equals("")) {
graph.setProperty("species.directory." + i,
outDir.split(separator)[outDir.split(separator).length - 1]);
}
else {
graph.setProperty("species.directory." + i,
outDir.split(separator)[outDir.split(separator).length - 1]
+ "/" + probGraphed.get(i).getDirectory());
}
}
}
try {
FileOutputStream store = new FileOutputStream(f);
graph.store(store, "Probability Graph Data");
store.close();
log.addText("Creating probability graph file:\n" + f.getAbsolutePath() + "\n");
change = false;
biomodelsim.addToTree(f.getName());
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Save Probability Graph!",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
private void open(String filename) {
if (timeSeries) {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
XMin.setText(graph.getProperty("x.min"));
XMax.setText(graph.getProperty("x.max"));
XScale.setText(graph.getProperty("x.scale"));
YMin.setText(graph.getProperty("y.min"));
YMax.setText(graph.getProperty("y.max"));
YScale.setText(graph.getProperty("y.scale"));
chart.setTitle(graph.getProperty("title"));
if (graph.containsKey("chart.background.paint")) {
chart.setBackgroundPaint(new Color(Integer.parseInt(graph
.getProperty("chart.background.paint"))));
}
if (graph.containsKey("plot.background.paint")) {
chart.getPlot()
.setBackgroundPaint(
new Color(Integer.parseInt(graph
.getProperty("plot.background.paint"))));
}
if (graph.containsKey("plot.domain.grid.line.paint")) {
chart.getXYPlot().setDomainGridlinePaint(
new Color(Integer.parseInt(graph
.getProperty("plot.domain.grid.line.paint"))));
}
if (graph.containsKey("plot.range.grid.line.paint")) {
chart.getXYPlot().setRangeGridlinePaint(
new Color(Integer.parseInt(graph
.getProperty("plot.range.grid.line.paint"))));
}
chart.getXYPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getXYPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.getProperty("auto.resize").equals("true")) {
resize.setSelected(true);
}
else {
resize.setSelected(false);
}
if (graph.containsKey("LogX") && graph.getProperty("LogX").equals("true")) {
LogX.setSelected(true);
}
else {
LogX.setSelected(false);
}
if (graph.containsKey("LogY") && graph.getProperty("LogY").equals("true")) {
LogY.setSelected(true);
}
else {
LogY.setSelected(false);
}
if (graph.containsKey("visibleLegend")
&& graph.getProperty("visibleLegend").equals("false")) {
visibleLegend.setSelected(false);
}
else {
visibleLegend.setSelected(true);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
boolean connected, filled, visible;
if (graph.getProperty("species.connected." + next).equals("true")) {
connected = true;
}
else {
connected = false;
}
if (graph.getProperty("species.filled." + next).equals("true")) {
filled = true;
}
else {
filled = false;
}
if (graph.getProperty("species.visible." + next).equals("true")) {
visible = true;
}
else {
visible = false;
}
int xnumber = 0;
if (graph.containsKey("species.xnumber." + next)) {
xnumber = Integer.parseInt(graph.getProperty("species.xnumber." + next));
}
graphed.add(new GraphSpecies(shapes.get(graph.getProperty("species.shape."
+ next)), graph.getProperty("species.paint." + next).trim(), filled,
visible, connected, graph.getProperty("species.run.number." + next),
graph.getProperty("species.id." + next), graph
.getProperty("species.name." + next), xnumber, Integer
.parseInt(graph.getProperty("species.number." + next)), graph
.getProperty("species.directory." + next)));
next++;
}
updateXNumber = false;
XVariable.addItem("time");
refresh();
}
catch (IOException except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
else {
Properties graph = new Properties();
try {
FileInputStream load = new FileInputStream(new File(filename));
graph.load(load);
load.close();
chart.setTitle(graph.getProperty("title"));
if (graph.containsKey("chart.background.paint")) {
chart.setBackgroundPaint(new Color(Integer.parseInt(graph
.getProperty("chart.background.paint"))));
}
if (graph.containsKey("plot.background.paint")) {
chart.getPlot()
.setBackgroundPaint(
new Color(Integer.parseInt(graph
.getProperty("plot.background.paint"))));
}
if (graph.containsKey("plot.range.grid.line.paint")) {
chart.getCategoryPlot().setRangeGridlinePaint(
new Color(Integer.parseInt(graph
.getProperty("plot.range.grid.line.paint"))));
}
chart.getCategoryPlot().getDomainAxis().setLabel(graph.getProperty("x.axis"));
chart.getCategoryPlot().getRangeAxis().setLabel(graph.getProperty("y.axis"));
if (graph.containsKey("gradient") && graph.getProperty("gradient").equals("true")) {
((BarRenderer) chart.getCategoryPlot().getRenderer())
.setBarPainter(new GradientBarPainter());
}
else {
((BarRenderer) chart.getCategoryPlot().getRenderer())
.setBarPainter(new StandardBarPainter());
}
if (graph.containsKey("shadow") && graph.getProperty("shadow").equals("false")) {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(false);
}
else {
((BarRenderer) chart.getCategoryPlot().getRenderer()).setShadowVisible(true);
}
if (graph.containsKey("visibleLegend")
&& graph.getProperty("visibleLegend").equals("false")) {
visibleLegend.setSelected(false);
}
else {
visibleLegend.setSelected(true);
}
int next = 0;
while (graph.containsKey("species.name." + next)) {
String color = graph.getProperty("species.paint." + next).trim();
Paint paint;
if (color.startsWith("Custom_")) {
paint = new Color(Integer.parseInt(color.replace("Custom_", "")));
}
else {
paint = colors.get(color);
}
probGraphed.add(new GraphProbs(paint, color, graph.getProperty("species.id."
+ next), graph.getProperty("species.name." + next), Integer
.parseInt(graph.getProperty("species.number." + next)), graph
.getProperty("species.directory." + next)));
next++;
}
refreshProb();
}
catch (Exception except) {
JOptionPane.showMessageDialog(Gui.frame, "Unable To Load Graph!", "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
public boolean isTSDGraph() {
return timeSeries;
}
public void refresh() {
if (timeSeries) {
if (learnSpecs != null) {
updateSpecies();
}
double minY = 0;
double maxY = 0;
double scaleY = 0;
double minX = 0;
double maxX = 0;
double scaleX = 0;
try {
minY = Double.parseDouble(YMin.getText().trim());
maxY = Double.parseDouble(YMax.getText().trim());
scaleY = Double.parseDouble(YScale.getText().trim());
minX = Double.parseDouble(XMin.getText().trim());
maxX = Double.parseDouble(XMax.getText().trim());
scaleX = Double.parseDouble(XScale.getText().trim());
/*
* NumberFormat num = NumberFormat.getInstance();
* num.setMaximumFractionDigits(4); num.setGroupingUsed(false);
* minY = Double.parseDouble(num.format(minY)); maxY =
* Double.parseDouble(num.format(maxY)); scaleY =
* Double.parseDouble(num.format(scaleY)); minX =
* Double.parseDouble(num.format(minX)); maxX =
* Double.parseDouble(num.format(maxX)); scaleX =
* Double.parseDouble(num.format(scaleX));
*/
}
catch (Exception e1) {
}
ArrayList<XYSeries> graphData = new ArrayList<XYSeries>();
XYLineAndShapeRenderer rend = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < graphed.size(); i++) {
GraphSpecies index = graphed.get(i);
int j = i;
while ((j > 0)
&& (graphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
graphed.set(j, graphed.get(j - 1));
j = j - 1;
}
graphed.set(j, index);
}
ArrayList<GraphSpecies> unableToGraph = new ArrayList<GraphSpecies>();
HashMap<String, ArrayList<ArrayList<Double>>> allData = new HashMap<String, ArrayList<ArrayList<Double>>>();
for (GraphSpecies g : graphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
readGraphSpecies(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8));
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
data = readData(outDir + separator + g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber(), null, false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (!ableToGraph) {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
}
if (ableToGraph) {
int nextOne = 1;
// while (!new File(outDir + separator + "run-" +
// nextOne + "."
// + printer_id.substring(0, printer_id.length() -
// 8)).exists()) {
// nextOne++;
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "standard_deviation"
+ "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else {
while (!new File(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else {
while (!new File(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
data = readData(outDir + separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
thisOne++;
rend.setSeriesVisible(thisOne, true);
rend.setSeriesLinesVisible(thisOne, g.getConnected());
rend.setSeriesShapesFilled(thisOne, g.getFilled());
rend.setSeriesShapesVisible(thisOne, g.getVisible());
rend.setSeriesPaint(thisOne, g.getShapeAndPaint().getPaint());
rend.setSeriesShape(thisOne, g.getShapeAndPaint().getShape());
if (!g.getRunNumber().equals("Average") && !g.getRunNumber().equals("Variance")
&& !g.getRunNumber().equals("Standard Deviation")
&& !g.getRunNumber().equals("Termination Time")
&& !g.getRunNumber().equals("Percent Termination")
&& !g.getRunNumber().equals("Constraint Termination")) {
if (new File(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8)).exists()) {
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
readGraphSpecies(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8));
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
data = readData(outDir + separator + g.getDirectory() + separator
+ g.getRunNumber() + "."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber(), g.getDirectory(), false);
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
boolean ableToGraph = false;
try {
for (String s : new File(outDir + separator + g.getDirectory()).list()) {
if (s.length() > 3 && s.substring(0, 4).equals("run-")) {
ableToGraph = true;
}
}
}
catch (Exception e) {
ableToGraph = false;
}
if (!ableToGraph) {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory() + separator
+ "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory() + separator
+ "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory() + separator
+ "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory() + separator
+ "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory() + separator
+ "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory() + separator
+ "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
ableToGraph = true;
}
}
if (ableToGraph) {
int nextOne = 1;
// while (!new File(outDir + separator +
// g.getDirectory() + separator
// + "run-" + nextOne + "."
// + printer_id.substring(0, printer_id.length() -
// 8)).exists()) {
// nextOne++;
ArrayList<ArrayList<Double>> data;
if (allData.containsKey(g.getRunNumber() + " " + g.getDirectory())) {
data = allData.get(g.getRunNumber() + " " + g.getDirectory());
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory()
+ separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + g.getDirectory()
+ separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory()
+ separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + g.getDirectory()
+ separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory()
+ separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + g.getDirectory()
+ separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory()
+ separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + g.getDirectory()
+ separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory()
+ separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + g.getDirectory()
+ separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory()
+ separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
readGraphSpecies(outDir + separator + g.getDirectory()
+ separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
else {
while (!new File(outDir + separator + g.getDirectory()
+ separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
readGraphSpecies(outDir + separator + g.getDirectory()
+ separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8));
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
}
updateXNumber = false;
XVariable.removeAllItems();
for (int i = 0; i < graphSpecies.size(); i++) {
XVariable.addItem(graphSpecies.get(i));
}
updateXNumber = true;
}
else {
if (g.getRunNumber().equals("Average")
&& new File(outDir + separator + g.getDirectory()
+ separator + "mean" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + g.getDirectory()
+ separator + "mean."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Variance")
&& new File(outDir + separator + g.getDirectory()
+ separator + "variance" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + g.getDirectory()
+ separator + "variance."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Standard Deviation")
&& new File(outDir + separator + g.getDirectory()
+ separator + "standard_deviation" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + g.getDirectory()
+ separator + "standard_deviation."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Termination Time")
&& new File(outDir + separator + g.getDirectory()
+ separator + "term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + g.getDirectory()
+ separator + "term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Percent Termination")
&& new File(outDir + separator + g.getDirectory()
+ separator + "percent-term-time" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + g.getDirectory()
+ separator + "percent-term-time."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else if (g.getRunNumber().equals("Constraint Termination")
&& new File(outDir + separator + g.getDirectory()
+ separator + "sim-rep" + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
data = readData(outDir + separator + g.getDirectory()
+ separator + "sim-rep."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), null, false);
}
else {
while (!new File(outDir + separator + g.getDirectory()
+ separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8))
.exists()) {
nextOne++;
}
data = readData(outDir + separator + g.getDirectory()
+ separator + "run-" + nextOne + "."
+ printer_id.substring(0, printer_id.length() - 8), g
.getRunNumber().toLowerCase(), g.getDirectory(), false);
}
for (int i = 2; i < graphSpecies.size(); i++) {
String index = graphSpecies.get(i);
ArrayList<Double> index2 = data.get(i);
int j = i;
while ((j > 1)
&& graphSpecies.get(j - 1).compareToIgnoreCase(index) > 0) {
graphSpecies.set(j, graphSpecies.get(j - 1));
data.set(j, data.get(j - 1));
j = j - 1;
}
graphSpecies.set(j, index);
data.set(j, index2);
}
allData.put(g.getRunNumber() + " " + g.getDirectory(), data);
}
boolean set = false;
for (int i = 1; i < graphSpecies.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (graphSpecies.get(i).equals(compare.split("~")[0].trim())) {
g.setNumber(i - 1);
set = true;
}
}
if (g.getNumber() + 1 < graphSpecies.size() && set) {
graphData.add(new XYSeries(g.getSpecies()));
if (data.size() != 0) {
for (int i = 0; i < (data.get(0)).size(); i++) {
graphData.get(graphData.size() - 1).add(
(data.get(g.getXNumber())).get(i),
(data.get(g.getNumber() + 1)).get(i));
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
}
for (GraphSpecies g : unableToGraph) {
graphed.remove(g);
}
XYSeriesCollection dataset = new XYSeriesCollection();
for (int i = 0; i < graphData.size(); i++) {
dataset.addSeries(graphData.get(i));
}
fixGraph(chart.getTitle().getText(), chart.getXYPlot().getDomainAxis().getLabel(),
chart.getXYPlot().getRangeAxis().getLabel(), dataset);
chart.getXYPlot().setRenderer(rend);
XYPlot plot = chart.getXYPlot();
if (resize.isSelected()) {
resize(dataset);
}
else {
NumberAxis axis = (NumberAxis) plot.getRangeAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minY, maxY);
axis.setTickUnit(new NumberTickUnit(scaleY));
axis = (NumberAxis) plot.getDomainAxis();
axis.setAutoTickUnitSelection(false);
axis.setRange(minX, maxX);
axis.setTickUnit(new NumberTickUnit(scaleX));
}
}
else {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0)
&& (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(
index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
if (graphProbs.contains(g.getID())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt")
.exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
String compare = g.getID().replace(" (", "~");
if (graphProbs.contains(compare.split("~")[0].trim())) {
for (int i = 0; i < graphProbs.size(); i++) {
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(), chart.getCategoryPlot().getDomainAxis()
.getLabel(), chart.getCategoryPlot().getRangeAxis().getLabel(), histDataset,
rend);
}
}
private class ShapeAndPaint {
private Shape shape;
private Paint paint;
private ShapeAndPaint(Shape s, String p) {
shape = s;
if (p.startsWith("Custom_")) {
paint = new Color(Integer.parseInt(p.replace("Custom_", "")));
}
else {
paint = colors.get(p);
}
}
private Shape getShape() {
return shape;
}
private Paint getPaint() {
return paint;
}
private String getShapeName() {
Object[] set = shapes.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (shape == shapes.get(set[i])) {
return (String) set[i];
}
}
return "Unknown Shape";
}
private String getPaintName() {
Object[] set = colors.keySet().toArray();
for (int i = 0; i < set.length; i++) {
if (paint == colors.get(set[i])) {
return (String) set[i];
}
}
return "Custom_" + ((Color) paint).getRGB();
}
public void setPaint(String paint) {
if (paint.startsWith("Custom_")) {
this.paint = new Color(Integer.parseInt(paint.replace("Custom_", "")));
}
else {
this.paint = colors.get(paint);
}
}
public void setShape(String shape) {
this.shape = shapes.get(shape);
}
}
private class GraphSpecies {
private ShapeAndPaint sP;
private boolean filled, visible, connected;
private String runNumber, species, directory, id;
private int xnumber, number;
private GraphSpecies(Shape s, String p, boolean filled, boolean visible, boolean connected,
String runNumber, String id, String species, int xnumber, int number,
String directory) {
sP = new ShapeAndPaint(s, p);
this.filled = filled;
this.visible = visible;
this.connected = connected;
this.runNumber = runNumber;
this.species = species;
this.xnumber = xnumber;
this.number = number;
this.directory = directory;
this.id = id;
}
private void setDirectory(String directory) {
this.directory = directory;
}
private void setXNumber(int xnumber) {
this.xnumber = xnumber;
}
private void setNumber(int number) {
this.number = number;
}
private void setSpecies(String species) {
this.species = species;
}
private void setPaint(String paint) {
sP.setPaint(paint);
}
private void setShape(String shape) {
sP.setShape(shape);
}
private void setVisible(boolean b) {
visible = b;
}
private void setFilled(boolean b) {
filled = b;
}
private void setConnected(boolean b) {
connected = b;
}
private int getXNumber() {
return xnumber;
}
private int getNumber() {
return number;
}
private String getSpecies() {
return species;
}
private ShapeAndPaint getShapeAndPaint() {
return sP;
}
private boolean getFilled() {
return filled;
}
private boolean getVisible() {
return visible;
}
private boolean getConnected() {
return connected;
}
private String getRunNumber() {
return runNumber;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
}
public void setDirectory(String newDirectory) {
outDir = newDirectory;
}
public void setGraphName(String graphName) {
this.graphName = graphName;
}
public boolean hasChanged() {
return change;
}
private void probGraph(String label) {
chart = ChartFactory.createBarChart(label, "", "Percent", new DefaultCategoryDataset(),
PlotOrientation.VERTICAL, true, true, false);
((BarRenderer) chart.getCategoryPlot().getRenderer())
.setBarPainter(new StandardBarPainter());
chart.setBackgroundPaint(new java.awt.Color(238, 238, 238));
chart.getPlot().setBackgroundPaint(java.awt.Color.WHITE);
chart.getCategoryPlot().setRangeGridlinePaint(java.awt.Color.LIGHT_GRAY);
legend = chart.getLegend();
visibleLegend = new JCheckBox("Visible Legend");
visibleLegend.setSelected(true);
ChartPanel graph = new ChartPanel(chart);
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
graph.addMouseListener(this);
change = false;
// creates the buttons for the graph frame
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
export = new JButton("Export");
refresh = new JButton("Refresh");
run.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// puts all the components of the graph gui into a display panel
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
}
private void editProbGraph() {
final ArrayList<GraphProbs> old = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
old.add(g);
}
final JPanel titlePanel = new JPanel(new BorderLayout());
JLabel titleLabel = new JLabel("Title:");
JLabel xLabel = new JLabel("X-Axis Label:");
JLabel yLabel = new JLabel("Y-Axis Label:");
final JCheckBox gradient = new JCheckBox("Paint In Gradient Style");
gradient.setSelected(!(((BarRenderer) chart.getCategoryPlot().getRenderer())
.getBarPainter() instanceof StandardBarPainter));
final JCheckBox shadow = new JCheckBox("Paint Bar Shadows");
shadow.setSelected(((BarRenderer) chart.getCategoryPlot().getRenderer())
.getShadowsVisible());
visibleLegend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (((JCheckBox) e.getSource()).isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
}
});
final JTextField title = new JTextField(chart.getTitle().getText(), 5);
final JTextField x = new JTextField(chart.getCategoryPlot().getDomainAxis().getLabel(), 5);
final JTextField y = new JTextField(chart.getCategoryPlot().getRangeAxis().getLabel(), 5);
String simDirString = outDir.split(separator)[outDir.split(separator).length - 1];
simDir = new IconNode(simDirString, simDirString);
simDir.setIconName("");
String[] files = new File(outDir).list();
// for (int i = 1; i < files.length; i++) {
// String index = files[i];
// int j = i;
// while ((j > 0) && files[j - 1].compareToIgnoreCase(index) > 0) {
// files[j] = files[j - 1];
// j = j - 1;
// files[j] = index;
boolean add = false;
final ArrayList<String> directories = new ArrayList<String>();
for (String file : files) {
if (file.length() > 3 && file.substring(file.length() - 4).equals(".txt")) {
if (file.contains("sim-rep")) {
add = true;
}
}
else if (new File(outDir + separator + file).isDirectory()) {
boolean addIt = false;
for (String getFile : new File(outDir + separator + file).list()) {
if (getFile.length() > 3
&& getFile.substring(getFile.length() - 4).equals(".txt")
&& getFile.contains("sim-rep")) {
addIt = true;
}
else if (new File(outDir + separator + file + separator + getFile)
.isDirectory()) {
for (String getFile2 : new File(outDir + separator + file + separator
+ getFile).list()) {
if (getFile2.length() > 3
&& getFile2.substring(getFile2.length() - 4).equals(".txt")
&& getFile2.contains("sim-rep")) {
addIt = true;
}
}
}
}
if (addIt) {
directories.add(file);
IconNode d = new IconNode(file, file);
d.setIconName("");
String[] files2 = new File(outDir + separator + file).list();
// for (int i = 1; i < files2.length; i++) {
// String index = files2[i];
// int j = i;
// while ((j > 0) && files2[j -
// 1].compareToIgnoreCase(index) > 0) {
// files2[j] = files2[j - 1];
// j = j - 1;
// files2[j] = index;
boolean add2 = false;
for (String f : files2) {
if (f.equals("sim-rep.txt")) {
add2 = true;
}
else if (new File(outDir + separator + file + separator + f).isDirectory()) {
boolean addIt2 = false;
for (String getFile : new File(outDir + separator + file + separator
+ f).list()) {
if (getFile.length() > 3
&& getFile.substring(getFile.length() - 4).equals(".txt")
&& getFile.contains("sim-rep")) {
addIt2 = true;
}
}
if (addIt2) {
directories.add(file + separator + f);
IconNode d2 = new IconNode(f, f);
d2.setIconName("");
for (String f2 : new File(outDir + separator + file + separator + f)
.list()) {
if (f2.equals("sim-rep.txt")) {
IconNode n = new IconNode(f2.substring(0, f2.length() - 4),
f2.substring(0, f2.length() - 4));
d2.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(
d.getName() + separator + d2.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d2.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d2.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory
.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
}
boolean added = false;
for (int j = 0; j < d.getChildCount(); j++) {
if ((d.getChildAt(j).toString().compareToIgnoreCase(
d2.toString()) > 0)
|| new File(outDir + separator + d.toString()
+ separator
+ (d.getChildAt(j).toString() + ".txt"))
.isFile()) {
d.insert(d2, j);
added = true;
break;
}
}
if (!added) {
d.add(d2);
}
}
}
}
if (add2) {
IconNode n = new IconNode("sim-rep", "sim-rep");
d.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(d.getName())) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
d.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
d.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
boolean added = false;
for (int j = 0; j < simDir.getChildCount(); j++) {
if ((simDir.getChildAt(j).toString().compareToIgnoreCase(d.toString()) > 0)
|| new File(outDir + separator
+ (simDir.getChildAt(j).toString() + ".txt")).isFile()) {
simDir.insert(d, j);
added = true;
break;
}
}
if (!added) {
simDir.add(d);
}
}
}
}
if (add) {
IconNode n = new IconNode("sim-rep", "sim-rep");
simDir.add(n);
n.setIconName("");
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
n.setIcon(TextIcons.getIcon("g"));
n.setIconName("" + (char) 10003);
simDir.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
simDir.setIconName("" + (char) 10003);
}
}
}
if (simDir.getChildCount() == 0) {
JOptionPane.showMessageDialog(Gui.frame, "No data to graph."
+ "\nPerform some simulations to create some data first.", "No Data",
JOptionPane.PLAIN_MESSAGE);
}
else {
tree = new JTree(simDir);
tree.putClientProperty("JTree.icons", makeIcons());
tree.setCellRenderer(new IconNodeRenderer());
DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) tree.getCellRenderer();
renderer.setLeafIcon(MetalIconFactory.getTreeLeafIcon());
renderer.setClosedIcon(MetalIconFactory.getTreeFolderIcon());
renderer.setOpenIcon(MetalIconFactory.getTreeFolderIcon());
final JPanel all = new JPanel(new BorderLayout());
final JScrollPane scroll = new JScrollPane();
tree.addTreeExpansionListener(new TreeExpansionListener() {
public void treeCollapsed(TreeExpansionEvent e) {
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
}
public void treeExpanded(TreeExpansionEvent e) {
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
all.removeAll();
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
all.revalidate();
all.repaint();
}
});
// for (int i = 0; i < tree.getRowCount(); i++) {
// tree.expandRow(i);
JScrollPane scrollpane = new JScrollPane();
scrollpane.getViewport().add(tree);
scrollpane.setPreferredSize(new Dimension(175, 100));
final JPanel specPanel = new JPanel();
boolean stop = false;
int selectionRow = 1;
for (int i = 1; i < tree.getRowCount(); i++) {
tree.setSelectionRow(i);
if (selected.equals(lastSelected)) {
stop = true;
selectionRow = i;
break;
}
}
tree.addTreeSelectionListener(new TreeSelectionListener() {
public void valueChanged(TreeSelectionEvent e) {
node = (IconNode) e.getPath().getLastPathComponent();
if (!directories.contains(node.getName())) {
selected = node.getName();
int select;
if (selected.equals("sim-rep")) {
select = 0;
}
else {
select = -1;
}
if (select != -1) {
specPanel.removeAll();
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent()
.getParent()).getName()
+ separator + ((IconNode) node.getParent()).getName())) {
specPanel.add(fixProbChoices(((IconNode) node.getParent()
.getParent()).getName()
+ separator + ((IconNode) node.getParent()).getName()));
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
specPanel.add(fixProbChoices(((IconNode) node.getParent())
.getName()));
}
else {
specPanel.add(fixProbChoices(""));
}
specPanel.revalidate();
specPanel.repaint();
for (int i = 0; i < series.size(); i++) {
series.get(i).setText(graphProbs.get(i));
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
}
for (int i = 0; i < boxes.size(); i++) {
boxes.get(i).setSelected(false);
}
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent()
.getParent()).getName()
+ separator + ((IconNode) node.getParent()).getName())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(
((IconNode) node.getParent().getParent()).getName()
+ separator
+ ((IconNode) node.getParent()).getName())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground(
(Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground(
(Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getPaintName().split("_")[0]);
}
}
}
else if (directories.contains(((IconNode) node.getParent()).getName())) {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals(
((IconNode) node.getParent()).getName())) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground(
(Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground(
(Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getPaintName().split("_")[0]);
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
boxes.get(g.getNumber()).setSelected(true);
series.get(g.getNumber()).setText(g.getSpecies());
series.get(g.getNumber()).setSelectionStart(0);
series.get(g.getNumber()).setSelectionEnd(0);
colorsButtons.get(g.getNumber()).setBackground(
(Color) g.getPaint());
colorsButtons.get(g.getNumber()).setForeground(
(Color) g.getPaint());
colorsCombo.get(g.getNumber()).setSelectedItem(
g.getPaintName().split("_")[0]);
}
}
}
boolean allChecked = true;
for (int i = 0; i < boxes.size(); i++) {
if (!boxes.get(i).isSelected()) {
allChecked = false;
String s = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent()
.getParent()).getName()
+ separator
+ ((IconNode) node.getParent()).getName())) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ")";
}
else if (directories.contains(((IconNode) node.getParent())
.getName())) {
s = "(" + ((IconNode) node.getParent()).getName() + ")";
}
String text = series.get(i).getText();
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
series.get(i).setText(text);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colors.get("Black"));
colorsButtons.get(i).setForeground((Color) colors.get("Black"));
}
else {
String s = "";
if (node.getParent().getParent() != null
&& directories.contains(((IconNode) node.getParent()
.getParent()).getName()
+ separator
+ ((IconNode) node.getParent()).getName())) {
s = "("
+ ((IconNode) node.getParent().getParent())
.getName() + separator
+ ((IconNode) node.getParent()).getName() + ")";
}
else if (directories.contains(((IconNode) node.getParent())
.getName())) {
s = "(" + ((IconNode) node.getParent()).getName() + ")";
}
String text = graphProbs.get(i);
String end = "";
if (!s.equals("")) {
if (text.length() >= s.length()) {
for (int j = 0; j < s.length(); j++) {
end = text.charAt(text.length() - 1 - j) + end;
}
if (!s.equals(end)) {
text += " " + s;
}
}
else {
text += " " + s;
}
}
boxes.get(i).setName(text);
}
}
if (allChecked) {
use.setSelected(true);
}
else {
use.setSelected(false);
}
}
}
else {
specPanel.removeAll();
specPanel.revalidate();
specPanel.repaint();
}
}
});
if (!stop) {
tree.setSelectionRow(0);
tree.setSelectionRow(1);
}
else {
tree.setSelectionRow(0);
tree.setSelectionRow(selectionRow);
}
scroll.setPreferredSize(new Dimension(1050, 500));
JPanel editPanel = new JPanel(new BorderLayout());
editPanel.add(specPanel, "Center");
scroll.setViewportView(editPanel);
final JButton deselect = new JButton("Deselect All");
deselect.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
IconNode n = simDir;
while (n != null) {
if (n.isLeaf()) {
n.setIcon(MetalIconFactory.getTreeLeafIcon());
n.setIconName("");
IconNode check = (IconNode) ((DefaultMutableTreeNode) n.getParent())
.getChildAfter(n);
if (check == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
IconNode check2 = (IconNode) ((DefaultMutableTreeNode) n
.getParent()).getChildAfter(n);
if (check2 == null) {
n = (IconNode) n.getParent();
if (n.getParent() == null) {
n = null;
}
else {
n = (IconNode) ((DefaultMutableTreeNode) n.getParent())
.getChildAfter(n);
}
}
else {
n = check2;
}
}
}
else {
n = check;
}
}
else {
n.setIcon(MetalIconFactory.getTreeFolderIcon());
n.setIconName("");
n = (IconNode) n.getChildAt(0);
}
}
tree.revalidate();
tree.repaint();
if (tree.getSelectionCount() > 0) {
int selectedRow = tree.getSelectionRows()[0];
tree.setSelectionRow(0);
tree.setSelectionRow(selectedRow);
}
}
});
JPanel titlePanel1 = new JPanel(new GridLayout(1, 6));
JPanel titlePanel2 = new JPanel(new GridLayout(1, 6));
titlePanel1.add(titleLabel);
titlePanel1.add(title);
titlePanel1.add(xLabel);
titlePanel1.add(x);
titlePanel1.add(yLabel);
titlePanel1.add(y);
JPanel deselectPanel = new JPanel();
deselectPanel.add(deselect);
titlePanel2.add(deselectPanel);
titlePanel2.add(gradient);
titlePanel2.add(shadow);
titlePanel2.add(visibleLegend);
titlePanel2.add(new JPanel());
titlePanel2.add(new JPanel());
titlePanel.add(titlePanel1, "Center");
titlePanel.add(titlePanel2, "South");
all.add(titlePanel, "North");
all.add(scroll, "Center");
all.add(scrollpane, "West");
Object[] options = { "Ok", "Cancel" };
int value = JOptionPane
.showOptionDialog(Gui.frame, all, "Edit Probability Graph",
JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options,
options[0]);
if (value == JOptionPane.YES_OPTION) {
change = true;
lastSelected = selected;
selected = "";
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
if (gradient.isSelected()) {
rend.setBarPainter(new GradientBarPainter());
}
else {
rend.setBarPainter(new StandardBarPainter());
}
if (shadow.isSelected()) {
rend.setShadowVisible(true);
}
else {
rend.setShadowVisible(false);
}
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0)
&& (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(
index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0)
&& graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory()
+ separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0)
&& graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(title.getText().trim(), x.getText().trim(), y.getText().trim(),
histDataset, rend);
}
else {
selected = "";
int size = probGraphed.size();
for (int i = 0; i < size; i++) {
probGraphed.remove();
}
for (GraphProbs g : old) {
probGraphed.add(g);
}
}
}
}
private JPanel fixProbChoices(final String directory) {
if (directory.equals("")) {
readProbSpecies(outDir + separator + "sim-rep.txt");
}
else {
readProbSpecies(outDir + separator + directory + separator + "sim-rep.txt");
}
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
j = j - 1;
}
graphProbs.set(j, index);
}
JPanel speciesPanel1 = new JPanel(new GridLayout(graphProbs.size() + 1, 1));
JPanel speciesPanel2 = new JPanel(new GridLayout(graphProbs.size() + 1, 2));
use = new JCheckBox("Use");
JLabel specs = new JLabel("Constraint");
JLabel color = new JLabel("Color");
boxes = new ArrayList<JCheckBox>();
series = new ArrayList<JTextField>();
colorsCombo = new ArrayList<JComboBox>();
colorsButtons = new ArrayList<JButton>();
use.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (use.isSelected()) {
for (JCheckBox box : boxes) {
if (!box.isSelected()) {
box.doClick();
}
}
}
else {
for (JCheckBox box : boxes) {
if (box.isSelected()) {
box.doClick();
}
}
}
}
});
speciesPanel1.add(use);
speciesPanel2.add(specs);
speciesPanel2.add(color);
final HashMap<String, Paint> colory = this.colors;
for (int i = 0; i < graphProbs.size(); i++) {
JCheckBox temp = new JCheckBox();
temp.setActionCommand("" + i);
temp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (((JCheckBox) e.getSource()).isSelected()) {
node.setIcon(TextIcons.getIcon("g"));
node.setIconName("" + (char) 10003);
IconNode n = ((IconNode) node.getParent());
while (n != null) {
n.setIcon(MetalIconFactory.getFileChooserUpFolderIcon());
n.setIconName("" + (char) 10003);
if (n.getParent() == null) {
n = null;
}
else {
n = ((IconNode) n.getParent());
}
}
tree.revalidate();
tree.repaint();
String s = series.get(i).getText();
((JCheckBox) e.getSource()).setSelected(false);
int[] cols = new int[35];
for (int k = 0; k < boxes.size(); k++) {
if (boxes.get(k).isSelected()) {
if (colorsCombo.get(k).getSelectedItem().equals("Red")) {
cols[0]++;
colorsButtons.get(k).setBackground((Color) colory.get("Red"));
colorsButtons.get(k).setForeground((Color) colory.get("Red"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue")) {
cols[1]++;
colorsButtons.get(k).setBackground((Color) colory.get("Blue"));
colorsButtons.get(k).setForeground((Color) colory.get("Blue"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Green")) {
cols[2]++;
colorsButtons.get(k).setBackground((Color) colory.get("Green"));
colorsButtons.get(k).setForeground((Color) colory.get("Green"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Yellow")) {
cols[3]++;
colorsButtons.get(k)
.setBackground((Color) colory.get("Yellow"));
colorsButtons.get(k)
.setForeground((Color) colory.get("Yellow"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Magenta")) {
cols[4]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan")) {
cols[5]++;
colorsButtons.get(k).setBackground((Color) colory.get("Cyan"));
colorsButtons.get(k).setForeground((Color) colory.get("Cyan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Tan")) {
cols[6]++;
colorsButtons.get(k).setBackground((Color) colory.get("Tan"));
colorsButtons.get(k).setForeground((Color) colory.get("Tan"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Gray (Dark)")) {
cols[7]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Gray (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Gray (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Dark)")) {
cols[8]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Red (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Red (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Blue (Dark)")) {
cols[9]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Blue (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Blue (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Green (Dark)")) {
cols[10]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Green (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Green (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Yellow (Dark)")) {
cols[11]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Yellow (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Yellow (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Magenta (Dark)")) {
cols[12]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Cyan (Dark)")) {
cols[13]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Cyan (Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Cyan (Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Black")) {
cols[14]++;
colorsButtons.get(k).setBackground((Color) colory.get("Black"));
colorsButtons.get(k).setForeground((Color) colory.get("Black"));
}
/*
* else if
* (colorsCombo.get(k).getSelectedItem().
* equals("Red ")) { cols[15]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Blue ")) {
* cols[16]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Green ")) { cols[17]++; } else if
* (colorsCombo.get(k).getSelectedItem().equals(
* "Yellow ")) { cols[18]++; } else if
* (colorsCombo
* .get(k).getSelectedItem().equals("Magenta "))
* { cols[19]++; } else if
* (colorsCombo.get(k).getSelectedItem
* ().equals("Cyan ")) { cols[20]++; }
*/
else if (colorsCombo.get(k).getSelectedItem().equals("Gray")) {
cols[21]++;
colorsButtons.get(k).setBackground((Color) colory.get("Gray"));
colorsButtons.get(k).setForeground((Color) colory.get("Gray"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Red (Extra Dark)")) {
cols[22]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Red (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Red (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Blue (Extra Dark)")) {
cols[23]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Blue (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Blue (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Green (Extra Dark)")) {
cols[24]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Green (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Green (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Yellow (Extra Dark)")) {
cols[25]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Yellow (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Yellow (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Magenta (Extra Dark)")) {
cols[26]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Cyan (Extra Dark)")) {
cols[27]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Cyan (Extra Dark)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Cyan (Extra Dark)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals("Red (Light)")) {
cols[28]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Red (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Red (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Blue (Light)")) {
cols[29]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Blue (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Blue (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Green (Light)")) {
cols[30]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Green (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Green (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Yellow (Light)")) {
cols[31]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Yellow (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Yellow (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem().equals(
"Magenta (Light)")) {
cols[32]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Magenta (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Magenta (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Cyan (Light)")) {
cols[33]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Cyan (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Cyan (Light)"));
}
else if (colorsCombo.get(k).getSelectedItem()
.equals("Gray (Light)")) {
cols[34]++;
colorsButtons.get(k).setBackground(
(Color) colory.get("Gray (Light)"));
colorsButtons.get(k).setForeground(
(Color) colory.get("Gray (Light)"));
}
}
}
for (GraphProbs graph : probGraphed) {
if (graph.getPaintName().equals("Red")) {
cols[0]++;
}
else if (graph.getPaintName().equals("Blue")) {
cols[1]++;
}
else if (graph.getPaintName().equals("Green")) {
cols[2]++;
}
else if (graph.getPaintName().equals("Yellow")) {
cols[3]++;
}
else if (graph.getPaintName().equals("Magenta")) {
cols[4]++;
}
else if (graph.getPaintName().equals("Cyan")) {
cols[5]++;
}
else if (graph.getPaintName().equals("Tan")) {
cols[6]++;
}
else if (graph.getPaintName().equals("Gray (Dark)")) {
cols[7]++;
}
else if (graph.getPaintName().equals("Red (Dark)")) {
cols[8]++;
}
else if (graph.getPaintName().equals("Blue (Dark)")) {
cols[9]++;
}
else if (graph.getPaintName().equals("Green (Dark)")) {
cols[10]++;
}
else if (graph.getPaintName().equals("Yellow (Dark)")) {
cols[11]++;
}
else if (graph.getPaintName().equals("Magenta (Dark)")) {
cols[12]++;
}
else if (graph.getPaintName().equals("Cyan (Dark)")) {
cols[13]++;
}
else if (graph.getPaintName().equals("Black")) {
cols[14]++;
}
/*
* else if (graph.getPaintName().equals("Red ")) {
* cols[15]++; } else if
* (graph.getPaintName().equals("Blue ")) {
* cols[16]++; } else if
* (graph.getPaintName().equals("Green ")) {
* cols[17]++; } else if
* (graph.getPaintName().equals("Yellow ")) {
* cols[18]++; } else if
* (graph.getPaintName().equals("Magenta ")) {
* cols[19]++; } else if
* (graph.getPaintName().equals("Cyan ")) {
* cols[20]++; }
*/
else if (graph.getPaintName().equals("Gray")) {
cols[21]++;
}
else if (graph.getPaintName().equals("Red (Extra Dark)")) {
cols[22]++;
}
else if (graph.getPaintName().equals("Blue (Extra Dark)")) {
cols[23]++;
}
else if (graph.getPaintName().equals("Green (Extra Dark)")) {
cols[24]++;
}
else if (graph.getPaintName().equals("Yellow (Extra Dark)")) {
cols[25]++;
}
else if (graph.getPaintName().equals("Magenta (Extra Dark)")) {
cols[26]++;
}
else if (graph.getPaintName().equals("Cyan (Extra Dark)")) {
cols[27]++;
}
else if (graph.getPaintName().equals("Red (Light)")) {
cols[28]++;
}
else if (graph.getPaintName().equals("Blue (Light)")) {
cols[29]++;
}
else if (graph.getPaintName().equals("Green (Light)")) {
cols[30]++;
}
else if (graph.getPaintName().equals("Yellow (Light)")) {
cols[31]++;
}
else if (graph.getPaintName().equals("Magenta (Light)")) {
cols[32]++;
}
else if (graph.getPaintName().equals("Cyan (Light)")) {
cols[33]++;
}
else if (graph.getPaintName().equals("Gray (Light)")) {
cols[34]++;
}
}
((JCheckBox) e.getSource()).setSelected(true);
series.get(i).setText(s);
series.get(i).setSelectionStart(0);
series.get(i).setSelectionEnd(0);
int colorSet = 0;
for (int j = 1; j < cols.length; j++) {
if ((j < 15 || j > 20) && cols[j] < cols[colorSet]) {
colorSet = j;
}
}
DefaultDrawingSupplier draw = new DefaultDrawingSupplier();
Paint paint;
if (colorSet == 34) {
paint = colors.get("Gray (Light)");
}
else {
for (int j = 0; j < colorSet; j++) {
draw.getNextPaint();
}
paint = draw.getNextPaint();
}
Object[] set = colory.keySet().toArray();
for (int j = 0; j < set.length; j++) {
if (paint == colory.get(set[j])) {
colorsCombo.get(i).setSelectedItem(set[j]);
colorsButtons.get(i).setBackground((Color) paint);
colorsButtons.get(i).setForeground((Color) paint);
}
}
boolean allChecked = true;
for (JCheckBox temp : boxes) {
if (!temp.isSelected()) {
allChecked = false;
}
}
if (allChecked) {
use.setSelected(true);
}
String color = (String) colorsCombo.get(i).getSelectedItem();
if (color.equals("Custom")) {
color += "_" + colorsButtons.get(i).getBackground().getRGB();
}
probGraphed.add(new GraphProbs(colorsButtons.get(i).getBackground(), color,
boxes.get(i).getName(), series.get(i).getText().trim(), i,
directory));
}
else {
boolean check = false;
for (JCheckBox b : boxes) {
if (b.isSelected()) {
check = true;
}
}
if (!check) {
node.setIcon(MetalIconFactory.getTreeLeafIcon());
node.setIconName("");
boolean check2 = false;
IconNode parent = ((IconNode) node.getParent());
while (parent != null) {
for (int j = 0; j < parent.getChildCount(); j++) {
if (((IconNode) parent.getChildAt(j)).getIconName().equals(
"" + (char) 10003)) {
check2 = true;
}
}
if (!check2) {
parent.setIcon(MetalIconFactory.getTreeFolderIcon());
parent.setIconName("");
}
check2 = false;
if (parent.getParent() == null) {
parent = null;
}
else {
parent = ((IconNode) parent.getParent());
}
}
tree.revalidate();
tree.repaint();
}
ArrayList<GraphProbs> remove = new ArrayList<GraphProbs>();
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
remove.add(g);
}
}
for (GraphProbs g : remove) {
probGraphed.remove(g);
}
use.setSelected(false);
colorsCombo.get(i).setSelectedIndex(0);
colorsButtons.get(i).setBackground((Color) colory.get("Black"));
colorsButtons.get(i).setForeground((Color) colory.get("Black"));
}
}
});
boxes.add(temp);
JTextField seriesName = new JTextField(graphProbs.get(i));
seriesName.setName("" + i);
seriesName.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyReleased(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
public void keyTyped(KeyEvent e) {
int i = Integer.parseInt(((JTextField) e.getSource()).getName());
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setSpecies(((JTextField) e.getSource()).getText());
}
}
}
});
series.add(seriesName);
ArrayList<String> allColors = new ArrayList<String>();
for (String c : this.colors.keySet()) {
allColors.add(c);
}
allColors.add("Custom");
Object[] col = allColors.toArray();
Arrays.sort(col);
JComboBox colBox = new JComboBox(col);
colBox.setActionCommand("" + i);
colBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
if (!((JComboBox) (e.getSource())).getSelectedItem().equals("Custom")) {
colorsButtons.get(i)
.setBackground(
(Color) colors.get(((JComboBox) (e.getSource()))
.getSelectedItem()));
colorsButtons.get(i)
.setForeground(
(Color) colors.get(((JComboBox) (e.getSource()))
.getSelectedItem()));
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName((String) ((JComboBox) e.getSource())
.getSelectedItem());
g.setPaint(colory
.get(((JComboBox) e.getSource()).getSelectedItem()));
}
}
}
else {
for (GraphProbs g : probGraphed) {
if (g.getNumber() == i && g.getDirectory().equals(directory)) {
g.setPaintName("Custom_"
+ colorsButtons.get(i).getBackground().getRGB());
g.setPaint(colorsButtons.get(i).getBackground());
}
}
}
}
});
colorsCombo.add(colBox);
JButton colorButton = new JButton();
colorButton.setPreferredSize(new Dimension(30, 20));
colorButton.setBorder(BorderFactory.createLineBorder(Color.darkGray));
colorButton.setBackground((Color) colory.get("Black"));
colorButton.setForeground((Color) colory.get("Black"));
colorButton.setUI(new MetalButtonUI());
colorButton.setActionCommand("" + i);
colorButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int i = Integer.parseInt(e.getActionCommand());
Color newColor = JColorChooser.showDialog(Gui.frame, "Choose Color",
((JButton) e.getSource()).getBackground());
if (newColor != null) {
((JButton) e.getSource()).setBackground(newColor);
((JButton) e.getSource()).setForeground(newColor);
colorsCombo.get(i).setSelectedItem("Custom");
}
}
});
colorsButtons.add(colorButton);
JPanel colorPanel = new JPanel(new BorderLayout());
colorPanel.add(colorsCombo.get(i), "Center");
colorPanel.add(colorsButtons.get(i), "East");
speciesPanel1.add(boxes.get(i));
speciesPanel2.add(series.get(i));
speciesPanel2.add(colorPanel);
}
JPanel speciesPanel = new JPanel(new BorderLayout());
speciesPanel.add(speciesPanel1, "West");
speciesPanel.add(speciesPanel2, "Center");
return speciesPanel;
}
private void readProbSpecies(String file) {
graphProbs = new ArrayList<String>();
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination")
&& ss[3].equals("count:") && ss[4].equals("0")) {
return;
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
for (String s : data) {
if (!s.split(" ")[0].equals("#total")) {
graphProbs.add(s.split(" ")[0]);
}
}
}
private double[] readProbs(String file) {
ArrayList<String> data = new ArrayList<String>();
try {
Scanner s = new Scanner(new File(file));
while (s.hasNextLine()) {
String[] ss = s.nextLine().split(" ");
if (ss[0].equals("The") && ss[1].equals("total") && ss[2].equals("termination")
&& ss[3].equals("count:") && ss[4].equals("0")) {
return new double[0];
}
if (data.size() == 0) {
for (String add : ss) {
data.add(add);
}
}
else {
for (int i = 0; i < ss.length; i++) {
data.set(i, data.get(i) + " " + ss[i]);
}
}
}
}
catch (Exception e) {
}
double[] dataSet = new double[data.size()];
double total = 0;
int i = 0;
if (data.get(0).split(" ")[0].equals("#total")) {
total = Double.parseDouble(data.get(0).split(" ")[1]);
i = 1;
}
for (; i < data.size(); i++) {
if (total == 0) {
dataSet[i] = Double.parseDouble(data.get(i).split(" ")[1]);
}
else {
dataSet[i - 1] = 100 * ((Double.parseDouble(data.get(i).split(" ")[1])) / total);
}
}
return dataSet;
}
private void fixProbGraph(String label, String xLabel, String yLabel,
DefaultCategoryDataset dataset, BarRenderer rend) {
Paint chartBackground = chart.getBackgroundPaint();
Paint plotBackground = chart.getPlot().getBackgroundPaint();
Paint plotRangeGridLine = chart.getCategoryPlot().getRangeGridlinePaint();
chart = ChartFactory.createBarChart(label, xLabel, yLabel, dataset,
PlotOrientation.VERTICAL, true, true, false);
chart.getCategoryPlot().setRenderer(rend);
chart.setBackgroundPaint(chartBackground);
chart.getPlot().setBackgroundPaint(plotBackground);
chart.getCategoryPlot().setRangeGridlinePaint(plotRangeGridLine);
ChartPanel graph = new ChartPanel(chart);
legend = chart.getLegend();
if (visibleLegend.isSelected()) {
if (chart.getLegend() == null) {
chart.addLegend(legend);
}
}
else {
if (chart.getLegend() != null) {
legend = chart.getLegend();
}
chart.removeLegend();
}
if (probGraphed.isEmpty()) {
graph.setLayout(new GridLayout(1, 1));
JLabel edit = new JLabel("Double click here to create graph");
edit.addMouseListener(this);
Font font = edit.getFont();
font = font.deriveFont(Font.BOLD, 42.0f);
edit.setFont(font);
edit.setHorizontalAlignment(SwingConstants.CENTER);
graph.add(edit);
}
graph.addMouseListener(this);
JPanel ButtonHolder = new JPanel();
run = new JButton("Save and Run");
save = new JButton("Save Graph");
saveAs = new JButton("Save As");
export = new JButton("Export");
refresh = new JButton("Refresh");
run.addActionListener(this);
save.addActionListener(this);
saveAs.addActionListener(this);
export.addActionListener(this);
refresh.addActionListener(this);
if (reb2sac != null) {
ButtonHolder.add(run);
}
ButtonHolder.add(save);
ButtonHolder.add(saveAs);
ButtonHolder.add(export);
ButtonHolder.add(refresh);
// JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
// ButtonHolder, null);
// splitPane.setDividerSize(0);
this.removeAll();
this.setLayout(new BorderLayout());
this.add(graph, "Center");
// this.add(splitPane, "South");
this.revalidate();
}
public void refreshProb() {
BarRenderer rend = (BarRenderer) chart.getCategoryPlot().getRenderer();
int thisOne = -1;
for (int i = 1; i < probGraphed.size(); i++) {
GraphProbs index = probGraphed.get(i);
int j = i;
while ((j > 0)
&& (probGraphed.get(j - 1).getSpecies().compareToIgnoreCase(index.getSpecies()) > 0)) {
probGraphed.set(j, probGraphed.get(j - 1));
j = j - 1;
}
probGraphed.set(j, index);
}
ArrayList<GraphProbs> unableToGraph = new ArrayList<GraphProbs>();
DefaultCategoryDataset histDataset = new DefaultCategoryDataset();
for (GraphProbs g : probGraphed) {
if (g.getDirectory().equals("")) {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + "sim-rep.txt").exists()) {
readProbSpecies(outDir + separator + "sim-rep.txt");
double[] data = readProbs(outDir + separator + "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
if (g.getID().equals(graphProbs.get(i))) {
g.setNumber(i);
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
else {
thisOne++;
rend.setSeriesPaint(thisOne, g.getPaint());
if (new File(outDir + separator + g.getDirectory() + separator + "sim-rep.txt")
.exists()) {
readProbSpecies(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
double[] data = readProbs(outDir + separator + g.getDirectory() + separator
+ "sim-rep.txt");
for (int i = 1; i < graphProbs.size(); i++) {
String index = graphProbs.get(i);
double index2 = data[i];
int j = i;
while ((j > 0) && graphProbs.get(j - 1).compareToIgnoreCase(index) > 0) {
graphProbs.set(j, graphProbs.get(j - 1));
data[j] = data[j - 1];
j = j - 1;
}
graphProbs.set(j, index);
data[j] = index2;
}
if (graphProbs.size() != 0) {
for (int i = 0; i < graphProbs.size(); i++) {
String compare = g.getID().replace(" (", "~");
if (compare.split("~")[0].trim().equals(graphProbs.get(i))) {
histDataset.setValue(data[i], g.getSpecies(), "");
}
}
}
}
else {
unableToGraph.add(g);
thisOne
}
}
}
for (GraphProbs g : unableToGraph) {
probGraphed.remove(g);
}
fixProbGraph(chart.getTitle().getText(),
chart.getCategoryPlot().getDomainAxis().getLabel(), chart.getCategoryPlot()
.getRangeAxis().getLabel(), histDataset, rend);
}
private void updateSpecies() {
String background;
try {
Properties p = new Properties();
String[] split = outDir.split(separator);
FileInputStream load = new FileInputStream(new File(outDir + separator
+ split[split.length - 1] + ".lrn"));
p.load(load);
load.close();
if (p.containsKey("genenet.file")) {
String[] getProp = p.getProperty("genenet.file").split(separator);
background = outDir
.substring(0, outDir.length() - split[split.length - 1].length())
+ separator + getProp[getProp.length - 1];
}
else if (p.containsKey("learn.file")) {
String[] getProp = p.getProperty("learn.file").split(separator);
background = outDir
.substring(0, outDir.length() - split[split.length - 1].length())
+ separator + getProp[getProp.length - 1];
}
else {
background = null;
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(Gui.frame, "Unable to load background file.", "Error",
JOptionPane.ERROR_MESSAGE);
background = null;
}
learnSpecs = new ArrayList<String>();
if (background != null) {
if (background.contains(".gcm")) {
GCMFile gcm = new GCMFile(biomodelsim.getRoot());
gcm.load(background);
HashMap<String, Properties> speciesMap = gcm.getSpecies();
for (String s : speciesMap.keySet()) {
learnSpecs.add(s);
}
}
else if (background.contains(".lpn")) {
LhpnFile lhpn = new LhpnFile(biomodelsim.log);
lhpn.load(background);
HashMap<String, Properties> speciesMap = lhpn.getContinuous();
/*
* for (String s : speciesMap.keySet()) { learnSpecs.add(s); }
*/
// ADDED BY SB.
TSDParser extractVars;
ArrayList<String> datFileVars = new ArrayList<String>();
// ArrayList<String> allVars = new ArrayList<String>();
Boolean varPresent = false;
// Finding the intersection of all the variables present in all
// data files.
for (int i = 1; (new File(outDir + separator + "run-" + i + ".tsd")).exists(); i++) {
extractVars = new TSDParser(outDir + separator + "run-" + i + ".tsd", false);
datFileVars = extractVars.getSpecies();
if (i == 1) {
learnSpecs.addAll(datFileVars);
}
for (String s : learnSpecs) {
varPresent = false;
for (String t : datFileVars) {
if (s.equalsIgnoreCase(t)) {
varPresent = true;
break;
}
}
if (!varPresent) {
learnSpecs.remove(s);
}
}
}
// END ADDED BY SB.
}
else {
SBMLDocument document = Gui.readSBML(background);
Model model = document.getModel();
ListOf ids = model.getListOfSpecies();
for (int i = 0; i < model.getNumSpecies(); i++) {
learnSpecs.add(((Species) ids.get(i)).getId());
}
}
}
for (int i = 0; i < learnSpecs.size(); i++) {
String index = learnSpecs.get(i);
int j = i;
while ((j > 0) && learnSpecs.get(j - 1).compareToIgnoreCase(index) > 0) {
learnSpecs.set(j, learnSpecs.get(j - 1));
j = j - 1;
}
learnSpecs.set(j, index);
}
}
public boolean getWarning() {
return warn;
}
private class GraphProbs {
private Paint paint;
private String species, directory, id, paintName;
private int number;
private GraphProbs(Paint paint, String paintName, String id, String species, int number,
String directory) {
this.paint = paint;
this.paintName = paintName;
this.species = species;
this.number = number;
this.directory = directory;
this.id = id;
}
private Paint getPaint() {
return paint;
}
private void setPaint(Paint p) {
paint = p;
}
private String getPaintName() {
return paintName;
}
private void setPaintName(String p) {
paintName = p;
}
private String getSpecies() {
return species;
}
private void setSpecies(String s) {
species = s;
}
private String getDirectory() {
return directory;
}
private String getID() {
return id;
}
private int getNumber() {
return number;
}
private void setNumber(int n) {
number = n;
}
}
private Hashtable makeIcons() {
Hashtable<String, Icon> icons = new Hashtable<String, Icon>();
icons.put("floppyDrive", MetalIconFactory.getTreeFloppyDriveIcon());
icons.put("hardDrive", MetalIconFactory.getTreeHardDriveIcon());
icons.put("computer", MetalIconFactory.getTreeComputerIcon());
icons.put("c", TextIcons.getIcon("c"));
icons.put("java", TextIcons.getIcon("java"));
icons.put("html", TextIcons.getIcon("html"));
return icons;
}
}
class IconNodeRenderer extends DefaultTreeCellRenderer {
private static final long serialVersionUID = -940588131120912851L;
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
Icon icon = ((IconNode) value).getIcon();
if (icon == null) {
Hashtable icons = (Hashtable) tree.getClientProperty("JTree.icons");
String name = ((IconNode) value).getIconName();
if ((icons != null) && (name != null)) {
icon = (Icon) icons.get(name);
if (icon != null) {
setIcon(icon);
}
}
}
else {
setIcon(icon);
}
return this;
}
}
class IconNode extends DefaultMutableTreeNode {
private static final long serialVersionUID = 2887169888272379817L;
protected Icon icon;
protected String iconName;
private String hiddenName;
public IconNode() {
this(null, "");
}
public IconNode(Object userObject, String name) {
this(userObject, true, null, name);
}
public IconNode(Object userObject, boolean allowsChildren, Icon icon, String name) {
super(userObject, allowsChildren);
this.icon = icon;
hiddenName = name;
}
public String getName() {
return hiddenName;
}
public void setName(String name) {
hiddenName = name;
}
public void setIcon(Icon icon) {
this.icon = icon;
}
public Icon getIcon() {
return icon;
}
public String getIconName() {
if (iconName != null) {
return iconName;
}
else {
String str = userObject.toString();
int index = str.lastIndexOf(".");
if (index != -1) {
return str.substring(++index);
}
else {
return null;
}
}
}
public void setIconName(String name) {
iconName = name;
}
}
class TextIcons extends MetalIconFactory.TreeLeafIcon {
private static final long serialVersionUID = 1623303213056273064L;
protected String label;
private static Hashtable<String, String> labels;
protected TextIcons() {
}
public void paintIcon(Component c, Graphics g, int x, int y) {
super.paintIcon(c, g, x, y);
if (label != null) {
FontMetrics fm = g.getFontMetrics();
int offsetX = (getIconWidth() - fm.stringWidth(label)) / 2;
int offsetY = (getIconHeight() - fm.getHeight()) / 2 - 2;
g.drawString(label, x + offsetX, y + offsetY + fm.getHeight());
}
}
public static Icon getIcon(String str) {
if (labels == null) {
labels = new Hashtable<String, String>();
setDefaultSet();
}
TextIcons icon = new TextIcons();
icon.label = (String) labels.get(str);
return icon;
}
public static void setLabelSet(String ext, String label) {
if (labels == null) {
labels = new Hashtable<String, String>();
setDefaultSet();
}
labels.put(ext, label);
}
private static void setDefaultSet() {
labels.put("c", "C");
labels.put("java", "J");
labels.put("html", "H");
labels.put("htm", "H");
labels.put("g", "" + (char) 10003);
// and so on
/*
* labels.put("txt" ,"TXT"); labels.put("TXT" ,"TXT"); labels.put("cc"
* ,"C++"); labels.put("C" ,"C++"); labels.put("cpp" ,"C++");
* labels.put("exe" ,"BIN"); labels.put("class" ,"BIN");
* labels.put("gif" ,"GIF"); labels.put("GIF" ,"GIF");
*
* labels.put("", "");
*/
}
} |
package de.fun2code.android.piratebox;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Environment;
import android.preference.PreferenceManager;
/**
* Constants that are used throughout the app
*
* @author joschi
*
*/
public class Constants {
private static String INSTALL_DIR;
public static final String TAG = "PirateBox";
public static final String PREF_START_ON_BOOT = "startOnBoot";
public static final String PREF_SSID_NAME = "ssidName";
public static final String PREF_AP_IP = "apIp";
public static final String PREF_DOMAIN_NAME = "domainName";
public static final String PREF_STORAGE_DIR = "storageDir";
public static final String PREF_IOS_WISPR_SUPPORT = "iosWispr";
public static final String PREF_WP_NCSI_SUPPORT = "wpNcsi";
public static final String PREF_VERSION = "version";
public static final String PREF_UPDATE = "update";
public static final String PREF_AUTO_AP_STARTUP = "autoApStartup";
public static final String PREF_DEV_CONTENT_SD = "devContentSd";
public static final String PREF_DEV_INFO_PIRATEBOX_VERSION = "infoPirateBoxVersion";
public static final String PREF_DEV_INFO_PAW_VERSION = "infoPawVersion";
public static final String PREF_DEV_INFO_AP_IP_ADDRESS = "infoApIpAddress";
public static final String PREF_DEV_INFO_IP_ADDRESS = "infoIpAddress";
public static final String PREF_DEV_INFO_LOCAL_PORT = "infoLocalPort";
public static final String PREF_DEV_INFO_UPLOADS = "infoUploads";
public static final String PREF_DEV_INFO_MESSAGES = "infoMessages";
public static final String PREF_DEV_INFO_CONNECTIONS = "infoConnections";
public static final String PREF_DEV_INFO_MAX_UPLOAD_SIZE = "infoMaxUploadSize";
public static final String PREF_DEV_RESTORE_DNSMASQ = "restoreDnsMasq";
public static final String PREF_DEV_RESET_NETWORKING = "resetNetworking";
public static final String PREF_EMULATE_DROOPY = "emulateDroopy";
public static final String PREF_KEEP_DEVICE_ON = "keepDeviceOn";
public static final String PREF_ENABLE_STATISTICS = "enableStatistics";
public static final String PREF_CLEAR_STATISTICS = "clearStatistics";
public static final String AP_IP_DEFAULT = "192.168.43.1"; // Default AP IP address
public static final String NAT_TABLE_NAME = "nat";
public static final int DEFAULT_MAX_POST = 209715200; // Default upload size
// Database constants
public static final String STATS_DATABASE_NAME = "statistics";
public static final int STATS_DATABASE_VERSION = 1;
public static final String STATS_TABLE_VISITORS = "vc_statistics";
public static final String STATS_TABLE_DOWNLOADS = "dl_statistics";
//public static final String DEV_SWITCH_FILE = Environment.getExternalStorageDirectory().getPath() + "/.piratebox_dev";
public static final String BROADCAST_INTENT_SERVER = "de.fun2code.android.piratebox.broadcast.intent.SERVER";
public static final String INTENT_SERVER_EXTRA_STATE = "SERVER_STATE";
public static final String BROADCAST_INTENT_AP = "de.fun2code.android.piratebox.broadcast.intent.AP";
public static final String INTENT_AP_EXTRA_STATE = "AP_STATE";
public static final String BROADCAST_INTENT_NETWORK = "de.fun2code.android.piratebox.broadcast.intent.NETWORK";
public static final String INTENT_NETWORK_EXTRA_STATE = "NETWORK_STATE";
public static final String BROADCAST_INTENT_SHOUT = "de.fun2code.android.piratebox.broadcast.intent.SHOUT";
public static final String INTENT_SHOUT_EXTRA_NAME = "SHOUT_NAME";
public static final String INTENT_SHOUT_EXTRA_TEXT = "SHOUT_TEXT";
public static final String INTENT_SHOUT_EXTRA_NUMBER = "SHOUT_NUMBER";
public static final String INTENT_SHOUT_EXTRA_DIR = "SHOUT_DIR";
public static final String BROADCAST_INTENT_UPLOAD = "de.fun2code.android.piratebox.broadcast.intent.UPLOAD";
public static final String INTENT_UPLOAD_EXTRA_FILE = "UPLOAD_FILE";
public static final String INTENT_UPLOAD_EXTRA_NUMBER = "UPLOAD_NUMBER";
public static final String INTENT_UPLOAD_EXTRA_DIR = "UPLOAD_DIR";
public static final String BROADCAST_INTENT_CONNECTION = "de.fun2code.android.piratebox.broadcast.intent.CONNECTION";
public static final String INTENT_CONNECTION_EXTRA_NUMBER = "CONNECTION_NUMBER";
public static final String BROADCAST_INTENT_STATUS_REQUEST = "de.fun2code.android.piratebox.broadcast.intent.STATUS_REQUEST";
public static final String BROADCAST_INTENT_STATUS_RESULT = "de.fun2code.android.piratebox.broadcast.intent.STATUS_RESULT";
/**
* Returns the directory PirateBox will be installed to
*
* @param context {@code Context} to use
* @return PirateBox installation directory
*/
public static String getInstallDir(Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
if(INSTALL_DIR == null) {
//if(new File(DEV_SWITCH_FILE).exists()) {
if(preferences.getBoolean(PREF_DEV_CONTENT_SD, false)) {
// Use external storage
INSTALL_DIR = Environment.getExternalStorageDirectory().getPath() + "/piratebox";
}
else {
// Use /data/data/... directory
INSTALL_DIR = context.getFilesDir().getAbsolutePath() + "/piratebox";
}
}
return INSTALL_DIR;
}
/**
* Resets the installation directory
*/
public static void resetInstallDir() {
INSTALL_DIR = null;
}
} |
package org.jetel.component;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
import org.jetel.component.rollup.RecordRollup;
import org.jetel.component.rollup.RecordRollupTL;
import org.jetel.data.DataRecord;
import org.jetel.data.Defaults;
import org.jetel.data.DoubleRecordBuffer;
import org.jetel.data.HashKey;
import org.jetel.data.RecordKey;
import org.jetel.exception.AttributeNotFoundException;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.ConfigurationProblem;
import org.jetel.exception.ConfigurationStatus;
import org.jetel.exception.JetelException;
import org.jetel.exception.NotInitializedException;
import org.jetel.exception.TransformException;
import org.jetel.exception.XMLConfigurationException;
import org.jetel.exception.ConfigurationStatus.Priority;
import org.jetel.exception.ConfigurationStatus.Severity;
import org.jetel.graph.InputPort;
import org.jetel.graph.Node;
import org.jetel.graph.Result;
import org.jetel.graph.TransformationGraph;
import org.jetel.metadata.DataRecordMetadata;
import org.jetel.util.SynchronizeUtils;
import org.jetel.util.compile.DynamicJavaCode;
import org.jetel.util.file.FileUtils;
import org.jetel.util.property.ComponentXMLAttributes;
import org.jetel.util.string.StringUtils;
import org.w3c.dom.Element;
/**
* <h3>Rollup Component</h3>
*
* <p>Executes the rollup transform on all the input data records.</p>
*
* <h4>Component:</h4>
* <table border="1">
* <tr>
* <td><b>Name:</b></td>
* <td>Rollup</td>
* </tr>
* <tr>
* <td><b>Category:</b></td>
* <td>transformers</td>
* </tr>
* <tr>
* <td><b>Description:</b></td>
* <td>
* Serves as an executor of rollup transforms written in Java or CTL. See the {@link RecordRollup} interface
* for more details on the life cycle of the rollup transform.
* </td>
* </tr>
* <tr>
* <td><b>Inputs:</b></td>
* <td>[0] - input data records</td>
* </tr>
* <tr>
* <td><b>Outputs:</b></td>
* <td>At least one connected output port.</td>
* </tr>
* </table>
*
* <h4>XML attributes:</h4>
* <table border="1">
* <tr>
* <td><b>id</b></td>
* <td>ID of the component.</td>
* </tr>
* <tr>
* <td><b>type</b></td>
* <td>ROLLUP</td>
* </tr>
* <tr>
* <td><b>groupKeyFields</b></td>
* <td>Field names that form the group key separated by ':', ';' or '|'.</td>
* </tr>
* <tr>
* <td>
* <b>groupAccumulatorMetadataId</b><br>
* <i>optional</i>
* </td>
* <td>ID of data record meta data that should be used to create group "accumulators" (if required).</td>
* </tr>
* <tr>
* <td><b>transform</b></td>
* <td>Rollup transform as a Java or CTL source code.</td>
* </tr>
* <tr>
* <td><b>transformUrl</b></td>
* <td>URL of an external Java/CTL source code of the rollup transform.</td>
* </tr>
* <tr>
* <td>
* <b>transformUrlCharset</b><br>
* <i>optional</i>
* </td>
* <td>Character set used in the source code of the rollup transform specified via an URL.</td>
* </tr>
* <tr>
* <td><b>transformClassName</b></td>
* <td>Class name of a Java class implementing the rollup transform.</td>
* </tr>
* <tr>
* <td>
* <b>inputSorted</b><br>
* <i>optional</i>
* </td>
* <td>
* Flag specifying whether the input data records are sorted or not. If set to false, the order of output
* data records is not specified.
* </td>
* </tr>
* </table>
*
* @author Martin Janik, Javlin a.s. <martin.janik@javlin.eu>
*
* @version 12th June 2009
* @since 30th April 2009
*
* @see RecordRollup
*/
public class Rollup extends Node {
/** the type of the component */
private static final String COMPONENT_TYPE = "ROLLUP";
// names of XML attributes
/** the name of an XML attribute used to store the group key fields */
private static final String XML_GROUP_KEY_FIELDS_ATTRIBUTE = "groupKeyFields";
/** the name of an XML attribute used to store the ID of the group "accumulator" meta data */
private static final String XML_GROUP_ACCUMULATOR_METADATA_ID_ATTRIBUTE = "groupAccumulatorMetadataId";
/** the name of an XML attribute used to store the source code of a Java/CTL transform */
private static final String XML_TRANSFORM_ATTRIBUTE = "transform";
/** the name of an XML attribute used to store the URL of an external Java/CTL transform */
private static final String XML_TRANSFORM_URL_ATTRIBUTE = "transformUrl";
/** the name of an XML attribute used to store the character set used in the rollup transform specified via an URL */
private static final String XML_TRANSFORM_URL_CHARSET_ATTRIBUTE = "transformUrlCharset";
/** the name of an XML attribute used to store the class name of a Java transform */
private static final String XML_TRANSFORM_CLASS_NAME_ATTRIBUTE = "transformClassName";
/** the name of an XML attribute used to store the "input sorted" flag */
private static final String XML_INPUT_SORTED_ATTRIBUTE = "inputSorted";
// constants used during execution
/** the port index used for data record input */
private static final int INPUT_PORT_NUMBER = 0;
/** the regular expression pattern that should be present in a Java source code transformation */
private static final String REGEX_JAVA_CLASS = "class\\s+\\w+";
/** the regular expression pattern that should be present in a CTL code transformation */
private static final String REGEX_TL_CODE = "function\\s+((init|update|finish)Group|updateTransform|transform)";
/**
* Creates an instance of the <code>Rollup</code> component from an XML element.
*
* @param transformationGraph the transformation graph the component belongs to
* @param xmlElement the XML element that should be used for construction
*
* @return an instance of the <code>Rollup</code> component
*
* @throws XMLConfigurationException when some attribute is missing
*/
public static Node fromXML(TransformationGraph transformationGraph, Element xmlElement)
throws XMLConfigurationException {
Rollup rollup = null;
ComponentXMLAttributes componentAttributes = new ComponentXMLAttributes(xmlElement, transformationGraph);
try {
if (!componentAttributes.getString(XML_TYPE_ATTRIBUTE).equalsIgnoreCase(COMPONENT_TYPE)) {
throw new XMLConfigurationException("The " + StringUtils.quote(XML_TYPE_ATTRIBUTE)
+ " attribute contains a value incompatible with this component!");
}
rollup = new Rollup(componentAttributes.getString(XML_ID_ATTRIBUTE));
String groupKeyString = componentAttributes.getString(XML_GROUP_KEY_FIELDS_ATTRIBUTE);
rollup.setGroupKeyFields(!StringUtils.isEmpty(groupKeyString)
? groupKeyString.trim().split(Defaults.Component.KEY_FIELDS_DELIMITER_REGEX) : null);
rollup.setGroupAccumulatorMetadataId(
componentAttributes.getString(XML_GROUP_ACCUMULATOR_METADATA_ID_ATTRIBUTE, null));
rollup.setTransform(componentAttributes.getString(XML_TRANSFORM_ATTRIBUTE, null));
rollup.setTransformUrl(componentAttributes.getString(XML_TRANSFORM_URL_ATTRIBUTE, null));
rollup.setTransformUrlCharset(componentAttributes.getString(XML_TRANSFORM_URL_CHARSET_ATTRIBUTE, null));
rollup.setTransformClassName(componentAttributes.getString(XML_TRANSFORM_CLASS_NAME_ATTRIBUTE, null));
rollup.setInputSorted(componentAttributes.getBoolean(XML_INPUT_SORTED_ATTRIBUTE, true));
} catch (AttributeNotFoundException exception) {
throw new XMLConfigurationException("Missing a required attribute!", exception);
} catch (Exception exception) {
throw new XMLConfigurationException("Error creating the component!", exception);
}
return rollup;
}
// component attributes read from or written to an XML document
/** the key fields specifying a key used to separate data records into groups */
private String[] groupKeyFields;
/** the ID of data record meta to be used for the group "accumulator" */
private String groupAccumulatorMetadataId;
/** the source code of a Java/CTL rollup transform */
private String transform;
/** the URL of an external Java/CTL rollup transform */
private String transformUrl;
/** the character set used in the rollup transform specified via an URL */
private String transformUrlCharset;
/** the class name of a Java rollup transform */
private String transformClassName;
/** the flag specifying whether the input data records are sorted or not */
private boolean inputSorted = true;
// runtime attributes initialized in the init() method
/** the group key used to separate data records into groups */
private RecordKey groupKey;
/** an instance of the rollup transform used during the execution */
private RecordRollup recordRollup;
/** the data records used for output */
private DataRecord[] outputRecords;
/**
* Constructs an instance of the <code>Rollup</code> component with the given ID.
*
* @param id an ID of the component
*/
public Rollup(String id) {
super(id);
}
@Override
public String getType() {
return COMPONENT_TYPE;
}
public void setGroupKeyFields(String[] groupKeyFields) {
this.groupKeyFields = groupKeyFields;
}
public void setGroupAccumulatorMetadataId(String groupAccumulatorMetadataId) {
this.groupAccumulatorMetadataId = groupAccumulatorMetadataId;
}
public void setTransform(String transform) {
this.transform = transform;
}
public void setTransformUrl(String transformUrl) {
this.transformUrl = transformUrl;
}
public void setTransformUrlCharset(String transformUrlCharset) {
this.transformUrlCharset = transformUrlCharset;
}
public void setTransformClassName(String transformClassName) {
this.transformClassName = transformClassName;
}
public void setInputSorted(boolean inputSorted) {
this.inputSorted = inputSorted;
}
@Override
public void toXML(Element xmlElement) {
super.toXML(xmlElement);
if (groupKeyFields != null) {
xmlElement.setAttribute(XML_GROUP_KEY_FIELDS_ATTRIBUTE,
StringUtils.stringArraytoString(groupKeyFields, Defaults.Component.KEY_FIELDS_DELIMITER));
}
if (!StringUtils.isEmpty(groupAccumulatorMetadataId)) {
xmlElement.setAttribute(XML_GROUP_ACCUMULATOR_METADATA_ID_ATTRIBUTE, groupAccumulatorMetadataId);
}
if (!StringUtils.isEmpty(transform)) {
xmlElement.setAttribute(XML_TRANSFORM_ATTRIBUTE, transform);
}
if (!StringUtils.isEmpty(transformUrl)) {
xmlElement.setAttribute(XML_TRANSFORM_URL_ATTRIBUTE, transformUrl);
}
if (!StringUtils.isEmpty(transformUrlCharset)) {
xmlElement.setAttribute(XML_TRANSFORM_URL_CHARSET_ATTRIBUTE, transformUrlCharset);
}
if (!StringUtils.isEmpty(transformClassName)) {
xmlElement.setAttribute(XML_TRANSFORM_CLASS_NAME_ATTRIBUTE, transformClassName);
}
if (!inputSorted) {
xmlElement.setAttribute(XML_INPUT_SORTED_ATTRIBUTE, Boolean.toString(inputSorted));
}
}
@Override
public ConfigurationStatus checkConfig(ConfigurationStatus status) {
super.checkConfig(status);
checkInputPorts(status, 1, 1);
checkOutputPorts(status, 1, Integer.MAX_VALUE);
if (groupKeyFields == null || groupKeyFields.length == 0) {
status.add(new ConfigurationProblem("No group key fields specified!",
Severity.ERROR, this, Priority.HIGH, XML_GROUP_KEY_FIELDS_ATTRIBUTE));
} else {
DataRecordMetadata metadata = getInputPort(INPUT_PORT_NUMBER).getMetadata();
for (String groupKeyField : groupKeyFields) {
if (metadata.getField(groupKeyField) == null) {
status.add(new ConfigurationProblem("The group key field " + StringUtils.quote(groupKeyField)
+ " doesn't exist!", Severity.ERROR, this, Priority.HIGH, XML_GROUP_KEY_FIELDS_ATTRIBUTE));
}
}
}
if (groupAccumulatorMetadataId != null && getGraph().getDataRecordMetadata(groupAccumulatorMetadataId) == null) {
status.add(new ConfigurationProblem("The group \"accumulator\" meta data ID is not valid!",
Severity.ERROR, this, Priority.HIGH, XML_GROUP_ACCUMULATOR_METADATA_ID_ATTRIBUTE));
}
if (StringUtils.isEmpty(transform) && StringUtils.isEmpty(transformUrl) && StringUtils.isEmpty(transformClassName)) {
status.add(new ConfigurationProblem("No rollup transform specified!", Severity.ERROR, this, Priority.HIGH));
}
if (transformUrlCharset != null && !Charset.isSupported(transformUrlCharset)) {
status.add(new ConfigurationProblem("The transform URL character set is not supported!",
Severity.ERROR, this, Priority.NORMAL, XML_TRANSFORM_URL_CHARSET_ATTRIBUTE));
}
return status;
}
@Override
public synchronized void init() throws ComponentNotReadyException {
if (isInitialized()) {
throw new IllegalStateException("The component has already been initialized!");
}
super.init();
groupKey = new RecordKey(groupKeyFields, getInputPort(INPUT_PORT_NUMBER).getMetadata());
groupKey.init();
if (transform != null) {
recordRollup = createTransformFromSourceCode(transform);
} else if (transformUrl != null) {
recordRollup = createTransformFromSourceCode(FileUtils.getStringFromURL(
getGraph().getProjectURL(), transformUrl, transformUrlCharset));
} else if (transformClassName != null) {
recordRollup = createTransformFromClassName(transformClassName);
}
recordRollup.init(null, getInputPort(INPUT_PORT_NUMBER).getMetadata(),
getGraph().getDataRecordMetadata(groupAccumulatorMetadataId),
getOutMetadata().toArray(new DataRecordMetadata[getOutPorts().size()]));
outputRecords = new DataRecord[getOutPorts().size()];
for (int i = 0; i < outputRecords.length; i++) {
outputRecords[i] = new DataRecord(getOutputPort(i).getMetadata());
outputRecords[i].init();
}
}
/**
* Creates a rollup transform using the given source code.
*
* @param sourceCode a Java or CTL source code to be used
*
* @return an instance of the <code>RecordRollup</code> transform
*
* @throws ComponentNotReadyException if an error occurred during the instantiation of the transform
* or if the type of the transformation could not be determined
*/
private RecordRollup createTransformFromSourceCode(String sourceCode) throws ComponentNotReadyException {
if (sourceCode.indexOf(WrapperTL.TL_TRANSFORM_CODE_ID) >= 0
|| Pattern.compile(REGEX_TL_CODE).matcher(sourceCode).find()) {
return new RecordRollupTL(sourceCode, getGraph());
}
if (Pattern.compile(REGEX_JAVA_CLASS).matcher(sourceCode).find()) {
try {
return (RecordRollup) new DynamicJavaCode(sourceCode, getClass().getClassLoader()).instantiate();
} catch (ClassCastException exception) {
throw new ComponentNotReadyException(
"The transformation code does not implement the RecordRollup interface!", exception);
} catch (RuntimeException exception) {
throw new ComponentNotReadyException("Cannot compile the transformation code!", exception);
}
}
throw new ComponentNotReadyException("Cannot determine the type of the transformation code!");
}
/**
* Creates a rollup transform using a Java class with the given class name.
*
* @param className a class name of a class to be instantiated
*
* @return an instance of the <code>RecordRollup</code> transform
*
* @throws ComponentNotReadyException if an error occurred during the instantiation of the transform
*/
private RecordRollup createTransformFromClassName(String className) throws ComponentNotReadyException {
try {
return (RecordRollup) Class.forName(transformClassName).newInstance();
} catch (ClassNotFoundException exception) {
throw new ComponentNotReadyException("Cannot find the transformation class!", exception);
} catch (IllegalAccessException exception) {
throw new ComponentNotReadyException("Cannot access the transformation class!", exception);
} catch (InstantiationException exception) {
throw new ComponentNotReadyException("Cannot instantiate the transformation class!", exception);
} catch (ClassCastException exception) {
throw new ComponentNotReadyException(
"The transformation class does not implement the RecordRollup interface!", exception);
}
}
@Override
public Result execute() throws Exception {
if (!isInitialized()) {
throw new NotInitializedException(this);
}
if (inputSorted) {
executeInputSorted();
} else {
executeInputUnsorted();
}
broadcastEOF();
return (runIt ? Result.FINISHED_OK : Result.ABORTED);
}
/**
* Execution code specific for sorted input of data records.
*
* @throws IOException if an error occurred while reading or writing data records
* @throws InterruptedException if an error occurred while reading or writing data records
* @throws JetelException if input data records are not sorted or an error occurred during the transformation
*/
private void executeInputSorted() throws IOException, InterruptedException, JetelException {
InputPort inputPort = getInputPort(INPUT_PORT_NUMBER);
DoubleRecordBuffer inputRecords = new DoubleRecordBuffer(inputPort.getMetadata());
DataRecord groupAccumulator = null;
if (groupAccumulatorMetadataId != null) {
groupAccumulator = new DataRecord(getGraph().getDataRecordMetadata(groupAccumulatorMetadataId));
groupAccumulator.init();
groupAccumulator.reset();
}
if (inputPort.readRecord(inputRecords.getCurrent()) != null) {
recordRollup.initGroup(inputRecords.getCurrent(), groupAccumulator);
if (recordRollup.updateGroup(inputRecords.getCurrent(), groupAccumulator)) {
updateTransform(inputRecords.getCurrent(), groupAccumulator);
}
inputRecords.swap();
int sortDirection = 0;
while (runIt && inputPort.readRecord(inputRecords.getCurrent()) != null) {
int comparisonResult = groupKey.compare(inputRecords.getCurrent(), inputRecords.getPrevious());
if (comparisonResult != 0) {
if (sortDirection == 0) {
sortDirection = comparisonResult;
} else if (comparisonResult != sortDirection) {
throw new JetelException("Input data records not sorted!");
}
if (recordRollup.finishGroup(inputRecords.getPrevious(), groupAccumulator)) {
transform(inputRecords.getPrevious(), groupAccumulator);
}
if (groupAccumulator != null) {
groupAccumulator.reset();
}
recordRollup.initGroup(inputRecords.getCurrent(), groupAccumulator);
}
if (recordRollup.updateGroup(inputRecords.getCurrent(), groupAccumulator)) {
updateTransform(inputRecords.getCurrent(), groupAccumulator);
}
inputRecords.swap();
SynchronizeUtils.cloverYield();
}
if (recordRollup.finishGroup(inputRecords.getPrevious(), groupAccumulator)) {
transform(inputRecords.getPrevious(), groupAccumulator);
}
}
}
/**
* Execution code specific for unsorted input of data records.
*
* @throws TransformException if an error occurred during the transformation
* @throws IOException if an error occurred while reading or writing data records
* @throws InterruptedException if an error occurred while reading or writing data records
*/
private void executeInputUnsorted() throws TransformException, IOException, InterruptedException {
InputPort inputPort = getInputPort(INPUT_PORT_NUMBER);
DataRecord inputRecord = new DataRecord(inputPort.getMetadata());
inputRecord.init();
DataRecordMetadata groupAccumulatorMetadata = (groupAccumulatorMetadataId != null)
? getGraph().getDataRecordMetadata(groupAccumulatorMetadataId) : null;
Map<HashKey, DataRecord> groupAccumulators = new HashMap<HashKey, DataRecord>();
HashKey lookupKey = new HashKey(groupKey, inputRecord);
while (runIt && inputPort.readRecord(inputRecord) != null) {
DataRecord groupAccumulator = groupAccumulators.get(lookupKey);
if (groupAccumulator == null && !groupAccumulators.containsKey(lookupKey)) {
if (groupAccumulatorMetadata != null) {
groupAccumulator = new DataRecord(groupAccumulatorMetadata);
groupAccumulator.init();
groupAccumulator.reset();
}
groupAccumulators.put(new HashKey(groupKey, inputRecord.duplicate()), groupAccumulator);
recordRollup.initGroup(inputRecord, groupAccumulator);
}
if (recordRollup.updateGroup(inputRecord, groupAccumulator)) {
updateTransform(inputRecord, groupAccumulator);
}
SynchronizeUtils.cloverYield();
}
for (Map.Entry<HashKey, DataRecord> entry : groupAccumulators.entrySet()) {
if (recordRollup.finishGroup(entry.getKey().getDataRecord(), entry.getValue())) {
transform(entry.getKey().getDataRecord(), entry.getValue());
}
}
}
/**
* Calls the updateTransform() method on the rollup transform and performs further processing based on the result.
*
* @param inputRecord the current input data record
* @param groupAccumulator the group "accumulator" for the current group
*
* @throws TransformException if an error occurred during the transformation
* @throws IOException if an error occurred while writing a data record to an output port
* @throws InterruptedException if an error occurred while writing a data record to an output port
*/
private void updateTransform(DataRecord inputRecord, DataRecord groupAccumulator)
throws TransformException, IOException, InterruptedException {
int counter = 0;
while (true) {
for (DataRecord outputRecord : outputRecords) {
outputRecord.reset();
}
int transformResult = recordRollup.updateTransform(counter++, inputRecord, groupAccumulator, outputRecords);
if (transformResult == RecordRollup.SKIP) {
break;
}
if (transformResult == RecordRollup.ALL) {
for (int i = 0; i < outputRecords.length; i++) {
writeRecord(i, outputRecords[i]);
}
} else if (transformResult >= 0) {
writeRecord(transformResult, outputRecords[transformResult]);
} else {
throw new TransformException("Transform finished with error " + transformResult + "!");
}
}
}
/**
* Calls the transform() method on the rollup transform and performs further processing based on the result.
*
* @param inputRecord the current input data record
* @param groupAccumulator the group "accumulator" for the current group
*
* @throws TransformException if an error occurred during the transformation
* @throws IOException if an error occurred while writing a data record to an output port
* @throws InterruptedException if an error occurred while writing a data record to an output port
*/
private void transform(DataRecord inputRecord, DataRecord groupAccumulator)
throws TransformException, IOException, InterruptedException {
int counter = 0;
while (true) {
for (DataRecord outputRecord : outputRecords) {
outputRecord.reset();
}
int transformResult = recordRollup.transform(counter++, inputRecord, groupAccumulator, outputRecords);
if (transformResult == RecordRollup.SKIP) {
break;
}
if (transformResult == RecordRollup.ALL) {
for (int i = 0; i < outputRecords.length; i++) {
writeRecord(i, outputRecords[i]);
}
} else if (transformResult >= 0) {
writeRecord(transformResult, outputRecords[transformResult]);
} else {
throw new TransformException("Transform finished with error " + transformResult + "!");
}
}
}
@Override
public synchronized void reset() throws ComponentNotReadyException {
if (!isInitialized()) {
throw new NotInitializedException(this);
}
recordRollup.reset();
super.reset();
}
@Override
public synchronized void free() {
if (!isInitialized()) {
throw new NotInitializedException(this);
}
groupKey = null;
recordRollup.free();
recordRollup = null;
outputRecords = null;
super.free();
}
} |
package org.jetel.util.file;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.Proxy;
import java.net.SocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.URLStreamHandler;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.Adler32;
import java.util.zip.Checksum;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipInputStream;
import org.jetel.component.fileoperation.CloverURI;
import org.jetel.component.fileoperation.FileManager;
import org.jetel.component.fileoperation.Operation;
import org.jetel.component.fileoperation.SimpleParameters.CreateParameters;
import org.jetel.component.fileoperation.URIUtils;
import org.jetel.data.Defaults;
import org.jetel.enums.ArchiveType;
import org.jetel.exception.ComponentNotReadyException;
import org.jetel.exception.JetelRuntimeException;
import org.jetel.graph.ContextProvider;
import org.jetel.graph.TransformationGraph;
import org.jetel.logger.SafeLog;
import org.jetel.logger.SafeLogFactory;
import org.jetel.util.MultiOutFile;
import org.jetel.util.Pair;
import org.jetel.util.bytes.SystemOutByteChannel;
import org.jetel.util.exec.PlatformUtils;
import org.jetel.util.protocols.ProxyAuthenticable;
import org.jetel.util.protocols.UserInfo;
import org.jetel.util.protocols.amazon.S3InputStream;
import org.jetel.util.protocols.amazon.S3OutputStream;
import org.jetel.util.protocols.ftp.FTPStreamHandler;
import org.jetel.util.protocols.proxy.ProxyHandler;
import org.jetel.util.protocols.proxy.ProxyProtocolEnum;
import org.jetel.util.protocols.sandbox.SandboxStreamHandler;
import org.jetel.util.protocols.sftp.SFTPConnection;
import org.jetel.util.protocols.sftp.SFTPStreamHandler;
import org.jetel.util.protocols.webdav.WebdavOutputStream;
import org.jetel.util.stream.StreamUtils;
import org.jetel.util.string.StringUtils;
import com.ice.tar.TarEntry;
import com.ice.tar.TarInputStream;
import com.jcraft.jsch.ChannelSftp;
import edu.umd.cs.findbugs.annotations.SuppressWarnings;
/**
* Helper class with some useful methods regarding file manipulation
*
* @author dpavlis
* @since May 24, 2002
* @revision $Revision$
*/
public class FileUtils {
private final static String DEFAULT_ZIP_FILE = "default_output";
// for embedded source
// "something : ( something ) [#something]?
// ([^:]*) (:) (\\() (.*) (\\)) (((
private final static Pattern INNER_SOURCE = Pattern.compile("(([^:]*)([:])([\\(]))(.*)(\\))(((
// standard input/output source
public final static String STD_CONSOLE = "-";
// sftp protocol handler
public static final SFTPStreamHandler sFtpStreamHandler = new SFTPStreamHandler();
// ftp protocol handler
public static final FTPStreamHandler ftpStreamHandler = new FTPStreamHandler();
// proxy protocol handler
public static final ProxyHandler proxyHandler = new ProxyHandler();
// file protocol name
private static final String FILE_PROTOCOL = "file";
private static final String FILE_PROTOCOL_ABSOLUTE_MARK = "file:./";
// archive protocol names
private static final String TAR_PROTOCOL = "tar";
private static final String GZIP_PROTOCOL = "gzip";
private static final String ZIP_PROTOCOL = "zip";
private static final ArchiveURLStreamHandler ARCHIVE_URL_STREAM_HANDLER = new ArchiveURLStreamHandler();
private static final URLStreamHandler HTTP_HANDLER = new CredentialsSerializingHandler() {
@Override
protected int getDefaultPort() {
return 80;
}
};
private static final URLStreamHandler HTTPS_HANDLER = new CredentialsSerializingHandler() {
@Override
protected int getDefaultPort() {
return 443;
}
};
private static final SafeLog log = SafeLogFactory.getSafeLog(FileUtils.class);
public static final Map<String, URLStreamHandler> handlers;
private static final String FTP_PROTOCOL = "ftp";
private static final String SFTP_PROTOCOL = "sftp";
private static final String SCP_PROTOCOL = "scp";
private static final String HTTP_PROTOCOL = "http";
private static final String HTTPS_PROTOCOL = "https";
private static final String UTF8 = "UTF-8";
static {
Map<String, URLStreamHandler> h = new HashMap<String, URLStreamHandler>();
h.put(GZIP_PROTOCOL, ARCHIVE_URL_STREAM_HANDLER);
h.put(ZIP_PROTOCOL, ARCHIVE_URL_STREAM_HANDLER);
h.put(TAR_PROTOCOL, ARCHIVE_URL_STREAM_HANDLER);
h.put(FTP_PROTOCOL, ftpStreamHandler);
h.put(SFTP_PROTOCOL, sFtpStreamHandler);
h.put(SCP_PROTOCOL, sFtpStreamHandler);
h.put(HTTP_PROTOCOL, HTTP_HANDLER);
h.put(HTTPS_PROTOCOL, HTTPS_HANDLER);
for (ProxyProtocolEnum p: ProxyProtocolEnum.values()) {
h.put(p.toString(), proxyHandler);
}
h.put(SandboxUrlUtils.SANDBOX_PROTOCOL, new SandboxStreamHandler());
handlers = Collections.unmodifiableMap(h);
}
/**
* Third-party implementation of path resolving - useful to make possible to run the graph inside of war file.
*/
private static final List<CustomPathResolver> customPathResolvers = new ArrayList<CustomPathResolver>();
private static final String PLUS_CHAR_ENCODED = URLEncoder.encode("+");
/**
* Used only to extract the protocol name in a generic manner
*/
private static final URLStreamHandler GENERIC_HANDLER = new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL u) throws IOException {
return null;
}
};
/**
* If the given string is an valid absolute URL
* with a known protocol, returns the URL.
*
* Throws MalformedURLException otherwise.
*
* @param url
* @return URL constructed from <code>url</code>
* @throws MalformedURLException
*/
public static final URL getUrl(String url) throws MalformedURLException {
try {
return new URL(url);
} catch (MalformedURLException e) {
String protocol = new URL(null, url, GENERIC_HANDLER).getProtocol();
URLStreamHandler handler = FileUtils.handlers.get(protocol.toLowerCase());
if (handler != null) {
return new URL(null, url, handler);
} else {
throw e;
}
}
}
public static URL getFileURL(String fileURL) throws MalformedURLException {
return getFileURL((URL) null, fileURL);
}
public static URL getFileURL(String contextURL, String fileURL) throws MalformedURLException {
return getFileURL(getFileURL((URL) null, contextURL), fileURL);
}
/**
* Creates URL object based on specified fileURL string. Handles
* situations when <code>fileURL</code> contains only path to file
* <i>(without "file:" string)</i>.
*
* @param contextURL context URL for converting relative to absolute path (see TransformationGraph.getProjectURL())
* @param fileURL string containing file URL
* @return URL object or NULL if object can't be created (due to Malformed URL)
* @throws MalformedURLException
*/
public static URL getFileURL(URL contextURL, String fileURL) throws MalformedURLException {
//FIX CLD-2895
//default value for addStrokePrefix was changed to true
//right now I am not sure if this change can have an impact to other part of project,
//but it seems this changed fix relatively important issue:
//contextURL "file:/c:/project/"
//fileURL "c:/otherProject/data.txt"
//leads to --> "file:/c:/project/c:/otherProject/data.txt"
return getFileURL(contextURL, fileURL, true);
}
private static Pattern DRIVE_LETTER_PATTERN = Pattern.compile("\\A\\p{Alpha}:[/\\\\]");
private static final String PORT_PROTOCOL = "port";
/**
* Returns <code>true</code> if <code>fileURL</code> specifies a protocol.
* On Windows, single letters are not considered protocol names.
*
* @param contextURL
* @param fileURL
* @return
*/
private static boolean isUnknownProtocol(URL contextURL, String fileURL) {
if (fileURL != null) {
try {
URL url = new URL(contextURL, fileURL, GENERIC_HANDLER);
String protocol = url.getProtocol();
if (!protocol.isEmpty() && !protocol.equals(PORT_PROTOCOL)) {
if (protocol.length() == 1 && PlatformUtils.isWindowsPlatform()) {
return !DRIVE_LETTER_PATTERN.matcher(fileURL).find();
}
return true;
}
} catch (MalformedURLException ex) {
}
}
return false;
}
/**
* Creates URL object based on specified fileURL string. Handles
* situations when <code>fileURL</code> contains only path to file
* <i>(without "file:" string)</i>.
*
* @param contextURL context URL for converting relative to absolute path (see TransformationGraph.getProjectURL())
* @param fileURL string containing file URL
* @return URL object or NULL if object can't be created (due to Malformed URL)
* @throws MalformedURLException
*/
public static URL getFileURL(URL contextURL, String fileURL, boolean addStrokePrefix) throws MalformedURLException {
// remove mark for absolute path
if (contextURL != null && fileURL.startsWith(FILE_PROTOCOL_ABSOLUTE_MARK)) {
fileURL = fileURL.substring((FILE_PROTOCOL+":").length());
}
// standard url
try {
if( fileURL.startsWith("/") ){
return new URL(fileURL);
} else {
return getStandardUrlWeblogicHack(contextURL, fileURL);
}
} catch(MalformedURLException ex) {}
// sftp url
try {
// ftp connection is connected via sftp handler, 22 port is ok but 21 is somehow blocked for the same connection
return new URL(contextURL, fileURL, sFtpStreamHandler);
} catch(MalformedURLException e) {}
// proxy url
try {
return new URL(contextURL, fileURL, proxyHandler);
} catch(MalformedURLException e) {}
// sandbox url
if (SandboxUrlUtils.isSandboxUrl(fileURL)){
try {
return new URL(contextURL, fileURL, new SandboxStreamHandler());
} catch(MalformedURLException e) {}
}
// archive url
if (isArchive(fileURL)) {
StringBuilder innerInput = new StringBuilder();
StringBuilder anchor = new StringBuilder();
ArchiveType type = getArchiveType(fileURL, innerInput, anchor);
URL archiveFileUrl = getFileURL(contextURL, innerInput.toString());
return new URL(null, type.getId() + ":(" + archiveFileUrl.toString() + ")#" + anchor, new ArchiveURLStreamHandler(contextURL));
}
// throw and exception if fileURL specifies a protocol (drive letters are ignored)
if (isUnknownProtocol(contextURL, fileURL)) {
return new URL(contextURL, fileURL);
}
// file url
String prefix = FILE_PROTOCOL + ":";
if (addStrokePrefix && new File(fileURL).isAbsolute() && !fileURL.startsWith("/")) {
prefix += "/";
}
return new URL(contextURL, prefix + fileURL);
}
private static URL getStandardUrlWeblogicHack(URL contextUrl, String fileUrl) throws MalformedURLException {
if (contextUrl != null || fileUrl != null) {
final URL resolvedInContextUrl = new URL(contextUrl, fileUrl);
String protocol = resolvedInContextUrl.getProtocol();
if (protocol != null) {
protocol = protocol.toLowerCase();
if (protocol.equals(HTTP_PROTOCOL)) {
return new URL(contextUrl, fileUrl, FileUtils.HTTP_HANDLER);
} else if (protocol.equals(HTTPS_PROTOCOL)) {
return new URL(contextUrl, fileUrl, FileUtils.HTTPS_HANDLER);
}
}
}
return new URL(contextUrl, fileUrl);
}
/**
* Converts a list of file URLs to URL objects by calling {@link #getFileURL(URL, String)}.
*
* @param contextUrl URL context for converting relative paths to absolute ones
* @param fileUrls array of string file URLs
*
* @return an array of file URL objects
*
* @throws MalformedURLException if any of the given file URLs is malformed
*/
public static URL[] getFileUrls(URL contextUrl, String[] fileUrls) throws MalformedURLException {
if (fileUrls == null) {
return null;
}
URL[] resultFileUrls = new URL[fileUrls.length];
for (int i = 0; i < fileUrls.length; i++) {
resultFileUrls[i] = getFileURL(contextUrl, fileUrls[i]);
}
return resultFileUrls;
}
/**
* Calculates checksum of specified file.<br>Is suitable for short files (not very much buffered).
*
* @param filename Filename (full path) of file to calculate checksum for
* @return Calculated checksum or -1 if some error (IO) occured
*/
public static long calculateFileCheckSum(String filename) {
byte[] buffer = new byte[1024];
Checksum checksum = new Adler32(); // we use Adler - should be faster
int length = 0;
try {
FileInputStream dataFile = new FileInputStream(filename);
try {
while (length != -1) {
length = dataFile.read(buffer);
if (length > 0) {
checksum.update(buffer, 0, length);
}
}
} finally {
dataFile.close();
}
} catch (IOException ex) {
return -1;
}
return checksum.getValue();
}
/**
* Reads file specified by URL. The content is returned as String
* @param contextURL context URL for converting relative to absolute path (see TransformationGraph.getProjectURL())
* @param fileURL URL specifying the location of file from which to read
* @return
*/
public static String getStringFromURL(URL contextURL, String fileURL, String charset){
InputStream source;
String chSet = charset != null ? charset : Defaults.DataParser.DEFAULT_CHARSET_DECODER;
StringBuffer sb = new StringBuffer(2048);
char[] charBuf=new char[256];
try {
source = FileUtils.getInputStream(contextURL, fileURL);
BufferedReader in = new BufferedReader(new InputStreamReader(source, chSet));
try {
int readNum;
while ((readNum = in.read(charBuf, 0, charBuf.length)) != -1) {
sb.append(charBuf, 0, readNum);
}
} finally {
in.close();
}
} catch (IOException ex) {
throw new RuntimeException("Can't get string from file " + fileURL + " : " + ex.getMessage());
}
return sb.toString();
}
/**
* Creates ReadableByteChannel from the url definition.
* <p>
* All standard url format are acceptable plus extended form of url by zip & gzip construction:
* </p>
* Examples:
* <dl>
* <dd>zip:<url_to_zip_file>#<inzip_path_to_file></dd>
* <dd>gzip:<url_to_gzip_file></dd>
* </dl>
*
* @param contextURL
* context URL for converting relative to absolute path (see TransformationGraph.getProjectURL())
* @param input
* URL of file to read
* @return
* @throws IOException
*/
public static ReadableByteChannel getReadableChannel(URL contextURL, String input) throws IOException {
InputStream in = getInputStream(contextURL, input);
//incremental reader needs FileChannel:
return in instanceof FileInputStream ? ((FileInputStream)in).getChannel() : Channels.newChannel(in);
}
/**
* Creates InputStream from the url definition.
* <p>
* All standard url format are acceptable plus extended form of url by zip & gzip construction:
* </p>
* Examples:
* <dl>
* <dd>zip:<url_to_zip_file>#<inzip_path_to_file></dd>
* <dd>gzip:<url_to_gzip_file></dd>
* </dl>
* For zip file, if anchor is not set there is return first zip entry.
*
* @param contextURL
* context URL for converting relative to absolute path (see TransformationGraph.getProjectURL())
* @param input
* URL of file to read
* @return
* @throws IOException
* @throws IOException
*/
public static InputStream getInputStream(URL contextURL, String input) throws IOException {
InputStream innerStream = null;
// It is important to use the same mechanism (TrueZip) for both reading and writing
// of the local archives!
// The TrueZip library has it's own virtual file system. Even after a stream from TrueZip
// gets closed, the contents are not immediately written to the disc.
// Therefore reading local archive with different library (e.g. java.util.zip) might lead to
// inconsistency if the archive has not been flushed by TrueZip yet.
StringBuilder localArchivePath = new StringBuilder();
if (getLocalArchiveInputPath(contextURL, input, localArchivePath)) {
// apply the contextURL
URL url = FileUtils.getFileURL(contextURL, localArchivePath.toString());
String absolutePath = getUrlFile(url);
registerTrueZipVSFEntry(new de.schlichtherle.io.File(localArchivePath.toString()));
return new de.schlichtherle.io.FileInputStream(absolutePath);
}
//first we try the custom path resolvers
for (CustomPathResolver customPathResolver : customPathResolvers) {
innerStream = customPathResolver.getInputStream(contextURL, input);
if (innerStream != null) {
log.debug("Input stream '" + input + "[" + contextURL + "] was opened by custom path resolver.");
return innerStream; //we found the desired input stream using external resolver method
}
}
// std input (console)
if (input.equals(STD_CONSOLE)) {
return System.in;
}
// get inner source
Matcher matcher = FileURLParser.getURLMatcher(input);
String innerSource;
if (matcher != null && (innerSource = matcher.group(5)) != null) {
// get and set proxy and go to inner source
Proxy proxy = getProxy(innerSource);
String proxyUserInfo = null;
if (proxy != null) {
try {
proxyUserInfo = new URI(innerSource).getUserInfo();
} catch (URISyntaxException ex) {
}
}
input = matcher.group(2) + matcher.group(3) + matcher.group(7);
innerStream = proxy == null ? getInputStream(contextURL, innerSource)
: getAuthorizedConnection(getFileURL(contextURL, input), proxy, proxyUserInfo).getInputStream();
}
// get archive type
StringBuilder sbAnchor = new StringBuilder();
StringBuilder sbInnerInput = new StringBuilder();
ArchiveType archiveType = getArchiveType(input, sbInnerInput, sbAnchor);
input = sbInnerInput.toString();
//open channel
URL url = null;
if (innerStream == null) {
url = FileUtils.getFileURL(contextURL, input);
// creates file input stream for incremental reading (random access file)
if (archiveType == null && url.getProtocol().equals(FILE_PROTOCOL)) {
return new FileInputStream(url.getRef() != null ? getUrlFile(url) + "#" + url.getRef() : getUrlFile(url));
} else if (archiveType == null && SandboxUrlUtils.isSandboxUrl(url)) {
TransformationGraph graph = ContextProvider.getGraph();
if (graph == null) {
throw new NullPointerException("Graph reference cannot be null when \"" + SandboxUrlUtils.SANDBOX_PROTOCOL + "\" protocol is used.");
}
return graph.getAuthorityProxy().getSandboxResourceInput(url.getHost(), getUrlFile(url));
}
try {
if (S3InputStream.isS3File(url)) {
return new S3InputStream(url);
}
try {
innerStream = getAuthorizedConnection(url).getInputStream();
}
catch (Exception e) {
throw new IOException("Cannot obtain connection input stream for URL '" + url + "'. Make sure the URL is valid.", e);
}
} catch (IOException e) {
log.debug("IOException occured for URL - host: '" + url.getHost() + "', path: '" + url.getPath() + "' (user info not shown)",
"IOException occured for URL - host: '" + url.getHost() + "', userinfo: '" + url.getUserInfo() + "', path: '" + url.getPath() + "'");
throw e;
}
}
// create archive streams
String anchor = URLDecoder.decode(sbAnchor.toString(), UTF8);
if (archiveType == ArchiveType.ZIP) {
return getZipInputStream(innerStream, anchor); // CL-2579
} else if (archiveType == ArchiveType.GZIP) {
return new GZIPInputStream(innerStream, Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE);
} else if (archiveType == ArchiveType.TAR) {
return getTarInputStream(innerStream, anchor);
}
return innerStream;
}
/**
* Gets archive type.
* @param input - input file
* @param innerInput - output parameter
* @param anchor - output parameter
* @return
*/
public static ArchiveType getArchiveType(String input, StringBuilder innerInput, StringBuilder anchor) {
// result value
ArchiveType archiveType = null;
//resolve url format for zip files
if (input.startsWith("zip:")) archiveType = ArchiveType.ZIP;
else if (input.startsWith("tar:")) archiveType = ArchiveType.TAR;
else if (input.startsWith("gzip:")) archiveType = ArchiveType.GZIP;
// parse the archive
if((archiveType == ArchiveType.ZIP) || (archiveType == ArchiveType.TAR)) {
if (input.contains(")
anchor.append(input.substring(input.lastIndexOf(")
innerInput.append(input.substring(input.indexOf(":(") + 2, input.lastIndexOf(")
}
else if (input.contains("
anchor.append(input.substring(input.lastIndexOf('
innerInput.append(input.substring(input.indexOf(':') + 1, input.lastIndexOf('
}
else {
anchor = null;
innerInput.append(input.substring(input.indexOf(':') + 1));
}
}
else if (archiveType == ArchiveType.GZIP) {
innerInput.append(input.substring(input.indexOf(':') + 1));
}
// if doesn't exist inner input, inner input is input
if (innerInput.length() == 0) innerInput.append(input);
// remove parentheses - fixes incorrect URL resolution
if (innerInput.length() >= 2 && innerInput.charAt(0) == '(' && innerInput.charAt(innerInput.length()-1) == ')') {
innerInput.deleteCharAt(innerInput.length()-1);
innerInput.deleteCharAt(0);
}
return archiveType;
}
/**
* Creates a zip input stream.
* @param innerStream
* @param anchor
* @param resolvedAnchors - output parameter
* @return
* @throws IOException
*
* @deprecated
* This method does not really work,
* it is not possible to open multiple ZipInputStreams
* from one parent input stream without extensive buffering.
*
* Use {@link #getMatchingZipEntries(InputStream, String)} to resolve wildcards
* or {@link #getZipInputStream(InputStream, String)} to open a TarInputStream.
*/
@Deprecated
public static List<InputStream> getZipInputStreams(InputStream innerStream, String anchor, List<String> resolvedAnchors) throws IOException {
anchor = URLDecoder.decode(anchor, UTF8); // CL-2579
return getZipInputStreamsInner(innerStream, anchor, 0, resolvedAnchors, true);
}
/**
* Creates a list of names of matching entries.
* @param parentStream
* @param pattern
*
* @return resolved anchors
* @throws IOException
*/
public static List<String> getMatchingZipEntries(InputStream parentStream, String pattern) throws IOException {
if (pattern == null) {
pattern = "";
}
pattern = URLDecoder.decode(pattern, UTF8); // CL-2579
List<String> resolvedAnchors = new ArrayList<String>();
Matcher matcher;
Pattern WILDCARD_PATTERN = null;
boolean containsWildcard = pattern.contains("?") || pattern.contains("*");
if (containsWildcard) {
WILDCARD_PATTERN = Pattern.compile(pattern.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\.", "\\\\.").replaceAll("\\?", "\\.").replaceAll("\\*", ".*"));
}
//resolve url format for zip files
ZipInputStream zis = new ZipInputStream(parentStream) ;
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) {
continue; // CLS-537: skip directories, we want to read the first file
}
// wild cards
if (containsWildcard) {
matcher = WILDCARD_PATTERN.matcher(entry.getName());
if (matcher.matches()) {
resolvedAnchors.add(entry.getName());
}
// without wild cards
} else if (pattern.isEmpty() || entry.getName().equals(pattern)) { //url is given without anchor; first entry in zip file is used
resolvedAnchors.add(pattern);
}
}
// if no wild carded entry found, it is ok
if (!pattern.isEmpty() && !containsWildcard && resolvedAnchors.isEmpty()) {
throw new IOException("Wrong anchor (" + pattern + ") to zip file.");
}
return resolvedAnchors;
}
/**
* Creates a list of names of matching entries.
* @param parentStream
* @param pattern
*
* @return resolved anchors
* @throws IOException
*/
public static List<String> getMatchingTarEntries(InputStream parentStream, String pattern) throws IOException {
if (pattern == null) {
pattern = "";
}
pattern = URLDecoder.decode(pattern, UTF8); // CL-2579
List<String> resolvedAnchors = new ArrayList<String>();
Matcher matcher;
Pattern WILDCARD_PATTERN = null;
boolean containsWildcard = pattern.contains("?") || pattern.contains("*");
if (containsWildcard) {
WILDCARD_PATTERN = Pattern.compile(pattern.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\.", "\\\\.").replaceAll("\\?", "\\.").replaceAll("\\*", ".*"));
}
//resolve url format for zip files
TarInputStream tis = new TarInputStream(parentStream) ;
TarEntry entry;
while ((entry = tis.getNextEntry()) != null) {
if (entry.isDirectory()) {
continue; // CLS-537: skip directories, we want to read the first file
}
// wild cards
if (containsWildcard) {
matcher = WILDCARD_PATTERN.matcher(entry.getName());
if (matcher.matches()) {
resolvedAnchors.add(entry.getName());
}
// without wild cards
} else if (pattern.isEmpty() || entry.getName().equals(pattern)) { //url is given without anchor; first entry in zip file is used
resolvedAnchors.add(pattern);
}
}
// if no wild carded entry found, it is ok
if (!pattern.isEmpty() && !containsWildcard && resolvedAnchors.isEmpty()) {
throw new IOException("Wrong anchor (" + pattern + ") to zip file.");
}
return resolvedAnchors;
}
/**
* Wraps the parent stream into ZipInputStream
* and positions it to read the given entry (no wildcards are applicable).
*
* If no entry is given, the stream is positioned to read the first file entry.
*
* @param parentStream
* @param entryName
* @return
* @throws IOException
*/
public static ZipInputStream getZipInputStream(InputStream parentStream, String entryName) throws IOException {
ZipInputStream zis = new ZipInputStream(parentStream) ;
ZipEntry entry;
// find a matching entry
while ((entry = zis.getNextEntry()) != null) {
if (entry.isDirectory()) {
continue; // CLS-537: skip directories, we want to read the first file
}
// when url is given without anchor; first entry in zip file is used
if (StringUtils.isEmpty(entryName) || entry.getName().equals(entryName)) {
return zis;
}
}
//no entry found report
throw new IOException("Wrong anchor (" + entryName + ") to zip file.");
}
/**
* Wraps the parent stream into TarInputStream
* and positions it to read the given entry (no wildcards are applicable).
*
* If no entry is given, the stream is positioned to read the first file entry.
*
* @param parentStream
* @param entryName
* @return
* @throws IOException
*/
public static TarInputStream getTarInputStream(InputStream parentStream, String entryName) throws IOException {
TarInputStream tis = new TarInputStream(parentStream) ;
TarEntry entry;
// find a matching entry
while ((entry = tis.getNextEntry()) != null) {
if (entry.isDirectory()) {
continue; // CLS-537: skip directories, we want to read the first file
}
// when url is given without anchor; first entry in tar file is used
if (StringUtils.isEmpty(entryName) || entry.getName().equals(entryName)) {
return tis;
}
}
//no entry found report
throw new IOException("Wrong anchor (" + entryName + ") to tar file.");
}
/**
* Creates list of zip input streams (only if <code>needInputStream</code> is true).
* Also stores their names in <code>resolvedAnchors</code>.
*
* @param innerStream
* @param anchor
* @param matchFilesFrom
* @param resolvedAnchors
* @param needInputStream if <code>true</code>, input streams for individual entries will be created (costly operation)
*
* @return
* @throws IOException
*/
private static List<InputStream> getZipInputStreamsInner(InputStream innerStream, String anchor,
int matchFilesFrom, List<String> resolvedAnchors, boolean needInputStream) throws IOException {
// result list of input streams
List<InputStream> streams = new ArrayList<InputStream>();
// check and prepare support for wild card matching
Matcher matcher;
Pattern WILDCARD_PATTERS = null;
boolean bWildcardedAnchor = anchor.contains("?") || anchor.contains("*");
if (bWildcardedAnchor)
WILDCARD_PATTERS = Pattern.compile(anchor.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\.", "\\\\.").replaceAll("\\?", "\\.").replaceAll("\\*", ".*"));
// the input stream must support a buffer for wild cards.
if (bWildcardedAnchor && needInputStream) {
if (!innerStream.markSupported()) {
innerStream = new BufferedInputStream(innerStream);
}
innerStream.mark(Integer.MAX_VALUE);
}
//resolve url format for zip files
ZipInputStream zin = new ZipInputStream(innerStream) ;
ZipEntry entry;
// find entries
int iMatched = 0;
while((entry = zin.getNextEntry()) != null) { // zin is changing -> recursion !!!
// wild cards
if (bWildcardedAnchor) {
matcher = WILDCARD_PATTERS.matcher(entry.getName());
if (matcher.find()) { // TODO replace find() with matches()
if (needInputStream && iMatched++ == matchFilesFrom) { // CL-2576 - only create streams when necessary, not when just resolving wildcards
streams.add(zin);
if (resolvedAnchors != null) resolvedAnchors.add(entry.getName());
innerStream.reset();
streams.addAll(getZipInputStreamsInner(innerStream, anchor, ++matchFilesFrom, resolvedAnchors, needInputStream));
innerStream.reset();
return streams;
} else { // if we don't need input streams for individual entries, there is no need for recursion
if (resolvedAnchors != null) resolvedAnchors.add(entry.getName());
}
}
// without wild cards
} else if(anchor == null || anchor.equals("") || entry.getName().equals(anchor)) { //url is given without anchor; first entry in zip file is used
streams.add(zin);
if (resolvedAnchors != null) resolvedAnchors.add(anchor);
return streams;
}
//finish up with entry
zin.closeEntry();
}
if (matchFilesFrom > 0 || streams.size() > 0) {
return streams;
}
// if no wild carded entry found, it is ok, return null
if (bWildcardedAnchor || !needInputStream) {
return null;
}
//close the archive
zin.close();
//no channel found report
throw new IOException("Wrong anchor (" + anchor + ") to zip file.");
}
/**
* Creates a tar input stream.
* @param innerStream
* @param anchor
* @param resolvedAnchors - output parameter
* @return
* @throws IOException
*
* @deprecated
* This method does not really work,
* it is not possible to open multiple TarInputStreams
* from one parent input stream without extensive buffering.
*
* Use {@link #getMatchingTarEntries(InputStream, String)} to resolve wildcards
* or {@link #getTarInputStream(InputStream, String)} to open a TarInputStream.
*/
@Deprecated
public static List<InputStream> getTarInputStreams(InputStream innerStream, String anchor, List<String> resolvedAnchors) throws IOException {
return getTarInputStreamsInner(innerStream, anchor, 0, resolvedAnchors);
}
/**
* Creates list of tar input streams.
* @param innerStream
* @param anchor
* @param matchFilesFrom
* @param resolvedAnchors
* @return
* @throws IOException
*/
private static List<InputStream> getTarInputStreamsInner(InputStream innerStream, String anchor,
int matchFilesFrom, List<String> resolvedAnchors) throws IOException {
// result list of input streams
List<InputStream> streams = new ArrayList<InputStream>();
// check and prepare support for wild card matching
Matcher matcher;
Pattern WILDCARD_PATTERS = null;
boolean bWildsCardedAnchor = anchor.contains("?") || anchor.contains("*");
if (bWildsCardedAnchor)
WILDCARD_PATTERS = Pattern.compile(anchor.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\.", "\\\\.").replaceAll("\\?", "\\.").replaceAll("\\*", ".*"));
// the input stream must support a buffer for wild cards.
if (bWildsCardedAnchor) {
if (!innerStream.markSupported()) {
innerStream = new BufferedInputStream(innerStream);
}
innerStream.mark(Integer.MAX_VALUE);
}
//resolve url format for zip files
TarInputStream tin = new TarInputStream(innerStream);
TarEntry entry;
// find entries
int iMatched = 0;
while((entry = tin.getNextEntry()) != null) { // tin is changing -> recursion !!!
// wild cards
if (bWildsCardedAnchor) {
matcher = WILDCARD_PATTERS.matcher(entry.getName());
if (matcher.find() && iMatched++ == matchFilesFrom) {
streams.add(tin);
if (resolvedAnchors != null) resolvedAnchors.add(entry.getName());
innerStream.reset();
streams.addAll(getTarInputStreamsInner(innerStream, anchor, ++matchFilesFrom, resolvedAnchors));
innerStream.reset();
return streams;
}
// without wild cards
} else if(anchor == null || anchor.equals("") || entry.getName().equals(anchor)) { //url is given without anchor; first entry in zip file is used
streams.add(tin);
if (resolvedAnchors != null) resolvedAnchors.add(anchor);
return streams;
}
}
if (matchFilesFrom > 0 || streams.size() > 0) return streams;
// if no wild carded entry found, it is ok, return null
if (bWildsCardedAnchor) return null;
//close the archive
tin.close();
//no channel found report
if(anchor == null) {
throw new IOException("Tar file is empty.");
} else {
throw new IOException("Wrong anchor (" + anchor + ") to tar file.");
}
}
/**
* Creates authorized url connection.
* @param url
* @return
* @throws IOException
*/
public static URLConnection getAuthorizedConnection(URL url) throws IOException {
return URLConnectionRequest.getAuthorizedConnection(
url.openConnection(),
url.getUserInfo(),
URLConnectionRequest.URL_CONNECTION_AUTHORIZATION);
}
/**
* Creates an authorized stream.
* @param url
* @param proxy
* @param proxyUserInfo username and password to access the proxy
*
* @return
* @throws IOException
*/
public static URLConnection getAuthorizedConnection(URL url, Proxy proxy, String proxyUserInfo) throws IOException {
URLConnection connection = url.openConnection(proxy);
if (connection instanceof ProxyAuthenticable) {
((ProxyAuthenticable) connection).setProxyCredentials(new UserInfo(proxyUserInfo));
}
connection = URLConnectionRequest.getAuthorizedConnection( // set authentication
connection,
url.getUserInfo(),
URLConnectionRequest.URL_CONNECTION_AUTHORIZATION);
connection = URLConnectionRequest.getAuthorizedConnection( // set proxy authentication
connection,
proxyUserInfo,
URLConnectionRequest.URL_CONNECTION_PROXY_AUTHORIZATION);
return connection;
}
/**
* Creates an authorized stream.
* @param url
* @return
* @throws IOException
*
* @deprecated Use {@link #getAuthorizedConnection(URL, Proxy, String)} instead
*/
@Deprecated
public static URLConnection getAuthorizedConnection(URL url, Proxy proxy) throws IOException {
// user info is obtained from the URL, most likely different from proxy user info
return getAuthorizedConnection(url, proxy, url.getUserInfo());
}
/**
* Returns a pair whose first element is the original URL
* with the proxy specification removed
* and whose second element is the proxy specification string (or <code>null</code>).
*
* @param url with an optional proxy specification
* @return [url, proxyString]
*/
public static Pair<String, String> extractProxyString(String url) {
String proxyString = null;
Matcher matcher = FileURLParser.getURLMatcher(url);
if (matcher != null && (proxyString = matcher.group(5)) != null) {
url = matcher.group(2) + matcher.group(3) + matcher.group(7);
}
return new Pair<String, String>(url, proxyString);
}
/**
* Creates an proxy from the file url string.
* @param fileURL
* @return
*/
public static Proxy getProxy(String fileURL) {
// create an url
URL url;
try {
url = getFileURL(fileURL);
} catch (MalformedURLException e) {
return null;
}
// get proxy type
ProxyProtocolEnum proxyProtocolEnum;
if ((proxyProtocolEnum = ProxyProtocolEnum.fromString(url.getProtocol())) == null) {
return null;
}
// no proxy
if (proxyProtocolEnum == ProxyProtocolEnum.NO_PROXY) {
return Proxy.NO_PROXY;
}
// create a proxy
SocketAddress addr = new InetSocketAddress(url.getHost(), url.getPort() < 0 ? 8080 : url.getPort());
Proxy proxy = new Proxy(Proxy.Type.valueOf(proxyProtocolEnum.getProxyString()), addr);
return proxy;
}
public static WritableByteChannel getWritableChannel(URL contextURL, String input, boolean appendData, int compressLevel) throws IOException {
return Channels.newChannel(getOutputStream(contextURL, input, appendData, compressLevel));
}
public static WritableByteChannel getWritableChannel(URL contextURL, String input, boolean appendData) throws IOException {
return getWritableChannel(contextURL, input, appendData, -1);
}
public static boolean isArchive(String input) {
return input.startsWith("zip:") || input.startsWith("tar:") || input.startsWith("gzip:");
}
private static boolean isZipArchive(String input) {
return input.startsWith("zip:");
}
public static boolean isRemoteFile(String input) {
return input.startsWith("http:")
|| input.startsWith("https:")
|| input.startsWith("ftp:") || input.startsWith("sftp:") || input.startsWith("scp:");
}
private static boolean isConsole(String input) {
return input.equals(STD_CONSOLE);
}
private static boolean isSandbox(String input) {
return SandboxUrlUtils.isSandboxUrl(input);
}
public static boolean isLocalFile(URL contextUrl, String input) {
if (input.startsWith("file:")) {
return true;
} else if (isRemoteFile(input) || isConsole(input) || isSandbox(input) || isArchive(input)) {
return false;
} else {
try {
URL url = getFileURL(contextUrl, input);
return !isSandbox(url.toString());
} catch (MalformedURLException e) {}
}
return false;
}
private static boolean isHttp(String input) {
return input.startsWith("http:") || input.startsWith("https:");
}
private static boolean hasCustomPathOutputResolver(URL contextURL, String input, boolean appendData,
int compressLevel)
throws IOException {
OutputStream os;
for (CustomPathResolver customPathResolver : customPathResolvers) {
os = customPathResolver.getOutputStream(contextURL, input, appendData, compressLevel);
if (os != null) {
os.close();
return true;
}
}
return false;
}
private static boolean hasCustomPathInputResolver(URL contextURL, String input) throws IOException {
InputStream innerStream;
for (CustomPathResolver customPathResolver : customPathResolvers) {
innerStream = customPathResolver.getInputStream(contextURL, input);
if (innerStream != null) {
innerStream.close();
return true;
}
}
return false;
}
@java.lang.SuppressWarnings("unchecked")
private static String getFirstFileInZipArchive(URL context, String filePath) throws NullPointerException, FileNotFoundException, ZipException, IOException {
File file;
if (context != null) {
file = new File(context.getPath(), filePath);
}
else {
file = new File(filePath);
}
de.schlichtherle.util.zip.ZipFile zipFile = new de.schlichtherle.util.zip.ZipFile(file);
Enumeration<de.schlichtherle.util.zip.ZipEntry> zipEnmr;
de.schlichtherle.util.zip.ZipEntry entry;
for (zipEnmr = zipFile.entries(); zipEnmr.hasMoreElements() ;) {
entry = zipEnmr.nextElement();
if (!entry.isDirectory()) {
return entry.getName();
}
}
return null;
}
/**
* Descends through the URL to figure out whether this is a local archive.
*
* If the whole URL represents a local archive, standard FS path (archive.zip/dir1/another_archive.zip/dir2/file)
* will be returned inside of the path string builder, and true will be returned.
*
* @param input URL to inspect
* @param path output buffer for full file-system path
* @return true if the URL represents a file inside a local archive
* @throws IOException
*/
private static boolean getLocalArchivePath(URL contextURL, String input, boolean appendData, int compressLevel,
StringBuilder path, int nestLevel, boolean output) throws IOException {
if (output) {
if (hasCustomPathOutputResolver(contextURL, input, appendData, compressLevel)) {
return false;
}
}
else {
if (hasCustomPathInputResolver(contextURL, input)) {
return false;
}
}
if (isZipArchive(input)) {
Matcher matcher = getInnerInput(input);
// URL-centered convention, zip:(inner.zip)/outer.txt
// this might be misleading, as what you will see on the filesystem first is inner.zip
// and inside of that there will be a file named outer.txt
String innerSource; // inner part of the URL (outer file on the FS)
String outer; // outer part of the URL (inner file file on the FS)
boolean ret;
if (matcher != null && (innerSource = matcher.group(5)) != null) {
outer = matcher.group(10);
}
else {
return false;
}
ret = getLocalArchivePath(contextURL, innerSource, appendData, compressLevel, path, nestLevel + 1, output);
if (ret) {
if (outer == null && isZipArchive(input)) {
outer = output ? DEFAULT_ZIP_FILE : getFirstFileInZipArchive(contextURL, path.toString());
if (outer == null) {
throw new IOException("The archive does not contain any files");
}
}
if (path.length() != 0) {
path.append(File.separator);
}
path.append(outer);
}
return ret;
}
else if (isLocalFile(contextURL, input) && nestLevel > 0) {
assert(path.length() == 0);
path.append(input);
return true;
}
else {
return false;
}
}
private static boolean getLocalArchiveOutputPath(URL contextURL, String input, boolean appendData,
int compressLevel, StringBuilder path) throws IOException {
return getLocalArchivePath(contextURL, input, appendData, compressLevel, path, 0, true);
}
static String getLocalArchiveInputPath(URL contextURL, String input)
throws IOException {
StringBuilder path = new StringBuilder();
return getLocalArchiveInputPath(contextURL, input, path) ? path.toString() : null;
}
static de.schlichtherle.io.File getLocalZipArchive(URL contextURL, String localArchivePath) throws IOException {
// apply the contextURL
URL url = FileUtils.getFileURL(contextURL, localArchivePath);
String absolutePath = FileUtils.getUrlFile(url);
registerTrueZipVSFEntry(new de.schlichtherle.io.File(localArchivePath));
return new de.schlichtherle.io.File(absolutePath);
}
private static boolean getLocalArchiveInputPath(URL contextURL, String input, StringBuilder path)
throws IOException {
return getLocalArchivePath(contextURL, input, false, 0, path, 0, false);
}
private static void registerTrueZipVSFEntry(de.schlichtherle.io.File entry) {
TransformationGraph graph = ContextProvider.getGraph();
if (graph != null) {
graph.getVfsEntries().addVFSEntry(entry);
}
}
public static OutputStream getOutputStream(URL contextURL, String input, boolean appendData, int compressLevel) throws IOException {
OutputStream os = null;
StringBuilder localArchivePath = new StringBuilder();
if (getLocalArchiveOutputPath(contextURL, input, appendData, compressLevel, localArchivePath)) {
String archPath = localArchivePath.toString();
// apply the contextURL
URL url = FileUtils.getFileURL(contextURL, archPath);
String absolutePath = getUrlFile(url);
de.schlichtherle.io.File archive = new de.schlichtherle.io.File(absolutePath);
boolean mkdirsResult = archive.getParentFile().mkdirs();
log.debug("Opening local archive entry " + archive.getAbsolutePath()
+ " (mkdirs: " + mkdirsResult
+ ", exists:" + archive.exists() + ")");
registerTrueZipVSFEntry(archive);
return new de.schlichtherle.io.FileOutputStream(absolutePath, appendData);
}
//first we try the custom path resolvers
for (CustomPathResolver customPathResolver : customPathResolvers) {
os = customPathResolver.getOutputStream(contextURL, input, appendData, compressLevel);
if (os != null) {
log.debug("Output stream '" + input + "[" + contextURL + "] was opened by custom path resolver.");
return os; //we found the desired output stream using external resolver method
}
}
// std input (console)
if (isConsole(input)) {
return Channels.newOutputStream(new SystemOutByteChannel());
}
// get inner source
Matcher matcher = getInnerInput(input);
String innerSource = null;
if (matcher != null && (innerSource = matcher.group(5)) != null) {
// get and set proxy and go to inner source
Proxy proxy = getProxy(innerSource);
String proxyUserInfo = null;
if (proxy != null) {
try {
proxyUserInfo = new URI(innerSource).getUserInfo();
} catch (URISyntaxException ex) {
}
}
input = matcher.group(2) + matcher.group(3) + matcher.group(7);
if (proxy == null) {
os = getOutputStream(contextURL, innerSource, appendData, compressLevel);
} else {
// this could work even for WebDAV via an authorized proxy,
// but getInnerInput() above would have to be replaced with FileURLParser.getURLMatcher().
// In addition, WebdavOutputStream creates parent directories (which is wrong, but we don't have anything better yet).
URLConnection connection = getAuthorizedConnection(getFileURL(contextURL, input), proxy, proxyUserInfo);
connection.setDoOutput(true);
os = connection.getOutputStream();
}
}
// get archive type
StringBuilder sbAnchor = new StringBuilder();
StringBuilder sbInnerInput = new StringBuilder();
ArchiveType archiveType = getArchiveType(input, sbInnerInput, sbAnchor);
input = sbInnerInput.toString();
//open channel
if (os == null) {
// create output stream
if (isRemoteFile(input) && !isHttp(input)) {
// ftp output stream
URL url = FileUtils.getFileURL(contextURL, input);
Pair<String, String> parts = FileUtils.extractProxyString(url.toString());
try {
url = FileUtils.getFileURL(contextURL, parts.getFirst());
} catch (MalformedURLException ex) {
}
String proxyString = parts.getSecond();
Proxy proxy = null;
UserInfo proxyCredentials = null;
if (proxyString != null) {
proxy = FileUtils.getProxy(proxyString);
try {
String userInfo = new URI(proxyString).getUserInfo();
if (userInfo != null) {
proxyCredentials = new UserInfo(userInfo);
}
} catch (URISyntaxException use) {
}
}
URLConnection urlConnection = ((proxy != null) ? url.openConnection(proxy) : url.openConnection());
if (urlConnection instanceof ProxyAuthenticable) {
((ProxyAuthenticable) urlConnection).setProxyCredentials(proxyCredentials);
}
if (urlConnection instanceof SFTPConnection) {
((SFTPConnection)urlConnection).setMode(appendData? ChannelSftp.APPEND : ChannelSftp.OVERWRITE);
}
try {
os = urlConnection.getOutputStream();
} catch (IOException e) {
log.debug("IOException occured for URL - host: '" + url.getHost() + "', path: '" + url.getPath() + "' (user info not shown)",
"IOException occured for URL - host: '" + url.getHost() + "', userinfo: '" + url.getUserInfo() + "', path: '" + url.getPath() + "'");
throw e;
}
} else if (S3InputStream.isS3File(input)) {
// must be done before isHttp() check
return new S3OutputStream(new URL(input));
} else if (isHttp(input)) {
return new WebdavOutputStream(input);
} else if (isSandbox(input)) {
TransformationGraph graph = ContextProvider.getGraph();
if (graph == null) {
throw new NullPointerException("Graph reference cannot be null when \"" + SandboxUrlUtils.SANDBOX_PROTOCOL + "\" protocol is used.");
}
URL url = FileUtils.getFileURL(contextURL, input);
return graph.getAuthorityProxy().getSandboxResourceOutput(url.getHost(), SandboxUrlUtils.getRelativeUrl(url.toString()), appendData);
} else {
// file path or relative URL
URL url = FileUtils.getFileURL(contextURL, input);
if (isSandbox(url.toString())) {
TransformationGraph graph = ContextProvider.getGraph();
if (graph == null) {
throw new NullPointerException("Graph reference cannot be null when \"" + SandboxUrlUtils.SANDBOX_PROTOCOL + "\" protocol is used.");
}
return graph.getAuthorityProxy().getSandboxResourceOutput(url.getHost(), getUrlFile(url), appendData);
}
// file input stream
String filePath = url.getRef() != null ? getUrlFile(url) + "#" + url.getRef() : getUrlFile(url);
os = new FileOutputStream(filePath, appendData);
}
}
// create writable channel
// zip channel
if(archiveType == ArchiveType.ZIP) {
// resolve url format for zip files
if (appendData) {
throw new IOException("Appending to remote archives is not supported");
}
de.schlichtherle.util.zip.ZipOutputStream zout = new de.schlichtherle.util.zip.ZipOutputStream(os);
if (compressLevel != -1) {
zout.setLevel(compressLevel);
}
String anchor = sbAnchor.toString();
de.schlichtherle.util.zip.ZipEntry entry =
new de.schlichtherle.util.zip.ZipEntry(anchor.equals("") ? DEFAULT_ZIP_FILE : anchor);
zout.putNextEntry(entry);
return zout;
}
// gzip channel
else if (archiveType == ArchiveType.GZIP) {
if (appendData) {
throw new IOException("Appending to remote archives is not supported");
}
GZIPOutputStream gzos = new GZIPOutputStream(os, Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE);
return gzos;
}
// other channel
return os;
}
/**
* This method checks whether it is possible to write to given file.
*
* @param contextURL
* @param fileURL
* @param mkDirs - tries to make directories if it is necessary
* @return true if can write, false otherwise
* @throws ComponentNotReadyException
*/
@SuppressWarnings(value = "RV_ABSOLUTE_VALUE_OF_HASHCODE")
public static boolean canWrite(URL contextURL, String fileURL, boolean mkDirs) throws ComponentNotReadyException {
// get inner source
Matcher matcher = getInnerInput(fileURL);
String innerSource;
if (matcher != null && (innerSource = matcher.group(5)) != null) {
return canWrite(contextURL, innerSource, mkDirs);
}
String fileName;
if (fileURL.startsWith("zip:") || fileURL.startsWith("tar:")){
int pos;
fileName = fileURL.substring(fileURL.indexOf(':') + 1,
(pos = fileURL.indexOf('#')) == -1 ? fileURL.length() : pos);
}else if (fileURL.startsWith("gzip:")){
fileName = fileURL.substring(fileURL.indexOf(':') + 1);
}else{
fileName = fileURL;
}
MultiOutFile multiOut = new MultiOutFile(fileName);
File file;
URL url;
boolean tmp = false;
//create file on given URL
try {
String filename = multiOut.next();
if(filename.startsWith("port:")) return true;
if(filename.startsWith("dict:")) return true;
url = getFileURL(contextURL, filename);
if(!url.getProtocol().equalsIgnoreCase("file")) return true;
// if the url is a path, make a fake file
String sUrl = getUrlFile(url);
boolean isFile = !sUrl.endsWith("/") && !sUrl.endsWith("\\");
if (!isFile) {
if (fileURL.indexOf("
sUrl = sUrl + "tmpfile" + Math.abs(sUrl.hashCode());
} else {
sUrl = sUrl + "tmpfile" + UUID.randomUUID();
}
}
file = new File(sUrl);
} catch (Exception e) {
throw new ComponentNotReadyException(e + ": " + fileURL);
}
//check if can write to this file
tmp = file.exists() ? file.canWrite() : createFile(file, mkDirs);
if (!tmp) {
throw new ComponentNotReadyException("Can't write to: " + fileURL);
}
return true;
}
/**
* Creates the parent dirs of the target file,
* if necessary. It is assumed that the target
* is a regular file, not a directory.
*
* The parent directories may not have been created,
* even if the method does not throw any exception.
*
* @param contextURL
* @param fileURL
* @throws ComponentNotReadyException
*/
public static void createParentDirs(URL contextURL, String fileURL) throws ComponentNotReadyException {
try {
URL innerMostURL = FileUtils.getFileURL(contextURL, FileURLParser.getMostInnerAddress(fileURL));
String innerMostURLString = innerMostURL.toString();
boolean isFile = !innerMostURLString.endsWith("/") && !innerMostURLString.endsWith("\\");
if (FileUtils.isLocalFile(contextURL, innerMostURLString)) {
File file = FileUtils.getJavaFile(contextURL, innerMostURLString);
String sFile = isFile ? file.getParent() : file.getPath();
FileUtils.makeDirs(contextURL, sFile);
} else if (SandboxUrlUtils.isSandboxUrl(innerMostURLString)) {
// SandboxUrlUtils.getRelativeUrl() ensures that the path won't start with a slash, which causes problems on Linux
File file = new File(SandboxUrlUtils.getRelativeUrl(innerMostURLString));
String sFile = isFile ? file.getParent() : file.getPath(); // a hack to get the parent directory
FileUtils.makeDirs(contextURL, sFile);
} else {
Operation operation = Operation.create(innerMostURL.getProtocol());
FileManager manager = FileManager.getInstance();
String sFile = isFile ? URIUtils.getParentURI(URI.create(innerMostURLString)).toString() : innerMostURLString;
if (manager.canPerform(operation)) {
manager.create(CloverURI.createURI(sFile), new CreateParameters().setDirectory(true).setMakeParents(true));
// ignore the result
}
}
} catch (Exception e) { // FIXME parent dir creation fails for proxies
log.debug(e.getMessage());
}
}
/**
* Creates directory for fileURL if it is necessary.
* @param contextURL
* @param fileURL
* @return created parent directory
* @throws ComponentNotReadyException
*/
public static File makeDirs(URL contextURL, String fileURL) throws ComponentNotReadyException {
if (contextURL == null && fileURL == null) return null;
URL url;
try {
url = FileUtils.getFileURL(contextURL, FileURLParser.getMostInnerAddress(fileURL));
} catch (MalformedURLException e) {
return null;
}
if (SandboxUrlUtils.isSandboxUrl(url)) {
TransformationGraph graph = ContextProvider.getGraph();
if (graph == null) {
throw new NullPointerException("Graph reference cannot be null when \"" + SandboxUrlUtils.SANDBOX_PROTOCOL + "\" protocol is used.");
}
try {
graph.getAuthorityProxy().makeDirectories(url.getHost(), url.getPath());
} catch (IOException exception) {
throw new ComponentNotReadyException("Making of sandbox directories failed!", exception);
}
return null;
}
if (!url.getProtocol().equals(FILE_PROTOCOL)) return null;
//find the first non-existing directory
File file = new File(url.getPath());
File fileTmp = file;
File createDir = null;
while (fileTmp != null && !fileTmp.exists()) {
createDir = fileTmp;
fileTmp = fileTmp.getParentFile();
}
if (createDir != null && !file.mkdirs()) {
if (!file.exists()) {
// dir still doesn't exist - throw ex.
throw new ComponentNotReadyException("Cannot create directory: " + file);
}
}
return createDir;
}
/**
* Gets file path from URL, properly handles special URL characters (like %20)
* @param url
* @return
* @throws UnsupportedEncodingException
*
* @see #handleSpecialCharacters(java.net.URL)
*/
private static String getUrlFile(URL url) {
try {
final String fixedFileUrl = handleSpecialCharacters(url);
return URLDecoder.decode(fixedFileUrl, UTF8);
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException("Encoding not supported!", ex);
}
}
/**
* Fix problems with special characters that occurs while running on Mac OS X enviroment and using path
* which contains '+' character, e.g. /var/folders/t6/t6VjEdukHKWHBtJyNy8wEU+++TI/-Tmp-/.
* Without special handling, method #getUrlFile will return /var/folders/t6/t6VjEdukHKWHBtJyNy8wEU TI/-Tmp-/,
* handling '+' characeter as ' ' (space).
*
* @param url
* @return
*/
private static String handleSpecialCharacters(URL url) {
return url.getFile().replace("+", PLUS_CHAR_ENCODED);
}
/**
* Tries to create file and directories.
* @param fileURL
* @return
* @throws ComponentNotReadyException
*/
private static boolean createFile(File file, boolean mkDirs) throws ComponentNotReadyException {
boolean tmp = false;
boolean fails = false;
try {
tmp = file.createNewFile();
} catch (IOException e) {
if (!mkDirs) throw new ComponentNotReadyException(e + ": " + file);
fails = true;
}
File createdDir = null;
if (fails) {
createdDir = file.getParentFile();
createdDir = makeDirs(null, createdDir.getAbsolutePath());
try {
tmp = file.createNewFile();
} catch (IOException e) {
if (createdDir != null) {
if (!deleteFile(createdDir)) {
log.error("error delete " + createdDir);
}
}
throw new ComponentNotReadyException(e + ": " + file);
}
}
if (tmp) {
if (!file.delete()) {
log.error("error delete " + file.getAbsolutePath());
}
}
if (createdDir != null) {
if (!deleteFile(createdDir)) {
log.error("error delete " + createdDir);
}
}
return tmp;
}
/**
* Deletes file.
* @param file
* @return true if the file is deleted
*/
private static boolean deleteFile(File file) {
if (!file.exists()) return true;
//list and delete all sub-directories
for (File child: file.listFiles()) {
if (!deleteFile(child)) {
return false;
}
}
return file.delete();
}
/**
* This method checks whether is is possible to write to given file
*
* @param contextURL
* @param fileURL
* @return true if can write, false otherwise
* @throws ComponentNotReadyException
*/
public static boolean canWrite(URL contextURL, String fileURL) throws ComponentNotReadyException {
return canWrite(contextURL, fileURL, false);
}
/**
* This method checks whether is is possible to write to given directory
*
* @param dest
* @return true if can write, false otherwise
*/
public static boolean canWrite(File dest){
if (dest.exists()) return dest.canWrite();
List<File> dirs = getDirs(dest);
boolean result = dest.mkdirs();
//clean up
for (File dir : dirs) {
if (dir.exists()) {
boolean deleted = dir.delete();
if( !deleted ){
log.error("error delete " + dir.getAbsolutePath());
}
}
}
return result;
}
/**
* @param file
* @return list of directories, which have to be created to create this directory (don't exist),
* empty list if requested directory exists
*/
private static List<File> getDirs(File file){
ArrayList<File> dirs = new ArrayList<File>();
File dir = file;
if (file.exists()) return dirs;
dirs.add(file);
while (!(dir = dir.getParentFile()).exists()) {
dirs.add(dir);
}
return dirs;
}
public static Matcher getInnerInput(String source) {
Matcher matcher = INNER_SOURCE.matcher(source);
return matcher.find() ? matcher : null;
}
/**
* Returns file name of input (URL).
*
* @param input - url file name
* @return file name
* @throws MalformedURLException
*
* @see java.net.URL#getFile()
*/
public static String getFile(URL contextURL, String input) throws MalformedURLException {
Matcher matcher = getInnerInput(input);
String innerSource2, innerSource3;
if (matcher != null && (innerSource2 = matcher.group(5)) != null) {
if (!(innerSource3 = matcher.group(7)).equals("")) {
return innerSource3.substring(1);
} else {
input = getFile(null, innerSource2);
}
}
URL url = getFileURL(contextURL, input);
if (SandboxUrlUtils.isSandboxUrl(url)) { // CLS-754
try {
CloverURI cloverUri = CloverURI.createURI(url.toURI());
File file = FileManager.getInstance().getFile(cloverUri);
if (file != null) {
return file.toString();
}
} catch (Exception e) {
log.debug("Failed to resolve sandbox URL", e);
}
}
if (url.getRef() != null) return url.getRef();
else {
input = getUrlFile(url);
if (input.startsWith("zip:") || input.startsWith("tar:")) {
input = input.contains("
input.substring(input.lastIndexOf('
input.substring(input.indexOf(':') + 1);
} else if (input.startsWith("gzip:")) {
input = input.substring(input.indexOf(':') + 1);
}
return normalizeFilePath(input);
}
}
/**
* Adds final slash to the directory path, if it is necessary.
* @param directoryPath
* @return
*/
public static String appendSlash(String directoryPath) {
if(directoryPath.length() == 0 || directoryPath.endsWith("/") || directoryPath.endsWith("\\")) {
return directoryPath;
} else {
return directoryPath + "/";
}
}
/**
* Parses address and returns true if the address contains a server.
*
* @param input
* @return
* @throws IOException
*/
public static boolean isServerURL(URL url) throws IOException {
return url != null && !url.getProtocol().equals(FILE_PROTOCOL);
}
public static boolean isArchiveURL(URL url) {
String protocol = null;
if (url != null) {
protocol = url.getProtocol();
}
return protocol.equals(TAR_PROTOCOL) || protocol.equals(GZIP_PROTOCOL) || protocol.equals(ZIP_PROTOCOL);
}
/**
* Creates URL connection and connect the server.
*
* @param url
* @throws IOException
*/
public static void checkServer(URL url) throws IOException {
if (url == null) {
return;
}
URLConnection connection = url.openConnection();
connection.connect();
if (connection instanceof SFTPConnection) {
((SFTPConnection) connection).disconnect();
}
}
/**
* Gets the most inner url address.
* @param contextURL
*
* @param input
* @return
* @throws IOException
*/
public static URL getInnerAddress(URL contextURL, String input) throws IOException {
URL url = null;
// get inner source
Matcher matcher = getInnerInput(input);
String innerSource;
if (matcher != null && (innerSource = matcher.group(5)) != null) {
url = getInnerAddress(contextURL, innerSource);
input = matcher.group(2) + matcher.group(3) + matcher.group(7);
}
// std input (console)
if (input.equals(STD_CONSOLE)) {
return null;
}
//resolve url format for zip files
if(input.startsWith("zip:") || input.startsWith("tar:")) {
if(!input.contains("#")) { //url is given without anchor - later is returned channel from first zip entry
input = input.substring(input.indexOf(':') + 1);
} else {
input = input.substring(input.indexOf(':') + 1, input.lastIndexOf('
}
}
else if (input.startsWith("gzip:")) {
input = input.substring(input.indexOf(':') + 1);
}
return url == null ? FileUtils.getFileURL(contextURL, input) : url;
}
/**
* Adds new custom path resolver. Useful for third-party implementation of path resolving.
* @param customPathResolver
*/
public static void addCustomPathResolver(CustomPathResolver customPathResolver) {
customPathResolvers.add(customPathResolver);
}
public static File convertUrlToFile(URL url) throws MalformedURLException {
String protocol = url.getProtocol();
if (protocol.equals(FILE_PROTOCOL)) {
try {
return new File(url.toURI());
} catch(URISyntaxException e) {
StringBuilder path = new StringBuilder(url.getFile());
if (!StringUtils.isEmpty(url.getRef())) {
path.append('#').append(url.getRef());
}
return new File(path.toString());
} catch(IllegalArgumentException e2) {
StringBuilder path = new StringBuilder(url.getFile());
if (!StringUtils.isEmpty(url.getRef())) {
path.append('#').append(url.getRef());
}
return new File(path.toString());
}
} else if (protocol.equals(SandboxUrlUtils.SANDBOX_PROTOCOL)) {
try {
CloverURI cloverUri = CloverURI.createURI(url.toURI());
File file = FileManager.getInstance().getFile(cloverUri);
if (file != null) {
return file;
}
} catch (Exception e) {
log.debug("Failed to resolve sandbox URL", e);
}
}
throw new MalformedURLException("URL '" + url.toString() + "' cannot be converted to File.");
}
/**
* Tries to convert the given string to {@link File}.
* @param contextUrl context URL which is used for relative path
* @param file string representing the file
* @return {@link File} representation
*/
public static File getJavaFile(URL contextUrl, String file) {
URL fileURL;
try {
fileURL = FileUtils.getFileURL(contextUrl, file);
} catch (MalformedURLException e) {
throw new JetelRuntimeException("Invalid file URL definition.", e);
}
try {
return FileUtils.convertUrlToFile(fileURL);
} catch (MalformedURLException e) {
throw new JetelRuntimeException("File URL does not have 'file' protocol.", e);
}
}
/**
* <p>This method affects only windows platform following way:
* <ul><li> backslashes are replaced by slashes
* <li>if first character is slash and device specification follows, the starting slash is removed
* </ul>
*
* <p>For example:
*
* <p><tt>c:\project\data.txt -> c:/project/data.txt<br>
* /c:/project/data.txt -> c:/project/data.txt
*
* <p>A path reached from method anUrl.getPath() (or anUrl.getFile()) should be cleaned by this method.
*
* @param path
* @return
*/
public static String normalizeFilePath(String path) {
if (path == null) {
return "";
} else {
if (PlatformUtils.isWindowsPlatform()) {
//convert backslash to forward slash
path = path.indexOf('\\') == -1 ? path : path.replace('\\', '/');
//if device is present
int i = path.indexOf(':');
if (i != -1) {
//remove leading slash from device part to handle output of URL.getFile()
path = path.charAt(0) == '/' ? path.substring(1, path.length()) : path;
}
}
return path;
}
}
/**
* Standardized way how to convert an URL to string.
* For URLs with 'file' protocol only simple path is returned (for example file:/c:/project/data.txt ->c:/project/data.txt)
* The URLs with other protocols are converted by URL.toString() method.
*
* @param url
* @return
*/
public static String convertUrlToString(URL url) {
if (url == null) {
return null;
}
if (url.getProtocol().equals(FILE_PROTOCOL)) {
return normalizeFilePath(url.getPath());
} else {
return url.toString();
}
}
public static class ArchiveURLStreamHandler extends URLStreamHandler {
private URL context;
public ArchiveURLStreamHandler() {
}
private ArchiveURLStreamHandler(URL context) {
this.context = context;
}
@Override
protected URLConnection openConnection(URL u) throws IOException {
return new ArchiveURLConnection(context, u);
}
}
private static class ArchiveURLConnection extends URLConnection {
private URL context;
public ArchiveURLConnection(URL context, URL url) {
super(url);
this.context = context;
}
@Override
public void connect() throws IOException {
}
@Override
public InputStream getInputStream() throws IOException {
String urlString;
try {
// Try to decode %-encoded URL
// Fix of CLD-2872 if scheme is in a zip file and the URL contains spaces (or other URL-invalid chars)
URI uri = url.toURI();
if (uri.isOpaque()) {
// This is intended to handle archive (e.g. zip:...) URLs
// Example of expected URI format: zip:(sandbox://sanboxName/path%20with%20spaces.zip)#path%20inside%20zip.xsd
// Decode only fragmet part to get zip:(sandbox://sanboxName/path%20with%20spaces.zip)#path inside zip.xsd
urlString = decodeFragment(uri);
} else {
urlString = uri.toString();
}
} catch (URISyntaxException e) {
urlString = url.toString();
}
return FileUtils.getInputStream(context, urlString);
}
private static String decodeFragment(URI uri) {
StringBuilder sb = new StringBuilder();
if (uri.getScheme() != null) {
sb.append(uri.getScheme()).append(':');
}
sb.append(uri.getRawSchemeSpecificPart());
if (uri.getFragment() != null) {
sb.append('#').append(uri.getFragment());
}
return sb.toString();
}
}
/**
* Quietly closes the passed IO object.
* Does nothing if the argument is <code>null</code>.
* Ignores any exceptions throw when closing the object.
*
* @param closeable an IO object to be closed
*/
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ex) {
// ignore
}
}
}
/**
* Closes all objects passed as the argument.
* If any of them throws an exception, the first exception is thrown.
*
* @param closeables
* @throws IOException
*/
public static void closeAll(Closeable... closeables) throws IOException {
if (closeables != null) {
IOException firstException = null;
for (Closeable closeable: closeables) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ex) {
if (firstException == null) {
firstException = ex;
}
}
}
}
if (firstException != null) {
throw firstException;
}
}
}
/**
* Efficiently copies file contents from source to target.
* Creates the target file, if it does not exist.
* The parent directories of the target file are not created.
*
* @param source source file
* @param target target file
* @return <code>true</code> if the whole content of the source file was copied.
*
* @throws IOException
*/
public static boolean copyFile(File source, File target) throws IOException {
FileInputStream inputStream = null;
FileOutputStream outputStream = null;
FileChannel inputChannel = null;
FileChannel outputChannel = null;
try {
inputStream = new FileInputStream(source);
outputStream = new FileOutputStream(target);
inputChannel = inputStream.getChannel();
outputChannel = outputStream.getChannel();
StreamUtils.copy(inputChannel, outputChannel);
return true;
} finally {
closeAll(outputChannel, outputStream, inputChannel, inputStream);
}
}
/**
* Delete the supplied {@link File} - for directories,
* recursively delete any nested directories or files as well.
* @param root the root <code>File</code> to delete
* @return <code>true</code> if the <code>File</code> was deleted,
* otherwise <code>false</code>
*/
public static boolean deleteRecursively(File root) throws IOException {
if (Thread.currentThread().isInterrupted()) {
throw new IOException("Interrupted");
}
if (root != null && root.exists()) {
if (root.isDirectory()) {
File[] children = root.listFiles();
if (children != null) {
for (int i = 0; i < children.length; i++) {
deleteRecursively(children[i]);
}
}
}
return root.delete();
}
return false;
}
/**
* Checks the given string whether represents multiple URL.
* This is only simple test, whether the given string contains
* one of these three characters <b>;*?</b>.
* @param fileURL
* @return true if and only if the given string represents multiple URL
*/
public static boolean isMultiURL(String fileURL) {
return fileURL != null && (fileURL.contains(";") || fileURL.contains("*") || fileURL.contains("?"));
}
}
/*
* End class FileUtils
*/ |
package net.minecraftforge.common;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.BiMap;
import com.google.common.collect.ForwardingSet;
import com.google.common.collect.HashBiMap;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSetMultimap;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.MapMaker;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.common.collect.Multiset;
import com.google.common.collect.SetMultimap;
import com.google.common.collect.Sets;
import com.google.common.collect.TreeMultiset;
import cpw.mods.fml.common.FMLLog;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.src.Chunk;
import net.minecraft.src.ChunkCoordIntPair;
import net.minecraft.src.CompressedStreamTools;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.MathHelper;
import net.minecraft.src.NBTBase;
import net.minecraft.src.NBTTagCompound;
import net.minecraft.src.NBTTagList;
import net.minecraft.src.World;
import net.minecraft.src.WorldServer;
import net.minecraftforge.common.ForgeChunkManager.Ticket;
import net.minecraftforge.event.Event;
/**
* Manages chunkloading for mods.
*
* The basic principle is a ticket based system.
* 1. Mods register a callback {@link #setForcedChunkLoadingCallback(Object, LoadingCallback)}
* 2. Mods ask for a ticket {@link #requestTicket(Object, World, Type)} and then hold on to that ticket.
* 3. Mods request chunks to stay loaded {@link #forceChunk(Ticket, ChunkCoordIntPair)} or remove chunks from force loading {@link #unforceChunk(Ticket, ChunkCoordIntPair)}.
* 4. When a world unloads, the tickets associated with that world are saved by the chunk manager.
* 5. When a world loads, saved tickets are offered to the mods associated with the tickets. The {@link Ticket#getModData()} that is set by the mod should be used to re-register
* chunks to stay loaded (and maybe take other actions).
*
* The chunkloading is configurable at runtime. The file "config/forgeChunkLoading.cfg" contains both default configuration for chunkloading, and a sample individual mod
* specific override section.
*
* @author cpw
*
*/
public class ForgeChunkManager
{
private static int defaultMaxCount;
private static int defaultMaxChunks;
private static boolean overridesEnabled;
private static Map<World, Multimap<String, Ticket>> tickets = new MapMaker().weakKeys().makeMap();
private static Map<String, Integer> ticketConstraints = Maps.newHashMap();
private static Map<String, Integer> chunkConstraints = Maps.newHashMap();
private static SetMultimap<String, Ticket> playerTickets = HashMultimap.create();
private static Map<String, LoadingCallback> callbacks = Maps.newHashMap();
private static Map<World, ImmutableSetMultimap<ChunkCoordIntPair,Ticket>> forcedChunks = new MapMaker().weakKeys().makeMap();
private static BiMap<UUID,Ticket> pendingEntities = HashBiMap.create();
private static Map<World,Cache<Long, Chunk>> dormantChunkCache = new MapMaker().weakKeys().makeMap();
private static File cfgFile;
private static Configuration config;
private static int playerTicketLength;
private static int dormantChunkCacheSize;
/**
* All mods requiring chunkloading need to implement this to handle the
* re-registration of chunk tickets at world loading time
*
* @author cpw
*
*/
public interface LoadingCallback
{
/**
* Called back when tickets are loaded from the world to allow the
* mod to re-register the chunks associated with those tickets. The list supplied
* here is truncated to length prior to use. Tickets unwanted by the
* mod must be disposed of manually unless the mod is an OrderedLoadingCallback instance
* in which case, they will have been disposed of by the earlier callback.
*
* @param tickets The tickets to re-register. The list is immutable and cannot be manipulated directly. Copy it first.
* @param world the world
*/
public void ticketsLoaded(List<Ticket> tickets, World world);
}
/**
* This is a special LoadingCallback that can be implemented as well as the
* LoadingCallback to provide access to additional behaviour.
* Specifically, this callback will fire prior to Forge dropping excess
* tickets. Tickets in the returned list are presumed ordered and excess will
* be truncated from the returned list.
* This allows the mod to control not only if they actually <em>want</em> a ticket but
* also their preferred ticket ordering.
*
* @author cpw
*
*/
public interface OrderedLoadingCallback extends LoadingCallback
{
/**
* Called back when tickets are loaded from the world to allow the
* mod to decide if it wants the ticket still, and prioritise overflow
* based on the ticket count.
* WARNING: You cannot force chunks in this callback, it is strictly for allowing the mod
* to be more selective in which tickets it wishes to preserve in an overflow situation
*
* @param tickets The tickets that you will want to select from. The list is immutable and cannot be manipulated directly. Copy it first.
* @param world The world
* @param maxTicketCount The maximum number of tickets that will be allowed.
* @return A list of the tickets this mod wishes to continue using. This list will be truncated
* to "maxTicketCount" size after the call returns and then offered to the other callback
* method
*/
public List<Ticket> ticketsLoaded(List<Ticket> tickets, World world, int maxTicketCount);
}
public interface PlayerOrderedLoadingCallback extends LoadingCallback
{
/**
* Called back when tickets are loaded from the world to allow the
* mod to decide if it wants the ticket still.
* This is for player bound tickets rather than mod bound tickets. It is here so mods can
* decide they want to dump all player tickets
*
* WARNING: You cannot force chunks in this callback, it is strictly for allowing the mod
* to be more selective in which tickets it wishes to preserve
*
* @param tickets The tickets that you will want to select from. The list is immutable and cannot be manipulated directly. Copy it first.
* @param world The world
* @return A list of the tickets this mod wishes to use. This list will subsequently be offered
* to the main callback for action
*/
public ListMultimap<String, Ticket> playerTicketsLoaded(ListMultimap<String, Ticket> tickets, World world);
}
public enum Type
{
/**
* For non-entity registrations
*/
NORMAL,
/**
* For entity registrations
*/
ENTITY
}
public static class Ticket
{
private String modId;
private Type ticketType;
private LinkedHashSet<ChunkCoordIntPair> requestedChunks;
private NBTTagCompound modData;
public final World world;
private int maxDepth;
private String entityClazz;
private int entityChunkX;
private int entityChunkZ;
private Entity entity;
private String player;
Ticket(String modId, Type type, World world)
{
this.modId = modId;
this.ticketType = type;
this.world = world;
this.maxDepth = getMaxChunkDepthFor(modId);
this.requestedChunks = Sets.newLinkedHashSet();
}
Ticket(String modId, Type type, World world, String player)
{
this(modId, type, world);
if (player != null)
{
this.player = player;
}
else
{
FMLLog.log(Level.SEVERE, "Attempt to create a player ticket without a valid player");
throw new RuntimeException();
}
}
/**
* The chunk list depth can be manipulated up to the maximal grant allowed for the mod. This value is configurable. Once the maximum is reached,
* the least recently forced chunk, by original registration time, is removed from the forced chunk list.
*
* @param depth The new depth to set
*/
public void setChunkListDepth(int depth)
{
if (depth > getMaxChunkDepthFor(modId) || (depth <= 0 && getMaxChunkDepthFor(modId) > 0))
{
FMLLog.warning("The mod %s tried to modify the chunk ticket depth to: %d, its allowed maximum is: %d", modId, depth, getMaxChunkDepthFor(modId));
}
else
{
this.maxDepth = depth;
}
}
/**
* Gets the current max depth for this ticket.
* Should be the same as getMaxChunkListDepth()
* unless setChunkListDepth has been called.
*
* @return Current max depth
*/
public int getChunkListDepth()
{
return maxDepth;
}
/**
* Get the maximum chunk depth size
*
* @return The maximum chunk depth size
*/
public int getMaxChunkListDepth()
{
return getMaxChunkDepthFor(modId);
}
/**
* Bind the entity to the ticket for {@link Type#ENTITY} type tickets. Other types will throw a runtime exception.
*
* @param entity The entity to bind
*/
public void bindEntity(Entity entity)
{
if (ticketType!=Type.ENTITY)
{
throw new RuntimeException("Cannot bind an entity to a non-entity ticket");
}
this.entity = entity;
}
/**
* Retrieve the {@link NBTTagCompound} that stores mod specific data for the chunk ticket.
* Example data to store would be a TileEntity or Block location. This is persisted with the ticket and
* provided to the {@link LoadingCallback} for the mod. It is recommended to use this to recover
* useful state information for the forced chunks.
*
* @return The custom compound tag for mods to store additional chunkloading data
*/
public NBTTagCompound getModData()
{
if (this.modData == null)
{
this.modData = new NBTTagCompound();
}
return modData;
}
/**
* Get the entity associated with this {@link Type#ENTITY} type ticket
* @return
*/
public Entity getEntity()
{
return entity;
}
/**
* Is this a player associated ticket rather than a mod associated ticket?
*/
public boolean isPlayerTicket()
{
return player != null;
}
/**
* Get the player associated with this ticket
*/
public String getPlayerName()
{
return player;
}
/**
* Get the associated mod id
*/
public String getModId()
{
return modId;
}
/**
* Gets the ticket type
*/
public Type getType()
{
return ticketType;
}
/**
* Gets a list of requested chunks for this ticket.
*/
public ImmutableSet getChunkList()
{
return ImmutableSet.copyOf(requestedChunks);
}
}
public static class ForceChunkEvent extends Event {
public final Ticket ticket;
public final ChunkCoordIntPair location;
public ForceChunkEvent(Ticket ticket, ChunkCoordIntPair location)
{
this.ticket = ticket;
this.location = location;
}
}
public static class UnforceChunkEvent extends Event {
public final Ticket ticket;
public final ChunkCoordIntPair location;
public UnforceChunkEvent(Ticket ticket, ChunkCoordIntPair location)
{
this.ticket = ticket;
this.location = location;
}
}
/**
* Allows dynamically loading world mods to test if there are chunk tickets in the world
* Mods that add dynamically generated worlds (like Mystcraft) should call this method
* to determine if the world should be loaded during server starting.
*
* @param chunkDir The chunk directory to test: should be equivalent to {@link WorldServer#getChunkSaveLocation()}
* @return if there are tickets outstanding for this world or not
*/
public static boolean savedWorldHasForcedChunkTickets(File chunkDir)
{
File chunkLoaderData = new File(chunkDir, "forcedchunks.dat");
if (chunkLoaderData.exists() && chunkLoaderData.isFile())
{
;
try
{
NBTTagCompound forcedChunkData = CompressedStreamTools.read(chunkLoaderData);
return forcedChunkData.getTagList("TicketList").tagCount() > 0;
}
catch (IOException e)
{
}
}
return false;
}
static void loadWorld(World world)
{
ArrayListMultimap<String, Ticket> newTickets = ArrayListMultimap.<String, Ticket>create();
tickets.put(world, newTickets);
forcedChunks.put(world, ImmutableSetMultimap.<ChunkCoordIntPair,Ticket>of());
if (!(world instanceof WorldServer))
{
return;
}
dormantChunkCache.put(world, CacheBuilder.newBuilder().maximumSize(dormantChunkCacheSize).<Long, Chunk>build());
WorldServer worldServer = (WorldServer) world;
File chunkDir = worldServer.getChunkSaveLocation();
File chunkLoaderData = new File(chunkDir, "forcedchunks.dat");
if (chunkLoaderData.exists() && chunkLoaderData.isFile())
{
ArrayListMultimap<String, Ticket> loadedTickets = ArrayListMultimap.<String, Ticket>create();
Map<String,ListMultimap<String,Ticket>> playerLoadedTickets = Maps.newHashMap();
NBTTagCompound forcedChunkData;
try
{
forcedChunkData = CompressedStreamTools.read(chunkLoaderData);
}
catch (IOException e)
{
FMLLog.log(Level.WARNING, e, "Unable to read forced chunk data at %s - it will be ignored", chunkLoaderData.getAbsolutePath());
return;
}
NBTTagList ticketList = forcedChunkData.getTagList("TicketList");
for (int i = 0; i < ticketList.tagCount(); i++)
{
NBTTagCompound ticketHolder = (NBTTagCompound) ticketList.tagAt(i);
String modId = ticketHolder.getString("Owner");
boolean isPlayer = "Forge".equals(modId);
if (!isPlayer && !Loader.isModLoaded(modId))
{
FMLLog.warning("Found chunkloading data for mod %s which is currently not available or active - it will be removed from the world save", modId);
continue;
}
if (!isPlayer && !callbacks.containsKey(modId))
{
FMLLog.warning("The mod %s has registered persistent chunkloading data but doesn't seem to want to be called back with it - it will be removed from the world save", modId);
continue;
}
NBTTagList tickets = ticketHolder.getTagList("Tickets");
for (int j = 0; j < tickets.tagCount(); j++)
{
NBTTagCompound ticket = (NBTTagCompound) tickets.tagAt(j);
modId = ticket.hasKey("ModId") ? ticket.getString("ModId") : modId;
Type type = Type.values()[ticket.getByte("Type")];
byte ticketChunkDepth = ticket.getByte("ChunkListDepth");
Ticket tick = new Ticket(modId, type, world);
if (ticket.hasKey("ModData"))
{
tick.modData = ticket.getCompoundTag("ModData");
}
if (ticket.hasKey("Player"))
{
tick.player = ticket.getString("Player");
if (!playerLoadedTickets.containsKey(tick.modId))
{
playerLoadedTickets.put(modId, ArrayListMultimap.<String,Ticket>create());
}
playerLoadedTickets.get(tick.modId).put(tick.player, tick);
}
else
{
loadedTickets.put(modId, tick);
}
if (type == Type.ENTITY)
{
tick.entityChunkX = ticket.getInteger("chunkX");
tick.entityChunkZ = ticket.getInteger("chunkZ");
UUID uuid = new UUID(ticket.getLong("PersistentIDMSB"), ticket.getLong("PersistentIDLSB"));
// add the ticket to the "pending entity" list
pendingEntities.put(uuid, tick);
}
}
}
for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values()))
{
if (tick.ticketType == Type.ENTITY && tick.entity == null)
{
// force the world to load the entity's chunk
// the load will come back through the loadEntity method and attach the entity
// to the ticket
world.getChunkFromChunkCoords(tick.entityChunkX, tick.entityChunkZ);
}
}
for (Ticket tick : ImmutableSet.copyOf(pendingEntities.values()))
{
if (tick.ticketType == Type.ENTITY && tick.entity == null)
{
FMLLog.warning("Failed to load persistent chunkloading entity %s from store.", pendingEntities.inverse().get(tick));
loadedTickets.remove(tick.modId, tick);
}
}
pendingEntities.clear();
// send callbacks
for (String modId : loadedTickets.keySet())
{
LoadingCallback loadingCallback = callbacks.get(modId);
int maxTicketLength = getMaxTicketLengthFor(modId);
List<Ticket> tickets = loadedTickets.get(modId);
if (loadingCallback instanceof OrderedLoadingCallback)
{
OrderedLoadingCallback orderedLoadingCallback = (OrderedLoadingCallback) loadingCallback;
tickets = orderedLoadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world, maxTicketLength);
}
if (tickets.size() > maxTicketLength)
{
FMLLog.warning("The mod %s has too many open chunkloading tickets %d. Excess will be dropped", modId, tickets.size());
tickets.subList(maxTicketLength, tickets.size()).clear();
}
ForgeChunkManager.tickets.get(world).putAll(modId, tickets);
loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets), world);
}
for (String modId : playerLoadedTickets.keySet())
{
LoadingCallback loadingCallback = callbacks.get(modId);
ListMultimap<String,Ticket> tickets = playerLoadedTickets.get(modId);
if (loadingCallback instanceof PlayerOrderedLoadingCallback)
{
PlayerOrderedLoadingCallback orderedLoadingCallback = (PlayerOrderedLoadingCallback) loadingCallback;
tickets = orderedLoadingCallback.playerTicketsLoaded(ImmutableListMultimap.copyOf(tickets), world);
playerTickets.putAll(tickets);
}
ForgeChunkManager.tickets.get(world).putAll("Forge", tickets.values());
loadingCallback.ticketsLoaded(ImmutableList.copyOf(tickets.values()), world);
}
}
}
static void unloadWorld(World world)
{
// World save fires before this event so the chunk loading info will be done
if (!(world instanceof WorldServer))
{
return;
}
forcedChunks.remove(world);
dormantChunkCache.remove(world);
// integrated server is shutting down
if (!MinecraftServer.getServer().isServerRunning())
{
playerTickets.clear();
tickets.clear();
}
}
/**
* Set a chunkloading callback for the supplied mod object
*
* @param mod The mod instance registering the callback
* @param callback The code to call back when forced chunks are loaded
*/
public static void setForcedChunkLoadingCallback(Object mod, LoadingCallback callback)
{
ModContainer container = getContainer(mod);
if (container == null)
{
FMLLog.warning("Unable to register a callback for an unknown mod %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod));
return;
}
callbacks.put(container.getModId(), callback);
}
/**
* Discover the available tickets for the mod in the world
*
* @param mod The mod that will own the tickets
* @param world The world
* @return The count of tickets left for the mod in the supplied world
*/
public static int ticketCountAvailableFor(Object mod, World world)
{
ModContainer container = getContainer(mod);
if (container!=null)
{
String modId = container.getModId();
int allowedCount = getMaxTicketLengthFor(modId);
return allowedCount - tickets.get(world).get(modId).size();
}
else
{
return 0;
}
}
private static ModContainer getContainer(Object mod)
{
ModContainer container = Loader.instance().getModObjectList().inverse().get(mod);
return container;
}
public static int getMaxTicketLengthFor(String modId)
{
int allowedCount = ticketConstraints.containsKey(modId) && overridesEnabled ? ticketConstraints.get(modId) : defaultMaxCount;
return allowedCount;
}
public static int getMaxChunkDepthFor(String modId)
{
int allowedCount = chunkConstraints.containsKey(modId) && overridesEnabled ? chunkConstraints.get(modId) : defaultMaxChunks;
return allowedCount;
}
public static int ticketCountAvaliableFor(String username)
{
return playerTicketLength - playerTickets.get(username).size();
}
@Deprecated
public static Ticket requestPlayerTicket(Object mod, EntityPlayer player, World world, Type type)
{
return requestPlayerTicket(mod, player.getEntityName(), world, type);
}
public static Ticket requestPlayerTicket(Object mod, String player, World world, Type type)
{
ModContainer mc = getContainer(mod);
if (mc == null)
{
FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod));
return null;
}
if (playerTickets.get(player).size()>playerTicketLength)
{
FMLLog.warning("Unable to assign further chunkloading tickets to player %s (on behalf of mod %s)", player, mc.getModId());
return null;
}
Ticket ticket = new Ticket(mc.getModId(),type,world,player);
playerTickets.put(player, ticket);
tickets.get(world).put("Forge", ticket);
return ticket;
}
/**
* Request a chunkloading ticket of the appropriate type for the supplied mod
*
* @param mod The mod requesting a ticket
* @param world The world in which it is requesting the ticket
* @param type The type of ticket
* @return A ticket with which to register chunks for loading, or null if no further tickets are available
*/
public static Ticket requestTicket(Object mod, World world, Type type)
{
ModContainer container = getContainer(mod);
if (container == null)
{
FMLLog.log(Level.SEVERE, "Failed to locate the container for mod instance %s (%s : %x)", mod, mod.getClass().getName(), System.identityHashCode(mod));
return null;
}
String modId = container.getModId();
if (!callbacks.containsKey(modId))
{
FMLLog.severe("The mod %s has attempted to request a ticket without a listener in place", modId);
throw new RuntimeException("Invalid ticket request");
}
int allowedCount = ticketConstraints.containsKey(modId) ? ticketConstraints.get(modId) : defaultMaxCount;
if (tickets.get(world).get(modId).size() >= allowedCount)
{
FMLLog.info("The mod %s has attempted to allocate a chunkloading ticket beyond it's currently allocated maximum : %d", modId, allowedCount);
return null;
}
Ticket ticket = new Ticket(modId, type, world);
tickets.get(world).put(modId, ticket);
return ticket;
}
/**
* Release the ticket back to the system. This will also unforce any chunks held by the ticket so that they can be unloaded and/or stop ticking.
*
* @param ticket The ticket to release
*/
public static void releaseTicket(Ticket ticket)
{
if (ticket == null)
{
return;
}
if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket))
{
return;
}
if (ticket.requestedChunks!=null)
{
for (ChunkCoordIntPair chunk : ImmutableSet.copyOf(ticket.requestedChunks))
{
unforceChunk(ticket, chunk);
}
}
if (ticket.isPlayerTicket())
{
playerTickets.remove(ticket.player, ticket);
tickets.get(ticket.world).remove("Forge",ticket);
}
else
{
tickets.get(ticket.world).remove(ticket.modId, ticket);
}
}
/**
* Force the supplied chunk coordinate to be loaded by the supplied ticket. If the ticket's {@link Ticket#maxDepth} is exceeded, the least
* recently registered chunk is unforced and may be unloaded.
* It is safe to force the chunk several times for a ticket, it will not generate duplication or change the ordering.
*
* @param ticket The ticket registering the chunk
* @param chunk The chunk to force
*/
public static void forceChunk(Ticket ticket, ChunkCoordIntPair chunk)
{
if (ticket == null || chunk == null)
{
return;
}
if (ticket.ticketType == Type.ENTITY && ticket.entity == null)
{
throw new RuntimeException("Attempted to use an entity ticket to force a chunk, without an entity");
}
if (ticket.isPlayerTicket() ? !playerTickets.containsValue(ticket) : !tickets.get(ticket.world).containsEntry(ticket.modId, ticket))
{
FMLLog.severe("The mod %s attempted to force load a chunk with an invalid ticket. This is not permitted.", ticket.modId);
return;
}
ticket.requestedChunks.add(chunk);
MinecraftForge.EVENT_BUS.post(new ForceChunkEvent(ticket, chunk));
ImmutableSetMultimap<ChunkCoordIntPair, Ticket> newMap = ImmutableSetMultimap.<ChunkCoordIntPair,Ticket>builder().putAll(forcedChunks.get(ticket.world)).put(chunk, ticket).build();
forcedChunks.put(ticket.world, newMap);
if (ticket.maxDepth > 0 && ticket.requestedChunks.size() > ticket.maxDepth)
{
ChunkCoordIntPair removed = ticket.requestedChunks.iterator().next();
unforceChunk(ticket,removed);
}
}
/**
* Reorganize the internal chunk list so that the chunk supplied is at the *end* of the list
* This helps if you wish to guarantee a certain "automatic unload ordering" for the chunks
* in the ticket list
*
* @param ticket The ticket holding the chunk list
* @param chunk The chunk you wish to push to the end (so that it would be unloaded last)
*/
public static void reorderChunk(Ticket ticket, ChunkCoordIntPair chunk)
{
if (ticket == null || chunk == null || !ticket.requestedChunks.contains(chunk))
{
return;
}
ticket.requestedChunks.remove(chunk);
ticket.requestedChunks.add(chunk);
}
/**
* Unforce the supplied chunk, allowing it to be unloaded and stop ticking.
*
* @param ticket The ticket holding the chunk
* @param chunk The chunk to unforce
*/
public static void unforceChunk(Ticket ticket, ChunkCoordIntPair chunk)
{
if (ticket == null || chunk == null)
{
return;
}
ticket.requestedChunks.remove(chunk);
MinecraftForge.EVENT_BUS.post(new UnforceChunkEvent(ticket, chunk));
LinkedHashMultimap<ChunkCoordIntPair, Ticket> copy = LinkedHashMultimap.create(forcedChunks.get(ticket.world));
copy.remove(chunk, ticket);
ImmutableSetMultimap<ChunkCoordIntPair, Ticket> newMap = ImmutableSetMultimap.copyOf(copy);
forcedChunks.put(ticket.world,newMap);
}
static void loadConfiguration()
{
for (String mod : config.categories.keySet())
{
if (mod.equals("Forge") || mod.equals("defaults"))
{
continue;
}
Property modTC = config.get(mod, "maximumTicketCount", 200);
Property modCPT = config.get(mod, "maximumChunksPerTicket", 25);
ticketConstraints.put(mod, modTC.getInt(200));
chunkConstraints.put(mod, modCPT.getInt(25));
}
config.save();
}
/**
* The list of persistent chunks in the world. This set is immutable.
* @param world
* @return
*/
public static ImmutableSetMultimap<ChunkCoordIntPair, Ticket> getPersistentChunksFor(World world)
{
return forcedChunks.containsKey(world) ? forcedChunks.get(world) : ImmutableSetMultimap.<ChunkCoordIntPair,Ticket>of();
}
static void saveWorld(World world)
{
// only persist persistent worlds
if (!(world instanceof WorldServer)) { return; }
WorldServer worldServer = (WorldServer) world;
File chunkDir = worldServer.getChunkSaveLocation();
File chunkLoaderData = new File(chunkDir, "forcedchunks.dat");
NBTTagCompound forcedChunkData = new NBTTagCompound();
NBTTagList ticketList = new NBTTagList();
forcedChunkData.setTag("TicketList", ticketList);
Multimap<String, Ticket> ticketSet = tickets.get(worldServer);
for (String modId : ticketSet.keySet())
{
NBTTagCompound ticketHolder = new NBTTagCompound();
ticketList.appendTag(ticketHolder);
ticketHolder.setString("Owner", modId);
NBTTagList tickets = new NBTTagList();
ticketHolder.setTag("Tickets", tickets);
for (Ticket tick : ticketSet.get(modId))
{
NBTTagCompound ticket = new NBTTagCompound();
ticket.setByte("Type", (byte) tick.ticketType.ordinal());
ticket.setByte("ChunkListDepth", (byte) tick.maxDepth);
if (tick.isPlayerTicket())
{
ticket.setString("ModId", tick.modId);
ticket.setString("Player", tick.player);
}
if (tick.modData != null)
{
ticket.setCompoundTag("ModData", tick.modData);
}
if (tick.ticketType == Type.ENTITY && tick.entity != null && tick.entity.addEntityID(new NBTTagCompound()))
{
ticket.setInteger("chunkX", MathHelper.floor_double(tick.entity.chunkCoordX));
ticket.setInteger("chunkZ", MathHelper.floor_double(tick.entity.chunkCoordZ));
ticket.setLong("PersistentIDMSB", tick.entity.getPersistentID().getMostSignificantBits());
ticket.setLong("PersistentIDLSB", tick.entity.getPersistentID().getLeastSignificantBits());
tickets.appendTag(ticket);
}
else if (tick.ticketType != Type.ENTITY)
{
tickets.appendTag(ticket);
}
}
}
try
{
CompressedStreamTools.write(forcedChunkData, chunkLoaderData);
}
catch (IOException e)
{
FMLLog.log(Level.WARNING, e, "Unable to write forced chunk data to %s - chunkloading won't work", chunkLoaderData.getAbsolutePath());
return;
}
}
static void loadEntity(Entity entity)
{
UUID id = entity.getPersistentID();
Ticket tick = pendingEntities.get(id);
if (tick != null)
{
tick.bindEntity(entity);
pendingEntities.remove(id);
}
}
public static void putDormantChunk(long coords, Chunk chunk)
{
Cache<Long, Chunk> cache = dormantChunkCache.get(chunk.worldObj);
if (cache != null)
{
cache.put(coords, chunk);
}
}
public static Chunk fetchDormantChunk(long coords, World world)
{
Cache<Long, Chunk> cache = dormantChunkCache.get(world);
return cache == null ? null : cache.getIfPresent(coords);
}
static void captureConfig(File configDir)
{
cfgFile = new File(configDir,"forgeChunkLoading.cfg");
config = new Configuration(cfgFile, true);
try
{
config.load();
}
catch (Exception e)
{
File dest = new File(cfgFile.getParentFile(),"forgeChunkLoading.cfg.bak");
if (dest.exists())
{
dest.delete();
}
cfgFile.renameTo(dest);
FMLLog.log(Level.SEVERE, e, "A critical error occured reading the forgeChunkLoading.cfg file, defaults will be used - the invalid file is backed up at forgeChunkLoading.cfg.bak");
}
config.addCustomCategoryComment("defaults", "Default configuration for forge chunk loading control");
Property maxTicketCount = config.get("defaults", "maximumTicketCount", 200);
maxTicketCount.comment = "The default maximum ticket count for a mod which does not have an override\n" +
"in this file. This is the number of chunk loading requests a mod is allowed to make.";
defaultMaxCount = maxTicketCount.getInt(200);
Property maxChunks = config.get("defaults", "maximumChunksPerTicket", 25);
maxChunks.comment = "The default maximum number of chunks a mod can force, per ticket, \n" +
"for a mod without an override. This is the maximum number of chunks a single ticket can force.";
defaultMaxChunks = maxChunks.getInt(25);
Property playerTicketCount = config.get("defaults", "playerTicketCount", 500);
playerTicketCount.comment = "The number of tickets a player can be assigned instead of a mod. This is shared across all mods and it is up to the mods to use it.";
playerTicketLength = playerTicketCount.getInt(500);
Property dormantChunkCacheSizeProperty = config.get("defaults", "dormantChunkCacheSize", 0);
dormantChunkCacheSizeProperty.comment = "Unloaded chunks can first be kept in a dormant cache for quicker\n" +
"loading times. Specify the size of that cache here";
dormantChunkCacheSize = dormantChunkCacheSizeProperty.getInt(0);
FMLLog.info("Configured a dormant chunk cache size of %d", dormantChunkCacheSizeProperty.getInt(0));
Property modOverridesEnabled = config.get("defaults", "enabled", true);
modOverridesEnabled.comment = "Are mod overrides enabled?";
overridesEnabled = modOverridesEnabled.getBoolean(true);
config.addCustomCategoryComment("Forge", "Sample mod specific control section.\n" +
"Copy this section and rename the with the modid for the mod you wish to override.\n" +
"A value of zero in either entry effectively disables any chunkloading capabilities\n" +
"for that mod");
Property sampleTC = config.get("Forge", "maximumTicketCount", 200);
sampleTC.comment = "Maximum ticket count for the mod. Zero disables chunkloading capabilities.";
sampleTC = config.get("Forge", "maximumChunksPerTicket", 25);
sampleTC.comment = "Maximum chunks per ticket for the mod.";
for (String mod : config.categories.keySet())
{
if (mod.equals("Forge") || mod.equals("defaults"))
{
continue;
}
Property modTC = config.get(mod, "maximumTicketCount", 200);
Property modCPT = config.get(mod, "maximumChunksPerTicket", 25);
}
}
public static Map<String,Property> getConfigMapFor(Object mod)
{
ModContainer container = getContainer(mod);
if (container != null)
{
return config.getCategory(container.getModId()).getValues();
}
return null;
}
public static void addConfigProperty(Object mod, String propertyName, String value, Property.Type type)
{
ModContainer container = getContainer(mod);
if (container != null)
{
Map<String, Property> props = config.getCategory(container.getModId()).getValues();
props.put(propertyName, new Property(propertyName, value, type));
}
}
} |
package dr.math;
/**
* Binomial coefficients
*
* @version $Id: Binomial.java,v 1.11 2005/05/24 20:26:00 rambaut Exp $
*
* @author Andrew Rambaut
* @author Alexei Drummond
* @author Korbinian Strimmer
*/
public class Binomial
{
// Public stuff
/**
* @return Binomial coefficient n choose k
* @param n total elements
* @param k chosen elements
*/
public static double choose(double n, double k)
{
n = Math.floor(n + 0.5);
k = Math.floor(k + 0.5);
double lchoose = GammaFunction.lnGamma(n + 1.0) -
GammaFunction.lnGamma(k + 1.0) - GammaFunction.lnGamma(n - k + 1.0);
return Math.floor(Math.exp(lchoose) + 0.5);
}
/**
* @param n # elements
* @return n choose 2 (number of distinct ways to choose a pair from n elements)
*/
public static double choose2(int n)
{
// not sure how much overhead there is with try-catch blocks
// i.e. would an if statement be better?
try {
return choose2LUT[n];
} catch (ArrayIndexOutOfBoundsException e) {
while (maxN < n) {
maxN += 1000;
}
initialize();
return choose2LUT[n];
}
}
private static void initialize() {
choose2LUT = new double[maxN+1];
choose2LUT[0] = 0;
choose2LUT[1] = 0;
choose2LUT[2] = 1;
for (int i = 3; i <= maxN; i++) {
choose2LUT[i] = ((double) (i*(i-1))) * 0.5;
}
}
private static int maxN = 5000;
private static double[] choose2LUT;
static {
initialize();
}
} |
package org.grobid.core.data;
/**
* Class for managing patent bibliographical references.
*
* @author Patrice Lopez
*/
public class PatentItem implements Comparable<PatentItem> {
// attribute
private String authority = null;
private String number = null;
private String kindCode = null;
// patent type when applicable
private Boolean application = false;
private Boolean provisional = false;
private Boolean reissued = false;
private Boolean plant = false;
private Boolean design = false;
// scores
private double conf = 0.0;
private String confidence = null;
// position in document
private int offset_begin = 0;
private int offset_end = 0;
// position in raw string (in case of factorised numbers)
private int offset_raw = 0;
// context of occurrence of the reference
private String context = null;
public String getAuthority() {
return authority;
}
public String getNumber() {
return number;
}
public String getKindCode() {
return kindCode;
}
public Boolean getApplication() {
return application;
}
public Boolean getProvisional() {
return provisional;
}
public Boolean getReissued() {
return reissued;
}
public Boolean getPlant() {
return plant;
}
public Boolean getDesign() {
return design;
}
public double getConf() {
return conf;
}
public String getConfidence() {
return confidence;
}
public int getOffsetBegin() {
return offset_begin;
}
public int getOffsetEnd() {
return offset_end;
}
public int getOffsetRaw() {
return offset_raw;
}
/**
* Context of occurrence of the reference
*/
public String getContext() {
return context;
}
public void setContext(String cont) {
context = cont;
}
public void setOffsetBegin(int ofs) {
offset_begin = ofs;
}
public void setOffsetEnd(int ofs) {
offset_end = ofs;
}
public void setOffsetRaw(int ofs) {
offset_raw = ofs;
}
public void setKindCode(String kc) {
kindCode = kc;
}
public void setNumber(String num) {
number = num;
}
public void setAuthority(String s) {
authority = s;
}
public void setApplication(boolean b) {
application = b;
}
public void setProvisional(boolean b) {
provisional = b;
}
public void setReissued(boolean b) {
reissued = b;
}
public void setPlant(boolean b) {
plant = b;
}
public void setDesign(boolean b) {
design = b;
}
public int compareTo(PatentItem another) {
return number.compareTo(another.getNumber());
}
private final static String espacenet = "http://v3.espacenet.com/publicationDetails/biblio?DB=EPODOC";
private final static String espacenet2 = "http://v3.espacenet.com/searchResults?DB=EPODOC";
private final static String epoline = "https://register.epoline.org/espacenet/application?number=";
private final static String epoline2 = "https://register.epoline.org/espacenet/simpleSearch?index[0]=publication&value[0]=";
private final static String epoline3 = "&index[1]=&value[1]=&index[2]=&value[2]=&searchMode=simple&recent=";
public String getEspacenetURL() {
String res = null;
if (provisional) {
res = espacenet2 + "&PR=" + authority + number + "P";
} else if (application) {
res = espacenet2 + "&AP=" + authority + number;
} else {
res = espacenet + "&CC=" + authority + "&NR=" + number;
}
return res;
}
public String getEpolineURL() {
String res = null;
if (application) {
res = epoline + authority + number;
} else {
// we need the application number corresponding to the publication
res = epoline2 + authority + number + epoline3;
}
return res;
}
public String getType() {
if (application)
return "application";
if (provisional)
return "provisional";
if (reissued)
return "reissued";
if (plant)
return "plant";
if (design)
return "design";
// default
return "publication";
}
public void setType(String type) {
if (type.equals("publication"))
return;
if (type.equals("application")) {
application = true;
} else if (type.equals("provisional")) {
provisional = true;
} else if (type.equals("reissued")) {
reissued = true;
} else if (type.equals("plant")) {
plant = true;
} else if (type.equals("design")) {
design = true;
}
}
@Override
public String toString() {
return "PatentItem [authority=" + authority + ", number=" + number
+ ", kindCode=" + kindCode + ", application=" + application
+ ", provisional=" + provisional + ", reissued=" + reissued
+ ", plant=" + plant + ", design=" + design + ", conf=" + conf
+ ", confidence=" + confidence + ", offset_begin="
+ offset_begin + ", offset_end=" + offset_end + ", offset_raw="
+ offset_raw + ", context=" + context + "]";
}
} |
package edu.jhu.util.vector;
import java.util.Arrays;
import java.util.Iterator;
import edu.jhu.util.Sort;
import edu.jhu.util.Utilities;
import edu.jhu.util.collections.PDoubleArrayList;
import edu.jhu.util.collections.PLongArrayList;
public class SortedLongDoubleMap implements Iterable<LongDoubleEntry> {
protected long[] indices;
protected double[] values;
protected int used; // TODO: size
public SortedLongDoubleMap() {
this.used = 0;
this.indices= new long[0];
this.values = new double[0];
}
public SortedLongDoubleMap(long[] index, double[] data) {
if (!Sort.isSortedAscAndUnique(index)) {
throw new IllegalStateException("Indices are not sorted ascending");
}
this.used = index.length;
this.indices = index;
this.values = data;
}
public SortedLongDoubleMap(SortedLongDoubleMap other) {
this.used = other.used;
this.indices = Utilities.copyOf(other.indices);
this.values = Utilities.copyOf(other.values);
}
public void clear() {
this.used = 0;
}
// TODO: rename to containsKey.
public boolean contains(long idx) {
return Arrays.binarySearch(indices, 0, used, idx) >= 0;
}
public double get(long idx) {
int i = Arrays.binarySearch(indices, 0, used, idx);
if (i < 0) {
throw new IllegalArgumentException("This map does not contain the key: " + idx);
}
return values[i];
}
public double getWithDefault(long idx, double defaultVal) {
int i = Arrays.binarySearch(indices, 0, used, idx);
if (i < 0) {
return defaultVal;
}
return values[i];
}
public void remove(long idx) {
int i = Arrays.binarySearch(indices, 0, used, idx);
if (i < 0) {
throw new IllegalArgumentException("This map does not contain the key: " + idx);
}
// Shift the values over.
System.arraycopy(indices, i+1, indices, i, used - i - 1);
System.arraycopy(values, i+1, values, i, used - i - 1);
used
}
public void put(long idx, double val) {
int i = Arrays.binarySearch(indices, 0, used, idx);
if (i >= 0) {
// Just update the value.
values[i] = val;
return;
}
int insertionPoint = -(i + 1);
indices = insert(indices, insertionPoint, idx);
values = insert(values, insertionPoint, val);
used++;
}
private final long[] insert(long[] array, int i, long val) {
if (used >= array.length) {
// Increase the capacity of the array.
array = PLongArrayList.ensureCapacity(array, used+1);
}
if (i < used) {
// Shift the values over.
System.arraycopy(array, i, array, i+1, used - i);
}
// Insert the new index into the array.
array[i] = val;
return array;
}
private final double[] insert(double[] array, int i, double val) {
if (used >= array.length) {
// Increase the capacity of the array.
array = PDoubleArrayList.ensureCapacity(array, used+1);
}
if (i < used) {
// Shift the values over.
System.arraycopy(array, i, array, i+1, used - i);
}
// Insert the new index into the array.
array[i] = val;
return array;
}
public class LongDoubleEntryImpl implements LongDoubleEntry {
private int i;
public LongDoubleEntryImpl(int i) {
this.i = i;
}
public long index() {
return indices[i];
}
public double get() {
return values[i];
}
}
/**
* This iterator is fast in the case of for(Entry e : vector) { }, however a
* given entry should not be used after the following call to next().
*/
public class LongDoubleIterator implements Iterator<LongDoubleEntry> {
// The current entry.
private LongDoubleEntryImpl entry = new LongDoubleEntryImpl(-1);
@Override
public boolean hasNext() {
return entry.i+1 < used;
}
@Override
public LongDoubleEntry next() {
entry.i++;
return entry;
}
@Override
public void remove() {
throw new RuntimeException("operation not supported");
}
}
@Override
public Iterator<LongDoubleEntry> iterator() {
return new LongDoubleIterator();
}
public int size() {
return used;
}
public int getUsed() {
return used;
}
/**
* Returns the indices.
*/
public long[] getIndices() {
if (used == indices.length)
return indices;
long[] tmpIndices = new long[used];
for (int i = 0; i < used; i++) {
tmpIndices[i] = indices[i];
}
return tmpIndices;
}
/**
* Returns the values.
*/
public double[] getValues() {
if (used == values.length)
return values;
double[] tmpValues = new double[used];
for (int i = 0; i < used; i++) {
tmpValues[i] = values[i];
}
return tmpValues;
}
} |
package org.grobid.trainer;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
public class StatsTest {
Stats target;
@Before
public void setUp() throws Exception {
target = new Stats();
}
@Test
public void testPrecision_fullMatch() throws Exception {
target.getLabelStat("BAO").setExpected(4);
target.getLabelStat("BAO").setObserved(4);
assertThat(target.getLabelStat("BAO").getPrecision(), is(1.0));
}
@Test
public void testPrecision_noMatch() throws Exception {
target.getLabelStat("MIAO").setExpected(4);
target.getLabelStat("MIAO").setObserved(0);
target.getLabelStat("MIAO").setFalsePositive(3);
target.getLabelStat("MIAO").setFalseNegative(1);
assertThat(target.getLabelStat("MIAO").getPrecision(), is(0.0));
}
@Test
public void testPrecision_missingMatch() throws Exception {
// The precision stays at 1.0 because none of the observed
// is wrong (no false positives)
target.getLabelStat("CIAO").setExpected(4);
target.getLabelStat("CIAO").setObserved(1);
target.getLabelStat("CIAO").setFalseNegative(3);
assertThat(target.getLabelStat("CIAO").getPrecision(), is(1.0));
}
@Test
public void testPrecision_2wronglyRecognised() throws Exception {
target.getLabelStat("ZIAO").setExpected(4);
target.getLabelStat("ZIAO").setObserved(1);
target.getLabelStat("ZIAO").setFalsePositive(2);
assertThat(target.getLabelStat("ZIAO").getPrecision(), is(0.3333333333333333));
}
@Test
public void testRecall_fullMatch() throws Exception {
target.getLabelStat("BAO").setExpected(4);
target.getLabelStat("BAO").setObserved(4);
assertThat(target.getLabelStat("BAO").getRecall(), is(1.0));
}
@Test
public void testRecall_noMatch() throws Exception {
target.getLabelStat("MIAO").setExpected(4);
target.getLabelStat("MIAO").setObserved(0);
target.getLabelStat("MIAO").setFalsePositive(3);
target.getLabelStat("MIAO").setFalseNegative(1);
assertThat(target.getLabelStat("MIAO").getRecall(), is(0.0));
}
@Test
public void testRecall_oneOverFour() throws Exception {
target.getLabelStat("CIAO").setExpected(4);
target.getLabelStat("CIAO").setObserved(1);
target.getLabelStat("CIAO").setFalseNegative(3);
assertThat(target.getLabelStat("CIAO").getRecall(), is(0.25));
}
@Test
public void testRecall_partialMatch() throws Exception {
target.getLabelStat("ZIAO").setExpected(4);
target.getLabelStat("ZIAO").setObserved(3);
target.getLabelStat("ZIAO").setFalsePositive(1);
assertThat(target.getLabelStat("ZIAO").getPrecision(), is(0.75));
}
// Average measures
@Test
public void testMicroAvgPrecision_shouldWork() throws Exception {
target.getLabelStat("BAO").setExpected(4);
target.getLabelStat("BAO").setObserved(4);
target.getLabelStat("MIAO").setExpected(4);
target.getLabelStat("MIAO").setObserved(0);
target.getLabelStat("MIAO").setFalsePositive(3);
target.getLabelStat("MIAO").setFalseNegative(1);
target.getLabelStat("CIAO").setExpected(4);
target.getLabelStat("CIAO").setObserved(1);
target.getLabelStat("CIAO").setFalseNegative(3);
target.getLabelStat("ZIAO").setExpected(4);
target.getLabelStat("ZIAO").setObserved(0);
target.getLabelStat("ZIAO").setFalsePositive(2);
assertThat(target.getMicroAveragePrecision(), is(((double) 4 + 0 + 1 + 0) / (4 + 0 + 3 + 1 + 0 + 2)));
}
@Test
public void testMacroAvgPrecision_shouldWork() throws Exception {
target.getLabelStat("BAO").setExpected(4);
target.getLabelStat("BAO").setObserved(4);
target.getLabelStat("MIAO").setExpected(4);
target.getLabelStat("MIAO").setObserved(0);
target.getLabelStat("MIAO").setFalsePositive(3);
target.getLabelStat("MIAO").setFalseNegative(1);
target.getLabelStat("CIAO").setExpected(4);
target.getLabelStat("CIAO").setObserved(1);
target.getLabelStat("CIAO").setFalseNegative(3);
target.getLabelStat("ZIAO").setExpected(4);
target.getLabelStat("ZIAO").setObserved(0);
target.getLabelStat("ZIAO").setFalsePositive(2);
final double precisionBao = target.getLabelStat("BAO").getPrecision();
final double precisionMiao = target.getLabelStat("MIAO").getPrecision();
final double precisionCiao = target.getLabelStat("CIAO").getPrecision();
final double precisionZiao = target.getLabelStat("ZIAO").getPrecision();
assertThat(target.getMacroAveragePrecision(),
is((precisionBao + precisionMiao + precisionCiao + precisionZiao) / (4)));
}
@Test
public void testMicroAvgRecall_shouldWork() throws Exception {
target.getLabelStat("BAO").setExpected(4);
target.getLabelStat("BAO").setObserved(4);
target.getLabelStat("MIAO").setExpected(4);
target.getLabelStat("MIAO").setObserved(0);
target.getLabelStat("MIAO").setFalsePositive(3);
target.getLabelStat("MIAO").setFalseNegative(1);
target.getLabelStat("CIAO").setExpected(4);
target.getLabelStat("CIAO").setObserved(1);
target.getLabelStat("CIAO").setFalseNegative(3);
target.getLabelStat("ZIAO").setExpected(4);
target.getLabelStat("ZIAO").setObserved(0);
target.getLabelStat("ZIAO").setFalsePositive(2);
assertThat(target.getMicroAverageRecall(), is(((double) 4 + 0 + 1 + 0) / (4 + 4 + 4 + 4)));
}
@Test
public void testMacroAvgRecall_shouldWork() throws Exception {
target.getLabelStat("BAO").setExpected(4);
target.getLabelStat("BAO").setObserved(4);
target.getLabelStat("MIAO").setExpected(4);
target.getLabelStat("MIAO").setObserved(0);
target.getLabelStat("MIAO").setFalsePositive(3);
target.getLabelStat("MIAO").setFalseNegative(1);
target.getLabelStat("CIAO").setExpected(4);
target.getLabelStat("CIAO").setObserved(1);
target.getLabelStat("CIAO").setFalseNegative(3);
target.getLabelStat("ZIAO").setExpected(4);
target.getLabelStat("ZIAO").setObserved(0);
target.getLabelStat("ZIAO").setFalsePositive(2);
final double recallBao = target.getLabelStat("BAO").getRecall();
final double recallMiao = target.getLabelStat("MIAO").getRecall();
final double recallCiao = target.getLabelStat("CIAO").getRecall();
final double recallZiao = target.getLabelStat("ZIAO").getRecall();
assertThat(target.getMacroAverageRecall(),
is((recallBao + recallMiao + recallCiao + recallZiao) / (4)));
}
@Test
public void testMicroAvgF0_shouldWork() throws Exception {
target.getLabelStat("BAO").setExpected(4);
target.getLabelStat("BAO").setObserved(4);
target.getLabelStat("MIAO").setExpected(4);
target.getLabelStat("MIAO").setObserved(0);
target.getLabelStat("MIAO").setFalsePositive(3);
target.getLabelStat("MIAO").setFalseNegative(1);
target.getLabelStat("CIAO").setExpected(4);
target.getLabelStat("CIAO").setObserved(1);
target.getLabelStat("CIAO").setFalseNegative(3);
target.getLabelStat("ZIAO").setExpected(4);
target.getLabelStat("ZIAO").setObserved(0);
target.getLabelStat("ZIAO").setFalsePositive(2);
assertThat(target.getMicroAverageF1(),
is(((double) 2 * target.getMicroAveragePrecision()
* target.getMicroAverageRecall())
/ (target.getMicroAveragePrecision() + target.getMicroAverageRecall())));
}
@Test
public void testMacroAvgF0_shouldWork() throws Exception {
target.getLabelStat("BAO").setExpected(4);
target.getLabelStat("BAO").setObserved(4);
target.getLabelStat("MIAO").setExpected(4);
target.getLabelStat("MIAO").setObserved(0);
target.getLabelStat("MIAO").setFalsePositive(3);
target.getLabelStat("MIAO").setFalseNegative(1);
target.getLabelStat("CIAO").setExpected(4);
target.getLabelStat("CIAO").setObserved(1);
target.getLabelStat("CIAO").setFalseNegative(3);
target.getLabelStat("ZIAO").setExpected(4);
target.getLabelStat("ZIAO").setObserved(0);
target.getLabelStat("ZIAO").setFalsePositive(2);
final double f1Bao = target.getLabelStat("BAO").getRecall();
final double f1Miao = target.getLabelStat("MIAO").getRecall();
final double f1Ciao = target.getLabelStat("CIAO").getRecall();
final double f1Ziao = target.getLabelStat("ZIAO").getRecall();
assertThat(target.getMacroAverageF1(),
is((f1Bao + f1Miao + f1Ciao + f1Ziao) / (4)));
}
@Ignore("Not really useful")
@Test
public void testMicroMacroAveragePrecision() throws Exception {
final LabelStat conceptual = target.getLabelStat("CONCEPTUAL");
conceptual.setFalsePositive(1);
conceptual.setFalseNegative(1);
conceptual.setObserved(2);
conceptual.setExpected(3);
final LabelStat location = target.getLabelStat("LOCATION");
location.setFalsePositive(0);
location.setFalseNegative(0);
location.setObserved(2);
location.setExpected(2);
final LabelStat media = target.getLabelStat("MEDIA");
media.setFalsePositive(0);
media.setFalseNegative(0);
media.setObserved(7);
media.setExpected(7);
final LabelStat national = target.getLabelStat("NATIONAL");
national.setFalsePositive(1);
national.setFalseNegative(0);
national.setObserved(0);
national.setExpected(0);
final LabelStat other = target.getLabelStat("O");
other.setFalsePositive(0);
other.setFalseNegative(1);
other.setObserved(33);
other.setExpected(34);
final LabelStat organisation = target.getLabelStat("ORGANISATION");
organisation.setFalsePositive(0);
organisation.setFalseNegative(0);
organisation.setObserved(2);
organisation.setExpected(2);
final LabelStat period = target.getLabelStat("PERIOD");
period.setFalsePositive(0);
period.setFalseNegative(0);
period.setObserved(8);
period.setExpected(8);
final LabelStat person = target.getLabelStat("PERSON");
person.setFalsePositive(1);
person.setFalseNegative(0);
person.setObserved(0);
person.setExpected(0);
final LabelStat personType = target.getLabelStat("PERSON_TYPE");
personType.setFalsePositive(0);
personType.setFalseNegative(1);
personType.setObserved(0);
personType.setExpected(1);
for (String label : target.getLabels()) {
System.out.println(label + " precision --> " + target.getLabelStat(label).getPrecision());
System.out.println(label + " recall --> " + target.getLabelStat(label).getRecall());
}
System.out.println(target.getMacroAveragePrecision());
System.out.println(target.getMicroAveragePrecision());
}
@Test
public void testMicroMacroAverageMeasures_realTest() throws Exception {
LabelStat otherLabelStats = target.getLabelStat("O");
otherLabelStats.setExpected(33);
otherLabelStats.setObserved(33);
otherLabelStats.setFalseNegative(1);
assertThat(otherLabelStats.getPrecision(), is(1.0));
assertThat(otherLabelStats.getRecall(), is(1.0));
LabelStat conceptualLabelStats = target.getLabelStat("CONCEPTUAL");
conceptualLabelStats.setObserved(2);
conceptualLabelStats.setExpected(3);
conceptualLabelStats.setFalseNegative(1);
conceptualLabelStats.setFalsePositive(1);
assertThat(conceptualLabelStats.getPrecision(), is(0.6666666666666666));
assertThat(conceptualLabelStats.getRecall(), is(0.6666666666666666));
LabelStat periodLabelStats = target.getLabelStat("PERIOD");
periodLabelStats.setObserved(8);
periodLabelStats.setExpected(8);
assertThat(periodLabelStats.getPrecision(), is(1.0));
assertThat(periodLabelStats.getRecall(), is(1.0));
LabelStat mediaLabelStats = target.getLabelStat("MEDIA");
mediaLabelStats.setObserved(7);
mediaLabelStats.setExpected(7);
assertThat(mediaLabelStats.getPrecision(), is(1.0));
assertThat(mediaLabelStats.getRecall(), is(1.0));
LabelStat personTypeLabelStats = target.getLabelStat("PERSON_TYPE");
personTypeLabelStats.setObserved(0);
personTypeLabelStats.setExpected(1);
personTypeLabelStats.setFalseNegative(1);
assertThat(personTypeLabelStats.getPrecision(), is(0.0));
assertThat(personTypeLabelStats.getRecall(), is(0.0));
LabelStat locationTypeLabelStats = target.getLabelStat("LOCATION");
locationTypeLabelStats.setObserved(2);
locationTypeLabelStats.setExpected(2);
assertThat(locationTypeLabelStats.getPrecision(), is(1.0));
assertThat(locationTypeLabelStats.getRecall(), is(1.0));
LabelStat organisationTypeLabelStats = target.getLabelStat("ORGANISATION");
organisationTypeLabelStats.setObserved(2);
organisationTypeLabelStats.setExpected(2);
assertThat(locationTypeLabelStats.getPrecision(), is(1.0));
assertThat(locationTypeLabelStats.getRecall(), is(1.0));
LabelStat personLabelStats = target.getLabelStat("PERSON");
personLabelStats.setFalsePositive(1);
assertThat(personLabelStats.getPrecision(), is(0.0));
assertThat(personLabelStats.getRecall(), is(0.0));
// 2+8+2+2+7 / (2+8+2+2+7+1)
assertThat(target.getMicroAverageRecall(), is(0.9130434782608695)); //91.3
// 2+8+2+2+7 / (3+8+7+2+2+1)
assertThat(target.getMicroAveragePrecision(), is(0.9545454545454546)); //95.45
// 0.66 + 1.0 + 1.0 + 0.0 + 1.0 + 1.0 / 6
assertThat(target.getMacroAverageRecall(), is(0.7777777777777777)); //77.78
// same as above
assertThat(target.getMacroAveragePrecision(), is(0.7777777777777777)); //77.78
}
} |
package foam.lib.formatter;
import foam.core.ClassInfo;
import foam.core.FEnum;
import foam.core.FObject;
import foam.core.PropertyInfo;
import foam.core.X;
import foam.lib.json.OutputJSON;
import foam.util.SafetyUtil;
import java.lang.reflect.Array;
import java.text.SimpleDateFormat;
import java.util.*;
/* To Make faster:
1. faster escaping
2. don't escape class names and property names
3. don't quote property keys
4. use short names
5. smaller format for enums and dates
6. have PropertyInfo output directly from primitive
7. support outputting directly to another Visitor,
StringBuilder, OutputStream, etc. without converting
to String.
8. Use Fast TimeStamper or similar
*/
public class JSONFObjectFormatter
extends AbstractFObjectFormatter
{
// TODO: use fast timestamper?
protected static ThreadLocal<SimpleDateFormat> sdf = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
df.setTimeZone(java.util.TimeZone.getTimeZone("UTC"));
return df;
}
};
protected boolean quoteKeys_ = false;
protected boolean outputShortNames_ = false;
protected boolean outputDefaultValues_ = false;
protected boolean multiLineOutput_ = false;
protected boolean outputClassNames_ = true;
protected boolean outputReadableDates_ = false;
protected boolean outputDefaultClassNames_ = true;
public JSONFObjectFormatter(X x) {
super(x);
}
public JSONFObjectFormatter() {
super();
}
protected void outputUndefined() {
}
protected void outputNull() {
}
public void output(String s) {
if ( multiLineOutput_ && s.indexOf('\n') >= 0 ) {
append("\n\"\"\"");
escapeAppend(s);
append("\"\"\"");
} else {
append('"');
escapeAppend(s);
append('"');
}
}
public void escapeAppend(String s) {
StringBuilder sb = new StringBuilder();
foam.lib.json.Util.escape(s, sb);
append(sb.toString());
}
public void output(short val) { append(val); }
public void output(int val) { append(val); }
public void output(long val) { append(val); }
public void output(float val) { append(val); }
public void output(double val) { append(val); }
public void output(boolean val) { append(val); }
protected void outputNumber(Number value) {
append(value);
}
protected void outputBoolean(Boolean value) {
output(value.booleanValue());
}
public void output(String[] arr) {
output((Object[]) arr);
}
public void output(Object[] array) {
append('[');
for ( int i = 0 ; i < array.length ; i++ ) {
output(array[i]);
if ( i < array.length - 1 ) append(',');
}
append(']');
}
public void output(byte[][] array) {
append('[');
for ( int i = 0 ; i < array.length ; i++ ) {
output(array[i]);
if ( i < array.length - 1 ) append(',');
}
append(']');
}
public void output(byte[] array) {
output(foam.util.SecurityUtil.ByteArrayToHexString(array));
}
public void output(Map map) {
append('{');
java.util.Iterator keys = map.keySet().iterator();
while ( keys.hasNext() ) {
Object key = keys.next();
Object value = map.get(key);
output(key == null ? "" : key.toString());
append(':');
output(value);
if ( keys.hasNext() ) append(',');
}
append('}');
}
public void output(List list) {
append('[');
java.util.Iterator iter = list.iterator();
while ( iter.hasNext() ) {
output(iter.next());
if ( iter.hasNext() ) append(',');
}
append(']');
}
protected void outputProperty(FObject o, PropertyInfo p) {
outputKey(getPropertyName(p));
append(':');
p.format(this, o);
}
/*
public void outputMap(Object... values) {
if ( values.length % 2 != 0 ) {
throw new RuntimeException("Need even number of arguments for outputMap");
}
append("{");
int i = 0;
while ( i < values.length ) {
append(beforeKey_());
append(values[i++].toString());
append(afterKey_());
append(":");
output(values[i++]);
if ( i < values.length ) append(",");
}
append("}");
}
*/
public void outputEnumValue(FEnum value) {
append('{');
outputKey("class");
append(':');
output(value.getClass().getName());
append(',');
outputKey("ordinal");
append(':');
outputNumber(value.getOrdinal());
append('}');
}
public void outputEnum(FEnum value) {
output(value.getOrdinal());
}
public void output(Object value) {
if ( value == null ) {
append("null");
} else if ( value instanceof OutputJSON ) {
((OutputJSON) value).formatJSON(this);
} else if ( value instanceof String ) {
output((String) value);
} else if ( value instanceof FEnum ) {
outputEnumValue((FEnum) value);
} else if ( value instanceof FObject ) {
output((FObject) value);
} else if ( value instanceof PropertyInfo) {
output((PropertyInfo) value);
} else if ( value instanceof ClassInfo ) {
output((ClassInfo) value);
} else if ( value instanceof Number ) {
outputNumber((Number) value);
} else if ( isArray(value) ) {
if ( value.getClass().equals(byte[][].class) ) {
output((byte[][]) value);
} else if ( value instanceof byte[] ) {
output((byte[]) value);
} else {
output((Object[]) value);
}
} else if ( value instanceof Boolean ) {
outputBoolean((Boolean) value);
} else if ( value instanceof Date ) {
outputDateValue((Date) value);
} else if ( value instanceof Map ) {
output((Map) value);
} else if ( value instanceof List ) {
output((List) value);
} else /*if ( value == null )*/ {
System.err.println(this.getClass().getSimpleName()+".output, Unexpected value type: "+value.getClass().getName());
append("null");
}
}
protected boolean isArray(Object value) {
return value != null &&
( value.getClass() != null ) &&
value.getClass().isArray();
}
/** Called when outputting a Date from an Object field so that the type is know. **/
public void outputDateValue(Date date) {
append("{\"class\":\"__Timestamp__\",\"value\":");
if ( outputReadableDates_ ) {
output(sdf.get().format(date));
} else {
outputNumber(date.getTime());
}
append('}');
}
public void output(Date date) {
if ( date != null ) {
output(date.getTime());
} else {
append("null");
}
}
protected Boolean maybeOutputProperty(FObject fo, PropertyInfo prop, boolean includeComma) {
if ( ! outputDefaultValues_ && ! prop.isSet(fo) ) return false;
Object value = prop.get(fo);
if ( value == null || ( isArray(value) && Array.getLength(value) == 0 ) ) {
return false;
}
if ( includeComma ) append(',');
if ( multiLineOutput_ ) addInnerNewline();
outputProperty(fo, prop);
return true;
}
public List getDelta(FObject oldFObject, FObject newFObject) {
return delta_ == null ? super.getDelta(oldFObject, newFObject) : delta_;
}
public void outputDelta(FObject oldFObject, FObject newFObject) {
outputDelta(oldFObject, newFObject, null);
}
public void outputDelta(FObject oldFObject, FObject newFObject, ClassInfo defaultClass) {
ClassInfo info = newFObject.getClassInfo();
boolean outputClass = outputClassNames_ && ( info != defaultClass || outputDefaultClassNames_ );
ClassInfo newInfo = newFObject.getClassInfo();
boolean outputComma = true;
List delta = getDelta(oldFObject, newFObject);
int size = delta.size();
if ( size == 0 ) {
return;
}
append('{');
addInnerNewline();
if ( outputClass ) {
//output Class name
outputKey("class");
append(':');
output(newInfo.getId());
append(',');
}
addInnerNewline();
PropertyInfo id = (PropertyInfo) newInfo.getAxiomByName("id");
outputProperty(newFObject, id);
for ( int i = 0 ; i < size ; i++ ) {
append(',');
addInnerNewline();
PropertyInfo prop = (PropertyInfo) delta.get(i);
outputProperty(newFObject, prop);
}
addInnerNewline();
append('}');
}
protected void addInnerNewline() {
if ( multiLineOutput_ ) {
append('\n');
}
}
/*
public void outputJSONJFObject(FObject o) {
append("p(");
outputFObject(o);
append(")\r\n");
}
*/
public void output(FObject[] arr, ClassInfo defaultClass) {
output(arr);
}
public void output(FObject[] arr) {
append('[');
for ( int i = 0 ; i < arr.length ; i++ ) {
output(arr[i]);
if ( i < arr.length - 1 ) append(',');
}
append(']');
}
public void output(FObject o, ClassInfo defaultClass) {
ClassInfo info = o.getClassInfo();
boolean outputClass = outputClassNames_ && ( info != defaultClass || outputDefaultClassNames_ );
append('{');
addInnerNewline();
if ( outputClass ) {
outputKey("class");
append(':');
output(info.getId());
}
boolean outputComma = outputClass;
List axioms = getProperties(info);
int size = axioms.size();
for ( int i = 0 ; i < size ; i++ ) {
PropertyInfo prop = (PropertyInfo) axioms.get(i);
outputComma = maybeOutputProperty(o, prop, outputComma) || outputComma;
}
addInnerNewline();
append('}');
}
public void output(FObject o) {
output(o, null);
}
public void output(PropertyInfo prop) {
append('{');
outputKey("class");
append(':');
output("__Property__");
append(',');
outputKey("forClass_");
append(':');
output(prop.getClassInfo().getId());
append(',');
outputKey("name");
append(':');
output(getPropertyName(prop));
// if ( quoteKeys_ ) {
// output(getPropertyName(prop));
// } else {
// outputRawString(getPropertyName(prop));
append('}');
}
public void outputJson(String str) {
if ( ! quoteKeys_ )
str = str.replaceAll("\"class\"", "class");
outputFormattedString(str);
}
public void output(ClassInfo info) {
outputKey(info.getId());
// append('{');
// if ( quoteKeys_ ) append(beforeKey_());
// append("class");
// if ( quoteKeys_ ) append(afterKey_());
// append(":");
// append("\"__Class__\"");
// append(":");
// append("{\"class\":\"__Class__\",\"forClass_\":");
// output(info.getId());
// append('}');
}
protected void appendQuote() {
append('"');
}
public String getPropertyName(PropertyInfo p) {
return outputShortNames_ && ! SafetyUtil.isEmpty(p.getShortName()) ? p.getShortName() : p.getName();
}
public void outputFormattedString(String str) {
append(str);
}
public JSONFObjectFormatter setQuoteKeys(boolean quoteKeys) {
quoteKeys_ = quoteKeys;
return this;
}
public JSONFObjectFormatter setOutputShortNames(boolean outputShortNames) {
// outputShortNames_ = outputShortNames;
return this;
}
public JSONFObjectFormatter setOutputDefaultValues(boolean outputDefaultValues) {
outputDefaultValues_ = outputDefaultValues;
return this;
}
public JSONFObjectFormatter setOutputDefaultClassNames(boolean f) {
outputDefaultClassNames_ = f;
return this;
}
public JSONFObjectFormatter setOutputReadableDates(boolean f) {
outputReadableDates_ = f;
return this;
}
public JSONFObjectFormatter setMultiLine(boolean ml) {
multiLineOutput_ = ml;
return this;
}
public JSONFObjectFormatter setOutputClassNames(boolean outputClassNames) {
outputClassNames_ = outputClassNames;
return this;
}
public void outputKey(String val) {
if ( quoteKeys_ ) appendQuote();
append(val);
if ( quoteKeys_ ) appendQuote();
}
} |
package net.time4j.i18n;
import net.time4j.format.PluralCategory;
import net.time4j.format.RelativeTimeProvider;
import net.time4j.format.TextWidth;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
public final class UnitPatternProviderSPI
implements RelativeTimeProvider {
@Override
public String getYearPattern(
Locale language,
TextWidth width,
PluralCategory category
) {
return this.getUnitPattern(language, 'Y', width, category);
}
@Override
public String getMonthPattern(
Locale language,
TextWidth width,
PluralCategory category
) {
return this.getUnitPattern(language, 'M', width, category);
}
@Override
public String getWeekPattern(
Locale language,
TextWidth width,
PluralCategory category
) {
return this.getUnitPattern(language, 'W', width, category);
}
@Override
public String getDayPattern(
Locale language,
TextWidth width,
PluralCategory category
) {
return this.getUnitPattern(language, 'D', width, category);
}
@Override
public String getHourPattern(
Locale language,
TextWidth width,
PluralCategory category
) {
return this.getUnitPattern(language, 'H', width, category);
}
@Override
public String getMinutePattern(
Locale language,
TextWidth width,
PluralCategory category
) {
return this.getUnitPattern(language, 'N', width, category);
}
@Override
public String getSecondPattern(
Locale language,
TextWidth width,
PluralCategory category
) {
return this.getUnitPattern(language, 'S', width, category);
}
@Override
public String getMilliPattern(
Locale lang,
TextWidth width,
PluralCategory category
) {
return this.getUnitPattern(lang, '3', width, category);
}
@Override
public String getMicroPattern(
Locale lang,
TextWidth width,
PluralCategory category
) {
return this.getUnitPattern(lang, '6', width, category);
}
@Override
public String getNanoPattern(
Locale lang,
TextWidth width,
PluralCategory category
) {
return this.getUnitPattern(lang, '9', width, category);
}
@Override
public String getYearPattern(
Locale language,
boolean future,
PluralCategory category
) {
return this.getRelativePattern(language, 'Y', future, category);
}
@Override
public String getMonthPattern(
Locale language,
boolean future,
PluralCategory category
) {
return this.getRelativePattern(language, 'M', future, category);
}
@Override
public String getWeekPattern(
Locale language,
boolean future,
PluralCategory category
) {
return this.getRelativePattern(language, 'W', future, category);
}
@Override
public String getDayPattern(
Locale language,
boolean future,
PluralCategory category
) {
return this.getRelativePattern(language, 'D', future, category);
}
@Override
public String getHourPattern(
Locale language,
boolean future,
PluralCategory category
) {
return this.getRelativePattern(language, 'H', future, category);
}
@Override
public String getMinutePattern(
Locale language,
boolean future,
PluralCategory category
) {
return this.getRelativePattern(language, 'N', future, category);
}
@Override
public String getSecondPattern(
Locale language,
boolean future,
PluralCategory category
) {
return this.getRelativePattern(language, 'S', future, category);
}
@Override
public String getNowWord(Locale lang) {
return this.getPattern(
lang,
"reltime/relpattern",
"now",
null,
PluralCategory.OTHER);
}
@Override
public String getShortYearPattern(
Locale language,
boolean future,
PluralCategory category
) {
return this.getRelativePattern(language, 'y', future, category);
}
@Override
public String getShortMonthPattern(
Locale language,
boolean future,
PluralCategory category
) {
return this.getRelativePattern(language, 'm', future, category);
}
@Override
public String getShortWeekPattern(
Locale language,
boolean future,
PluralCategory category
) {
return this.getRelativePattern(language, 'w', future, category);
}
@Override
public String getShortDayPattern(
Locale language,
boolean future,
PluralCategory category
) {
return this.getRelativePattern(language, 'd', future, category);
}
@Override
public String getShortHourPattern(
Locale language,
boolean future,
PluralCategory category
) {
return this.getRelativePattern(language, 'h', future, category);
}
@Override
public String getShortMinutePattern(
Locale language,
boolean future,
PluralCategory category
) {
return this.getRelativePattern(language, 'n', future, category);
}
@Override
public String getShortSecondPattern(
Locale language,
boolean future,
PluralCategory category
) {
return this.getRelativePattern(language, 's', future, category);
}
@Override
public String getYesterdayWord(Locale lang) {
return this.getPattern(
lang,
"reltime/relpattern",
"yesterday",
null,
PluralCategory.OTHER);
}
@Override
public String getTodayWord(Locale lang) {
return this.getPattern(
lang,
"reltime/relpattern",
"today",
null,
PluralCategory.OTHER);
}
@Override
public String getTomorrowWord(Locale lang) {
return this.getPattern(
lang,
"reltime/relpattern",
"tomorrow",
null,
PluralCategory.OTHER);
}
@Override
public String getListPattern(
Locale desired,
TextWidth width,
int size
) {
if (size < 2) {
throw new IllegalArgumentException("Size must be greater than 1.");
}
ClassLoader loader = this.getClass().getClassLoader();
ResourceBundle.Control control = UTF8ResourceControl.SINGLETON;
ResourceBundle rb =
ResourceBundle.getBundle("units/upattern", desired, loader, control);
String exact = buildListKey(width, String.valueOf(size));
if (rb.containsKey(exact)) {
return rb.getString(exact);
}
String end = rb.getString(buildListKey(width, "end"));
if (size == 2) {
return end;
}
String start = rb.getString(buildListKey(width, "start"));
String middle = rb.getString(buildListKey(width, "middle"));
end = replace(end, '1', size - 1);
end = replace(end, '0', size - 2);
String previous = end;
String result = previous;
for (int i = size - 3; i >= 0; i
String pattern = ((i == 0) ? start : middle);
int pos = -1;
int n = pattern.length();
for (int j = n - 1; j >= 0; j
if (
(j >= 2)
&& (pattern.charAt(j) == '}')
&& (pattern.charAt(j - 1) == '1')
&& (pattern.charAt(j - 2) == '{')
) {
pos = j - 2;
break;
}
}
if (pos > -1) {
result = pattern.substring(0, pos) + previous;
if (pos < n - 3) {
result += pattern.substring(pos + 3);
}
}
if (i > 0) {
previous = replace(result, '0', i);
}
}
return result;
}
private String getUnitPattern(
Locale lang,
char unitID,
TextWidth width,
PluralCategory category
) {
return this.getPattern(
lang,
"units/upattern",
buildKey(unitID, width, category),
buildKey(unitID, width, PluralCategory.OTHER),
category
);
}
private String getRelativePattern(
Locale lang,
char unitID,
boolean future,
PluralCategory category
) {
return this.getPattern(
lang,
"reltime/relpattern",
buildKey(unitID, future, category),
buildKey(unitID, future, PluralCategory.OTHER),
category
);
}
private String getPattern(
Locale desired,
String baseName,
String key,
String alt,
PluralCategory category
) {
ClassLoader loader = this.getClass().getClassLoader();
ResourceBundle.Control control = UTF8ResourceControl.SINGLETON;
boolean init = true;
ResourceBundle first = null;
for (Locale locale : control.getCandidateLocales(baseName, desired)) {
ResourceBundle rb = (
init && (first != null)
? first
: ResourceBundle.getBundle(baseName, locale, loader, control));
if (init) {
if (locale.equals(rb.getLocale())) {
init = false;
} else {
first = rb;
continue;
}
}
UTF8ResourceBundle bundle = UTF8ResourceBundle.class.cast(rb);
if (bundle.getInternalKeys().contains(key)) {
return bundle.getString(key);
} else if (
(category != PluralCategory.OTHER)
&& bundle.getInternalKeys().contains(alt)
) {
return bundle.getString(alt);
}
}
throw new MissingResourceException(
"Can't find resource for bundle "
+ baseName + ".properties, key " + key,
baseName + ".properties",
key
);
}
private static String buildKey(
char unitID,
TextWidth width,
PluralCategory category
) {
StringBuilder sb = new StringBuilder(3);
sb.append(unitID);
switch (width) {
case WIDE:
sb.append('w');
break;
case ABBREVIATED:
case SHORT:
sb.append('s');
break;
case NARROW:
sb.append('n');
break;
default:
throw new UnsupportedOperationException(width.name());
}
return sb.append(category.ordinal()).toString();
}
private static String buildKey(
char unitID,
boolean future,
PluralCategory category
) {
StringBuilder sb = new StringBuilder(3);
sb.append(unitID);
sb.append(future ? '+' : '-');
return sb.append(category.ordinal()).toString();
}
private static String buildListKey(
TextWidth width,
String suffix
) {
StringBuilder sb = new StringBuilder();
sb.append('L');
switch (width) {
case WIDE:
sb.append('w');
break;
case ABBREVIATED:
case SHORT:
sb.append('s');
break;
case NARROW:
sb.append('n');
break;
default:
throw new UnsupportedOperationException(width.name());
}
return sb.append('-').append(suffix).toString();
}
private static String replace(
String s,
char search,
int value
) {
for (int i = 0, n = s.length() - 2; i < n; i++) {
if (
(s.charAt(i) == '{')
&& (s.charAt(i + 1) == search)
&& (s.charAt(i + 2) == '}')
) {
StringBuilder b = new StringBuilder(n + 10);
b.append(s);
b.replace(i + 1, i + 2, String.valueOf(value));
return b.toString();
}
}
return s;
}
} |
package com.structurizr;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.structurizr.documentation.Documentation;
import com.structurizr.documentation.StructurizrDocumentation;
import com.structurizr.model.*;
import com.structurizr.view.ViewSet;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.LinkedList;
import java.util.List;
/**
* Represents a Structurizr workspace, which is a wrapper for a
* software architecture model, views and documentation.
*/
public final class Workspace extends AbstractWorkspace {
private static final Log log = LogFactory.getLog(Workspace.class);
private Model model = new Model();
private ViewSet viewSet = new ViewSet(model);
private Documentation documentation = new StructurizrDocumentation(this);
Workspace() {
}
/**
* Creates a new workspace.
*
* @param name the name of the workspace
* @param description a short description
*/
public Workspace(String name, String description) {
super(name, description);
}
/**
* Gets the software architecture model.
*
* @return a Model instance
*/
public Model getModel() {
return model;
}
void setModel(Model model) {
this.model = model;
}
/**
* Gets the set of views onto a software architecture model.
*
* @return a ViewSet instance
*/
public ViewSet getViews() {
return viewSet;
}
void setViews(ViewSet viewSet) {
this.viewSet = viewSet;
}
/**
* Called when deserialising JSON, to re-create the object graph
* based upon element/relationship IDs.
*/
public void hydrate() {
this.viewSet.setModel(model);
this.documentation.setModel(model);
this.model.hydrate();
this.viewSet.hydrate();
this.documentation.hydrate();
}
/**
* Gets the documentation associated with this workspace.
*
* @return a Documentation object
*/
public Documentation getDocumentation() {
return documentation;
}
/**
* Sets the documentation associated with this workspace.
*
* @param documentation a Documentation object
*/
public void setDocumentation(Documentation documentation) {
this.documentation = documentation;
documentation.setModel(getModel());
}
@JsonIgnore
public boolean isEmpty() {
return model.isEmpty() && viewSet.isEmpty() && documentation.isEmpty();
}
/**
* Counts and logs any warnings within the workspace (e.g. missing element descriptions).
*
* @return the number of warnings
*/
public int countAndLogWarnings() {
final List<String> warnings = new LinkedList<>();
// find elements with a missing description
getModel().getElements().stream()
.filter(e -> !(e instanceof ContainerInstance))
.filter(e -> e.getDescription() == null || e.getDescription().trim().length() == 0)
.forEach(e -> warnings.add("The " + typeof(e) + " \"" + e.getCanonicalName().substring(1) + "\" is missing a description."));
// find containers with a missing technology
getModel().getElements().stream()
.filter(e -> e instanceof Container)
.map(e -> (Container)e)
.filter(c -> c.getTechnology() == null || c.getTechnology().trim().length() == 0)
.forEach(c -> warnings.add("The container \"" + c.getCanonicalName().substring(1) + "\" is missing a technology."));
// find components with a missing technology
getModel().getElements().stream()
.filter(e -> e instanceof Component)
.map(e -> (Component)e)
.filter(c -> c.getTechnology() == null || c.getTechnology().trim().length() == 0)
.forEach(c -> warnings.add("The component \"" + c.getCanonicalName().substring(1) + "\" is missing a technology."));
// find component relationships with a missing description
for (Relationship relationship : getModel().getRelationships()) {
if (relationship.getSource() instanceof Component && relationship.getDestination() instanceof Component &&
relationship.getSource().getParent().equals(relationship.getDestination().getParent())) {
// ignore component-component relationships inside the same container because these are
// often identified using reflection and won't have a description
// (i.e. let's not flood the user with warnings)
} else {
if (relationship.getDescription() == null || relationship.getDescription().trim().length() == 0) {
warnings.add("The relationship between " + typeof(relationship.getSource()) + " \"" + relationship.getSource().getCanonicalName().substring(1) + "\" and " + typeof(relationship.getDestination()) + " \"" + relationship.getDestination().getCanonicalName().substring(1) + "\" is missing a description.");
}
}
}
// diagram keys have not been specified - this is only applicable to
// workspaces created with the early versions of Structurizr for Java
getViews().getEnterpriseContextViews().stream()
.filter(v -> v.getKey() == null)
.forEach(v -> warnings.add("Enterprise Context view \"" + v.getName() + "\": Missing key"));
getViews().getSystemContextViews().stream()
.filter(v -> v.getKey() == null)
.forEach(v -> warnings.add("System Context view \"" + v.getName() + "\": Missing key"));
getViews().getContainerViews().stream()
.filter(v -> v.getKey() == null)
.forEach(v -> warnings.add("Container view \"" + v.getName() + "\": Missing key"));
getViews().getComponentViews().stream()
.filter(v -> v.getKey() == null)
.forEach(v -> warnings.add("Component view \"" + v.getName() + "\": Missing key"));
getViews().getDynamicViews().stream()
.filter(v -> v.getKey() == null)
.forEach(v -> warnings.add("Dynamic view \"" + v.getName() + "\": Missing key"));
getViews().getDeploymentViews().stream()
.filter(v -> v.getKey() == null)
.forEach(v -> warnings.add("Deployment view \"" + v.getName() + "\": Missing key"));
warnings.forEach(log::warn);
return warnings.size();
}
private String typeof(Element element) {
if (element instanceof SoftwareSystem) {
return "software system";
} else {
return element.getClass().getSimpleName().toLowerCase();
}
}
} |
package Electro2D;/*
* A 2D simulation of electrophoresis using Swing components.
*/
/**
* @author Jill Zapoticznyj
* @author Adam Bazinet
* @author Amanda Fisher
*/
import Electro2D.Electro2D;
import javax.swing.JPanel;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Image;
import java.awt.Dimension;
import java.util.Vector;
import java.util.ArrayList;
import java.awt.Color;
import java.awt.Graphics;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.FileOutputStream;
/**
* Controls the actual movement and placement for the animation frame.
*/
public class GelCanvas extends JPanel implements MouseListener {
private Electro2D electro2D;
private Vector barProteins;
private Vector dotProteins;
private Vector barProteins2;
private Vector dotProteins2;
private double maxPH = -1;
private double minPH = -1;
private double lowAcrylamide;
private double highAcrylamide;
private CompIEF comp;
private static final int VOLTAGE = 50;
private Graphics graphic;
private Rectangle gelCanvasRectangle;
private Image bufferImage;
private Graphics bufferImageGraphics;
private boolean pHLinesNeedToBeDrawn;
private boolean mWLinesNeedToBeDrawn;
private boolean redrawPHAndMWLines;
private boolean indicateProteinPosition;
private double tenK = 48;
private double twentyfiveK = 48;
private double fiftyK = 48;
private double hundredK = 48;
private int genDotsRepeats;
private boolean calculateMW = true;
private boolean reMWLabel = false;
private boolean barProteinsStillMoving = true;
private static int iefRed = 54;
private static int iefGreen = 100;
private static int iefBlue = 139;
private double xLoc;
private double yLoc;
private static boolean blink = false;
private boolean mousePress = false;
private int startX = -1;
private int startY = -1;
private int stopX = -1;
private int stopY = -1;
/**
* Constructs a gel canvas and adds itself as a mouse listener
*
* @param e Used to link back to the electro2D that will use the gel canvas
*/
public GelCanvas(Electro2D e) {
super();
electro2D = e;
addMouseListener(this);
}
/**
* This method is used to ensure that Electro2D.GelCanvas will take up
* enough space to allow the user to easily see its display.
*
* @return the dimension object used by the JFrame to allocate the space for
* the component
*/
public Dimension getMinimiumSize() {
return new Dimension(800, electro2D.getHeight());
}
/**
* Sets up the gel canvas for animating the Electro1D simulation
*/
public void prepare() {
/**
* Make two vectors that will contain the objects that are the image
* representations of the proteins in gel canvas
*/
barProteins = new Vector();
dotProteins = new Vector();
/**
* Set up the static variables in Electro2D.IEFProtein so it knows the pH range
*/
maxPH = electro2D.getMaxRange();
minPH = electro2D.getMinRange();
IEFProtein.setRange(maxPH, minPH);
/**
* Create the Electro2D.CompIEF object that later will help sort the proteins
*/
comp = new CompIEF(maxPH, minPH);
/**
* Call the next method, which will handle setting up the barProtein
* vector
*/
fillBarProteinVector();
}
public void fillBarProteinVector() {
/**
* Get all the information barProtein vector will need from electro2D
* into local variable vectors.
*/
Vector sequenceTitles = electro2D.getSequenceTitles();
Vector molecularWeights = electro2D.getMolecularWeights();
Vector pIValues = electro2D.getPiValues();
Vector sequences = electro2D.getSequences();
Vector functions = electro2D.getFunctions();
/**
* Fill up the barProteins vector
*/
for (int i = 0; i < sequenceTitles.size(); i++) {
barProteins.addElement(
new IEFProtein(
new E2DProtein(
sequenceTitles.elementAt(i).toString(),
Double.valueOf(molecularWeights.elementAt(i).toString()),
Double.valueOf(pIValues.elementAt(i).toString()),
sequences.elementAt(i).toString(),
functions.elementAt(i).toString()
),
this)
);
}
/**
* Call the next method, which will sort the elements in barProteins
*/
sortBarProteins();
}
public void sortBarProteins() {
/**
* This nested for loop will do a sort of collapsing exercise; every
* protein in the barProtein vector will be evaluated by the Electro2D.CompIEF
* class against every other protein, and if they're the same they'll
* be collapsed into the same element.
*
* The for loops start out with their iterators at -1 the length of
* barProteins so that they can access their elements in order correctly
*/
for (int i = barProteins.size() - 1; i >= 0; i
for (int j = i - 1; j >= 0; j
if (comp.compare((IEFProtein) barProteins.elementAt(i),
(IEFProtein) barProteins.elementAt(j)) == 0) {
((IEFProtein) (barProteins.elementAt(i))).addProtein(
((IEFProtein) (barProteins.elementAt(j))).getProtein());
barProteins.remove(j);
i
j = i;
}
}
}
/**
* call the next method, makeDotProteins(), which will convert the bar
* proteins into dot proteins, animation wise
*/
makeDotProteins();
}
public void makeDotProteins() {
/**
* this next for loop goes through each element in the vector that we
* just collapsed everything in and retrieves all the proteins that
* were represented by each bar in the last animation
*/
Vector tempProteins = new Vector();
double tempx = 0;
double tempy = 0;
for (int i = 0; i < barProteins.size(); i++) {
/**
* retrieve the coordinates and proteins of each bar protein
*/
tempx = ((IEFProtein) (barProteins.elementAt(i))).returnX();
tempy = ((IEFProtein) (barProteins.elementAt(i))).returnY();
tempProteins = ((IEFProtein) (barProteins.elementAt(i))).getProtein();
for (int j = 0; j < tempProteins.size(); j++) {
/**
* make a protein dot animation for each protein contained in
* the bar proteins
*/
dotProteins.addElement(new ProteinDot(
((E2DProtein) (tempProteins.elementAt(j))), this, tempx,
tempy + 43));
}
tempProteins.removeAllElements();
}
}
/**
* The prepare2 method is called only when the user wishes to compare
* two proteome files. The method performs the same basic steps as
* the original prepare method cascade, as well as comparing the proteins
* from the second file to those already contained in the first file.
* If two proteins are the same, it colors the first file's matching
* proteins green and removes the proteins from the second file's
* collection of proteins.
*/
public void prepare2() {
Vector sequenceTitles2 = electro2D.getSequenceTitles2();
Vector molecularWeights2 = electro2D.getMolecularWeights2();
Vector pIValues2 = electro2D.getPiValues2();
Vector sequences2 = electro2D.getSequences2();
Vector functions2 = electro2D.getFunctions2();
barProteins2 = new Vector();
dotProteins2 = new Vector();
/**
* compare the sequences of the second file to the sequences of
* the proteins in the first file
*/
for (int i = dotProteins.size() - 1; i >= 0; i
/**
* color the proteins in the first file red
*/
((ProteinDot) dotProteins.elementAt(i)).changeColor(Color.red);
String tempSequence = ((ProteinDot) dotProteins.elementAt(i)).getPro().getSequence();
for (int j = sequences2.size() - 1; j >= 0; j
/**
* if the sequences match, remove the sequence and its
* corresponding information from the second file's list of
* info and color the protein green in the vector of proteins
* from the first file
*/
if (((String) sequences2.elementAt(j)).equals(tempSequence)) {
sequences2.remove(j);
sequenceTitles2.remove(j);
molecularWeights2.remove(j);
pIValues2.remove(j);
functions2.remove(j);
((ProteinDot) dotProteins.elementAt(i)).changeColor(Color.green);
break;
}
}
}
/**
* Next, make IEF bar proteins out of the proteins on the second list
* that didn't match the proteins in the first list so that their
* positions on the gel field can later be determined
*/
for (int i = 0; i < sequences2.size(); i++) {
barProteins2.addElement(new IEFProtein(new E2DProtein(
((String) sequenceTitles2.elementAt(i)),
((Double.valueOf(
(String) molecularWeights2.elementAt(i)))).doubleValue(),
((Double.valueOf(
(String) pIValues2.elementAt(i)))).doubleValue(),
(String) sequences2.elementAt(i),
(String) functions2.elementAt(i)), this));
}
/**
* Convert the bar proteins into dot proteins and color them all yellow
* to designate them as being the ones from the second list that did
* not match.
*/
int tempx;
int tempy;
Vector tempProteins;
ProteinDot tempDot;
for (int i = 0; i < barProteins2.size(); i++) {
tempx = ((IEFProtein) barProteins2.elementAt(i)).returnX();
tempy = ((IEFProtein) barProteins2.elementAt(i)).returnY();
tempProteins = ((IEFProtein) barProteins2.elementAt(i)).getProtein();
tempDot = new ProteinDot((E2DProtein) tempProteins.elementAt(0), this, tempx, tempy + 43);
tempDot.changeColor(Color.yellow);
dotProteins2.addElement(tempDot);
}
}
/**
* The paintComponent method does the actual drawing when the System calls
* for the Electro2D.GelCanvas to be set up.
*
* @override overrides the paintComponent method of JPanel
*/
public void paintComponent(Graphics g) {
/**
* We first set up the graphics object to equal an instance variable
* so other methods can interact with it.
*/
graphic = g;
/**
* We then set up a buffer image area so that once we're done painting
* on it we can transfer what we've drawn to the actual area that the
* user can see. This reduces flickering.
*/
if (gelCanvasRectangle == null || bufferImage == null || bufferImageGraphics == null) {
gelCanvasRectangle = getBounds();
bufferImage = this.createImage(gelCanvasRectangle.width, gelCanvasRectangle.height);
bufferImageGraphics = bufferImage.getGraphics();
bufferImageGraphics.setColor(Color.BLACK);
bufferImageGraphics.fillRect(0, 0, gelCanvasRectangle.width - 1, gelCanvasRectangle.height - 1);
}
/**
* Next we check to see if it's time to draw the pH lines by finding if
* an animation has been run by looking at whether or not the PH values
* are different from their startig values of -1 as well as checking to
* see if the Line boolean indicates that the lines have already been
* drawn.
*/
if (maxPH != -1 && minPH != -1 && pHLinesNeedToBeDrawn) {
drawPHLines();
}
/**
* Check to see if the SDS animation has been run, and if it has
* draw the lines for molecular weight.
*/
if (mWLinesNeedToBeDrawn) {
initiateMWLines();
mWLinesNeedToBeDrawn = false;
redrawPHAndMWLines = true;
} else if (redrawPHAndMWLines) {
drawPHLines();
redoMWLines();
}
/**
* When the user clicks on a protein name in the protein list in
* Electro2D.Electro2D, the drawProteinPosition method will draw a draw axis on
* the gel canvas with the protein of interest at its origin.
*/
if (indicateProteinPosition) {
redrawLocation();
}
/**
* Next, we color the buffer image with a rectangle the size of our
* canvas in black. Then we make a black
* rectangle at the top of the image that's almost as long as the
* image itself but only 46 pixals tall.
* Then we copy it all over to our canvas.
*/
bufferImageGraphics.setColor(Color.RED);
bufferImageGraphics.drawRect(0, 0, gelCanvasRectangle.width - 1, gelCanvasRectangle.height - 1);
bufferImageGraphics.drawRect(1, 1, gelCanvasRectangle.width - 3, 46);
graphic.drawImage(bufferImage, 0, 0, this);
}
/**
* This method is responsible for drawing the dot proteins onto the canvas
*
* @param g the graphics object
*/
public void update(Graphics g) {
if (dotProteins == null) {
dotProteins = new Vector();
}
if (dotProteins2 == null) {
dotProteins2 = new Vector();
}
// First, clear off any dots left over from the last animation
bufferImageGraphics.setColor(Color.BLACK);//trying to turn canvas black
bufferImageGraphics.clearRect(1, 48, gelCanvasRectangle.width - 2, gelCanvasRectangle.height - 49);
bufferImageGraphics.fillRect(1, 48, gelCanvasRectangle.width - 2, gelCanvasRectangle.height - 49); //trying to turn canvas black
bufferImageGraphics.setColor(Color.RED);//trying to turn canvas black
bufferImageGraphics.drawRect(1, 48, gelCanvasRectangle.width - 2, gelCanvasRectangle.height - 49);
// Then, draw the protein dots
for (int i = 0; i < dotProteins.size(); i++) {
((ProteinDot) (dotProteins.elementAt(i))).draw(bufferImageGraphics);
}
for (int i = 0; i < dotProteins2.size(); i++) {
((ProteinDot) (dotProteins2.elementAt(i))).draw(bufferImageGraphics);
}
// update the background
if (mWLinesNeedToBeDrawn && tenK != 48) {
redoMWLines();
drawPHLines();
}
// transfer the buffer image to the real canvas
g.drawImage(bufferImage, 0, 0, this);
paint(g);
}
/**
* This method is used to generate GIF files for when the user is not
* viewing the gel canvas.
*
* @param dts The vector of dots to create an image of.
* @param seconds Used in writing the file that stores the image.
*/
public void genGIFFile(Vector dts, int seconds) {
ProteinDot.setShow();
dotProteins = dts;
mWLinesNeedToBeDrawn = true;
maxPH = 10;
minPH = 3;
this.repaint();
try {
GIFEncoder gifEnc = new GIFEncoder(bufferImage);
gifEnc.Write(new BufferedOutputStream(new FileOutputStream(electro2D.getLastFileLoaded() + seconds + ".gif")));
} catch (IOException ex) {
System.err.println(ex.getMessage());
} catch (AWTException ex) {
System.err.println(ex.getMessage());
}
}
/**
* returns the graphics object used to draw on the canvas
*
* @return graphic
*/
public Graphics getGraphic() {
return graphic;
}
/**
* This method draws the dotted black vertical lines that represent
* where the different pH values are on the canvas.
*/
public void drawPHLines() {
ArrayList<Integer> linePositions = electro2D.showPH();
int length = 0;
int loc = 0;
int offset = (this.getTopLevelAncestor().getWidth() - this.getWidth() - 25);
bufferImageGraphics.setColor(Color.WHITE);
/**
* Loop through each integer that's in the range between the minPH
* and the maxPH and use that integer to figure out the starting point
* for the line. Then draw a dotted line down the length of the canvas.
*/
for (int i = 0; i < linePositions.size() - 1; i++) {
length = 0;
loc = linePositions.get(i) - 24;
if (loc > 0 && loc < getWidth()) {
while (length < this.getHeight()) {
bufferImageGraphics.drawLine(loc, length, loc, length + 5);
length = length + 10;
}
}
}
pHLinesNeedToBeDrawn = false;
}
/**
* Use this method to say that the pH lines need to be redrawn, but not the
* molecular weight lines.
*/
public void setreLine() {
pHLinesNeedToBeDrawn = true;
redrawPHAndMWLines = false;
}
/**
* Use this method to say that the pH lines and the molecular wieght
* lines shouldn't be redrawn.
*/
public void resetReLine() {
pHLinesNeedToBeDrawn = false;
redrawPHAndMWLines = false;
}
/**
* This method is called by the reset button and sets all of the animation
* variables back to their default values.
*/
public void resetRanges() {
minPH = -1;
maxPH = -1;
tenK = 48;
twentyfiveK = 48;
fiftyK = 48;
hundredK = 48;
reMWLabel = false;
calculateMW = true;
redrawPHAndMWLines = false;
mWLinesNeedToBeDrawn = false;
barProteinsStillMoving = true;
}
/**
* This method is used by Electro2D.DotThread to let the paint method know it's time
* to generate the molecular weight markers.
*
* @param i Number of times the genDots() method was called.
*/
public void setMWLines(int i) {
mWLinesNeedToBeDrawn = true;
calculateMW = true;
genDotsRepeats = i;
}
/**
* This method initializes the lines that denote the different ranges of
* molecular weight and draws them for the first time.
*/
public void initiateMWLines() {
lowAcrylamide = electro2D.getLowPercent();
highAcrylamide = electro2D.getHighPercent();
int height = this.getHeight();
if (calculateMW) {
if (lowAcrylamide == highAcrylamide) {
for (int i = 0; i < genDotsRepeats; i++) {
hundredK = hundredK + (10 * (1 / lowAcrylamide)) * (VOLTAGE / 25) * .25 * (100000 / 100000);
fiftyK = fiftyK + (10 * (1 / lowAcrylamide)) * (VOLTAGE / 25) * .25 * (100000 / 50000);
twentyfiveK = twentyfiveK + (10 * (1 / lowAcrylamide)) * (VOLTAGE / 25) * .25 * (100000 / 25000);
tenK = tenK + (10 * (1 / lowAcrylamide)) * (VOLTAGE / 25) * .25 * (100000 / 10000);
}
} else {
for (int i = 0; i < genDotsRepeats; i++) {
hundredK = hundredK + (10 * 1 / (((hundredK - 48) * (highAcrylamide - lowAcrylamide) / (height - 48)) + lowAcrylamide)) * (VOLTAGE / 25) * .25 * (100000 / 100000);
fiftyK = fiftyK + (10 * 1 / (((fiftyK - 48) * (highAcrylamide - lowAcrylamide) / (height - 48)) + lowAcrylamide)) * (VOLTAGE / 25) * .25 * (100000 / 50000);
twentyfiveK = twentyfiveK + (10 * 1 / (((twentyfiveK - 48) * (highAcrylamide - lowAcrylamide) / (height - 48)) + lowAcrylamide)) * (VOLTAGE / 25) * .25 * (100000 / 25000);
tenK = tenK + (10 * 1 / (((tenK - 48) * (highAcrylamide - lowAcrylamide) / (height - 48)) + lowAcrylamide)) * (VOLTAGE / 25) * .25 * (100000 / 10000);
}
}
calculateMW = false;
int width = 0;
bufferImageGraphics.setColor(Color.LIGHT_GRAY);
while (width < this.getWidth()) {
bufferImageGraphics.drawLine(width, (int) hundredK, width + 5, (int) hundredK);
bufferImageGraphics.drawLine(width, (int) fiftyK, width + 5, (int) fiftyK);
bufferImageGraphics.drawLine(width, (int) twentyfiveK, width + 5, (int) twentyfiveK);
bufferImageGraphics.drawLine(width, (int) tenK, width + 5, (int) tenK);
width = width + 10;
}
electro2D.clearMW();
electro2D.showMW((int) hundredK, (int) fiftyK, (int) twentyfiveK, (int) tenK, reMWLabel);
reMWLabel = true;
graphic.drawImage(bufferImage, 0, 0, this);
}
}
/**
* This method redraws the lines that denote the different ranges of
* molecular weight after the initializeMWLines method has already been
* run.
*/
public void redoMWLines() {
lowAcrylamide = electro2D.getLowPercent();
highAcrylamide = electro2D.getHighPercent();
int width = 0;
bufferImageGraphics.setColor(Color.WHITE);
while (width < this.getWidth()) {
bufferImageGraphics.drawLine(width, (int) hundredK, width + 5, (int) hundredK);
bufferImageGraphics.drawLine(width, (int) fiftyK, width + 5, (int) fiftyK);
bufferImageGraphics.drawLine(width, (int) twentyfiveK, width + 5, (int) twentyfiveK);
bufferImageGraphics.drawLine(width, (int) tenK, width + 5, (int) tenK);
width = width + 10;
}
electro2D.clearMW();
electro2D.showMW((int) hundredK, (int) fiftyK, (int) twentyfiveK, (int) tenK, reMWLabel);
reMWLabel = true;
}
/**
* This method draws the IEF proteins, which appear as moving rectangles at
* the top of the animation, to the screen.
*/
public void drawIEF() {
for (int i = 0; i < barProteins.size(); i++) {
if (barProteinsStillMoving) {
((IEFProtein) barProteins.elementAt(i)).changeX();
} else {
((IEFProtein) barProteins.elementAt(i)).setX();
}
((IEFProtein) (barProteins.elementAt(i))).draw(bufferImageGraphics);
}
if (barProteins2 != null && barProteins2.size() > 0) {
for (int i = 0; i < barProteins2.size(); i++) {
if (barProteinsStillMoving) {
((IEFProtein) barProteins2.elementAt(i)).changeX();
} else {
((IEFProtein) barProteins2.elementAt(i)).setX();
}
((IEFProtein) (barProteins2.elementAt(i))).draw(bufferImageGraphics);
}
}
graphic.drawImage(bufferImage, 0, 0, this);
this.repaint();
}
/**
* This method gives the illusion that the barProteins are being squashed
* into the lower part of the animation.
*/
public void shrinkIEF() {
clearIEF();
drawIEF();
}
/**
* This method clears the IEF animation area.
*/
public void clearIEF() {
bufferImageGraphics.setColor(Color.BLACK);
bufferImageGraphics.clearRect(2, 2, gelCanvasRectangle.width - 3, 45);
bufferImageGraphics.fillRect(2, 2, gelCanvasRectangle.width - 3, 45); //trying to turn canvas black
bufferImageGraphics.setColor(Color.RED);
bufferImageGraphics.drawRect(2, 2, gelCanvasRectangle.width - 3, 45);
graphic.drawImage(bufferImage, 0, 0, this);
}
/**
* Returns the red value for the background of the IEF animation.
*
* @return IEFRED
*/
public static int getRed() {
return iefRed;
}
/**
* Returns the green value for the background of the IEF animation.
*
* @return IEFGREEN
*/
public static int getGreen() {
return iefGreen;
}
/**
* Returns the blue value for the background of the IEF animation.
*
* @return IEFBLUE
*/
public static int getBlue() {
return iefBlue;
}
/**
* Resets the red value for the IEF animation background when the reset
* button is pressed.
*/
public static void setRed() {
iefRed = 54;
}
/**
* Resets the green value for the IEF animation background when the reset
* button is pressed.
*/
public static void setGreen() {
iefGreen = 100;
}
/**
* Resets the blue value for the IEF animation background when the reset
* button is pressed.
*/
public static void setBlue() {
iefBlue = 139;
}
/**
* Controls the animation for the initial display of IEF proteins.
*/
public void animateIEF() {
int finalRed = 0;
int finalGreen = 0;
int finalBlue = 0;
double width = IEFProtein.returnTempWidth();
double finalWidth = IEFProtein.returnWidth();
bufferImageGraphics.setColor(new Color(iefRed, iefGreen, iefBlue));
bufferImageGraphics.fillRect(2, 2, gelCanvasRectangle.width - 3, 45);
IEFProtein.changeWidth();
drawIEF();
iefRed = iefRed - 1;
iefGreen = iefGreen - 2;
iefBlue = (int) (iefBlue - 2.78);
if (iefRed <= finalRed || iefGreen <= finalGreen || iefBlue <= finalBlue || width >= finalWidth) {
barProteinsStillMoving = false;
bufferImageGraphics.setColor(new Color(finalRed, finalGreen, finalBlue));
IEFProtein.setWidth();
bufferImageGraphics.fillRect(2, 2, gelCanvasRectangle.width - 3, 45);
drawIEF();
}
}
/**
* Returns the vector that contains the ProteinDots.
*
* @return the protein dots
*/
public Vector getDots() {
return dotProteins;
}
/**
* Returns the second vector that contains ProteinDots.
*
* @return the protein dots used for comparison
*/
public Vector getDots2() {
return dotProteins2;
}
/**
* Increments the y values for the protein dots depending on whether the
* start button for the second animation has been pushed or not.
*/
public void genDots() {
clearCanvas();
for (int i = 0; i < dotProteins.size(); i++) {
((ProteinDot) (dotProteins.elementAt(i))).changeY();
}
if (dotProteins2 != null) {
for (int j = 0; j < dotProteins2.size(); j++) {
((ProteinDot) (dotProteins2.elementAt(j))).changeY();
}
}
repaint();
}
/**
* Called with the reset button, sets the dotProteins back to how they were
* when the application was first opened.
*/
public void restartCanvas() {
barProteins = null;
dotProteins = null;
barProteins2 = null;
dotProteins2 = null;
/** for(int i = 0; i < dotProteins.size(); i++) {
((Electro2D.ProteinDot)(dotProteins.elementAt(i))).restart();
}
if(dotProteins2 != null) {
for(int i = 0; i < dotProteins2.size(); i++) {
((Electro2D.ProteinDot)(dotProteins2.elementAt(i))).restart();
}
}
**/
update(graphic);
repaint();
}
/**
* Clears the canvas in preperation for more animation.
*/
public void clearCanvas() {
graphic.setColor(Color.BLACK);
graphic.clearRect(1, 48, gelCanvasRectangle.width - 1, gelCanvasRectangle.height - 47);
graphic.fillRect(1, 48, gelCanvasRectangle.width - 1, gelCanvasRectangle.height - 47); //trying to turn canvas black
graphic.setColor(Color.RED);
graphic.drawRect(1, 48, gelCanvasRectangle.width - 1, gelCanvasRectangle.height - 47);
update(graphic);
}
/**
* Draws black axis lines over a protein on the canvas whose name has been
* selected from a list of proteins.
*
* @param id the title of the protein to be indicated
*/
public void drawLocation(String id) {
xLoc = 0;
yLoc = 0;
bufferImageGraphics.setColor(Color.BLACK);
bufferImageGraphics.fillRect(2, 2, gelCanvasRectangle.width - 4, 45);
for (int i = 0; i < dotProteins.size(); i++) {
if ((((ProteinDot) dotProteins.elementAt(i)).getPro().getID()).equals(id)) {
xLoc = ((ProteinDot) dotProteins.elementAt(i)).returnX();
yLoc = ((ProteinDot) dotProteins.elementAt(i)).returnY();
i = dotProteins.size();
}
}
indicateProteinPosition = true;
repaint();
}
/**
* Used by the Electro2D.DotThread class.
*/
public void startDotBlink() {
blink = true;
}
/**
* Returns the statis of blink.
*
* @return blink
*/
public static boolean getBlink() {
return blink;
}
/**
* Sets blink to false.
*/
public static void stopBlink() {
blink = false;
}
/**
* This method draws the location of a protein to the screen using its
* xLoc and yLoc values.
*/
public void redrawLocation() {
bufferImageGraphics.setColor(Color.LIGHT_GRAY);
bufferImageGraphics.drawLine((int) xLoc + 2, (int) yLoc, 0, (int) yLoc);
bufferImageGraphics.drawLine((int) xLoc + 2, (int) yLoc, (int) xLoc + 2, 0);
}
/**
* Called during reset, sets indicateProteinPosition to false.
*/
public void resetLocation() {
indicateProteinPosition = false;
}
/**
* Mouse listener event, called when the user presses down on the mouse.
* Used to select many proteins.
*
* @param e used to return the x and y location of the event
*/
public void mousePressed(MouseEvent e) {
}
/**
* Mouse listener event. Works with the variables set in mousePressed to
* figure out where the user dragged the mouse and select the proteins
* within that area for zoomed display.
*
* @param e used to find where the user released the mouse
*/
public void mouseReleased(MouseEvent e) {
/** if (mousePress) {
stopX = e.getX();
stopY = e.getY();
if(startX != stopX && stopX > startX + 5) {
if(startY != stopY && stopY > startY + 5) {
Vector bigDot = new Vector();
Electro2D.ProteinDot theDot = null;
double diameter = Electro2D.ProteinDot.getDiameter();
for(int i = 0; i < dotProteins.size(); i++) {
theDot = (Electro2D.ProteinDot)dotProteins.get(i);
if((theDot.returnX() + diameter >= startX) && (theDot.returnX() <= stopX)) {
if((theDot.returnY() + diameter >= startY) && (theDot.returnY() <= stopY)) {
bigDot.add(theDot);
}
}
}
if(dotProteins2 != null) {
for(int i = 0; i < dotProteins2.size(); i++) {
theDot = (Electro2D.ProteinDot)dotProteins2.get(i);
if((theDot.returnX() + diameter >= startX) && (theDot.returnX() <= stopX)) {
if((theDot.returnY() + diameter >= startY) && (theDot.returnY() <= stopY)) {
bigDot.add(theDot);
}
}
}
}
ImageZoom zoom = new ImageZoom(electro2D, bufferImage.getSource(), startX, startY, stopX, stopY, bigDot);
}
}
}
**/}
public void mouseEntered(MouseEvent e) {
}
/**
* This method sets mousePress to false, so that a user can't drag a zoom
* box outside of the Electro2D.GelCanvas.
*
* @param e unused
*/
public void mouseExited(MouseEvent e) {
mousePress = false;
}
/**
* This method is called when the user clicks on the Electro2D.GelCanvas
* and will find the protein clicked on and bring up information about it
* in a different window.
*
* @param e used to get the position where the mouse was clicked
*/
public void mouseClicked(MouseEvent e) {
double clickX = e.getX();
double clickY = e.getY();
if (dotProteins != null) {
for (int i = 0; i < dotProteins.size(); i++) {
double dotX = ((ProteinDot) dotProteins.elementAt(i)).returnX();
double dotY = ((ProteinDot) dotProteins.elementAt(i)).returnY();
if (((ProteinDot) dotProteins.elementAt(i)).getShowMe() && clickX <= dotX + 6 && clickX >= dotX - 1) {
if (clickY <= dotY + 7 && clickY >= dotY - 1) {
ProteinFrame pFrame = new ProteinFrame(electro2D, ((ProteinDot) dotProteins.elementAt(i)).getPro().getID(), 1);
pFrame.show();
}
}
}
}
if (dotProteins2 != null) {
for (int i = 0; i < dotProteins2.size(); i++) {
double dotX = ((ProteinDot) dotProteins2.elementAt(i)).returnX();
double dotY = ((ProteinDot) dotProteins2.elementAt(i)).returnY();
if (((ProteinDot) dotProteins2.elementAt(i)).getShowMe() && clickX <= dotX + 5 && clickX >= dotX - 1) {
if (clickY <= dotY + 5 && clickY >= dotY - 1) {
ProteinFrame pFrame = new ProteinFrame(electro2D, ((ProteinDot) dotProteins2.elementAt(i)).getPro().getID(), 2);
pFrame.show();
}
}
}
}
Vector containsBarProteinsProteins = new Vector();
double iefWidth = IEFProtein.returnWidth();
if (barProteins != null) {
for (int j = 0; j < barProteins.size(); j++) {
double iefX = ((IEFProtein) barProteins.elementAt(j)).returnX();
double iefY = ((IEFProtein) barProteins.elementAt(j)).returnY();
if (IEFProtein.returnHeight() > 0) {
if (clickX >= iefX && clickX <= iefX + iefWidth) {
if (clickY >= iefY && clickY <= iefY + 40) {
containsBarProteinsProteins = ((IEFProtein) barProteins.elementAt(j)).getProtein();
IEFFrame iFrame = new IEFFrame((IEFProtein) barProteins.elementAt(j));
iFrame.setResizable(true);
iFrame.pack();
iFrame.show();
}
}
}
}
}
if (barProteins2 != null) {
for (int j = 0; j < barProteins2.size(); j++) {
double iefX = ((IEFProtein) barProteins2.elementAt(j)).returnX();
double iefY = ((IEFProtein) barProteins2.elementAt(j)).returnY();
if (IEFProtein.returnHeight() > 0) {
if (clickX >= iefX && clickX <= iefX + iefWidth) {
if (clickY >= iefY && clickY <= iefY + 40) {
containsBarProteinsProteins = ((IEFProtein) barProteins2.elementAt(j)).getProtein();
IEFFrame iFrame = new IEFFrame((IEFProtein) barProteins2.elementAt(j));
iFrame.setResizable(true);
iFrame.pack();
iFrame.show();
}
}
}
}
}
}
} |
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Double;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
public class NodeShape extends TreeNode {
final private static int radius = 17;
final private static int xShift = 50;
final private static int yShift = 50;
/**
* The center can EASILY be extracted from shape, but I want to finish the algorithms first
*/
Point2D.Double center = null;
Shape shape = null;
private boolean black = true;
public NodeShape(Person pVal, TreeNode pLkid, TreeNode pRkid) {
super(pVal, pLkid, pRkid);
}
/**
* Gives you the node that is contained in the point
*
* @param arg0
* @return
*/
public NodeShape contains(Point2D.Double arg0) {
if (shape != null) {
if (shape.contains(arg0)) {
return this;
}
else {
if (getRkid() != null) {
NodeShape temp = ((NodeShape) getRkid()).contains(arg0);
if (temp != null) {
return temp;
}
}
if (getLkid() != null) {
NodeShape temp = ((NodeShape) getLkid()).contains(arg0);
if (temp != null) {
return temp;
}
}
}
}
return null;
}
public int totalNodesInTree() {
int res = 1;
if (this.getRkid() != null) {
res += ((NodeShape) getRkid()).totalNodesInTree();
}
if (this.getLkid() != null) {
res += ((NodeShape) getLkid()).totalNodesInTree();
}
return res;
}
/*
* TopNode has its coordinates locked
*
* The direction the node is being pointed at is critical to drawing it. It
* has to be adjusted IFF it has kids in the opposite direction. Otherwise
* we are ok drawing them in the normal fashion.
*
* DrawRoot DrawKid requires direction of parent(boolean) If child is right
* child, we need the absolute maximum count of nodes to the right. We shift
* the drawing of this node that many 'shifts' in the direction the parent
* is pointing to us.
*
*
* 50 0 60 56 70
*
* Because of 56 in the above tree we have to shift the drawing of 60 by one
* width. Once we know the x coordinate of the 60, we infer the y coordinate
* based on the depth of the node, and then directly draw it to the screen
* like the root. Drawing the children follows the same process based on the
* coordinates of the parents.
*
* 50 will always and forever be drawn in the same location, because that
* greately simplifies the algorithm.
*
* To sum the process is, get coordinates of parent, get direction from
* parent, find the number of steps from that parent you have to take and
* then draw the node, recursively iterate for children.
*
* Once we KNOW the coordinates of the node, it is much easier to draw the
* children.
*/
public void drawAbsolutely(Graphics2D gd, Point2D.Double initialPoint) {
this.center = initialPoint;
this.shape = new RoundRectangle2D.Double(initialPoint.x - radius, initialPoint.y
- radius, radius * 2, radius * 2,10,10);
int depth = 0; // when drawing absolutely we assume the depth at this node is 0
if (this.getRkid() != null) {
((NodeShape) getRkid()).prepare(initialPoint, true, depth + 1);
}
if (this.getLkid() != null) {
((NodeShape) getLkid()).prepare(initialPoint, false, depth + 1);
}
draw(gd);
}
static int re = 0;
private void draw(Graphics2D gd) {
if (this.getRkid() != null) {
NodeShape rightKid = ((NodeShape)getRkid());
gd.draw(new Line2D.Double(this.center, rightKid.center));
rightKid.draw(gd);
}
if (this.getLkid() != null) {
NodeShape leftKid = ((NodeShape)getLkid());
gd.draw(new Line2D.Double(this.center, leftKid.center));
leftKid.draw(gd);
}
gd.setColor(gd.getBackground());
gd.fill(shape);
gd.setColor(getColor());
gd.draw(shape);
int iter = -8;
/*
* if(i == 2) {
gd.drawString("Age: " +s, (int)center.x-16, (int)center.y + iter);
} else {
gd.drawString(s, (int)center.x-16, (int)center.y + iter);
}
iter+=6;
i++;
*/
String[] words = new String[4];
int i = 0;
for(String s: getVal().allFields().split(",")) {
words[i++] = s;
}
gd.drawString("First: " + words[1], (int)center.x-14, (int)center.y-8);
gd.drawString("Last: " + words[0], (int)center.x-14, (int)center.y-2);
gd.drawString("Age: " + words[2], (int)center.x-14, (int)center.y+4);
gd.drawString("State: " + words[3], (int)center.x-14, (int)center.y+10);
}
public void toggleColor() {
black = !black;
}
private Color getColor() {
if(black) {
return Color.black;
} else {
return Color.red;
}
}
/**
* @param gd
* @param initialPoint
* @param depth
* @return the center of the shape that is drawn
*/
private void prepare(Double initialPoint, boolean rightOfParent, int depth) {
double centerOfCircleYCoordinate = initialPoint.getY() + yShift;
double centerOfCircleXCoordinate = 1;
// to get the xShift, we completely ignore the nodes in the opposite
// direction of the parent. We only worry about the the nodes
// 'in-between' this node and the parent node, which is the total of
// number of nodes in the tree towards the parent
if (rightOfParent) {
if (getLkid() != null) {
centerOfCircleXCoordinate += ((NodeShape) getLkid())
.totalNodesInTree();
}
}
else { // leftOfParent
if (getRkid() != null) {
centerOfCircleXCoordinate += ((NodeShape) getRkid())
.totalNodesInTree();
}
centerOfCircleXCoordinate *= -1;
}
centerOfCircleXCoordinate = centerOfCircleXCoordinate * xShift
+ initialPoint.getX();
this.center = new Point2D.Double(centerOfCircleXCoordinate, centerOfCircleYCoordinate);
this.shape = new RoundRectangle2D.Double(center.x - radius, center.y
- radius, radius * 2, radius * 2,10,10);
if (this.getRkid() != null) {
((NodeShape) getRkid()).prepare(center, true, depth + 1);
}
if (this.getLkid() != null) {
((NodeShape) getLkid()).prepare(center, false, depth + 1);
}
}
} |
package org.flymine.dataloader;
import java.util.Iterator;
import java.util.Collection;
import java.util.Set;
import java.util.HashSet;
import org.acedb.Ace;
import org.acedb.AceException;
import org.acedb.AceURL;
import org.acedb.AceUtils;
import org.acedb.AceSet;
import org.acedb.AceNode;
import org.acedb.AceObject;
import org.acedb.StringValue;
import org.acedb.IntValue;
import org.acedb.FloatValue;
import org.acedb.Reference;
import org.acedb.staticobj.StaticAceObject;
import java.lang.reflect.Field;
import org.flymine.FlyMineException;
import org.flymine.metadata.Model;
import org.flymine.util.TypeUtil;
/**
* DataLoader for AceDB data
* @author Andrew Varley
*/
public class AceDataLoader extends AbstractDataLoader
{
/**
* Static method to unmarshall business objects from a given xml file and call
* store on each.
*
* @param model data model being used
* @param iw writer to handle storing data
* @param source access to AceDb
* @throws FlyMineException if anything goes wrong with xml or storing
*/
public static void processAce(Model model, IntegrationWriter iw,
AceURL source) throws FlyMineException {
try {
Ace.registerDriver(new org.acedb.socket.SocketDriver());
// Go through each class in the model and get a dump of the objects of
// that class
Collection clazzNames = model.getClassNames();
Iterator clazzIter = clazzNames.iterator();
while (clazzIter.hasNext()) {
String clazzName = (String) clazzIter.next();
AceURL objURL = source.relativeURL(clazzName);
AceSet fetchedAceObjects = (AceSet) Ace.fetch(objURL);
Collection objects = processAceObjects(fetchedAceObjects, model);
Iterator objIter = objects.iterator();
while (objIter.hasNext()) {
// Now store that object
store(objIter.next(), iw);
}
}
} catch (Exception e) {
throw new FlyMineException(e);
}
}
/**
* Process a set of Ace objects
*
* @param set the set of Ace objects to process
* @param model the model they belong to
* @return a set of Java objects
*
* @throws AceException if an error occurs with the Ace data
* @throws FlyMineException if an object cannot be instantiated
*/
protected static Set processAceObjects(AceSet set, Model model)
throws AceException, FlyMineException {
HashSet ret = new HashSet();
Iterator aceObjIter = set.iterator();
while (aceObjIter.hasNext()) {
// Convert to Java object
Object obj = processAceObject((AceObject) aceObjIter.next(), null);
ret.add(obj);
}
return ret;
}
/**
* Process an AceObject. This will create a new instance of the
* object and set the identifier.
*
* @param aceObject the AceObject to process
* @param model the model this object comes from, or null if AceObject name is fully qualified
* @return an instance of the object
*
* @throws AceException if an error occurs with the Ace data
* @throws FlyMineException if object cannot be instantiated
*/
protected static Object processAceObject(AceObject aceObject, Model model)
throws AceException, FlyMineException {
Object currentObject = null;
try {
String clazzName = ((AceObject) aceObject).getClassName();
if (model != null) {
clazzName = model.getName() + "." + clazzName;
}
currentObject = Class.forName(clazzName).newInstance();
setField(currentObject, "identifier", AceUtils.decode(aceObject.getName()));
} catch (ClassNotFoundException e) {
throw new FlyMineException(e);
} catch (InstantiationException e) {
throw new FlyMineException(e);
} catch (IllegalAccessException e) {
throw new FlyMineException(e);
}
processAceNode(aceObject, currentObject, model);
return currentObject;
}
/**
* Process an AceNode. This will set field values in the given
* object if the node is a data node.
*
* @param aceNode the AceNode to process
* @param currentObject the object in which to set field
* @param model the model this object comes from, or null if AceObject name is fully qualified
*
* @throws AceException if an error occurs with the Ace data
* @throws FlyMineException if object cannot be instantiated
*/
protected static void processAceNode(AceNode aceNode, Object currentObject, Model model)
throws AceException, FlyMineException {
String nodeType;
Object nodeValue;
String nodeName;
if (aceNode instanceof Reference) {
// nodeName is the name of the field in currentObject
nodeName = getName(aceNode);
// nodeValue is the identifier of the referred to object
nodeValue = AceUtils.decode(aceNode.getName());
// nodeClass is the class of the referred to object, and is part of the target AceURL
String nodeClass = ((Reference) aceNode).getTarget().getPath();
nodeClass = nodeClass.substring(1, nodeClass.indexOf("/", 1));
// Set up a dummy AceObject to encapsulate this info and convert to proper Object
AceObject referredToAceObject = new StaticAceObject((String) nodeValue,
null, nodeClass);
Object referredToObject = processAceObject(referredToAceObject, model);
setField(currentObject, nodeName, referredToObject);
} else if (aceNode instanceof FloatValue) {
nodeName = getName(aceNode);
nodeValue = new Float(((FloatValue) aceNode).toFloat());
setField(currentObject, nodeName, nodeValue);
} else if (aceNode instanceof IntValue) {
nodeName = getName(aceNode);
nodeValue = new Integer(((IntValue) aceNode).toInt());
setField(currentObject, nodeName, nodeValue);
} else if (aceNode instanceof StringValue) {
nodeName = getName(aceNode);
String nodeStringValue = ((StringValue) aceNode).toString();
setField(currentObject, nodeName, AceUtils.decode(nodeStringValue));
} else if (aceNode instanceof AceNode) {
nodeName = AceUtils.decode(aceNode.getName());
// Give it a chance to set a Boolean flag
Field nodeField = TypeUtil.getField(currentObject.getClass(), nodeName);
if ((nodeField != null) && (nodeField.getType() == Boolean.class)) {
setField(currentObject, nodeName, Boolean.TRUE);
} else if ((nodeField != null) && !hasChildValues(aceNode)) {
// Is it a hash? If it is, currentObject will have a field of this name
// and node will not have any values hanging off it
// TODO: this logic
String nodeClass = AceUtils.decode(nodeField.getType().getName());
StaticAceObject referredToAceObject = new StaticAceObject("", // no identifier
null, // no parent
nodeClass);
// Add all of the child nodes to this AceObject
Iterator nodesIter = aceNode.iterator();
while (nodesIter.hasNext()) {
referredToAceObject.addNode((AceNode) nodesIter.next());
}
Object referredToObject = processAceObject(referredToAceObject, model);
setField(currentObject, nodeName, referredToObject);
}
}
// Now iterate through all the child nodes
if (aceNode instanceof AceNode) {
Iterator objIter = aceNode.iterator();
while (objIter.hasNext()) {
processAceNode((AceNode) objIter.next(), currentObject, model);
}
} else {
throw new FlyMineException("Node type " + aceNode.getClass() + " not dealt with");
}
}
/**
* Sets a field in a target object, or adds the piece of data to a collection
*
* @param target the object in which to set the field
* @param fieldName the name of the field to set
* @param fieldValue the value to set or to be added to a collection
* @throws FlyMineException if the field cannot be accessed
*/
protected static void setField(Object target, String fieldName, Object fieldValue)
throws FlyMineException {
try {
Field field = TypeUtil.getField(target.getClass(), fieldName);
if (field != null) {
Class fieldType = field.getType();
if (Collection.class.isAssignableFrom(fieldType)) {
((Collection) TypeUtil.getFieldValue(target, fieldName)).add(fieldValue);
} else {
TypeUtil.setFieldValue(target, fieldName, fieldValue);
}
}
// else the field cannot be found -- do nothing
} catch (IllegalAccessException e) {
throw new FlyMineException(e);
}
}
/**
* Get the name of the parent of an AceNode, with suffix if a multi-valued tag
*
* @param aceNode the node
* @return the name of the parent of the node, or the parent's name if this node is a data node
* @throws AceException if error occurs with the Ace data
*/
protected static String getName(AceSet aceNode) throws AceException {
String name = aceNode.getParent().getName();
AceSet node = aceNode;
int count = 1;
while (((node = node.getParent()) != null)
&& ((node instanceof StringValue)
|| (node instanceof IntValue)
|| (node instanceof FloatValue)
|| (node instanceof Reference))) {
count++;
}
if (count > 1) {
name = node.getName() + "_" + count;;
}
return AceUtils.decode(name);
}
/**
* Returns true if the given node has values as children
*
* @param node the node to test
* @return true if the node has values as children
* @throws AceException if error occurs with the Ace data
*/
protected static boolean hasChildValues(AceNode node) throws AceException {
Iterator childIter = node.iterator();
while (childIter.hasNext()) {
AceNode childNode = (AceNode) childIter.next();
if ((childNode instanceof StringValue)
|| (childNode instanceof IntValue)
|| (childNode instanceof FloatValue)
|| (childNode instanceof Reference)) {
return true;
}
}
return false;
}
/**
* Used for testing access to an AceDB server
*
* @param args command line arguments
* @throws Exception if an error occurs
*/
public static void main(String [] args) throws Exception {
if (args.length != 5) {
throw new RuntimeException("AceDataLoader hostname port username password classname");
}
String host = args[0];
String port = args[1];
String user = args[2];
String passwd = args[3];
String clazzName = args[4];
// URL _dbURL = new URL("acedb://" + host + ":" + port);
// AceURL dbURL = new AceURL(_dbURL, user, passwd, null);
AceURL dbURL = new AceURL("acedb://" + user + ':' + passwd + '@' + host + ':' + port);
Ace.registerDriver(new org.acedb.socket.SocketDriver());
AceURL objURL = dbURL.relativeURL(clazzName);
AceSet fetchedAceObjects = (AceSet) Ace.fetch(objURL);
// Collection col = processAceObjects(fetchedAceObjects, null);
Iterator iter = fetchedAceObjects.iterator();
while (iter.hasNext()) {
AceNode node = (AceNode) iter.next();
}
}
} |
package goryachev.fxdock.internal;
import goryachev.common.util.CList;
import goryachev.common.util.GlobalSettings;
import goryachev.common.util.Log;
import goryachev.common.util.WeakList;
import goryachev.fx.OnWindowClosing;
import goryachev.fxdock.FxDockFramework;
import goryachev.fxdock.FxDockPane;
import goryachev.fxdock.FxDockWindow;
import java.util.List;
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.stage.WindowEvent;
/**
* Docking Framework Implementation.
*/
public class FrameworkBase
{
/** creates windows and panes */
protected FxDockFramework.Generator generator;
/** window stack: top window first */
protected final WeakList<FxDockWindow> windowStack = new WeakList<>();
protected static final Log log = Log.get("FxDockFramework");
/** generator allows for creation of custom docking Stages and docking Panes */
public void setGenerator(FxDockFramework.Generator g)
{
generator = g;
}
public FxDockWindow createWindow()
{
FxDockWindow w = generator().createWindow();
addFocusListener(w);
return w;
}
public FxDockPane createPane(String type)
{
return generator().createPane(type);
}
protected FxDockFramework.Generator generator()
{
if(generator == null)
{
throw new Error("Please configure generator");
}
return generator;
}
public int loadLayout()
{
int ct = FxDockSchema.getWindowCount();
// restore in proper z order
for(int i=ct-1; i>=0; i
{
try
{
FxDockWindow w = createWindow();
String prefix = FxDockSchema.windowID(i);
FxDockSchema.restoreWindow(prefix, w);
registerWindow(w);
Node n = FxDockSchema.loadLayout(prefix);
w.setContent(n);
w.loadSettings(prefix);
w.show();
}
catch(Exception e)
{
log.err(e);
}
}
return ct;
}
public void saveLayout()
{
List<FxDockWindow> ws = getWindows();
int ct = ws.size();
FxDockSchema.clearSettings();
FxDockSchema.setWindowCount(ct);
for(int i=0; i<ct; i++)
{
FxDockWindow w = ws.get(i);
// ensure proper z-order
storeWindow(ct - i - 1, w);
}
GlobalSettings.save();
}
protected void storeWindow(int ix, FxDockWindow w)
{
String prefix = FxDockSchema.windowID(ix);
FxDockSchema.saveLayout(prefix, w.getContent());
w.saveSettings(prefix);
FxDockSchema.storeWindow(prefix, w);
}
public void open(FxDockWindow w)
{
registerWindow(w);
w.show();
}
protected void registerWindow(FxDockWindow w)
{
w.setOnCloseRequest((ev) -> handleClose(w, ev));
w.showingProperty().addListener((src,old,cur) ->
{
if(!cur)
{
unlinkWindow(w);
}
});
}
protected void handleClose(FxDockWindow w, WindowEvent ev)
{
OnWindowClosing ch = new OnWindowClosing(false);
w.confirmClosing(ch);
if(ch.isCancelled())
{
// don't close the window
ev.consume();
}
}
protected void unlinkWindow(FxDockWindow w)
{
if(getWindowCount() == 1)
{
saveLayout();
exitPrivate();
}
}
// FX cannot tell us which window is on top, so we have to do the dirty work ourselves
public void addFocusListener(FxDockWindow w)
{
w.focusedProperty().addListener((src,old,v) ->
{
if(v)
{
onWindowFocused(w);
}
});
}
protected void onWindowFocused(FxDockWindow win)
{
int ix = 0;
while(ix < windowStack.size())
{
FxDockWindow w = windowStack.get(ix);
if((w == null) || (w == win))
{
windowStack.remove(ix);
}
else
{
ix++;
}
}
windowStack.add(win);
}
public FxDockWindow findTopWindow(List<FxDockWindow> ws)
{
int sz = ws.size();
for(int i=windowStack.size()-1; i>=0; --i)
{
FxDockWindow w = windowStack.get(i);
if(w == null)
{
windowStack.remove(i);
}
else
{
for(int j=0; j<sz; j++)
{
if(w == ws.get(j))
{
return w;
}
}
}
}
return null;
}
/** returns a list of vidible windows, topmost window first */
public List<FxDockWindow> getWindows()
{
int sz = windowStack.size();
CList<FxDockWindow> rv = new CList<>(sz);
for(int i=0; i<sz; i++)
{
FxDockWindow w = windowStack.get(i);
if(w != null)
{
if(w.isShowing())
{
rv.add(w);
}
}
}
return rv;
}
public int getWindowCount()
{
int ct = 0;
for(int i=windowStack.size()-1; i>=0; --i)
{
FxDockWindow w = windowStack.get(i);
if(w == null)
{
windowStack.remove(i);
}
else
{
ct++;
}
}
return ct;
}
protected boolean confirmExit()
{
List<FxDockWindow> ws = getWindows();
OnWindowClosing choice = new OnWindowClosing(ws.size() > 1);
for(FxDockWindow w: ws)
{
w.confirmClosing(choice);
if(choice.isCancelled())
{
return false;
}
}
return true;
}
public void exit()
{
saveLayout();
if(confirmExit())
{
exitPrivate();
}
}
protected void exitPrivate()
{
Platform.exit();
System.exit(0);
}
} |
// DatasetFactory.java
package imagej.data;
import net.imglib2.img.Axis;
import net.imglib2.img.Img;
import net.imglib2.img.ImgFactory;
import net.imglib2.img.ImgPlus;
import net.imglib2.img.planar.PlanarImgFactory;
import net.imglib2.type.NativeType;
import net.imglib2.type.logic.BitType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.integer.ByteType;
import net.imglib2.type.numeric.integer.IntType;
import net.imglib2.type.numeric.integer.LongType;
import net.imglib2.type.numeric.integer.ShortType;
import net.imglib2.type.numeric.integer.Unsigned12BitType;
import net.imglib2.type.numeric.integer.UnsignedByteType;
import net.imglib2.type.numeric.integer.UnsignedIntType;
import net.imglib2.type.numeric.integer.UnsignedShortType;
import net.imglib2.type.numeric.real.DoubleType;
import net.imglib2.type.numeric.real.FloatType;
/**
* A utility class with {@link Dataset}-related methods.
*
* @author Curtis Rueden
*/
public final class DatasetFactory {
// TODO - Decide whether to convert this from a utility class into a truly
// extensible factory implementation.
private DatasetFactory() {
// prevent instantiation of utility class
}
public static Dataset create(final long[] dims, final String name,
final Axis[] axes, final int bitsPerPixel, final boolean signed,
final boolean floating)
{
if (bitsPerPixel == 1) {
if (signed || floating) invalidParams(bitsPerPixel, signed, floating);
return create(new BitType(), dims, name, axes);
}
if (bitsPerPixel == 8) {
if (floating) invalidParams(bitsPerPixel, signed, floating);
if (signed) return create(new ByteType(), dims, name, axes);
return create(new UnsignedByteType(), dims, name, axes);
}
if (bitsPerPixel == 12) {
if (signed || floating) invalidParams(bitsPerPixel, signed, floating);
return create(new Unsigned12BitType(), dims, name, axes);
}
if (bitsPerPixel == 16) {
if (floating) invalidParams(bitsPerPixel, signed, floating);
if (signed) return create(new ShortType(), dims, name, axes);
return create(new UnsignedShortType(), dims, name, axes);
}
if (bitsPerPixel == 32) {
if (floating) {
if (!signed) invalidParams(bitsPerPixel, signed, floating);
return create(new FloatType(), dims, name, axes);
}
if (signed) return create(new IntType(), dims, name, axes);
return create(new UnsignedIntType(), dims, name, axes);
}
if (bitsPerPixel == 64) {
if (!signed) invalidParams(bitsPerPixel, signed, floating);
if (floating) return create(new DoubleType(), dims, name, axes);
return create(new LongType(), dims, name, axes);
}
invalidParams(bitsPerPixel, signed, floating);
return null;
}
/**
* Creates a new dataset.
*
* @param <T> The type of the dataset.
* @param type The type of the dataset.
* @param dims The dataset's dimensional extents.
* @param name The dataset's name.
* @param axes The dataset's dimensional axis labels.
* @return The newly created dataset.
*/
public static <T extends RealType<T> & NativeType<T>> Dataset create(
final T type, final long[] dims, final String name, final Axis[] axes)
{
final PlanarImgFactory<T> imgFactory = new PlanarImgFactory<T>();
return create(imgFactory, type, dims, name, axes);
}
/**
* Creates a new dataset using provided ImgFactory
*
* @param <T> The type of the dataset.
* @param factory The ImgFactory to use to create the data.
* @param type The type of the dataset.
* @param dims The dataset's dimensional extents.
* @param name The dataset's name.
* @param axes The dataset's dimensional axis labels.
* @return The newly created dataset.
*/
public static <T extends RealType<T> & NativeType<T>> Dataset create(
final ImgFactory<T> factory, final T type, final long[] dims,
final String name, final Axis[] axes)
{
final Img<T> img = factory.create(dims, type);
final ImgPlus<T> imgPlus = new ImgPlus<T>(img, name, axes, null);
return new ImgLibDataset(imgPlus);
}
// -- Helper methods --
private static void invalidParams(final int bitsPerPixel,
final boolean signed, final boolean floating)
{
throw new IllegalArgumentException("Invalid parameters: bitsPerPixel=" +
bitsPerPixel + ", signed=" + signed + ", floating=" + floating);
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.