diff
stringlengths
262
553k
is_single_chunk
bool
2 classes
is_single_function
bool
1 class
buggy_function
stringlengths
20
391k
fixed_function
stringlengths
0
392k
diff --git a/main/src/main/java/com/bloatit/model/managers/HighlightFeatureManager.java b/main/src/main/java/com/bloatit/model/managers/HighlightFeatureManager.java index 9d2bfcf9a..fa6366b2f 100644 --- a/main/src/main/java/com/bloatit/model/managers/HighlightFeatureManager.java +++ b/main/src/main/java/com/bloatit/model/managers/HighlightFeatureManager.java @@ -1,87 +1,87 @@ // // Copyright (c) 2011 Linkeos. // // This file is part of Elveos.org. // Elveos.org is free software: you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the // Free Software Foundation, either version 3 of the License, or (at your // option) any later version. // // Elveos.org is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for // more details. // You should have received a copy of the GNU General Public License along // with Elveos.org. If not, see http://www.gnu.org/licenses/. // package com.bloatit.model.managers; import java.util.ArrayList; import java.util.List; import com.bloatit.data.DaoHighlightFeature; import com.bloatit.data.queries.DBRequests; import com.bloatit.framework.utils.PageIterable; import com.bloatit.model.HighlightFeature; import com.bloatit.model.lists.HighlightFeatureList; /** * The Class HighlightFeatureManager is an utility class containing static * methods for {@link HighlightFeature} loading etc. */ public final class HighlightFeatureManager { /** * Desactivated constructor on utility class. */ private HighlightFeatureManager() { // Desactivate default ctor } /** * Gets a {@link HighlightFeature} by its id. * * @param id the id * @return the {@link HighlightFeature} or null if not found. */ public static HighlightFeature getById(final Integer id) { return HighlightFeature.create(DBRequests.getById(DaoHighlightFeature.class, id)); } /** * Gets the all th {@link HighlightFeature}s. * * @return the {@link HighlightFeature} features. */ public static PageIterable<HighlightFeature> getAll() { return new HighlightFeatureList(DBRequests.getAll(DaoHighlightFeature.class)); } public static List<HighlightFeature> getPositionArray(int featureCount) { final PageIterable<HighlightFeature> hightlightFeatureList = HighlightFeatureManager.getAll(); final List<HighlightFeature> hightlightFeatureArray = new ArrayList<HighlightFeature>(featureCount); for(int i = 0; i< featureCount; i++) { hightlightFeatureArray.add(null); } for (final HighlightFeature highlightFeature : hightlightFeatureList) { if(!highlightFeature.isActive()) { continue; } final int position = highlightFeature.getPosition() - 1; if (position < featureCount) { if (hightlightFeatureArray.get(position) == null) { - hightlightFeatureArray.add(position, highlightFeature); + hightlightFeatureArray.set(position, highlightFeature); } else { if (!hightlightFeatureArray.get(position).getActivationDate().after(highlightFeature.getActivationDate())) { hightlightFeatureArray.set(position, highlightFeature); } } } } return hightlightFeatureArray; } }
true
true
public static List<HighlightFeature> getPositionArray(int featureCount) { final PageIterable<HighlightFeature> hightlightFeatureList = HighlightFeatureManager.getAll(); final List<HighlightFeature> hightlightFeatureArray = new ArrayList<HighlightFeature>(featureCount); for(int i = 0; i< featureCount; i++) { hightlightFeatureArray.add(null); } for (final HighlightFeature highlightFeature : hightlightFeatureList) { if(!highlightFeature.isActive()) { continue; } final int position = highlightFeature.getPosition() - 1; if (position < featureCount) { if (hightlightFeatureArray.get(position) == null) { hightlightFeatureArray.add(position, highlightFeature); } else { if (!hightlightFeatureArray.get(position).getActivationDate().after(highlightFeature.getActivationDate())) { hightlightFeatureArray.set(position, highlightFeature); } } } } return hightlightFeatureArray; }
public static List<HighlightFeature> getPositionArray(int featureCount) { final PageIterable<HighlightFeature> hightlightFeatureList = HighlightFeatureManager.getAll(); final List<HighlightFeature> hightlightFeatureArray = new ArrayList<HighlightFeature>(featureCount); for(int i = 0; i< featureCount; i++) { hightlightFeatureArray.add(null); } for (final HighlightFeature highlightFeature : hightlightFeatureList) { if(!highlightFeature.isActive()) { continue; } final int position = highlightFeature.getPosition() - 1; if (position < featureCount) { if (hightlightFeatureArray.get(position) == null) { hightlightFeatureArray.set(position, highlightFeature); } else { if (!hightlightFeatureArray.get(position).getActivationDate().after(highlightFeature.getActivationDate())) { hightlightFeatureArray.set(position, highlightFeature); } } } } return hightlightFeatureArray; }
diff --git a/DanmakuFlameMaster/src/main/java/master/flame/danmaku/controller/DrawHandler.java b/DanmakuFlameMaster/src/main/java/master/flame/danmaku/controller/DrawHandler.java index c478698..03eb669 100644 --- a/DanmakuFlameMaster/src/main/java/master/flame/danmaku/controller/DrawHandler.java +++ b/DanmakuFlameMaster/src/main/java/master/flame/danmaku/controller/DrawHandler.java @@ -1,223 +1,224 @@ package master.flame.danmaku.controller; import android.content.Context; import android.os.Handler; import android.os.Looper; import android.os.Message; import master.flame.danmaku.danmaku.model.BaseDanmaku; import master.flame.danmaku.danmaku.model.DanmakuTimer; import master.flame.danmaku.danmaku.parser.BaseDanmakuParser; import master.flame.danmaku.danmaku.util.AndroidUtils; public class DrawHandler extends Handler { public interface Callback { public void prepared(); public void updateTimer(DanmakuTimer timer); } public static final int START = 1; public static final int UPDATE = 2; public static final int RESUME = 3; public static final int SEEK_POS = 4; public static final int PREPARE = 5; private static final int QUIT = 6; private static final int PAUSE = 7; private long pausedPostion = 0; private boolean quitFlag = true; private long mTimeBase; private boolean mReady; private Callback mCallback; private DanmakuTimer timer; private BaseDanmakuParser mParser; public IDrawTask drawTask; private IDanmakuView mDanmakuView; public DrawHandler(Looper looper, IDanmakuView view) { super(looper); if (timer == null) { timer = new DanmakuTimer(); } bindView(view); } private void bindView(IDanmakuView view) { this.mDanmakuView = view; } public void setParser(BaseDanmakuParser parser) { mParser = parser; } public void setCallback(Callback cb) { mCallback = cb; } public void quit() { removeCallbacksAndMessages(null); sendEmptyMessage(QUIT); } public boolean isStop() { return quitFlag; } @Override public void handleMessage(Message msg) { int what = msg.what; switch (what) { case PREPARE: if (mParser == null || !mDanmakuView.isViewReady()) { sendEmptyMessageDelayed(PREPARE, 100); } else { prepare(new Runnable() { @Override public void run() { mReady = true; if (mCallback != null) { mCallback.prepared(); } } }); } break; case START: Long startTime = (Long) msg.obj; if (startTime != null) { pausedPostion = startTime.longValue(); } else { pausedPostion = 0; } case RESUME: quitFlag = false; if (mReady) { mTimeBase = System.currentTimeMillis() - pausedPostion; timer.update(pausedPostion); removeMessages(RESUME); sendEmptyMessage(UPDATE); drawTask.start(); } else { sendEmptyMessageDelayed(RESUME, 100); } break; case SEEK_POS: Long deltaMs = (Long) msg.obj; mTimeBase -= deltaMs; timer.update(System.currentTimeMillis() - mTimeBase); if (drawTask != null) drawTask.seek(timer.currMillisecond); pausedPostion = timer.currMillisecond; removeMessages(RESUME); sendEmptyMessage(RESUME); break; case UPDATE: if (quitFlag) { break; } long startMS = System.currentTimeMillis(); long d = timer.update(startMS - mTimeBase); if (mCallback != null) { mCallback.updateTimer(timer); } if (d <= 0) { removeMessages(UPDATE); sendEmptyMessageDelayed(UPDATE, 60 - d); break; } d = mDanmakuView.drawDanmakus(); removeMessages(UPDATE); if (d < 15) { sendEmptyMessageDelayed(UPDATE, 15 - d); break; } sendEmptyMessage(UPDATE); break; case PAUSE: case QUIT: removeCallbacksAndMessages(null); quitFlag = true; pausedPostion = timer.currMillisecond; if (what == QUIT){ - this.drawTask.quit(); + if (this.drawTask != null) + this.drawTask.quit(); this.getLooper().quit(); } break; } } private void prepare(final Runnable runnable) { if (drawTask == null) { drawTask = createTask(mDanmakuView.isDanmakuDrawingCacheEnabled(), timer, mDanmakuView.getContext(), mDanmakuView.getWidth(), mDanmakuView.getHeight(), new IDrawTask.TaskListener() { @Override public void ready() { runnable.run(); } }); } else { runnable.run(); } } public boolean isPrepared() { return mReady; } private IDrawTask createTask(boolean useDrwaingCache, DanmakuTimer timer, Context context, int width, int height, IDrawTask.TaskListener taskListener) { IDrawTask task = useDrwaingCache ? new CacheManagingDrawTask(timer, context, width, height, taskListener, 1024 * 1024 * AndroidUtils.getMemoryClass(context) / 3) : new DrawTask(timer, context, width, height, taskListener); task.setParser(mParser); task.prepare(); return task; } public void seekTo(Long ms) { seekBy(ms - timer.currMillisecond); } public void seekBy(Long deltaMs) { removeMessages(DrawHandler.UPDATE); obtainMessage(DrawHandler.SEEK_POS, deltaMs).sendToTarget(); } public void addDanmaku(BaseDanmaku item) { if (drawTask != null) { drawTask.addDanmaku(item); } } public void resume() { sendEmptyMessage(DrawHandler.RESUME); } public void prepare() { sendEmptyMessage(DrawHandler.PREPARE); } public void pause() { sendEmptyMessage(DrawHandler.PAUSE); } }
true
true
public void handleMessage(Message msg) { int what = msg.what; switch (what) { case PREPARE: if (mParser == null || !mDanmakuView.isViewReady()) { sendEmptyMessageDelayed(PREPARE, 100); } else { prepare(new Runnable() { @Override public void run() { mReady = true; if (mCallback != null) { mCallback.prepared(); } } }); } break; case START: Long startTime = (Long) msg.obj; if (startTime != null) { pausedPostion = startTime.longValue(); } else { pausedPostion = 0; } case RESUME: quitFlag = false; if (mReady) { mTimeBase = System.currentTimeMillis() - pausedPostion; timer.update(pausedPostion); removeMessages(RESUME); sendEmptyMessage(UPDATE); drawTask.start(); } else { sendEmptyMessageDelayed(RESUME, 100); } break; case SEEK_POS: Long deltaMs = (Long) msg.obj; mTimeBase -= deltaMs; timer.update(System.currentTimeMillis() - mTimeBase); if (drawTask != null) drawTask.seek(timer.currMillisecond); pausedPostion = timer.currMillisecond; removeMessages(RESUME); sendEmptyMessage(RESUME); break; case UPDATE: if (quitFlag) { break; } long startMS = System.currentTimeMillis(); long d = timer.update(startMS - mTimeBase); if (mCallback != null) { mCallback.updateTimer(timer); } if (d <= 0) { removeMessages(UPDATE); sendEmptyMessageDelayed(UPDATE, 60 - d); break; } d = mDanmakuView.drawDanmakus(); removeMessages(UPDATE); if (d < 15) { sendEmptyMessageDelayed(UPDATE, 15 - d); break; } sendEmptyMessage(UPDATE); break; case PAUSE: case QUIT: removeCallbacksAndMessages(null); quitFlag = true; pausedPostion = timer.currMillisecond; if (what == QUIT){ this.drawTask.quit(); this.getLooper().quit(); } break; } }
public void handleMessage(Message msg) { int what = msg.what; switch (what) { case PREPARE: if (mParser == null || !mDanmakuView.isViewReady()) { sendEmptyMessageDelayed(PREPARE, 100); } else { prepare(new Runnable() { @Override public void run() { mReady = true; if (mCallback != null) { mCallback.prepared(); } } }); } break; case START: Long startTime = (Long) msg.obj; if (startTime != null) { pausedPostion = startTime.longValue(); } else { pausedPostion = 0; } case RESUME: quitFlag = false; if (mReady) { mTimeBase = System.currentTimeMillis() - pausedPostion; timer.update(pausedPostion); removeMessages(RESUME); sendEmptyMessage(UPDATE); drawTask.start(); } else { sendEmptyMessageDelayed(RESUME, 100); } break; case SEEK_POS: Long deltaMs = (Long) msg.obj; mTimeBase -= deltaMs; timer.update(System.currentTimeMillis() - mTimeBase); if (drawTask != null) drawTask.seek(timer.currMillisecond); pausedPostion = timer.currMillisecond; removeMessages(RESUME); sendEmptyMessage(RESUME); break; case UPDATE: if (quitFlag) { break; } long startMS = System.currentTimeMillis(); long d = timer.update(startMS - mTimeBase); if (mCallback != null) { mCallback.updateTimer(timer); } if (d <= 0) { removeMessages(UPDATE); sendEmptyMessageDelayed(UPDATE, 60 - d); break; } d = mDanmakuView.drawDanmakus(); removeMessages(UPDATE); if (d < 15) { sendEmptyMessageDelayed(UPDATE, 15 - d); break; } sendEmptyMessage(UPDATE); break; case PAUSE: case QUIT: removeCallbacksAndMessages(null); quitFlag = true; pausedPostion = timer.currMillisecond; if (what == QUIT){ if (this.drawTask != null) this.drawTask.quit(); this.getLooper().quit(); } break; } }
diff --git a/CardGames/src/com/worthwhilegames/cardgames/shared/SoundManager.java b/CardGames/src/com/worthwhilegames/cardgames/shared/SoundManager.java index 9655d68..e743962 100644 --- a/CardGames/src/com/worthwhilegames/cardgames/shared/SoundManager.java +++ b/CardGames/src/com/worthwhilegames/cardgames/shared/SoundManager.java @@ -1,266 +1,268 @@ package com.worthwhilegames.cardgames.shared; import static com.worthwhilegames.cardgames.shared.Constants.LANGUAGE; import static com.worthwhilegames.cardgames.shared.Constants.LANGUAGE_CANADA; import static com.worthwhilegames.cardgames.shared.Constants.LANGUAGE_FRANCE; import static com.worthwhilegames.cardgames.shared.Constants.LANGUAGE_GERMAN; import static com.worthwhilegames.cardgames.shared.Constants.LANGUAGE_UK; import static com.worthwhilegames.cardgames.shared.Constants.LANGUAGE_US; import java.util.Locale; import java.util.Random; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.SoundPool; import android.speech.tts.TextToSpeech; import android.speech.tts.TextToSpeech.OnInitListener; import android.util.Log; import com.worthwhilegames.cardgames.R; /** * This class is used to control the all of the sound in the game. It has * several methods for playing specific sounds and for using the Text To Speech * feature of android */ public class SoundManager { /** * The Logcat Debug tag */ private static final String TAG = SoundManager.class.getName(); /** * The Singleton instance of SoundManager */ private static SoundManager mInstance; /** * This has a bunch of sounds that can be played */ private static SoundPool soundpool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0); /** * This will play music or other sounds */ private static MediaPlayer mediaplayer = new MediaPlayer(); /** * This is how we will read the names of the players out loud */ private static TextToSpeech tts; /** * This is how we can tell if the TTS has been initialized */ private boolean isTTSInitialized = false; /** * This will be obtained from the shared preference to see if the player wants sound fx */ private boolean isSoundFXOn = true; /** * This will be obtained from the shared preference to see if the player wants to have TTS */ private boolean isTTSOn = true; /** * This is how we will get the settings that the user has set. */ private final SharedPreferences sharedPreferences; /** * Strings to be spoken when it is a player's turn */ private static String[] playerTurnPrompt; /** * array to store the SoundPool IDs for the draw card sounds */ private static int[] drawCardSounds; /** * array to store the SoundPool IDs for the play card sounds */ private static int[] playCardSounds; /** * array to store the SoundPool IDs for the shuffle card sounds */ private static int[] shuffleCardSounds; /** * Get an instance of the SoundManager * * @param ctx * @return */ public static SoundManager getInstance(Context ctx) { if (mInstance == null) { mInstance = new SoundManager(ctx); } return mInstance; } /** * this will initialize the SoundManager by initializing all the sound FX * and the TTS object and obtaining user sound preferences * * @param context The context of the class to use the SoundManager */ private SoundManager(Context context) { sharedPreferences = context.getSharedPreferences(Constants.PREFERENCES, Context.MODE_WORLD_READABLE); isSoundFXOn = sharedPreferences.getBoolean(Constants.SOUND_EFFECTS, true); isTTSOn = sharedPreferences.getBoolean(Constants.SPEECH_VOLUME, true); // Initialize the strings to speak when it is a users turn playerTurnPrompt = context.getResources().getStringArray(R.array.phrases); // draw card sounds TypedArray drawSounds = context.getResources().obtainTypedArray(R.array.drawCard); drawCardSounds = new int[drawSounds.length()]; for (int i = 0; i < drawCardSounds.length; i++) { drawCardSounds[i] = soundpool.load(context, drawSounds.getResourceId(i, 0), 1); } // card playing sounds TypedArray playSounds = context.getResources().obtainTypedArray(R.array.playCard); playCardSounds = new int[playSounds.length()]; for (int i = 0; i < playCardSounds.length; i++) { playCardSounds[i] = soundpool.load(context, playSounds.getResourceId(i, 0), 1); } // card shuffling sounds TypedArray shuffleSounds = context.getResources().obtainTypedArray(R.array.shuffle); shuffleCardSounds = new int[shuffleSounds.length()]; for (int i = 0; i < shuffleCardSounds.length; i++) { shuffleCardSounds[i] = soundpool.load(context, shuffleSounds.getResourceId(i, 0), 1); } tts = new TextToSpeech(context.getApplicationContext(), new OnInitListener() { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { // get the user preference String lang = sharedPreferences.getString(LANGUAGE, LANGUAGE_US); - int langResult = -1; + int langResult = TextToSpeech.LANG_MISSING_DATA; - if (lang.equals(LANGUAGE_US)) { // default + if (tts == null) { + langResult = TextToSpeech.LANG_MISSING_DATA; + } else if (lang.equals(LANGUAGE_US)) { // default langResult = tts.setLanguage(Locale.US); } else if (lang.equals(LANGUAGE_GERMAN)) { langResult = tts.setLanguage(Locale.GERMAN); } else if (lang.equals(LANGUAGE_FRANCE)) { langResult = tts.setLanguage(Locale.FRANCE); } else if (lang.equals(LANGUAGE_CANADA)) { langResult = tts.setLanguage(Locale.CANADA); } else if (lang.equals(LANGUAGE_UK)) { langResult = tts.setLanguage(Locale.UK); } if (langResult == TextToSpeech.LANG_MISSING_DATA || langResult == TextToSpeech.LANG_NOT_SUPPORTED) { if (Util.isDebugBuild()) { Log.d(TAG, "Language not available"); } } else { // let us know that it is safe to use it now isTTSInitialized = true; } } else if (Util.isDebugBuild()) { Log.d(TAG, "Text To Speech did not initialize correctly"); } } }); } /** * plays the sound of a card being drawn. plays various sounds. */ public void drawCardSound() { if (isSoundFXOn) { Random rand = new Random(); int i = Math.abs(rand.nextInt() % drawCardSounds.length); soundpool.play(drawCardSounds[i], 1, 1, 1, 0, 1); } } /** * plays the sound of a card being played. plays various sounds. */ public void playCardSound() { if (isSoundFXOn) { Random rand = new Random(); int i = Math.abs(rand.nextInt() % playCardSounds.length); soundpool.play(playCardSounds[i], 1, 1, 1, 0, 1); } } /** * plays the sound of a card being played. plays various sounds. */ public void shuffleCardsSound() { if (isSoundFXOn) { Random rand = new Random(); int i = Math.abs(rand.nextInt() % shuffleCardSounds.length); soundpool.play(shuffleCardSounds[i], 1, 1, 1, 0, 1); } } /** * This will use TextToSpeech to say the string out loud * * @param words this string will be read aloud */ public void speak(String words) { if (isTTSInitialized && isTTSOn) { tts.speak(words, TextToSpeech.QUEUE_FLUSH, null); } } /** * This function will tell a player it is their turn using various strings * * @param name the name of the player */ public void sayTurn(String name) { Random rand = new Random(); int i = Math.abs(rand.nextInt() % playerTurnPrompt.length); speak(playerTurnPrompt[i].replace("%s", name) ); } /** * This will play the theme music */ public void playMusic() { if (isSoundFXOn) { mediaplayer.seekTo(0); mediaplayer.start(); } } /** * This will stop the music from playing */ public void stopMusic() { if (mediaplayer.isPlaying()) { mediaplayer.stop(); } } /** * This should make all sounds stop playing */ public void stopAllSound() { if (mediaplayer.isPlaying()) { mediaplayer.stop(); } soundpool.autoPause(); tts.stop(); } }
false
true
private SoundManager(Context context) { sharedPreferences = context.getSharedPreferences(Constants.PREFERENCES, Context.MODE_WORLD_READABLE); isSoundFXOn = sharedPreferences.getBoolean(Constants.SOUND_EFFECTS, true); isTTSOn = sharedPreferences.getBoolean(Constants.SPEECH_VOLUME, true); // Initialize the strings to speak when it is a users turn playerTurnPrompt = context.getResources().getStringArray(R.array.phrases); // draw card sounds TypedArray drawSounds = context.getResources().obtainTypedArray(R.array.drawCard); drawCardSounds = new int[drawSounds.length()]; for (int i = 0; i < drawCardSounds.length; i++) { drawCardSounds[i] = soundpool.load(context, drawSounds.getResourceId(i, 0), 1); } // card playing sounds TypedArray playSounds = context.getResources().obtainTypedArray(R.array.playCard); playCardSounds = new int[playSounds.length()]; for (int i = 0; i < playCardSounds.length; i++) { playCardSounds[i] = soundpool.load(context, playSounds.getResourceId(i, 0), 1); } // card shuffling sounds TypedArray shuffleSounds = context.getResources().obtainTypedArray(R.array.shuffle); shuffleCardSounds = new int[shuffleSounds.length()]; for (int i = 0; i < shuffleCardSounds.length; i++) { shuffleCardSounds[i] = soundpool.load(context, shuffleSounds.getResourceId(i, 0), 1); } tts = new TextToSpeech(context.getApplicationContext(), new OnInitListener() { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { // get the user preference String lang = sharedPreferences.getString(LANGUAGE, LANGUAGE_US); int langResult = -1; if (lang.equals(LANGUAGE_US)) { // default langResult = tts.setLanguage(Locale.US); } else if (lang.equals(LANGUAGE_GERMAN)) { langResult = tts.setLanguage(Locale.GERMAN); } else if (lang.equals(LANGUAGE_FRANCE)) { langResult = tts.setLanguage(Locale.FRANCE); } else if (lang.equals(LANGUAGE_CANADA)) { langResult = tts.setLanguage(Locale.CANADA); } else if (lang.equals(LANGUAGE_UK)) { langResult = tts.setLanguage(Locale.UK); } if (langResult == TextToSpeech.LANG_MISSING_DATA || langResult == TextToSpeech.LANG_NOT_SUPPORTED) { if (Util.isDebugBuild()) { Log.d(TAG, "Language not available"); } } else { // let us know that it is safe to use it now isTTSInitialized = true; } } else if (Util.isDebugBuild()) { Log.d(TAG, "Text To Speech did not initialize correctly"); } } }); }
private SoundManager(Context context) { sharedPreferences = context.getSharedPreferences(Constants.PREFERENCES, Context.MODE_WORLD_READABLE); isSoundFXOn = sharedPreferences.getBoolean(Constants.SOUND_EFFECTS, true); isTTSOn = sharedPreferences.getBoolean(Constants.SPEECH_VOLUME, true); // Initialize the strings to speak when it is a users turn playerTurnPrompt = context.getResources().getStringArray(R.array.phrases); // draw card sounds TypedArray drawSounds = context.getResources().obtainTypedArray(R.array.drawCard); drawCardSounds = new int[drawSounds.length()]; for (int i = 0; i < drawCardSounds.length; i++) { drawCardSounds[i] = soundpool.load(context, drawSounds.getResourceId(i, 0), 1); } // card playing sounds TypedArray playSounds = context.getResources().obtainTypedArray(R.array.playCard); playCardSounds = new int[playSounds.length()]; for (int i = 0; i < playCardSounds.length; i++) { playCardSounds[i] = soundpool.load(context, playSounds.getResourceId(i, 0), 1); } // card shuffling sounds TypedArray shuffleSounds = context.getResources().obtainTypedArray(R.array.shuffle); shuffleCardSounds = new int[shuffleSounds.length()]; for (int i = 0; i < shuffleCardSounds.length; i++) { shuffleCardSounds[i] = soundpool.load(context, shuffleSounds.getResourceId(i, 0), 1); } tts = new TextToSpeech(context.getApplicationContext(), new OnInitListener() { @Override public void onInit(int status) { if (status == TextToSpeech.SUCCESS) { // get the user preference String lang = sharedPreferences.getString(LANGUAGE, LANGUAGE_US); int langResult = TextToSpeech.LANG_MISSING_DATA; if (tts == null) { langResult = TextToSpeech.LANG_MISSING_DATA; } else if (lang.equals(LANGUAGE_US)) { // default langResult = tts.setLanguage(Locale.US); } else if (lang.equals(LANGUAGE_GERMAN)) { langResult = tts.setLanguage(Locale.GERMAN); } else if (lang.equals(LANGUAGE_FRANCE)) { langResult = tts.setLanguage(Locale.FRANCE); } else if (lang.equals(LANGUAGE_CANADA)) { langResult = tts.setLanguage(Locale.CANADA); } else if (lang.equals(LANGUAGE_UK)) { langResult = tts.setLanguage(Locale.UK); } if (langResult == TextToSpeech.LANG_MISSING_DATA || langResult == TextToSpeech.LANG_NOT_SUPPORTED) { if (Util.isDebugBuild()) { Log.d(TAG, "Language not available"); } } else { // let us know that it is safe to use it now isTTSInitialized = true; } } else if (Util.isDebugBuild()) { Log.d(TAG, "Text To Speech did not initialize correctly"); } } }); }
diff --git a/app/controllers/AccountWebService.java b/app/controllers/AccountWebService.java index 25b77e6..d6246e6 100644 --- a/app/controllers/AccountWebService.java +++ b/app/controllers/AccountWebService.java @@ -1,78 +1,78 @@ package controllers; import global.GlobalContext; import org.jcheng.service.account.AccountService; import org.jcheng.service.account.AuthorizationService; import play.data.DynamicForm; import play.libs.Json; import play.mvc.BodyParser; import play.mvc.Controller; import play.mvc.Result; import play.mvc.With; import actions.AccountAuthAction; import com.google.common.base.Strings; /** * Provides a JSON web service for managing accounts. * * @author jcheng * */ public class AccountWebService extends Controller { private static AccountService accountService = (AccountService) GlobalContext.getApplicationContext().getBean("accountService"); private static AuthorizationService authorizationService = (AuthorizationService) GlobalContext.getApplicationContext().getBean("authorizationService"); @BodyParser.Of(play.mvc.BodyParser.Json.class) public static Result doCreate() { - DynamicForm data = form().bindFromRequest(); + DynamicForm data = new DynamicForm().bindFromRequest(); String username = data.get("username"); String pwHash = data.get("pwHash"); System.err.println( username + " , " + pwHash); boolean isCreated = accountService.isAccountCreated(username); if ( isCreated ) { return badRequest(Json.toJson(new WSResult(false, "account already exists"))); } else { boolean created = accountService.createAccount(username, pwHash, "identity"); if ( created ) { return ok(Json.toJson(new WSResult(true, "ok"))); } else { return badRequest(Json.toJson(new WSResult(false, "failed"))); } } } public static Result doLogin(String username, String pwHash) { boolean isValid = accountService.isLoginValid(username, pwHash); if ( isValid ) { String authToken = authorizationService.getToken(username); return ok(Json.toJson(new WSResult(true, authToken))); } else { return forbidden(Json.toJson(new WSResult(false, "login failed"))); } } @With(AccountAuthAction.class) public static Result getLuckyColor(String username) { String luckyColor = accountService.getLuckyColor(username); WSResult result; if ( Strings.isNullOrEmpty(luckyColor) ) { result = new WSResult(false, "invalid request"); } else { result = new WSResult(true, luckyColor); } return ok(Json.toJson(result)); } @With(AccountAuthAction.class) public static Result removeAllAccounts(String username) { accountService.removeAll(); return ok(Json.toJson("ok")); } }
true
true
public static Result doCreate() { DynamicForm data = form().bindFromRequest(); String username = data.get("username"); String pwHash = data.get("pwHash"); System.err.println( username + " , " + pwHash); boolean isCreated = accountService.isAccountCreated(username); if ( isCreated ) { return badRequest(Json.toJson(new WSResult(false, "account already exists"))); } else { boolean created = accountService.createAccount(username, pwHash, "identity"); if ( created ) { return ok(Json.toJson(new WSResult(true, "ok"))); } else { return badRequest(Json.toJson(new WSResult(false, "failed"))); } } }
public static Result doCreate() { DynamicForm data = new DynamicForm().bindFromRequest(); String username = data.get("username"); String pwHash = data.get("pwHash"); System.err.println( username + " , " + pwHash); boolean isCreated = accountService.isAccountCreated(username); if ( isCreated ) { return badRequest(Json.toJson(new WSResult(false, "account already exists"))); } else { boolean created = accountService.createAccount(username, pwHash, "identity"); if ( created ) { return ok(Json.toJson(new WSResult(true, "ok"))); } else { return badRequest(Json.toJson(new WSResult(false, "failed"))); } } }
diff --git a/maven-embedder/src/main/java/org/apache/maven/cli/CLIRequestUtils.java b/maven-embedder/src/main/java/org/apache/maven/cli/CLIRequestUtils.java index ed75b6ba6..5813d1b6d 100644 --- a/maven-embedder/src/main/java/org/apache/maven/cli/CLIRequestUtils.java +++ b/maven-embedder/src/main/java/org/apache/maven/cli/CLIRequestUtils.java @@ -1,345 +1,336 @@ package org.apache.maven.cli; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import org.apache.commons.cli.CommandLine; import org.apache.maven.MavenTransferListener; import org.apache.maven.embedder.MavenEmbedder; import org.apache.maven.execution.DefaultMavenExecutionRequest; import org.apache.maven.execution.MavenExecutionRequest; import org.codehaus.plexus.util.cli.CommandLineUtils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import java.util.Map.Entry; public final class CLIRequestUtils { private CLIRequestUtils() { } public static MavenExecutionRequest buildRequest( CommandLine commandLine, boolean debug, boolean quiet, boolean showErrors ) { // ---------------------------------------------------------------------- // Now that we have everything that we need we will fire up plexus and // bring the maven component to life for use. // ---------------------------------------------------------------------- boolean interactive = true; if ( commandLine.hasOption( CLIManager.BATCH_MODE ) ) { interactive = false; } boolean pluginUpdateOverride = false; if ( commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES ) || commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES2 ) ) { pluginUpdateOverride = true; } else if ( commandLine.hasOption( CLIManager.SUPPRESS_PLUGIN_UPDATES ) ) { pluginUpdateOverride = false; } boolean noSnapshotUpdates = false; if ( commandLine.hasOption( CLIManager.SUPRESS_SNAPSHOT_UPDATES ) ) { noSnapshotUpdates = true; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- List goals = commandLine.getArgList(); boolean recursive = true; // this is the default behavior. String reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST; if ( commandLine.hasOption( CLIManager.NON_RECURSIVE ) ) { recursive = false; } if ( commandLine.hasOption( CLIManager.FAIL_FAST ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST; } else if ( commandLine.hasOption( CLIManager.FAIL_AT_END ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END; } else if ( commandLine.hasOption( CLIManager.FAIL_NEVER ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER; } boolean offline = false; if ( commandLine.hasOption( CLIManager.OFFLINE ) ) { offline = true; } boolean updateSnapshots = false; if ( commandLine.hasOption( CLIManager.UPDATE_SNAPSHOTS ) ) { updateSnapshots = true; } String globalChecksumPolicy = null; if ( commandLine.hasOption( CLIManager.CHECKSUM_FAILURE_POLICY ) ) { // todo; log System.out.println( "+ Enabling strict checksum verification on all artifact downloads." ); globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL; } else if ( commandLine.hasOption( CLIManager.CHECKSUM_WARNING_POLICY ) ) { // todo: log System.out.println( "+ Disabling strict checksum verification on all artifact downloads." ); globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN; } File baseDirectory = new File( System.getProperty( "user.dir" ) ); // ---------------------------------------------------------------------- // Profile Activation // ---------------------------------------------------------------------- List activeProfiles = new ArrayList(); List inactiveProfiles = new ArrayList(); if ( commandLine.hasOption( CLIManager.ACTIVATE_PROFILES ) ) { String [] profileOptionValues = commandLine.getOptionValues( CLIManager.ACTIVATE_PROFILES ); if ( profileOptionValues != null ) { for ( int i=0; i < profileOptionValues.length; ++i ) { StringTokenizer profileTokens = new StringTokenizer( profileOptionValues[i] , "," ); while ( profileTokens.hasMoreTokens() ) { String profileAction = profileTokens.nextToken().trim(); - if ( profileAction.startsWith( "-" ) ) + if ( profileAction.startsWith( "-" ) || profileAction.startsWith( "!" ) ) { inactiveProfiles.add( profileAction.substring( 1 ) ); } - else if ( profileAction.startsWith( "D:" ) ) - { - inactiveProfiles.add( profileAction.substring( 2 ) ); - } else if ( profileAction.startsWith( "+" ) ) { activeProfiles.add( profileAction.substring( 1 ) ); } - else if ( profileAction.startsWith( "E:" ) ) - { - activeProfiles.add( profileAction.substring( 2 ) ); - } else { - // TODO: deprecate this eventually! activeProfiles.add( profileAction ); } } } } } MavenTransferListener transferListener; if ( interactive ) { transferListener = new ConsoleDownloadMonitor(); } else { transferListener = new BatchModeDownloadMonitor(); } transferListener.setShowChecksumEvents( false ); // This means to scan a directory structure for POMs and process them. boolean useReactor = false; if ( commandLine.hasOption( CLIManager.REACTOR ) ) { useReactor = true; } String alternatePomFile = null; if ( commandLine.hasOption( CLIManager.ALTERNATE_POM_FILE ) ) { alternatePomFile = commandLine.getOptionValue( CLIManager.ALTERNATE_POM_FILE ); } int loggingLevel; if ( debug ) { loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_DEBUG; } else if ( quiet ) { // TODO: we need to do some more work here. Some plugins use sys out or log errors at info level. // Ideally, we could use Warn across the board loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_ERROR; // TODO:Additionally, we can't change the mojo level because the component key includes the version and it isn't known ahead of time. This seems worth changing. } else { loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_INFO; } Properties executionProperties = new Properties(); Properties userProperties = new Properties(); populateProperties( commandLine, executionProperties, userProperties ); MavenExecutionRequest request = new DefaultMavenExecutionRequest() .setBaseDirectory( baseDirectory ) .setGoals( goals ) .setProperties( executionProperties ) // optional .setUserProperties( userProperties ) // optional .setReactorFailureBehavior( reactorFailureBehaviour ) // default: fail fast .setRecursive( recursive ) // default: true .setUseReactor( useReactor ) // default: false .setShowErrors( showErrors ) // default: false .setInteractiveMode( interactive ) // default: false .setOffline( offline ) // default: false .setUsePluginUpdateOverride( pluginUpdateOverride ) .addActiveProfiles( activeProfiles ) // optional .addInactiveProfiles( inactiveProfiles ) // optional .setLoggingLevel( loggingLevel ) // default: info .setTransferListener( transferListener ) // default: batch mode which goes along with interactive .setUpdateSnapshots( updateSnapshots ) // default: false .setNoSnapshotUpdates( noSnapshotUpdates ) // default: false .setGlobalChecksumPolicy( globalChecksumPolicy ); // default: warn if ( alternatePomFile != null ) { request.setPom( new File( alternatePomFile ) ); System.out.println( "Request pom set to: " + request.getPom() ); } return request; } // ---------------------------------------------------------------------- // System properties handling // ---------------------------------------------------------------------- static void populateProperties( CommandLine commandLine, Properties executionProperties, Properties userProperties ) { System.setProperty( MavenEmbedder.STANDALONE_MODE, "true" ); executionProperties.setProperty( MavenEmbedder.STANDALONE_MODE, "true" ); // add the env vars to the property set, with the "env." prefix // XXX support for env vars should probably be removed from the ModelInterpolator try { Properties envVars = CommandLineUtils.getSystemEnvVars(); Iterator i = envVars.entrySet().iterator(); while ( i.hasNext() ) { Entry e = (Entry) i.next(); executionProperties.setProperty( "env." + e.getKey().toString(), e.getValue().toString() ); } } catch ( IOException e ) { System.err.println( "Error getting environment vars for profile activation: " + e ); } // ---------------------------------------------------------------------- // Options that are set on the command line become system properties // and therefore are set in the session properties. System properties // are most dominant. // ---------------------------------------------------------------------- if ( commandLine.hasOption( CLIManager.SET_SYSTEM_PROPERTY ) ) { String[] defStrs = commandLine.getOptionValues( CLIManager.SET_SYSTEM_PROPERTY ); if ( defStrs != null ) { for ( int i = 0; i < defStrs.length; ++i ) { setCliProperty( defStrs[i], userProperties ); } } executionProperties.putAll( userProperties ); } executionProperties.putAll( System.getProperties() ); } private static void setCliProperty( String property, Properties executionProperties ) { String name; String value; int i = property.indexOf( "=" ); if ( i <= 0 ) { name = property.trim(); value = "true"; } else { name = property.substring( 0, i ).trim(); value = property.substring( i + 1 ).trim(); } executionProperties.setProperty( name, value ); // ---------------------------------------------------------------------- // I'm leaving the setting of system properties here as not to break // the SystemPropertyProfileActivator. This won't harm embedding. jvz. // ---------------------------------------------------------------------- System.setProperty( name, value ); } }
false
true
public static MavenExecutionRequest buildRequest( CommandLine commandLine, boolean debug, boolean quiet, boolean showErrors ) { // ---------------------------------------------------------------------- // Now that we have everything that we need we will fire up plexus and // bring the maven component to life for use. // ---------------------------------------------------------------------- boolean interactive = true; if ( commandLine.hasOption( CLIManager.BATCH_MODE ) ) { interactive = false; } boolean pluginUpdateOverride = false; if ( commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES ) || commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES2 ) ) { pluginUpdateOverride = true; } else if ( commandLine.hasOption( CLIManager.SUPPRESS_PLUGIN_UPDATES ) ) { pluginUpdateOverride = false; } boolean noSnapshotUpdates = false; if ( commandLine.hasOption( CLIManager.SUPRESS_SNAPSHOT_UPDATES ) ) { noSnapshotUpdates = true; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- List goals = commandLine.getArgList(); boolean recursive = true; // this is the default behavior. String reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST; if ( commandLine.hasOption( CLIManager.NON_RECURSIVE ) ) { recursive = false; } if ( commandLine.hasOption( CLIManager.FAIL_FAST ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST; } else if ( commandLine.hasOption( CLIManager.FAIL_AT_END ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END; } else if ( commandLine.hasOption( CLIManager.FAIL_NEVER ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER; } boolean offline = false; if ( commandLine.hasOption( CLIManager.OFFLINE ) ) { offline = true; } boolean updateSnapshots = false; if ( commandLine.hasOption( CLIManager.UPDATE_SNAPSHOTS ) ) { updateSnapshots = true; } String globalChecksumPolicy = null; if ( commandLine.hasOption( CLIManager.CHECKSUM_FAILURE_POLICY ) ) { // todo; log System.out.println( "+ Enabling strict checksum verification on all artifact downloads." ); globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL; } else if ( commandLine.hasOption( CLIManager.CHECKSUM_WARNING_POLICY ) ) { // todo: log System.out.println( "+ Disabling strict checksum verification on all artifact downloads." ); globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN; } File baseDirectory = new File( System.getProperty( "user.dir" ) ); // ---------------------------------------------------------------------- // Profile Activation // ---------------------------------------------------------------------- List activeProfiles = new ArrayList(); List inactiveProfiles = new ArrayList(); if ( commandLine.hasOption( CLIManager.ACTIVATE_PROFILES ) ) { String [] profileOptionValues = commandLine.getOptionValues( CLIManager.ACTIVATE_PROFILES ); if ( profileOptionValues != null ) { for ( int i=0; i < profileOptionValues.length; ++i ) { StringTokenizer profileTokens = new StringTokenizer( profileOptionValues[i] , "," ); while ( profileTokens.hasMoreTokens() ) { String profileAction = profileTokens.nextToken().trim(); if ( profileAction.startsWith( "-" ) ) { inactiveProfiles.add( profileAction.substring( 1 ) ); } else if ( profileAction.startsWith( "D:" ) ) { inactiveProfiles.add( profileAction.substring( 2 ) ); } else if ( profileAction.startsWith( "+" ) ) { activeProfiles.add( profileAction.substring( 1 ) ); } else if ( profileAction.startsWith( "E:" ) ) { activeProfiles.add( profileAction.substring( 2 ) ); } else { // TODO: deprecate this eventually! activeProfiles.add( profileAction ); } } } } } MavenTransferListener transferListener; if ( interactive ) { transferListener = new ConsoleDownloadMonitor(); } else { transferListener = new BatchModeDownloadMonitor(); } transferListener.setShowChecksumEvents( false ); // This means to scan a directory structure for POMs and process them. boolean useReactor = false; if ( commandLine.hasOption( CLIManager.REACTOR ) ) { useReactor = true; } String alternatePomFile = null; if ( commandLine.hasOption( CLIManager.ALTERNATE_POM_FILE ) ) { alternatePomFile = commandLine.getOptionValue( CLIManager.ALTERNATE_POM_FILE ); } int loggingLevel; if ( debug ) { loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_DEBUG; } else if ( quiet ) { // TODO: we need to do some more work here. Some plugins use sys out or log errors at info level. // Ideally, we could use Warn across the board loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_ERROR; // TODO:Additionally, we can't change the mojo level because the component key includes the version and it isn't known ahead of time. This seems worth changing. } else { loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_INFO; } Properties executionProperties = new Properties(); Properties userProperties = new Properties(); populateProperties( commandLine, executionProperties, userProperties ); MavenExecutionRequest request = new DefaultMavenExecutionRequest() .setBaseDirectory( baseDirectory ) .setGoals( goals ) .setProperties( executionProperties ) // optional .setUserProperties( userProperties ) // optional .setReactorFailureBehavior( reactorFailureBehaviour ) // default: fail fast .setRecursive( recursive ) // default: true .setUseReactor( useReactor ) // default: false .setShowErrors( showErrors ) // default: false .setInteractiveMode( interactive ) // default: false .setOffline( offline ) // default: false .setUsePluginUpdateOverride( pluginUpdateOverride ) .addActiveProfiles( activeProfiles ) // optional .addInactiveProfiles( inactiveProfiles ) // optional .setLoggingLevel( loggingLevel ) // default: info .setTransferListener( transferListener ) // default: batch mode which goes along with interactive .setUpdateSnapshots( updateSnapshots ) // default: false .setNoSnapshotUpdates( noSnapshotUpdates ) // default: false .setGlobalChecksumPolicy( globalChecksumPolicy ); // default: warn if ( alternatePomFile != null ) { request.setPom( new File( alternatePomFile ) ); System.out.println( "Request pom set to: " + request.getPom() ); } return request; }
public static MavenExecutionRequest buildRequest( CommandLine commandLine, boolean debug, boolean quiet, boolean showErrors ) { // ---------------------------------------------------------------------- // Now that we have everything that we need we will fire up plexus and // bring the maven component to life for use. // ---------------------------------------------------------------------- boolean interactive = true; if ( commandLine.hasOption( CLIManager.BATCH_MODE ) ) { interactive = false; } boolean pluginUpdateOverride = false; if ( commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES ) || commandLine.hasOption( CLIManager.FORCE_PLUGIN_UPDATES2 ) ) { pluginUpdateOverride = true; } else if ( commandLine.hasOption( CLIManager.SUPPRESS_PLUGIN_UPDATES ) ) { pluginUpdateOverride = false; } boolean noSnapshotUpdates = false; if ( commandLine.hasOption( CLIManager.SUPRESS_SNAPSHOT_UPDATES ) ) { noSnapshotUpdates = true; } // ---------------------------------------------------------------------- // // ---------------------------------------------------------------------- List goals = commandLine.getArgList(); boolean recursive = true; // this is the default behavior. String reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST; if ( commandLine.hasOption( CLIManager.NON_RECURSIVE ) ) { recursive = false; } if ( commandLine.hasOption( CLIManager.FAIL_FAST ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST; } else if ( commandLine.hasOption( CLIManager.FAIL_AT_END ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END; } else if ( commandLine.hasOption( CLIManager.FAIL_NEVER ) ) { reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER; } boolean offline = false; if ( commandLine.hasOption( CLIManager.OFFLINE ) ) { offline = true; } boolean updateSnapshots = false; if ( commandLine.hasOption( CLIManager.UPDATE_SNAPSHOTS ) ) { updateSnapshots = true; } String globalChecksumPolicy = null; if ( commandLine.hasOption( CLIManager.CHECKSUM_FAILURE_POLICY ) ) { // todo; log System.out.println( "+ Enabling strict checksum verification on all artifact downloads." ); globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL; } else if ( commandLine.hasOption( CLIManager.CHECKSUM_WARNING_POLICY ) ) { // todo: log System.out.println( "+ Disabling strict checksum verification on all artifact downloads." ); globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN; } File baseDirectory = new File( System.getProperty( "user.dir" ) ); // ---------------------------------------------------------------------- // Profile Activation // ---------------------------------------------------------------------- List activeProfiles = new ArrayList(); List inactiveProfiles = new ArrayList(); if ( commandLine.hasOption( CLIManager.ACTIVATE_PROFILES ) ) { String [] profileOptionValues = commandLine.getOptionValues( CLIManager.ACTIVATE_PROFILES ); if ( profileOptionValues != null ) { for ( int i=0; i < profileOptionValues.length; ++i ) { StringTokenizer profileTokens = new StringTokenizer( profileOptionValues[i] , "," ); while ( profileTokens.hasMoreTokens() ) { String profileAction = profileTokens.nextToken().trim(); if ( profileAction.startsWith( "-" ) || profileAction.startsWith( "!" ) ) { inactiveProfiles.add( profileAction.substring( 1 ) ); } else if ( profileAction.startsWith( "+" ) ) { activeProfiles.add( profileAction.substring( 1 ) ); } else { activeProfiles.add( profileAction ); } } } } } MavenTransferListener transferListener; if ( interactive ) { transferListener = new ConsoleDownloadMonitor(); } else { transferListener = new BatchModeDownloadMonitor(); } transferListener.setShowChecksumEvents( false ); // This means to scan a directory structure for POMs and process them. boolean useReactor = false; if ( commandLine.hasOption( CLIManager.REACTOR ) ) { useReactor = true; } String alternatePomFile = null; if ( commandLine.hasOption( CLIManager.ALTERNATE_POM_FILE ) ) { alternatePomFile = commandLine.getOptionValue( CLIManager.ALTERNATE_POM_FILE ); } int loggingLevel; if ( debug ) { loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_DEBUG; } else if ( quiet ) { // TODO: we need to do some more work here. Some plugins use sys out or log errors at info level. // Ideally, we could use Warn across the board loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_ERROR; // TODO:Additionally, we can't change the mojo level because the component key includes the version and it isn't known ahead of time. This seems worth changing. } else { loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_INFO; } Properties executionProperties = new Properties(); Properties userProperties = new Properties(); populateProperties( commandLine, executionProperties, userProperties ); MavenExecutionRequest request = new DefaultMavenExecutionRequest() .setBaseDirectory( baseDirectory ) .setGoals( goals ) .setProperties( executionProperties ) // optional .setUserProperties( userProperties ) // optional .setReactorFailureBehavior( reactorFailureBehaviour ) // default: fail fast .setRecursive( recursive ) // default: true .setUseReactor( useReactor ) // default: false .setShowErrors( showErrors ) // default: false .setInteractiveMode( interactive ) // default: false .setOffline( offline ) // default: false .setUsePluginUpdateOverride( pluginUpdateOverride ) .addActiveProfiles( activeProfiles ) // optional .addInactiveProfiles( inactiveProfiles ) // optional .setLoggingLevel( loggingLevel ) // default: info .setTransferListener( transferListener ) // default: batch mode which goes along with interactive .setUpdateSnapshots( updateSnapshots ) // default: false .setNoSnapshotUpdates( noSnapshotUpdates ) // default: false .setGlobalChecksumPolicy( globalChecksumPolicy ); // default: warn if ( alternatePomFile != null ) { request.setPom( new File( alternatePomFile ) ); System.out.println( "Request pom set to: " + request.getPom() ); } return request; }
diff --git a/JsTestDriver/src-test/com/google/jstestdriver/ConfigurationParserTest.java b/JsTestDriver/src-test/com/google/jstestdriver/ConfigurationParserTest.java index 52fbc65..8b88e7e 100644 --- a/JsTestDriver/src-test/com/google/jstestdriver/ConfigurationParserTest.java +++ b/JsTestDriver/src-test/com/google/jstestdriver/ConfigurationParserTest.java @@ -1,75 +1,75 @@ /* * Copyright 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.jstestdriver; import junit.framework.TestCase; import java.io.ByteArrayInputStream; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Set; /** * @author [email protected] (Jeremie Lenfant-Engelmann) */ public class ConfigurationParserTest extends TestCase { public void testParseConfigFileAndHaveListOfFiles() throws Exception { File tmpDir = File.createTempFile("test", "JsTestDriver", new File(System.getProperty("java.io.tmpdir"))); tmpDir.delete(); tmpDir.mkdir(); tmpDir.deleteOnExit(); File codeDir = new File(tmpDir, "code"); File testDir = new File(tmpDir, "test"); codeDir.mkdir(); codeDir.deleteOnExit(); testDir.mkdir(); testDir.deleteOnExit(); File code = new File(codeDir, "code.js"); File code2 = new File(codeDir, "code2.js"); File test = new File(testDir, "test.js"); File test2 = new File(testDir, "test2.js"); File test3 = new File(testDir, "test3.js"); code.createNewFile(); code.deleteOnExit(); code2.createNewFile(); code2.deleteOnExit(); test.createNewFile(); test.deleteOnExit(); test2.createNewFile(); test2.deleteOnExit(); test3.createNewFile(); test3.deleteOnExit(); ConfigurationParser parser = new ConfigurationParser(tmpDir); String configFile = "load:\n - code/*.js\n - test/*.js\nexclude:\n" + " - code/code2.js\n - test/test2.js"; ByteArrayInputStream bais = new ByteArrayInputStream(configFile.getBytes()); parser.parse(bais); Set<String> files = parser.getFilesList(); List<String> listFiles = new ArrayList<String>(files); assertEquals(3, files.size()); - assertEquals("code/code.js", listFiles.get(0)); - assertEquals("test/test.js", listFiles.get(1)); - assertEquals("test/test3.js", listFiles.get(2)); + assertTrue(listFiles.get(0).endsWith("code/code.js")); + assertTrue(listFiles.get(1).endsWith("test/test.js")); + assertTrue(listFiles.get(2).endsWith("test/test3.js")); } }
true
true
public void testParseConfigFileAndHaveListOfFiles() throws Exception { File tmpDir = File.createTempFile("test", "JsTestDriver", new File(System.getProperty("java.io.tmpdir"))); tmpDir.delete(); tmpDir.mkdir(); tmpDir.deleteOnExit(); File codeDir = new File(tmpDir, "code"); File testDir = new File(tmpDir, "test"); codeDir.mkdir(); codeDir.deleteOnExit(); testDir.mkdir(); testDir.deleteOnExit(); File code = new File(codeDir, "code.js"); File code2 = new File(codeDir, "code2.js"); File test = new File(testDir, "test.js"); File test2 = new File(testDir, "test2.js"); File test3 = new File(testDir, "test3.js"); code.createNewFile(); code.deleteOnExit(); code2.createNewFile(); code2.deleteOnExit(); test.createNewFile(); test.deleteOnExit(); test2.createNewFile(); test2.deleteOnExit(); test3.createNewFile(); test3.deleteOnExit(); ConfigurationParser parser = new ConfigurationParser(tmpDir); String configFile = "load:\n - code/*.js\n - test/*.js\nexclude:\n" + " - code/code2.js\n - test/test2.js"; ByteArrayInputStream bais = new ByteArrayInputStream(configFile.getBytes()); parser.parse(bais); Set<String> files = parser.getFilesList(); List<String> listFiles = new ArrayList<String>(files); assertEquals(3, files.size()); assertEquals("code/code.js", listFiles.get(0)); assertEquals("test/test.js", listFiles.get(1)); assertEquals("test/test3.js", listFiles.get(2)); }
public void testParseConfigFileAndHaveListOfFiles() throws Exception { File tmpDir = File.createTempFile("test", "JsTestDriver", new File(System.getProperty("java.io.tmpdir"))); tmpDir.delete(); tmpDir.mkdir(); tmpDir.deleteOnExit(); File codeDir = new File(tmpDir, "code"); File testDir = new File(tmpDir, "test"); codeDir.mkdir(); codeDir.deleteOnExit(); testDir.mkdir(); testDir.deleteOnExit(); File code = new File(codeDir, "code.js"); File code2 = new File(codeDir, "code2.js"); File test = new File(testDir, "test.js"); File test2 = new File(testDir, "test2.js"); File test3 = new File(testDir, "test3.js"); code.createNewFile(); code.deleteOnExit(); code2.createNewFile(); code2.deleteOnExit(); test.createNewFile(); test.deleteOnExit(); test2.createNewFile(); test2.deleteOnExit(); test3.createNewFile(); test3.deleteOnExit(); ConfigurationParser parser = new ConfigurationParser(tmpDir); String configFile = "load:\n - code/*.js\n - test/*.js\nexclude:\n" + " - code/code2.js\n - test/test2.js"; ByteArrayInputStream bais = new ByteArrayInputStream(configFile.getBytes()); parser.parse(bais); Set<String> files = parser.getFilesList(); List<String> listFiles = new ArrayList<String>(files); assertEquals(3, files.size()); assertTrue(listFiles.get(0).endsWith("code/code.js")); assertTrue(listFiles.get(1).endsWith("test/test.js")); assertTrue(listFiles.get(2).endsWith("test/test3.js")); }
diff --git a/framework/src/play/data/binding/DateBinder.java b/framework/src/play/data/binding/DateBinder.java index a44b8ae1..4bbea7d9 100644 --- a/framework/src/play/data/binding/DateBinder.java +++ b/framework/src/play/data/binding/DateBinder.java @@ -1,67 +1,67 @@ package play.data.binding; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; /** * Binder that support Date class. */ public class DateBinder implements SupportedType<Date> { public Date bind(String value) throws Exception { return AlternativeDateFormat.getDefaultFormatter().parse(value); } public static class AlternativeDateFormat { Locale locale; List<SimpleDateFormat> formats = new ArrayList<SimpleDateFormat>(); public AlternativeDateFormat(Locale locale, String... alternativeFormats) { super(); this.locale = locale; setFormats(alternativeFormats); } public void setFormats(String... alternativeFormats) { for (String format : alternativeFormats) { formats.add(new SimpleDateFormat(format, locale)); } } public Date parse(String source) throws ParseException { for (SimpleDateFormat dateFormat : formats) { if (source.length() == dateFormat.toPattern().replace("\'", "").length()) { try { return dateFormat.parse(source); } catch (ParseException ex) { } } } throw new ParseException("Date format not understood", 0); } static ThreadLocal<AlternativeDateFormat> dateformat = new ThreadLocal<AlternativeDateFormat>(); public static AlternativeDateFormat getDefaultFormatter() { if (dateformat.get() == null) { dateformat.set(new AlternativeDateFormat(Locale.US, - "yyyy-MM-dd'T'hh:mm:ss'Z'", // ISO8601 + timezone - "yyyy-MM-dd'T'hh:mm:ss", // ISO8601 + "yyyy-MM-dd'T'HH:mm:ss'Z'", // ISO8601 + timezone + "yyyy-MM-dd'T'HH:mm:ss", // ISO8601 "yyyy-MM-dd", - "yyyyMMdd'T'hhmmss", - "yyyyMMddhhmmss", + "yyyyMMdd'T'HHmmss", + "yyyyMMddHHmmss", "dd'/'MM'/'yyyy", "dd-MM-yyyy", "ddMMyyyy", "MMddyy", "MM-dd-yy", "MM'/'dd'/'yy")); } return dateformat.get(); } } }
false
true
public static AlternativeDateFormat getDefaultFormatter() { if (dateformat.get() == null) { dateformat.set(new AlternativeDateFormat(Locale.US, "yyyy-MM-dd'T'hh:mm:ss'Z'", // ISO8601 + timezone "yyyy-MM-dd'T'hh:mm:ss", // ISO8601 "yyyy-MM-dd", "yyyyMMdd'T'hhmmss", "yyyyMMddhhmmss", "dd'/'MM'/'yyyy", "dd-MM-yyyy", "ddMMyyyy", "MMddyy", "MM-dd-yy", "MM'/'dd'/'yy")); } return dateformat.get(); }
public static AlternativeDateFormat getDefaultFormatter() { if (dateformat.get() == null) { dateformat.set(new AlternativeDateFormat(Locale.US, "yyyy-MM-dd'T'HH:mm:ss'Z'", // ISO8601 + timezone "yyyy-MM-dd'T'HH:mm:ss", // ISO8601 "yyyy-MM-dd", "yyyyMMdd'T'HHmmss", "yyyyMMddHHmmss", "dd'/'MM'/'yyyy", "dd-MM-yyyy", "ddMMyyyy", "MMddyy", "MM-dd-yy", "MM'/'dd'/'yy")); } return dateformat.get(); }
diff --git a/src/nu/validator/htmlparser/impl/TreeBuilder.java b/src/nu/validator/htmlparser/impl/TreeBuilder.java index 35138ba..24dc049 100644 --- a/src/nu/validator/htmlparser/impl/TreeBuilder.java +++ b/src/nu/validator/htmlparser/impl/TreeBuilder.java @@ -1,5647 +1,5653 @@ /* * Copyright (c) 2007 Henri Sivonen * Copyright (c) 2007-2010 Mozilla Foundation * Portions of comments Copyright 2004-2008 Apple Computer, Inc., Mozilla * Foundation, and Opera Software ASA. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /* * The comments following this one that use the same comment syntax as this * comment are quotes from the WHATWG HTML 5 spec as of 27 June 2007 * amended as of June 28 2007. * That document came with this statement: * "© Copyright 2004-2007 Apple Computer, Inc., Mozilla Foundation, and * Opera Software ASA. You are granted a license to use, reproduce and * create derivative works of this document." */ package nu.validator.htmlparser.impl; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import nu.validator.htmlparser.annotation.Auto; import nu.validator.htmlparser.annotation.Const; import nu.validator.htmlparser.annotation.IdType; import nu.validator.htmlparser.annotation.Inline; import nu.validator.htmlparser.annotation.Literal; import nu.validator.htmlparser.annotation.Local; import nu.validator.htmlparser.annotation.NoLength; import nu.validator.htmlparser.annotation.NsUri; import nu.validator.htmlparser.common.DoctypeExpectation; import nu.validator.htmlparser.common.DocumentMode; import nu.validator.htmlparser.common.DocumentModeHandler; import nu.validator.htmlparser.common.Interner; import nu.validator.htmlparser.common.TokenHandler; import nu.validator.htmlparser.common.XmlViolationPolicy; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public abstract class TreeBuilder<T> implements TokenHandler, TreeBuilderState<T> { /** * Array version of U+FFFD. */ private static final @NoLength char[] REPLACEMENT_CHARACTER = { '\uFFFD' }; // Start dispatch groups final static int OTHER = 0; final static int A = 1; final static int BASE = 2; final static int BODY = 3; final static int BR = 4; final static int BUTTON = 5; final static int CAPTION = 6; final static int COL = 7; final static int COLGROUP = 8; final static int FORM = 9; final static int FRAME = 10; final static int FRAMESET = 11; final static int IMAGE = 12; final static int INPUT = 13; final static int ISINDEX = 14; final static int LI = 15; final static int LINK_OR_BASEFONT_OR_BGSOUND = 16; final static int MATH = 17; final static int META = 18; final static int SVG = 19; final static int HEAD = 20; final static int HR = 22; final static int HTML = 23; final static int NOBR = 24; final static int NOFRAMES = 25; final static int NOSCRIPT = 26; final static int OPTGROUP = 27; final static int OPTION = 28; final static int P = 29; final static int PLAINTEXT = 30; final static int SCRIPT = 31; final static int SELECT = 32; final static int STYLE = 33; final static int TABLE = 34; final static int TEXTAREA = 35; final static int TITLE = 36; final static int TR = 37; final static int XMP = 38; final static int TBODY_OR_THEAD_OR_TFOOT = 39; final static int TD_OR_TH = 40; final static int DD_OR_DT = 41; final static int H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6 = 42; final static int MARQUEE_OR_APPLET = 43; final static int PRE_OR_LISTING = 44; final static int B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U = 45; final static int UL_OR_OL_OR_DL = 46; final static int IFRAME = 47; final static int EMBED_OR_IMG = 48; final static int AREA_OR_WBR = 49; final static int DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU = 50; final static int ADDRESS_OR_ARTICLE_OR_ASIDE_OR_DETAILS_OR_DIR_OR_FIGCAPTION_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_HGROUP_OR_NAV_OR_SECTION_OR_SUMMARY = 51; final static int RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR = 52; final static int RT_OR_RP = 53; final static int COMMAND = 54; final static int PARAM_OR_SOURCE = 55; final static int MGLYPH_OR_MALIGNMARK = 56; final static int MI_MO_MN_MS_MTEXT = 57; final static int ANNOTATION_XML = 58; final static int FOREIGNOBJECT_OR_DESC = 59; final static int NOEMBED = 60; final static int FIELDSET = 61; final static int OUTPUT_OR_LABEL = 62; final static int OBJECT = 63; final static int FONT = 64; final static int KEYGEN = 65; // start insertion modes private static final int INITIAL = 0; private static final int BEFORE_HTML = 1; private static final int BEFORE_HEAD = 2; private static final int IN_HEAD = 3; private static final int IN_HEAD_NOSCRIPT = 4; private static final int AFTER_HEAD = 5; private static final int IN_BODY = 6; private static final int IN_TABLE = 7; private static final int IN_CAPTION = 8; private static final int IN_COLUMN_GROUP = 9; private static final int IN_TABLE_BODY = 10; private static final int IN_ROW = 11; private static final int IN_CELL = 12; private static final int IN_SELECT = 13; private static final int IN_SELECT_IN_TABLE = 14; private static final int AFTER_BODY = 15; private static final int IN_FRAMESET = 16; private static final int AFTER_FRAMESET = 17; private static final int AFTER_AFTER_BODY = 18; private static final int AFTER_AFTER_FRAMESET = 19; private static final int TEXT = 20; private static final int FRAMESET_OK = 21; // start charset states private static final int CHARSET_INITIAL = 0; private static final int CHARSET_C = 1; private static final int CHARSET_H = 2; private static final int CHARSET_A = 3; private static final int CHARSET_R = 4; private static final int CHARSET_S = 5; private static final int CHARSET_E = 6; private static final int CHARSET_T = 7; private static final int CHARSET_EQUALS = 8; private static final int CHARSET_SINGLE_QUOTED = 9; private static final int CHARSET_DOUBLE_QUOTED = 10; private static final int CHARSET_UNQUOTED = 11; // end pseudo enums // [NOCPP[ private final static String[] HTML4_PUBLIC_IDS = { "-//W3C//DTD HTML 4.0 Frameset//EN", "-//W3C//DTD HTML 4.0 Transitional//EN", "-//W3C//DTD HTML 4.0//EN", "-//W3C//DTD HTML 4.01 Frameset//EN", "-//W3C//DTD HTML 4.01 Transitional//EN", "-//W3C//DTD HTML 4.01//EN" }; // ]NOCPP] @Literal private final static String[] QUIRKY_PUBLIC_IDS = { "+//silmaril//dtd html pro v0r11 19970101//", "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", "-//as//dtd html 3.0 aswedit + extensions//", "-//ietf//dtd html 2.0 level 1//", "-//ietf//dtd html 2.0 level 2//", "-//ietf//dtd html 2.0 strict level 1//", "-//ietf//dtd html 2.0 strict level 2//", "-//ietf//dtd html 2.0 strict//", "-//ietf//dtd html 2.0//", "-//ietf//dtd html 2.1e//", "-//ietf//dtd html 3.0//", "-//ietf//dtd html 3.2 final//", "-//ietf//dtd html 3.2//", "-//ietf//dtd html 3//", "-//ietf//dtd html level 0//", "-//ietf//dtd html level 1//", "-//ietf//dtd html level 2//", "-//ietf//dtd html level 3//", "-//ietf//dtd html strict level 0//", "-//ietf//dtd html strict level 1//", "-//ietf//dtd html strict level 2//", "-//ietf//dtd html strict level 3//", "-//ietf//dtd html strict//", "-//ietf//dtd html//", "-//metrius//dtd metrius presentational//", "-//microsoft//dtd internet explorer 2.0 html strict//", "-//microsoft//dtd internet explorer 2.0 html//", "-//microsoft//dtd internet explorer 2.0 tables//", "-//microsoft//dtd internet explorer 3.0 html strict//", "-//microsoft//dtd internet explorer 3.0 html//", "-//microsoft//dtd internet explorer 3.0 tables//", "-//netscape comm. corp.//dtd html//", "-//netscape comm. corp.//dtd strict html//", "-//o'reilly and associates//dtd html 2.0//", "-//o'reilly and associates//dtd html extended 1.0//", "-//o'reilly and associates//dtd html extended relaxed 1.0//", "-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//", "-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//", "-//spyglass//dtd html 2.0 extended//", "-//sq//dtd html 2.0 hotmetal + extensions//", "-//sun microsystems corp.//dtd hotjava html//", "-//sun microsystems corp.//dtd hotjava strict html//", "-//w3c//dtd html 3 1995-03-24//", "-//w3c//dtd html 3.2 draft//", "-//w3c//dtd html 3.2 final//", "-//w3c//dtd html 3.2//", "-//w3c//dtd html 3.2s draft//", "-//w3c//dtd html 4.0 frameset//", "-//w3c//dtd html 4.0 transitional//", "-//w3c//dtd html experimental 19960712//", "-//w3c//dtd html experimental 970421//", "-//w3c//dtd w3 html//", "-//w3o//dtd w3 html 3.0//", "-//webtechs//dtd mozilla html 2.0//", "-//webtechs//dtd mozilla html//" }; private static final int NOT_FOUND_ON_STACK = Integer.MAX_VALUE; // [NOCPP[ private static final @Local String HTML_LOCAL = "html"; // ]NOCPP] private int mode = INITIAL; private int originalMode = INITIAL; /** * Used only when moving back to IN_BODY. */ private boolean framesetOk = true; private boolean inForeign = false; protected Tokenizer tokenizer; // [NOCPP[ protected ErrorHandler errorHandler; private DocumentModeHandler documentModeHandler; private DoctypeExpectation doctypeExpectation = DoctypeExpectation.HTML; // ]NOCPP] private boolean scriptingEnabled = false; private boolean needToDropLF; // [NOCPP[ private boolean wantingComments; // ]NOCPP] private boolean fragment; private @Local String contextName; private @NsUri String contextNamespace; private T contextNode; private @Auto StackNode<T>[] stack; private int currentPtr = -1; private @Auto StackNode<T>[] listOfActiveFormattingElements; private int listPtr = -1; private T formPointer; private T headPointer; /** * Used to work around Gecko limitations. Not used in Java. */ private T deepTreeSurrogateParent; protected @Auto char[] charBuffer; protected int charBufferLen = 0; private boolean quirks = false; // [NOCPP[ private boolean reportingDoctype = true; private XmlViolationPolicy namePolicy = XmlViolationPolicy.ALTER_INFOSET; private final Map<String, LocatorImpl> idLocations = new HashMap<String, LocatorImpl>(); private boolean html4; // ]NOCPP] protected TreeBuilder() { fragment = false; } /** * Reports an condition that would make the infoset incompatible with XML * 1.0 as fatal. * * @throws SAXException * @throws SAXParseException */ protected void fatal() throws SAXException { } // [NOCPP[ protected final void fatal(Exception e) throws SAXException { SAXParseException spe = new SAXParseException(e.getMessage(), tokenizer, e); if (errorHandler != null) { errorHandler.fatalError(spe); } throw spe; } final void fatal(String s) throws SAXException { SAXParseException spe = new SAXParseException(s, tokenizer); if (errorHandler != null) { errorHandler.fatalError(spe); } throw spe; } // ]NOCPP] /** * Reports a Parse Error. * * @param message * the message * @throws SAXException */ final void err(String message) throws SAXException { // [NOCPP[ if (errorHandler == null) { return; } errNoCheck(message); // ]NOCPP] } /** * Reports a Parse Error without checking if an error handler is present. * * @param message * the message * @throws SAXException */ final void errNoCheck(String message) throws SAXException { // [NOCPP[ SAXParseException spe = new SAXParseException(message, tokenizer); errorHandler.error(spe); // ]NOCPP] } /** * Reports a warning * * @param message * the message * @throws SAXException */ final void warn(String message) throws SAXException { // [NOCPP[ if (errorHandler == null) { return; } SAXParseException spe = new SAXParseException(message, tokenizer); errorHandler.warning(spe); // ]NOCPP] } @SuppressWarnings("unchecked") public final void startTokenization(Tokenizer self) throws SAXException { tokenizer = self; stack = new StackNode[64]; listOfActiveFormattingElements = new StackNode[64]; needToDropLF = false; originalMode = INITIAL; currentPtr = -1; listPtr = -1; Portability.releaseElement(formPointer); formPointer = null; Portability.releaseElement(headPointer); headPointer = null; Portability.releaseElement(deepTreeSurrogateParent); deepTreeSurrogateParent = null; // [NOCPP[ html4 = false; idLocations.clear(); wantingComments = wantsComments(); // ]NOCPP] start(fragment); charBufferLen = 0; charBuffer = new char[1024]; framesetOk = true; if (fragment) { T elt; if (contextNode != null) { elt = contextNode; Portability.retainElement(elt); } else { elt = createHtmlElementSetAsRoot(tokenizer.emptyAttributes()); } StackNode<T> node = new StackNode<T>( "http://www.w3.org/1999/xhtml", ElementName.HTML, elt); currentPtr++; stack[currentPtr] = node; resetTheInsertionMode(); if ("title" == contextName || "textarea" == contextName) { tokenizer.setStateAndEndTagExpectation(Tokenizer.RCDATA, contextName); } else if ("style" == contextName || "xmp" == contextName || "iframe" == contextName || "noembed" == contextName || "noframes" == contextName || (scriptingEnabled && "noscript" == contextName)) { tokenizer.setStateAndEndTagExpectation(Tokenizer.RAWTEXT, contextName); } else if ("plaintext" == contextName) { tokenizer.setStateAndEndTagExpectation(Tokenizer.PLAINTEXT, contextName); } else if ("script" == contextName) { tokenizer.setStateAndEndTagExpectation(Tokenizer.SCRIPT_DATA, contextName); } else { tokenizer.setStateAndEndTagExpectation(Tokenizer.DATA, contextName); } Portability.releaseLocal(contextName); contextName = null; Portability.releaseElement(contextNode); contextNode = null; Portability.releaseElement(elt); } else { mode = INITIAL; inForeign = false; } } public final void doctype(@Local String name, String publicIdentifier, String systemIdentifier, boolean forceQuirks) throws SAXException { needToDropLF = false; if (!inForeign) { switch (mode) { case INITIAL: // [NOCPP[ if (reportingDoctype) { // ]NOCPP] String emptyString = Portability.newEmptyString(); appendDoctypeToDocument(name == null ? "" : name, publicIdentifier == null ? emptyString : publicIdentifier, systemIdentifier == null ? emptyString : systemIdentifier); Portability.releaseString(emptyString); // [NOCPP[ } switch (doctypeExpectation) { case HTML: // ]NOCPP] if (isQuirky(name, publicIdentifier, systemIdentifier, forceQuirks)) { err("Quirky doctype. Expected \u201C<!DOCTYPE html>\u201D."); documentModeInternal(DocumentMode.QUIRKS_MODE, publicIdentifier, systemIdentifier, false); } else if (isAlmostStandards(publicIdentifier, systemIdentifier)) { err("Almost standards mode doctype. Expected \u201C<!DOCTYPE html>\u201D."); documentModeInternal( DocumentMode.ALMOST_STANDARDS_MODE, publicIdentifier, systemIdentifier, false); } else { // [NOCPP[ if ((Portability.literalEqualsString( "-//W3C//DTD HTML 4.0//EN", publicIdentifier) && (systemIdentifier == null || Portability.literalEqualsString( "http://www.w3.org/TR/REC-html40/strict.dtd", systemIdentifier))) || (Portability.literalEqualsString( "-//W3C//DTD HTML 4.01//EN", publicIdentifier) && (systemIdentifier == null || Portability.literalEqualsString( "http://www.w3.org/TR/html4/strict.dtd", systemIdentifier))) || (Portability.literalEqualsString( "-//W3C//DTD XHTML 1.0 Strict//EN", publicIdentifier) && Portability.literalEqualsString( "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd", systemIdentifier)) || (Portability.literalEqualsString( "-//W3C//DTD XHTML 1.1//EN", publicIdentifier) && Portability.literalEqualsString( "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd", systemIdentifier)) ) { warn("Obsolete doctype. Expected \u201C<!DOCTYPE html>\u201D."); } else if (!((systemIdentifier == null || Portability.literalEqualsString( "about:legacy-compat", systemIdentifier)) && publicIdentifier == null)) { err("Legacy doctype. Expected \u201C<!DOCTYPE html>\u201D."); } // ]NOCPP] documentModeInternal( DocumentMode.STANDARDS_MODE, publicIdentifier, systemIdentifier, false); } // [NOCPP[ break; case HTML401_STRICT: html4 = true; tokenizer.turnOnAdditionalHtml4Errors(); if (isQuirky(name, publicIdentifier, systemIdentifier, forceQuirks)) { err("Quirky doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); documentModeInternal(DocumentMode.QUIRKS_MODE, publicIdentifier, systemIdentifier, true); } else if (isAlmostStandards(publicIdentifier, systemIdentifier)) { err("Almost standards mode doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); documentModeInternal( DocumentMode.ALMOST_STANDARDS_MODE, publicIdentifier, systemIdentifier, true); } else { if ("-//W3C//DTD HTML 4.01//EN".equals(publicIdentifier)) { if (!"http://www.w3.org/TR/html4/strict.dtd".equals(systemIdentifier)) { warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); } } else { err("The doctype was not the HTML 4.01 Strict doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); } documentModeInternal( DocumentMode.STANDARDS_MODE, publicIdentifier, systemIdentifier, true); } break; case HTML401_TRANSITIONAL: html4 = true; tokenizer.turnOnAdditionalHtml4Errors(); if (isQuirky(name, publicIdentifier, systemIdentifier, forceQuirks)) { err("Quirky doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); documentModeInternal(DocumentMode.QUIRKS_MODE, publicIdentifier, systemIdentifier, true); } else if (isAlmostStandards(publicIdentifier, systemIdentifier)) { if ("-//W3C//DTD HTML 4.01 Transitional//EN".equals(publicIdentifier) && systemIdentifier != null) { if (!"http://www.w3.org/TR/html4/loose.dtd".equals(systemIdentifier)) { warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); } } else { err("The doctype was not a non-quirky HTML 4.01 Transitional doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); } documentModeInternal( DocumentMode.ALMOST_STANDARDS_MODE, publicIdentifier, systemIdentifier, true); } else { err("The doctype was not the HTML 4.01 Transitional doctype. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); documentModeInternal( DocumentMode.STANDARDS_MODE, publicIdentifier, systemIdentifier, true); } break; case AUTO: html4 = isHtml4Doctype(publicIdentifier); if (html4) { tokenizer.turnOnAdditionalHtml4Errors(); } if (isQuirky(name, publicIdentifier, systemIdentifier, forceQuirks)) { err("Quirky doctype. Expected e.g. \u201C<!DOCTYPE html>\u201D."); documentModeInternal(DocumentMode.QUIRKS_MODE, publicIdentifier, systemIdentifier, html4); } else if (isAlmostStandards(publicIdentifier, systemIdentifier)) { if ("-//W3C//DTD HTML 4.01 Transitional//EN".equals(publicIdentifier)) { if (!"http://www.w3.org/TR/html4/loose.dtd".equals(systemIdentifier)) { warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); } } else { err("Almost standards mode doctype. Expected e.g. \u201C<!DOCTYPE html>\u201D."); } documentModeInternal( DocumentMode.ALMOST_STANDARDS_MODE, publicIdentifier, systemIdentifier, html4); } else { if ("-//W3C//DTD HTML 4.01//EN".equals(publicIdentifier)) { if (!"http://www.w3.org/TR/html4/strict.dtd".equals(systemIdentifier)) { warn("The doctype did not contain the system identifier prescribed by the HTML 4.01 specification. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); } } else { if (!(publicIdentifier == null && systemIdentifier == null)) { err("Legacy doctype. Expected e.g. \u201C<!DOCTYPE html>\u201D."); } } documentModeInternal( DocumentMode.STANDARDS_MODE, publicIdentifier, systemIdentifier, html4); } break; case NO_DOCTYPE_ERRORS: if (isQuirky(name, publicIdentifier, systemIdentifier, forceQuirks)) { documentModeInternal(DocumentMode.QUIRKS_MODE, publicIdentifier, systemIdentifier, false); } else if (isAlmostStandards(publicIdentifier, systemIdentifier)) { documentModeInternal( DocumentMode.ALMOST_STANDARDS_MODE, publicIdentifier, systemIdentifier, false); } else { documentModeInternal( DocumentMode.STANDARDS_MODE, publicIdentifier, systemIdentifier, false); } break; } // ]NOCPP] /* * * Then, switch to the root element mode of the tree * construction stage. */ mode = BEFORE_HTML; return; default: break; } } /* * A DOCTYPE token Parse error. */ err("Stray doctype."); /* * Ignore the token. */ return; } // [NOCPP[ private boolean isHtml4Doctype(String publicIdentifier) { if (publicIdentifier != null && (Arrays.binarySearch(TreeBuilder.HTML4_PUBLIC_IDS, publicIdentifier) > -1)) { return true; } return false; } // ]NOCPP] public final void comment(@NoLength char[] buf, int start, int length) throws SAXException { needToDropLF = false; // [NOCPP[ if (!wantingComments) { return; } // ]NOCPP] if (!inForeign) { switch (mode) { case INITIAL: case BEFORE_HTML: case AFTER_AFTER_BODY: case AFTER_AFTER_FRAMESET: /* * A comment token Append a Comment node to the Document * object with the data attribute set to the data given in * the comment token. */ appendCommentToDocument(buf, start, length); return; case AFTER_BODY: /* * A comment token Append a Comment node to the first * element in the stack of open elements (the html element), * with the data attribute set to the data given in the * comment token. */ flushCharacters(); appendComment(stack[0].node, buf, start, length); return; default: break; } } /* * A comment token Append a Comment node to the current node with the * data attribute set to the data given in the comment token. */ flushCharacters(); appendComment(stack[currentPtr].node, buf, start, length); return; } /** * @see nu.validator.htmlparser.common.TokenHandler#characters(char[], int, * int) */ public final void characters(@Const @NoLength char[] buf, int start, int length) throws SAXException { if (needToDropLF) { if (buf[start] == '\n') { start++; length--; if (length == 0) { return; } } needToDropLF = false; } // optimize the most common case switch (mode) { case IN_BODY: case IN_CELL: case IN_CAPTION: if (!inForeign) { reconstructTheActiveFormattingElements(); } // fall through case TEXT: accumulateCharacters(buf, start, length); return; case IN_TABLE: case IN_TABLE_BODY: case IN_ROW: accumulateCharactersForced(buf, start, length); return; default: int end = start + length; charactersloop: for (int i = start; i < end; i++) { switch (buf[i]) { case ' ': case '\t': case '\n': case '\r': case '\u000C': /* * A character token that is one of one of U+0009 * CHARACTER TABULATION, U+000A LINE FEED (LF), * U+000C FORM FEED (FF), or U+0020 SPACE */ switch (mode) { case INITIAL: case BEFORE_HTML: case BEFORE_HEAD: /* * Ignore the token. */ start = i + 1; continue; case IN_HEAD: case IN_HEAD_NOSCRIPT: case AFTER_HEAD: case IN_COLUMN_GROUP: case IN_FRAMESET: case AFTER_FRAMESET: /* * Append the character to the current node. */ continue; case FRAMESET_OK: case IN_BODY: case IN_CELL: case IN_CAPTION: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Reconstruct the active formatting * elements, if any. */ if (!inForeign) { flushCharacters(); reconstructTheActiveFormattingElements(); } /* * Append the token's character to the * current node. */ break charactersloop; case IN_SELECT: case IN_SELECT_IN_TABLE: break charactersloop; case IN_TABLE: case IN_TABLE_BODY: case IN_ROW: accumulateCharactersForced(buf, i, 1); start = i + 1; continue; case AFTER_BODY: case AFTER_AFTER_BODY: case AFTER_AFTER_FRAMESET: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Reconstruct the active formatting * elements, if any. */ flushCharacters(); reconstructTheActiveFormattingElements(); /* * Append the token's character to the * current node. */ continue; } default: /* * A character token that is not one of one of * U+0009 CHARACTER TABULATION, U+000A LINE FEED * (LF), U+000C FORM FEED (FF), or U+0020 SPACE */ switch (mode) { case INITIAL: /* * Parse error. */ // [NOCPP[ switch (doctypeExpectation) { case AUTO: err("Non-space characters found without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D."); break; case HTML: err("Non-space characters found without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D."); break; case HTML401_STRICT: err("Non-space characters found without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); break; case HTML401_TRANSITIONAL: err("Non-space characters found without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); break; case NO_DOCTYPE_ERRORS: } // ]NOCPP] /* * * Set the document to quirks mode. */ documentModeInternal( DocumentMode.QUIRKS_MODE, null, null, false); /* * Then, switch to the root element mode of * the tree construction stage */ mode = BEFORE_HTML; /* * and reprocess the current token. */ i--; continue; case BEFORE_HTML: /* * Create an HTMLElement node with the tag * name html, in the HTML namespace. Append * it to the Document object. */ // No need to flush characters here, // because there's nothing to flush. appendHtmlElementToDocumentAndPush(); /* Switch to the main mode */ mode = BEFORE_HEAD; /* * reprocess the current token. */ i--; continue; case BEFORE_HEAD: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * /Act as if a start tag token with the tag * name "head" and no attributes had been * seen, */ flushCharacters(); appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_HEAD; /* * then reprocess the current token. * * This will result in an empty head element * being generated, with the current token * being reprocessed in the "after head" * insertion mode. */ i--; continue; case IN_HEAD: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Act as if an end tag token with the tag * name "head" had been seen, */ flushCharacters(); pop(); mode = AFTER_HEAD; /* * and reprocess the current token. */ i--; continue; case IN_HEAD_NOSCRIPT: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Parse error. Act as if an end tag with * the tag name "noscript" had been seen */ err("Non-space character inside \u201Cnoscript\u201D inside \u201Chead\u201D."); flushCharacters(); pop(); mode = IN_HEAD; /* * and reprocess the current token. */ i--; continue; case AFTER_HEAD: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Act as if a start tag token with the tag * name "body" and no attributes had been * seen, */ flushCharacters(); appendToCurrentNodeAndPushBodyElement(); mode = FRAMESET_OK; /* * and then reprocess the current token. */ i--; continue; case FRAMESET_OK: framesetOk = false; mode = IN_BODY; i--; continue; case IN_BODY: case IN_CELL: case IN_CAPTION: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Reconstruct the active formatting * elements, if any. */ if (!inForeign) { flushCharacters(); reconstructTheActiveFormattingElements(); } /* * Append the token's character to the * current node. */ break charactersloop; case IN_TABLE: case IN_TABLE_BODY: case IN_ROW: accumulateCharactersForced(buf, i, 1); start = i + 1; continue; case IN_COLUMN_GROUP: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Act as if an end tag with the tag name * "colgroup" had been seen, and then, if * that token wasn't ignored, reprocess the * current token. */ if (currentPtr == 0) { err("Non-space in \u201Ccolgroup\u201D when parsing fragment."); start = i + 1; continue; } flushCharacters(); pop(); mode = IN_TABLE; i--; continue; case IN_SELECT: case IN_SELECT_IN_TABLE: break charactersloop; case AFTER_BODY: err("Non-space character after body."); fatal(); mode = framesetOk ? FRAMESET_OK : IN_BODY; i--; continue; case IN_FRAMESET: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Parse error. */ err("Non-space in \u201Cframeset\u201D."); /* * Ignore the token. */ start = i + 1; continue; case AFTER_FRAMESET: if (start < i) { accumulateCharacters(buf, start, i - start); start = i; } /* * Parse error. */ err("Non-space after \u201Cframeset\u201D."); /* * Ignore the token. */ start = i + 1; continue; case AFTER_AFTER_BODY: /* * Parse error. */ err("Non-space character in page trailer."); /* * Switch back to the main mode and * reprocess the token. */ mode = framesetOk ? FRAMESET_OK : IN_BODY; i--; continue; case AFTER_AFTER_FRAMESET: /* * Parse error. */ err("Non-space character in page trailer."); /* * Switch back to the main mode and * reprocess the token. */ mode = IN_FRAMESET; i--; continue; } } } if (start < end) { accumulateCharacters(buf, start, end - start); } } } /** * @see nu.validator.htmlparser.common.TokenHandler#zeroOriginatingReplacementCharacter() */ public void zeroOriginatingReplacementCharacter() throws SAXException { if (inForeign || mode == TEXT) { characters(REPLACEMENT_CHARACTER, 0, 1); } } public final void eof() throws SAXException { flushCharacters(); eofloop: for (;;) { if (inForeign) { err("End of file in a foreign namespace context."); break eofloop; } switch (mode) { case INITIAL: /* * Parse error. */ // [NOCPP[ switch (doctypeExpectation) { case AUTO: err("End of file seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D."); break; case HTML: err("End of file seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D."); break; case HTML401_STRICT: err("End of file seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); break; case HTML401_TRANSITIONAL: err("End of file seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); break; case NO_DOCTYPE_ERRORS: } // ]NOCPP] /* * * Set the document to quirks mode. */ documentModeInternal(DocumentMode.QUIRKS_MODE, null, null, false); /* * Then, switch to the root element mode of the tree * construction stage */ mode = BEFORE_HTML; /* * and reprocess the current token. */ continue; case BEFORE_HTML: /* * Create an HTMLElement node with the tag name html, in the * HTML namespace. Append it to the Document object. */ appendHtmlElementToDocumentAndPush(); // XXX application cache manifest /* Switch to the main mode */ mode = BEFORE_HEAD; /* * reprocess the current token. */ continue; case BEFORE_HEAD: appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_HEAD; continue; case IN_HEAD: if (errorHandler != null && currentPtr > 1) { err("End of file seen and there were open elements."); } while (currentPtr > 0) { popOnEof(); } mode = AFTER_HEAD; continue; case IN_HEAD_NOSCRIPT: err("End of file seen and there were open elements."); while (currentPtr > 1) { popOnEof(); } mode = IN_HEAD; continue; case AFTER_HEAD: appendToCurrentNodeAndPushBodyElement(); mode = IN_BODY; continue; case IN_COLUMN_GROUP: if (currentPtr == 0) { assert fragment; break eofloop; } else { popOnEof(); mode = IN_TABLE; continue; } case FRAMESET_OK: case IN_CAPTION: case IN_CELL: case IN_BODY: // [NOCPP[ openelementloop: for (int i = currentPtr; i >= 0; i--) { int group = stack[i].group; switch (group) { case DD_OR_DT: case LI: case P: case TBODY_OR_THEAD_OR_TFOOT: case TD_OR_TH: case BODY: case HTML: break; default: err("End of file seen and there were open elements."); break openelementloop; } } // ]NOCPP] break eofloop; case TEXT: err("End of file seen when expecting text or an end tag."); // XXX mark script as already executed if (originalMode == AFTER_HEAD) { popOnEof(); } popOnEof(); mode = originalMode; continue; case IN_TABLE_BODY: case IN_ROW: case IN_TABLE: case IN_SELECT: case IN_SELECT_IN_TABLE: case IN_FRAMESET: if (errorHandler != null && currentPtr > 0) { errNoCheck("End of file seen and there were open elements."); } break eofloop; case AFTER_BODY: case AFTER_FRAMESET: case AFTER_AFTER_BODY: case AFTER_AFTER_FRAMESET: default: // [NOCPP[ if (currentPtr == 0) { // This silliness is here to poison // buggy compiler optimizations in // GWT System.currentTimeMillis(); } // ]NOCPP] break eofloop; } } while (currentPtr > 0) { popOnEof(); } if (!fragment) { popOnEof(); } /* Stop parsing. */ } /** * @see nu.validator.htmlparser.common.TokenHandler#endTokenization() */ public final void endTokenization() throws SAXException { Portability.releaseElement(formPointer); formPointer = null; Portability.releaseElement(headPointer); headPointer = null; Portability.releaseElement(deepTreeSurrogateParent); deepTreeSurrogateParent = null; if (stack != null) { while (currentPtr > -1) { stack[currentPtr].release(); currentPtr--; } stack = null; } if (listOfActiveFormattingElements != null) { while (listPtr > -1) { if (listOfActiveFormattingElements[listPtr] != null) { listOfActiveFormattingElements[listPtr].release(); } listPtr--; } listOfActiveFormattingElements = null; } // [NOCPP[ idLocations.clear(); // ]NOCPP] charBuffer = null; end(); } public final void startTag(ElementName elementName, HtmlAttributes attributes, boolean selfClosing) throws SAXException { flushCharacters(); // [NOCPP[ if (errorHandler != null) { // ID uniqueness @IdType String id = attributes.getId(); if (id != null) { LocatorImpl oldLoc = idLocations.get(id); if (oldLoc != null) { err("Duplicate ID \u201C" + id + "\u201D."); errorHandler.warning(new SAXParseException( "The first occurrence of ID \u201C" + id + "\u201D was here.", oldLoc)); } else { idLocations.put(id, new LocatorImpl(tokenizer)); } } } // ]NOCPP] int eltPos; needToDropLF = false; boolean needsPostProcessing = false; starttagloop: for (;;) { int group = elementName.group; @Local String name = elementName.name; if (inForeign) { StackNode<T> currentNode = stack[currentPtr]; @NsUri String currNs = currentNode.ns; int currGroup = currentNode.group; if (("http://www.w3.org/1999/xhtml" == currNs) || ("http://www.w3.org/1998/Math/MathML" == currNs && ((MGLYPH_OR_MALIGNMARK != group && MI_MO_MN_MS_MTEXT == currGroup) || (SVG == group && ANNOTATION_XML == currGroup))) || ("http://www.w3.org/2000/svg" == currNs && (TITLE == currGroup || (FOREIGNOBJECT_OR_DESC == currGroup)))) { needsPostProcessing = true; // fall through to non-foreign behavior } else { switch (group) { case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U: case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU: case BODY: case BR: case RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR: case DD_OR_DT: case UL_OR_OL_OR_DL: case EMBED_OR_IMG: case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: case HEAD: case HR: case LI: case META: case NOBR: case P: case PRE_OR_LISTING: case TABLE: err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (!isSpecialParentInForeign(stack[currentPtr])) { pop(); } if (!hasForeignInScope()) { inForeign = false; } continue starttagloop; case FONT: if (attributes.contains(AttributeName.COLOR) || attributes.contains(AttributeName.FACE) || attributes.contains(AttributeName.SIZE)) { err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (!isSpecialParentInForeign(stack[currentPtr])) { pop(); } if (!hasForeignInScope()) { inForeign = false; } continue starttagloop; } // else fall thru default: if ("http://www.w3.org/2000/svg" == currNs) { attributes.adjustForSvg(); if (selfClosing) { appendVoidElementToCurrentMayFosterCamelCase( currNs, elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFosterCamelCase( currNs, elementName, attributes); } attributes = null; // CPP break starttagloop; } else { attributes.adjustForMath(); if (selfClosing) { appendVoidElementToCurrentMayFoster( currNs, elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFosterNoScoping( currNs, elementName, attributes); } attributes = null; // CPP break starttagloop; } } // switch } // foreignObject / annotation-xml } switch (mode) { case IN_TABLE_BODY: switch (group) { case TR: clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot()); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_ROW; attributes = null; // CPP break starttagloop; case TD_OR_TH: err("\u201C" + name + "\u201D start tag in table body."); clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot()); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.TR, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_ROW; continue; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: eltPos = findLastInTableScopeOrRootTbodyTheadTfoot(); if (eltPos == 0) { err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } else { clearStackBackTo(eltPos); pop(); mode = IN_TABLE; continue; } default: // fall through to IN_TABLE } case IN_ROW: switch (group) { case TD_OR_TH: clearStackBackTo(findLastOrRoot(TreeBuilder.TR)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_CELL; insertMarker(); attributes = null; // CPP break starttagloop; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: eltPos = findLastOrRoot(TreeBuilder.TR); if (eltPos == 0) { assert fragment; err("No table row to close."); break starttagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE_BODY; continue; default: // fall through to IN_TABLE } case IN_TABLE: intableloop: for (;;) { switch (group) { case CAPTION: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); insertMarker(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_CAPTION; attributes = null; // CPP break starttagloop; case COLGROUP: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_COLUMN_GROUP; attributes = null; // CPP break starttagloop; case COL: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.COLGROUP, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_COLUMN_GROUP; continue starttagloop; case TBODY_OR_THEAD_OR_TFOOT: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_TABLE_BODY; attributes = null; // CPP break starttagloop; case TR: case TD_OR_TH: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.TBODY, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_TABLE_BODY; continue starttagloop; case TABLE: err("Start tag for \u201Ctable\u201D seen but the previous \u201Ctable\u201D is still open."); eltPos = findLastInTableScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; } generateImpliedEndTags(); // XXX is the next if dead code? if (errorHandler != null && !isCurrent("table")) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue starttagloop; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case INPUT: if (!Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "hidden", attributes.getValue(AttributeName.TYPE))) { break intableloop; } appendVoidElementToCurrent( "http://www.w3.org/1999/xhtml", name, attributes, formPointer); selfClosing = false; attributes = null; // CPP break starttagloop; case FORM: if (formPointer != null) { err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag."); break starttagloop; } else { err("Start tag \u201Cform\u201D seen in \u201Ctable\u201D."); appendVoidFormToCurrent(attributes); attributes = null; // CPP break starttagloop; } default: err("Start tag \u201C" + name + "\u201D seen in \u201Ctable\u201D."); // fall through to IN_BODY break intableloop; } } case IN_CAPTION: switch (group) { case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: err("Stray \u201C" + name + "\u201D start tag in \u201Ccaption\u201D."); eltPos = findLastInTableScope("caption"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { break starttagloop; } generateImpliedEndTags(); if (errorHandler != null && currentPtr != eltPos) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); mode = IN_TABLE; continue; default: // fall through to IN_BODY } case IN_CELL: switch (group) { case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: eltPos = findLastInTableScopeTdTh(); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("No cell to close."); break starttagloop; } else { closeTheCell(eltPos); continue; } default: // fall through to IN_BODY } case FRAMESET_OK: switch (group) { case FRAMESET: if (mode == FRAMESET_OK) { if (currentPtr == 0 || stack[1].group != BODY) { assert fragment; err("Stray \u201Cframeset\u201D start tag."); break starttagloop; } else { err("\u201Cframeset\u201D start tag seen."); detachFromParent(stack[1].node); while (currentPtr > 0) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_FRAMESET; attributes = null; // CPP break starttagloop; } } else { err("Stray \u201Cframeset\u201D start tag."); break starttagloop; } // NOT falling through! case PRE_OR_LISTING: case LI: case DD_OR_DT: case BUTTON: case MARQUEE_OR_APPLET: case OBJECT: case TABLE: case AREA_OR_WBR: case BR: case EMBED_OR_IMG: case INPUT: case KEYGEN: case HR: case TEXTAREA: case XMP: case IFRAME: case SELECT: if (mode == FRAMESET_OK && !(group == INPUT && Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "hidden", attributes.getValue(AttributeName.TYPE)))) { framesetOk = false; mode = IN_BODY; } // fall through to IN_BODY default: // fall through to IN_BODY } case IN_BODY: inbodyloop: for (;;) { switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BASE: case LINK_OR_BASEFONT_OR_BGSOUND: case META: case STYLE: case SCRIPT: case TITLE: case COMMAND: // Fall through to IN_HEAD break inbodyloop; case BODY: err("\u201Cbody\u201D start tag found but the \u201Cbody\u201D element is already open."); if (addAttributesToBody(attributes)) { attributes = null; // CPP } break starttagloop; case P: case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU: case UL_OR_OL_OR_DL: case ADDRESS_OR_ARTICLE_OR_ASIDE_OR_DETAILS_OR_DIR_OR_FIGCAPTION_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_HGROUP_OR_NAV_OR_SECTION_OR_SUMMARY: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: implicitlyCloseP(); if (stack[currentPtr].group == H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) { err("Heading cannot be a child of another heading."); pop(); } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case FIELDSET: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; case PRE_OR_LISTING: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); needToDropLF = true; attributes = null; // CPP break starttagloop; case FORM: if (formPointer != null) { err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag."); break starttagloop; } else { implicitlyCloseP(); appendToCurrentNodeAndPushFormElementMayFoster(attributes); attributes = null; // CPP break starttagloop; } case LI: case DD_OR_DT: eltPos = currentPtr; for (;;) { StackNode<T> node = stack[eltPos]; // weak // ref if (node.group == group) { // LI or // DD_OR_DT generateImpliedEndTagsExceptFor(node.name); if (errorHandler != null && eltPos != currentPtr) { errNoCheck("Unclosed elements inside a list."); } while (currentPtr >= eltPos) { pop(); } break; } else if (node.scoping || (node.special && node.name != "p" && node.name != "address" && node.name != "div")) { break; } eltPos--; } implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case PLAINTEXT: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); tokenizer.setStateAndEndTagExpectation( Tokenizer.PLAINTEXT, elementName); attributes = null; // CPP break starttagloop; case A: int activeAPos = findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker("a"); if (activeAPos != -1) { err("An \u201Ca\u201D start tag seen with already an active \u201Ca\u201D element."); StackNode<T> activeA = listOfActiveFormattingElements[activeAPos]; activeA.retain(); adoptionAgencyEndTag("a"); removeFromStack(activeA); activeAPos = findInListOfActiveFormattingElements(activeA); if (activeAPos != -1) { removeFromListOfActiveFormattingElements(activeAPos); } activeA.release(); } reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U: case FONT: reconstructTheActiveFormattingElements(); maybeForgetEarlierDuplicateFormattingElement(elementName.name, attributes); appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case NOBR: reconstructTheActiveFormattingElements(); if (TreeBuilder.NOT_FOUND_ON_STACK != findLastInScope("nobr")) { err("\u201Cnobr\u201D start tag seen when there was an open \u201Cnobr\u201D element in scope."); adoptionAgencyEndTag("nobr"); } appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case BUTTON: eltPos = findLastInScope(name); if (eltPos != TreeBuilder.NOT_FOUND_ON_STACK) { err("\u201Cbutton\u201D start tag seen when there was an open \u201Cbutton\u201D element in scope."); generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201Cbutton\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } continue starttagloop; } else { reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; } case OBJECT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); insertMarker(); attributes = null; // CPP break starttagloop; case MARQUEE_OR_APPLET: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); insertMarker(); attributes = null; // CPP break starttagloop; case TABLE: // The only quirk. Blame Hixie and // Acid2. if (!quirks) { implicitlyCloseP(); } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_TABLE; attributes = null; // CPP break starttagloop; case BR: case EMBED_OR_IMG: case AREA_OR_WBR: reconstructTheActiveFormattingElements(); // FALL THROUGH to PARAM_OR_SOURCE case PARAM_OR_SOURCE: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case HR: implicitlyCloseP(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case IMAGE: err("Saw a start tag \u201Cimage\u201D."); elementName = ElementName.IMG; continue starttagloop; case KEYGEN: case INPUT: reconstructTheActiveFormattingElements(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", name, attributes, formPointer); selfClosing = false; attributes = null; // CPP break starttagloop; case ISINDEX: err("\u201Cisindex\u201D seen."); if (formPointer != null) { break starttagloop; } implicitlyCloseP(); HtmlAttributes formAttrs = new HtmlAttributes(0); int actionIndex = attributes.getIndex(AttributeName.ACTION); if (actionIndex > -1) { formAttrs.addAttribute( AttributeName.ACTION, attributes.getValue(actionIndex) // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); } appendToCurrentNodeAndPushFormElementMayFoster(formAttrs); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", ElementName.HR, HtmlAttributes.EMPTY_ATTRIBUTES); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", ElementName.LABEL, HtmlAttributes.EMPTY_ATTRIBUTES); int promptIndex = attributes.getIndex(AttributeName.PROMPT); if (promptIndex > -1) { @Auto char[] prompt = Portability.newCharArrayFromString(attributes.getValue(promptIndex)); appendCharacters(stack[currentPtr].node, prompt, 0, prompt.length); } else { appendIsindexPrompt(stack[currentPtr].node); } HtmlAttributes inputAttributes = new HtmlAttributes( 0); inputAttributes.addAttribute( AttributeName.NAME, Portability.newStringFromLiteral("isindex") // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); for (int i = 0; i < attributes.getLength(); i++) { AttributeName attributeQName = attributes.getAttributeName(i); if (AttributeName.NAME == attributeQName || AttributeName.PROMPT == attributeQName) { attributes.releaseValue(i); } else if (AttributeName.ACTION != attributeQName) { inputAttributes.addAttribute( attributeQName, attributes.getValue(i) // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); } } attributes.clearWithoutReleasingContents(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", "input", inputAttributes, formPointer); pop(); // label appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", ElementName.HR, HtmlAttributes.EMPTY_ATTRIBUTES); pop(); // form selfClosing = false; // Portability.delete(formAttrs); // Portability.delete(inputAttributes); // Don't delete attributes, they are deleted // later break starttagloop; case TEXTAREA: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); originalMode = mode; mode = TEXT; needToDropLF = true; attributes = null; // CPP break starttagloop; case XMP: implicitlyCloseP(); reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case NOSCRIPT: if (!scriptingEnabled) { reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; } else { // fall through } case NOFRAMES: case IFRAME: case NOEMBED: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case SELECT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); switch (mode) { case IN_TABLE: case IN_CAPTION: case IN_COLUMN_GROUP: case IN_TABLE_BODY: case IN_ROW: case IN_CELL: mode = IN_SELECT_IN_TABLE; break; default: mode = IN_SELECT; break; } attributes = null; // CPP break starttagloop; case OPTGROUP: case OPTION: /* * If the stack of open elements has an option * element in scope, then act as if an end tag * with the tag name "option" had been seen. */ if (findLastInScope("option") != TreeBuilder.NOT_FOUND_ON_STACK) { optionendtagloop: for (;;) { if (isCurrent("option")) { pop(); break optionendtagloop; } eltPos = currentPtr; for (;;) { if (stack[eltPos].name == "option") { generateImpliedEndTags(); if (errorHandler != null && !isCurrent("option")) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } break optionendtagloop; } eltPos--; } } } /* * Reconstruct the active formatting elements, * if any. */ reconstructTheActiveFormattingElements(); /* * Insert an HTML element for the token. */ appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case RT_OR_RP: /* * If the stack of open elements has a ruby * element in scope, then generate implied end * tags. If the current node is not then a ruby * element, this is a parse error; pop all the * nodes from the current node up to the node * immediately before the bottommost ruby * element on the stack of open elements. * * Insert an HTML element for the token. */ eltPos = findLastInScope("ruby"); if (eltPos != NOT_FOUND_ON_STACK) { generateImpliedEndTags(); } if (eltPos != currentPtr) { - err("Unclosed children in \u201Cruby\u201D."); + if (eltPos != NOT_FOUND_ON_STACK) { + err("Start tag \u201C" + + name + + "\u201D seen without a \u201Cruby\u201D element being open."); + } else { + err("Unclosed children in \u201Cruby\u201D."); + } while (currentPtr > eltPos) { pop(); } } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case MATH: reconstructTheActiveFormattingElements(); attributes.adjustForMath(); if (selfClosing) { appendVoidElementToCurrentMayFoster( "http://www.w3.org/1998/Math/MathML", elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1998/Math/MathML", elementName, attributes); inForeign = true; } attributes = null; // CPP break starttagloop; case SVG: reconstructTheActiveFormattingElements(); attributes.adjustForSvg(); if (selfClosing) { appendVoidElementToCurrentMayFosterCamelCase( "http://www.w3.org/2000/svg", elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/2000/svg", elementName, attributes); inForeign = true; } attributes = null; // CPP break starttagloop; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: case FRAME: case FRAMESET: case HEAD: err("Stray start tag \u201C" + name + "\u201D."); break starttagloop; case OUTPUT_OR_LABEL: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; default: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; } } case IN_HEAD: inheadloop: for (;;) { switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BASE: case COMMAND: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case META: case LINK_OR_BASEFONT_OR_BGSOUND: // Fall through to IN_HEAD_NOSCRIPT break inheadloop; case TITLE: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); attributes = null; // CPP break starttagloop; case NOSCRIPT: if (scriptingEnabled) { appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_HEAD_NOSCRIPT; } attributes = null; // CPP break starttagloop; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case HEAD: /* Parse error. */ err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open."); /* Ignore the token. */ break starttagloop; default: pop(); mode = AFTER_HEAD; continue starttagloop; } } case IN_HEAD_NOSCRIPT: switch (group) { case HTML: // XXX did Hixie really mean to omit "base" // here? err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case LINK_OR_BASEFONT_OR_BGSOUND: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case META: checkMetaCharset(attributes); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case HEAD: err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open."); break starttagloop; case NOSCRIPT: err("Start tag for \u201Cnoscript\u201D seen when \u201Cnoscript\u201D was already open."); break starttagloop; default: err("Bad start tag in \u201C" + name + "\u201D in \u201Chead\u201D."); pop(); mode = IN_HEAD; continue; } case IN_COLUMN_GROUP: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case COL: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; default: if (currentPtr == 0) { assert fragment; err("Garbage in \u201Ccolgroup\u201D fragment."); break starttagloop; } pop(); mode = IN_TABLE; continue; } case IN_SELECT_IN_TABLE: switch (group) { case CAPTION: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: case TABLE: err("\u201C" + name + "\u201D start tag with \u201Cselect\u201D open."); eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375 } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue; default: // fall through to IN_SELECT } case IN_SELECT: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case OPTION: if (isCurrent("option")) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case OPTGROUP: if (isCurrent("option")) { pop(); } if (isCurrent("optgroup")) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case SELECT: err("\u201Cselect\u201D start tag where end tag expected."); eltPos = findLastInTableScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; err("No \u201Cselect\u201D in table scope."); break starttagloop; } else { while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); break starttagloop; } case INPUT: case TEXTAREA: case KEYGEN: err("\u201C" + name + "\u201D start tag seen in \u201Cselect\2201D."); eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case AFTER_BODY: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; } case IN_FRAMESET: switch (group) { case FRAMESET: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case FRAME: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; default: // fall through to AFTER_FRAMESET } case AFTER_FRAMESET: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case NOFRAMES: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case INITIAL: /* * Parse error. */ // [NOCPP[ switch (doctypeExpectation) { case AUTO: err("Start tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D."); break; case HTML: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D."); break; case HTML401_STRICT: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); break; case HTML401_TRANSITIONAL: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); break; case NO_DOCTYPE_ERRORS: } // ]NOCPP] /* * * Set the document to quirks mode. */ documentModeInternal(DocumentMode.QUIRKS_MODE, null, null, false); /* * Then, switch to the root element mode of the tree * construction stage */ mode = BEFORE_HTML; /* * and reprocess the current token. */ continue; case BEFORE_HTML: switch (group) { case HTML: // optimize error check and streaming SAX by // hoisting // "html" handling here. if (attributes == HtmlAttributes.EMPTY_ATTRIBUTES) { // This has the right magic side effect // that // it // makes attributes in SAX Tree mutable. appendHtmlElementToDocumentAndPush(); } else { appendHtmlElementToDocumentAndPush(attributes); } // XXX application cache should fire here mode = BEFORE_HEAD; attributes = null; // CPP break starttagloop; default: /* * Create an HTMLElement node with the tag name * html, in the HTML namespace. Append it to the * Document object. */ appendHtmlElementToDocumentAndPush(); /* Switch to the main mode */ mode = BEFORE_HEAD; /* * reprocess the current token. */ continue; } case BEFORE_HEAD: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case HEAD: /* * A start tag whose tag name is "head" * * Create an element for the token. * * Set the head element pointer to this new element * node. * * Append the new element to the current node and * push it onto the stack of open elements. */ appendToCurrentNodeAndPushHeadElement(attributes); /* * Change the insertion mode to "in head". */ mode = IN_HEAD; attributes = null; // CPP break starttagloop; default: /* * Any other start tag token * * Act as if a start tag token with the tag name * "head" and no attributes had been seen, */ appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_HEAD; /* * then reprocess the current token. * * This will result in an empty head element being * generated, with the current token being * reprocessed in the "after head" insertion mode. */ continue; } case AFTER_HEAD: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BODY: if (attributes.getLength() == 0) { // This has the right magic side effect // that // it // makes attributes in SAX Tree mutable. appendToCurrentNodeAndPushBodyElement(); } else { appendToCurrentNodeAndPushBodyElement(attributes); } framesetOk = false; mode = IN_BODY; attributes = null; // CPP break starttagloop; case FRAMESET: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_FRAMESET; attributes = null; // CPP break starttagloop; case BASE: err("\u201Cbase\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case LINK_OR_BASEFONT_OR_BGSOUND: err("\u201Clink\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case META: err("\u201Cmeta\u201D element outside \u201Chead\u201D."); checkMetaCharset(attributes); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case SCRIPT: err("\u201Cscript\u201D element between \u201Chead\u201D and \u201Cbody\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: err("\u201C" + name + "\u201D element between \u201Chead\u201D and \u201Cbody\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case TITLE: err("\u201Ctitle\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); attributes = null; // CPP break starttagloop; case HEAD: err("Stray start tag \u201Chead\u201D."); break starttagloop; default: appendToCurrentNodeAndPushBodyElement(); mode = FRAMESET_OK; continue; } case AFTER_AFTER_BODY: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); fatal(); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; } case AFTER_AFTER_FRAMESET: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case NOFRAMES: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case TEXT: assert false; break starttagloop; // Avoid infinite loop if the assertion // fails } } if (needsPostProcessing && inForeign && !hasForeignInScope()) { /* * If, after doing so, the insertion mode is still "in foreign * content", but there is no element in scope that has a namespace * other than the HTML namespace, switch the insertion mode to the * secondary insertion mode. */ inForeign = false; } if (errorHandler != null && selfClosing) { errNoCheck("Self-closing syntax (\u201C/>\u201D) used on a non-void HTML element. Ignoring the slash and treating as a start tag."); } if (attributes != HtmlAttributes.EMPTY_ATTRIBUTES) { Portability.delete(attributes); } } private boolean isSpecialParentInForeign(StackNode<T> stackNode) { @NsUri String ns = stackNode.ns; if ("http://www.w3.org/1999/xhtml" == ns) { return true; } if (ns == "http://www.w3.org/2000/svg") { return stackNode.group == FOREIGNOBJECT_OR_DESC || stackNode.group == TITLE; } assert ns == "http://www.w3.org/1998/Math/MathML" : "Unexpected namespace."; return stackNode.group == MI_MO_MN_MS_MTEXT; } /** * * <p> * C++ memory note: The return value must be released. * * @return * @throws SAXException * @throws StopSniffingException */ public static String extractCharsetFromContent(String attributeValue) { // This is a bit ugly. Converting the string to char array in order to // make the portability layer smaller. int charsetState = CHARSET_INITIAL; int start = -1; int end = -1; @Auto char[] buffer = Portability.newCharArrayFromString(attributeValue); charsetloop: for (int i = 0; i < buffer.length; i++) { char c = buffer[i]; switch (charsetState) { case CHARSET_INITIAL: switch (c) { case 'c': case 'C': charsetState = CHARSET_C; continue; default: continue; } case CHARSET_C: switch (c) { case 'h': case 'H': charsetState = CHARSET_H; continue; default: charsetState = CHARSET_INITIAL; continue; } case CHARSET_H: switch (c) { case 'a': case 'A': charsetState = CHARSET_A; continue; default: charsetState = CHARSET_INITIAL; continue; } case CHARSET_A: switch (c) { case 'r': case 'R': charsetState = CHARSET_R; continue; default: charsetState = CHARSET_INITIAL; continue; } case CHARSET_R: switch (c) { case 's': case 'S': charsetState = CHARSET_S; continue; default: charsetState = CHARSET_INITIAL; continue; } case CHARSET_S: switch (c) { case 'e': case 'E': charsetState = CHARSET_E; continue; default: charsetState = CHARSET_INITIAL; continue; } case CHARSET_E: switch (c) { case 't': case 'T': charsetState = CHARSET_T; continue; default: charsetState = CHARSET_INITIAL; continue; } case CHARSET_T: switch (c) { case '\t': case '\n': case '\u000C': case '\r': case ' ': continue; case '=': charsetState = CHARSET_EQUALS; continue; default: return null; } case CHARSET_EQUALS: switch (c) { case '\t': case '\n': case '\u000C': case '\r': case ' ': continue; case '\'': start = i + 1; charsetState = CHARSET_SINGLE_QUOTED; continue; case '\"': start = i + 1; charsetState = CHARSET_DOUBLE_QUOTED; continue; default: start = i; charsetState = CHARSET_UNQUOTED; continue; } case CHARSET_SINGLE_QUOTED: switch (c) { case '\'': end = i; break charsetloop; default: continue; } case CHARSET_DOUBLE_QUOTED: switch (c) { case '\"': end = i; break charsetloop; default: continue; } case CHARSET_UNQUOTED: switch (c) { case '\t': case '\n': case '\u000C': case '\r': case ' ': case ';': end = i; break charsetloop; default: continue; } } } String charset = null; if (start != -1) { if (end == -1) { end = buffer.length; } charset = Portability.newStringFromBuffer(buffer, start, end - start); } return charset; } private void checkMetaCharset(HtmlAttributes attributes) throws SAXException { String content = attributes.getValue(AttributeName.CONTENT); String internalCharsetLegacy = null; if (content != null) { internalCharsetLegacy = TreeBuilder.extractCharsetFromContent(content); // [NOCPP[ if (errorHandler != null && internalCharsetLegacy != null && !Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "content-type", attributes.getValue(AttributeName.HTTP_EQUIV))) { warn("Attribute \u201Ccontent\u201D would be sniffed as an internal character encoding declaration but there was no matching \u201Chttp-equiv='Content-Type'\u201D attribute."); } // ]NOCPP] } if (internalCharsetLegacy == null) { String internalCharsetHtml5 = attributes.getValue(AttributeName.CHARSET); if (internalCharsetHtml5 != null) { tokenizer.internalEncodingDeclaration(internalCharsetHtml5); requestSuspension(); } } else { tokenizer.internalEncodingDeclaration(internalCharsetLegacy); Portability.releaseString(internalCharsetLegacy); requestSuspension(); } } public final void endTag(ElementName elementName) throws SAXException { flushCharacters(); needToDropLF = false; int eltPos; int group = elementName.group; @Local String name = elementName.name; endtagloop: for (;;) { assert !inForeign || currentPtr >= 0 : "In foreign without a root element?"; if (inForeign && stack[currentPtr].ns != "http://www.w3.org/1999/xhtml") { if (errorHandler != null && stack[currentPtr].name != name) { errNoCheck("End tag \u201C" + name + "\u201D did not match the name of the current open element (\u201C" + stack[currentPtr].popName + "\u201D)."); } eltPos = currentPtr; for (;;) { if (stack[eltPos].name == name) { while (currentPtr >= eltPos) { pop(); } break endtagloop; } if (stack[--eltPos].ns == "http://www.w3.org/1999/xhtml") { break; } } } switch (mode) { case IN_ROW: switch (group) { case TR: eltPos = findLastOrRoot(TreeBuilder.TR); if (eltPos == 0) { assert fragment; err("No table row to close."); break endtagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE_BODY; break endtagloop; case TABLE: eltPos = findLastOrRoot(TreeBuilder.TR); if (eltPos == 0) { assert fragment; err("No table row to close."); break endtagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE_BODY; continue; case TBODY_OR_THEAD_OR_TFOOT: if (findLastInTableScope(name) == TreeBuilder.NOT_FOUND_ON_STACK) { err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } eltPos = findLastOrRoot(TreeBuilder.TR); if (eltPos == 0) { assert fragment; err("No table row to close."); break endtagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE_BODY; continue; case BODY: case CAPTION: case COL: case COLGROUP: case HTML: case TD_OR_TH: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; default: // fall through to IN_TABLE } case IN_TABLE_BODY: switch (group) { case TBODY_OR_THEAD_OR_TFOOT: eltPos = findLastOrRoot(name); if (eltPos == 0) { err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE; break endtagloop; case TABLE: eltPos = findLastInTableScopeOrRootTbodyTheadTfoot(); if (eltPos == 0) { assert fragment; err("Stray end tag \u201Ctable\u201D."); break endtagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE; continue; case BODY: case CAPTION: case COL: case COLGROUP: case HTML: case TD_OR_TH: case TR: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; default: // fall through to IN_TABLE } case IN_TABLE: switch (group) { case TABLE: eltPos = findLast("table"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; err("Stray end tag \u201Ctable\u201D."); break endtagloop; } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); break endtagloop; case BODY: case CAPTION: case COL: case COLGROUP: case HTML: case TBODY_OR_THEAD_OR_TFOOT: case TD_OR_TH: case TR: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; default: err("Stray end tag \u201C" + name + "\u201D."); // fall through to IN_BODY } case IN_CAPTION: switch (group) { case CAPTION: eltPos = findLastInTableScope("caption"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { break endtagloop; } generateImpliedEndTags(); if (errorHandler != null && currentPtr != eltPos) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); mode = IN_TABLE; break endtagloop; case TABLE: err("\u201Ctable\u201D closed but \u201Ccaption\u201D was still open."); eltPos = findLastInTableScope("caption"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { break endtagloop; } generateImpliedEndTags(); if (errorHandler != null && currentPtr != eltPos) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); mode = IN_TABLE; continue; case BODY: case COL: case COLGROUP: case HTML: case TBODY_OR_THEAD_OR_TFOOT: case TD_OR_TH: case TR: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; default: // fall through to IN_BODY } case IN_CELL: switch (group) { case TD_OR_TH: eltPos = findLastInTableScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("Unclosed elements."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); mode = IN_ROW; break endtagloop; case TABLE: case TBODY_OR_THEAD_OR_TFOOT: case TR: if (findLastInTableScope(name) == TreeBuilder.NOT_FOUND_ON_STACK) { err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } closeTheCell(findLastInTableScopeTdTh()); continue; case BODY: case CAPTION: case COL: case COLGROUP: case HTML: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; default: // fall through to IN_BODY } case FRAMESET_OK: case IN_BODY: switch (group) { case BODY: if (!isSecondOnStackBody()) { assert fragment; err("Stray end tag \u201Cbody\u201D."); break endtagloop; } assert currentPtr >= 1; if (errorHandler != null) { uncloseloop1: for (int i = 2; i <= currentPtr; i++) { switch (stack[i].group) { case DD_OR_DT: case LI: case OPTGROUP: case OPTION: // is this possible? case P: case RT_OR_RP: case TD_OR_TH: case TBODY_OR_THEAD_OR_TFOOT: break; default: err("End tag for \u201Cbody\u201D seen but there were unclosed elements."); break uncloseloop1; } } } mode = AFTER_BODY; break endtagloop; case HTML: if (!isSecondOnStackBody()) { assert fragment; err("Stray end tag \u201Chtml\u201D."); break endtagloop; } if (errorHandler != null) { uncloseloop2: for (int i = 0; i <= currentPtr; i++) { switch (stack[i].group) { case DD_OR_DT: case LI: case P: case TBODY_OR_THEAD_OR_TFOOT: case TD_OR_TH: case BODY: case HTML: break; default: err("End tag for \u201Chtml\u201D seen but there were unclosed elements."); break uncloseloop2; } } } mode = AFTER_BODY; continue; case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU: case UL_OR_OL_OR_DL: case PRE_OR_LISTING: case FIELDSET: case BUTTON: case ADDRESS_OR_ARTICLE_OR_ASIDE_OR_DETAILS_OR_DIR_OR_FIGCAPTION_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_HGROUP_OR_NAV_OR_SECTION_OR_SUMMARY: eltPos = findLastInScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("Stray end tag \u201C" + name + "\u201D."); } else { generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } } break endtagloop; case FORM: if (formPointer == null) { err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } Portability.releaseElement(formPointer); formPointer = null; eltPos = findLastInScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } removeFromStack(eltPos); break endtagloop; case P: eltPos = findLastInButtonScope("p"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("No \u201Cp\u201D element in scope but a \u201Cp\u201D end tag seen."); // XXX inline this case if (inForeign) { err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (stack[currentPtr].ns != "http://www.w3.org/1999/xhtml") { pop(); } inForeign = false; } appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, HtmlAttributes.EMPTY_ATTRIBUTES); break endtagloop; } generateImpliedEndTagsExceptFor("p"); assert eltPos != TreeBuilder.NOT_FOUND_ON_STACK; if (errorHandler != null && eltPos != currentPtr) { errNoCheck("End tag for \u201Cp\u201D seen, but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } break endtagloop; case LI: eltPos = findLastInListScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("No \u201Cli\u201D element in list scope but a \u201Cli\u201D end tag seen."); } else { generateImpliedEndTagsExceptFor(name); if (errorHandler != null && eltPos != currentPtr) { errNoCheck("End tag for \u201Cli\u201D seen, but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } } break endtagloop; case DD_OR_DT: eltPos = findLastInScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("No \u201C" + name + "\u201D element in scope but a \u201C" + name + "\u201D end tag seen."); } else { generateImpliedEndTagsExceptFor(name); if (errorHandler != null && eltPos != currentPtr) { errNoCheck("End tag for \u201C" + name + "\u201D seen, but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } } break endtagloop; case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: eltPos = findLastInScopeHn(); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("Stray end tag \u201C" + name + "\u201D."); } else { generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } } break endtagloop; case OBJECT: case MARQUEE_OR_APPLET: eltPos = findLastInScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("Stray end tag \u201C" + name + "\u201D."); } else { generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); } break endtagloop; case BR: err("End tag \u201Cbr\u201D."); if (inForeign) { err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (stack[currentPtr].ns != "http://www.w3.org/1999/xhtml") { pop(); } inForeign = false; } reconstructTheActiveFormattingElements(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, HtmlAttributes.EMPTY_ATTRIBUTES); break endtagloop; case AREA_OR_WBR: case PARAM_OR_SOURCE: case EMBED_OR_IMG: case IMAGE: case INPUT: case KEYGEN: // XXX?? case HR: case ISINDEX: case IFRAME: case NOEMBED: // XXX??? case NOFRAMES: // XXX?? case SELECT: case TABLE: case TEXTAREA: // XXX?? err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; case NOSCRIPT: if (scriptingEnabled) { err("Stray end tag \u201Cnoscript\u201D."); break endtagloop; } else { // fall through } case A: case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U: case FONT: case NOBR: if (adoptionAgencyEndTag(name)) { break endtagloop; } // else handle like any other tag default: if (isCurrent(name)) { pop(); break endtagloop; } eltPos = currentPtr; for (;;) { StackNode<T> node = stack[eltPos]; if (node.name == name) { generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } break endtagloop; } else if (node.scoping || node.special) { err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } eltPos--; } } case IN_COLUMN_GROUP: switch (group) { case COLGROUP: if (currentPtr == 0) { assert fragment; err("Garbage in \u201Ccolgroup\u201D fragment."); break endtagloop; } pop(); mode = IN_TABLE; break endtagloop; case COL: err("Stray end tag \u201Ccol\u201D."); break endtagloop; default: if (currentPtr == 0) { assert fragment; err("Garbage in \u201Ccolgroup\u201D fragment."); break endtagloop; } pop(); mode = IN_TABLE; continue; } case IN_SELECT_IN_TABLE: switch (group) { case CAPTION: case TABLE: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: err("\u201C" + name + "\u201D end tag with \u201Cselect\u201D open."); if (findLastInTableScope(name) != TreeBuilder.NOT_FOUND_ON_STACK) { eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break endtagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375 } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue; } else { break endtagloop; } default: // fall through to IN_SELECT } case IN_SELECT: switch (group) { case OPTION: if (isCurrent("option")) { pop(); break endtagloop; } else { err("Stray end tag \u201Coption\u201D"); break endtagloop; } case OPTGROUP: if (isCurrent("option") && "optgroup" == stack[currentPtr - 1].name) { pop(); } if (isCurrent("optgroup")) { pop(); } else { err("Stray end tag \u201Coptgroup\u201D"); } break endtagloop; case SELECT: eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; err("Stray end tag \u201Cselect\u201D"); break endtagloop; } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); break endtagloop; default: err("Stray end tag \u201C" + name + "\u201D"); break endtagloop; } case AFTER_BODY: switch (group) { case HTML: if (fragment) { err("Stray end tag \u201Chtml\u201D"); break endtagloop; } else { mode = AFTER_AFTER_BODY; break endtagloop; } default: err("Saw an end tag after \u201Cbody\u201D had been closed."); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; } case IN_FRAMESET: switch (group) { case FRAMESET: if (currentPtr == 0) { assert fragment; err("Stray end tag \u201Cframeset\u201D"); break endtagloop; } pop(); if ((!fragment) && !isCurrent("frameset")) { mode = AFTER_FRAMESET; } break endtagloop; default: err("Stray end tag \u201C" + name + "\u201D"); break endtagloop; } case AFTER_FRAMESET: switch (group) { case HTML: mode = AFTER_AFTER_FRAMESET; break endtagloop; default: err("Stray end tag \u201C" + name + "\u201D"); break endtagloop; } case INITIAL: /* * Parse error. */ // [NOCPP[ switch (doctypeExpectation) { case AUTO: err("End tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D."); break; case HTML: err("End tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D."); break; case HTML401_STRICT: err("End tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); break; case HTML401_TRANSITIONAL: err("End tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); break; case NO_DOCTYPE_ERRORS: } // ]NOCPP] /* * * Set the document to quirks mode. */ documentModeInternal(DocumentMode.QUIRKS_MODE, null, null, false); /* * Then, switch to the root element mode of the tree * construction stage */ mode = BEFORE_HTML; /* * and reprocess the current token. */ continue; case BEFORE_HTML: switch (group) { case HEAD: case BR: case HTML: case BODY: /* * Create an HTMLElement node with the tag name * html, in the HTML namespace. Append it to the * Document object. */ appendHtmlElementToDocumentAndPush(); /* Switch to the main mode */ mode = BEFORE_HEAD; /* * reprocess the current token. */ continue; default: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } case BEFORE_HEAD: switch (group) { case HEAD: case BR: case HTML: case BODY: appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_HEAD; continue; default: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } case IN_HEAD: switch (group) { case HEAD: pop(); mode = AFTER_HEAD; break endtagloop; case BR: case HTML: case BODY: pop(); mode = AFTER_HEAD; continue; default: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } case IN_HEAD_NOSCRIPT: switch (group) { case NOSCRIPT: pop(); mode = IN_HEAD; break endtagloop; case BR: err("Stray end tag \u201C" + name + "\u201D."); pop(); mode = IN_HEAD; continue; default: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } case AFTER_HEAD: switch (group) { case HTML: case BODY: case BR: appendToCurrentNodeAndPushBodyElement(); mode = FRAMESET_OK; continue; default: err("Stray end tag \u201C" + name + "\u201D."); break endtagloop; } case AFTER_AFTER_BODY: err("Stray \u201C" + name + "\u201D end tag."); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; case AFTER_AFTER_FRAMESET: err("Stray \u201C" + name + "\u201D end tag."); mode = IN_FRAMESET; continue; case TEXT: // XXX need to manage insertion point here pop(); if (originalMode == AFTER_HEAD) { silentPop(); } mode = originalMode; break endtagloop; } } // endtagloop if (inForeign && !hasForeignInScope()) { /* * If, after doing so, the insertion mode is still "in foreign * content", but there is no element in scope that has a namespace * other than the HTML namespace, switch the insertion mode to the * secondary insertion mode. */ inForeign = false; } } private int findLastInTableScopeOrRootTbodyTheadTfoot() { for (int i = currentPtr; i > 0; i--) { if (stack[i].group == TreeBuilder.TBODY_OR_THEAD_OR_TFOOT) { return i; } } return 0; } private int findLast(@Local String name) { for (int i = currentPtr; i > 0; i--) { if (stack[i].name == name) { return i; } } return TreeBuilder.NOT_FOUND_ON_STACK; } private int findLastInTableScope(@Local String name) { for (int i = currentPtr; i > 0; i--) { if (stack[i].name == name) { return i; } else if (stack[i].name == "table") { return TreeBuilder.NOT_FOUND_ON_STACK; } } return TreeBuilder.NOT_FOUND_ON_STACK; } private int findLastInButtonScope(@Local String name) { for (int i = currentPtr; i > 0; i--) { if (stack[i].name == name) { return i; } else if (stack[i].scoping || stack[i].name == "button") { return TreeBuilder.NOT_FOUND_ON_STACK; } } return TreeBuilder.NOT_FOUND_ON_STACK; } private int findLastInScope(@Local String name) { for (int i = currentPtr; i > 0; i--) { if (stack[i].name == name) { return i; } else if (stack[i].scoping) { return TreeBuilder.NOT_FOUND_ON_STACK; } } return TreeBuilder.NOT_FOUND_ON_STACK; } private int findLastInListScope(@Local String name) { for (int i = currentPtr; i > 0; i--) { if (stack[i].name == name) { return i; } else if (stack[i].scoping || stack[i].name == "ul" || stack[i].name == "ol") { return TreeBuilder.NOT_FOUND_ON_STACK; } } return TreeBuilder.NOT_FOUND_ON_STACK; } private int findLastInScopeHn() { for (int i = currentPtr; i > 0; i--) { if (stack[i].group == TreeBuilder.H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) { return i; } else if (stack[i].scoping) { return TreeBuilder.NOT_FOUND_ON_STACK; } } return TreeBuilder.NOT_FOUND_ON_STACK; } private boolean hasForeignInScope() { for (int i = currentPtr; i > 0; i--) { if (stack[i].ns != "http://www.w3.org/1999/xhtml") { return true; } else if (stack[i].scoping) { return false; } } return false; } private void generateImpliedEndTagsExceptFor(@Local String name) throws SAXException { for (;;) { StackNode<T> node = stack[currentPtr]; switch (node.group) { case P: case LI: case DD_OR_DT: case OPTION: case OPTGROUP: case RT_OR_RP: if (node.name == name) { return; } pop(); continue; default: return; } } } private void generateImpliedEndTags() throws SAXException { for (;;) { switch (stack[currentPtr].group) { case P: case LI: case DD_OR_DT: case OPTION: case OPTGROUP: case RT_OR_RP: pop(); continue; default: return; } } } private boolean isSecondOnStackBody() { return currentPtr >= 1 && stack[1].group == TreeBuilder.BODY; } private void documentModeInternal(DocumentMode m, String publicIdentifier, String systemIdentifier, boolean html4SpecificAdditionalErrorChecks) throws SAXException { quirks = (m == DocumentMode.QUIRKS_MODE); if (documentModeHandler != null) { documentModeHandler.documentMode( m // [NOCPP[ , publicIdentifier, systemIdentifier, html4SpecificAdditionalErrorChecks // ]NOCPP] ); } // [NOCPP[ documentMode(m, publicIdentifier, systemIdentifier, html4SpecificAdditionalErrorChecks); // ]NOCPP] } private boolean isAlmostStandards(String publicIdentifier, String systemIdentifier) { if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-//w3c//dtd xhtml 1.0 transitional//en", publicIdentifier)) { return true; } if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-//w3c//dtd xhtml 1.0 frameset//en", publicIdentifier)) { return true; } if (systemIdentifier != null) { if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-//w3c//dtd html 4.01 transitional//en", publicIdentifier)) { return true; } if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-//w3c//dtd html 4.01 frameset//en", publicIdentifier)) { return true; } } return false; } private boolean isQuirky(@Local String name, String publicIdentifier, String systemIdentifier, boolean forceQuirks) { if (forceQuirks) { return true; } if (name != HTML_LOCAL) { return true; } if (publicIdentifier != null) { for (int i = 0; i < TreeBuilder.QUIRKY_PUBLIC_IDS.length; i++) { if (Portability.lowerCaseLiteralIsPrefixOfIgnoreAsciiCaseString( TreeBuilder.QUIRKY_PUBLIC_IDS[i], publicIdentifier)) { return true; } } if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-//w3o//dtd w3 html strict 3.0//en//", publicIdentifier) || Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-/w3c/dtd html 4.0 transitional/en", publicIdentifier) || Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "html", publicIdentifier)) { return true; } } if (systemIdentifier == null) { if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-//w3c//dtd html 4.01 transitional//en", publicIdentifier)) { return true; } else if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "-//w3c//dtd html 4.01 frameset//en", publicIdentifier)) { return true; } } else if (Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd", systemIdentifier)) { return true; } return false; } private void closeTheCell(int eltPos) throws SAXException { generateImpliedEndTags(); if (errorHandler != null && eltPos != currentPtr) { errNoCheck("Unclosed elements."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); mode = IN_ROW; return; } private int findLastInTableScopeTdTh() { for (int i = currentPtr; i > 0; i--) { @Local String name = stack[i].name; if ("td" == name || "th" == name) { return i; } else if (name == "table") { return TreeBuilder.NOT_FOUND_ON_STACK; } } return TreeBuilder.NOT_FOUND_ON_STACK; } private void clearStackBackTo(int eltPos) throws SAXException { while (currentPtr > eltPos) { // > not >= intentional pop(); } } private void resetTheInsertionMode() { inForeign = false; StackNode<T> node; @Local String name; @NsUri String ns; for (int i = currentPtr; i >= 0; i--) { node = stack[i]; name = node.name; ns = node.ns; if (i == 0) { if (!(contextNamespace == "http://www.w3.org/1999/xhtml" && (contextName == "td" || contextName == "th"))) { name = contextName; ns = contextNamespace; } else { mode = framesetOk ? FRAMESET_OK : IN_BODY; // XXX from Hixie's email return; } } if ("select" == name) { mode = IN_SELECT; return; } else if ("td" == name || "th" == name) { mode = IN_CELL; return; } else if ("tr" == name) { mode = IN_ROW; return; } else if ("tbody" == name || "thead" == name || "tfoot" == name) { mode = IN_TABLE_BODY; return; } else if ("caption" == name) { mode = IN_CAPTION; return; } else if ("colgroup" == name) { mode = IN_COLUMN_GROUP; return; } else if ("table" == name) { mode = IN_TABLE; return; } else if ("http://www.w3.org/1999/xhtml" != ns) { inForeign = true; mode = framesetOk ? FRAMESET_OK : IN_BODY; return; } else if ("head" == name) { mode = framesetOk ? FRAMESET_OK : IN_BODY; // really return; } else if ("body" == name) { mode = framesetOk ? FRAMESET_OK : IN_BODY; return; } else if ("frameset" == name) { mode = IN_FRAMESET; return; } else if ("html" == name) { if (headPointer == null) { mode = BEFORE_HEAD; } else { mode = AFTER_HEAD; } return; } else if (i == 0) { mode = framesetOk ? FRAMESET_OK : IN_BODY; return; } } } /** * @throws SAXException * */ private void implicitlyCloseP() throws SAXException { int eltPos = findLastInButtonScope("p"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { return; } generateImpliedEndTagsExceptFor("p"); if (errorHandler != null && eltPos != currentPtr) { err("Unclosed elements."); } while (currentPtr >= eltPos) { pop(); } } private boolean clearLastStackSlot() { stack[currentPtr] = null; return true; } private boolean clearLastListSlot() { listOfActiveFormattingElements[listPtr] = null; return true; } @SuppressWarnings("unchecked") private void push(StackNode<T> node) throws SAXException { currentPtr++; if (currentPtr == stack.length) { StackNode<T>[] newStack = new StackNode[stack.length + 64]; System.arraycopy(stack, 0, newStack, 0, stack.length); stack = newStack; } stack[currentPtr] = node; elementPushed(node.ns, node.popName, node.node); } @SuppressWarnings("unchecked") private void silentPush(StackNode<T> node) throws SAXException { currentPtr++; if (currentPtr == stack.length) { StackNode<T>[] newStack = new StackNode[stack.length + 64]; System.arraycopy(stack, 0, newStack, 0, stack.length); stack = newStack; } stack[currentPtr] = node; } @SuppressWarnings("unchecked") private void append(StackNode<T> node) { listPtr++; if (listPtr == listOfActiveFormattingElements.length) { StackNode<T>[] newList = new StackNode[listOfActiveFormattingElements.length + 64]; System.arraycopy(listOfActiveFormattingElements, 0, newList, 0, listOfActiveFormattingElements.length); listOfActiveFormattingElements = newList; } listOfActiveFormattingElements[listPtr] = node; } @Inline private void insertMarker() { append(null); } private void clearTheListOfActiveFormattingElementsUpToTheLastMarker() { while (listPtr > -1) { if (listOfActiveFormattingElements[listPtr] == null) { --listPtr; return; } listOfActiveFormattingElements[listPtr].release(); --listPtr; } } @Inline private boolean isCurrent(@Local String name) { return name == stack[currentPtr].name; } private void removeFromStack(int pos) throws SAXException { if (currentPtr == pos) { pop(); } else { fatal(); stack[pos].release(); System.arraycopy(stack, pos + 1, stack, pos, currentPtr - pos); assert clearLastStackSlot(); currentPtr--; } } private void removeFromStack(StackNode<T> node) throws SAXException { if (stack[currentPtr] == node) { pop(); } else { int pos = currentPtr - 1; while (pos >= 0 && stack[pos] != node) { pos--; } if (pos == -1) { // dead code? return; } fatal(); node.release(); System.arraycopy(stack, pos + 1, stack, pos, currentPtr - pos); currentPtr--; } } private void removeFromListOfActiveFormattingElements(int pos) { assert listOfActiveFormattingElements[pos] != null; listOfActiveFormattingElements[pos].release(); if (pos == listPtr) { assert clearLastListSlot(); listPtr--; return; } assert pos < listPtr; System.arraycopy(listOfActiveFormattingElements, pos + 1, listOfActiveFormattingElements, pos, listPtr - pos); assert clearLastListSlot(); listPtr--; } private boolean adoptionAgencyEndTag(@Local String name) throws SAXException { // If you crash around here, perhaps some stack node variable claimed to // be a weak ref isn't. for (int i = 0; i < 8; ++i) { int formattingEltListPos = listPtr; while (formattingEltListPos > -1) { StackNode<T> listNode = listOfActiveFormattingElements[formattingEltListPos]; // weak // ref if (listNode == null) { formattingEltListPos = -1; break; } else if (listNode.name == name) { break; } formattingEltListPos--; } if (formattingEltListPos == -1) { return false; } StackNode<T> formattingElt = listOfActiveFormattingElements[formattingEltListPos]; // this // *looks* // like // a // weak // ref // to // the // list // of // formatting // elements int formattingEltStackPos = currentPtr; boolean inScope = true; while (formattingEltStackPos > -1) { StackNode<T> node = stack[formattingEltStackPos]; // weak ref if (node == formattingElt) { break; } else if (node.scoping) { inScope = false; } formattingEltStackPos--; } if (formattingEltStackPos == -1) { err("No element \u201C" + name + "\u201D to close."); removeFromListOfActiveFormattingElements(formattingEltListPos); return true; } if (!inScope) { err("No element \u201C" + name + "\u201D to close."); return true; } // stackPos now points to the formatting element and it is in scope if (errorHandler != null && formattingEltStackPos != currentPtr) { errNoCheck("End tag \u201C" + name + "\u201D violates nesting rules."); } int furthestBlockPos = formattingEltStackPos + 1; while (furthestBlockPos <= currentPtr) { StackNode<T> node = stack[furthestBlockPos]; // weak ref if (node.scoping || node.special) { break; } furthestBlockPos++; } if (furthestBlockPos > currentPtr) { // no furthest block while (currentPtr >= formattingEltStackPos) { pop(); } removeFromListOfActiveFormattingElements(formattingEltListPos); return true; } StackNode<T> commonAncestor = stack[formattingEltStackPos - 1]; // weak // ref StackNode<T> furthestBlock = stack[furthestBlockPos]; // weak ref // detachFromParent(furthestBlock.node); XXX AAA CHANGE int bookmark = formattingEltListPos; int nodePos = furthestBlockPos; StackNode<T> lastNode = furthestBlock; // weak ref for (int j = 0; j < 3; ++j) { nodePos--; StackNode<T> node = stack[nodePos]; // weak ref int nodeListPos = findInListOfActiveFormattingElements(node); if (nodeListPos == -1) { assert formattingEltStackPos < nodePos; assert bookmark < nodePos; assert furthestBlockPos > nodePos; removeFromStack(nodePos); // node is now a bad pointer in // C++ furthestBlockPos--; continue; } // now node is both on stack and in the list if (nodePos == formattingEltStackPos) { break; } if (nodePos == furthestBlockPos) { bookmark = nodeListPos + 1; } // if (hasChildren(node.node)) { XXX AAA CHANGE assert node == listOfActiveFormattingElements[nodeListPos]; assert node == stack[nodePos]; T clone = createElement("http://www.w3.org/1999/xhtml", node.name, node.attributes.cloneAttributes(null)); StackNode<T> newNode = new StackNode<T>(node.group, node.ns, node.name, clone, node.scoping, node.special, node.fosterParenting, node.popName, node.attributes); // creation // ownership // goes // to // stack node.dropAttributes(); // adopt ownership to newNode stack[nodePos] = newNode; newNode.retain(); // retain for list listOfActiveFormattingElements[nodeListPos] = newNode; node.release(); // release from stack node.release(); // release from list node = newNode; Portability.releaseElement(clone); // } XXX AAA CHANGE detachFromParent(lastNode.node); appendElement(lastNode.node, node.node); lastNode = node; } if (commonAncestor.fosterParenting) { fatal(); detachFromParent(lastNode.node); insertIntoFosterParent(lastNode.node); } else { detachFromParent(lastNode.node); appendElement(lastNode.node, commonAncestor.node); } T clone = createElement("http://www.w3.org/1999/xhtml", formattingElt.name, formattingElt.attributes.cloneAttributes(null)); StackNode<T> formattingClone = new StackNode<T>( formattingElt.group, formattingElt.ns, formattingElt.name, clone, formattingElt.scoping, formattingElt.special, formattingElt.fosterParenting, formattingElt.popName, formattingElt.attributes); // Ownership // transfers // to // stack // below formattingElt.dropAttributes(); // transfer ownership to // formattingClone appendChildrenToNewParent(furthestBlock.node, clone); appendElement(clone, furthestBlock.node); removeFromListOfActiveFormattingElements(formattingEltListPos); insertIntoListOfActiveFormattingElements(formattingClone, bookmark); assert formattingEltStackPos < furthestBlockPos; removeFromStack(formattingEltStackPos); // furthestBlockPos is now off by one and points to the slot after // it insertIntoStack(formattingClone, furthestBlockPos); Portability.releaseElement(clone); } return true; } private void insertIntoStack(StackNode<T> node, int position) throws SAXException { assert currentPtr + 1 < stack.length; assert position <= currentPtr + 1; if (position == currentPtr + 1) { push(node); } else { System.arraycopy(stack, position, stack, position + 1, (currentPtr - position) + 1); currentPtr++; stack[position] = node; } } private void insertIntoListOfActiveFormattingElements( StackNode<T> formattingClone, int bookmark) { formattingClone.retain(); assert listPtr + 1 < listOfActiveFormattingElements.length; if (bookmark <= listPtr) { System.arraycopy(listOfActiveFormattingElements, bookmark, listOfActiveFormattingElements, bookmark + 1, (listPtr - bookmark) + 1); } listPtr++; listOfActiveFormattingElements[bookmark] = formattingClone; } private int findInListOfActiveFormattingElements(StackNode<T> node) { for (int i = listPtr; i >= 0; i--) { if (node == listOfActiveFormattingElements[i]) { return i; } } return -1; } private int findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker( @Local String name) { for (int i = listPtr; i >= 0; i--) { StackNode<T> node = listOfActiveFormattingElements[i]; if (node == null) { return -1; } else if (node.name == name) { return i; } } return -1; } private void maybeForgetEarlierDuplicateFormattingElement( @Local String name, HtmlAttributes attributes) throws SAXException { int candidate = -1; int count = 0; for (int i = listPtr; i >= 0; i--) { StackNode<T> node = listOfActiveFormattingElements[i]; if (node == null) { break; } if (node.name == name && node.attributes.equalsAnother(attributes)) { candidate = i; ++count; } } if (count >= 3) { removeFromListOfActiveFormattingElements(candidate); } } private int findLastOrRoot(@Local String name) { for (int i = currentPtr; i > 0; i--) { if (stack[i].name == name) { return i; } } return 0; } private int findLastOrRoot(int group) { for (int i = currentPtr; i > 0; i--) { if (stack[i].group == group) { return i; } } return 0; } /** * Attempt to add attribute to the body element. * @param attributes the attributes * @return <code>true</code> iff the attributes were added * @throws SAXException */ private boolean addAttributesToBody(HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, "http://www.w3.org/1999/xhtml"); // ]NOCPP] if (currentPtr >= 1) { StackNode<T> body = stack[1]; if (body.group == TreeBuilder.BODY) { addAttributesToElement(body.node, attributes); return true; } } return false; } private void addAttributesToHtml(HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, "http://www.w3.org/1999/xhtml"); // ]NOCPP] addAttributesToElement(stack[0].node, attributes); } private void pushHeadPointerOntoStack() throws SAXException { assert headPointer != null; assert !fragment; assert mode == AFTER_HEAD; fatal(); silentPush(new StackNode<T>("http://www.w3.org/1999/xhtml", ElementName.HEAD, headPointer)); } /** * @throws SAXException * */ private void reconstructTheActiveFormattingElements() throws SAXException { if (listPtr == -1) { return; } StackNode<T> mostRecent = listOfActiveFormattingElements[listPtr]; if (mostRecent == null || isInStack(mostRecent)) { return; } int entryPos = listPtr; for (;;) { entryPos--; if (entryPos == -1) { break; } if (listOfActiveFormattingElements[entryPos] == null) { break; } if (isInStack(listOfActiveFormattingElements[entryPos])) { break; } } while (entryPos < listPtr) { entryPos++; StackNode<T> entry = listOfActiveFormattingElements[entryPos]; T clone = createElement("http://www.w3.org/1999/xhtml", entry.name, entry.attributes.cloneAttributes(null)); StackNode<T> entryClone = new StackNode<T>(entry.group, entry.ns, entry.name, clone, entry.scoping, entry.special, entry.fosterParenting, entry.popName, entry.attributes); entry.dropAttributes(); // transfer ownership to entryClone StackNode<T> currentNode = stack[currentPtr]; if (currentNode.fosterParenting) { insertIntoFosterParent(clone); } else { appendElement(clone, currentNode.node); } push(entryClone); // stack takes ownership of the local variable listOfActiveFormattingElements[entryPos] = entryClone; // overwriting the old entry on the list, so release & retain entry.release(); entryClone.retain(); } } private void insertIntoFosterParent(T child) throws SAXException { int eltPos = findLastOrRoot(TreeBuilder.TABLE); StackNode<T> node = stack[eltPos]; T elt = node.node; if (eltPos == 0) { appendElement(child, elt); return; } insertFosterParentedChild(child, elt, stack[eltPos - 1].node); } private boolean isInStack(StackNode<T> node) { for (int i = currentPtr; i >= 0; i--) { if (stack[i] == node) { return true; } } return false; } private void pop() throws SAXException { StackNode<T> node = stack[currentPtr]; assert clearLastStackSlot(); currentPtr--; elementPopped(node.ns, node.popName, node.node); node.release(); } private void silentPop() throws SAXException { StackNode<T> node = stack[currentPtr]; assert clearLastStackSlot(); currentPtr--; node.release(); } private void popOnEof() throws SAXException { StackNode<T> node = stack[currentPtr]; assert clearLastStackSlot(); currentPtr--; markMalformedIfScript(node.node); elementPopped(node.ns, node.popName, node.node); node.release(); } // [NOCPP[ private void checkAttributes(HtmlAttributes attributes, @NsUri String ns) throws SAXException { if (errorHandler != null) { int len = attributes.getXmlnsLength(); for (int i = 0; i < len; i++) { AttributeName name = attributes.getXmlnsAttributeName(i); if (name == AttributeName.XMLNS) { if (html4) { err("Attribute \u201Cxmlns\u201D not allowed here. (HTML4-only error.)"); } else { String xmlns = attributes.getXmlnsValue(i); if (!ns.equals(xmlns)) { err("Bad value \u201C" + xmlns + "\u201D for the attribute \u201Cxmlns\u201D (only \u201C" + ns + "\u201D permitted here)."); switch (namePolicy) { case ALTER_INFOSET: // fall through case ALLOW: warn("Attribute \u201Cxmlns\u201D is not serializable as XML 1.0."); break; case FATAL: fatal("Attribute \u201Cxmlns\u201D is not serializable as XML 1.0."); break; } } } } else if (ns != "http://www.w3.org/1999/xhtml" && name == AttributeName.XMLNS_XLINK) { String xmlns = attributes.getXmlnsValue(i); if (!"http://www.w3.org/1999/xlink".equals(xmlns)) { err("Bad value \u201C" + xmlns + "\u201D for the attribute \u201Cxmlns:link\u201D (only \u201Chttp://www.w3.org/1999/xlink\u201D permitted here)."); switch (namePolicy) { case ALTER_INFOSET: // fall through case ALLOW: warn("Attribute \u201Cxmlns:xlink\u201D with the value \u201Chttp://www.w3org/1999/xlink\u201D is not serializable as XML 1.0 without changing document semantics."); break; case FATAL: fatal("Attribute \u201Cxmlns:xlink\u201D with the value \u201Chttp://www.w3org/1999/xlink\u201D is not serializable as XML 1.0 without changing document semantics."); break; } } } else { err("Attribute \u201C" + attributes.getXmlnsLocalName(i) + "\u201D not allowed here."); switch (namePolicy) { case ALTER_INFOSET: // fall through case ALLOW: warn("Attribute with the local name \u201C" + attributes.getXmlnsLocalName(i) + "\u201D is not serializable as XML 1.0."); break; case FATAL: fatal("Attribute with the local name \u201C" + attributes.getXmlnsLocalName(i) + "\u201D is not serializable as XML 1.0."); break; } } } } attributes.processNonNcNames(this, namePolicy); } private String checkPopName(@Local String name) throws SAXException { if (NCName.isNCName(name)) { return name; } else { switch (namePolicy) { case ALLOW: warn("Element name \u201C" + name + "\u201D cannot be represented as XML 1.0."); return name; case ALTER_INFOSET: warn("Element name \u201C" + name + "\u201D cannot be represented as XML 1.0."); return NCName.escapeName(name); case FATAL: fatal("Element name \u201C" + name + "\u201D cannot be represented as XML 1.0."); } } return null; // keep compiler happy } // ]NOCPP] private void appendHtmlElementToDocumentAndPush(HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, "http://www.w3.org/1999/xhtml"); // ]NOCPP] T elt = createHtmlElementSetAsRoot(attributes); StackNode<T> node = new StackNode<T>("http://www.w3.org/1999/xhtml", ElementName.HTML, elt); push(node); Portability.releaseElement(elt); } private void appendHtmlElementToDocumentAndPush() throws SAXException { appendHtmlElementToDocumentAndPush(tokenizer.emptyAttributes()); } private void appendToCurrentNodeAndPushHeadElement(HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, "http://www.w3.org/1999/xhtml"); // ]NOCPP] T elt = createElement("http://www.w3.org/1999/xhtml", "head", attributes); appendElement(elt, stack[currentPtr].node); headPointer = elt; Portability.retainElement(headPointer); StackNode<T> node = new StackNode<T>("http://www.w3.org/1999/xhtml", ElementName.HEAD, elt); push(node); Portability.releaseElement(elt); } private void appendToCurrentNodeAndPushBodyElement(HtmlAttributes attributes) throws SAXException { appendToCurrentNodeAndPushElement("http://www.w3.org/1999/xhtml", ElementName.BODY, attributes); } private void appendToCurrentNodeAndPushBodyElement() throws SAXException { appendToCurrentNodeAndPushBodyElement(tokenizer.emptyAttributes()); } private void appendToCurrentNodeAndPushFormElementMayFoster( HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, "http://www.w3.org/1999/xhtml"); // ]NOCPP] T elt = createElement("http://www.w3.org/1999/xhtml", "form", attributes); formPointer = elt; Portability.retainElement(formPointer); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } StackNode<T> node = new StackNode<T>("http://www.w3.org/1999/xhtml", ElementName.FORM, elt); push(node); Portability.releaseElement(elt); } private void appendToCurrentNodeAndPushFormattingElementMayFoster( @NsUri String ns, ElementName elementName, HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, ns); // ]NOCPP] // This method can't be called for custom elements T elt = createElement(ns, elementName.name, attributes); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } StackNode<T> node = new StackNode<T>(ns, elementName, elt, attributes.cloneAttributes(null)); push(node); append(node); node.retain(); // append doesn't retain itself Portability.releaseElement(elt); } private void appendToCurrentNodeAndPushElement(@NsUri String ns, ElementName elementName, HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, ns); // ]NOCPP] // This method can't be called for custom elements T elt = createElement(ns, elementName.name, attributes); appendElement(elt, stack[currentPtr].node); StackNode<T> node = new StackNode<T>(ns, elementName, elt); push(node); Portability.releaseElement(elt); } private void appendToCurrentNodeAndPushElementMayFoster(@NsUri String ns, ElementName elementName, HtmlAttributes attributes) throws SAXException { @Local String popName = elementName.name; // [NOCPP[ checkAttributes(attributes, ns); if (elementName.custom) { popName = checkPopName(popName); } // ]NOCPP] T elt = createElement(ns, popName, attributes); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } StackNode<T> node = new StackNode<T>(ns, elementName, elt, popName); push(node); Portability.releaseElement(elt); } private void appendToCurrentNodeAndPushElementMayFosterNoScoping( @NsUri String ns, ElementName elementName, HtmlAttributes attributes) throws SAXException { @Local String popName = elementName.name; // [NOCPP[ checkAttributes(attributes, ns); if (elementName.custom) { popName = checkPopName(popName); } // ]NOCPP] T elt = createElement(ns, popName, attributes); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } StackNode<T> node = new StackNode<T>(ns, elementName, elt, popName, false); push(node); Portability.releaseElement(elt); } private void appendToCurrentNodeAndPushElementMayFosterCamelCase( @NsUri String ns, ElementName elementName, HtmlAttributes attributes) throws SAXException { @Local String popName = elementName.camelCaseName; // [NOCPP[ checkAttributes(attributes, ns); if (elementName.custom) { popName = checkPopName(popName); } // ]NOCPP] T elt = createElement(ns, popName, attributes); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } StackNode<T> node = new StackNode<T>(ns, elementName, elt, popName, ElementName.FOREIGNOBJECT == elementName); push(node); Portability.releaseElement(elt); } private void appendToCurrentNodeAndPushElementMayFoster(@NsUri String ns, ElementName elementName, HtmlAttributes attributes, T form) throws SAXException { // [NOCPP[ checkAttributes(attributes, ns); // ]NOCPP] // Can't be called for custom elements T elt = createElement(ns, elementName.name, attributes, fragment ? null : form); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } StackNode<T> node = new StackNode<T>(ns, elementName, elt); push(node); Portability.releaseElement(elt); } private void appendVoidElementToCurrentMayFoster( @NsUri String ns, @Local String name, HtmlAttributes attributes, T form) throws SAXException { // [NOCPP[ checkAttributes(attributes, ns); // ]NOCPP] // Can't be called for custom elements T elt = createElement(ns, name, attributes, fragment ? null : form); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } elementPushed(ns, name, elt); elementPopped(ns, name, elt); Portability.releaseElement(elt); } private void appendVoidElementToCurrentMayFoster( @NsUri String ns, ElementName elementName, HtmlAttributes attributes) throws SAXException { @Local String popName = elementName.name; // [NOCPP[ checkAttributes(attributes, ns); if (elementName.custom) { popName = checkPopName(popName); } // ]NOCPP] T elt = createElement(ns, popName, attributes); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } elementPushed(ns, popName, elt); elementPopped(ns, popName, elt); Portability.releaseElement(elt); } private void appendVoidElementToCurrentMayFosterCamelCase( @NsUri String ns, ElementName elementName, HtmlAttributes attributes) throws SAXException { @Local String popName = elementName.camelCaseName; // [NOCPP[ checkAttributes(attributes, ns); if (elementName.custom) { popName = checkPopName(popName); } // ]NOCPP] T elt = createElement(ns, popName, attributes); StackNode<T> current = stack[currentPtr]; if (current.fosterParenting) { fatal(); insertIntoFosterParent(elt); } else { appendElement(elt, current.node); } elementPushed(ns, popName, elt); elementPopped(ns, popName, elt); Portability.releaseElement(elt); } private void appendVoidElementToCurrent( @NsUri String ns, @Local String name, HtmlAttributes attributes, T form) throws SAXException { // [NOCPP[ checkAttributes(attributes, ns); // ]NOCPP] // Can't be called for custom elements T elt = createElement(ns, name, attributes, fragment ? null : form); StackNode<T> current = stack[currentPtr]; appendElement(elt, current.node); elementPushed(ns, name, elt); elementPopped(ns, name, elt); Portability.releaseElement(elt); } private void appendVoidFormToCurrent(HtmlAttributes attributes) throws SAXException { // [NOCPP[ checkAttributes(attributes, "http://www.w3.org/1999/xhtml"); // ]NOCPP] T elt = createElement("http://www.w3.org/1999/xhtml", "form", attributes); formPointer = elt; // ownership transferred to form pointer StackNode<T> current = stack[currentPtr]; appendElement(elt, current.node); elementPushed("http://www.w3.org/1999/xhtml", "form", elt); elementPopped("http://www.w3.org/1999/xhtml", "form", elt); } // [NOCPP[ private final void accumulateCharactersForced(@Const @NoLength char[] buf, int start, int length) throws SAXException { int newLen = charBufferLen + length; if (newLen > charBuffer.length) { char[] newBuf = new char[newLen]; System.arraycopy(charBuffer, 0, newBuf, 0, charBufferLen); charBuffer = newBuf; } System.arraycopy(buf, start, charBuffer, charBufferLen, length); charBufferLen = newLen; } // ]NOCPP] protected void accumulateCharacters(@Const @NoLength char[] buf, int start, int length) throws SAXException { appendCharacters(stack[currentPtr].node, buf, start, length); } // ------------------------------- // protected final void requestSuspension() { tokenizer.requestSuspension(); } protected abstract T createElement(@NsUri String ns, @Local String name, HtmlAttributes attributes) throws SAXException; protected T createElement(@NsUri String ns, @Local String name, HtmlAttributes attributes, T form) throws SAXException { return createElement("http://www.w3.org/1999/xhtml", name, attributes); } protected abstract T createHtmlElementSetAsRoot(HtmlAttributes attributes) throws SAXException; protected abstract void detachFromParent(T element) throws SAXException; protected abstract boolean hasChildren(T element) throws SAXException; protected abstract void appendElement(T child, T newParent) throws SAXException; protected abstract void appendChildrenToNewParent(T oldParent, T newParent) throws SAXException; protected abstract void insertFosterParentedChild(T child, T table, T stackParent) throws SAXException; protected abstract void insertFosterParentedCharacters( @NoLength char[] buf, int start, int length, T table, T stackParent) throws SAXException; protected abstract void appendCharacters(T parent, @NoLength char[] buf, int start, int length) throws SAXException; protected abstract void appendIsindexPrompt(T parent) throws SAXException; protected abstract void appendComment(T parent, @NoLength char[] buf, int start, int length) throws SAXException; protected abstract void appendCommentToDocument(@NoLength char[] buf, int start, int length) throws SAXException; protected abstract void addAttributesToElement(T element, HtmlAttributes attributes) throws SAXException; protected void markMalformedIfScript(T elt) throws SAXException { } protected void start(boolean fragmentMode) throws SAXException { } protected void end() throws SAXException { } protected void appendDoctypeToDocument(@Local String name, String publicIdentifier, String systemIdentifier) throws SAXException { } protected void elementPushed(@NsUri String ns, @Local String name, T node) throws SAXException { } protected void elementPopped(@NsUri String ns, @Local String name, T node) throws SAXException { } // [NOCPP[ protected void documentMode(DocumentMode m, String publicIdentifier, String systemIdentifier, boolean html4SpecificAdditionalErrorChecks) throws SAXException { } /** * @see nu.validator.htmlparser.common.TokenHandler#wantsComments() */ public boolean wantsComments() { return wantingComments; } public void setIgnoringComments(boolean ignoreComments) { wantingComments = !ignoreComments; } /** * Sets the errorHandler. * * @param errorHandler * the errorHandler to set */ public final void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; } /** * Returns the errorHandler. * * @return the errorHandler */ public ErrorHandler getErrorHandler() { return errorHandler; } /** * The argument MUST be an interned string or <code>null</code>. * * @param context */ public final void setFragmentContext(@Local String context) { this.contextName = context; this.contextNamespace = "http://www.w3.org/1999/xhtml"; this.contextNode = null; this.fragment = (contextName != null); this.quirks = false; } // ]NOCPP] /** * @see nu.validator.htmlparser.common.TokenHandler#cdataSectionAllowed() */ public boolean cdataSectionAllowed() throws SAXException { return inForeign && currentPtr >= 0 && stack[currentPtr].ns != "http://www.w3.org/1999/xhtml"; } /** * The argument MUST be an interned string or <code>null</code>. * * @param context */ public final void setFragmentContext(@Local String context, @NsUri String ns, T node, boolean quirks) { this.contextName = context; Portability.retainLocal(context); this.contextNamespace = ns; this.contextNode = node; Portability.retainElement(node); this.fragment = (contextName != null); this.quirks = quirks; } protected final T currentNode() { return stack[currentPtr].node; } /** * Returns the scriptingEnabled. * * @return the scriptingEnabled */ public boolean isScriptingEnabled() { return scriptingEnabled; } /** * Sets the scriptingEnabled. * * @param scriptingEnabled * the scriptingEnabled to set */ public void setScriptingEnabled(boolean scriptingEnabled) { this.scriptingEnabled = scriptingEnabled; } // [NOCPP[ /** * Sets the doctypeExpectation. * * @param doctypeExpectation * the doctypeExpectation to set */ public void setDoctypeExpectation(DoctypeExpectation doctypeExpectation) { this.doctypeExpectation = doctypeExpectation; } public void setNamePolicy(XmlViolationPolicy namePolicy) { this.namePolicy = namePolicy; } /** * Sets the documentModeHandler. * * @param documentModeHandler * the documentModeHandler to set */ public void setDocumentModeHandler(DocumentModeHandler documentModeHandler) { this.documentModeHandler = documentModeHandler; } /** * Sets the reportingDoctype. * * @param reportingDoctype * the reportingDoctype to set */ public void setReportingDoctype(boolean reportingDoctype) { this.reportingDoctype = reportingDoctype; } // ]NOCPP] /** * Flushes the pending characters. Public for document.write use cases only. * @throws SAXException */ public final void flushCharacters() throws SAXException { if (charBufferLen > 0) { if ((mode == IN_TABLE || mode == IN_TABLE_BODY || mode == IN_ROW) && charBufferContainsNonWhitespace()) { err("Misplaced non-space characters insided a table."); reconstructTheActiveFormattingElements(); if (!stack[currentPtr].fosterParenting) { // reconstructing gave us a new current node appendCharacters(currentNode(), charBuffer, 0, charBufferLen); charBufferLen = 0; return; } int eltPos = findLastOrRoot(TreeBuilder.TABLE); StackNode<T> node = stack[eltPos]; T elt = node.node; if (eltPos == 0) { appendCharacters(elt, charBuffer, 0, charBufferLen); charBufferLen = 0; return; } insertFosterParentedCharacters(charBuffer, 0, charBufferLen, elt, stack[eltPos - 1].node); charBufferLen = 0; return; } appendCharacters(currentNode(), charBuffer, 0, charBufferLen); charBufferLen = 0; } } private boolean charBufferContainsNonWhitespace() { for (int i = 0; i < charBufferLen; i++) { switch (charBuffer[i]) { case ' ': case '\t': case '\n': case '\r': case '\u000C': continue; default: return true; } } return false; } /** * Creates a comparable snapshot of the tree builder state. Snapshot * creation is only supported immediately after a script end tag has been * processed. In C++ the caller is responsible for calling * <code>delete</code> on the returned object. * * @return a snapshot. * @throws SAXException */ @SuppressWarnings("unchecked") public TreeBuilderState<T> newSnapshot() throws SAXException { StackNode<T>[] listCopy = new StackNode[listPtr + 1]; for (int i = 0; i < listCopy.length; i++) { StackNode<T> node = listOfActiveFormattingElements[i]; if (node != null) { StackNode<T> newNode = new StackNode<T>(node.group, node.ns, node.name, node.node, node.scoping, node.special, node.fosterParenting, node.popName, node.attributes.cloneAttributes(null)); listCopy[i] = newNode; } else { listCopy[i] = null; } } StackNode<T>[] stackCopy = new StackNode[currentPtr + 1]; for (int i = 0; i < stackCopy.length; i++) { StackNode<T> node = stack[i]; int listIndex = findInListOfActiveFormattingElements(node); if (listIndex == -1) { StackNode<T> newNode = new StackNode<T>(node.group, node.ns, node.name, node.node, node.scoping, node.special, node.fosterParenting, node.popName, null); stackCopy[i] = newNode; } else { stackCopy[i] = listCopy[listIndex]; stackCopy[i].retain(); } } Portability.retainElement(formPointer); return new StateSnapshot<T>(stackCopy, listCopy, formPointer, headPointer, deepTreeSurrogateParent, mode, originalMode, framesetOk, inForeign, needToDropLF, quirks); } public boolean snapshotMatches(TreeBuilderState<T> snapshot) { StackNode<T>[] stackCopy = snapshot.getStack(); int stackLen = snapshot.getStackLength(); StackNode<T>[] listCopy = snapshot.getListOfActiveFormattingElements(); int listLen = snapshot.getListOfActiveFormattingElementsLength(); if (stackLen != currentPtr + 1 || listLen != listPtr + 1 || formPointer != snapshot.getFormPointer() || headPointer != snapshot.getHeadPointer() || deepTreeSurrogateParent != snapshot.getDeepTreeSurrogateParent() || mode != snapshot.getMode() || originalMode != snapshot.getOriginalMode() || framesetOk != snapshot.isFramesetOk() || inForeign != snapshot.isInForeign() || needToDropLF != snapshot.isNeedToDropLF() || quirks != snapshot.isQuirks()) { // maybe just assert quirks return false; } for (int i = listLen - 1; i >= 0; i--) { if (listCopy[i] == null && listOfActiveFormattingElements[i] == null) { continue; } else if (listCopy[i] == null || listOfActiveFormattingElements[i] == null) { return false; } if (listCopy[i].node != listOfActiveFormattingElements[i].node) { return false; // it's possible that this condition is overly // strict } } for (int i = stackLen - 1; i >= 0; i--) { if (stackCopy[i].node != stack[i].node) { return false; } } return true; } @SuppressWarnings("unchecked") public void loadState( TreeBuilderState<T> snapshot, Interner interner) throws SAXException { StackNode<T>[] stackCopy = snapshot.getStack(); int stackLen = snapshot.getStackLength(); StackNode<T>[] listCopy = snapshot.getListOfActiveFormattingElements(); int listLen = snapshot.getListOfActiveFormattingElementsLength(); for (int i = 0; i <= listPtr; i++) { if (listOfActiveFormattingElements[i] != null) { listOfActiveFormattingElements[i].release(); } } if (listOfActiveFormattingElements.length < listLen) { listOfActiveFormattingElements = new StackNode[listLen]; } listPtr = listLen - 1; for (int i = 0; i <= currentPtr; i++) { stack[i].release(); } if (stack.length < stackLen) { stack = new StackNode[stackLen]; } currentPtr = stackLen - 1; for (int i = 0; i < listLen; i++) { StackNode<T> node = listCopy[i]; if (node != null) { StackNode<T> newNode = new StackNode<T>(node.group, node.ns, Portability.newLocalFromLocal(node.name, interner), node.node, node.scoping, node.special, node.fosterParenting, Portability.newLocalFromLocal(node.popName, interner), node.attributes.cloneAttributes(null)); listOfActiveFormattingElements[i] = newNode; } else { listOfActiveFormattingElements[i] = null; } } for (int i = 0; i < stackLen; i++) { StackNode<T> node = stackCopy[i]; int listIndex = findInArray(node, listCopy); if (listIndex == -1) { StackNode<T> newNode = new StackNode<T>(node.group, node.ns, Portability.newLocalFromLocal(node.name, interner), node.node, node.scoping, node.special, node.fosterParenting, Portability.newLocalFromLocal(node.popName, interner), null); stack[i] = newNode; } else { stack[i] = listOfActiveFormattingElements[listIndex]; stack[i].retain(); } } Portability.releaseElement(formPointer); formPointer = snapshot.getFormPointer(); Portability.retainElement(formPointer); Portability.releaseElement(headPointer); headPointer = snapshot.getHeadPointer(); Portability.retainElement(headPointer); Portability.releaseElement(deepTreeSurrogateParent); deepTreeSurrogateParent = snapshot.getDeepTreeSurrogateParent(); Portability.retainElement(deepTreeSurrogateParent); mode = snapshot.getMode(); originalMode = snapshot.getOriginalMode(); framesetOk = snapshot.isFramesetOk(); inForeign = snapshot.isInForeign(); needToDropLF = snapshot.isNeedToDropLF(); quirks = snapshot.isQuirks(); } private int findInArray(StackNode<T> node, StackNode<T>[] arr) { for (int i = listPtr; i >= 0; i--) { if (node == arr[i]) { return i; } } return -1; } /** * @see nu.validator.htmlparser.impl.TreeBuilderState#getFormPointer() */ public T getFormPointer() { return formPointer; } /** * Returns the headPointer. * * @return the headPointer */ public T getHeadPointer() { return headPointer; } /** * Returns the deepTreeSurrogateParent. * * @return the deepTreeSurrogateParent */ public T getDeepTreeSurrogateParent() { return deepTreeSurrogateParent; } /** * @see nu.validator.htmlparser.impl.TreeBuilderState#getListOfActiveFormattingElements() */ public StackNode<T>[] getListOfActiveFormattingElements() { return listOfActiveFormattingElements; } /** * @see nu.validator.htmlparser.impl.TreeBuilderState#getStack() */ public StackNode<T>[] getStack() { return stack; } /** * Returns the mode. * * @return the mode */ public int getMode() { return mode; } /** * Returns the originalMode. * * @return the originalMode */ public int getOriginalMode() { return originalMode; } /** * Returns the framesetOk. * * @return the framesetOk */ public boolean isFramesetOk() { return framesetOk; } /** * Returns the foreignFlag. * * @return the foreignFlag */ public boolean isInForeign() { return inForeign; } /** * Returns the needToDropLF. * * @return the needToDropLF */ public boolean isNeedToDropLF() { return needToDropLF; } /** * Returns the quirks. * * @return the quirks */ public boolean isQuirks() { return quirks; } /** * @see nu.validator.htmlparser.impl.TreeBuilderState#getListOfActiveFormattingElementsLength() */ public int getListOfActiveFormattingElementsLength() { return listPtr + 1; } /** * @see nu.validator.htmlparser.impl.TreeBuilderState#getStackLength() */ public int getStackLength() { return currentPtr + 1; } }
true
true
public final void startTag(ElementName elementName, HtmlAttributes attributes, boolean selfClosing) throws SAXException { flushCharacters(); // [NOCPP[ if (errorHandler != null) { // ID uniqueness @IdType String id = attributes.getId(); if (id != null) { LocatorImpl oldLoc = idLocations.get(id); if (oldLoc != null) { err("Duplicate ID \u201C" + id + "\u201D."); errorHandler.warning(new SAXParseException( "The first occurrence of ID \u201C" + id + "\u201D was here.", oldLoc)); } else { idLocations.put(id, new LocatorImpl(tokenizer)); } } } // ]NOCPP] int eltPos; needToDropLF = false; boolean needsPostProcessing = false; starttagloop: for (;;) { int group = elementName.group; @Local String name = elementName.name; if (inForeign) { StackNode<T> currentNode = stack[currentPtr]; @NsUri String currNs = currentNode.ns; int currGroup = currentNode.group; if (("http://www.w3.org/1999/xhtml" == currNs) || ("http://www.w3.org/1998/Math/MathML" == currNs && ((MGLYPH_OR_MALIGNMARK != group && MI_MO_MN_MS_MTEXT == currGroup) || (SVG == group && ANNOTATION_XML == currGroup))) || ("http://www.w3.org/2000/svg" == currNs && (TITLE == currGroup || (FOREIGNOBJECT_OR_DESC == currGroup)))) { needsPostProcessing = true; // fall through to non-foreign behavior } else { switch (group) { case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U: case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU: case BODY: case BR: case RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR: case DD_OR_DT: case UL_OR_OL_OR_DL: case EMBED_OR_IMG: case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: case HEAD: case HR: case LI: case META: case NOBR: case P: case PRE_OR_LISTING: case TABLE: err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (!isSpecialParentInForeign(stack[currentPtr])) { pop(); } if (!hasForeignInScope()) { inForeign = false; } continue starttagloop; case FONT: if (attributes.contains(AttributeName.COLOR) || attributes.contains(AttributeName.FACE) || attributes.contains(AttributeName.SIZE)) { err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (!isSpecialParentInForeign(stack[currentPtr])) { pop(); } if (!hasForeignInScope()) { inForeign = false; } continue starttagloop; } // else fall thru default: if ("http://www.w3.org/2000/svg" == currNs) { attributes.adjustForSvg(); if (selfClosing) { appendVoidElementToCurrentMayFosterCamelCase( currNs, elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFosterCamelCase( currNs, elementName, attributes); } attributes = null; // CPP break starttagloop; } else { attributes.adjustForMath(); if (selfClosing) { appendVoidElementToCurrentMayFoster( currNs, elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFosterNoScoping( currNs, elementName, attributes); } attributes = null; // CPP break starttagloop; } } // switch } // foreignObject / annotation-xml } switch (mode) { case IN_TABLE_BODY: switch (group) { case TR: clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot()); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_ROW; attributes = null; // CPP break starttagloop; case TD_OR_TH: err("\u201C" + name + "\u201D start tag in table body."); clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot()); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.TR, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_ROW; continue; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: eltPos = findLastInTableScopeOrRootTbodyTheadTfoot(); if (eltPos == 0) { err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } else { clearStackBackTo(eltPos); pop(); mode = IN_TABLE; continue; } default: // fall through to IN_TABLE } case IN_ROW: switch (group) { case TD_OR_TH: clearStackBackTo(findLastOrRoot(TreeBuilder.TR)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_CELL; insertMarker(); attributes = null; // CPP break starttagloop; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: eltPos = findLastOrRoot(TreeBuilder.TR); if (eltPos == 0) { assert fragment; err("No table row to close."); break starttagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE_BODY; continue; default: // fall through to IN_TABLE } case IN_TABLE: intableloop: for (;;) { switch (group) { case CAPTION: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); insertMarker(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_CAPTION; attributes = null; // CPP break starttagloop; case COLGROUP: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_COLUMN_GROUP; attributes = null; // CPP break starttagloop; case COL: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.COLGROUP, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_COLUMN_GROUP; continue starttagloop; case TBODY_OR_THEAD_OR_TFOOT: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_TABLE_BODY; attributes = null; // CPP break starttagloop; case TR: case TD_OR_TH: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.TBODY, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_TABLE_BODY; continue starttagloop; case TABLE: err("Start tag for \u201Ctable\u201D seen but the previous \u201Ctable\u201D is still open."); eltPos = findLastInTableScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; } generateImpliedEndTags(); // XXX is the next if dead code? if (errorHandler != null && !isCurrent("table")) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue starttagloop; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case INPUT: if (!Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "hidden", attributes.getValue(AttributeName.TYPE))) { break intableloop; } appendVoidElementToCurrent( "http://www.w3.org/1999/xhtml", name, attributes, formPointer); selfClosing = false; attributes = null; // CPP break starttagloop; case FORM: if (formPointer != null) { err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag."); break starttagloop; } else { err("Start tag \u201Cform\u201D seen in \u201Ctable\u201D."); appendVoidFormToCurrent(attributes); attributes = null; // CPP break starttagloop; } default: err("Start tag \u201C" + name + "\u201D seen in \u201Ctable\u201D."); // fall through to IN_BODY break intableloop; } } case IN_CAPTION: switch (group) { case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: err("Stray \u201C" + name + "\u201D start tag in \u201Ccaption\u201D."); eltPos = findLastInTableScope("caption"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { break starttagloop; } generateImpliedEndTags(); if (errorHandler != null && currentPtr != eltPos) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); mode = IN_TABLE; continue; default: // fall through to IN_BODY } case IN_CELL: switch (group) { case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: eltPos = findLastInTableScopeTdTh(); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("No cell to close."); break starttagloop; } else { closeTheCell(eltPos); continue; } default: // fall through to IN_BODY } case FRAMESET_OK: switch (group) { case FRAMESET: if (mode == FRAMESET_OK) { if (currentPtr == 0 || stack[1].group != BODY) { assert fragment; err("Stray \u201Cframeset\u201D start tag."); break starttagloop; } else { err("\u201Cframeset\u201D start tag seen."); detachFromParent(stack[1].node); while (currentPtr > 0) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_FRAMESET; attributes = null; // CPP break starttagloop; } } else { err("Stray \u201Cframeset\u201D start tag."); break starttagloop; } // NOT falling through! case PRE_OR_LISTING: case LI: case DD_OR_DT: case BUTTON: case MARQUEE_OR_APPLET: case OBJECT: case TABLE: case AREA_OR_WBR: case BR: case EMBED_OR_IMG: case INPUT: case KEYGEN: case HR: case TEXTAREA: case XMP: case IFRAME: case SELECT: if (mode == FRAMESET_OK && !(group == INPUT && Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "hidden", attributes.getValue(AttributeName.TYPE)))) { framesetOk = false; mode = IN_BODY; } // fall through to IN_BODY default: // fall through to IN_BODY } case IN_BODY: inbodyloop: for (;;) { switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BASE: case LINK_OR_BASEFONT_OR_BGSOUND: case META: case STYLE: case SCRIPT: case TITLE: case COMMAND: // Fall through to IN_HEAD break inbodyloop; case BODY: err("\u201Cbody\u201D start tag found but the \u201Cbody\u201D element is already open."); if (addAttributesToBody(attributes)) { attributes = null; // CPP } break starttagloop; case P: case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU: case UL_OR_OL_OR_DL: case ADDRESS_OR_ARTICLE_OR_ASIDE_OR_DETAILS_OR_DIR_OR_FIGCAPTION_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_HGROUP_OR_NAV_OR_SECTION_OR_SUMMARY: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: implicitlyCloseP(); if (stack[currentPtr].group == H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) { err("Heading cannot be a child of another heading."); pop(); } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case FIELDSET: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; case PRE_OR_LISTING: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); needToDropLF = true; attributes = null; // CPP break starttagloop; case FORM: if (formPointer != null) { err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag."); break starttagloop; } else { implicitlyCloseP(); appendToCurrentNodeAndPushFormElementMayFoster(attributes); attributes = null; // CPP break starttagloop; } case LI: case DD_OR_DT: eltPos = currentPtr; for (;;) { StackNode<T> node = stack[eltPos]; // weak // ref if (node.group == group) { // LI or // DD_OR_DT generateImpliedEndTagsExceptFor(node.name); if (errorHandler != null && eltPos != currentPtr) { errNoCheck("Unclosed elements inside a list."); } while (currentPtr >= eltPos) { pop(); } break; } else if (node.scoping || (node.special && node.name != "p" && node.name != "address" && node.name != "div")) { break; } eltPos--; } implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case PLAINTEXT: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); tokenizer.setStateAndEndTagExpectation( Tokenizer.PLAINTEXT, elementName); attributes = null; // CPP break starttagloop; case A: int activeAPos = findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker("a"); if (activeAPos != -1) { err("An \u201Ca\u201D start tag seen with already an active \u201Ca\u201D element."); StackNode<T> activeA = listOfActiveFormattingElements[activeAPos]; activeA.retain(); adoptionAgencyEndTag("a"); removeFromStack(activeA); activeAPos = findInListOfActiveFormattingElements(activeA); if (activeAPos != -1) { removeFromListOfActiveFormattingElements(activeAPos); } activeA.release(); } reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U: case FONT: reconstructTheActiveFormattingElements(); maybeForgetEarlierDuplicateFormattingElement(elementName.name, attributes); appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case NOBR: reconstructTheActiveFormattingElements(); if (TreeBuilder.NOT_FOUND_ON_STACK != findLastInScope("nobr")) { err("\u201Cnobr\u201D start tag seen when there was an open \u201Cnobr\u201D element in scope."); adoptionAgencyEndTag("nobr"); } appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case BUTTON: eltPos = findLastInScope(name); if (eltPos != TreeBuilder.NOT_FOUND_ON_STACK) { err("\u201Cbutton\u201D start tag seen when there was an open \u201Cbutton\u201D element in scope."); generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201Cbutton\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } continue starttagloop; } else { reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; } case OBJECT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); insertMarker(); attributes = null; // CPP break starttagloop; case MARQUEE_OR_APPLET: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); insertMarker(); attributes = null; // CPP break starttagloop; case TABLE: // The only quirk. Blame Hixie and // Acid2. if (!quirks) { implicitlyCloseP(); } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_TABLE; attributes = null; // CPP break starttagloop; case BR: case EMBED_OR_IMG: case AREA_OR_WBR: reconstructTheActiveFormattingElements(); // FALL THROUGH to PARAM_OR_SOURCE case PARAM_OR_SOURCE: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case HR: implicitlyCloseP(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case IMAGE: err("Saw a start tag \u201Cimage\u201D."); elementName = ElementName.IMG; continue starttagloop; case KEYGEN: case INPUT: reconstructTheActiveFormattingElements(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", name, attributes, formPointer); selfClosing = false; attributes = null; // CPP break starttagloop; case ISINDEX: err("\u201Cisindex\u201D seen."); if (formPointer != null) { break starttagloop; } implicitlyCloseP(); HtmlAttributes formAttrs = new HtmlAttributes(0); int actionIndex = attributes.getIndex(AttributeName.ACTION); if (actionIndex > -1) { formAttrs.addAttribute( AttributeName.ACTION, attributes.getValue(actionIndex) // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); } appendToCurrentNodeAndPushFormElementMayFoster(formAttrs); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", ElementName.HR, HtmlAttributes.EMPTY_ATTRIBUTES); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", ElementName.LABEL, HtmlAttributes.EMPTY_ATTRIBUTES); int promptIndex = attributes.getIndex(AttributeName.PROMPT); if (promptIndex > -1) { @Auto char[] prompt = Portability.newCharArrayFromString(attributes.getValue(promptIndex)); appendCharacters(stack[currentPtr].node, prompt, 0, prompt.length); } else { appendIsindexPrompt(stack[currentPtr].node); } HtmlAttributes inputAttributes = new HtmlAttributes( 0); inputAttributes.addAttribute( AttributeName.NAME, Portability.newStringFromLiteral("isindex") // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); for (int i = 0; i < attributes.getLength(); i++) { AttributeName attributeQName = attributes.getAttributeName(i); if (AttributeName.NAME == attributeQName || AttributeName.PROMPT == attributeQName) { attributes.releaseValue(i); } else if (AttributeName.ACTION != attributeQName) { inputAttributes.addAttribute( attributeQName, attributes.getValue(i) // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); } } attributes.clearWithoutReleasingContents(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", "input", inputAttributes, formPointer); pop(); // label appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", ElementName.HR, HtmlAttributes.EMPTY_ATTRIBUTES); pop(); // form selfClosing = false; // Portability.delete(formAttrs); // Portability.delete(inputAttributes); // Don't delete attributes, they are deleted // later break starttagloop; case TEXTAREA: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); originalMode = mode; mode = TEXT; needToDropLF = true; attributes = null; // CPP break starttagloop; case XMP: implicitlyCloseP(); reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case NOSCRIPT: if (!scriptingEnabled) { reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; } else { // fall through } case NOFRAMES: case IFRAME: case NOEMBED: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case SELECT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); switch (mode) { case IN_TABLE: case IN_CAPTION: case IN_COLUMN_GROUP: case IN_TABLE_BODY: case IN_ROW: case IN_CELL: mode = IN_SELECT_IN_TABLE; break; default: mode = IN_SELECT; break; } attributes = null; // CPP break starttagloop; case OPTGROUP: case OPTION: /* * If the stack of open elements has an option * element in scope, then act as if an end tag * with the tag name "option" had been seen. */ if (findLastInScope("option") != TreeBuilder.NOT_FOUND_ON_STACK) { optionendtagloop: for (;;) { if (isCurrent("option")) { pop(); break optionendtagloop; } eltPos = currentPtr; for (;;) { if (stack[eltPos].name == "option") { generateImpliedEndTags(); if (errorHandler != null && !isCurrent("option")) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } break optionendtagloop; } eltPos--; } } } /* * Reconstruct the active formatting elements, * if any. */ reconstructTheActiveFormattingElements(); /* * Insert an HTML element for the token. */ appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case RT_OR_RP: /* * If the stack of open elements has a ruby * element in scope, then generate implied end * tags. If the current node is not then a ruby * element, this is a parse error; pop all the * nodes from the current node up to the node * immediately before the bottommost ruby * element on the stack of open elements. * * Insert an HTML element for the token. */ eltPos = findLastInScope("ruby"); if (eltPos != NOT_FOUND_ON_STACK) { generateImpliedEndTags(); } if (eltPos != currentPtr) { err("Unclosed children in \u201Cruby\u201D."); while (currentPtr > eltPos) { pop(); } } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case MATH: reconstructTheActiveFormattingElements(); attributes.adjustForMath(); if (selfClosing) { appendVoidElementToCurrentMayFoster( "http://www.w3.org/1998/Math/MathML", elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1998/Math/MathML", elementName, attributes); inForeign = true; } attributes = null; // CPP break starttagloop; case SVG: reconstructTheActiveFormattingElements(); attributes.adjustForSvg(); if (selfClosing) { appendVoidElementToCurrentMayFosterCamelCase( "http://www.w3.org/2000/svg", elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/2000/svg", elementName, attributes); inForeign = true; } attributes = null; // CPP break starttagloop; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: case FRAME: case FRAMESET: case HEAD: err("Stray start tag \u201C" + name + "\u201D."); break starttagloop; case OUTPUT_OR_LABEL: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; default: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; } } case IN_HEAD: inheadloop: for (;;) { switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BASE: case COMMAND: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case META: case LINK_OR_BASEFONT_OR_BGSOUND: // Fall through to IN_HEAD_NOSCRIPT break inheadloop; case TITLE: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); attributes = null; // CPP break starttagloop; case NOSCRIPT: if (scriptingEnabled) { appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_HEAD_NOSCRIPT; } attributes = null; // CPP break starttagloop; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case HEAD: /* Parse error. */ err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open."); /* Ignore the token. */ break starttagloop; default: pop(); mode = AFTER_HEAD; continue starttagloop; } } case IN_HEAD_NOSCRIPT: switch (group) { case HTML: // XXX did Hixie really mean to omit "base" // here? err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case LINK_OR_BASEFONT_OR_BGSOUND: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case META: checkMetaCharset(attributes); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case HEAD: err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open."); break starttagloop; case NOSCRIPT: err("Start tag for \u201Cnoscript\u201D seen when \u201Cnoscript\u201D was already open."); break starttagloop; default: err("Bad start tag in \u201C" + name + "\u201D in \u201Chead\u201D."); pop(); mode = IN_HEAD; continue; } case IN_COLUMN_GROUP: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case COL: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; default: if (currentPtr == 0) { assert fragment; err("Garbage in \u201Ccolgroup\u201D fragment."); break starttagloop; } pop(); mode = IN_TABLE; continue; } case IN_SELECT_IN_TABLE: switch (group) { case CAPTION: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: case TABLE: err("\u201C" + name + "\u201D start tag with \u201Cselect\u201D open."); eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375 } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue; default: // fall through to IN_SELECT } case IN_SELECT: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case OPTION: if (isCurrent("option")) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case OPTGROUP: if (isCurrent("option")) { pop(); } if (isCurrent("optgroup")) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case SELECT: err("\u201Cselect\u201D start tag where end tag expected."); eltPos = findLastInTableScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; err("No \u201Cselect\u201D in table scope."); break starttagloop; } else { while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); break starttagloop; } case INPUT: case TEXTAREA: case KEYGEN: err("\u201C" + name + "\u201D start tag seen in \u201Cselect\2201D."); eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case AFTER_BODY: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; } case IN_FRAMESET: switch (group) { case FRAMESET: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case FRAME: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; default: // fall through to AFTER_FRAMESET } case AFTER_FRAMESET: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case NOFRAMES: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case INITIAL: /* * Parse error. */ // [NOCPP[ switch (doctypeExpectation) { case AUTO: err("Start tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D."); break; case HTML: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D."); break; case HTML401_STRICT: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); break; case HTML401_TRANSITIONAL: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); break; case NO_DOCTYPE_ERRORS: } // ]NOCPP] /* * * Set the document to quirks mode. */ documentModeInternal(DocumentMode.QUIRKS_MODE, null, null, false); /* * Then, switch to the root element mode of the tree * construction stage */ mode = BEFORE_HTML; /* * and reprocess the current token. */ continue; case BEFORE_HTML: switch (group) { case HTML: // optimize error check and streaming SAX by // hoisting // "html" handling here. if (attributes == HtmlAttributes.EMPTY_ATTRIBUTES) { // This has the right magic side effect // that // it // makes attributes in SAX Tree mutable. appendHtmlElementToDocumentAndPush(); } else { appendHtmlElementToDocumentAndPush(attributes); } // XXX application cache should fire here mode = BEFORE_HEAD; attributes = null; // CPP break starttagloop; default: /* * Create an HTMLElement node with the tag name * html, in the HTML namespace. Append it to the * Document object. */ appendHtmlElementToDocumentAndPush(); /* Switch to the main mode */ mode = BEFORE_HEAD; /* * reprocess the current token. */ continue; } case BEFORE_HEAD: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case HEAD: /* * A start tag whose tag name is "head" * * Create an element for the token. * * Set the head element pointer to this new element * node. * * Append the new element to the current node and * push it onto the stack of open elements. */ appendToCurrentNodeAndPushHeadElement(attributes); /* * Change the insertion mode to "in head". */ mode = IN_HEAD; attributes = null; // CPP break starttagloop; default: /* * Any other start tag token * * Act as if a start tag token with the tag name * "head" and no attributes had been seen, */ appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_HEAD; /* * then reprocess the current token. * * This will result in an empty head element being * generated, with the current token being * reprocessed in the "after head" insertion mode. */ continue; } case AFTER_HEAD: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BODY: if (attributes.getLength() == 0) { // This has the right magic side effect // that // it // makes attributes in SAX Tree mutable. appendToCurrentNodeAndPushBodyElement(); } else { appendToCurrentNodeAndPushBodyElement(attributes); } framesetOk = false; mode = IN_BODY; attributes = null; // CPP break starttagloop; case FRAMESET: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_FRAMESET; attributes = null; // CPP break starttagloop; case BASE: err("\u201Cbase\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case LINK_OR_BASEFONT_OR_BGSOUND: err("\u201Clink\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case META: err("\u201Cmeta\u201D element outside \u201Chead\u201D."); checkMetaCharset(attributes); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case SCRIPT: err("\u201Cscript\u201D element between \u201Chead\u201D and \u201Cbody\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: err("\u201C" + name + "\u201D element between \u201Chead\u201D and \u201Cbody\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case TITLE: err("\u201Ctitle\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); attributes = null; // CPP break starttagloop; case HEAD: err("Stray start tag \u201Chead\u201D."); break starttagloop; default: appendToCurrentNodeAndPushBodyElement(); mode = FRAMESET_OK; continue; } case AFTER_AFTER_BODY: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); fatal(); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; } case AFTER_AFTER_FRAMESET: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case NOFRAMES: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case TEXT: assert false; break starttagloop; // Avoid infinite loop if the assertion // fails } } if (needsPostProcessing && inForeign && !hasForeignInScope()) { /* * If, after doing so, the insertion mode is still "in foreign * content", but there is no element in scope that has a namespace * other than the HTML namespace, switch the insertion mode to the * secondary insertion mode. */ inForeign = false; } if (errorHandler != null && selfClosing) { errNoCheck("Self-closing syntax (\u201C/>\u201D) used on a non-void HTML element. Ignoring the slash and treating as a start tag."); } if (attributes != HtmlAttributes.EMPTY_ATTRIBUTES) { Portability.delete(attributes); } }
public final void startTag(ElementName elementName, HtmlAttributes attributes, boolean selfClosing) throws SAXException { flushCharacters(); // [NOCPP[ if (errorHandler != null) { // ID uniqueness @IdType String id = attributes.getId(); if (id != null) { LocatorImpl oldLoc = idLocations.get(id); if (oldLoc != null) { err("Duplicate ID \u201C" + id + "\u201D."); errorHandler.warning(new SAXParseException( "The first occurrence of ID \u201C" + id + "\u201D was here.", oldLoc)); } else { idLocations.put(id, new LocatorImpl(tokenizer)); } } } // ]NOCPP] int eltPos; needToDropLF = false; boolean needsPostProcessing = false; starttagloop: for (;;) { int group = elementName.group; @Local String name = elementName.name; if (inForeign) { StackNode<T> currentNode = stack[currentPtr]; @NsUri String currNs = currentNode.ns; int currGroup = currentNode.group; if (("http://www.w3.org/1999/xhtml" == currNs) || ("http://www.w3.org/1998/Math/MathML" == currNs && ((MGLYPH_OR_MALIGNMARK != group && MI_MO_MN_MS_MTEXT == currGroup) || (SVG == group && ANNOTATION_XML == currGroup))) || ("http://www.w3.org/2000/svg" == currNs && (TITLE == currGroup || (FOREIGNOBJECT_OR_DESC == currGroup)))) { needsPostProcessing = true; // fall through to non-foreign behavior } else { switch (group) { case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U: case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU: case BODY: case BR: case RUBY_OR_SPAN_OR_SUB_OR_SUP_OR_VAR: case DD_OR_DT: case UL_OR_OL_OR_DL: case EMBED_OR_IMG: case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: case HEAD: case HR: case LI: case META: case NOBR: case P: case PRE_OR_LISTING: case TABLE: err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (!isSpecialParentInForeign(stack[currentPtr])) { pop(); } if (!hasForeignInScope()) { inForeign = false; } continue starttagloop; case FONT: if (attributes.contains(AttributeName.COLOR) || attributes.contains(AttributeName.FACE) || attributes.contains(AttributeName.SIZE)) { err("HTML start tag \u201C" + name + "\u201D in a foreign namespace context."); while (!isSpecialParentInForeign(stack[currentPtr])) { pop(); } if (!hasForeignInScope()) { inForeign = false; } continue starttagloop; } // else fall thru default: if ("http://www.w3.org/2000/svg" == currNs) { attributes.adjustForSvg(); if (selfClosing) { appendVoidElementToCurrentMayFosterCamelCase( currNs, elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFosterCamelCase( currNs, elementName, attributes); } attributes = null; // CPP break starttagloop; } else { attributes.adjustForMath(); if (selfClosing) { appendVoidElementToCurrentMayFoster( currNs, elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFosterNoScoping( currNs, elementName, attributes); } attributes = null; // CPP break starttagloop; } } // switch } // foreignObject / annotation-xml } switch (mode) { case IN_TABLE_BODY: switch (group) { case TR: clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot()); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_ROW; attributes = null; // CPP break starttagloop; case TD_OR_TH: err("\u201C" + name + "\u201D start tag in table body."); clearStackBackTo(findLastInTableScopeOrRootTbodyTheadTfoot()); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.TR, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_ROW; continue; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: eltPos = findLastInTableScopeOrRootTbodyTheadTfoot(); if (eltPos == 0) { err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } else { clearStackBackTo(eltPos); pop(); mode = IN_TABLE; continue; } default: // fall through to IN_TABLE } case IN_ROW: switch (group) { case TD_OR_TH: clearStackBackTo(findLastOrRoot(TreeBuilder.TR)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_CELL; insertMarker(); attributes = null; // CPP break starttagloop; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: eltPos = findLastOrRoot(TreeBuilder.TR); if (eltPos == 0) { assert fragment; err("No table row to close."); break starttagloop; } clearStackBackTo(eltPos); pop(); mode = IN_TABLE_BODY; continue; default: // fall through to IN_TABLE } case IN_TABLE: intableloop: for (;;) { switch (group) { case CAPTION: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); insertMarker(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_CAPTION; attributes = null; // CPP break starttagloop; case COLGROUP: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_COLUMN_GROUP; attributes = null; // CPP break starttagloop; case COL: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.COLGROUP, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_COLUMN_GROUP; continue starttagloop; case TBODY_OR_THEAD_OR_TFOOT: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_TABLE_BODY; attributes = null; // CPP break starttagloop; case TR: case TD_OR_TH: clearStackBackTo(findLastOrRoot(TreeBuilder.TABLE)); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", ElementName.TBODY, HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_TABLE_BODY; continue starttagloop; case TABLE: err("Start tag for \u201Ctable\u201D seen but the previous \u201Ctable\u201D is still open."); eltPos = findLastInTableScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; } generateImpliedEndTags(); // XXX is the next if dead code? if (errorHandler != null && !isCurrent("table")) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue starttagloop; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case INPUT: if (!Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "hidden", attributes.getValue(AttributeName.TYPE))) { break intableloop; } appendVoidElementToCurrent( "http://www.w3.org/1999/xhtml", name, attributes, formPointer); selfClosing = false; attributes = null; // CPP break starttagloop; case FORM: if (formPointer != null) { err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag."); break starttagloop; } else { err("Start tag \u201Cform\u201D seen in \u201Ctable\u201D."); appendVoidFormToCurrent(attributes); attributes = null; // CPP break starttagloop; } default: err("Start tag \u201C" + name + "\u201D seen in \u201Ctable\u201D."); // fall through to IN_BODY break intableloop; } } case IN_CAPTION: switch (group) { case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: err("Stray \u201C" + name + "\u201D start tag in \u201Ccaption\u201D."); eltPos = findLastInTableScope("caption"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { break starttagloop; } generateImpliedEndTags(); if (errorHandler != null && currentPtr != eltPos) { errNoCheck("Unclosed elements on stack."); } while (currentPtr >= eltPos) { pop(); } clearTheListOfActiveFormattingElementsUpToTheLastMarker(); mode = IN_TABLE; continue; default: // fall through to IN_BODY } case IN_CELL: switch (group) { case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: eltPos = findLastInTableScopeTdTh(); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { err("No cell to close."); break starttagloop; } else { closeTheCell(eltPos); continue; } default: // fall through to IN_BODY } case FRAMESET_OK: switch (group) { case FRAMESET: if (mode == FRAMESET_OK) { if (currentPtr == 0 || stack[1].group != BODY) { assert fragment; err("Stray \u201Cframeset\u201D start tag."); break starttagloop; } else { err("\u201Cframeset\u201D start tag seen."); detachFromParent(stack[1].node); while (currentPtr > 0) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_FRAMESET; attributes = null; // CPP break starttagloop; } } else { err("Stray \u201Cframeset\u201D start tag."); break starttagloop; } // NOT falling through! case PRE_OR_LISTING: case LI: case DD_OR_DT: case BUTTON: case MARQUEE_OR_APPLET: case OBJECT: case TABLE: case AREA_OR_WBR: case BR: case EMBED_OR_IMG: case INPUT: case KEYGEN: case HR: case TEXTAREA: case XMP: case IFRAME: case SELECT: if (mode == FRAMESET_OK && !(group == INPUT && Portability.lowerCaseLiteralEqualsIgnoreAsciiCaseString( "hidden", attributes.getValue(AttributeName.TYPE)))) { framesetOk = false; mode = IN_BODY; } // fall through to IN_BODY default: // fall through to IN_BODY } case IN_BODY: inbodyloop: for (;;) { switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BASE: case LINK_OR_BASEFONT_OR_BGSOUND: case META: case STYLE: case SCRIPT: case TITLE: case COMMAND: // Fall through to IN_HEAD break inbodyloop; case BODY: err("\u201Cbody\u201D start tag found but the \u201Cbody\u201D element is already open."); if (addAttributesToBody(attributes)) { attributes = null; // CPP } break starttagloop; case P: case DIV_OR_BLOCKQUOTE_OR_CENTER_OR_MENU: case UL_OR_OL_OR_DL: case ADDRESS_OR_ARTICLE_OR_ASIDE_OR_DETAILS_OR_DIR_OR_FIGCAPTION_OR_FIGURE_OR_FOOTER_OR_HEADER_OR_HGROUP_OR_NAV_OR_SECTION_OR_SUMMARY: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6: implicitlyCloseP(); if (stack[currentPtr].group == H1_OR_H2_OR_H3_OR_H4_OR_H5_OR_H6) { err("Heading cannot be a child of another heading."); pop(); } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case FIELDSET: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; case PRE_OR_LISTING: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); needToDropLF = true; attributes = null; // CPP break starttagloop; case FORM: if (formPointer != null) { err("Saw a \u201Cform\u201D start tag, but there was already an active \u201Cform\u201D element. Nested forms are not allowed. Ignoring the tag."); break starttagloop; } else { implicitlyCloseP(); appendToCurrentNodeAndPushFormElementMayFoster(attributes); attributes = null; // CPP break starttagloop; } case LI: case DD_OR_DT: eltPos = currentPtr; for (;;) { StackNode<T> node = stack[eltPos]; // weak // ref if (node.group == group) { // LI or // DD_OR_DT generateImpliedEndTagsExceptFor(node.name); if (errorHandler != null && eltPos != currentPtr) { errNoCheck("Unclosed elements inside a list."); } while (currentPtr >= eltPos) { pop(); } break; } else if (node.scoping || (node.special && node.name != "p" && node.name != "address" && node.name != "div")) { break; } eltPos--; } implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case PLAINTEXT: implicitlyCloseP(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); tokenizer.setStateAndEndTagExpectation( Tokenizer.PLAINTEXT, elementName); attributes = null; // CPP break starttagloop; case A: int activeAPos = findInListOfActiveFormattingElementsContainsBetweenEndAndLastMarker("a"); if (activeAPos != -1) { err("An \u201Ca\u201D start tag seen with already an active \u201Ca\u201D element."); StackNode<T> activeA = listOfActiveFormattingElements[activeAPos]; activeA.retain(); adoptionAgencyEndTag("a"); removeFromStack(activeA); activeAPos = findInListOfActiveFormattingElements(activeA); if (activeAPos != -1) { removeFromListOfActiveFormattingElements(activeAPos); } activeA.release(); } reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case B_OR_BIG_OR_CODE_OR_EM_OR_I_OR_S_OR_SMALL_OR_STRIKE_OR_STRONG_OR_TT_OR_U: case FONT: reconstructTheActiveFormattingElements(); maybeForgetEarlierDuplicateFormattingElement(elementName.name, attributes); appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case NOBR: reconstructTheActiveFormattingElements(); if (TreeBuilder.NOT_FOUND_ON_STACK != findLastInScope("nobr")) { err("\u201Cnobr\u201D start tag seen when there was an open \u201Cnobr\u201D element in scope."); adoptionAgencyEndTag("nobr"); } appendToCurrentNodeAndPushFormattingElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case BUTTON: eltPos = findLastInScope(name); if (eltPos != TreeBuilder.NOT_FOUND_ON_STACK) { err("\u201Cbutton\u201D start tag seen when there was an open \u201Cbutton\u201D element in scope."); generateImpliedEndTags(); if (errorHandler != null && !isCurrent(name)) { errNoCheck("End tag \u201Cbutton\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } continue starttagloop; } else { reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; } case OBJECT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); insertMarker(); attributes = null; // CPP break starttagloop; case MARQUEE_OR_APPLET: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); insertMarker(); attributes = null; // CPP break starttagloop; case TABLE: // The only quirk. Blame Hixie and // Acid2. if (!quirks) { implicitlyCloseP(); } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_TABLE; attributes = null; // CPP break starttagloop; case BR: case EMBED_OR_IMG: case AREA_OR_WBR: reconstructTheActiveFormattingElements(); // FALL THROUGH to PARAM_OR_SOURCE case PARAM_OR_SOURCE: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case HR: implicitlyCloseP(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case IMAGE: err("Saw a start tag \u201Cimage\u201D."); elementName = ElementName.IMG; continue starttagloop; case KEYGEN: case INPUT: reconstructTheActiveFormattingElements(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", name, attributes, formPointer); selfClosing = false; attributes = null; // CPP break starttagloop; case ISINDEX: err("\u201Cisindex\u201D seen."); if (formPointer != null) { break starttagloop; } implicitlyCloseP(); HtmlAttributes formAttrs = new HtmlAttributes(0); int actionIndex = attributes.getIndex(AttributeName.ACTION); if (actionIndex > -1) { formAttrs.addAttribute( AttributeName.ACTION, attributes.getValue(actionIndex) // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); } appendToCurrentNodeAndPushFormElementMayFoster(formAttrs); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", ElementName.HR, HtmlAttributes.EMPTY_ATTRIBUTES); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", ElementName.LABEL, HtmlAttributes.EMPTY_ATTRIBUTES); int promptIndex = attributes.getIndex(AttributeName.PROMPT); if (promptIndex > -1) { @Auto char[] prompt = Portability.newCharArrayFromString(attributes.getValue(promptIndex)); appendCharacters(stack[currentPtr].node, prompt, 0, prompt.length); } else { appendIsindexPrompt(stack[currentPtr].node); } HtmlAttributes inputAttributes = new HtmlAttributes( 0); inputAttributes.addAttribute( AttributeName.NAME, Portability.newStringFromLiteral("isindex") // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); for (int i = 0; i < attributes.getLength(); i++) { AttributeName attributeQName = attributes.getAttributeName(i); if (AttributeName.NAME == attributeQName || AttributeName.PROMPT == attributeQName) { attributes.releaseValue(i); } else if (AttributeName.ACTION != attributeQName) { inputAttributes.addAttribute( attributeQName, attributes.getValue(i) // [NOCPP[ , XmlViolationPolicy.ALLOW // ]NOCPP] ); } } attributes.clearWithoutReleasingContents(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", "input", inputAttributes, formPointer); pop(); // label appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", ElementName.HR, HtmlAttributes.EMPTY_ATTRIBUTES); pop(); // form selfClosing = false; // Portability.delete(formAttrs); // Portability.delete(inputAttributes); // Don't delete attributes, they are deleted // later break starttagloop; case TEXTAREA: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); originalMode = mode; mode = TEXT; needToDropLF = true; attributes = null; // CPP break starttagloop; case XMP: implicitlyCloseP(); reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case NOSCRIPT: if (!scriptingEnabled) { reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; } else { // fall through } case NOFRAMES: case IFRAME: case NOEMBED: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case SELECT: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); switch (mode) { case IN_TABLE: case IN_CAPTION: case IN_COLUMN_GROUP: case IN_TABLE_BODY: case IN_ROW: case IN_CELL: mode = IN_SELECT_IN_TABLE; break; default: mode = IN_SELECT; break; } attributes = null; // CPP break starttagloop; case OPTGROUP: case OPTION: /* * If the stack of open elements has an option * element in scope, then act as if an end tag * with the tag name "option" had been seen. */ if (findLastInScope("option") != TreeBuilder.NOT_FOUND_ON_STACK) { optionendtagloop: for (;;) { if (isCurrent("option")) { pop(); break optionendtagloop; } eltPos = currentPtr; for (;;) { if (stack[eltPos].name == "option") { generateImpliedEndTags(); if (errorHandler != null && !isCurrent("option")) { errNoCheck("End tag \u201C" + name + "\u201D seen but there were unclosed elements."); } while (currentPtr >= eltPos) { pop(); } break optionendtagloop; } eltPos--; } } } /* * Reconstruct the active formatting elements, * if any. */ reconstructTheActiveFormattingElements(); /* * Insert an HTML element for the token. */ appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case RT_OR_RP: /* * If the stack of open elements has a ruby * element in scope, then generate implied end * tags. If the current node is not then a ruby * element, this is a parse error; pop all the * nodes from the current node up to the node * immediately before the bottommost ruby * element on the stack of open elements. * * Insert an HTML element for the token. */ eltPos = findLastInScope("ruby"); if (eltPos != NOT_FOUND_ON_STACK) { generateImpliedEndTags(); } if (eltPos != currentPtr) { if (eltPos != NOT_FOUND_ON_STACK) { err("Start tag \u201C" + name + "\u201D seen without a \u201Cruby\u201D element being open."); } else { err("Unclosed children in \u201Cruby\u201D."); } while (currentPtr > eltPos) { pop(); } } appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case MATH: reconstructTheActiveFormattingElements(); attributes.adjustForMath(); if (selfClosing) { appendVoidElementToCurrentMayFoster( "http://www.w3.org/1998/Math/MathML", elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1998/Math/MathML", elementName, attributes); inForeign = true; } attributes = null; // CPP break starttagloop; case SVG: reconstructTheActiveFormattingElements(); attributes.adjustForSvg(); if (selfClosing) { appendVoidElementToCurrentMayFosterCamelCase( "http://www.w3.org/2000/svg", elementName, attributes); selfClosing = false; } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/2000/svg", elementName, attributes); inForeign = true; } attributes = null; // CPP break starttagloop; case CAPTION: case COL: case COLGROUP: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: case FRAME: case FRAMESET: case HEAD: err("Stray start tag \u201C" + name + "\u201D."); break starttagloop; case OUTPUT_OR_LABEL: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes, formPointer); attributes = null; // CPP break starttagloop; default: reconstructTheActiveFormattingElements(); appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; } } case IN_HEAD: inheadloop: for (;;) { switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BASE: case COMMAND: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case META: case LINK_OR_BASEFONT_OR_BGSOUND: // Fall through to IN_HEAD_NOSCRIPT break inheadloop; case TITLE: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); attributes = null; // CPP break starttagloop; case NOSCRIPT: if (scriptingEnabled) { appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); } else { appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_HEAD_NOSCRIPT; } attributes = null; // CPP break starttagloop; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case HEAD: /* Parse error. */ err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open."); /* Ignore the token. */ break starttagloop; default: pop(); mode = AFTER_HEAD; continue starttagloop; } } case IN_HEAD_NOSCRIPT: switch (group) { case HTML: // XXX did Hixie really mean to omit "base" // here? err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case LINK_OR_BASEFONT_OR_BGSOUND: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case META: checkMetaCharset(attributes); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case HEAD: err("Start tag for \u201Chead\u201D seen when \u201Chead\u201D was already open."); break starttagloop; case NOSCRIPT: err("Start tag for \u201Cnoscript\u201D seen when \u201Cnoscript\u201D was already open."); break starttagloop; default: err("Bad start tag in \u201C" + name + "\u201D in \u201Chead\u201D."); pop(); mode = IN_HEAD; continue; } case IN_COLUMN_GROUP: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case COL: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; default: if (currentPtr == 0) { assert fragment; err("Garbage in \u201Ccolgroup\u201D fragment."); break starttagloop; } pop(); mode = IN_TABLE; continue; } case IN_SELECT_IN_TABLE: switch (group) { case CAPTION: case TBODY_OR_THEAD_OR_TFOOT: case TR: case TD_OR_TH: case TABLE: err("\u201C" + name + "\u201D start tag with \u201Cselect\u201D open."); eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; // http://www.w3.org/Bugs/Public/show_bug.cgi?id=8375 } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue; default: // fall through to IN_SELECT } case IN_SELECT: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case OPTION: if (isCurrent("option")) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case OPTGROUP: if (isCurrent("option")) { pop(); } if (isCurrent("optgroup")) { pop(); } appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case SELECT: err("\u201Cselect\u201D start tag where end tag expected."); eltPos = findLastInTableScope(name); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; err("No \u201Cselect\u201D in table scope."); break starttagloop; } else { while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); break starttagloop; } case INPUT: case TEXTAREA: case KEYGEN: err("\u201C" + name + "\u201D start tag seen in \u201Cselect\2201D."); eltPos = findLastInTableScope("select"); if (eltPos == TreeBuilder.NOT_FOUND_ON_STACK) { assert fragment; break starttagloop; } while (currentPtr >= eltPos) { pop(); } resetTheInsertionMode(); continue; case SCRIPT: // XXX need to manage much more stuff // here if // supporting // document.write() appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case AFTER_BODY: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; } case IN_FRAMESET: switch (group) { case FRAMESET: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); attributes = null; // CPP break starttagloop; case FRAME: appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; attributes = null; // CPP break starttagloop; default: // fall through to AFTER_FRAMESET } case AFTER_FRAMESET: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case NOFRAMES: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case INITIAL: /* * Parse error. */ // [NOCPP[ switch (doctypeExpectation) { case AUTO: err("Start tag seen without seeing a doctype first. Expected e.g. \u201C<!DOCTYPE html>\u201D."); break; case HTML: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE html>\u201D."); break; case HTML401_STRICT: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\u201D."); break; case HTML401_TRANSITIONAL: err("Start tag seen without seeing a doctype first. Expected \u201C<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\u201D."); break; case NO_DOCTYPE_ERRORS: } // ]NOCPP] /* * * Set the document to quirks mode. */ documentModeInternal(DocumentMode.QUIRKS_MODE, null, null, false); /* * Then, switch to the root element mode of the tree * construction stage */ mode = BEFORE_HTML; /* * and reprocess the current token. */ continue; case BEFORE_HTML: switch (group) { case HTML: // optimize error check and streaming SAX by // hoisting // "html" handling here. if (attributes == HtmlAttributes.EMPTY_ATTRIBUTES) { // This has the right magic side effect // that // it // makes attributes in SAX Tree mutable. appendHtmlElementToDocumentAndPush(); } else { appendHtmlElementToDocumentAndPush(attributes); } // XXX application cache should fire here mode = BEFORE_HEAD; attributes = null; // CPP break starttagloop; default: /* * Create an HTMLElement node with the tag name * html, in the HTML namespace. Append it to the * Document object. */ appendHtmlElementToDocumentAndPush(); /* Switch to the main mode */ mode = BEFORE_HEAD; /* * reprocess the current token. */ continue; } case BEFORE_HEAD: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case HEAD: /* * A start tag whose tag name is "head" * * Create an element for the token. * * Set the head element pointer to this new element * node. * * Append the new element to the current node and * push it onto the stack of open elements. */ appendToCurrentNodeAndPushHeadElement(attributes); /* * Change the insertion mode to "in head". */ mode = IN_HEAD; attributes = null; // CPP break starttagloop; default: /* * Any other start tag token * * Act as if a start tag token with the tag name * "head" and no attributes had been seen, */ appendToCurrentNodeAndPushHeadElement(HtmlAttributes.EMPTY_ATTRIBUTES); mode = IN_HEAD; /* * then reprocess the current token. * * This will result in an empty head element being * generated, with the current token being * reprocessed in the "after head" insertion mode. */ continue; } case AFTER_HEAD: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case BODY: if (attributes.getLength() == 0) { // This has the right magic side effect // that // it // makes attributes in SAX Tree mutable. appendToCurrentNodeAndPushBodyElement(); } else { appendToCurrentNodeAndPushBodyElement(attributes); } framesetOk = false; mode = IN_BODY; attributes = null; // CPP break starttagloop; case FRAMESET: appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); mode = IN_FRAMESET; attributes = null; // CPP break starttagloop; case BASE: err("\u201Cbase\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case LINK_OR_BASEFONT_OR_BGSOUND: err("\u201Clink\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case META: err("\u201Cmeta\u201D element outside \u201Chead\u201D."); checkMetaCharset(attributes); pushHeadPointerOntoStack(); appendVoidElementToCurrentMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); selfClosing = false; pop(); // head attributes = null; // CPP break starttagloop; case SCRIPT: err("\u201Cscript\u201D element between \u201Chead\u201D and \u201Cbody\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; case STYLE: case NOFRAMES: err("\u201C" + name + "\u201D element between \u201Chead\u201D and \u201Cbody\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RAWTEXT, elementName); attributes = null; // CPP break starttagloop; case TITLE: err("\u201Ctitle\u201D element outside \u201Chead\u201D."); pushHeadPointerOntoStack(); appendToCurrentNodeAndPushElement( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.RCDATA, elementName); attributes = null; // CPP break starttagloop; case HEAD: err("Stray start tag \u201Chead\u201D."); break starttagloop; default: appendToCurrentNodeAndPushBodyElement(); mode = FRAMESET_OK; continue; } case AFTER_AFTER_BODY: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); fatal(); mode = framesetOk ? FRAMESET_OK : IN_BODY; continue; } case AFTER_AFTER_FRAMESET: switch (group) { case HTML: err("Stray \u201Chtml\u201D start tag."); if (!fragment) { addAttributesToHtml(attributes); attributes = null; // CPP } break starttagloop; case NOFRAMES: appendToCurrentNodeAndPushElementMayFoster( "http://www.w3.org/1999/xhtml", elementName, attributes); originalMode = mode; mode = TEXT; tokenizer.setStateAndEndTagExpectation( Tokenizer.SCRIPT_DATA, elementName); attributes = null; // CPP break starttagloop; default: err("Stray \u201C" + name + "\u201D start tag."); break starttagloop; } case TEXT: assert false; break starttagloop; // Avoid infinite loop if the assertion // fails } } if (needsPostProcessing && inForeign && !hasForeignInScope()) { /* * If, after doing so, the insertion mode is still "in foreign * content", but there is no element in scope that has a namespace * other than the HTML namespace, switch the insertion mode to the * secondary insertion mode. */ inForeign = false; } if (errorHandler != null && selfClosing) { errNoCheck("Self-closing syntax (\u201C/>\u201D) used on a non-void HTML element. Ignoring the slash and treating as a start tag."); } if (attributes != HtmlAttributes.EMPTY_ATTRIBUTES) { Portability.delete(attributes); } }
diff --git a/src/main/battlecode/world/InternalRobot.java b/src/main/battlecode/world/InternalRobot.java index 480f6c9f..ab895931 100644 --- a/src/main/battlecode/world/InternalRobot.java +++ b/src/main/battlecode/world/InternalRobot.java @@ -1,359 +1,360 @@ package battlecode.world; import static battlecode.common.GameConstants.*; import java.util.ArrayList; import java.util.Collection; import java.util.EnumMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.google.common.base.Predicate; import com.google.common.collect.ForwardingMultimap; import com.google.common.collect.HashMultimap; import com.google.common.collect.Iterables; import com.google.common.collect.Multimap; import battlecode.common.Chassis; import battlecode.common.ComponentClass; import battlecode.common.ComponentType; import battlecode.common.Direction; import battlecode.common.GameActionException; import battlecode.common.GameActionExceptionType; import battlecode.common.RobotLevel; import battlecode.common.MapLocation; import battlecode.common.Message; import battlecode.common.Robot; import battlecode.common.Team; import battlecode.engine.ErrorReporter; import battlecode.engine.GenericRobot; import battlecode.engine.signal.Signal; import battlecode.server.Config; import battlecode.world.signal.BroadcastSignal; import battlecode.world.signal.DeathSignal; public class InternalRobot extends InternalObject implements Robot, GenericRobot { private volatile double myEnergonLevel; protected volatile Direction myDirection; private volatile boolean energonChanged = true; protected volatile double myMaxEnergon; protected volatile long controlBits; // is this used ever? protected volatile boolean hasBeenAttacked = false; private static boolean upkeepEnabled = Config.getGlobalConfig().getBoolean("bc.engine.upkeep-enabled"); /** first index is robot type, second is direction, third is x or y */ private static final Map<ComponentType,int[][][]> offsets = GameMap.computeVisibleOffsets(); /** number of bytecodes used in the most recent round */ private volatile int bytecodesUsed = 0; private List<Message> incomingMessageQueue; protected GameMap.MapMemory mapMemory; private InternalRobotBuffs buffs = new InternalRobotBuffs(this); public final Chassis chassis; /** all actions that have been performed in the current round */ private List<Signal> actions; private volatile boolean on; private volatile boolean hasBeenOff; public static class ComponentSet extends ForwardingMultimap<ComponentClass,BaseComponent> { Multimap<ComponentClass,BaseComponent> backingMap = HashMultimap.create(); protected Multimap<ComponentClass,BaseComponent> delegate() { return backingMap; } public boolean add(BaseComponent c) { return put(c.componentClass(),c); } public boolean remove(BaseComponent c) { return remove(c.componentClass(),c); } public boolean contains(BaseComponent c) { return containsEntry(c.componentClass(),c); } } public final ComponentSet components; public InternalRobotBuffs getBuffs() { return buffs; } @SuppressWarnings("unchecked") public InternalRobot(GameWorld gw, Chassis chassis, MapLocation loc, Team t, boolean spawnedRobot) { super(gw, loc, chassis.level, t); myDirection = Direction.values()[gw.getRandGen().nextInt(8)]; this.chassis = chassis; myMaxEnergon = chassis.maxHp; myEnergonLevel = myMaxEnergon; incomingMessageQueue = new LinkedList<Message>(); mapMemory = new GameMap.MapMemory(gw.getGameMap()); saveMapMemory(null, loc, false); controlBits = 0; components = new ComponentSet(); if(chassis.motor!=null) equip(new InternalComponent(myGameWorld,myLocation,chassis.motor)); actions = new LinkedList<Signal>(); on = true; } public boolean isOn() { return on; } public void setPower(boolean b) { on = b; if(!b) hasBeenOff=true; } public boolean queryHasBeenOff() { boolean tmp = hasBeenOff; hasBeenOff = false; return tmp; } public void equip(InternalComponent c) { BaseComponent controller; switch(c.type().componentClass) { case MOTOR: controller = new Motor(c,this); // remove this once all components are written default: controller = null; } c.setController(controller); components.add(controller); } public void unequip(BaseComponent c) { c.getComponent().setController(null); components.remove(c); } public void addAction(Signal s) { actions.add(s); } public Chassis getChassis() { return chassis; } public InternalComponent [] getComponents() { return Iterables.toArray(Iterables.transform(components.values(),Util.controllerToComponent),InternalComponent.class); } public BaseComponent [] getComponentControllers() { return components.values().toArray(new BaseComponent [0]); } public BaseComponent [] getComponentControllers(ComponentClass cl) { return components.get(cl).toArray(new BaseComponent [0]); } public BaseComponent [] getComponentControllers(final ComponentType t) { Predicate<BaseComponent> p = new Predicate<BaseComponent>() { public boolean apply(BaseComponent c) { return c.type()==t; } }; Iterable<BaseComponent> filtered = Iterables.filter(components.get(t.componentClass),p); return Iterables.toArray(filtered,BaseComponent.class); } @Override public void processBeginningOfRound() { super.processBeginningOfRound(); buffs.processBeginningOfRound(); for(BaseComponent c : components.values()) { c.component.processBeginningOfRound(); } } public void processBeginningOfTurn() { } @Override public void processEndOfTurn() { super.processEndOfTurn(); for(BaseComponent c : components.values()) { c.getComponent().processEndOfTurn(); } for(Signal s : actions) { myGameWorld.visitSignal(s); } actions.clear(); } @Override public void processEndOfRound() { super.processEndOfRound(); if (upkeepEnabled) { // TODO: upkeep } // TODO: regeneration buffs.processEndOfRound(); if (myEnergonLevel <= 0) { suicide(); } } public double getEnergonLevel() { return myEnergonLevel; } public Direction getDirection() { return myDirection; } public void takeDamage(double baseAmount) { // TODO: iron (use buffs) + if(baseAmount<0) changeEnergonLevel(-baseAmount); boolean haveHardened = false; double minDamage = Math.min(SHIELD_MIN_DAMAGE, baseAmount); for(BaseComponent c : components.get(ComponentClass.ARMOR)) { switch(c.type()) { case SHIELD: baseAmount-=SHIELD_DAMAGE_REDUCTION; break; case HARDENED: haveHardened=true; break; case PLASMA: if(!c.getComponent().isActive()) { c.getComponent().activate(); return; } break; } } if(haveHardened&&baseAmount>HARDENED_MAX_DAMAGE) - changeEnergonLevelFromAttack(HARDENED_MAX_DAMAGE); + changeEnergonLevelFromAttack(-HARDENED_MAX_DAMAGE); else - changeEnergonLevelFromAttack(Math.max(minDamage,baseAmount)); + changeEnergonLevelFromAttack(-Math.max(minDamage,baseAmount)); } public void changeEnergonLevelFromAttack(double amount) { hasBeenAttacked = true; changeEnergonLevel(amount * (buffs.getDamageReceivedMultiplier() + 1)); } public void changeEnergonLevel(double amount) { myEnergonLevel += amount; if (myEnergonLevel > myMaxEnergon) { myEnergonLevel = myMaxEnergon; } energonChanged = true; } public boolean clearEnergonChanged() { if (energonChanged) { energonChanged = false; return true; } else { return false; } } public double getMaxEnergon() { return myMaxEnergon; } public void setDirection(Direction dir) { myDirection = dir; saveMapMemory(getLocation(), getLocation(), false); } public void suicide() { (new DeathSignal(this)).accept(myGameWorld); } public void enqueueIncomingMessage(Message msg) { incomingMessageQueue.add(msg); } public Message dequeueIncomingMessage() { if (incomingMessageQueue.size() > 0) { return incomingMessageQueue.remove(0); } else { return null; } // ~ return incomingMessageQueue.poll(); } public Message[] dequeueIncomingMessages() { Message[] result = incomingMessageQueue.toArray(new Message[incomingMessageQueue.size()]); incomingMessageQueue.clear(); return result; } public GameMap.MapMemory getMapMemory() { return mapMemory; } public void saveMapMemory(MapLocation oldLoc, MapLocation newLoc, boolean fringeOnly) { for(BaseComponent c : components.get(ComponentClass.SENSOR)) { int[][] myOffsets = offsets.get(c.type())[myDirection.ordinal()]; mapMemory.rememberLocations(newLoc, myOffsets[0], myOffsets[1]); } } @Override public void setLocation(MapLocation newLoc) { MapLocation oldLoc = getLocation(); super.setLocation(newLoc); saveMapMemory(oldLoc, newLoc, false); } public void setControlBits(long l) { controlBits = l; } public long getControlBits() { return controlBits; } public void setBytecodesUsed(int numBytecodes) { bytecodesUsed = numBytecodes; } public int getBytecodesUsed() { return bytecodesUsed; } public int getBytecodeLimit() { return BYTECODE_LIMIT_BASE; } public boolean hasBeenAttacked() { return hasBeenAttacked; } @Override public String toString() { return String.format("%s:%s#%d",getTeam(),chassis,getID()); } public void freeMemory() { incomingMessageQueue = null; mapMemory = null; buffs = null; } }
false
true
public void takeDamage(double baseAmount) { // TODO: iron (use buffs) boolean haveHardened = false; double minDamage = Math.min(SHIELD_MIN_DAMAGE, baseAmount); for(BaseComponent c : components.get(ComponentClass.ARMOR)) { switch(c.type()) { case SHIELD: baseAmount-=SHIELD_DAMAGE_REDUCTION; break; case HARDENED: haveHardened=true; break; case PLASMA: if(!c.getComponent().isActive()) { c.getComponent().activate(); return; } break; } } if(haveHardened&&baseAmount>HARDENED_MAX_DAMAGE) changeEnergonLevelFromAttack(HARDENED_MAX_DAMAGE); else changeEnergonLevelFromAttack(Math.max(minDamage,baseAmount)); }
public void takeDamage(double baseAmount) { // TODO: iron (use buffs) if(baseAmount<0) changeEnergonLevel(-baseAmount); boolean haveHardened = false; double minDamage = Math.min(SHIELD_MIN_DAMAGE, baseAmount); for(BaseComponent c : components.get(ComponentClass.ARMOR)) { switch(c.type()) { case SHIELD: baseAmount-=SHIELD_DAMAGE_REDUCTION; break; case HARDENED: haveHardened=true; break; case PLASMA: if(!c.getComponent().isActive()) { c.getComponent().activate(); return; } break; } } if(haveHardened&&baseAmount>HARDENED_MAX_DAMAGE) changeEnergonLevelFromAttack(-HARDENED_MAX_DAMAGE); else changeEnergonLevelFromAttack(-Math.max(minDamage,baseAmount)); }
diff --git a/java/modules/core/src/main/java/org/apache/synapse/config/xml/EntrySerializer.java b/java/modules/core/src/main/java/org/apache/synapse/config/xml/EntrySerializer.java index 012648309..f2194872c 100644 --- a/java/modules/core/src/main/java/org/apache/synapse/config/xml/EntrySerializer.java +++ b/java/modules/core/src/main/java/org/apache/synapse/config/xml/EntrySerializer.java @@ -1,84 +1,84 @@ /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.synapse.config.xml; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMElement; import org.apache.synapse.config.Entry; import org.apache.synapse.SynapseException; import org.apache.axiom.om.impl.llom.OMTextImpl; import javax.xml.stream.XMLStreamConstants; public class EntrySerializer { private static Log log = LogFactory.getLog(EntrySerializer.class); protected static final OMFactory fac = OMAbstractFactory.getOMFactory(); protected static final OMNamespace synNS = fac.createOMNamespace( Constants.SYNAPSE_NAMESPACE, "syn"); protected static final OMNamespace nullNS = fac.createOMNamespace(Constants.NULL_NAMESPACE, ""); /** * Serialize the Entry object to an OMElement representing the entry * @param entry * @param parent * @return OMElement representing the entry */ public static OMElement serializeEntry(Entry entry, OMElement parent) { - OMElement propertyElement = fac.createOMElement("set-entry", synNS); + OMElement propertyElement = fac.createOMElement("localEntry", synNS); propertyElement.addAttribute(fac.createOMAttribute( "key", nullNS, entry.getKey())); // propertyElement.addAttribute(fac.createOMAttribute( // "type", nullNS, "" + entry.getType())); if (entry.getType() == Entry.REMOTE_ENTRY) { propertyElement.addAttribute(fac.createOMAttribute( "key", nullNS, entry.getKey())); } else if (entry.getType() == Entry.URL_SRC) { propertyElement.addAttribute(fac.createOMAttribute( "src", nullNS, entry.getSrc().toString())); // } else if (entry.getType() == Entry.VALUE_TYPE) { // propertyElement.addAttribute(fac.createOMAttribute( // "value", nullNS, (String) entry.getValue())); } else if (entry.getType() == Entry.INLINE_XML) { propertyElement.addChild((OMElement) entry.getValue()); } else if (entry.getType() == Entry.INLINE_TEXT) { OMTextImpl textData = (OMTextImpl) fac.createOMText((String) entry.getValue()); textData.setType(XMLStreamConstants.CDATA); propertyElement.addChild(textData); } else { handleException("Entry type undefined"); } if(parent != null) { parent.addChild(propertyElement); } return propertyElement; } private static void handleException(String msg) { log.error(msg); throw new SynapseException(msg); } }
true
true
public static OMElement serializeEntry(Entry entry, OMElement parent) { OMElement propertyElement = fac.createOMElement("set-entry", synNS); propertyElement.addAttribute(fac.createOMAttribute( "key", nullNS, entry.getKey())); // propertyElement.addAttribute(fac.createOMAttribute( // "type", nullNS, "" + entry.getType())); if (entry.getType() == Entry.REMOTE_ENTRY) { propertyElement.addAttribute(fac.createOMAttribute( "key", nullNS, entry.getKey())); } else if (entry.getType() == Entry.URL_SRC) { propertyElement.addAttribute(fac.createOMAttribute( "src", nullNS, entry.getSrc().toString())); // } else if (entry.getType() == Entry.VALUE_TYPE) { // propertyElement.addAttribute(fac.createOMAttribute( // "value", nullNS, (String) entry.getValue())); } else if (entry.getType() == Entry.INLINE_XML) { propertyElement.addChild((OMElement) entry.getValue()); } else if (entry.getType() == Entry.INLINE_TEXT) { OMTextImpl textData = (OMTextImpl) fac.createOMText((String) entry.getValue()); textData.setType(XMLStreamConstants.CDATA); propertyElement.addChild(textData); } else { handleException("Entry type undefined"); } if(parent != null) { parent.addChild(propertyElement); } return propertyElement; }
public static OMElement serializeEntry(Entry entry, OMElement parent) { OMElement propertyElement = fac.createOMElement("localEntry", synNS); propertyElement.addAttribute(fac.createOMAttribute( "key", nullNS, entry.getKey())); // propertyElement.addAttribute(fac.createOMAttribute( // "type", nullNS, "" + entry.getType())); if (entry.getType() == Entry.REMOTE_ENTRY) { propertyElement.addAttribute(fac.createOMAttribute( "key", nullNS, entry.getKey())); } else if (entry.getType() == Entry.URL_SRC) { propertyElement.addAttribute(fac.createOMAttribute( "src", nullNS, entry.getSrc().toString())); // } else if (entry.getType() == Entry.VALUE_TYPE) { // propertyElement.addAttribute(fac.createOMAttribute( // "value", nullNS, (String) entry.getValue())); } else if (entry.getType() == Entry.INLINE_XML) { propertyElement.addChild((OMElement) entry.getValue()); } else if (entry.getType() == Entry.INLINE_TEXT) { OMTextImpl textData = (OMTextImpl) fac.createOMText((String) entry.getValue()); textData.setType(XMLStreamConstants.CDATA); propertyElement.addChild(textData); } else { handleException("Entry type undefined"); } if(parent != null) { parent.addChild(propertyElement); } return propertyElement; }
diff --git a/src/com/thevoxelbox/vPainting.java b/src/com/thevoxelbox/vPainting.java index 9a97b52..5a11d5e 100755 --- a/src/com/thevoxelbox/vPainting.java +++ b/src/com/thevoxelbox/vPainting.java @@ -1,81 +1,81 @@ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.thevoxelbox; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import net.minecraft.server.AxisAlignedBB; import net.minecraft.server.EntityPainting; import net.minecraft.server.EnumArt; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.craftbukkit.CraftWorld; import org.bukkit.craftbukkit.entity.CraftPlayer; import org.bukkit.entity.Player; /** * Painting state change handler * * @author Piotr */ public class vPainting { /** * ArrayList of Notch's paintings from the EnumArt enum * Stored here for easy access, also EnumArt doesn't have a .get */ public static final ArrayList<EnumArt> paintings = new ArrayList<EnumArt>(Arrays.asList(EnumArt.values())); /** * The paint method used to scroll or set a painting to a specific type * * @param p The player executing the method * @param _auto Scroll automatically? If false will use 'choice' to try and set the painting * @param back Scroll in reverse? * @param choice Chosen index to set the painting to */ public static void paint(Player p, boolean _auto, boolean back, int choice) { boolean auto = _auto; Location loc = p.getTargetBlock(null, 4).getLocation(); Location loc2 = p.getLocation(); CraftWorld craftWorld = (CraftWorld) p.getWorld(); double x1 = loc.getX() + 0.4D; double y1 = loc.getY() + 0.4D; double z1 = loc.getZ() + 0.4D; double x2 = loc2.getX(); double y2 = loc.getY() + 0.6D; double z2 = loc2.getZ(); AxisAlignedBB bb = AxisAlignedBB.a(Math.min(x1, x2), y1, Math.min(z1, z2), Math.max(x1, x2), y2, Math.max(z1, z2)); - List entities = craftWorld.getHandle().b(((CraftPlayer) p).getHandle(), bb); + List entities = craftWorld.getHandle().getEntities(((CraftPlayer) p).getHandle(), bb); if ((entities.size() == 1) && ((entities.get(0) instanceof EntityPainting))) { EntityPainting oldPainting = (EntityPainting) entities.get(0); - EntityPainting newPainting = new EntityPainting(craftWorld.getHandle(), oldPainting.b, oldPainting.c, oldPainting.d, oldPainting.a % 4); + EntityPainting newPainting = new EntityPainting(craftWorld.getHandle(), oldPainting.x, oldPainting.y, oldPainting.z, oldPainting.direction % 4); - newPainting.e = oldPainting.e; + newPainting.art = oldPainting.art; oldPainting.dead = true; if (auto) { - int i = (paintings.indexOf(newPainting.e) + (back ? -1 : 1) + paintings.size()) % paintings.size(); - newPainting.e = (paintings.get(i)); - newPainting.b(newPainting.a); + int i = (paintings.indexOf(newPainting.art) + (back ? -1 : 1) + paintings.size()) % paintings.size(); + newPainting.art = (paintings.get(i)); + newPainting.setDirection(newPainting.direction); newPainting.world.addEntity(newPainting); p.sendMessage(ChatColor.GREEN + "Painting set to ID: " + (i)); } else { try { - newPainting.e = (paintings.get(choice)); - newPainting.b(newPainting.a); + newPainting.art = (paintings.get(choice)); + newPainting.setDirection(newPainting.direction); newPainting.world.addEntity(newPainting); p.sendMessage(ChatColor.GREEN + "Painting set to ID: " + choice); } catch (Exception e) { p.sendMessage(ChatColor.RED + "Your input was invalid somewhere."); } } } } }
false
true
public static void paint(Player p, boolean _auto, boolean back, int choice) { boolean auto = _auto; Location loc = p.getTargetBlock(null, 4).getLocation(); Location loc2 = p.getLocation(); CraftWorld craftWorld = (CraftWorld) p.getWorld(); double x1 = loc.getX() + 0.4D; double y1 = loc.getY() + 0.4D; double z1 = loc.getZ() + 0.4D; double x2 = loc2.getX(); double y2 = loc.getY() + 0.6D; double z2 = loc2.getZ(); AxisAlignedBB bb = AxisAlignedBB.a(Math.min(x1, x2), y1, Math.min(z1, z2), Math.max(x1, x2), y2, Math.max(z1, z2)); List entities = craftWorld.getHandle().b(((CraftPlayer) p).getHandle(), bb); if ((entities.size() == 1) && ((entities.get(0) instanceof EntityPainting))) { EntityPainting oldPainting = (EntityPainting) entities.get(0); EntityPainting newPainting = new EntityPainting(craftWorld.getHandle(), oldPainting.b, oldPainting.c, oldPainting.d, oldPainting.a % 4); newPainting.e = oldPainting.e; oldPainting.dead = true; if (auto) { int i = (paintings.indexOf(newPainting.e) + (back ? -1 : 1) + paintings.size()) % paintings.size(); newPainting.e = (paintings.get(i)); newPainting.b(newPainting.a); newPainting.world.addEntity(newPainting); p.sendMessage(ChatColor.GREEN + "Painting set to ID: " + (i)); } else { try { newPainting.e = (paintings.get(choice)); newPainting.b(newPainting.a); newPainting.world.addEntity(newPainting); p.sendMessage(ChatColor.GREEN + "Painting set to ID: " + choice); } catch (Exception e) { p.sendMessage(ChatColor.RED + "Your input was invalid somewhere."); } } } }
public static void paint(Player p, boolean _auto, boolean back, int choice) { boolean auto = _auto; Location loc = p.getTargetBlock(null, 4).getLocation(); Location loc2 = p.getLocation(); CraftWorld craftWorld = (CraftWorld) p.getWorld(); double x1 = loc.getX() + 0.4D; double y1 = loc.getY() + 0.4D; double z1 = loc.getZ() + 0.4D; double x2 = loc2.getX(); double y2 = loc.getY() + 0.6D; double z2 = loc2.getZ(); AxisAlignedBB bb = AxisAlignedBB.a(Math.min(x1, x2), y1, Math.min(z1, z2), Math.max(x1, x2), y2, Math.max(z1, z2)); List entities = craftWorld.getHandle().getEntities(((CraftPlayer) p).getHandle(), bb); if ((entities.size() == 1) && ((entities.get(0) instanceof EntityPainting))) { EntityPainting oldPainting = (EntityPainting) entities.get(0); EntityPainting newPainting = new EntityPainting(craftWorld.getHandle(), oldPainting.x, oldPainting.y, oldPainting.z, oldPainting.direction % 4); newPainting.art = oldPainting.art; oldPainting.dead = true; if (auto) { int i = (paintings.indexOf(newPainting.art) + (back ? -1 : 1) + paintings.size()) % paintings.size(); newPainting.art = (paintings.get(i)); newPainting.setDirection(newPainting.direction); newPainting.world.addEntity(newPainting); p.sendMessage(ChatColor.GREEN + "Painting set to ID: " + (i)); } else { try { newPainting.art = (paintings.get(choice)); newPainting.setDirection(newPainting.direction); newPainting.world.addEntity(newPainting); p.sendMessage(ChatColor.GREEN + "Painting set to ID: " + choice); } catch (Exception e) { p.sendMessage(ChatColor.RED + "Your input was invalid somewhere."); } } } }
diff --git a/src/main/java/net/oneandone/sushi/launcher/Launcher.java b/src/main/java/net/oneandone/sushi/launcher/Launcher.java index 12738996..fa6e2c88 100644 --- a/src/main/java/net/oneandone/sushi/launcher/Launcher.java +++ b/src/main/java/net/oneandone/sushi/launcher/Launcher.java @@ -1,200 +1,198 @@ /** * Copyright 1&1 Internet AG, https://github.com/1and1/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.oneandone.sushi.launcher; import net.oneandone.sushi.fs.file.FileNode; import net.oneandone.sushi.util.Separator; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.List; /** * Configures and executes an operating system process. This class wraps a ProcessBuilder to simplify usage. * In particular, most methods return this so you can configure and execute a program in a single expression * (short methods names further simplify this). In addition, you can easily get process output as a string. * * None-zero exit codes of a process are reported as ExitCode exceptions. This helps to improve reliability * because it's harder to ignore exceptions than to ignore return codes. * * Note that the first "arg" passed to an instance of this class is actually not an argument, but * the name of the program or script to be executed. I accept this inconsistency because it simplifies * the api and allows for shorter method names. */ public class Launcher { private final ProcessBuilder builder; private String encoding; public Launcher(String... args) { this.builder = new ProcessBuilder(); arg(args); } public Launcher(FileNode dir, String... args) { this(args); dir(dir); } //-- configuration public Launcher env(String key, String value) { builder.environment().put(key, value); return this; } public Launcher arg(String... args) { for (String a : args) { builder.command().add(a); } return this; } public Launcher args(List<String> args) { builder.command().addAll(args); return this; } /** initializes the directory to execute the command in */ public Launcher dir(FileNode dir) { return dir(dir.toPath().toFile(), dir.getWorld().getSettings().encoding); } /** You'll normally use the dir(FileNode) method instead. */ public Launcher dir(File dir, String encoding) { this.builder.directory(dir); this.encoding = encoding; return this; } //-- execution public void execNoOutput() throws Failure { String result; result = exec(); if (result.trim().length() > 0) { throw new Failure(this, builder.command().get(0) + ": unexpected output " + result); } } public String exec() throws Failure { ByteArrayOutputStream result; result = new ByteArrayOutputStream(); exec(result); return string(result.toByteArray()); } public void exec(OutputStream all) throws Failure { exec(all, null); } public void exec(OutputStream stdout, OutputStream stderr) throws Failure { exec(stdout, stderr, System.in, true); } /** * Executes a command in this directory, wired with the specified streams. None of the argument stream is closed. * * @param stderr may be null (which will redirect the error stream to stdout. * @param stdin may be null */ public void exec(OutputStream stdout, OutputStream stderr, InputStream stdin, boolean stdinInherit) throws Failure { Process process; int exit; String output; PumpStream psout; PumpStream pserr; PumpStream psin; if (builder.directory() == null) { // builder.start() does not check, I would not detect the problem until process.waitFor is called // - that's to late because buffer would also be null throw new IllegalStateException("Missing directory. Call dir() before invoking this method"); } builder.redirectErrorStream(stderr == null); + if (stdinInherit) { + builder.redirectInput(ProcessBuilder.Redirect.INHERIT); + } try { process = builder.start(); } catch (IOException e) { throw new Failure(this, e); } psout = new PumpStream(process.getInputStream(), stdout, false); psout.start(); if (stderr != null) { pserr = new PumpStream(process.getErrorStream(), stderr, false); pserr.start(); } else { pserr = null; } - if (stdin != null) { - if (stdinInherit) { - builder.redirectInput(ProcessBuilder.Redirect.INHERIT); - psin = null; - } else { - psin = new PumpStream(stdin, process.getOutputStream(), true); - psin.start(); - } + if (stdin != null && !stdinInherit) { + psin = new PumpStream(stdin, process.getOutputStream(), true); + psin.start(); } else { psin = null; } psout.finish(this); if (pserr != null) { pserr.finish(this); } try { exit = process.waitFor(); } catch (InterruptedException e) { throw new Interrupted(e); } if (psin != null) { psin.finish(this); } if (exit != 0) { if (stderr == null && stdout instanceof ByteArrayOutputStream) { output = string(((ByteArrayOutputStream) stdout).toByteArray()); } else { output = ""; } throw new ExitCode(this, exit, output); } } //-- /** If you need access to the internals. Most applications won't need this method. */ public ProcessBuilder getBuilder() { return builder; } @Override public String toString() { return "[" + builder.directory() + "] " + Separator.SPACE.join(builder.command()); } //-- private String string(byte[] bytes) { try { return new String(bytes, encoding); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } }
false
true
public void exec(OutputStream stdout, OutputStream stderr, InputStream stdin, boolean stdinInherit) throws Failure { Process process; int exit; String output; PumpStream psout; PumpStream pserr; PumpStream psin; if (builder.directory() == null) { // builder.start() does not check, I would not detect the problem until process.waitFor is called // - that's to late because buffer would also be null throw new IllegalStateException("Missing directory. Call dir() before invoking this method"); } builder.redirectErrorStream(stderr == null); try { process = builder.start(); } catch (IOException e) { throw new Failure(this, e); } psout = new PumpStream(process.getInputStream(), stdout, false); psout.start(); if (stderr != null) { pserr = new PumpStream(process.getErrorStream(), stderr, false); pserr.start(); } else { pserr = null; } if (stdin != null) { if (stdinInherit) { builder.redirectInput(ProcessBuilder.Redirect.INHERIT); psin = null; } else { psin = new PumpStream(stdin, process.getOutputStream(), true); psin.start(); } } else { psin = null; } psout.finish(this); if (pserr != null) { pserr.finish(this); } try { exit = process.waitFor(); } catch (InterruptedException e) { throw new Interrupted(e); } if (psin != null) { psin.finish(this); } if (exit != 0) { if (stderr == null && stdout instanceof ByteArrayOutputStream) { output = string(((ByteArrayOutputStream) stdout).toByteArray()); } else { output = ""; } throw new ExitCode(this, exit, output); } }
public void exec(OutputStream stdout, OutputStream stderr, InputStream stdin, boolean stdinInherit) throws Failure { Process process; int exit; String output; PumpStream psout; PumpStream pserr; PumpStream psin; if (builder.directory() == null) { // builder.start() does not check, I would not detect the problem until process.waitFor is called // - that's to late because buffer would also be null throw new IllegalStateException("Missing directory. Call dir() before invoking this method"); } builder.redirectErrorStream(stderr == null); if (stdinInherit) { builder.redirectInput(ProcessBuilder.Redirect.INHERIT); } try { process = builder.start(); } catch (IOException e) { throw new Failure(this, e); } psout = new PumpStream(process.getInputStream(), stdout, false); psout.start(); if (stderr != null) { pserr = new PumpStream(process.getErrorStream(), stderr, false); pserr.start(); } else { pserr = null; } if (stdin != null && !stdinInherit) { psin = new PumpStream(stdin, process.getOutputStream(), true); psin.start(); } else { psin = null; } psout.finish(this); if (pserr != null) { pserr.finish(this); } try { exit = process.waitFor(); } catch (InterruptedException e) { throw new Interrupted(e); } if (psin != null) { psin.finish(this); } if (exit != 0) { if (stderr == null && stdout instanceof ByteArrayOutputStream) { output = string(((ByteArrayOutputStream) stdout).toByteArray()); } else { output = ""; } throw new ExitCode(this, exit, output); } }
diff --git a/src/org/morsi/android/nethack/redux/EncyclopediaActivity.java b/src/org/morsi/android/nethack/redux/EncyclopediaActivity.java index ad67ef3..ac7ec38 100644 --- a/src/org/morsi/android/nethack/redux/EncyclopediaActivity.java +++ b/src/org/morsi/android/nethack/redux/EncyclopediaActivity.java @@ -1,125 +1,129 @@ /********************************** * Nethack Encyclopedia - Encyclopedia Activity * * Copyright (C) 2011: Mo Morsi <[email protected]> * Distributed under the MIT License **********************************/ package org.morsi.android.nethack.redux; import java.util.Arrays; import java.util.List; import android.app.Dialog; import android.app.ListActivity; import android.content.Context; import android.os.AsyncTask; import android.os.Bundle; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.AdapterView.OnItemClickListener; import org.morsi.android.nethack.redux.R; import org.morsi.android.nethack.redux.util.Android; import org.morsi.android.nethack.redux.util.AndroidMenu; import org.morsi.android.nethack.redux.util.Encyclopedia; import org.morsi.android.nethack.redux.util.NString; // Provides access to view html based Nethack Encyclopedia articles public class EncyclopediaActivity extends ListActivity { // Override menu / about dialog handlers @Override public boolean onSearchRequested() {return AndroidMenu.onEncyclopediaSearchRequested(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { return AndroidMenu.onCreateOptionsMenu(this, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { return AndroidMenu.onOptionsItemSelected(this, item); } @Override protected Dialog onCreateDialog(int id) { return AndroidMenu.onCreateDialog(this, id); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && !EncyclopediaActivity.in_alphabetical_mode) { setListAdapter(alphabet_adapter); EncyclopediaActivity.in_alphabetical_mode = true; return true; } return super.onKeyDown(keyCode, event); } // divide encyclopedia into alphabetical sections public static boolean in_alphabetical_mode = true; public static String current_section; // alphabet sections public static final List<String> alphabet_sections = Arrays.asList(Encyclopedia.symbol_string, Encyclopedia.number_string, "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"); // Store a mapping of topic names to EncylopediaEntry objects public static Encyclopedia encyclopedia; // store adapters used to bind data to list // FIXME these adapters are not thread safe and may cause intermitent errors as // section_adapter is updated in asynctask, see this for more info: // http://stackoverflow.com/questions/6244330/is-arrayadapter-thread-safe-in-android-if-not-what-can-i-do-to-make-it-thread private static ArrayAdapter<String> alphabet_adapter; private static ArrayAdapter<String> section_adapter = null; // helper to load the encyclopedia in the background public static void load_encyclopedia(Context c){ encyclopedia = new Encyclopedia(); new LoadEncyclopediaTask().execute(c); } // Asynchronous task to load encyclopedia in the background // need to pass in a context so as to retrieve encyclopedia from application's assets private static class LoadEncyclopediaTask extends AsyncTask<Context, Void, Void> { protected Void doInBackground(Context... c) { // parse the list of topics and redirects from a registry file NString registry = Android.assetToNString(c[0].getAssets(), "encyclopedia/registry"); NString redirects = Android.assetToNString(c[0].getAssets(), "encyclopedia/redirects"); encyclopedia.retrieveTopics(registry, redirects); return null; } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - alphabet_adapter = new ArrayAdapter<String>(this, R.layout.encyclopedia, alphabet_sections); - setListAdapter(alphabet_adapter); + if(EncyclopediaActivity.in_alphabetical_mode){ + alphabet_adapter = new ArrayAdapter<String>(this, R.layout.encyclopedia, alphabet_sections); + setListAdapter(alphabet_adapter); + }else{ + setListAdapter(section_adapter); + } // display the list, enable filtering when the user types // characters and wire up item click listener ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new EncyclopediaItemClickedListener()); }; // Handles encyclopedia article clicks private class EncyclopediaItemClickedListener implements OnItemClickListener { public EncyclopediaItemClickedListener(){ super(); } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(EncyclopediaActivity.in_alphabetical_mode){ EncyclopediaActivity.current_section = ((TextView) view).getText().toString(); EncyclopediaActivity.in_alphabetical_mode = false; section_adapter = new ArrayAdapter<String>(view.getContext(), R.layout.encyclopedia, encyclopedia.topicNames(EncyclopediaActivity.current_section)); setListAdapter(section_adapter); }else{ //create encyclopedia page activity when topic is picked String popup_topic = ((TextView) view).getText().toString(); EncyclopediaPage.showPage(EncyclopediaActivity.this, popup_topic); } } } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); alphabet_adapter = new ArrayAdapter<String>(this, R.layout.encyclopedia, alphabet_sections); setListAdapter(alphabet_adapter); // display the list, enable filtering when the user types // characters and wire up item click listener ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new EncyclopediaItemClickedListener()); };
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if(EncyclopediaActivity.in_alphabetical_mode){ alphabet_adapter = new ArrayAdapter<String>(this, R.layout.encyclopedia, alphabet_sections); setListAdapter(alphabet_adapter); }else{ setListAdapter(section_adapter); } // display the list, enable filtering when the user types // characters and wire up item click listener ListView lv = getListView(); lv.setTextFilterEnabled(true); lv.setOnItemClickListener(new EncyclopediaItemClickedListener()); };
diff --git a/src/net/sf/freecol/common/model/Game.java b/src/net/sf/freecol/common/model/Game.java index 83476849b..45f01a398 100644 --- a/src/net/sf/freecol/common/model/Game.java +++ b/src/net/sf/freecol/common/model/Game.java @@ -1,1059 +1,1063 @@ /** * Copyright (C) 2002-2007 The FreeCol Team * * This file is part of FreeCol. * * FreeCol is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * FreeCol is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with FreeCol. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.freecol.common.model; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.logging.Logger; import javax.xml.stream.XMLStreamConstants; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import net.sf.freecol.FreeCol; /** * The main component of the game model. * * <br> * <br> * * If an object of this class returns a non-null result to {@link #getViewOwner}, * then this object just represents a view of the game from a single player's * perspective. In that case, some information might be missing from the model. */ public class Game extends FreeColGameObject { private static final Logger logger = Logger.getLogger(Game.class.getName()); protected int playerIndex = 0; /** * A virtual player to use with enemy privateers */ private Player unknownEnemy; /** Contains all the players in the game. */ private List<Player> players = new ArrayList<Player>(); private Map map; private GameOptions gameOptions; /** The name of the player whose turn it is. */ private Player currentPlayer = null; /** * The owner of this view of the game, or <code>null</code> if this game * has all the information. */ private Player viewOwner; /** The maximum number of (human) players allowed in this game. */ private int maxPlayers = 4; /** Contains references to all objects created in this game. */ private HashMap<String, FreeColGameObject> freeColGameObjects = new HashMap<String, FreeColGameObject>(10000); /** * The next available ID, that can be given to a new * <code>FreeColGameObject</code>. */ private int nextId = 1; /** Indicates whether or not this object may give IDs. */ private boolean canGiveID; private Turn turn = new Turn(1); private final ModelController modelController; private FreeColGameObjectListener freeColGameObjectListener; /** The lost city rumour class. */ private final static LostCityRumour lostCityRumour = new LostCityRumour(); /** * Describe combatModel here. */ private CombatModel combatModel; /** * The nations that can still be selected in this Game. */ private List<Nation> vacantNations = new ArrayList<Nation>(); /** * Creates a new game model. * * @param modelController A controller object the model can use to make * actions not allowed from the model (generate random numbers * etc). * @see net.sf.freecol.server.FreeColServer#FreeColServer(boolean, boolean, * int, String) */ public Game(ModelController modelController) { super(null); this.modelController = modelController; this.combatModel = new SimpleCombatModel(modelController.getPseudoRandom()); this.viewOwner = null; gameOptions = new GameOptions(); currentPlayer = null; canGiveID = true; //market = new Market(this); } /** * Initiate a new <code>Game</code> with information from a saved game. * * @param freeColGameObjectListener A listener that should be monitoring * this <code>Game</code>. * @param modelController A controller object the model can use to make * actions not allowed from the model (generate random numbers * etc). * @param in The input stream containing the XML. * @param fcgos A list of <code>FreeColGameObject</code>s to be added to * this <code>Game</code>. * @throws XMLStreamException if an error occurred during parsing. * @see net.sf.freecol.server.FreeColServer#loadGame(File) */ public Game(FreeColGameObjectListener freeColGameObjectListener, ModelController modelController, XMLStreamReader in, FreeColGameObject[] fcgos) throws XMLStreamException { super(null, in); setFreeColGameObjectListener(freeColGameObjectListener); this.modelController = modelController; if (modelController != null) { // no model controller when using the map editor this.combatModel = new SimpleCombatModel(modelController.getPseudoRandom()); } this.viewOwner = null; canGiveID = true; for (int i = 0; i < fcgos.length; i++) { fcgos[i].setGame(this); fcgos[i].updateID(); if (fcgos[i] instanceof Player) { players.add((Player) fcgos[i]); } } readFromXML(in); } /* * Initiate a new <code>Game</code> with information from a saved game. * * Currently not used, commented. * * @param freeColGameObjectListener A listener that should be monitoring * this <code>Game</code>. @param modelController A controller object the * model can use to make actions not allowed from the model (generate random * numbers etc). @param fcgos A list of <code>FreeColGameObject</code>s * to be added to this <code>Game</code>. @param e An XML-element that * will be used to initialize this object. * * public Game(FreeColGameObjectListener freeColGameObjectListener, * ModelController modelController, Element e, FreeColGameObject[] fcgos){ * super(null, e); * * setFreeColGameObjectListener(freeColGameObjectListener); * this.modelController = modelController; this.viewOwner = null; * * canGiveID = true; * * for (int i=0; i<fcgos.length; i++) { fcgos[i].setGame(this); * fcgos[i].updateID(); * * if (fcgos[i] instanceof Player) { players.add((Player) fcgos[i]); } } * * readFromXMLElement(e); } */ /* * Initiate a new <code>Game</code> object from a <code>Element</code> * in a DOM-parsed XML-tree. * * Currently not used, commented. * * @param modelController A controller object the model can use to make * actions not allowed from the model (generate random numbers etc). @param * viewOwnerUsername The username of the owner of this view of the game. * @param e An XML-element that will be used to initialize this object. * * public Game(ModelController modelController, Element e, String * viewOwnerUsername){ super(null, e); * * this.modelController = modelController; canGiveID = false; * readFromXMLElement(e); this.viewOwner = * getPlayerByName(viewOwnerUsername); } */ /** * Initiate a new <code>Game</code> object from an XML-representation. * <p> * Note that this is used on the client side; the game is really a partial * view of the server-side game. * * @param modelController A controller object the model can use to make * actions not allowed from the model (generate random numbers * etc). * @param in The XML stream to read the data from. * @param viewOwnerUsername The username of the owner of this view of the * game. * @throws XMLStreamException if an error occured during parsing. * @see net.sf.freecol.client.control.ConnectController#login(String, * String, int) */ public Game(ModelController modelController, XMLStreamReader in, String viewOwnerUsername) throws XMLStreamException { super(null, in); this.modelController = modelController; this.combatModel = new SimpleCombatModel(modelController.getPseudoRandom()); canGiveID = false; readFromXML(in); this.viewOwner = getPlayerByName(viewOwnerUsername); } public ModelController getModelController() { return modelController; } public Player getUnknownEnemy() { return unknownEnemy; } public void setUnknownEnemy(Player player) { this.unknownEnemy = player; } /** * Get the <code>VacantNations</code> value. * * @return a <code>List<Nation></code> value */ public final List<Nation> getVacantNations() { return vacantNations; } /** * Set the <code>VacantNations</code> value. * * @param newNations the new list of vacant nations */ public final void setVacantNations(final List<Nation> newNations) { this.vacantNations = newNations; } /** * Check if the clients are trusted or if the server should keep secrets in * order to prevent cheating. * * @return true if clients are to be trusted. */ public boolean isClientTrusted() { // Trust the clients in order to prevent certain bugs, fix this later return false; } /** * Returns the owner of this view of the game, or <code>null</code> if * this game has all the information. <br> * <br> * If this value is <code>null</code>, then it means that this * <code>Game</code> object has access to all information (ie is the * server model). * * @return The <code>Player</code> using this <code>Game</code>-object * as a view. */ public Player getViewOwner() { return viewOwner; } /** * Returns the first <code>Colony</code> with the given name. * * @param name The name of the <code>Colony</code>. * @return The <code>Colony</code> or <code>null</code> if there is no * known <code>Colony</code> with the specified name (the colony * might not be visible to a client). */ public Colony getColony(String name) { Iterator<Player> pit = getPlayerIterator(); while (pit.hasNext()) { Player p = pit.next(); if (p.isEuropean()) { Colony result = p.getColony(name); if (result != null) { return result; } } } return null; } public Turn getTurn() { return turn; } /** * Get the <code>CombatModel</code> value. * * @return a <code>CombatModel</code> value */ public final CombatModel getCombatModel() { return combatModel; } /** * Set the <code>CombatModel</code> value. * * @param newCombatModel The new CombatModel value. */ public final void setCombatModel(final CombatModel newCombatModel) { this.combatModel = newCombatModel; } /** * Returns this game's LostCityRumour. * * @return This game's LostCityRumour. */ public LostCityRumour getLostCityRumour() { return lostCityRumour; } /** * Get a unique ID to identify a <code>FreeColGameObject</code>. * * @return A unique ID. */ public String getNextID() { if (canGiveID) { String id = Integer.toString(nextId); nextId++; return id; } else { logger.warning("The client's \"Game\" was requested to give out an id."); throw new Error("The client's \"Game\" was requested to give out an id."); // return null; } } /** * Adds the specified player to the game. * * @param player The <code>Player</code> that shall be added to this * <code>Game</code>. */ public void addPlayer(Player player) { if (player.isAI() || canAddNewPlayer()) { players.add(player); vacantNations.remove(FreeCol.getSpecification().getNation(player.getNationID())); if (currentPlayer == null) { currentPlayer = player; } } else { logger.warning("Tried to add a new player, but the game was already full."); } } /** * Removes the specified player from the game. * * @param player The <code>Player</code> that shall be removed from this * <code>Game</code>. */ public void removePlayer(Player player) { boolean updateCurrentPlayer = (currentPlayer == player); players.remove(players.indexOf(player)); vacantNations.add(FreeCol.getSpecification().getNation(player.getNationID())); player.dispose(); if (updateCurrentPlayer) { currentPlayer = getFirstPlayer(); } } /** * Registers a new <code>FreeColGameObject</code> with the specified ID. * * @param id The unique ID of the <code>FreeColGameObject</code>. * @param freeColGameObject The <code>FreeColGameObject</code> that shall * be added to this <code>Game</code>. * @exception NullPointerException If either <code>id</code> or * <code>freeColGameObject * </code> are <i>null</i>. */ public void setFreeColGameObject(String id, FreeColGameObject freeColGameObject) { if (id == null || id.equals("") || freeColGameObject == null) { throw new NullPointerException(); } FreeColGameObject old = freeColGameObjects.put(id, freeColGameObject); if (old != null) { logger.warning("Replacing FreeColGameObject: " + old.getClass() + " with " + freeColGameObject.getClass()); throw new IllegalArgumentException("Replacing FreeColGameObject: " + old.getClass() + " with " + freeColGameObject.getClass()); } if (freeColGameObjectListener != null) { freeColGameObjectListener.setFreeColGameObject(id, freeColGameObject); } } public void setFreeColGameObjectListener(FreeColGameObjectListener freeColGameObjectListener) { this.freeColGameObjectListener = freeColGameObjectListener; } public FreeColGameObjectListener getFreeColGameObjectListener() { return freeColGameObjectListener; } /** * Gets the <code>FreeColGameObject</code> with the specified ID. * * @param id The identifier of the <code>FreeColGameObject</code>. * @return The <code>FreeColGameObject</code>. * @exception NullPointerException If <code>id == null</code>. */ public FreeColGameObject getFreeColGameObject(String id) { if (id == null || id.equals("")) { throw new NullPointerException(); } return freeColGameObjects.get(id); } /** * Get the {@link FreeColGameObject} with the given id or null. This method * does NOT throw if the id is invalid. * * @param id The id, may be null or invalid. * @return game object with id or null. */ public FreeColGameObject getFreeColGameObjectSafely(String id) { if (id != null) { return freeColGameObjects.get(id); } else { return null; } } /** * Removes the <code>FreeColGameObject</code> with the specified ID. * * @param id The identifier of the <code>FreeColGameObject</code> that * shall be removed from this <code>Game</code>. * @return The <code>FreeColGameObject</code> that has been removed. * @exception NullPointerException If <code>id == null</code>. */ public FreeColGameObject removeFreeColGameObject(String id) { if (id == null || id.equals("")) { throw new NullPointerException(); } if (freeColGameObjectListener != null) { freeColGameObjectListener.removeFreeColGameObject(id); } return freeColGameObjects.remove(id); } /** * Gets the <code>Map</code> that is being used in this game. * * @return The <code>Map</code> that is being used in this game or * <i>null</i> if no <code>Map</code> has been created. */ public Map getMap() { return map; } /** * Sets the <code>Map</code> that is going to be used in this game. * * @param map The <code>Map</code> that is going to be used in this game. */ public void setMap(Map map) { this.map = map; } /** * Returns a vacant nation. * * @return A vacant nation. */ public Nation getVacantNation() { if (vacantNations.isEmpty()) { return null; } else { return vacantNations.get(0); } } /** * Return a <code>Player</code> identified by it's nation. * * @param nationID The nation. * @return The <code>Player</code> of the given nation. */ public Player getPlayer(String nationID) { Iterator<Player> playerIterator = getPlayerIterator(); while (playerIterator.hasNext()) { Player player = playerIterator.next(); if (player.getNationID().equals(nationID)) { return player; } } return null; } public Player getPlayer(int index) { return players.get(index); } /** * Sets the current player. * * @param newCp The new current player. */ public void setCurrentPlayer(Player newCp) { if (newCp != null) { if (currentPlayer != null) { currentPlayer.endTurn(); } } else { logger.info("Current player set to 'null'."); } currentPlayer = newCp; } /** * Gets the current player. This is the <code>Player</code> currently * playing the <code>Game</code>. * * @return The current player. */ public Player getCurrentPlayer() { return currentPlayer; } /** * Gets the next current player. * * @return The player that will start its turn as soon as the current player * is ready. * @see #getCurrentPlayer */ public Player getNextPlayer() { return getPlayerAfter(currentPlayer); } /** * Gets the player after the given player. * * @param beforePlayer The <code>Player</code> before the * <code>Player</code> to be returned. * @return The <code>Player</code> after the <code>beforePlayer</code> * in the list which determines the order each player becomes the * current player. * @see #getNextPlayer */ public Player getPlayerAfter(Player beforePlayer) { if (players.size() == 0) { return null; } int index = players.indexOf(beforePlayer) + 1; if (index >= players.size()) { index = 0; } // Find first non-dead player: while (true) { Player player = players.get(index); if (!player.isDead()) { return player; } index++; if (index >= players.size()) { index = 0; } } } /** * Checks if the next player is in a new turn. * * @return <code>true</code> if changing to the <code>Player</code> * given by {@link #getNextPlayer()} would increase the current * number of turns by one. */ public boolean isNextPlayerInNewTurn() { return (players.indexOf(currentPlayer) > players.indexOf(getNextPlayer()) || currentPlayer == getNextPlayer()); /* * int index = players.indexOf(currentPlayer) + 1; return index >= * players.size(); */ } /** * Gets the first player in this game. * * @return the <code>Player</code> that was first added to this * <code>Game</code>. */ public Player getFirstPlayer() { if (players.size() > 0) { return players.get(0); } else { return null; } } /** * Gets an <code>Iterator</code> of every registered * <code>FreeColGameObject</code>. * * @return an <code>Iterator</code> containing every registered * <code>FreeColGameObject</code>. * @see #setFreeColGameObject */ public Iterator<FreeColGameObject> getFreeColGameObjectIterator() { return freeColGameObjects.values().iterator(); } /** * Gets a <code>Player</code> specified by a name. * * @param name The name identifying the <code>Player</code>. * @return The <code>Player</code>. */ public Player getPlayerByName(String name) { Iterator<Player> playerIterator = getPlayerIterator(); while (playerIterator.hasNext()) { Player player = playerIterator.next(); if (player.getName().equals(name)) { return player; } } return null; } /** * Checks if the specified name is in use. * * @param username The name. * @return <i>true</i> if the name is already in use and <i>false</i> * otherwise. */ public boolean playerNameInUse(String username) { Iterator<Player> playerIterator = getPlayerIterator(); while (playerIterator.hasNext()) { Player player = playerIterator.next(); if (player.getName().equals(username)) { return true; } } return false; } /** * Gets an <code>Iterator</code> of every <code>Player</code> in this * game. * * @return The <code>Iterator</code>. */ public Iterator<Player> getPlayerIterator() { return players.iterator(); } /** * Gets an <code>Vector</code> containing every <code>Player</code> in * this game. * * @return The <code>Vector</code>. */ public List<Player> getPlayers() { return players; } public int getNumberOfPlayers() { return players.size(); } /** * Returns all the European players known by the player of this game. * * @return All the European players known by the player of this game. */ public List<Player> getEuropeanPlayers() { List<Player> europeans = new ArrayList<Player>(); Iterator<Player> playerIterator = getPlayerIterator(); while (playerIterator.hasNext()) { Player player = playerIterator.next(); if (player.isEuropean()) { europeans.add(player); } } return europeans; } /** * Gets the maximum number of (human) players that can be added to * this game. * * @return the maximum number of (human) players that can be added to this * game */ public int getMaximumPlayers() { return maxPlayers; } /** * Sets the maximum number of (human) players that can be added to * this game. * * @param newMax an <code>int</code> value */ public void setMaximumPlayers(int newMax) { maxPlayers = newMax; } /** * Checks if a new <code>Player</code> can be added. * * @return <i>true</i> if a new player can be added and <i>false</i> * otherwise. */ public boolean canAddNewPlayer() { int realPlayers = 0; for (Player player : players) { if (!player.isAI()) realPlayers++; } return realPlayers < getMaximumPlayers(); } /** * Checks if all players are ready to launch. * * @return <i>true</i> if all players are ready to launch and <i>false</i> * otherwise. */ public boolean isAllPlayersReadyToLaunch() { Iterator<Player> playerIterator = getPlayerIterator(); while (playerIterator.hasNext()) { Player player = playerIterator.next(); if (!player.isReady()) { return false; } } return true; } /** * Checks the integrity of this <code>Game</code * by checking if there are any * {@link FreeColGameObject#isUninitialized() uninitialized objects}. * * Detected problems gets written to the log. * * @return <code>true</code> if the <code>Game</code> has * been loaded properly. */ @SuppressWarnings("unchecked") public boolean checkIntegrity() { boolean ok = true; Iterator<FreeColGameObject> iterator = ((HashMap<String, FreeColGameObject>) freeColGameObjects.clone()) .values().iterator(); while (iterator.hasNext()) { FreeColGameObject fgo = iterator.next(); if (fgo.isUninitialized()) { logger.warning("Uinitialized object: " + fgo.getId() + " (" + fgo.getClass() + ")"); ok = false; } } if (ok) { logger.info("Game integrity ok."); } else { logger.warning("Game integrity test failed."); } return ok; } /** * Prepares this <code>Game</code> for a new turn. * * Invokes <code>newTurn()</code> for every registered * <code>FreeColGamObject</code>. * * @see #setFreeColGameObject */ @SuppressWarnings("unchecked") public void newTurn() { turn.increase(); logger.info("Turn is now " + turn.toString()); for (Player player : players) { logger.finer("Calling newTurn for player " + player.getName()); player.newTurn(); } } /** * Gets the <code>GameOptions</code> that is associated with this * {@link Game}. */ public GameOptions getGameOptions() { return gameOptions; } /** * Gets the amount of gold needed for inciting. This method should NEVER be * randomized: it should always return the same amount if given the same * three parameters. * * @param payingPlayer The <code>Player</code> paying for the incite. * @param targetPlayer The <code>Player</code> to be attacked by the * <code>attackingPlayer</code>. * @param attackingPlayer The player that would be receiving the money for * incite. * @return The amount of gold that should be payed by * <code>payingPlayer</code> to <code>attackingPlayer</code> in * order for <code>attackingPlayer</code> to attack * <code>targetPlayer</code>. */ public static int getInciteAmount(Player payingPlayer, Player targetPlayer, Player attackingPlayer) { int amount = 0; Tension payingTension = attackingPlayer.getTension(payingPlayer); Tension targetTension = attackingPlayer.getTension(targetPlayer); if (targetTension != null && payingTension.getValue() > targetTension.getValue()) { amount = 10000; } else { amount = 5000; } amount += 20 * (payingTension.getValue() - targetTension.getValue()); return Math.max(amount, 650); } /** * This method writes an XML-representation of this object to the given * stream. * * <br> * <br> * * Only attributes visible to the given <code>Player</code> will be added * to that representation if <code>showAll</code> is set to * <code>false</code>. * * @param out The target stream. * @param player The <code>Player</code> this XML-representation should be * made for, or <code>null</code> if * <code>showAll == true</code>. * @param showAll Only attributes visible to <code>player</code> will be * added to the representation if <code>showAll</code> is set * to <i>false</i>. * @param toSavedGame If <code>true</code> then information that is only * needed when saving a game is added. * @throws XMLStreamException if there are any problems writing to the * stream. */ protected void toXMLImpl(XMLStreamWriter out, Player player, boolean showAll, boolean toSavedGame) throws XMLStreamException { // Start element: out.writeStartElement(getXMLElementTagName()); if (toSavedGame && !showAll) { throw new IllegalArgumentException("showAll must be set to true when toSavedGame is true."); } out.writeAttribute("ID", getId()); out.writeAttribute("turn", Integer.toString(getTurn().getNumber())); if (currentPlayer != null) { out.writeAttribute("currentPlayer", currentPlayer.getId()); } if (toSavedGame) { out.writeAttribute("nextID", Integer.toString(nextId)); } gameOptions.toXML(out); // serialize players Iterator<Player> playerIterator = getPlayerIterator(); while (playerIterator.hasNext()) { Player p = playerIterator.next(); p.toXML(out, player, showAll, toSavedGame); } if (getUnknownEnemy()!=null) { getUnknownEnemy().toXML(out, player, showAll, toSavedGame); } // serialize map if (map != null) { map.toXML(out, player, showAll, toSavedGame); } // serialize messages playerIterator = getPlayerIterator(); while (playerIterator.hasNext()) { Player p = playerIterator.next(); if (this.isClientTrusted() || showAll || p.equals(player)) { for (ModelMessage message : p.getModelMessages()) { message.toXML(out); } } } out.writeEndElement(); } /** * Initialize this object from an XML-representation of this object. * * @param in The input stream with the XML. */ protected void readFromXMLImpl(XMLStreamReader in) throws XMLStreamException { setId(in.getAttributeValue(null, "ID")); getTurn().setNumber(Integer.parseInt(in.getAttributeValue(null, "turn"))); final String nextIDStr = in.getAttributeValue(null, "nextID"); if (nextIDStr != null) { nextId = Integer.parseInt(nextIDStr); } final String currentPlayerStr = in.getAttributeValue(null, "currentPlayer"); if (currentPlayerStr != null) { currentPlayer = (Player) getFreeColGameObject(currentPlayerStr); if (currentPlayer == null) { currentPlayer = new Player(this, currentPlayerStr); players.add(currentPlayer); } } else { currentPlayer = null; } gameOptions = null; while (in.nextTag() != XMLStreamConstants.END_ELEMENT) { if (in.getLocalName().equals(GameOptions.getXMLElementTagName())) { // Gets the game options: if (gameOptions != null) { gameOptions.readFromXML(in); } else { gameOptions = new GameOptions(in); } } else if (in.getLocalName().equals(Player.getXMLElementTagName())) { Player player = (Player) getFreeColGameObject(in.getAttributeValue(null, "ID")); if (player != null) { player.readFromXML(in); } else { player = new Player(this, in); - players.add(player); + if (player.getName().equals(Player.UNKNOWN_ENEMY)) { + setUnknownEnemy(player); + } else { + players.add(player); + } } } else if (in.getLocalName().equals(Map.getXMLElementTagName())) { String mapId = in.getAttributeValue(null, "ID"); map = (Map) getFreeColGameObject(mapId); if (map != null) { map.readFromXML(in); } else { map = new Map(this, mapId); map.readFromXML(in); } } else if (in.getLocalName().equals(ModelMessage.getXMLElementTagName())) { ModelMessage message = new ModelMessage(); message.readFromXML(in, this); } else { logger.warning("Unknown tag: " + in.getLocalName() + " loading game"); } } // sanity check: we should be on the closing tag if (!in.getLocalName().equals(Game.getXMLElementTagName())) { logger.warning("Error parsing xml: expecting closing tag </" + Game.getXMLElementTagName() + "> "+ "found instead: " +in.getLocalName()); } if (gameOptions == null) { gameOptions = new GameOptions(); } } /** * Returns the tag name of the root element representing this object. * * @return the tag name. */ public static String getXMLElementTagName() { return "game"; } /** * Need to overwrite behavior of equals inherited from FreeColGameObject, * since two games are not the same if the have the same id. */ public boolean equals(Object o) { return this == o; } /** * Returns an increasing number that can be used when creating players. * @return The next player index */ public int getNextPlayerIndex() { return playerIndex++; } }
true
true
protected void readFromXMLImpl(XMLStreamReader in) throws XMLStreamException { setId(in.getAttributeValue(null, "ID")); getTurn().setNumber(Integer.parseInt(in.getAttributeValue(null, "turn"))); final String nextIDStr = in.getAttributeValue(null, "nextID"); if (nextIDStr != null) { nextId = Integer.parseInt(nextIDStr); } final String currentPlayerStr = in.getAttributeValue(null, "currentPlayer"); if (currentPlayerStr != null) { currentPlayer = (Player) getFreeColGameObject(currentPlayerStr); if (currentPlayer == null) { currentPlayer = new Player(this, currentPlayerStr); players.add(currentPlayer); } } else { currentPlayer = null; } gameOptions = null; while (in.nextTag() != XMLStreamConstants.END_ELEMENT) { if (in.getLocalName().equals(GameOptions.getXMLElementTagName())) { // Gets the game options: if (gameOptions != null) { gameOptions.readFromXML(in); } else { gameOptions = new GameOptions(in); } } else if (in.getLocalName().equals(Player.getXMLElementTagName())) { Player player = (Player) getFreeColGameObject(in.getAttributeValue(null, "ID")); if (player != null) { player.readFromXML(in); } else { player = new Player(this, in); players.add(player); } } else if (in.getLocalName().equals(Map.getXMLElementTagName())) { String mapId = in.getAttributeValue(null, "ID"); map = (Map) getFreeColGameObject(mapId); if (map != null) { map.readFromXML(in); } else { map = new Map(this, mapId); map.readFromXML(in); } } else if (in.getLocalName().equals(ModelMessage.getXMLElementTagName())) { ModelMessage message = new ModelMessage(); message.readFromXML(in, this); } else { logger.warning("Unknown tag: " + in.getLocalName() + " loading game"); } } // sanity check: we should be on the closing tag if (!in.getLocalName().equals(Game.getXMLElementTagName())) { logger.warning("Error parsing xml: expecting closing tag </" + Game.getXMLElementTagName() + "> "+ "found instead: " +in.getLocalName()); } if (gameOptions == null) { gameOptions = new GameOptions(); } }
protected void readFromXMLImpl(XMLStreamReader in) throws XMLStreamException { setId(in.getAttributeValue(null, "ID")); getTurn().setNumber(Integer.parseInt(in.getAttributeValue(null, "turn"))); final String nextIDStr = in.getAttributeValue(null, "nextID"); if (nextIDStr != null) { nextId = Integer.parseInt(nextIDStr); } final String currentPlayerStr = in.getAttributeValue(null, "currentPlayer"); if (currentPlayerStr != null) { currentPlayer = (Player) getFreeColGameObject(currentPlayerStr); if (currentPlayer == null) { currentPlayer = new Player(this, currentPlayerStr); players.add(currentPlayer); } } else { currentPlayer = null; } gameOptions = null; while (in.nextTag() != XMLStreamConstants.END_ELEMENT) { if (in.getLocalName().equals(GameOptions.getXMLElementTagName())) { // Gets the game options: if (gameOptions != null) { gameOptions.readFromXML(in); } else { gameOptions = new GameOptions(in); } } else if (in.getLocalName().equals(Player.getXMLElementTagName())) { Player player = (Player) getFreeColGameObject(in.getAttributeValue(null, "ID")); if (player != null) { player.readFromXML(in); } else { player = new Player(this, in); if (player.getName().equals(Player.UNKNOWN_ENEMY)) { setUnknownEnemy(player); } else { players.add(player); } } } else if (in.getLocalName().equals(Map.getXMLElementTagName())) { String mapId = in.getAttributeValue(null, "ID"); map = (Map) getFreeColGameObject(mapId); if (map != null) { map.readFromXML(in); } else { map = new Map(this, mapId); map.readFromXML(in); } } else if (in.getLocalName().equals(ModelMessage.getXMLElementTagName())) { ModelMessage message = new ModelMessage(); message.readFromXML(in, this); } else { logger.warning("Unknown tag: " + in.getLocalName() + " loading game"); } } // sanity check: we should be on the closing tag if (!in.getLocalName().equals(Game.getXMLElementTagName())) { logger.warning("Error parsing xml: expecting closing tag </" + Game.getXMLElementTagName() + "> "+ "found instead: " +in.getLocalName()); } if (gameOptions == null) { gameOptions = new GameOptions(); } }
diff --git a/src/org/radare/installer/LaunchActivity.java b/src/org/radare/installer/LaunchActivity.java index adc2b52..1790bdf 100644 --- a/src/org/radare/installer/LaunchActivity.java +++ b/src/org/radare/installer/LaunchActivity.java @@ -1,105 +1,107 @@ /* radare2 installer for Android (c) 2012 Pau Oliva Fora <pof[at]eslack[dot]org> */ package org.radare.installer; import org.radare.installer.Utils; import android.app.Activity; import android.os.Bundle; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.RadioGroup; import android.widget.EditText; import android.widget.TextView; import android.widget.TextView.BufferType; import android.net.Uri; import android.widget.Toast; import java.io.File; public class LaunchActivity extends Activity { private Utils mUtils; private RadioGroup radiogroup; private Button btnDisplay; private EditText file_to_open; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUtils = new Utils(getApplicationContext()); File radarebin = new File("/data/data/org.radare.installer/radare2/bin/radare2"); if (radarebin.exists()) { - // Get intent, action and MIME type + // Get intent, action and extras Intent intent = getIntent(); String action = intent.getAction(); - String type = intent.getType(); Bundle bundle = intent.getExtras(); setContentView(R.layout.launch); String path = "/system/bin/toolbox"; - if (Intent.ACTION_SEND.equals(action) && type.startsWith("application/")) { + if (Intent.ACTION_SEND.equals(action)) { Uri uri = (Uri)bundle.get(Intent.EXTRA_STREAM); path = uri.decode(uri.toString()); - if (path.endsWith(".apk") || path.endsWith(".APK")) { - path = path.replace("file://", "apk://"); - } if (path.startsWith("file://")) { path = path.replace("file://", ""); } + if (path.startsWith("content://")) { + path = path.replaceAll("content://[^/]*", ""); + } + if (path.endsWith(".apk") || path.endsWith(".APK")) { + path = path.replaceAll("^", "apk://"); + } if (path == null) path = "/system/bin/toolbox"; file_to_open = (EditText) findViewById(R.id.file_to_open); file_to_open.setText(path, TextView.BufferType.EDITABLE); } addListenerOnButton(); } else { mUtils.myToast("Please install radare2 first!", Toast.LENGTH_SHORT); finish(); } } public void addListenerOnButton() { radiogroup = (RadioGroup) findViewById(R.id.radiogroup1); btnDisplay = (Button) findViewById(R.id.button_open); btnDisplay.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { int selectedId = radiogroup.getCheckedRadioButtonId(); file_to_open = (EditText) findViewById(R.id.file_to_open); Bundle b = new Bundle(); b.putString("filename", '"' + file_to_open.getText().toString() + '"'); switch (selectedId) { case R.id.radiobutton_web : Intent intent1 = new Intent(LaunchActivity.this, WebActivity.class); intent1.putExtras(b); startActivity(intent1); break; case R.id.radiobutton_console : Intent intent2 = new Intent(LaunchActivity.this, LauncherActivity.class); intent2.putExtras(b); startActivity(intent2); break; } } }); } }
false
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUtils = new Utils(getApplicationContext()); File radarebin = new File("/data/data/org.radare.installer/radare2/bin/radare2"); if (radarebin.exists()) { // Get intent, action and MIME type Intent intent = getIntent(); String action = intent.getAction(); String type = intent.getType(); Bundle bundle = intent.getExtras(); setContentView(R.layout.launch); String path = "/system/bin/toolbox"; if (Intent.ACTION_SEND.equals(action) && type.startsWith("application/")) { Uri uri = (Uri)bundle.get(Intent.EXTRA_STREAM); path = uri.decode(uri.toString()); if (path.endsWith(".apk") || path.endsWith(".APK")) { path = path.replace("file://", "apk://"); } if (path.startsWith("file://")) { path = path.replace("file://", ""); } if (path == null) path = "/system/bin/toolbox"; file_to_open = (EditText) findViewById(R.id.file_to_open); file_to_open.setText(path, TextView.BufferType.EDITABLE); } addListenerOnButton(); } else { mUtils.myToast("Please install radare2 first!", Toast.LENGTH_SHORT); finish(); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUtils = new Utils(getApplicationContext()); File radarebin = new File("/data/data/org.radare.installer/radare2/bin/radare2"); if (radarebin.exists()) { // Get intent, action and extras Intent intent = getIntent(); String action = intent.getAction(); Bundle bundle = intent.getExtras(); setContentView(R.layout.launch); String path = "/system/bin/toolbox"; if (Intent.ACTION_SEND.equals(action)) { Uri uri = (Uri)bundle.get(Intent.EXTRA_STREAM); path = uri.decode(uri.toString()); if (path.startsWith("file://")) { path = path.replace("file://", ""); } if (path.startsWith("content://")) { path = path.replaceAll("content://[^/]*", ""); } if (path.endsWith(".apk") || path.endsWith(".APK")) { path = path.replaceAll("^", "apk://"); } if (path == null) path = "/system/bin/toolbox"; file_to_open = (EditText) findViewById(R.id.file_to_open); file_to_open.setText(path, TextView.BufferType.EDITABLE); } addListenerOnButton(); } else { mUtils.myToast("Please install radare2 first!", Toast.LENGTH_SHORT); finish(); } }
diff --git a/src/com/bukkit/cian1500ww/giveit/GiveMeAdd.java b/src/com/bukkit/cian1500ww/giveit/GiveMeAdd.java index 7f11a2e..4fc031b 100644 --- a/src/com/bukkit/cian1500ww/giveit/GiveMeAdd.java +++ b/src/com/bukkit/cian1500ww/giveit/GiveMeAdd.java @@ -1,85 +1,85 @@ package com.bukkit.cian1500ww.giveit; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Properties; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** * GiveIt for Bukkit * * @author cian1500ww [email protected] * @version 1.2 * This class logs the players actions to GiveIt.log * */ public class GiveMeAdd { private ArrayList mods = new ArrayList(); public boolean givemeadd(CommandSender sender, String[] trimmedArgs) throws IOException{ Player player = (Player)sender; String f ="plugins/GiveIt/allowed.txt"; if ((trimmedArgs[0] == null) || (trimmedArgs[1]== null)) { return false; } - else if(trimmedArgs[2]==null){ + else if(trimmedArgs.length>2 && trimmedArgs[2]!=null){ String itemid = trimmedArgs[0]; String amount = trimmedArgs[1]; BufferedWriter out = new BufferedWriter(new FileWriter(f, true)); out.write(itemid+"="+amount); player.sendMessage("GiveIt: Item added to allowed list"); return true; } - else if(trimmedArgs[2]!=null){ + else if(trimmedArgs.length<=2){ String itemid = trimmedArgs[0]; String amount = trimmedArgs[1]; String chosen_player = trimmedArgs[2]; BufferedWriter out = new BufferedWriter(new FileWriter(f, true)); out.write(itemid+"="+amount+"."+chosen_player); player.sendMessage("GiveIt: Item added to allowed list"); return true; } else return false; } public boolean givemeremove(CommandSender sender, String[] trimmedArgs) throws IOException{ Player player = (Player)sender; Properties prop = new Properties(); try { InputStream is = new FileInputStream("plugins/GiveIt/allowed.txt"); prop.load(is); } catch (IOException e) { System.out.println("GiveIt: Problem opening allowed.txt file"); } if ((trimmedArgs[0] == null) || (trimmedArgs[0].length() > 3) || (trimmedArgs[0].length() < 3)) { return false; } else if(trimmedArgs[0]!=null){ prop.remove(trimmedArgs[0]); player.sendMessage("GiveIt: Successfully removed item number "+ trimmedArgs[0]); return true; } else return false; } }
false
true
public boolean givemeadd(CommandSender sender, String[] trimmedArgs) throws IOException{ Player player = (Player)sender; String f ="plugins/GiveIt/allowed.txt"; if ((trimmedArgs[0] == null) || (trimmedArgs[1]== null)) { return false; } else if(trimmedArgs[2]==null){ String itemid = trimmedArgs[0]; String amount = trimmedArgs[1]; BufferedWriter out = new BufferedWriter(new FileWriter(f, true)); out.write(itemid+"="+amount); player.sendMessage("GiveIt: Item added to allowed list"); return true; } else if(trimmedArgs[2]!=null){ String itemid = trimmedArgs[0]; String amount = trimmedArgs[1]; String chosen_player = trimmedArgs[2]; BufferedWriter out = new BufferedWriter(new FileWriter(f, true)); out.write(itemid+"="+amount+"."+chosen_player); player.sendMessage("GiveIt: Item added to allowed list"); return true; } else return false; }
public boolean givemeadd(CommandSender sender, String[] trimmedArgs) throws IOException{ Player player = (Player)sender; String f ="plugins/GiveIt/allowed.txt"; if ((trimmedArgs[0] == null) || (trimmedArgs[1]== null)) { return false; } else if(trimmedArgs.length>2 && trimmedArgs[2]!=null){ String itemid = trimmedArgs[0]; String amount = trimmedArgs[1]; BufferedWriter out = new BufferedWriter(new FileWriter(f, true)); out.write(itemid+"="+amount); player.sendMessage("GiveIt: Item added to allowed list"); return true; } else if(trimmedArgs.length<=2){ String itemid = trimmedArgs[0]; String amount = trimmedArgs[1]; String chosen_player = trimmedArgs[2]; BufferedWriter out = new BufferedWriter(new FileWriter(f, true)); out.write(itemid+"="+amount+"."+chosen_player); player.sendMessage("GiveIt: Item added to allowed list"); return true; } else return false; }
diff --git a/plugins/org.eclipse.wazaabi.engine.swt.commons/src/org/eclipse/wazaabi/engine/swt/commons/views/collections/DynamicFilterProvider.java b/plugins/org.eclipse.wazaabi.engine.swt.commons/src/org/eclipse/wazaabi/engine/swt/commons/views/collections/DynamicFilterProvider.java index 6ae881be..2066e79a 100644 --- a/plugins/org.eclipse.wazaabi.engine.swt.commons/src/org/eclipse/wazaabi/engine/swt/commons/views/collections/DynamicFilterProvider.java +++ b/plugins/org.eclipse.wazaabi.engine.swt.commons/src/org/eclipse/wazaabi/engine/swt/commons/views/collections/DynamicFilterProvider.java @@ -1,74 +1,74 @@ /******************************************************************************* * Copyright (c) 2013 Olivier Moises * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Olivier Moises- initial API and implementation *******************************************************************************/ package org.eclipse.wazaabi.engine.swt.commons.views.collections; import org.eclipse.jface.viewers.Viewer; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.wazaabi.engine.edp.EDPSingletons; import org.eclipse.wazaabi.engine.edp.coderesolution.AbstractCodeDescriptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class DynamicFilterProvider extends ViewerFilter { private static final Logger logger = LoggerFactory .getLogger(DynamicFilterProvider.class); private String uri = null; private AbstractCodeDescriptor.MethodDescriptor getSelectMethodDescriptor = null; // TODO : very bad and verbose code // we should be able to get the codeDescriptor from the methodDescriptor private AbstractCodeDescriptor getSelectCodeDescriptor = null; public String getURI() { return uri; } public void updateDynamicProviderURI(String uri, String baseURI) { this.uri = uri; if (uri == null || uri.length() == 0) { return; } - if (baseURI != null && !baseURI.isEmpty()) + if (baseURI != null && baseURI.length() != 0) uri = EDPSingletons.getComposedCodeLocator().getFullPath(baseURI, uri, null); AbstractCodeDescriptor codeDescriptor = EDPSingletons .getComposedCodeLocator().resolveCodeDescriptor(uri); if (codeDescriptor != null) { AbstractCodeDescriptor.MethodDescriptor methodDescriptor = codeDescriptor .getMethodDescriptor( "select", new String[] { "parentElement", "element" }, new Class[] { Object.class, Object.class }, boolean.class); //$NON-NLS-1$ //$NON-NLS-2$ if (methodDescriptor != null) { getSelectMethodDescriptor = methodDescriptor; getSelectCodeDescriptor = codeDescriptor; } } } public void dispose() { logger.debug("Disposing filter {}", this); } @Override public boolean select(Viewer viewer, Object parentElement, Object element) { if (getSelectMethodDescriptor != null && getSelectCodeDescriptor != null) { return (Boolean) getSelectCodeDescriptor.invokeMethod( getSelectMethodDescriptor, new Object[] { parentElement, element }); } return false; } }
true
true
public void updateDynamicProviderURI(String uri, String baseURI) { this.uri = uri; if (uri == null || uri.length() == 0) { return; } if (baseURI != null && !baseURI.isEmpty()) uri = EDPSingletons.getComposedCodeLocator().getFullPath(baseURI, uri, null); AbstractCodeDescriptor codeDescriptor = EDPSingletons .getComposedCodeLocator().resolveCodeDescriptor(uri); if (codeDescriptor != null) { AbstractCodeDescriptor.MethodDescriptor methodDescriptor = codeDescriptor .getMethodDescriptor( "select", new String[] { "parentElement", "element" }, new Class[] { Object.class, Object.class }, boolean.class); //$NON-NLS-1$ //$NON-NLS-2$ if (methodDescriptor != null) { getSelectMethodDescriptor = methodDescriptor; getSelectCodeDescriptor = codeDescriptor; } }
public void updateDynamicProviderURI(String uri, String baseURI) { this.uri = uri; if (uri == null || uri.length() == 0) { return; } if (baseURI != null && baseURI.length() != 0) uri = EDPSingletons.getComposedCodeLocator().getFullPath(baseURI, uri, null); AbstractCodeDescriptor codeDescriptor = EDPSingletons .getComposedCodeLocator().resolveCodeDescriptor(uri); if (codeDescriptor != null) { AbstractCodeDescriptor.MethodDescriptor methodDescriptor = codeDescriptor .getMethodDescriptor( "select", new String[] { "parentElement", "element" }, new Class[] { Object.class, Object.class }, boolean.class); //$NON-NLS-1$ //$NON-NLS-2$ if (methodDescriptor != null) { getSelectMethodDescriptor = methodDescriptor; getSelectCodeDescriptor = codeDescriptor; } }
diff --git a/src/org/bouncycastle/crypto/params/DHKeyGenerationParameters.java b/src/org/bouncycastle/crypto/params/DHKeyGenerationParameters.java index abafe4bd..910081e8 100644 --- a/src/org/bouncycastle/crypto/params/DHKeyGenerationParameters.java +++ b/src/org/bouncycastle/crypto/params/DHKeyGenerationParameters.java @@ -1,25 +1,25 @@ package org.bouncycastle.crypto.params; import java.security.SecureRandom; import org.bouncycastle.crypto.KeyGenerationParameters; public class DHKeyGenerationParameters extends KeyGenerationParameters { private DHParameters params; public DHKeyGenerationParameters( SecureRandom random, DHParameters params) { - super(random, (params.getJ() != 0) ? params.getJ() : params.getP().bitLength() - 1); + super(random, params.getP().bitLength()); this.params = params; } public DHParameters getParameters() { return params; } }
true
true
public DHKeyGenerationParameters( SecureRandom random, DHParameters params) { super(random, (params.getJ() != 0) ? params.getJ() : params.getP().bitLength() - 1); this.params = params; }
public DHKeyGenerationParameters( SecureRandom random, DHParameters params) { super(random, params.getP().bitLength()); this.params = params; }
diff --git a/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java b/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java index 5f2ae1a7a..3a4fbb24b 100644 --- a/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java +++ b/core/src/main/java/hudson/node_monitors/AbstractNodeMonitorDescriptor.java @@ -1,133 +1,136 @@ package hudson.node_monitors; import hudson.model.Computer; import hudson.model.Descriptor; import hudson.model.Hudson; import hudson.triggers.Trigger; import hudson.triggers.SafeTimerTask; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * Convenient base class for common {@link NodeMonitor} implementation * where the "monitoring" consists of executing something periodically on every node * and taking some action based on its result. * * <p> * "T" represents the the result of the monitoring. * * @author Kohsuke Kawaguchi */ public abstract class AbstractNodeMonitorDescriptor<T> extends Descriptor<NodeMonitor> { protected AbstractNodeMonitorDescriptor(Class<? extends NodeMonitor> clazz) { this(clazz,HOUR); } protected AbstractNodeMonitorDescriptor(Class<? extends NodeMonitor> clazz, long interval) { super(clazz); // check every hour Trigger.timer.scheduleAtFixedRate(new SafeTimerTask() { public void doRun() { // start checking new Record().start(); } }, interval, interval); } /** * Represents the last record of the update */ private volatile Record record = null; /** * Represents the update activity in progress. */ private volatile Record inProgress = null; /** * Performs monitoring of the given computer object. * This method is invoked periodically to perform the monitoring of the computer. */ protected abstract T monitor(Computer c) throws IOException,InterruptedException; /** * Obtains the monitoring result. */ public T get(Computer c) { if(record==null) { // if this is the first time, schedule the check now if(inProgress==null) { synchronized(this) { if(inProgress==null) new Record().start(); } } return null; } return record.data.get(c); } /** * Thread that monitors nodes, as well as the data structure to record * the result. */ private final class Record extends Thread { /** * Last computed monitoring result. */ private final Map<Computer,T> data = new HashMap<Computer,T>(); /** * When was {@link #data} last updated? */ private Date lastUpdated; public Record() { super("Monitoring thread for "+getDisplayName()+" started on "+new Date()); synchronized(AbstractNodeMonitorDescriptor.this) { if(inProgress!=null) { // maybe it got stuck? LOGGER.warning("Previous "+getDisplayName()+" monitoring activity still in progress. Interrupting"); inProgress.interrupt(); } inProgress = this; } } public void run() { try { long startTime = System.currentTimeMillis(); for( Computer c : Hudson.getInstance().getComputers() ) { try { - data.put(c,monitor(c)); + if(c.isOffline()) + data.put(c,null); + else + data.put(c,monitor(c)); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to monitor "+c+" for "+getDisplayName(), e); } } lastUpdated = new Date(); synchronized(AbstractNodeMonitorDescriptor.this) { assert inProgress==this; inProgress = null; record = this; } LOGGER.info("Node monitoring "+getDisplayName()+" completed in "+(System.currentTimeMillis()-startTime)+"ms"); } catch (InterruptedException e) { LOGGER.log(Level.WARNING,"Node monitoring "+getDisplayName()+" aborted.",e); } } } private final Logger LOGGER = Logger.getLogger(getClass().getName()); private static final long HOUR = 1000*60*60L; }
true
true
public void run() { try { long startTime = System.currentTimeMillis(); for( Computer c : Hudson.getInstance().getComputers() ) { try { data.put(c,monitor(c)); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to monitor "+c+" for "+getDisplayName(), e); } } lastUpdated = new Date(); synchronized(AbstractNodeMonitorDescriptor.this) { assert inProgress==this; inProgress = null; record = this; } LOGGER.info("Node monitoring "+getDisplayName()+" completed in "+(System.currentTimeMillis()-startTime)+"ms"); } catch (InterruptedException e) { LOGGER.log(Level.WARNING,"Node monitoring "+getDisplayName()+" aborted.",e); } }
public void run() { try { long startTime = System.currentTimeMillis(); for( Computer c : Hudson.getInstance().getComputers() ) { try { if(c.isOffline()) data.put(c,null); else data.put(c,monitor(c)); } catch (IOException e) { LOGGER.log(Level.WARNING, "Failed to monitor "+c+" for "+getDisplayName(), e); } } lastUpdated = new Date(); synchronized(AbstractNodeMonitorDescriptor.this) { assert inProgress==this; inProgress = null; record = this; } LOGGER.info("Node monitoring "+getDisplayName()+" completed in "+(System.currentTimeMillis()-startTime)+"ms"); } catch (InterruptedException e) { LOGGER.log(Level.WARNING,"Node monitoring "+getDisplayName()+" aborted.",e); } }
diff --git a/tool/src/java/org/sakaiproject/evaluation/tool/producers/ReportsViewEssaysProducer.java b/tool/src/java/org/sakaiproject/evaluation/tool/producers/ReportsViewEssaysProducer.java index d5f0f33a..7f4452be 100644 --- a/tool/src/java/org/sakaiproject/evaluation/tool/producers/ReportsViewEssaysProducer.java +++ b/tool/src/java/org/sakaiproject/evaluation/tool/producers/ReportsViewEssaysProducer.java @@ -1,278 +1,278 @@ /****************************************************************************** * ReportsViewEssaysProducer.java - created on Oct 05, 2006 * * Copyright (c) 2007 Virginia Polytechnic Institute and State University * Licensed under the Educational Community License version 1.0 * * A copy of the Educational Community License has been included in this * distribution and is available at: http://www.opensource.org/licenses/ecl1.php *****************************************************************************/ package org.sakaiproject.evaluation.tool.producers; import java.util.ArrayList; import java.util.List; import org.sakaiproject.evaluation.logic.EvalAuthoringService; import org.sakaiproject.evaluation.logic.EvalEvaluationService; import org.sakaiproject.evaluation.logic.EvalDeliveryService; import org.sakaiproject.evaluation.logic.externals.EvalExternalLogic; import org.sakaiproject.evaluation.model.EvalAnswer; import org.sakaiproject.evaluation.model.EvalEvaluation; import org.sakaiproject.evaluation.model.EvalItem; import org.sakaiproject.evaluation.model.EvalTemplate; import org.sakaiproject.evaluation.model.EvalTemplateItem; import org.sakaiproject.evaluation.model.constant.EvalConstants; import org.sakaiproject.evaluation.tool.reporting.ReportingPermissions; import org.sakaiproject.evaluation.tool.viewparams.EssayResponseParams; import org.sakaiproject.evaluation.tool.viewparams.ReportParameters; import org.sakaiproject.evaluation.tool.viewparams.TemplateViewParameters; import org.sakaiproject.evaluation.utils.TemplateItemUtils; import org.sakaiproject.util.FormattedText; import uk.org.ponder.rsf.components.UIBranchContainer; import uk.org.ponder.rsf.components.UIContainer; import uk.org.ponder.rsf.components.UIInternalLink; import uk.org.ponder.rsf.components.UIMessage; import uk.org.ponder.rsf.components.UIOutput; import uk.org.ponder.rsf.components.decorators.DecoratorList; import uk.org.ponder.rsf.components.decorators.UIStyleDecorator; import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter; import uk.org.ponder.rsf.view.ComponentChecker; import uk.org.ponder.rsf.view.ViewComponentProducer; import uk.org.ponder.rsf.viewstate.SimpleViewParameters; import uk.org.ponder.rsf.viewstate.ViewParameters; import uk.org.ponder.rsf.viewstate.ViewParamsReporter; /** * rendering the Short Answer/Essay part report of an evaluation * * @author Rui Feng ([email protected]) * @author Will Humphries ([email protected]) */ public class ReportsViewEssaysProducer implements ViewComponentProducer, NavigationCaseReporter, ViewParamsReporter { public static final String VIEW_ID = "view_essay_response"; public String getViewID() { return VIEW_ID; } private EvalExternalLogic externalLogic; public void setExternalLogic(EvalExternalLogic externalLogic) { this.externalLogic = externalLogic; } private EvalAuthoringService authoringService; public void setAuthoringService(EvalAuthoringService authoringService) { this.authoringService = authoringService; } private EvalEvaluationService evaluationService; public void setEvaluationService(EvalEvaluationService evaluationService) { this.evaluationService = evaluationService; } private EvalDeliveryService deliveryService; public void setDeliveryService(EvalDeliveryService deliveryService) { this.deliveryService = deliveryService; } private ReportingPermissions reportingPermissions; public void setReportingPermissions(ReportingPermissions perms) { this.reportingPermissions = perms; } public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { // local variables used in the render logic String currentUserId = externalLogic.getCurrentUserId(); boolean userAdmin = externalLogic.isUserAdmin(currentUserId); boolean createTemplate = authoringService.canCreateTemplate(currentUserId); boolean beginEvaluation = evaluationService.canBeginEvaluation(currentUserId); /* * top links here */ UIInternalLink.make(tofill, "summary-link", UIMessage.make("summary.page.title"), new SimpleViewParameters(SummaryProducer.VIEW_ID)); if (userAdmin) { UIInternalLink.make(tofill, "administrate-link", UIMessage.make("administrate.page.title"), new SimpleViewParameters(AdministrateProducer.VIEW_ID)); UIInternalLink.make(tofill, "control-scales-link", UIMessage.make("controlscales.page.title"), new SimpleViewParameters(ControlScalesProducer.VIEW_ID)); } if (createTemplate) { UIInternalLink.make(tofill, "control-templates-link", UIMessage.make("controltemplates.page.title"), new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID)); UIInternalLink.make(tofill, "control-items-link", UIMessage.make("controlitems.page.title"), new SimpleViewParameters(ControlItemsProducer.VIEW_ID)); } else { throw new SecurityException("User attempted to access " + VIEW_ID + " when they are not allowed"); } if (beginEvaluation) { UIInternalLink.make(tofill, "control-evaluations-link", UIMessage.make("controlevaluations.page.title"), new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID)); } UIMessage.make(tofill, "view-essay-title", "viewessay.page.title"); EssayResponseParams ervps = (EssayResponseParams) viewparams; UIInternalLink.make(tofill, "report-groups-title", UIMessage.make("reportgroups.page.title"), new TemplateViewParameters(ReportChooseGroupsProducer.VIEW_ID, ervps.evalId)); UIInternalLink.make(tofill, "viewReportLink", UIMessage.make("viewreport.page.title"), new ReportParameters(ReportsViewingProducer.VIEW_ID, ervps.evalId, ervps.groupIds)); // Note: The groups id's should always be passed whether it is for single item or all items if (ervps.evalId != null) { EvalEvaluation evaluation = evaluationService.getEvaluationById(ervps.evalId); // do a permission check - if (reportingPermissions.canViewEvaluationResponses(evaluation, ervps.groupIds)) { + if (!reportingPermissions.canViewEvaluationResponses(evaluation, ervps.groupIds)) { throw new SecurityException("Invalid user attempting to access reports page: " + currentUserId); } // get template from DAO EvalTemplate template = evaluation.getTemplate(); // output single set of essay responses if (ervps.itemId != null) { // we are actually passing EvalTemplateItem ID EvalTemplateItem myTempItem = authoringService.getTemplateItemById(ervps.itemId); EvalItem myItem = myTempItem.getItem(); String cat = myTempItem.getCategory(); UIBranchContainer radiobranch = null; UIBranchContainer courseSection = null; UIBranchContainer instructorSection = null; if (cat != null && cat.equals(EvalConstants.ITEM_CATEGORY_COURSE)) {// "Course" courseSection = UIBranchContainer.make(tofill, "courseSection:"); UIMessage.make(courseSection, "course-questions-header", "takeeval.group.questions.header"); radiobranch = UIBranchContainer.make(courseSection, "itemrow:first", "0"); this.doFillComponent(myItem, ervps.evalId, 0, ervps.groupIds, radiobranch, courseSection); } else if (cat != null && cat.equals(EvalConstants.ITEM_CATEGORY_INSTRUCTOR)) {// "Instructor" instructorSection = UIBranchContainer.make(tofill, "instructorSection:"); UIMessage.make(instructorSection, "instructor-questions-header", "takeeval.instructor.questions.header"); radiobranch = UIBranchContainer.make(instructorSection, "itemrow:first", "0"); this.doFillComponent(myItem, ervps.evalId, 0, ervps.groupIds, radiobranch, instructorSection); } } else { // get all items since one is not specified List<EvalTemplateItem> allItems = new ArrayList<EvalTemplateItem>(template.getTemplateItems()); // LAZY LOAD if (!allItems.isEmpty()) { // non-child items are sorted by display order List<EvalTemplateItem> ncItemsList = TemplateItemUtils.getNonChildItems(allItems); // check if there are any "Course" items or "Instructor" items; UIBranchContainer courseSection = null; UIBranchContainer instructorSection = null; if (TemplateItemUtils.checkTemplateItemsCategoryExists( EvalConstants.ITEM_CATEGORY_COURSE, ncItemsList)) { courseSection = UIBranchContainer.make(tofill, "courseSection:"); //$NON-NLS-1$ } if (TemplateItemUtils.checkTemplateItemsCategoryExists( EvalConstants.ITEM_CATEGORY_INSTRUCTOR, ncItemsList)) { instructorSection = UIBranchContainer.make(tofill, "instructorSection:"); //$NON-NLS-1$ } for (int i = 0; i < ncItemsList.size(); i++) { EvalTemplateItem tempItem1 = (EvalTemplateItem) ncItemsList.get(i); EvalItem item1 = tempItem1.getItem(); String cat = tempItem1.getCategory(); UIBranchContainer radiobranch = null; if (cat != null && cat.equals(EvalConstants.ITEM_CATEGORY_COURSE) && item1.getClassification().equals(EvalConstants.ITEM_TYPE_TEXT)) { // "Course","Short Answer/Essay" radiobranch = UIBranchContainer.make(courseSection, "itemrow:first", i + ""); // need the alt row highlights between essays, not groups of essays // if (i % 2 == 1) // radiobranch.decorators = new DecoratorList( // new UIColourDecorator(null, // Color.decode(EvalToolConstants.LIGHT_GRAY_COLOR))); this.doFillComponent(item1, evaluation.getId(), i, ervps.groupIds, radiobranch, courseSection); } else if (cat != null && cat.equals(EvalConstants.ITEM_CATEGORY_INSTRUCTOR) && item1.getClassification().equals(EvalConstants.ITEM_TYPE_TEXT)) { // "Instructor","Short Answer/Essay" radiobranch = UIBranchContainer.make(instructorSection, "itemrow:first", i + ""); // need the alt row highlights between essays, not groups of essays // if (i % 2 == 1) // radiobranch.decorators = new DecoratorList( // new UIColourDecorator(null, // Color.decode(EvalToolConstants.LIGHT_GRAY_COLOR))); this.doFillComponent(item1, evaluation.getId(), i, ervps.groupIds, radiobranch, instructorSection); } } // end of for loop } } } } /** * @param myItem * @param evalId * @param i * @param groupIds * @param radiobranch * @param tofill */ private void doFillComponent(EvalItem myItem, Long evalId, int i, String[] groupIds, UIBranchContainer radiobranch, UIContainer tofill) { if (myItem.getClassification().equals(EvalConstants.ITEM_TYPE_TEXT)) { // "Short Answer/Essay" UIBranchContainer essay = UIBranchContainer.make(radiobranch, "essayType:"); UIOutput.make(essay, "itemNum", (i + 1) + ""); UIOutput.make(essay, "itemText", FormattedText.convertFormattedTextToPlaintext(myItem.getItemText())); List<EvalAnswer> itemAnswers = deliveryService.getEvalAnswers(myItem.getId(), evalId, groupIds); //count the number of answers that match this one for (int y = 0; y < itemAnswers.size(); y++) { UIBranchContainer answerbranch = UIBranchContainer.make(essay, "answers:", y + ""); if (y % 2 == 1) { answerbranch.decorators = new DecoratorList(new UIStyleDecorator("itemsListOddLine")); // must match the existing CSS class } EvalAnswer curr = itemAnswers.get(y); UIOutput.make(answerbranch, "answerNum", new Integer(y + 1).toString()); UIOutput.make(answerbranch, "itemAnswer", curr.getText()); } } } public ViewParameters getViewParameters() { return new EssayResponseParams(VIEW_ID, null, null, null); } public List reportNavigationCases() { List i = new ArrayList(); return i; } }
true
true
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { // local variables used in the render logic String currentUserId = externalLogic.getCurrentUserId(); boolean userAdmin = externalLogic.isUserAdmin(currentUserId); boolean createTemplate = authoringService.canCreateTemplate(currentUserId); boolean beginEvaluation = evaluationService.canBeginEvaluation(currentUserId); /* * top links here */ UIInternalLink.make(tofill, "summary-link", UIMessage.make("summary.page.title"), new SimpleViewParameters(SummaryProducer.VIEW_ID)); if (userAdmin) { UIInternalLink.make(tofill, "administrate-link", UIMessage.make("administrate.page.title"), new SimpleViewParameters(AdministrateProducer.VIEW_ID)); UIInternalLink.make(tofill, "control-scales-link", UIMessage.make("controlscales.page.title"), new SimpleViewParameters(ControlScalesProducer.VIEW_ID)); } if (createTemplate) { UIInternalLink.make(tofill, "control-templates-link", UIMessage.make("controltemplates.page.title"), new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID)); UIInternalLink.make(tofill, "control-items-link", UIMessage.make("controlitems.page.title"), new SimpleViewParameters(ControlItemsProducer.VIEW_ID)); } else { throw new SecurityException("User attempted to access " + VIEW_ID + " when they are not allowed"); } if (beginEvaluation) { UIInternalLink.make(tofill, "control-evaluations-link", UIMessage.make("controlevaluations.page.title"), new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID)); } UIMessage.make(tofill, "view-essay-title", "viewessay.page.title"); EssayResponseParams ervps = (EssayResponseParams) viewparams; UIInternalLink.make(tofill, "report-groups-title", UIMessage.make("reportgroups.page.title"), new TemplateViewParameters(ReportChooseGroupsProducer.VIEW_ID, ervps.evalId)); UIInternalLink.make(tofill, "viewReportLink", UIMessage.make("viewreport.page.title"), new ReportParameters(ReportsViewingProducer.VIEW_ID, ervps.evalId, ervps.groupIds)); // Note: The groups id's should always be passed whether it is for single item or all items if (ervps.evalId != null) { EvalEvaluation evaluation = evaluationService.getEvaluationById(ervps.evalId); // do a permission check if (reportingPermissions.canViewEvaluationResponses(evaluation, ervps.groupIds)) { throw new SecurityException("Invalid user attempting to access reports page: " + currentUserId); } // get template from DAO EvalTemplate template = evaluation.getTemplate(); // output single set of essay responses if (ervps.itemId != null) { // we are actually passing EvalTemplateItem ID EvalTemplateItem myTempItem = authoringService.getTemplateItemById(ervps.itemId); EvalItem myItem = myTempItem.getItem(); String cat = myTempItem.getCategory(); UIBranchContainer radiobranch = null; UIBranchContainer courseSection = null; UIBranchContainer instructorSection = null; if (cat != null && cat.equals(EvalConstants.ITEM_CATEGORY_COURSE)) {// "Course" courseSection = UIBranchContainer.make(tofill, "courseSection:"); UIMessage.make(courseSection, "course-questions-header", "takeeval.group.questions.header"); radiobranch = UIBranchContainer.make(courseSection, "itemrow:first", "0"); this.doFillComponent(myItem, ervps.evalId, 0, ervps.groupIds, radiobranch, courseSection); } else if (cat != null && cat.equals(EvalConstants.ITEM_CATEGORY_INSTRUCTOR)) {// "Instructor" instructorSection = UIBranchContainer.make(tofill, "instructorSection:"); UIMessage.make(instructorSection, "instructor-questions-header", "takeeval.instructor.questions.header"); radiobranch = UIBranchContainer.make(instructorSection, "itemrow:first", "0"); this.doFillComponent(myItem, ervps.evalId, 0, ervps.groupIds, radiobranch, instructorSection); } } else { // get all items since one is not specified List<EvalTemplateItem> allItems = new ArrayList<EvalTemplateItem>(template.getTemplateItems()); // LAZY LOAD if (!allItems.isEmpty()) { // non-child items are sorted by display order List<EvalTemplateItem> ncItemsList = TemplateItemUtils.getNonChildItems(allItems); // check if there are any "Course" items or "Instructor" items; UIBranchContainer courseSection = null; UIBranchContainer instructorSection = null; if (TemplateItemUtils.checkTemplateItemsCategoryExists( EvalConstants.ITEM_CATEGORY_COURSE, ncItemsList)) { courseSection = UIBranchContainer.make(tofill, "courseSection:"); //$NON-NLS-1$ } if (TemplateItemUtils.checkTemplateItemsCategoryExists( EvalConstants.ITEM_CATEGORY_INSTRUCTOR, ncItemsList)) { instructorSection = UIBranchContainer.make(tofill, "instructorSection:"); //$NON-NLS-1$ } for (int i = 0; i < ncItemsList.size(); i++) { EvalTemplateItem tempItem1 = (EvalTemplateItem) ncItemsList.get(i); EvalItem item1 = tempItem1.getItem(); String cat = tempItem1.getCategory(); UIBranchContainer radiobranch = null; if (cat != null && cat.equals(EvalConstants.ITEM_CATEGORY_COURSE) && item1.getClassification().equals(EvalConstants.ITEM_TYPE_TEXT)) { // "Course","Short Answer/Essay" radiobranch = UIBranchContainer.make(courseSection, "itemrow:first", i + ""); // need the alt row highlights between essays, not groups of essays // if (i % 2 == 1) // radiobranch.decorators = new DecoratorList( // new UIColourDecorator(null, // Color.decode(EvalToolConstants.LIGHT_GRAY_COLOR))); this.doFillComponent(item1, evaluation.getId(), i, ervps.groupIds, radiobranch, courseSection); } else if (cat != null && cat.equals(EvalConstants.ITEM_CATEGORY_INSTRUCTOR) && item1.getClassification().equals(EvalConstants.ITEM_TYPE_TEXT)) { // "Instructor","Short Answer/Essay" radiobranch = UIBranchContainer.make(instructorSection, "itemrow:first", i + ""); // need the alt row highlights between essays, not groups of essays // if (i % 2 == 1) // radiobranch.decorators = new DecoratorList( // new UIColourDecorator(null, // Color.decode(EvalToolConstants.LIGHT_GRAY_COLOR))); this.doFillComponent(item1, evaluation.getId(), i, ervps.groupIds, radiobranch, instructorSection); } } // end of for loop } } } }
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) { // local variables used in the render logic String currentUserId = externalLogic.getCurrentUserId(); boolean userAdmin = externalLogic.isUserAdmin(currentUserId); boolean createTemplate = authoringService.canCreateTemplate(currentUserId); boolean beginEvaluation = evaluationService.canBeginEvaluation(currentUserId); /* * top links here */ UIInternalLink.make(tofill, "summary-link", UIMessage.make("summary.page.title"), new SimpleViewParameters(SummaryProducer.VIEW_ID)); if (userAdmin) { UIInternalLink.make(tofill, "administrate-link", UIMessage.make("administrate.page.title"), new SimpleViewParameters(AdministrateProducer.VIEW_ID)); UIInternalLink.make(tofill, "control-scales-link", UIMessage.make("controlscales.page.title"), new SimpleViewParameters(ControlScalesProducer.VIEW_ID)); } if (createTemplate) { UIInternalLink.make(tofill, "control-templates-link", UIMessage.make("controltemplates.page.title"), new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID)); UIInternalLink.make(tofill, "control-items-link", UIMessage.make("controlitems.page.title"), new SimpleViewParameters(ControlItemsProducer.VIEW_ID)); } else { throw new SecurityException("User attempted to access " + VIEW_ID + " when they are not allowed"); } if (beginEvaluation) { UIInternalLink.make(tofill, "control-evaluations-link", UIMessage.make("controlevaluations.page.title"), new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID)); } UIMessage.make(tofill, "view-essay-title", "viewessay.page.title"); EssayResponseParams ervps = (EssayResponseParams) viewparams; UIInternalLink.make(tofill, "report-groups-title", UIMessage.make("reportgroups.page.title"), new TemplateViewParameters(ReportChooseGroupsProducer.VIEW_ID, ervps.evalId)); UIInternalLink.make(tofill, "viewReportLink", UIMessage.make("viewreport.page.title"), new ReportParameters(ReportsViewingProducer.VIEW_ID, ervps.evalId, ervps.groupIds)); // Note: The groups id's should always be passed whether it is for single item or all items if (ervps.evalId != null) { EvalEvaluation evaluation = evaluationService.getEvaluationById(ervps.evalId); // do a permission check if (!reportingPermissions.canViewEvaluationResponses(evaluation, ervps.groupIds)) { throw new SecurityException("Invalid user attempting to access reports page: " + currentUserId); } // get template from DAO EvalTemplate template = evaluation.getTemplate(); // output single set of essay responses if (ervps.itemId != null) { // we are actually passing EvalTemplateItem ID EvalTemplateItem myTempItem = authoringService.getTemplateItemById(ervps.itemId); EvalItem myItem = myTempItem.getItem(); String cat = myTempItem.getCategory(); UIBranchContainer radiobranch = null; UIBranchContainer courseSection = null; UIBranchContainer instructorSection = null; if (cat != null && cat.equals(EvalConstants.ITEM_CATEGORY_COURSE)) {// "Course" courseSection = UIBranchContainer.make(tofill, "courseSection:"); UIMessage.make(courseSection, "course-questions-header", "takeeval.group.questions.header"); radiobranch = UIBranchContainer.make(courseSection, "itemrow:first", "0"); this.doFillComponent(myItem, ervps.evalId, 0, ervps.groupIds, radiobranch, courseSection); } else if (cat != null && cat.equals(EvalConstants.ITEM_CATEGORY_INSTRUCTOR)) {// "Instructor" instructorSection = UIBranchContainer.make(tofill, "instructorSection:"); UIMessage.make(instructorSection, "instructor-questions-header", "takeeval.instructor.questions.header"); radiobranch = UIBranchContainer.make(instructorSection, "itemrow:first", "0"); this.doFillComponent(myItem, ervps.evalId, 0, ervps.groupIds, radiobranch, instructorSection); } } else { // get all items since one is not specified List<EvalTemplateItem> allItems = new ArrayList<EvalTemplateItem>(template.getTemplateItems()); // LAZY LOAD if (!allItems.isEmpty()) { // non-child items are sorted by display order List<EvalTemplateItem> ncItemsList = TemplateItemUtils.getNonChildItems(allItems); // check if there are any "Course" items or "Instructor" items; UIBranchContainer courseSection = null; UIBranchContainer instructorSection = null; if (TemplateItemUtils.checkTemplateItemsCategoryExists( EvalConstants.ITEM_CATEGORY_COURSE, ncItemsList)) { courseSection = UIBranchContainer.make(tofill, "courseSection:"); //$NON-NLS-1$ } if (TemplateItemUtils.checkTemplateItemsCategoryExists( EvalConstants.ITEM_CATEGORY_INSTRUCTOR, ncItemsList)) { instructorSection = UIBranchContainer.make(tofill, "instructorSection:"); //$NON-NLS-1$ } for (int i = 0; i < ncItemsList.size(); i++) { EvalTemplateItem tempItem1 = (EvalTemplateItem) ncItemsList.get(i); EvalItem item1 = tempItem1.getItem(); String cat = tempItem1.getCategory(); UIBranchContainer radiobranch = null; if (cat != null && cat.equals(EvalConstants.ITEM_CATEGORY_COURSE) && item1.getClassification().equals(EvalConstants.ITEM_TYPE_TEXT)) { // "Course","Short Answer/Essay" radiobranch = UIBranchContainer.make(courseSection, "itemrow:first", i + ""); // need the alt row highlights between essays, not groups of essays // if (i % 2 == 1) // radiobranch.decorators = new DecoratorList( // new UIColourDecorator(null, // Color.decode(EvalToolConstants.LIGHT_GRAY_COLOR))); this.doFillComponent(item1, evaluation.getId(), i, ervps.groupIds, radiobranch, courseSection); } else if (cat != null && cat.equals(EvalConstants.ITEM_CATEGORY_INSTRUCTOR) && item1.getClassification().equals(EvalConstants.ITEM_TYPE_TEXT)) { // "Instructor","Short Answer/Essay" radiobranch = UIBranchContainer.make(instructorSection, "itemrow:first", i + ""); // need the alt row highlights between essays, not groups of essays // if (i % 2 == 1) // radiobranch.decorators = new DecoratorList( // new UIColourDecorator(null, // Color.decode(EvalToolConstants.LIGHT_GRAY_COLOR))); this.doFillComponent(item1, evaluation.getId(), i, ervps.groupIds, radiobranch, instructorSection); } } // end of for loop } } } }
diff --git a/bm-api-impl/src/main/java/com/pa165/bookingmanager/service/impl/UserServiceImpl.java b/bm-api-impl/src/main/java/com/pa165/bookingmanager/service/impl/UserServiceImpl.java index 5921bb8..d00e793 100644 --- a/bm-api-impl/src/main/java/com/pa165/bookingmanager/service/impl/UserServiceImpl.java +++ b/bm-api-impl/src/main/java/com/pa165/bookingmanager/service/impl/UserServiceImpl.java @@ -1,147 +1,147 @@ package com.pa165.bookingmanager.service.impl; import com.pa165.bookingmanager.convertor.impl.UserConvertorImpl; import com.pa165.bookingmanager.dao.UserDao; import com.pa165.bookingmanager.dto.UserDto; import com.pa165.bookingmanager.entity.UserEntity; import com.pa165.bookingmanager.service.UserService; import org.hibernate.criterion.Criterion; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * @author Jana Polakova, Jakub Polak */ @Service("userService") @Transactional(readOnly = true) public class UserServiceImpl implements UserService { @Autowired UserDao userDao; @Autowired UserConvertorImpl userConvertor; /** * {@inheritDoc} */ @Override public List<UserDto> findAll() { List<UserEntity> userEntities = userDao.findAll(); List<UserDto> userDtos = null; if (userEntities != null){ userDtos = userConvertor.convertEntityListToDtoList(userEntities); } return userDtos; } /** * {@inheritDoc} */ @Override public List<UserDto> findByCriteria(Criterion criterion) { if (criterion == null){ throw new IllegalArgumentException("Id can't be null."); } - List<UserEntity> userEntities = userDao.findAll(); + List<UserEntity> userEntities = userDao.findByCriteria(criterion); List<UserDto> userDtos = null; if (userEntities != null){ userDtos = userConvertor.convertEntityListToDtoList(userEntities); } return userDtos; } /** * {@inheritDoc} */ @Override public UserDto findOneByEmail(String email){ if (email == null){ throw new IllegalArgumentException("Email can't be null."); } UserEntity userEntity = userDao.findOneByEmail(email); UserDto userDto = null; if (userEntity != null){ userDto = userConvertor.convertEntityToDto(userEntity); } return userDto; } /** * {@inheritDoc} */ @Override public UserDto find(Long id) { if (id == null){ throw new IllegalArgumentException("Id can't be null."); } UserEntity userEntity = userDao.find(id); UserDto userDto = null; if (userEntity != null){ userDto = userConvertor.convertEntityToDto(userEntity); } return userDto; } /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public void create(UserDto userDto) { if (userDto == null){ throw new IllegalArgumentException("UserDto can't be null."); } userDao.create(userConvertor.convertDtoToEntity(userDto)); } /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public void update(UserDto userDto) { if (userDto == null){ throw new IllegalArgumentException("UserDto can't be null."); } UserEntity userEntity = userDao.find(userDto.getId()); if (userEntity != null){ userConvertor.convertDtoToEntity(userDto, userEntity); userDao.update(userEntity); } } /** * {@inheritDoc} */ @Override @Transactional(readOnly = false) public void delete(UserDto userDto) { if (userDto == null){ throw new IllegalArgumentException("UserDto can't be null."); } UserEntity userEntity = userDao.find(userDto.getId()); if (userEntity != null){ userDao.delete(userEntity); } } }
true
true
public List<UserDto> findByCriteria(Criterion criterion) { if (criterion == null){ throw new IllegalArgumentException("Id can't be null."); } List<UserEntity> userEntities = userDao.findAll(); List<UserDto> userDtos = null; if (userEntities != null){ userDtos = userConvertor.convertEntityListToDtoList(userEntities); } return userDtos; }
public List<UserDto> findByCriteria(Criterion criterion) { if (criterion == null){ throw new IllegalArgumentException("Id can't be null."); } List<UserEntity> userEntities = userDao.findByCriteria(criterion); List<UserDto> userDtos = null; if (userEntities != null){ userDtos = userConvertor.convertEntityListToDtoList(userEntities); } return userDtos; }
diff --git a/Assignment6/StupidWorkload.java b/Assignment6/StupidWorkload.java index f9b72dd..9ce35fc 100644 --- a/Assignment6/StupidWorkload.java +++ b/Assignment6/StupidWorkload.java @@ -1,90 +1,90 @@ import java.util.ArrayList; import java.util.List; import java.util.Random; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; /** * This one measures time between reads and writes of the same document. * Ryan thinks that it is stupid. */ public class StupidWorkload extends Workload { private static final int TIMES = 1000000; //private static final int TIMES = 10; private String[] randomStrings; /** * Do setup in constructor to avoid artifically slowing down the experiment. */ public StupidWorkload() { randomStrings = new String[TIMES]; // Seed it so it is repeatable. Random rand = new Random(4); for (int i = 0; i < TIMES; i++) { randomStrings[i] = "" + rand.nextInt(); } } protected Stats executeMySQLImpl() { String readQuery = "SELECT name FROM ReadWriteTest WHERE id = 1"; - String writeUpdate = "UPDATE users SET name = '%s' WHERE id = 1"; + String writeUpdate = "UPDATE ReadWriteTest SET name = '%s' WHERE id = 1"; List<Long> readAfterWriteTimes = new ArrayList<Long>(TIMES); List<Long> writeAfterReadTimes = new ArrayList<Long>(TIMES); Statement statement = null; ResultSet results = null; try { // Get a statement from the connection statement = conn.createStatement(); long time = System.currentTimeMillis(); for (int i = 0; i < TIMES; i++) { results = statement.executeQuery(readQuery); if (i != 0) { readAfterWriteTimes.add(System.currentTimeMillis() - time); } time = System.currentTimeMillis(); statement.executeUpdate(String.format(writeUpdate, randomStrings[i])); writeAfterReadTimes.add(System.currentTimeMillis() - time); time = System.currentTimeMillis(); } } catch (Exception ex) { System.err.println("Error getting read/write times."); ex.printStackTrace(System.err); } finally { try { if (results != null) { results.close(); results = null; } if (statement != null) { statement.close(); statement = null; } } catch (SQLException sqlEx) { // ... oh well. System.err.println("Error Closing results."); } } return new ReadWriteStats(readAfterWriteTimes, writeAfterReadTimes); } protected Stats executeCouchImpl() { // Nope throw new UnsupportedOperationException(); } }
true
true
protected Stats executeMySQLImpl() { String readQuery = "SELECT name FROM ReadWriteTest WHERE id = 1"; String writeUpdate = "UPDATE users SET name = '%s' WHERE id = 1"; List<Long> readAfterWriteTimes = new ArrayList<Long>(TIMES); List<Long> writeAfterReadTimes = new ArrayList<Long>(TIMES); Statement statement = null; ResultSet results = null; try { // Get a statement from the connection statement = conn.createStatement(); long time = System.currentTimeMillis(); for (int i = 0; i < TIMES; i++) { results = statement.executeQuery(readQuery); if (i != 0) { readAfterWriteTimes.add(System.currentTimeMillis() - time); } time = System.currentTimeMillis(); statement.executeUpdate(String.format(writeUpdate, randomStrings[i])); writeAfterReadTimes.add(System.currentTimeMillis() - time); time = System.currentTimeMillis(); } } catch (Exception ex) { System.err.println("Error getting read/write times."); ex.printStackTrace(System.err); } finally { try { if (results != null) { results.close(); results = null; } if (statement != null) { statement.close(); statement = null; } } catch (SQLException sqlEx) { // ... oh well. System.err.println("Error Closing results."); } } return new ReadWriteStats(readAfterWriteTimes, writeAfterReadTimes); }
protected Stats executeMySQLImpl() { String readQuery = "SELECT name FROM ReadWriteTest WHERE id = 1"; String writeUpdate = "UPDATE ReadWriteTest SET name = '%s' WHERE id = 1"; List<Long> readAfterWriteTimes = new ArrayList<Long>(TIMES); List<Long> writeAfterReadTimes = new ArrayList<Long>(TIMES); Statement statement = null; ResultSet results = null; try { // Get a statement from the connection statement = conn.createStatement(); long time = System.currentTimeMillis(); for (int i = 0; i < TIMES; i++) { results = statement.executeQuery(readQuery); if (i != 0) { readAfterWriteTimes.add(System.currentTimeMillis() - time); } time = System.currentTimeMillis(); statement.executeUpdate(String.format(writeUpdate, randomStrings[i])); writeAfterReadTimes.add(System.currentTimeMillis() - time); time = System.currentTimeMillis(); } } catch (Exception ex) { System.err.println("Error getting read/write times."); ex.printStackTrace(System.err); } finally { try { if (results != null) { results.close(); results = null; } if (statement != null) { statement.close(); statement = null; } } catch (SQLException sqlEx) { // ... oh well. System.err.println("Error Closing results."); } } return new ReadWriteStats(readAfterWriteTimes, writeAfterReadTimes); }
diff --git a/srcj/com/sun/electric/tool/generator/layout/fill/FillGenConfig.java b/srcj/com/sun/electric/tool/generator/layout/fill/FillGenConfig.java index d803f9932..26a9877d6 100644 --- a/srcj/com/sun/electric/tool/generator/layout/fill/FillGenConfig.java +++ b/srcj/com/sun/electric/tool/generator/layout/fill/FillGenConfig.java @@ -1,159 +1,158 @@ /* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: FillGenConfig.java * * Copyright (c) 2006 Sun Microsystems and Static Free Software * * Electric(tm) is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Electric(tm) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.generator.layout.fill; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import com.sun.electric.technology.Technology; import com.sun.electric.tool.Job; import com.sun.electric.tool.generator.layout.TechType; /****************************** CONFIG ******************************/ public class FillGenConfig implements Serializable { private TechType.TechTypeEnum techType = null; public FillGeneratorTool.FillTypeEnum fillType = FillGeneratorTool.FillTypeEnum.INVALID; public String fillLibName; List<ReserveConfig> reserves = new ArrayList<ReserveConfig>(); public boolean evenLayersHorizontal; public double width, height, targetW, targetH, minTileSizeX, minTileSizeY; public ExportConfig perim; public int firstLayer, lastLayer; public int[] cellTiles; public boolean hierarchy; public double minOverlap; public double drcSpacingRule; public boolean binary; public boolean useMaster; public boolean onlyAround; public double gap; // allowed overlap between given cells and masters. Typical value is 1.5 public FillGenType fillCellType = FillGenType.INTERNAL; public int level; // to control the level of hierarchy in case of onlyAround option public Job job; public enum FillGenType { INTERNAL(0), // uses internal router ONLYSKILL(1), // only generates the fill without connection SEAGATES(2); // uses sea-of-gates router for connection private final int mode; FillGenType(int m) { mode = m; } public int getMode() {return mode;} public static FillGenType find(int mode) { for (FillGenType m : FillGenType.values()) { if (m.mode == mode) return m; } return INTERNAL; // It should not assume that is the default case } } public FillGenConfig(TechType.TechTypeEnum tech) { techType = tech; } - public FillGenConfig(TechType.TechTypeEnum tech, FillGeneratorTool.FillTypeEnum type, String lib, ExportConfig perim, - int first, int last, - double w, double h, boolean even, + public FillGenConfig(TechType.TechTypeEnum tech, FillGeneratorTool.FillTypeEnum type, String lib, + ExportConfig perim, int first, int last, double w, double h, boolean even, int[] cellTiles, boolean hierarchy, double minO, double drcSpacingRule, boolean binary, boolean useMaster, boolean onlyAround, double gap, FillGenType genType, int level) { this.fillType = type; this.cellTiles = cellTiles; this.hierarchy = hierarchy; this.minOverlap = minO; this.drcSpacingRule = drcSpacingRule; this.binary = binary; this.width = w; this.height = h; this.evenLayersHorizontal = even; this.useMaster = useMaster; techType = tech; this.fillLibName = lib; this.perim = perim; this.firstLayer = first; this.lastLayer = last; this.onlyAround = onlyAround; this.gap = gap; // only valid if onlyAround=true this.fillCellType = genType; this.level = level; } public TechType getTechType() { return techType.getTechType(); } public boolean is180Tech() { return techType == TechType.TechTypeEnum.MOCMOS || techType == TechType.TechTypeEnum.TSMC180; } public void setTargetValues(double targetW, double targetH, double sx, double sy) { this.targetW = targetW; this.targetH = targetH; this.minTileSizeX = sx; this.minTileSizeY = sy; } public ReserveConfig reserveSpaceOnLayer(Technology tech, int layer, double vddReserved, FillGeneratorTool.Units vddUnits, double gndReserved, FillGeneratorTool.Units gndUnits) { int numMetals = tech.getNumMetals(); Job.error(layer<1 || layer>numMetals, "Bad layer. Layers must be between 2 and "+numMetals+ " inclusive: "+ layer); ReserveConfig config = new ReserveConfig(layer, vddReserved, gndReserved, vddUnits, gndUnits); reserves.add(config); return config; } public static class ReserveConfig implements Serializable { int layer; double vddReserved, gndReserved, vddWidth, gndWidth; FillGeneratorTool.Units vddUnits, gndUnits, vddWUnits, gndWUnits; ReserveConfig(int layer, double vddReserved, double gndReserved, FillGeneratorTool.Units vddUnits, FillGeneratorTool.Units gndUnits) { this.layer = layer; this.vddReserved = vddReserved; this.gndReserved = gndReserved; this.vddUnits = vddUnits; this.gndUnits = gndUnits; this.vddWUnits = FillGeneratorTool.Units.NONE; this.gndWUnits = FillGeneratorTool.Units.NONE; } public void reserveWidthOnLayer(double vddW, FillGeneratorTool.Units vddUnits, double gndW, FillGeneratorTool.Units gndUnits) { this.vddWidth = vddW; this.gndWidth = gndW; this.vddWUnits = vddUnits; this.gndWUnits = gndUnits; } } }
true
true
public FillGenConfig(TechType.TechTypeEnum tech, FillGeneratorTool.FillTypeEnum type, String lib, ExportConfig perim, int first, int last, double w, double h, boolean even, int[] cellTiles, boolean hierarchy, double minO, double drcSpacingRule, boolean binary, boolean useMaster, boolean onlyAround, double gap, FillGenType genType, int level) { this.fillType = type; this.cellTiles = cellTiles; this.hierarchy = hierarchy; this.minOverlap = minO; this.drcSpacingRule = drcSpacingRule; this.binary = binary; this.width = w; this.height = h; this.evenLayersHorizontal = even; this.useMaster = useMaster; techType = tech; this.fillLibName = lib; this.perim = perim; this.firstLayer = first; this.lastLayer = last; this.onlyAround = onlyAround; this.gap = gap; // only valid if onlyAround=true this.fillCellType = genType; this.level = level; }
public FillGenConfig(TechType.TechTypeEnum tech, FillGeneratorTool.FillTypeEnum type, String lib, ExportConfig perim, int first, int last, double w, double h, boolean even, int[] cellTiles, boolean hierarchy, double minO, double drcSpacingRule, boolean binary, boolean useMaster, boolean onlyAround, double gap, FillGenType genType, int level) { this.fillType = type; this.cellTiles = cellTiles; this.hierarchy = hierarchy; this.minOverlap = minO; this.drcSpacingRule = drcSpacingRule; this.binary = binary; this.width = w; this.height = h; this.evenLayersHorizontal = even; this.useMaster = useMaster; techType = tech; this.fillLibName = lib; this.perim = perim; this.firstLayer = first; this.lastLayer = last; this.onlyAround = onlyAround; this.gap = gap; // only valid if onlyAround=true this.fillCellType = genType; this.level = level; }
diff --git a/src/main/java/org/apache/ibatis/type/BaseTypeHandler.java b/src/main/java/org/apache/ibatis/type/BaseTypeHandler.java index db40cdc0d8..69683ca536 100644 --- a/src/main/java/org/apache/ibatis/type/BaseTypeHandler.java +++ b/src/main/java/org/apache/ibatis/type/BaseTypeHandler.java @@ -1,85 +1,85 @@ /* * Copyright 2009-2011 The MyBatis Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.type; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.apache.ibatis.session.Configuration; public abstract class BaseTypeHandler<T> extends TypeReference<T> implements TypeHandler<T> { protected Configuration configuration; public void setConfiguration(Configuration c) { this.configuration = c; } public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException { if (parameter == null) { if (jdbcType == null) { throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters."); } try { ps.setNull(i, jdbcType.TYPE_CODE); } catch (SQLException e) { throw new TypeException("Error setting null for parameter #" + i + " with JdbcType " + jdbcType + " . " + - "Try setting a different jdbcTypeForNull configuration propertiy or provide an explicit JdbcType for this parameter. " + + "Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. " + "Cause: " + e, e); } } else { setNonNullParameter(ps, i, parameter, jdbcType); } } public T getResult(ResultSet rs, String columnName) throws SQLException { T result = getNullableResult(rs, columnName); if (rs.wasNull()) { return null; } else { return result; } } public T getResult(ResultSet rs, int columnIndex) throws SQLException { T result = getNullableResult(rs, columnIndex); if (rs.wasNull()) { return null; } else { return result; } } public T getResult(CallableStatement cs, int columnIndex) throws SQLException { T result = getNullableResult(cs, columnIndex); if (cs.wasNull()) { return null; } else { return result; } } public abstract void setNonNullParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException; public abstract T getNullableResult(ResultSet rs, String columnName) throws SQLException; public abstract T getNullableResult(ResultSet rs, int columnIndex) throws SQLException; public abstract T getNullableResult(CallableStatement cs, int columnIndex) throws SQLException; }
true
true
public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException { if (parameter == null) { if (jdbcType == null) { throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters."); } try { ps.setNull(i, jdbcType.TYPE_CODE); } catch (SQLException e) { throw new TypeException("Error setting null for parameter #" + i + " with JdbcType " + jdbcType + " . " + "Try setting a different jdbcTypeForNull configuration propertiy or provide an explicit JdbcType for this parameter. " + "Cause: " + e, e); } } else { setNonNullParameter(ps, i, parameter, jdbcType); } }
public void setParameter(PreparedStatement ps, int i, T parameter, JdbcType jdbcType) throws SQLException { if (parameter == null) { if (jdbcType == null) { throw new TypeException("JDBC requires that the JdbcType must be specified for all nullable parameters."); } try { ps.setNull(i, jdbcType.TYPE_CODE); } catch (SQLException e) { throw new TypeException("Error setting null for parameter #" + i + " with JdbcType " + jdbcType + " . " + "Try setting a different JdbcType for this parameter or a different jdbcTypeForNull configuration property. " + "Cause: " + e, e); } } else { setNonNullParameter(ps, i, parameter, jdbcType); } }
diff --git a/org.eclipse.swordfish.plugins.planner.policy/src/org/eclipse/swordfish/plugins/planner/policy/PolicyAssertionHintExtractor.java b/org.eclipse.swordfish.plugins.planner.policy/src/org/eclipse/swordfish/plugins/planner/policy/PolicyAssertionHintExtractor.java index aa37417f..195681cc 100644 --- a/org.eclipse.swordfish.plugins.planner.policy/src/org/eclipse/swordfish/plugins/planner/policy/PolicyAssertionHintExtractor.java +++ b/org.eclipse.swordfish.plugins.planner.policy/src/org/eclipse/swordfish/plugins/planner/policy/PolicyAssertionHintExtractor.java @@ -1,109 +1,112 @@ /******************************************************************************* * Copyright (c) 2008, 2009 SOPERA GmbH. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * SOPERA GmbH - initial API and implementation *******************************************************************************/ package org.eclipse.swordfish.plugins.planner.policy; import static java.util.Collections.emptyList; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.jbi.messaging.MessageExchange; import javax.xml.namespace.QName; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.neethi.Assertion; import org.apache.neethi.Policy; import org.apache.servicemix.common.util.DOMUtil; import org.apache.servicemix.nmr.api.Exchange; import org.apache.servicemix.nmr.api.Role; import org.eclipse.swordfish.core.planner.strategy.Hint; import org.eclipse.swordfish.core.planner.strategy.HintExtractor; import org.eclipse.swordfish.core.resolver.policy.PolicyExtractor; import org.eclipse.swordfish.internal.core.util.smx.ServiceMixSupport; import org.w3c.dom.DocumentFragment; import org.w3c.dom.Element; public class PolicyAssertionHintExtractor implements HintExtractor { public static final String ENDPOINT_METADAT_PROPERTY = "org.eclipse.swordfish.core.resolver.EndpointMetadata"; private static final Log LOG = LogFactory.getLog(PolicyAssertionHintExtractor.class); private static final List<Hint<?>> EMPTY_LIST = emptyList(); private PolicyExtractor policyExtractor; public PolicyExtractor getPolicyExtractor() { return policyExtractor; } public void setPolicyExtractor(PolicyExtractor policyExtractor) { this.policyExtractor = policyExtractor; } public PolicyAssertionHintExtractor() { } public List<Hint<?>> extractHints(MessageExchange messageExchange) { Policy policy = getPolicy(messageExchange); return policy != null ? extractAssertions(policy) : EMPTY_LIST; } private Policy getPolicy(MessageExchange messageExchange) { Policy policy = null; try { Exchange exchange = ServiceMixSupport.toNMRExchange(messageExchange); if(exchange.getRole() == Role.Consumer){ Map headers = (Map)exchange.getIn().getHeader("org.apache.servicemix.soap.headers"); - DocumentFragment policyFragment = + if (headers == null) { + return null; + } + DocumentFragment policyFragment = (DocumentFragment)headers.get(new QName("http://eclipse.org/swordfish/headers", "Policy")); if (policyFragment == null) { for (Object key : headers.keySet()) { if (key instanceof QName && ((QName)key).getLocalPart().equals("Policy")) { policyFragment = (DocumentFragment) headers.get(key); } } } if (policyFragment == null) { return null; } Element policyElement = (Element)policyFragment.getFirstChild(); String source = DOMUtil.asXML(policyElement); return policyExtractor.extractPolicy(new ByteArrayInputStream(source.getBytes("UTF8"))); } } catch (Exception ex) { LOG.warn(ex.getMessage(), ex); } return policy; } @SuppressWarnings("unchecked") public List <Hint<?>> extractAssertions(Policy policy) { List <Hint<?>> assertions = new ArrayList<Hint<?>>(); Iterator<Iterable<Assertion>> alternativesIter = policy.getAlternatives(); if (alternativesIter.hasNext()) { Iterable<Assertion> alternative = alternativesIter.next(); for (Assertion assertion : alternative) { assertions.add(new AssertionHint<Assertion>(assertion)); } } return assertions; } }
true
true
private Policy getPolicy(MessageExchange messageExchange) { Policy policy = null; try { Exchange exchange = ServiceMixSupport.toNMRExchange(messageExchange); if(exchange.getRole() == Role.Consumer){ Map headers = (Map)exchange.getIn().getHeader("org.apache.servicemix.soap.headers"); DocumentFragment policyFragment = (DocumentFragment)headers.get(new QName("http://eclipse.org/swordfish/headers", "Policy")); if (policyFragment == null) { for (Object key : headers.keySet()) { if (key instanceof QName && ((QName)key).getLocalPart().equals("Policy")) { policyFragment = (DocumentFragment) headers.get(key); } } } if (policyFragment == null) { return null; } Element policyElement = (Element)policyFragment.getFirstChild(); String source = DOMUtil.asXML(policyElement); return policyExtractor.extractPolicy(new ByteArrayInputStream(source.getBytes("UTF8"))); } } catch (Exception ex) { LOG.warn(ex.getMessage(), ex); } return policy; }
private Policy getPolicy(MessageExchange messageExchange) { Policy policy = null; try { Exchange exchange = ServiceMixSupport.toNMRExchange(messageExchange); if(exchange.getRole() == Role.Consumer){ Map headers = (Map)exchange.getIn().getHeader("org.apache.servicemix.soap.headers"); if (headers == null) { return null; } DocumentFragment policyFragment = (DocumentFragment)headers.get(new QName("http://eclipse.org/swordfish/headers", "Policy")); if (policyFragment == null) { for (Object key : headers.keySet()) { if (key instanceof QName && ((QName)key).getLocalPart().equals("Policy")) { policyFragment = (DocumentFragment) headers.get(key); } } } if (policyFragment == null) { return null; } Element policyElement = (Element)policyFragment.getFirstChild(); String source = DOMUtil.asXML(policyElement); return policyExtractor.extractPolicy(new ByteArrayInputStream(source.getBytes("UTF8"))); } } catch (Exception ex) { LOG.warn(ex.getMessage(), ex); } return policy; }
diff --git a/src/cli/src/test/java/org/geogit/cli/test/functional/InitSteps.java b/src/cli/src/test/java/org/geogit/cli/test/functional/InitSteps.java index 09661659..f90e4efe 100644 --- a/src/cli/src/test/java/org/geogit/cli/test/functional/InitSteps.java +++ b/src/cli/src/test/java/org/geogit/cli/test/functional/InitSteps.java @@ -1,276 +1,278 @@ /* Copyright (c) 2011 TOPP - www.openplans.org. All rights reserved. * This code is licensed under the LGPL 2.1 license, available at the root * application directory. */ package org.geogit.cli.test.functional; import static org.geogit.cli.test.functional.GlobalState.currentDirectory; import static org.geogit.cli.test.functional.GlobalState.geogit; import static org.geogit.cli.test.functional.GlobalState.geogitCLI; import static org.geogit.cli.test.functional.GlobalState.homeDirectory; import static org.geogit.cli.test.functional.GlobalState.stdOut; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.List; import org.apache.commons.io.FileUtils; import org.geogit.api.GeoGIT; import org.geogit.api.GlobalInjectorBuilder; import org.geogit.api.ObjectId; import org.geogit.api.Ref; import org.geogit.api.plumbing.RefParse; import org.geogit.api.plumbing.UpdateRef; import com.google.common.base.Optional; import com.google.inject.Injector; import cucumber.annotation.en.Given; import cucumber.annotation.en.Then; import cucumber.annotation.en.When; /** * */ public class InitSteps extends AbstractGeogitFunctionalTest { @cucumber.annotation.After public void after() { if (GlobalState.geogit != null) { GlobalState.geogit.close(); } deleteDirectories(); } @Given("^I am in an empty directory$") public void I_am_in_an_empty_directory() throws Throwable { setUpDirectories(); assertEquals(0, currentDirectory.list().length); setupGeogit(); } @When("^I run the command \"([^\"]*)\"$") public void I_run_the_command_X(String commandSpec) throws Throwable { String[] args = commandSpec.split(" "); runCommand(args); } @Then("^it should answer \"([^\"]*)\"$") public void it_should_answer_exactly(String expected) throws Throwable { expected = expected.replace("${currentdir}", currentDirectory.getAbsolutePath()) .toLowerCase(); String actual = stdOut.toString().replaceAll("\n", "").trim().toLowerCase(); assertEquals(expected, actual); } @Then("^the response should contain \"([^\"]*)\"$") public void the_response_should_contain(String expected) throws Throwable { String actual = stdOut.toString().replaceAll("\n", ""); assertTrue(actual, actual.contains(expected)); } @Then("^the response should not contain \"([^\"]*)\"$") public void the_response_should_not_contain(String expected) throws Throwable { String actual = stdOut.toString().replaceAll("\n", ""); assertFalse(actual, actual.contains(expected)); } @Then("^the response should contain ([^\"]*) lines$") public void the_response_should_contain_x_lines(int lines) throws Throwable { String[] lineStrings = stdOut.toString().split("\n"); assertEquals(lines, lineStrings.length); } @Then("^the response should start with \"([^\"]*)\"$") public void the_response_should_start_with(String expected) throws Throwable { String actual = stdOut.toString().replaceAll("\n", ""); assertTrue(actual, actual.startsWith(expected)); } @Then("^the repository directory shall exist$") public void the_repository_directory_shall_exist() throws Throwable { List<String> output = runAndParseCommand("rev-parse", "--resolve-geogit-dir"); assertEquals(output.toString(), 1, output.size()); String location = output.get(0); assertNotNull(location); if (location.startsWith("Error:")) { fail(location); } File repoDir = new File(new URI(location)); assertTrue("Repository directory not found: " + repoDir.getAbsolutePath(), repoDir.exists()); } @Given("^I have a remote ref called \"([^\"]*)\"$") public void i_have_a_remote_ref_called(String expected) throws Throwable { String ref = "refs/remotes/origin/" + expected; geogit.command(UpdateRef.class).setName(ref).setNewValue(ObjectId.NULL).call(); Optional<Ref> refValue = geogit.command(RefParse.class).setName(ref).call(); assertTrue(refValue.isPresent()); assertEquals(refValue.get().getObjectId(), ObjectId.NULL); } @Given("^I have an unconfigured repository$") public void I_have_an_unconfigured_repository() throws Throwable { setUpDirectories(); setupGeogit(); List<String> output = runAndParseCommand("init"); assertEquals(output.toString(), 1, output.size()); assertNotNull(output.get(0)); assertTrue(output.get(0), output.get(0).startsWith("Initialized")); } @Given("^there is a remote repository$") public void there_is_a_remote_repository() throws Throwable { I_am_in_an_empty_directory(); GeoGIT oldGeogit = geogit; Injector oldInjector = geogitCLI.getGeogitInjector(); geogitCLI.setGeogitInjector(GlobalInjectorBuilder.builder.get()); List<String> output = runAndParseCommand("init", "remoterepo"); assertEquals(output.toString(), 1, output.size()); assertNotNull(output.get(0)); assertTrue(output.get(0), output.get(0).startsWith("Initialized")); geogit = geogitCLI.getGeogit(); + runCommand("config", "--global", "user.name", "John Doe"); + runCommand("config", "--global", "user.email", "[email protected]"); insertAndAdd(points1); runCommand(("commit -m Commit1").split(" ")); runCommand(("branch -c branch1").split(" ")); insertAndAdd(points2); runCommand(("commit -m Commit2").split(" ")); insertAndAdd(points3); runCommand(("commit -m Commit3").split(" ")); runCommand(("checkout master").split(" ")); insertAndAdd(lines1); runCommand(("commit -m Commit4").split(" ")); geogit.close(); geogit = oldGeogit; geogitCLI.setGeogit(oldGeogit); geogitCLI.setGeogitInjector(oldInjector); } @Given("^I have a repository$") public void I_have_a_repository() throws Throwable { I_have_an_unconfigured_repository(); runCommand("config", "--global", "user.name", "John Doe"); runCommand("config", "--global", "user.email", "[email protected]"); } @Given("^I have a repository with a remote$") public void I_have_a_repository_with_a_remote() throws Throwable { there_is_a_remote_repository(); List<String> output = runAndParseCommand("init", "localrepo"); assertEquals(output.toString(), 1, output.size()); assertNotNull(output.get(0)); assertTrue(output.get(0), output.get(0).startsWith("Initialized")); runCommand("config", "--global", "user.name", "John Doe"); runCommand("config", "--global", "user.email", "[email protected]"); runCommand("remote", "add", "origin", currentDirectory + "/remoterepo"); } private void setUpDirectories() throws IOException { homeDirectory = new File("target", "fakeHomeDir"); FileUtils.deleteDirectory(homeDirectory); assertFalse(homeDirectory.exists()); assertTrue(homeDirectory.mkdirs()); currentDirectory = new File("target", "testrepo"); FileUtils.deleteDirectory(currentDirectory); assertFalse(currentDirectory.exists()); assertTrue(currentDirectory.mkdirs()); } private void deleteDirectories() { try { FileUtils.deleteDirectory(homeDirectory); assertFalse(homeDirectory.exists()); FileUtils.deleteDirectory(currentDirectory); assertFalse(currentDirectory.exists()); } catch (IOException e) { } } @Given("^I have 6 unstaged features$") public void I_have_6_unstaged_features() throws Throwable { insertFeatures(); } @Given("^I stage 6 features$") public void I_stage_6_features() throws Throwable { insertAndAddFeatures(); } @Given("^I have several commits") public void I_have_several_commits() throws Throwable { insertAndAdd(points1); insertAndAdd(points2); runCommand(("commit -m Commit1").split(" ")); insertAndAdd(points3); insertAndAdd(lines1); runCommand(("commit -m Commit2").split(" ")); insertAndAdd(lines2); insertAndAdd(lines3); runCommand(("commit -m Commit3").split(" ")); insertAndAdd(points1_modified); runCommand(("commit -m Commit4").split(" ")); } @Given("^I have several branches") public void I_have_several_branches() throws Throwable { insertAndAdd(points1); runCommand(("commit -m Commit1").split(" ")); runCommand(("branch -c branch1").split(" ")); insertAndAdd(points2); runCommand(("commit -m Commit2").split(" ")); insertAndAdd(points3); runCommand(("commit -m Commit3").split(" ")); runCommand(("branch -c branch2").split(" ")); insertAndAdd(lines1); runCommand(("commit -m Commit4").split(" ")); runCommand(("checkout master").split(" ")); insertAndAdd(lines2); runCommand(("commit -m Commit5").split(" ")); } @Given("I modify and add a feature") public void I_modify_and_add_a_feature() throws Throwable { insertAndAdd(points1_modified); } @Given("I modify a feature") public void I_modify_a_feature() throws Throwable { insert(points1_modified); } @Then("^if I change to the respository subdirectory \"([^\"]*)\"$") public void if_I_change_to_the_respository_subdirectory(String subdirSpec) throws Throwable { String[] subdirs = subdirSpec.split("/"); File dir = currentDirectory; for (String subdir : subdirs) { dir = new File(dir, subdir); } assertTrue(dir.exists()); currentDirectory = dir; } @Given("^I am inside a repository subdirectory \"([^\"]*)\"$") public void I_am_inside_a_repository_subdirectory(String subdirSpec) throws Throwable { String[] subdirs = subdirSpec.split("/"); File dir = currentDirectory; for (String subdir : subdirs) { dir = new File(dir, subdir); } assertTrue(dir.mkdirs()); currentDirectory = dir; } }
true
true
public void there_is_a_remote_repository() throws Throwable { I_am_in_an_empty_directory(); GeoGIT oldGeogit = geogit; Injector oldInjector = geogitCLI.getGeogitInjector(); geogitCLI.setGeogitInjector(GlobalInjectorBuilder.builder.get()); List<String> output = runAndParseCommand("init", "remoterepo"); assertEquals(output.toString(), 1, output.size()); assertNotNull(output.get(0)); assertTrue(output.get(0), output.get(0).startsWith("Initialized")); geogit = geogitCLI.getGeogit(); insertAndAdd(points1); runCommand(("commit -m Commit1").split(" ")); runCommand(("branch -c branch1").split(" ")); insertAndAdd(points2); runCommand(("commit -m Commit2").split(" ")); insertAndAdd(points3); runCommand(("commit -m Commit3").split(" ")); runCommand(("checkout master").split(" ")); insertAndAdd(lines1); runCommand(("commit -m Commit4").split(" ")); geogit.close(); geogit = oldGeogit; geogitCLI.setGeogit(oldGeogit); geogitCLI.setGeogitInjector(oldInjector); }
public void there_is_a_remote_repository() throws Throwable { I_am_in_an_empty_directory(); GeoGIT oldGeogit = geogit; Injector oldInjector = geogitCLI.getGeogitInjector(); geogitCLI.setGeogitInjector(GlobalInjectorBuilder.builder.get()); List<String> output = runAndParseCommand("init", "remoterepo"); assertEquals(output.toString(), 1, output.size()); assertNotNull(output.get(0)); assertTrue(output.get(0), output.get(0).startsWith("Initialized")); geogit = geogitCLI.getGeogit(); runCommand("config", "--global", "user.name", "John Doe"); runCommand("config", "--global", "user.email", "[email protected]"); insertAndAdd(points1); runCommand(("commit -m Commit1").split(" ")); runCommand(("branch -c branch1").split(" ")); insertAndAdd(points2); runCommand(("commit -m Commit2").split(" ")); insertAndAdd(points3); runCommand(("commit -m Commit3").split(" ")); runCommand(("checkout master").split(" ")); insertAndAdd(lines1); runCommand(("commit -m Commit4").split(" ")); geogit.close(); geogit = oldGeogit; geogitCLI.setGeogit(oldGeogit); geogitCLI.setGeogitInjector(oldInjector); }
diff --git a/htroot/Crawler_p.java b/htroot/Crawler_p.java index a1013c263..70870670d 100644 --- a/htroot/Crawler_p.java +++ b/htroot/Crawler_p.java @@ -1,604 +1,604 @@ // Crawler_p.java // (C) 2006 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany // first published 18.12.2006 on http://www.anomic.de // this file was created using the an implementation from IndexCreate_p.java, published 02.12.2004 // // This is a part of YaCy, a peer-to-peer based web search engine // // $LastChangedDate$ // $LastChangedRevision$ // $LastChangedBy$ // // LICENSE // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA import java.io.File; import java.io.FileInputStream; import java.io.Writer; import java.net.MalformedURLException; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import net.yacy.cora.document.MultiProtocolURI; import net.yacy.cora.protocol.RequestHeader; import net.yacy.document.parser.html.ContentScraper; import net.yacy.document.parser.html.TransformerWriter; import net.yacy.kelondro.data.meta.DigestURI; import net.yacy.kelondro.logging.Log; import net.yacy.kelondro.util.FileUtils; import de.anomic.crawler.CrawlProfile; import de.anomic.crawler.SitemapImporter; import de.anomic.crawler.retrieval.Request; import de.anomic.data.BookmarkHelper; import de.anomic.data.WorkTables; import de.anomic.data.BookmarksDB; import de.anomic.data.ListManager; import de.anomic.search.Segment; import de.anomic.search.Segments; import de.anomic.search.Switchboard; import de.anomic.search.SwitchboardConstants; import de.anomic.server.serverObjects; import de.anomic.server.serverSwitch; import de.anomic.yacy.yacyNewsPool; public class Crawler_p { // this servlet does NOT create the Crawler servlet page content! // this servlet starts a web crawl. The interface for entering the web crawl parameters is in IndexCreate_p.html public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) { // return variable that accumulates replacements final Switchboard sb = (Switchboard) env; // inital values for AJAX Elements (without JavaScript) final serverObjects prop = new serverObjects(); prop.put("rejected", 0); prop.put("urlpublictextSize", 0); prop.put("rwipublictextSize", 0); prop.put("list", "0"); prop.put("loaderSize", 0); prop.put("loaderMax", 0); prop.put("list-loader", 0); prop.put("localCrawlSize", sb.crawlQueues.coreCrawlJobSize()); prop.put("localCrawlState", ""); prop.put("limitCrawlSize", sb.crawlQueues.limitCrawlJobSize()); prop.put("limitCrawlState", ""); prop.put("remoteCrawlSize", sb.crawlQueues.limitCrawlJobSize()); prop.put("remoteCrawlState", ""); prop.put("list-remote", 0); prop.put("forwardToCrawlStart", "0"); // get segment Segment indexSegment = null; if (post != null && post.containsKey("segment")) { String segmentName = post.get("segment"); if (sb.indexSegments.segmentExist(segmentName)) { indexSegment = sb.indexSegments.segment(segmentName); } } else { // take default segment indexSegment = sb.indexSegments.segment(Segments.Process.PUBLIC); } prop.put("info", "0"); if (post != null && post.containsKey("continue")) { // continue queue final String queue = post.get("continue", ""); if ("localcrawler".equals(queue)) { sb.continueCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); } else if ("remotecrawler".equals(queue)) { sb.continueCrawlJob(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL); } } if (post != null && post.containsKey("pause")) { // pause queue final String queue = post.get("pause", ""); if ("localcrawler".equals(queue)) { sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); } else if ("remotecrawler".equals(queue)) { sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL); } } if (post != null && post.containsKey("crawlingstart")) { // init crawl if (sb.peers == null) { prop.put("info", "3"); } else { String crawlingStart = post.get("crawlingURL","").trim(); // the crawljob start url // add the prefix http:// if necessary int pos = crawlingStart.indexOf("://"); if (pos == -1) { if (crawlingStart.startsWith("www")) crawlingStart = "http://" + crawlingStart; if (crawlingStart.startsWith("ftp")) crawlingStart = "ftp://" + crawlingStart; } // normalize URL DigestURI crawlingStartURL = null; try {crawlingStartURL = new DigestURI(crawlingStart);} catch (final MalformedURLException e1) {} crawlingStart = (crawlingStartURL == null) ? null : crawlingStartURL.toNormalform(true, true); // set new properties final boolean fullDomain = "domain".equals(post.get("range", "wide")); // special property in simple crawl start final boolean subPath = "subpath".equals(post.get("range", "wide")); // special property in simple crawl start // set the crawl filter String newcrawlingMustMatch = post.get("mustmatch", CrawlProfile.MATCH_ALL); String newcrawlingMustNotMatch = post.get("mustnotmatch", CrawlProfile.MATCH_NEVER); if (newcrawlingMustMatch.length() < 2) newcrawlingMustMatch = CrawlProfile.MATCH_ALL; // avoid that all urls are filtered out if bad value was submitted // special cases: if (crawlingStartURL!= null && fullDomain) { if (crawlingStartURL.isFile()) { newcrawlingMustMatch = "file://" + crawlingStartURL.getPath() + ".*"; } else if (crawlingStartURL.isSMB()) { newcrawlingMustMatch = "smb://.*" + crawlingStartURL.getHost() + ".*" + crawlingStartURL.getPath() + ".*"; } else if (crawlingStartURL.isFTP()) { newcrawlingMustMatch = "ftp://.*" + crawlingStartURL.getHost() + ".*" + crawlingStartURL.getPath() + ".*"; } else { newcrawlingMustMatch = ".*" + crawlingStartURL.getHost() + ".*"; } } if (crawlingStart!= null && subPath && (pos = crawlingStart.lastIndexOf('/')) > 0) { newcrawlingMustMatch = crawlingStart.substring(0, pos + 1) + ".*"; } final boolean crawlOrder = post.get("crawlOrder", "off").equals("on"); env.setConfig("crawlOrder", crawlOrder); int newcrawlingdepth = post.getInt("crawlingDepth", 8); env.setConfig("crawlingDepth", Integer.toString(newcrawlingdepth)); if ((crawlOrder) && (newcrawlingdepth > 8)) newcrawlingdepth = 8; // recrawl final String recrawl = post.get("recrawl", "nodoubles"); // nodoubles, reload, scheduler boolean crawlingIfOlderCheck = "on".equals(post.get("crawlingIfOlderCheck", "off")); int crawlingIfOlderNumber = post.getInt("crawlingIfOlderNumber", -1); String crawlingIfOlderUnit = post.get("crawlingIfOlderUnit","year"); // year, month, day, hour int repeat_time = post.getInt("repeat_time", -1); final String repeat_unit = post.get("repeat_unit", "seldays"); // selminutes, selhours, seldays if ("scheduler".equals(recrawl) && repeat_time > 0) { // set crawlingIfOlder attributes that are appropriate for scheduled crawling crawlingIfOlderCheck = true; crawlingIfOlderNumber = "selminutes".equals(repeat_unit) ? 1 : "selhours".equals(repeat_unit) ? repeat_time / 2 : repeat_time * 12; crawlingIfOlderUnit = "hour"; } else if ("reload".equals(recrawl)) { repeat_time = -1; crawlingIfOlderCheck = true; } else if ("nodoubles".equals(recrawl)) { repeat_time = -1; crawlingIfOlderCheck = false; } long crawlingIfOlder = recrawlIfOlderC(crawlingIfOlderCheck, crawlingIfOlderNumber, crawlingIfOlderUnit); env.setConfig("crawlingIfOlder", crawlingIfOlder); // remove crawlingFileContent before we record the call final String crawlingFileName = post.get("crawlingFile"); final File crawlingFile = (crawlingFileName != null && crawlingFileName.length() > 0) ? new File(crawlingFileName) : null; if (crawlingFile != null && crawlingFile.exists()) { post.remove("crawlingFile$file"); } // store this call as api call if (repeat_time > 0) { // store as scheduled api call sb.tables.recordAPICall(post, "Crawler_p.html", WorkTables.TABLE_API_TYPE_CRAWLER, "crawl start for " + ((crawlingStart == null) ? post.get("crawlingFile", "") : crawlingStart), repeat_time, repeat_unit.substring(3)); } else { // store just a protocol sb.tables.recordAPICall(post, "Crawler_p.html", WorkTables.TABLE_API_TYPE_CRAWLER, "crawl start for " + ((crawlingStart == null) ? post.get("crawlingFile", "") : crawlingStart)); } final boolean crawlingDomMaxCheck = "on".equals(post.get("crawlingDomMaxCheck", "off")); final int crawlingDomMaxPages = (crawlingDomMaxCheck) ? post.getInt("crawlingDomMaxPages", -1) : -1; env.setConfig("crawlingDomMaxPages", Integer.toString(crawlingDomMaxPages)); final boolean crawlingQ = "on".equals(post.get("crawlingQ", "off")); env.setConfig("crawlingQ", crawlingQ); final boolean indexText = "on".equals(post.get("indexText", "on")); env.setConfig("indexText", indexText); final boolean indexMedia = "on".equals(post.get("indexMedia", "on")); env.setConfig("indexMedia", indexMedia); boolean storeHTCache = "on".equals(post.get("storeHTCache", "on")); if (crawlingStartURL!= null &&(crawlingStartURL.isFile() || crawlingStartURL.isSMB())) storeHTCache = false; env.setConfig("storeHTCache", storeHTCache); CrawlProfile.CacheStrategy cachePolicy = CrawlProfile.CacheStrategy.parse(post.get("cachePolicy", "iffresh")); if (cachePolicy == null) cachePolicy = CrawlProfile.CacheStrategy.IFFRESH; final boolean xsstopw = "on".equals(post.get("xsstopw", "off")); env.setConfig("xsstopw", xsstopw); final boolean xdstopw = "on".equals(post.get("xdstopw", "off")); env.setConfig("xdstopw", xdstopw); final boolean xpstopw = "on".equals(post.get("xpstopw", "off")); env.setConfig("xpstopw", xpstopw); final String crawlingMode = post.get("crawlingMode","url"); if (crawlingStart != null && crawlingStart.startsWith("ftp")) { try { // check if the crawl filter works correctly Pattern.compile(newcrawlingMustMatch); final CrawlProfile profile = new CrawlProfile( crawlingStart, crawlingStartURL, newcrawlingMustMatch, CrawlProfile.MATCH_NEVER, newcrawlingdepth, crawlingIfOlder, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(profile.handle().getBytes(), profile); sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); final DigestURI url = crawlingStartURL; sb.crawlStacker.enqueueEntriesFTP(sb.peers.mySeed().hash.getBytes(), profile.handle(), url.getHost(), url.getPort(), false); } catch (final PatternSyntaxException e) { prop.put("info", "4"); // crawlfilter does not match url prop.putHTML("info_newcrawlingfilter", newcrawlingMustMatch); prop.putHTML("info_error", e.getMessage()); } catch (final Exception e) { // mist prop.put("info", "7"); // Error with file prop.putHTML("info_crawlingStart", crawlingStart); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } sb.continueCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); } else if ("url".equals(crawlingMode)) { // check if pattern matches if ((crawlingStart == null || crawlingStartURL == null) /* || (!(crawlingStart.matches(newcrawlingfilter))) */) { // print error message prop.put("info", "4"); //crawlfilter does not match url prop.putHTML("info_newcrawlingfilter", newcrawlingMustMatch); prop.putHTML("info_crawlingStart", crawlingStart); } else try { // check if the crawl filter works correctly Pattern.compile(newcrawlingMustMatch); // stack request // first delete old entry, if exists final DigestURI url = new DigestURI(crawlingStart); final byte[] urlhash = url.hash(); indexSegment.urlMetadata().remove(urlhash); sb.crawlQueues.noticeURL.removeByURLHash(urlhash); sb.crawlQueues.errorURL.remove(urlhash); // stack url sb.crawler.removePassive(crawlingStartURL.hash()); // if there is an old entry, delete it final CrawlProfile pe = new CrawlProfile( (crawlingStartURL.getHost() == null) ? crawlingStartURL.toNormalform(true, false) : crawlingStartURL.getHost(), crawlingStartURL, newcrawlingMustMatch, newcrawlingMustNotMatch, newcrawlingdepth, crawlingIfOlder, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(pe.handle().getBytes(), pe); final String reasonString = sb.crawlStacker.stackCrawl(new Request( sb.peers.mySeed().hash.getBytes(), url, null, "CRAWLING-ROOT", new Date(), pe.handle(), 0, 0, 0, 0 )); if (reasonString == null) { // create a bookmark from crawl start url Set<String> tags=ListManager.string2set(BookmarkHelper.cleanTagsString(post.get("bookmarkFolder","/crawlStart"))); tags.add("crawlStart"); if ("on".equals(post.get("createBookmark","off"))) { BookmarksDB.Bookmark bookmark = sb.bookmarksDB.createBookmark(crawlingStart, "admin"); if (bookmark != null) { bookmark.setProperty(BookmarksDB.Bookmark.BOOKMARK_TITLE, post.get("bookmarkTitle", crawlingStart)); bookmark.setOwner("admin"); bookmark.setPublic(false); bookmark.setTags(tags, true); sb.bookmarksDB.saveBookmark(bookmark); } } // liftoff! prop.put("info", "8");//start msg prop.putHTML("info_crawlingURL", (post.get("crawlingURL"))); // generate a YaCyNews if the global flag was set if (!sb.isRobinsonMode() && crawlOrder) { final Map<String, String> m = new HashMap<String, String>(pe); // must be cloned m.remove("specificDepth"); m.remove("indexText"); m.remove("indexMedia"); m.remove("remoteIndexing"); m.remove("xsstopw"); m.remove("xpstopw"); m.remove("xdstopw"); m.remove("storeTXCache"); m.remove("storeHTCache"); m.remove("generalFilter"); m.remove("specificFilter"); m.put("intention", post.get("intention", "").replace(',', '/')); sb.peers.newsPool.publishMyNews(sb.peers.mySeed(), yacyNewsPool.CATEGORY_CRAWL_START, m); } } else { prop.put("info", "5"); //Crawling failed prop.putHTML("info_crawlingURL", (post.get("crawlingURL"))); prop.putHTML("info_reasonString", reasonString); sb.crawlQueues.errorURL.push( new Request( sb.peers.mySeed().hash.getBytes(), crawlingStartURL, null, "", new Date(), pe.handle(), 0, 0, 0, 0), sb.peers.mySeed().hash.getBytes(), new Date(), 1, reasonString); } } catch (final PatternSyntaxException e) { prop.put("info", "4"); // crawlfilter does not match url prop.putHTML("info_newcrawlingfilter", newcrawlingMustMatch); prop.putHTML("info_error", e.getMessage()); } catch (final Exception e) { // mist prop.put("info", "6"); // Error with url prop.putHTML("info_crawlingStart", crawlingStart); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } } else if ("file".equals(crawlingMode)) { if (post.containsKey("crawlingFile")) { final String crawlingFileContent = post.get("crawlingFile$file", ""); try { // check if the crawl filter works correctly Pattern.compile(newcrawlingMustMatch); final ContentScraper scraper = new ContentScraper(new DigestURI(crawlingFile)); final Writer writer = new TransformerWriter(null, null, scraper, null, false); if (crawlingFile != null && crawlingFile.exists()) { FileUtils.copy(new FileInputStream(crawlingFile), writer); } else { FileUtils.copy(crawlingFileContent, writer); } writer.close(); // get links and generate filter final Map<MultiProtocolURI, String> hyperlinks = scraper.getAnchors(); - if (fullDomain) newcrawlingMustMatch = siteFilter(hyperlinks.keySet()); + if (fullDomain && newcrawlingdepth > 0) newcrawlingMustMatch = siteFilter(hyperlinks.keySet()); final DigestURI crawlURL = new DigestURI("file://" + crawlingFile.toString()); final CrawlProfile profile = new CrawlProfile( crawlingFileName, crawlURL, newcrawlingMustMatch, CrawlProfile.MATCH_NEVER, newcrawlingdepth, crawlingIfOlder, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(profile.handle().getBytes(), profile); sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); sb.crawlStacker.enqueueEntries(sb.peers.mySeed().hash.getBytes(), profile.handle(), hyperlinks, true); } catch (final PatternSyntaxException e) { prop.put("info", "4"); // crawlfilter does not match url prop.putHTML("info_newcrawlingfilter", newcrawlingMustMatch); prop.putHTML("info_error", e.getMessage()); } catch (final Exception e) { // mist prop.put("info", "7"); // Error with file prop.putHTML("info_crawlingStart", crawlingFileName); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } sb.continueCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); } } else if ("sitemap".equals(crawlingMode)) { String sitemapURLStr = post.get("sitemapURL",""); try { final DigestURI sitemapURL = new DigestURI(sitemapURLStr); final CrawlProfile pe = new CrawlProfile( sitemapURLStr, sitemapURL, CrawlProfile.MATCH_ALL, CrawlProfile.MATCH_NEVER, 0, crawlingIfOlder, crawlingDomMaxPages, true, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(pe.handle().getBytes(), pe); final SitemapImporter importer = new SitemapImporter(sb, sitemapURL, pe); importer.start(); } catch (final Exception e) { // mist prop.put("info", "6");//Error with url prop.putHTML("info_crawlingStart", sitemapURLStr); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } } else if ("sitelist".equals(crawlingMode)) { try { final DigestURI sitelistURL = new DigestURI(crawlingStart); // download document ContentScraper scraper = null; scraper = sb.loader.parseResource(sitelistURL, CrawlProfile.CacheStrategy.IFFRESH); // String title = scraper.getTitle(); // String description = scraper.getDescription(); // get links and generate filter final Map<MultiProtocolURI, String> hyperlinks = scraper.getAnchors(); - if (fullDomain) newcrawlingMustMatch = siteFilter(hyperlinks.keySet()); + if (fullDomain && newcrawlingdepth > 0) newcrawlingMustMatch = siteFilter(hyperlinks.keySet()); // put links onto crawl queue final CrawlProfile profile = new CrawlProfile( sitelistURL.getHost(), sitelistURL, newcrawlingMustMatch, CrawlProfile.MATCH_NEVER, newcrawlingdepth, crawlingIfOlder, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(profile.handle().getBytes(), profile); sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); final Iterator<Map.Entry<MultiProtocolURI, String>> linkiterator = hyperlinks.entrySet().iterator(); DigestURI nexturl; while (linkiterator.hasNext()) { final Map.Entry<MultiProtocolURI, String> e = linkiterator.next(); if (e.getKey() == null) continue; nexturl = new DigestURI(e.getKey()); // remove the url from the database to be prepared to crawl them again final byte[] urlhash = nexturl.hash(); indexSegment.urlMetadata().remove(urlhash); sb.crawlQueues.noticeURL.removeByURLHash(urlhash); sb.crawlQueues.errorURL.remove(urlhash); sb.crawlStacker.enqueueEntry(new Request( sb.peers.mySeed().hash.getBytes(), nexturl, null, e.getValue(), new Date(), profile.handle(), 0, 0, 0, 0 )); } } catch (final Exception e) { // mist prop.put("info", "6");//Error with url prop.putHTML("info_crawlingStart", crawlingStart); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } } } } if (post != null && post.containsKey("crawlingPerformance")) { setPerformance(sb, post); } // performance settings final long LCbusySleep = env.getConfigLong(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, 1000L); final int LCppm = (int) (60000L / Math.max(1,LCbusySleep)); prop.put("crawlingSpeedMaxChecked", (LCppm >= 30000) ? "1" : "0"); prop.put("crawlingSpeedCustChecked", ((LCppm > 10) && (LCppm < 30000)) ? "1" : "0"); prop.put("crawlingSpeedMinChecked", (LCppm <= 10) ? "1" : "0"); prop.put("customPPMdefault", Integer.toString(LCppm)); // return rewrite properties return prop; } private static long recrawlIfOlderC(final boolean recrawlIfOlderCheck, final int recrawlIfOlderNumber, final String crawlingIfOlderUnit) { if (!recrawlIfOlderCheck) return 0L; if ("year".equals(crawlingIfOlderUnit)) return System.currentTimeMillis() - (long) recrawlIfOlderNumber * 1000L * 60L * 60L * 24L * 365L; if ("month".equals(crawlingIfOlderUnit)) return System.currentTimeMillis() - (long) recrawlIfOlderNumber * 1000L * 60L * 60L * 24L * 30L; if ("day".equals(crawlingIfOlderUnit)) return System.currentTimeMillis() - (long) recrawlIfOlderNumber * 1000L * 60L * 60L * 24L; if ("hour".equals(crawlingIfOlderUnit)) return System.currentTimeMillis() - (long) recrawlIfOlderNumber * 1000L * 60L * 60L; return System.currentTimeMillis() - (long) recrawlIfOlderNumber; } private static void setPerformance(final Switchboard sb, final serverObjects post) { final String crawlingPerformance = post.get("crawlingPerformance", "custom"); final long LCbusySleep = sb.getConfigLong(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, 1000L); int wantedPPM = (LCbusySleep == 0) ? 30000 : (int) (60000L / LCbusySleep); try { wantedPPM = post.getInt("customPPM", wantedPPM); } catch (final NumberFormatException e) {} if ("minimum".equals(crawlingPerformance.toLowerCase())) wantedPPM = 10; if ("maximum".equals(crawlingPerformance.toLowerCase())) wantedPPM = 30000; sb.setPerformance(wantedPPM); } private static String siteFilter(Set<MultiProtocolURI> uris) { final StringBuilder filter = new StringBuilder(); final Set<String> filterSet = new HashSet<String>(); for (final MultiProtocolURI uri: uris) { filterSet.add(new StringBuilder().append(uri.getProtocol()).append("://").append(uri.getHost()).append(".*").toString()); if (!uri.getHost().startsWith("www.")) { filterSet.add(new StringBuilder().append(uri.getProtocol()).append("://www.").append(uri.getHost()).append(".*").toString()); } } for (final String element : filterSet) { filter.append('|').append(element); } return filter.length() > 0 ? filter.substring(1) : ""; } }
false
true
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) { // return variable that accumulates replacements final Switchboard sb = (Switchboard) env; // inital values for AJAX Elements (without JavaScript) final serverObjects prop = new serverObjects(); prop.put("rejected", 0); prop.put("urlpublictextSize", 0); prop.put("rwipublictextSize", 0); prop.put("list", "0"); prop.put("loaderSize", 0); prop.put("loaderMax", 0); prop.put("list-loader", 0); prop.put("localCrawlSize", sb.crawlQueues.coreCrawlJobSize()); prop.put("localCrawlState", ""); prop.put("limitCrawlSize", sb.crawlQueues.limitCrawlJobSize()); prop.put("limitCrawlState", ""); prop.put("remoteCrawlSize", sb.crawlQueues.limitCrawlJobSize()); prop.put("remoteCrawlState", ""); prop.put("list-remote", 0); prop.put("forwardToCrawlStart", "0"); // get segment Segment indexSegment = null; if (post != null && post.containsKey("segment")) { String segmentName = post.get("segment"); if (sb.indexSegments.segmentExist(segmentName)) { indexSegment = sb.indexSegments.segment(segmentName); } } else { // take default segment indexSegment = sb.indexSegments.segment(Segments.Process.PUBLIC); } prop.put("info", "0"); if (post != null && post.containsKey("continue")) { // continue queue final String queue = post.get("continue", ""); if ("localcrawler".equals(queue)) { sb.continueCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); } else if ("remotecrawler".equals(queue)) { sb.continueCrawlJob(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL); } } if (post != null && post.containsKey("pause")) { // pause queue final String queue = post.get("pause", ""); if ("localcrawler".equals(queue)) { sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); } else if ("remotecrawler".equals(queue)) { sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL); } } if (post != null && post.containsKey("crawlingstart")) { // init crawl if (sb.peers == null) { prop.put("info", "3"); } else { String crawlingStart = post.get("crawlingURL","").trim(); // the crawljob start url // add the prefix http:// if necessary int pos = crawlingStart.indexOf("://"); if (pos == -1) { if (crawlingStart.startsWith("www")) crawlingStart = "http://" + crawlingStart; if (crawlingStart.startsWith("ftp")) crawlingStart = "ftp://" + crawlingStart; } // normalize URL DigestURI crawlingStartURL = null; try {crawlingStartURL = new DigestURI(crawlingStart);} catch (final MalformedURLException e1) {} crawlingStart = (crawlingStartURL == null) ? null : crawlingStartURL.toNormalform(true, true); // set new properties final boolean fullDomain = "domain".equals(post.get("range", "wide")); // special property in simple crawl start final boolean subPath = "subpath".equals(post.get("range", "wide")); // special property in simple crawl start // set the crawl filter String newcrawlingMustMatch = post.get("mustmatch", CrawlProfile.MATCH_ALL); String newcrawlingMustNotMatch = post.get("mustnotmatch", CrawlProfile.MATCH_NEVER); if (newcrawlingMustMatch.length() < 2) newcrawlingMustMatch = CrawlProfile.MATCH_ALL; // avoid that all urls are filtered out if bad value was submitted // special cases: if (crawlingStartURL!= null && fullDomain) { if (crawlingStartURL.isFile()) { newcrawlingMustMatch = "file://" + crawlingStartURL.getPath() + ".*"; } else if (crawlingStartURL.isSMB()) { newcrawlingMustMatch = "smb://.*" + crawlingStartURL.getHost() + ".*" + crawlingStartURL.getPath() + ".*"; } else if (crawlingStartURL.isFTP()) { newcrawlingMustMatch = "ftp://.*" + crawlingStartURL.getHost() + ".*" + crawlingStartURL.getPath() + ".*"; } else { newcrawlingMustMatch = ".*" + crawlingStartURL.getHost() + ".*"; } } if (crawlingStart!= null && subPath && (pos = crawlingStart.lastIndexOf('/')) > 0) { newcrawlingMustMatch = crawlingStart.substring(0, pos + 1) + ".*"; } final boolean crawlOrder = post.get("crawlOrder", "off").equals("on"); env.setConfig("crawlOrder", crawlOrder); int newcrawlingdepth = post.getInt("crawlingDepth", 8); env.setConfig("crawlingDepth", Integer.toString(newcrawlingdepth)); if ((crawlOrder) && (newcrawlingdepth > 8)) newcrawlingdepth = 8; // recrawl final String recrawl = post.get("recrawl", "nodoubles"); // nodoubles, reload, scheduler boolean crawlingIfOlderCheck = "on".equals(post.get("crawlingIfOlderCheck", "off")); int crawlingIfOlderNumber = post.getInt("crawlingIfOlderNumber", -1); String crawlingIfOlderUnit = post.get("crawlingIfOlderUnit","year"); // year, month, day, hour int repeat_time = post.getInt("repeat_time", -1); final String repeat_unit = post.get("repeat_unit", "seldays"); // selminutes, selhours, seldays if ("scheduler".equals(recrawl) && repeat_time > 0) { // set crawlingIfOlder attributes that are appropriate for scheduled crawling crawlingIfOlderCheck = true; crawlingIfOlderNumber = "selminutes".equals(repeat_unit) ? 1 : "selhours".equals(repeat_unit) ? repeat_time / 2 : repeat_time * 12; crawlingIfOlderUnit = "hour"; } else if ("reload".equals(recrawl)) { repeat_time = -1; crawlingIfOlderCheck = true; } else if ("nodoubles".equals(recrawl)) { repeat_time = -1; crawlingIfOlderCheck = false; } long crawlingIfOlder = recrawlIfOlderC(crawlingIfOlderCheck, crawlingIfOlderNumber, crawlingIfOlderUnit); env.setConfig("crawlingIfOlder", crawlingIfOlder); // remove crawlingFileContent before we record the call final String crawlingFileName = post.get("crawlingFile"); final File crawlingFile = (crawlingFileName != null && crawlingFileName.length() > 0) ? new File(crawlingFileName) : null; if (crawlingFile != null && crawlingFile.exists()) { post.remove("crawlingFile$file"); } // store this call as api call if (repeat_time > 0) { // store as scheduled api call sb.tables.recordAPICall(post, "Crawler_p.html", WorkTables.TABLE_API_TYPE_CRAWLER, "crawl start for " + ((crawlingStart == null) ? post.get("crawlingFile", "") : crawlingStart), repeat_time, repeat_unit.substring(3)); } else { // store just a protocol sb.tables.recordAPICall(post, "Crawler_p.html", WorkTables.TABLE_API_TYPE_CRAWLER, "crawl start for " + ((crawlingStart == null) ? post.get("crawlingFile", "") : crawlingStart)); } final boolean crawlingDomMaxCheck = "on".equals(post.get("crawlingDomMaxCheck", "off")); final int crawlingDomMaxPages = (crawlingDomMaxCheck) ? post.getInt("crawlingDomMaxPages", -1) : -1; env.setConfig("crawlingDomMaxPages", Integer.toString(crawlingDomMaxPages)); final boolean crawlingQ = "on".equals(post.get("crawlingQ", "off")); env.setConfig("crawlingQ", crawlingQ); final boolean indexText = "on".equals(post.get("indexText", "on")); env.setConfig("indexText", indexText); final boolean indexMedia = "on".equals(post.get("indexMedia", "on")); env.setConfig("indexMedia", indexMedia); boolean storeHTCache = "on".equals(post.get("storeHTCache", "on")); if (crawlingStartURL!= null &&(crawlingStartURL.isFile() || crawlingStartURL.isSMB())) storeHTCache = false; env.setConfig("storeHTCache", storeHTCache); CrawlProfile.CacheStrategy cachePolicy = CrawlProfile.CacheStrategy.parse(post.get("cachePolicy", "iffresh")); if (cachePolicy == null) cachePolicy = CrawlProfile.CacheStrategy.IFFRESH; final boolean xsstopw = "on".equals(post.get("xsstopw", "off")); env.setConfig("xsstopw", xsstopw); final boolean xdstopw = "on".equals(post.get("xdstopw", "off")); env.setConfig("xdstopw", xdstopw); final boolean xpstopw = "on".equals(post.get("xpstopw", "off")); env.setConfig("xpstopw", xpstopw); final String crawlingMode = post.get("crawlingMode","url"); if (crawlingStart != null && crawlingStart.startsWith("ftp")) { try { // check if the crawl filter works correctly Pattern.compile(newcrawlingMustMatch); final CrawlProfile profile = new CrawlProfile( crawlingStart, crawlingStartURL, newcrawlingMustMatch, CrawlProfile.MATCH_NEVER, newcrawlingdepth, crawlingIfOlder, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(profile.handle().getBytes(), profile); sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); final DigestURI url = crawlingStartURL; sb.crawlStacker.enqueueEntriesFTP(sb.peers.mySeed().hash.getBytes(), profile.handle(), url.getHost(), url.getPort(), false); } catch (final PatternSyntaxException e) { prop.put("info", "4"); // crawlfilter does not match url prop.putHTML("info_newcrawlingfilter", newcrawlingMustMatch); prop.putHTML("info_error", e.getMessage()); } catch (final Exception e) { // mist prop.put("info", "7"); // Error with file prop.putHTML("info_crawlingStart", crawlingStart); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } sb.continueCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); } else if ("url".equals(crawlingMode)) { // check if pattern matches if ((crawlingStart == null || crawlingStartURL == null) /* || (!(crawlingStart.matches(newcrawlingfilter))) */) { // print error message prop.put("info", "4"); //crawlfilter does not match url prop.putHTML("info_newcrawlingfilter", newcrawlingMustMatch); prop.putHTML("info_crawlingStart", crawlingStart); } else try { // check if the crawl filter works correctly Pattern.compile(newcrawlingMustMatch); // stack request // first delete old entry, if exists final DigestURI url = new DigestURI(crawlingStart); final byte[] urlhash = url.hash(); indexSegment.urlMetadata().remove(urlhash); sb.crawlQueues.noticeURL.removeByURLHash(urlhash); sb.crawlQueues.errorURL.remove(urlhash); // stack url sb.crawler.removePassive(crawlingStartURL.hash()); // if there is an old entry, delete it final CrawlProfile pe = new CrawlProfile( (crawlingStartURL.getHost() == null) ? crawlingStartURL.toNormalform(true, false) : crawlingStartURL.getHost(), crawlingStartURL, newcrawlingMustMatch, newcrawlingMustNotMatch, newcrawlingdepth, crawlingIfOlder, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(pe.handle().getBytes(), pe); final String reasonString = sb.crawlStacker.stackCrawl(new Request( sb.peers.mySeed().hash.getBytes(), url, null, "CRAWLING-ROOT", new Date(), pe.handle(), 0, 0, 0, 0 )); if (reasonString == null) { // create a bookmark from crawl start url Set<String> tags=ListManager.string2set(BookmarkHelper.cleanTagsString(post.get("bookmarkFolder","/crawlStart"))); tags.add("crawlStart"); if ("on".equals(post.get("createBookmark","off"))) { BookmarksDB.Bookmark bookmark = sb.bookmarksDB.createBookmark(crawlingStart, "admin"); if (bookmark != null) { bookmark.setProperty(BookmarksDB.Bookmark.BOOKMARK_TITLE, post.get("bookmarkTitle", crawlingStart)); bookmark.setOwner("admin"); bookmark.setPublic(false); bookmark.setTags(tags, true); sb.bookmarksDB.saveBookmark(bookmark); } } // liftoff! prop.put("info", "8");//start msg prop.putHTML("info_crawlingURL", (post.get("crawlingURL"))); // generate a YaCyNews if the global flag was set if (!sb.isRobinsonMode() && crawlOrder) { final Map<String, String> m = new HashMap<String, String>(pe); // must be cloned m.remove("specificDepth"); m.remove("indexText"); m.remove("indexMedia"); m.remove("remoteIndexing"); m.remove("xsstopw"); m.remove("xpstopw"); m.remove("xdstopw"); m.remove("storeTXCache"); m.remove("storeHTCache"); m.remove("generalFilter"); m.remove("specificFilter"); m.put("intention", post.get("intention", "").replace(',', '/')); sb.peers.newsPool.publishMyNews(sb.peers.mySeed(), yacyNewsPool.CATEGORY_CRAWL_START, m); } } else { prop.put("info", "5"); //Crawling failed prop.putHTML("info_crawlingURL", (post.get("crawlingURL"))); prop.putHTML("info_reasonString", reasonString); sb.crawlQueues.errorURL.push( new Request( sb.peers.mySeed().hash.getBytes(), crawlingStartURL, null, "", new Date(), pe.handle(), 0, 0, 0, 0), sb.peers.mySeed().hash.getBytes(), new Date(), 1, reasonString); } } catch (final PatternSyntaxException e) { prop.put("info", "4"); // crawlfilter does not match url prop.putHTML("info_newcrawlingfilter", newcrawlingMustMatch); prop.putHTML("info_error", e.getMessage()); } catch (final Exception e) { // mist prop.put("info", "6"); // Error with url prop.putHTML("info_crawlingStart", crawlingStart); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } } else if ("file".equals(crawlingMode)) { if (post.containsKey("crawlingFile")) { final String crawlingFileContent = post.get("crawlingFile$file", ""); try { // check if the crawl filter works correctly Pattern.compile(newcrawlingMustMatch); final ContentScraper scraper = new ContentScraper(new DigestURI(crawlingFile)); final Writer writer = new TransformerWriter(null, null, scraper, null, false); if (crawlingFile != null && crawlingFile.exists()) { FileUtils.copy(new FileInputStream(crawlingFile), writer); } else { FileUtils.copy(crawlingFileContent, writer); } writer.close(); // get links and generate filter final Map<MultiProtocolURI, String> hyperlinks = scraper.getAnchors(); if (fullDomain) newcrawlingMustMatch = siteFilter(hyperlinks.keySet()); final DigestURI crawlURL = new DigestURI("file://" + crawlingFile.toString()); final CrawlProfile profile = new CrawlProfile( crawlingFileName, crawlURL, newcrawlingMustMatch, CrawlProfile.MATCH_NEVER, newcrawlingdepth, crawlingIfOlder, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(profile.handle().getBytes(), profile); sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); sb.crawlStacker.enqueueEntries(sb.peers.mySeed().hash.getBytes(), profile.handle(), hyperlinks, true); } catch (final PatternSyntaxException e) { prop.put("info", "4"); // crawlfilter does not match url prop.putHTML("info_newcrawlingfilter", newcrawlingMustMatch); prop.putHTML("info_error", e.getMessage()); } catch (final Exception e) { // mist prop.put("info", "7"); // Error with file prop.putHTML("info_crawlingStart", crawlingFileName); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } sb.continueCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); } } else if ("sitemap".equals(crawlingMode)) { String sitemapURLStr = post.get("sitemapURL",""); try { final DigestURI sitemapURL = new DigestURI(sitemapURLStr); final CrawlProfile pe = new CrawlProfile( sitemapURLStr, sitemapURL, CrawlProfile.MATCH_ALL, CrawlProfile.MATCH_NEVER, 0, crawlingIfOlder, crawlingDomMaxPages, true, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(pe.handle().getBytes(), pe); final SitemapImporter importer = new SitemapImporter(sb, sitemapURL, pe); importer.start(); } catch (final Exception e) { // mist prop.put("info", "6");//Error with url prop.putHTML("info_crawlingStart", sitemapURLStr); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } } else if ("sitelist".equals(crawlingMode)) { try { final DigestURI sitelistURL = new DigestURI(crawlingStart); // download document ContentScraper scraper = null; scraper = sb.loader.parseResource(sitelistURL, CrawlProfile.CacheStrategy.IFFRESH); // String title = scraper.getTitle(); // String description = scraper.getDescription(); // get links and generate filter final Map<MultiProtocolURI, String> hyperlinks = scraper.getAnchors(); if (fullDomain) newcrawlingMustMatch = siteFilter(hyperlinks.keySet()); // put links onto crawl queue final CrawlProfile profile = new CrawlProfile( sitelistURL.getHost(), sitelistURL, newcrawlingMustMatch, CrawlProfile.MATCH_NEVER, newcrawlingdepth, crawlingIfOlder, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(profile.handle().getBytes(), profile); sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); final Iterator<Map.Entry<MultiProtocolURI, String>> linkiterator = hyperlinks.entrySet().iterator(); DigestURI nexturl; while (linkiterator.hasNext()) { final Map.Entry<MultiProtocolURI, String> e = linkiterator.next(); if (e.getKey() == null) continue; nexturl = new DigestURI(e.getKey()); // remove the url from the database to be prepared to crawl them again final byte[] urlhash = nexturl.hash(); indexSegment.urlMetadata().remove(urlhash); sb.crawlQueues.noticeURL.removeByURLHash(urlhash); sb.crawlQueues.errorURL.remove(urlhash); sb.crawlStacker.enqueueEntry(new Request( sb.peers.mySeed().hash.getBytes(), nexturl, null, e.getValue(), new Date(), profile.handle(), 0, 0, 0, 0 )); } } catch (final Exception e) { // mist prop.put("info", "6");//Error with url prop.putHTML("info_crawlingStart", crawlingStart); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } } } } if (post != null && post.containsKey("crawlingPerformance")) { setPerformance(sb, post); } // performance settings final long LCbusySleep = env.getConfigLong(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, 1000L); final int LCppm = (int) (60000L / Math.max(1,LCbusySleep)); prop.put("crawlingSpeedMaxChecked", (LCppm >= 30000) ? "1" : "0"); prop.put("crawlingSpeedCustChecked", ((LCppm > 10) && (LCppm < 30000)) ? "1" : "0"); prop.put("crawlingSpeedMinChecked", (LCppm <= 10) ? "1" : "0"); prop.put("customPPMdefault", Integer.toString(LCppm)); // return rewrite properties return prop; }
public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) { // return variable that accumulates replacements final Switchboard sb = (Switchboard) env; // inital values for AJAX Elements (without JavaScript) final serverObjects prop = new serverObjects(); prop.put("rejected", 0); prop.put("urlpublictextSize", 0); prop.put("rwipublictextSize", 0); prop.put("list", "0"); prop.put("loaderSize", 0); prop.put("loaderMax", 0); prop.put("list-loader", 0); prop.put("localCrawlSize", sb.crawlQueues.coreCrawlJobSize()); prop.put("localCrawlState", ""); prop.put("limitCrawlSize", sb.crawlQueues.limitCrawlJobSize()); prop.put("limitCrawlState", ""); prop.put("remoteCrawlSize", sb.crawlQueues.limitCrawlJobSize()); prop.put("remoteCrawlState", ""); prop.put("list-remote", 0); prop.put("forwardToCrawlStart", "0"); // get segment Segment indexSegment = null; if (post != null && post.containsKey("segment")) { String segmentName = post.get("segment"); if (sb.indexSegments.segmentExist(segmentName)) { indexSegment = sb.indexSegments.segment(segmentName); } } else { // take default segment indexSegment = sb.indexSegments.segment(Segments.Process.PUBLIC); } prop.put("info", "0"); if (post != null && post.containsKey("continue")) { // continue queue final String queue = post.get("continue", ""); if ("localcrawler".equals(queue)) { sb.continueCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); } else if ("remotecrawler".equals(queue)) { sb.continueCrawlJob(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL); } } if (post != null && post.containsKey("pause")) { // pause queue final String queue = post.get("pause", ""); if ("localcrawler".equals(queue)) { sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); } else if ("remotecrawler".equals(queue)) { sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_REMOTE_TRIGGERED_CRAWL); } } if (post != null && post.containsKey("crawlingstart")) { // init crawl if (sb.peers == null) { prop.put("info", "3"); } else { String crawlingStart = post.get("crawlingURL","").trim(); // the crawljob start url // add the prefix http:// if necessary int pos = crawlingStart.indexOf("://"); if (pos == -1) { if (crawlingStart.startsWith("www")) crawlingStart = "http://" + crawlingStart; if (crawlingStart.startsWith("ftp")) crawlingStart = "ftp://" + crawlingStart; } // normalize URL DigestURI crawlingStartURL = null; try {crawlingStartURL = new DigestURI(crawlingStart);} catch (final MalformedURLException e1) {} crawlingStart = (crawlingStartURL == null) ? null : crawlingStartURL.toNormalform(true, true); // set new properties final boolean fullDomain = "domain".equals(post.get("range", "wide")); // special property in simple crawl start final boolean subPath = "subpath".equals(post.get("range", "wide")); // special property in simple crawl start // set the crawl filter String newcrawlingMustMatch = post.get("mustmatch", CrawlProfile.MATCH_ALL); String newcrawlingMustNotMatch = post.get("mustnotmatch", CrawlProfile.MATCH_NEVER); if (newcrawlingMustMatch.length() < 2) newcrawlingMustMatch = CrawlProfile.MATCH_ALL; // avoid that all urls are filtered out if bad value was submitted // special cases: if (crawlingStartURL!= null && fullDomain) { if (crawlingStartURL.isFile()) { newcrawlingMustMatch = "file://" + crawlingStartURL.getPath() + ".*"; } else if (crawlingStartURL.isSMB()) { newcrawlingMustMatch = "smb://.*" + crawlingStartURL.getHost() + ".*" + crawlingStartURL.getPath() + ".*"; } else if (crawlingStartURL.isFTP()) { newcrawlingMustMatch = "ftp://.*" + crawlingStartURL.getHost() + ".*" + crawlingStartURL.getPath() + ".*"; } else { newcrawlingMustMatch = ".*" + crawlingStartURL.getHost() + ".*"; } } if (crawlingStart!= null && subPath && (pos = crawlingStart.lastIndexOf('/')) > 0) { newcrawlingMustMatch = crawlingStart.substring(0, pos + 1) + ".*"; } final boolean crawlOrder = post.get("crawlOrder", "off").equals("on"); env.setConfig("crawlOrder", crawlOrder); int newcrawlingdepth = post.getInt("crawlingDepth", 8); env.setConfig("crawlingDepth", Integer.toString(newcrawlingdepth)); if ((crawlOrder) && (newcrawlingdepth > 8)) newcrawlingdepth = 8; // recrawl final String recrawl = post.get("recrawl", "nodoubles"); // nodoubles, reload, scheduler boolean crawlingIfOlderCheck = "on".equals(post.get("crawlingIfOlderCheck", "off")); int crawlingIfOlderNumber = post.getInt("crawlingIfOlderNumber", -1); String crawlingIfOlderUnit = post.get("crawlingIfOlderUnit","year"); // year, month, day, hour int repeat_time = post.getInt("repeat_time", -1); final String repeat_unit = post.get("repeat_unit", "seldays"); // selminutes, selhours, seldays if ("scheduler".equals(recrawl) && repeat_time > 0) { // set crawlingIfOlder attributes that are appropriate for scheduled crawling crawlingIfOlderCheck = true; crawlingIfOlderNumber = "selminutes".equals(repeat_unit) ? 1 : "selhours".equals(repeat_unit) ? repeat_time / 2 : repeat_time * 12; crawlingIfOlderUnit = "hour"; } else if ("reload".equals(recrawl)) { repeat_time = -1; crawlingIfOlderCheck = true; } else if ("nodoubles".equals(recrawl)) { repeat_time = -1; crawlingIfOlderCheck = false; } long crawlingIfOlder = recrawlIfOlderC(crawlingIfOlderCheck, crawlingIfOlderNumber, crawlingIfOlderUnit); env.setConfig("crawlingIfOlder", crawlingIfOlder); // remove crawlingFileContent before we record the call final String crawlingFileName = post.get("crawlingFile"); final File crawlingFile = (crawlingFileName != null && crawlingFileName.length() > 0) ? new File(crawlingFileName) : null; if (crawlingFile != null && crawlingFile.exists()) { post.remove("crawlingFile$file"); } // store this call as api call if (repeat_time > 0) { // store as scheduled api call sb.tables.recordAPICall(post, "Crawler_p.html", WorkTables.TABLE_API_TYPE_CRAWLER, "crawl start for " + ((crawlingStart == null) ? post.get("crawlingFile", "") : crawlingStart), repeat_time, repeat_unit.substring(3)); } else { // store just a protocol sb.tables.recordAPICall(post, "Crawler_p.html", WorkTables.TABLE_API_TYPE_CRAWLER, "crawl start for " + ((crawlingStart == null) ? post.get("crawlingFile", "") : crawlingStart)); } final boolean crawlingDomMaxCheck = "on".equals(post.get("crawlingDomMaxCheck", "off")); final int crawlingDomMaxPages = (crawlingDomMaxCheck) ? post.getInt("crawlingDomMaxPages", -1) : -1; env.setConfig("crawlingDomMaxPages", Integer.toString(crawlingDomMaxPages)); final boolean crawlingQ = "on".equals(post.get("crawlingQ", "off")); env.setConfig("crawlingQ", crawlingQ); final boolean indexText = "on".equals(post.get("indexText", "on")); env.setConfig("indexText", indexText); final boolean indexMedia = "on".equals(post.get("indexMedia", "on")); env.setConfig("indexMedia", indexMedia); boolean storeHTCache = "on".equals(post.get("storeHTCache", "on")); if (crawlingStartURL!= null &&(crawlingStartURL.isFile() || crawlingStartURL.isSMB())) storeHTCache = false; env.setConfig("storeHTCache", storeHTCache); CrawlProfile.CacheStrategy cachePolicy = CrawlProfile.CacheStrategy.parse(post.get("cachePolicy", "iffresh")); if (cachePolicy == null) cachePolicy = CrawlProfile.CacheStrategy.IFFRESH; final boolean xsstopw = "on".equals(post.get("xsstopw", "off")); env.setConfig("xsstopw", xsstopw); final boolean xdstopw = "on".equals(post.get("xdstopw", "off")); env.setConfig("xdstopw", xdstopw); final boolean xpstopw = "on".equals(post.get("xpstopw", "off")); env.setConfig("xpstopw", xpstopw); final String crawlingMode = post.get("crawlingMode","url"); if (crawlingStart != null && crawlingStart.startsWith("ftp")) { try { // check if the crawl filter works correctly Pattern.compile(newcrawlingMustMatch); final CrawlProfile profile = new CrawlProfile( crawlingStart, crawlingStartURL, newcrawlingMustMatch, CrawlProfile.MATCH_NEVER, newcrawlingdepth, crawlingIfOlder, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(profile.handle().getBytes(), profile); sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); final DigestURI url = crawlingStartURL; sb.crawlStacker.enqueueEntriesFTP(sb.peers.mySeed().hash.getBytes(), profile.handle(), url.getHost(), url.getPort(), false); } catch (final PatternSyntaxException e) { prop.put("info", "4"); // crawlfilter does not match url prop.putHTML("info_newcrawlingfilter", newcrawlingMustMatch); prop.putHTML("info_error", e.getMessage()); } catch (final Exception e) { // mist prop.put("info", "7"); // Error with file prop.putHTML("info_crawlingStart", crawlingStart); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } sb.continueCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); } else if ("url".equals(crawlingMode)) { // check if pattern matches if ((crawlingStart == null || crawlingStartURL == null) /* || (!(crawlingStart.matches(newcrawlingfilter))) */) { // print error message prop.put("info", "4"); //crawlfilter does not match url prop.putHTML("info_newcrawlingfilter", newcrawlingMustMatch); prop.putHTML("info_crawlingStart", crawlingStart); } else try { // check if the crawl filter works correctly Pattern.compile(newcrawlingMustMatch); // stack request // first delete old entry, if exists final DigestURI url = new DigestURI(crawlingStart); final byte[] urlhash = url.hash(); indexSegment.urlMetadata().remove(urlhash); sb.crawlQueues.noticeURL.removeByURLHash(urlhash); sb.crawlQueues.errorURL.remove(urlhash); // stack url sb.crawler.removePassive(crawlingStartURL.hash()); // if there is an old entry, delete it final CrawlProfile pe = new CrawlProfile( (crawlingStartURL.getHost() == null) ? crawlingStartURL.toNormalform(true, false) : crawlingStartURL.getHost(), crawlingStartURL, newcrawlingMustMatch, newcrawlingMustNotMatch, newcrawlingdepth, crawlingIfOlder, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(pe.handle().getBytes(), pe); final String reasonString = sb.crawlStacker.stackCrawl(new Request( sb.peers.mySeed().hash.getBytes(), url, null, "CRAWLING-ROOT", new Date(), pe.handle(), 0, 0, 0, 0 )); if (reasonString == null) { // create a bookmark from crawl start url Set<String> tags=ListManager.string2set(BookmarkHelper.cleanTagsString(post.get("bookmarkFolder","/crawlStart"))); tags.add("crawlStart"); if ("on".equals(post.get("createBookmark","off"))) { BookmarksDB.Bookmark bookmark = sb.bookmarksDB.createBookmark(crawlingStart, "admin"); if (bookmark != null) { bookmark.setProperty(BookmarksDB.Bookmark.BOOKMARK_TITLE, post.get("bookmarkTitle", crawlingStart)); bookmark.setOwner("admin"); bookmark.setPublic(false); bookmark.setTags(tags, true); sb.bookmarksDB.saveBookmark(bookmark); } } // liftoff! prop.put("info", "8");//start msg prop.putHTML("info_crawlingURL", (post.get("crawlingURL"))); // generate a YaCyNews if the global flag was set if (!sb.isRobinsonMode() && crawlOrder) { final Map<String, String> m = new HashMap<String, String>(pe); // must be cloned m.remove("specificDepth"); m.remove("indexText"); m.remove("indexMedia"); m.remove("remoteIndexing"); m.remove("xsstopw"); m.remove("xpstopw"); m.remove("xdstopw"); m.remove("storeTXCache"); m.remove("storeHTCache"); m.remove("generalFilter"); m.remove("specificFilter"); m.put("intention", post.get("intention", "").replace(',', '/')); sb.peers.newsPool.publishMyNews(sb.peers.mySeed(), yacyNewsPool.CATEGORY_CRAWL_START, m); } } else { prop.put("info", "5"); //Crawling failed prop.putHTML("info_crawlingURL", (post.get("crawlingURL"))); prop.putHTML("info_reasonString", reasonString); sb.crawlQueues.errorURL.push( new Request( sb.peers.mySeed().hash.getBytes(), crawlingStartURL, null, "", new Date(), pe.handle(), 0, 0, 0, 0), sb.peers.mySeed().hash.getBytes(), new Date(), 1, reasonString); } } catch (final PatternSyntaxException e) { prop.put("info", "4"); // crawlfilter does not match url prop.putHTML("info_newcrawlingfilter", newcrawlingMustMatch); prop.putHTML("info_error", e.getMessage()); } catch (final Exception e) { // mist prop.put("info", "6"); // Error with url prop.putHTML("info_crawlingStart", crawlingStart); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } } else if ("file".equals(crawlingMode)) { if (post.containsKey("crawlingFile")) { final String crawlingFileContent = post.get("crawlingFile$file", ""); try { // check if the crawl filter works correctly Pattern.compile(newcrawlingMustMatch); final ContentScraper scraper = new ContentScraper(new DigestURI(crawlingFile)); final Writer writer = new TransformerWriter(null, null, scraper, null, false); if (crawlingFile != null && crawlingFile.exists()) { FileUtils.copy(new FileInputStream(crawlingFile), writer); } else { FileUtils.copy(crawlingFileContent, writer); } writer.close(); // get links and generate filter final Map<MultiProtocolURI, String> hyperlinks = scraper.getAnchors(); if (fullDomain && newcrawlingdepth > 0) newcrawlingMustMatch = siteFilter(hyperlinks.keySet()); final DigestURI crawlURL = new DigestURI("file://" + crawlingFile.toString()); final CrawlProfile profile = new CrawlProfile( crawlingFileName, crawlURL, newcrawlingMustMatch, CrawlProfile.MATCH_NEVER, newcrawlingdepth, crawlingIfOlder, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(profile.handle().getBytes(), profile); sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); sb.crawlStacker.enqueueEntries(sb.peers.mySeed().hash.getBytes(), profile.handle(), hyperlinks, true); } catch (final PatternSyntaxException e) { prop.put("info", "4"); // crawlfilter does not match url prop.putHTML("info_newcrawlingfilter", newcrawlingMustMatch); prop.putHTML("info_error", e.getMessage()); } catch (final Exception e) { // mist prop.put("info", "7"); // Error with file prop.putHTML("info_crawlingStart", crawlingFileName); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } sb.continueCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); } } else if ("sitemap".equals(crawlingMode)) { String sitemapURLStr = post.get("sitemapURL",""); try { final DigestURI sitemapURL = new DigestURI(sitemapURLStr); final CrawlProfile pe = new CrawlProfile( sitemapURLStr, sitemapURL, CrawlProfile.MATCH_ALL, CrawlProfile.MATCH_NEVER, 0, crawlingIfOlder, crawlingDomMaxPages, true, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(pe.handle().getBytes(), pe); final SitemapImporter importer = new SitemapImporter(sb, sitemapURL, pe); importer.start(); } catch (final Exception e) { // mist prop.put("info", "6");//Error with url prop.putHTML("info_crawlingStart", sitemapURLStr); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } } else if ("sitelist".equals(crawlingMode)) { try { final DigestURI sitelistURL = new DigestURI(crawlingStart); // download document ContentScraper scraper = null; scraper = sb.loader.parseResource(sitelistURL, CrawlProfile.CacheStrategy.IFFRESH); // String title = scraper.getTitle(); // String description = scraper.getDescription(); // get links and generate filter final Map<MultiProtocolURI, String> hyperlinks = scraper.getAnchors(); if (fullDomain && newcrawlingdepth > 0) newcrawlingMustMatch = siteFilter(hyperlinks.keySet()); // put links onto crawl queue final CrawlProfile profile = new CrawlProfile( sitelistURL.getHost(), sitelistURL, newcrawlingMustMatch, CrawlProfile.MATCH_NEVER, newcrawlingdepth, crawlingIfOlder, crawlingDomMaxPages, crawlingQ, indexText, indexMedia, storeHTCache, crawlOrder, xsstopw, xdstopw, xpstopw, cachePolicy); sb.crawler.putActive(profile.handle().getBytes(), profile); sb.pauseCrawlJob(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL); final Iterator<Map.Entry<MultiProtocolURI, String>> linkiterator = hyperlinks.entrySet().iterator(); DigestURI nexturl; while (linkiterator.hasNext()) { final Map.Entry<MultiProtocolURI, String> e = linkiterator.next(); if (e.getKey() == null) continue; nexturl = new DigestURI(e.getKey()); // remove the url from the database to be prepared to crawl them again final byte[] urlhash = nexturl.hash(); indexSegment.urlMetadata().remove(urlhash); sb.crawlQueues.noticeURL.removeByURLHash(urlhash); sb.crawlQueues.errorURL.remove(urlhash); sb.crawlStacker.enqueueEntry(new Request( sb.peers.mySeed().hash.getBytes(), nexturl, null, e.getValue(), new Date(), profile.handle(), 0, 0, 0, 0 )); } } catch (final Exception e) { // mist prop.put("info", "6");//Error with url prop.putHTML("info_crawlingStart", crawlingStart); prop.putHTML("info_error", e.getMessage()); Log.logException(e); } } } } if (post != null && post.containsKey("crawlingPerformance")) { setPerformance(sb, post); } // performance settings final long LCbusySleep = env.getConfigLong(SwitchboardConstants.CRAWLJOB_LOCAL_CRAWL_BUSYSLEEP, 1000L); final int LCppm = (int) (60000L / Math.max(1,LCbusySleep)); prop.put("crawlingSpeedMaxChecked", (LCppm >= 30000) ? "1" : "0"); prop.put("crawlingSpeedCustChecked", ((LCppm > 10) && (LCppm < 30000)) ? "1" : "0"); prop.put("crawlingSpeedMinChecked", (LCppm <= 10) ? "1" : "0"); prop.put("customPPMdefault", Integer.toString(LCppm)); // return rewrite properties return prop; }
diff --git a/src/net/rptools/maptool/client/ui/ConnectToServerDialog.java b/src/net/rptools/maptool/client/ui/ConnectToServerDialog.java index fdbc9aeb..a9068e16 100644 --- a/src/net/rptools/maptool/client/ui/ConnectToServerDialog.java +++ b/src/net/rptools/maptool/client/ui/ConnectToServerDialog.java @@ -1,424 +1,424 @@ /* The MIT License * * Copyright (c) 2005 David Rice, Trevor Croft * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation files * (the "Software"), to deal in the Software without restriction, * including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.rptools.maptool.client.ui; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.net.InetAddress; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JList; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumn; import net.rptools.lib.swing.SwingUtil; import net.rptools.maptool.client.AppConstants; import net.rptools.maptool.client.MapTool; import net.rptools.maptool.client.MapToolRegistry; import net.rptools.maptool.client.swing.AbeillePanel; import net.rptools.maptool.client.swing.GenericDialog; import net.tsc.servicediscovery.AnnouncementListener; import net.tsc.servicediscovery.ServiceFinder; import org.jdesktop.swingworker.SwingWorker; import yasb.Binder; /** * @author trevor */ public class ConnectToServerDialog extends AbeillePanel<ConnectToServerDialogPreferences> implements AnnouncementListener{ private static ServiceFinder finder; static { finder = new ServiceFinder(AppConstants.SERVICE_GROUP); } private boolean accepted; private GenericDialog dialog; private int port; private String hostname; /** * This is the default constructor */ public ConnectToServerDialog() { super("net/rptools/maptool/client/ui/forms/connectToServerDialog.jfrm"); setPreferredSize(new Dimension(400, 400)); panelInit(); } @Override protected void preModelBind() { Binder.setFormat(getPortTextField(), new DecimalFormat("####")); } public int getPort() { return port; } public String getServer() { return hostname; } public void showDialog() { dialog = new GenericDialog("Connect to Server", MapTool.getFrame(), this); bind(new ConnectToServerDialogPreferences()); getRootPane().setDefaultButton(getOKButton()); dialog.showDialog(); } public JButton getOKButton() { return (JButton) getComponent("okButton"); } @Override public void bind(ConnectToServerDialogPreferences model) { finder.addAnnouncementListener(this); updateLocalServerList(); updateRemoteServerList(); super.bind(model); } @Override public void unbind() { // Shutting down finder.removeAnnouncementListener(this); finder.dispose(); super.unbind(); } public JButton getCancelButton() { return (JButton) getComponent("cancelButton"); } public void initCancelButton() { getCancelButton().addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { accepted = false; dialog.closeDialog(); } }); } public void initOKButton() { getOKButton().addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent e) { handleOK(); } }); } public boolean accepted() { return accepted; } public JComboBox getRoleComboBox() { return (JComboBox) getComponent("@role"); } public void initRoleComboBox() { getRoleComboBox().setModel(new DefaultComboBoxModel(new String[]{"Player", "GM"})); } public void initLocalServerList() { getLocalServerList().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); getLocalServerList().addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { handleOK(); } }; }); } public JList getLocalServerList() { return (JList)getComponent("localServerList"); } private void updateLocalServerList() { finder.find(); } private void updateRemoteServerList() { new SwingWorker<Object, Object>() { RemoteServerTableModel model = null; @Override protected Object doInBackground() throws Exception { model = new RemoteServerTableModel(MapToolRegistry.findAllInstances()); return null; } @Override protected void done() { getRemoteServerTable().setModel(model); TableColumn column = getRemoteServerTable().getColumnModel().getColumn(1); column.setPreferredWidth(70); column.setMaxWidth(70); column.setCellRenderer(new DefaultTableCellRenderer() { { setHorizontalAlignment(RIGHT); } }); } }.execute(); } public void initRemoteServerTable() { getRemoteServerTable().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); getRemoteServerTable().addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { getServerNameTextField().setText(getRemoteServerTable().getModel().getValueAt(getRemoteServerTable().getSelectedRow(), 0).toString()); handleOK(); } }; }); } public JTable getRemoteServerTable() { return (JTable) getComponent("aliasTable"); } public JButton getRescanButton() { return (JButton) getComponent("rescanButton"); } public JButton getRefreshButton() { return (JButton) getComponent("refreshButton"); } public void initRescanButton() { getRescanButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ((DefaultListModel)getLocalServerList().getModel()).clear(); finder.find(); } }); } public void initRefreshButton() { getRefreshButton().addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateRemoteServerList(); } }); } public JTextField getUsernameTextField() { return (JTextField) getComponent("@username"); } public JTextField getPortTextField() { return (JTextField) getComponent("@port"); } public JTextField getHostTextField() { return (JTextField) getComponent("@host"); } public JTextField getServerNameTextField() { return (JTextField) getComponent("@serverName"); } public JTabbedPane getTabPane() { return (JTabbedPane) getComponent("tabPane"); } private void handleOK() { if (getUsernameTextField().getText().length() == 0) { MapTool.showError("Must supply a username"); return; } JComponent selectedPanel = (JComponent) getTabPane().getSelectedComponent(); if (SwingUtil.hasComponent(selectedPanel, "lanPanel")) { if (getLocalServerList().getSelectedIndex() < 0) { MapTool.showError("Must select a server"); return; } // OK ServerInfo info = (ServerInfo) getLocalServerList().getSelectedValue(); port = info.port; hostname = info.address.getHostAddress(); } if (SwingUtil.hasComponent(selectedPanel, "directPanel")) { // TODO: put these into a validation method if (getPortTextField().getText().length() == 0) { MapTool.showError("Must supply a port"); return; } try { Integer.parseInt(getPortTextField().getText()); } catch (NumberFormatException nfe) { MapTool.showError("Port must be numeric"); return; } if (getHostTextField().getText().length() == 0) { MapTool.showError("Must supply a server"); return; } // OK port = Integer.parseInt(getPortTextField().getText()); - hostname = getServerNameTextField().getText(); + hostname = getHostTextField().getText(); } if (SwingUtil.hasComponent(selectedPanel, "rptoolsPanel")) { if (getServerNameTextField().getText().length() == 0) { MapTool.showError("Must supply a server name"); return; } // Do the lookup String serverName = getServerNameTextField().getText(); String serverInfo = MapToolRegistry.findInstance(serverName); if (serverInfo == null || serverInfo.length() == 0) { MapTool.showError("Could not find server: " + serverName); return; } String[] data = serverInfo.split(":"); hostname = data[0]; port = Integer.parseInt(data[1]); } if (commit()) { accepted = true; dialog.closeDialog(); } } @Override public boolean commit() { ConnectToServerDialogPreferences prefs = new ConnectToServerDialogPreferences(); // Not bindable .. yet prefs.setTab(getTabPane().getSelectedIndex()); return super.commit(); } private static class RemoteServerTableModel extends AbstractTableModel { private List<String[]> data; public RemoteServerTableModel(List<String> encodedData) { System.out.println(encodedData); data = new ArrayList<String[]>(encodedData.size()); for (String line : encodedData) { String[] row = line.split(":"); if (row.length == 1) { row = new String[]{row[0], "Pre 1.3"}; } data.add(row); } } @Override public String getColumnName(int column) { switch(column) { case 0: return "Server Name"; case 1: return "Version"; } return ""; } public int getColumnCount() { return 2; } public int getRowCount() { return data.size(); } public Object getValueAt(int rowIndex, int columnIndex) { String[] row = data.get(rowIndex); return row[columnIndex]; } } //// // ANNOUNCEMENT LISTENER public void serviceAnnouncement(String type, InetAddress address, int port, byte[] data) { ((DefaultListModel)getLocalServerList().getModel()).addElement(new ServerInfo(new String(data), address, port)); } private class ServerInfo { String id; InetAddress address; int port; public ServerInfo (String id, InetAddress address, int port) { this.id = id; this.address = address; this.port = port; } public String toString() { return id; } } }
true
true
private void handleOK() { if (getUsernameTextField().getText().length() == 0) { MapTool.showError("Must supply a username"); return; } JComponent selectedPanel = (JComponent) getTabPane().getSelectedComponent(); if (SwingUtil.hasComponent(selectedPanel, "lanPanel")) { if (getLocalServerList().getSelectedIndex() < 0) { MapTool.showError("Must select a server"); return; } // OK ServerInfo info = (ServerInfo) getLocalServerList().getSelectedValue(); port = info.port; hostname = info.address.getHostAddress(); } if (SwingUtil.hasComponent(selectedPanel, "directPanel")) { // TODO: put these into a validation method if (getPortTextField().getText().length() == 0) { MapTool.showError("Must supply a port"); return; } try { Integer.parseInt(getPortTextField().getText()); } catch (NumberFormatException nfe) { MapTool.showError("Port must be numeric"); return; } if (getHostTextField().getText().length() == 0) { MapTool.showError("Must supply a server"); return; } // OK port = Integer.parseInt(getPortTextField().getText()); hostname = getServerNameTextField().getText(); } if (SwingUtil.hasComponent(selectedPanel, "rptoolsPanel")) { if (getServerNameTextField().getText().length() == 0) { MapTool.showError("Must supply a server name"); return; } // Do the lookup String serverName = getServerNameTextField().getText(); String serverInfo = MapToolRegistry.findInstance(serverName); if (serverInfo == null || serverInfo.length() == 0) { MapTool.showError("Could not find server: " + serverName); return; } String[] data = serverInfo.split(":"); hostname = data[0]; port = Integer.parseInt(data[1]); } if (commit()) { accepted = true; dialog.closeDialog(); } }
private void handleOK() { if (getUsernameTextField().getText().length() == 0) { MapTool.showError("Must supply a username"); return; } JComponent selectedPanel = (JComponent) getTabPane().getSelectedComponent(); if (SwingUtil.hasComponent(selectedPanel, "lanPanel")) { if (getLocalServerList().getSelectedIndex() < 0) { MapTool.showError("Must select a server"); return; } // OK ServerInfo info = (ServerInfo) getLocalServerList().getSelectedValue(); port = info.port; hostname = info.address.getHostAddress(); } if (SwingUtil.hasComponent(selectedPanel, "directPanel")) { // TODO: put these into a validation method if (getPortTextField().getText().length() == 0) { MapTool.showError("Must supply a port"); return; } try { Integer.parseInt(getPortTextField().getText()); } catch (NumberFormatException nfe) { MapTool.showError("Port must be numeric"); return; } if (getHostTextField().getText().length() == 0) { MapTool.showError("Must supply a server"); return; } // OK port = Integer.parseInt(getPortTextField().getText()); hostname = getHostTextField().getText(); } if (SwingUtil.hasComponent(selectedPanel, "rptoolsPanel")) { if (getServerNameTextField().getText().length() == 0) { MapTool.showError("Must supply a server name"); return; } // Do the lookup String serverName = getServerNameTextField().getText(); String serverInfo = MapToolRegistry.findInstance(serverName); if (serverInfo == null || serverInfo.length() == 0) { MapTool.showError("Could not find server: " + serverName); return; } String[] data = serverInfo.split(":"); hostname = data[0]; port = Integer.parseInt(data[1]); } if (commit()) { accepted = true; dialog.closeDialog(); } }
diff --git a/src/com/suxsem/liquidnextparts/activities/settings.java b/src/com/suxsem/liquidnextparts/activities/settings.java index 2f9c636..6a54172 100755 --- a/src/com/suxsem/liquidnextparts/activities/settings.java +++ b/src/com/suxsem/liquidnextparts/activities/settings.java @@ -1,538 +1,538 @@ package com.suxsem.liquidnextparts.activities; import com.suxsem.liquidnextparts.components.StartSystem; import com.suxsem.liquidnextparts.BatteryLED; import com.suxsem.liquidnextparts.DiskSpace; import com.suxsem.liquidnextparts.LSystem; import com.suxsem.liquidnextparts.LiquidSettings; import com.suxsem.liquidnextparts.NetworkMode; import com.suxsem.liquidnextparts.OTA_updates; import com.suxsem.liquidnextparts.R; import com.suxsem.liquidnextparts.SdCache; import com.suxsem.liquidnextparts.Strings; import com.suxsem.liquidnextparts.parsebuildprop; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ComponentName; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceManager; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.widget.Toast; import android.content.Intent; import android.content.SharedPreferences.Editor; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; public class settings extends PreferenceActivity { @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.inflatedmenu, menu); return true; } @Override public void onStop() { super.onStop(); this.finish(); return; } public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menu_help: showhelp(); return true; case R.id.menu_close: this.finish(); return true; default: return super.onOptionsItemSelected(item); } } public boolean ROOT = false; public boolean isFirstTime = false; public SharedPreferences prefs; public String noiseValue, sensitivityValue, softsensValue, hftimeValue; public int SDCacheSize; private settings myactivity = this; EditTextPreference editNoise, editSensitivity, editSoftsens, editHftime; public String DownloadTaskInformations = ""; Boolean update = false; Boolean connection = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!LSystem.checkInitFolder()){ Toast.makeText(this, "Can't make init.d folder, your system must be rooted", 4000).show(); this.finish(); //Exit app } ROOT = LiquidSettings.isRoot(); prefs = PreferenceManager.getDefaultSharedPreferences(myactivity); new StartSystem().startsystem(myactivity); addPreferencesFromResource(R.xml.menu); final Context context = getApplicationContext(); final CheckBoxPreference hf = (CheckBoxPreference)findPreference("hf"); final EditTextPreference sdcache = (EditTextPreference)findPreference("sdcache"); final CheckBoxPreference powerled = (CheckBoxPreference)findPreference("powerled"); // final CheckBoxPreference fixled = (CheckBoxPreference)findPreference("fixled"); final CheckBoxPreference noprox = (CheckBoxPreference)findPreference("noprox"); final CheckBoxPreference updateonstart = (CheckBoxPreference)findPreference("updateonstart"); final Preference menu_info = findPreference("menu_info"); final Preference diskspace = findPreference("diskspace"); final Preference hotreboot = findPreference("hotreboot"); final Preference forceupdate = findPreference("forceupdate"); final Preference donateclick = findPreference("donateclick"); final Preference v6scripttweaker = findPreference("v6scripttweaker"); final Preference reportissue = findPreference("reportissue"); final ListPreference networkmode = (ListPreference)findPreference("2g3gmode"); final Preference resetall = findPreference("resetall"); //noprox.setChecked((parsebuildprop.parseInt("hw.acer.psensor_calib_min_base")==32717)); editNoise = (EditTextPreference)findPreference("noise"); editSensitivity = (EditTextPreference)findPreference("sensitivity"); editSoftsens = (EditTextPreference)findPreference("softsens"); editHftime = (EditTextPreference)findPreference("hftime"); if (!LSystem.hapticAvailable()) hf.setEnabled(false); else hf.setChecked(LSystem.vibrStatus()); if (!SdCache.isCachePathAvailable()) sdcache.setEnabled(false); if ((SDCacheSize=SdCache.getSdCacheSize()) >= 128){ sdcache.setText(Integer.toString(SDCacheSize)); } noiseValue = editNoise.getText(); sensitivityValue = editSensitivity.getText(); softsensValue = editSoftsens.getText(); hftimeValue = editHftime.getText(); updateValues(); editNoise.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to noiseValue noiseValue = newValue.toString(); int noiseValueInt = Integer.parseInt(noiseValue); if(noiseValueInt < 20) noiseValue = "20"; else if(noiseValueInt > 75) noiseValue = "75"; if(ROOT) { if(ROOT && LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity"); LSystem.RemountROnly(); if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity")) Toast.makeText(context, "Sensitivity set correctly", 4000).show(); else Toast.makeText(context, "Error, unable to set noise", 4000).show(); } updateValues(); } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); } return true; } }); editSensitivity.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to sensitivityValue sensitivityValue = newValue.toString(); int sensitivityValueInt = Integer.parseInt(sensitivityValue); if(sensitivityValueInt < (20)) sensitivityValue = ("20"); else if (sensitivityValueInt>(75)) sensitivityValue=("75"); if(ROOT) { if(ROOT && LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity"); LSystem.RemountROnly(); if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity")) Toast.makeText(context, "Sensitivity set correctly", 4000).show(); else Toast.makeText(context, "Error, unable to set noise", 4000).show(); } updateValues(); } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); } return true; } }); editSoftsens.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to sensitivityValue softsensValue = newValue.toString(); int softsensValueInt = Integer.parseInt(softsensValue); if(softsensValueInt < (15)) softsensValue = ("15"); else if (softsensValueInt>(30)) softsensValue=("30"); if(ROOT) { if(ROOT && LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity"); LSystem.RemountROnly(); if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity")) Toast.makeText(context, "Sensitivity set correctly", 4000).show(); else Toast.makeText(context, "Error, unable to set noise", 4000).show(); } updateValues(); } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); } return true; } }); powerled.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { if (ROOT){ if (powerled.isChecked()) { LiquidSettings.runRootCommand("echo '0' > /sys/class/leds2/power"); LiquidSettings.runRootCommand("chmod 000 /sys/class/leds2/power"); }else{ LiquidSettings.runRootCommand("chmod 222 /sys/class/leds2/power"); } if (BatteryLED.setdisable(powerled.isChecked())){ return true; } else{ Toast.makeText(context, "Error while set Power LED disable", 4000).show(); return false; } }else { Toast.makeText(context, "Sorry, you need ROOT permissions", 4000).show(); return false; } } }); hf.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { if(ROOT){ if(LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo " + ((hf.isChecked()) ? Strings.getvibr() : Strings.getnovibr()) + " > /system/etc/init.d/06vibrate"); LiquidSettings.runRootCommand("echo " + ((hf.isChecked()==true) ? "1": "0") +" > /sys/module/avr/parameters/vibr"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06vibrate"); LSystem.RemountROnly(); Toast.makeText(context, "Haptic set on " + Boolean.toString(hf.isChecked()), 4000).show(); } else { Toast.makeText(context, "Error: unable to mount partition", 4000).show(); hf.setChecked(false); } } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); hf.setChecked(false); } return true; } }); editHftime.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to sensitivityValue hftimeValue = newValue.toString(); int hftimeValueInt = Integer.parseInt(hftimeValue); if(hftimeValueInt < (10)) hftimeValue = ("10"); else if (hftimeValueInt>(2000)) hftimeValue=("2000"); if(ROOT) { if(ROOT && LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity"); LSystem.RemountROnly(); if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity")) Toast.makeText(context, "Sensitivity set correctly", 4000).show(); else Toast.makeText(context, "Error, unable to set noise", 4000).show(); } updateValues(); } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); } return true; } }); sdcache.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to sensitivityValue String newValueString = newValue.toString(); int newValueInt = Integer.parseInt(newValueString); if(newValueInt < 128) newValueInt = 128; else if (newValueInt > 4096) newValueInt = 4096; if (ROOT){ if (SdCache.setSDCache(newValueInt)){ Toast.makeText(context, "SD cache size set to " + newValueInt, 4000).show(); return true; }else{ Toast.makeText(context, "Error while setting SD Cache", 4000).show(); return false; } } else Toast.makeText(context, "Sorry you need root permissions", 4000).show(); return false; } }); networkmode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { NetworkMode.switchnetworkmode(myactivity); return true; } }); noprox.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { if (noprox.isChecked()) { parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32717"); }else{ parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32716"); } AlertDialog.Builder builder = new AlertDialog.Builder(myactivity); builder.setTitle("Reboot required"); builder.setCancelable(true); builder.setMessage("This option requires a reboot to be applied. Do you want to reboot now?"); builder.setPositiveButton("Reboot", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { LiquidSettings.runRootCommand("reboot"); } }); builder.setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); return true; } }); v6scripttweaker.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { try { Intent intent = new Intent(Intent.ACTION_MAIN); - intent.setComponent(new ComponentName("jackpal.androidterm", "jackpal.androidterm.Term")); - intent.putExtra("jackpal.androidterm.iInitialCommand", "su \r sh /system/xbin/v6SuperChargerLN.sh"); + intent.setComponent(new ComponentName("jackpal.androidterm2", "jackpal.androidterm2.Term")); + intent.putExtra("jackpal.androidterm.iInitialCommand", "su \r sh /system/xbin/V6SuperChargerLN.sh"); startActivity(intent); } catch (Exception e) { Toast.makeText(myactivity, "No terminal emulator app found", 4000).show(); } return true; } }); diskspace.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { final AlertDialog.Builder builder = new AlertDialog.Builder(myactivity); builder.setTitle("DiskSpace"); builder.setCancelable(true); builder.setMessage(DiskSpace.getdiskspace()); builder.setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); return true; } }); hotreboot.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { ProgressDialog.show(myactivity, "", "Rebooting...", true); LiquidSettings.runRootCommand("killall system_server"); return true; } }); donateclick.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { ConnectivityManager connManager = (ConnectivityManager)myactivity.getSystemService(Context.CONNECTIVITY_SERVICE); android.net.NetworkInfo netInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); android.net.NetworkInfo wifiInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (netInfo.getState() == android.net.NetworkInfo.State.CONNECTED || wifiInfo.getState() == android.net.NetworkInfo.State.CONNECTED ) { Intent myintent = new Intent (Intent.ACTION_VIEW); myintent.setClassName(context, Webview.class.getName()); startActivity(myintent); }else{ Toast.makeText(myactivity, "ERROR: NO CONNECTIONS!", 4000).show(); } return true; } }); forceupdate.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { //checkupdates(); new OTA_updates().checkupdates(myactivity, myactivity); return true; } }); updateonstart.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { if (!updateonstart.isChecked()) { parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32717"); AlertDialog.Builder builder = new AlertDialog.Builder(myactivity); builder.setTitle("Are you sure?"); builder.setCancelable(true); builder.setMessage("It's very important to have the latest available updates! Please check this option only if you have problems launching app."); builder.setPositiveButton("Undo", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Editor editor = prefs.edit(); editor.putBoolean("updateonstart",true); updateonstart.setChecked(true); editor.commit(); } }); builder.setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); } return true; } }); reportissue.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { ConnectivityManager connManager = (ConnectivityManager)myactivity.getSystemService(Context.CONNECTIVITY_SERVICE); android.net.NetworkInfo netInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); android.net.NetworkInfo wifiInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (netInfo.getState() == android.net.NetworkInfo.State.CONNECTED || wifiInfo.getState() == android.net.NetworkInfo.State.CONNECTED ) { ProgressDialog.show(myactivity, "Report an issue", "Loading issues list...", true); Intent myintent = new Intent (Intent.ACTION_VIEW); myintent.setClassName(myactivity, ReportIssue.class.getName()); startActivity(myintent); }else{ Toast.makeText(myactivity, "ERROR: NO CONNECTIONS!", 4000).show(); } return true; } }); menu_info.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { showhelp(); return true; } }); resetall.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Editor editor = prefs.edit(); editor.putBoolean("firststart", true); editor.commit(); new StartSystem().startsystem(myactivity); return true; } }); // fixled.setOnPreferenceClickListener(new OnPreferenceClickListener() { // // public boolean onPreferenceClick(Preference preference) { // return true; // } // }); if(prefs.getBoolean("updateonstart", true)){ //checkupdates(); new OTA_updates().checkupdates(myactivity,myactivity); } } private void showhelp(){ Intent myintent = new Intent (Intent.ACTION_VIEW); myintent.setClassName(myactivity, InfoPreferenceActivity.class.getName()); startActivity(myintent); } private void updateValues() { editNoise.setSummary("Noise is set to " + noiseValue); editSensitivity.setSummary("Sensitivity is set to " + sensitivityValue); editSoftsens.setSummary("Softkey sensitivity is set to "+ softsensValue); editHftime.setSummary("Softkey vibration time is set to "+ hftimeValue +"ms"); } }
true
true
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!LSystem.checkInitFolder()){ Toast.makeText(this, "Can't make init.d folder, your system must be rooted", 4000).show(); this.finish(); //Exit app } ROOT = LiquidSettings.isRoot(); prefs = PreferenceManager.getDefaultSharedPreferences(myactivity); new StartSystem().startsystem(myactivity); addPreferencesFromResource(R.xml.menu); final Context context = getApplicationContext(); final CheckBoxPreference hf = (CheckBoxPreference)findPreference("hf"); final EditTextPreference sdcache = (EditTextPreference)findPreference("sdcache"); final CheckBoxPreference powerled = (CheckBoxPreference)findPreference("powerled"); // final CheckBoxPreference fixled = (CheckBoxPreference)findPreference("fixled"); final CheckBoxPreference noprox = (CheckBoxPreference)findPreference("noprox"); final CheckBoxPreference updateonstart = (CheckBoxPreference)findPreference("updateonstart"); final Preference menu_info = findPreference("menu_info"); final Preference diskspace = findPreference("diskspace"); final Preference hotreboot = findPreference("hotreboot"); final Preference forceupdate = findPreference("forceupdate"); final Preference donateclick = findPreference("donateclick"); final Preference v6scripttweaker = findPreference("v6scripttweaker"); final Preference reportissue = findPreference("reportissue"); final ListPreference networkmode = (ListPreference)findPreference("2g3gmode"); final Preference resetall = findPreference("resetall"); //noprox.setChecked((parsebuildprop.parseInt("hw.acer.psensor_calib_min_base")==32717)); editNoise = (EditTextPreference)findPreference("noise"); editSensitivity = (EditTextPreference)findPreference("sensitivity"); editSoftsens = (EditTextPreference)findPreference("softsens"); editHftime = (EditTextPreference)findPreference("hftime"); if (!LSystem.hapticAvailable()) hf.setEnabled(false); else hf.setChecked(LSystem.vibrStatus()); if (!SdCache.isCachePathAvailable()) sdcache.setEnabled(false); if ((SDCacheSize=SdCache.getSdCacheSize()) >= 128){ sdcache.setText(Integer.toString(SDCacheSize)); } noiseValue = editNoise.getText(); sensitivityValue = editSensitivity.getText(); softsensValue = editSoftsens.getText(); hftimeValue = editHftime.getText(); updateValues(); editNoise.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to noiseValue noiseValue = newValue.toString(); int noiseValueInt = Integer.parseInt(noiseValue); if(noiseValueInt < 20) noiseValue = "20"; else if(noiseValueInt > 75) noiseValue = "75"; if(ROOT) { if(ROOT && LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity"); LSystem.RemountROnly(); if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity")) Toast.makeText(context, "Sensitivity set correctly", 4000).show(); else Toast.makeText(context, "Error, unable to set noise", 4000).show(); } updateValues(); } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); } return true; } }); editSensitivity.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to sensitivityValue sensitivityValue = newValue.toString(); int sensitivityValueInt = Integer.parseInt(sensitivityValue); if(sensitivityValueInt < (20)) sensitivityValue = ("20"); else if (sensitivityValueInt>(75)) sensitivityValue=("75"); if(ROOT) { if(ROOT && LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity"); LSystem.RemountROnly(); if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity")) Toast.makeText(context, "Sensitivity set correctly", 4000).show(); else Toast.makeText(context, "Error, unable to set noise", 4000).show(); } updateValues(); } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); } return true; } }); editSoftsens.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to sensitivityValue softsensValue = newValue.toString(); int softsensValueInt = Integer.parseInt(softsensValue); if(softsensValueInt < (15)) softsensValue = ("15"); else if (softsensValueInt>(30)) softsensValue=("30"); if(ROOT) { if(ROOT && LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity"); LSystem.RemountROnly(); if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity")) Toast.makeText(context, "Sensitivity set correctly", 4000).show(); else Toast.makeText(context, "Error, unable to set noise", 4000).show(); } updateValues(); } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); } return true; } }); powerled.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { if (ROOT){ if (powerled.isChecked()) { LiquidSettings.runRootCommand("echo '0' > /sys/class/leds2/power"); LiquidSettings.runRootCommand("chmod 000 /sys/class/leds2/power"); }else{ LiquidSettings.runRootCommand("chmod 222 /sys/class/leds2/power"); } if (BatteryLED.setdisable(powerled.isChecked())){ return true; } else{ Toast.makeText(context, "Error while set Power LED disable", 4000).show(); return false; } }else { Toast.makeText(context, "Sorry, you need ROOT permissions", 4000).show(); return false; } } }); hf.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { if(ROOT){ if(LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo " + ((hf.isChecked()) ? Strings.getvibr() : Strings.getnovibr()) + " > /system/etc/init.d/06vibrate"); LiquidSettings.runRootCommand("echo " + ((hf.isChecked()==true) ? "1": "0") +" > /sys/module/avr/parameters/vibr"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06vibrate"); LSystem.RemountROnly(); Toast.makeText(context, "Haptic set on " + Boolean.toString(hf.isChecked()), 4000).show(); } else { Toast.makeText(context, "Error: unable to mount partition", 4000).show(); hf.setChecked(false); } } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); hf.setChecked(false); } return true; } }); editHftime.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to sensitivityValue hftimeValue = newValue.toString(); int hftimeValueInt = Integer.parseInt(hftimeValue); if(hftimeValueInt < (10)) hftimeValue = ("10"); else if (hftimeValueInt>(2000)) hftimeValue=("2000"); if(ROOT) { if(ROOT && LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity"); LSystem.RemountROnly(); if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity")) Toast.makeText(context, "Sensitivity set correctly", 4000).show(); else Toast.makeText(context, "Error, unable to set noise", 4000).show(); } updateValues(); } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); } return true; } }); sdcache.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to sensitivityValue String newValueString = newValue.toString(); int newValueInt = Integer.parseInt(newValueString); if(newValueInt < 128) newValueInt = 128; else if (newValueInt > 4096) newValueInt = 4096; if (ROOT){ if (SdCache.setSDCache(newValueInt)){ Toast.makeText(context, "SD cache size set to " + newValueInt, 4000).show(); return true; }else{ Toast.makeText(context, "Error while setting SD Cache", 4000).show(); return false; } } else Toast.makeText(context, "Sorry you need root permissions", 4000).show(); return false; } }); networkmode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { NetworkMode.switchnetworkmode(myactivity); return true; } }); noprox.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { if (noprox.isChecked()) { parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32717"); }else{ parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32716"); } AlertDialog.Builder builder = new AlertDialog.Builder(myactivity); builder.setTitle("Reboot required"); builder.setCancelable(true); builder.setMessage("This option requires a reboot to be applied. Do you want to reboot now?"); builder.setPositiveButton("Reboot", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { LiquidSettings.runRootCommand("reboot"); } }); builder.setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); return true; } }); v6scripttweaker.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { try { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setComponent(new ComponentName("jackpal.androidterm", "jackpal.androidterm.Term")); intent.putExtra("jackpal.androidterm.iInitialCommand", "su \r sh /system/xbin/v6SuperChargerLN.sh"); startActivity(intent); } catch (Exception e) { Toast.makeText(myactivity, "No terminal emulator app found", 4000).show(); } return true; } }); diskspace.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { final AlertDialog.Builder builder = new AlertDialog.Builder(myactivity); builder.setTitle("DiskSpace"); builder.setCancelable(true); builder.setMessage(DiskSpace.getdiskspace()); builder.setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); return true; } }); hotreboot.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { ProgressDialog.show(myactivity, "", "Rebooting...", true); LiquidSettings.runRootCommand("killall system_server"); return true; } }); donateclick.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { ConnectivityManager connManager = (ConnectivityManager)myactivity.getSystemService(Context.CONNECTIVITY_SERVICE); android.net.NetworkInfo netInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); android.net.NetworkInfo wifiInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (netInfo.getState() == android.net.NetworkInfo.State.CONNECTED || wifiInfo.getState() == android.net.NetworkInfo.State.CONNECTED ) { Intent myintent = new Intent (Intent.ACTION_VIEW); myintent.setClassName(context, Webview.class.getName()); startActivity(myintent); }else{ Toast.makeText(myactivity, "ERROR: NO CONNECTIONS!", 4000).show(); } return true; } }); forceupdate.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { //checkupdates(); new OTA_updates().checkupdates(myactivity, myactivity); return true; } }); updateonstart.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { if (!updateonstart.isChecked()) { parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32717"); AlertDialog.Builder builder = new AlertDialog.Builder(myactivity); builder.setTitle("Are you sure?"); builder.setCancelable(true); builder.setMessage("It's very important to have the latest available updates! Please check this option only if you have problems launching app."); builder.setPositiveButton("Undo", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Editor editor = prefs.edit(); editor.putBoolean("updateonstart",true); updateonstart.setChecked(true); editor.commit(); } }); builder.setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); } return true; } }); reportissue.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { ConnectivityManager connManager = (ConnectivityManager)myactivity.getSystemService(Context.CONNECTIVITY_SERVICE); android.net.NetworkInfo netInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); android.net.NetworkInfo wifiInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (netInfo.getState() == android.net.NetworkInfo.State.CONNECTED || wifiInfo.getState() == android.net.NetworkInfo.State.CONNECTED ) { ProgressDialog.show(myactivity, "Report an issue", "Loading issues list...", true); Intent myintent = new Intent (Intent.ACTION_VIEW); myintent.setClassName(myactivity, ReportIssue.class.getName()); startActivity(myintent); }else{ Toast.makeText(myactivity, "ERROR: NO CONNECTIONS!", 4000).show(); } return true; } }); menu_info.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { showhelp(); return true; } }); resetall.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Editor editor = prefs.edit(); editor.putBoolean("firststart", true); editor.commit(); new StartSystem().startsystem(myactivity); return true; } }); // fixled.setOnPreferenceClickListener(new OnPreferenceClickListener() { // // public boolean onPreferenceClick(Preference preference) { // return true; // } // }); if(prefs.getBoolean("updateonstart", true)){ //checkupdates(); new OTA_updates().checkupdates(myactivity,myactivity); } }
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!LSystem.checkInitFolder()){ Toast.makeText(this, "Can't make init.d folder, your system must be rooted", 4000).show(); this.finish(); //Exit app } ROOT = LiquidSettings.isRoot(); prefs = PreferenceManager.getDefaultSharedPreferences(myactivity); new StartSystem().startsystem(myactivity); addPreferencesFromResource(R.xml.menu); final Context context = getApplicationContext(); final CheckBoxPreference hf = (CheckBoxPreference)findPreference("hf"); final EditTextPreference sdcache = (EditTextPreference)findPreference("sdcache"); final CheckBoxPreference powerled = (CheckBoxPreference)findPreference("powerled"); // final CheckBoxPreference fixled = (CheckBoxPreference)findPreference("fixled"); final CheckBoxPreference noprox = (CheckBoxPreference)findPreference("noprox"); final CheckBoxPreference updateonstart = (CheckBoxPreference)findPreference("updateonstart"); final Preference menu_info = findPreference("menu_info"); final Preference diskspace = findPreference("diskspace"); final Preference hotreboot = findPreference("hotreboot"); final Preference forceupdate = findPreference("forceupdate"); final Preference donateclick = findPreference("donateclick"); final Preference v6scripttweaker = findPreference("v6scripttweaker"); final Preference reportissue = findPreference("reportissue"); final ListPreference networkmode = (ListPreference)findPreference("2g3gmode"); final Preference resetall = findPreference("resetall"); //noprox.setChecked((parsebuildprop.parseInt("hw.acer.psensor_calib_min_base")==32717)); editNoise = (EditTextPreference)findPreference("noise"); editSensitivity = (EditTextPreference)findPreference("sensitivity"); editSoftsens = (EditTextPreference)findPreference("softsens"); editHftime = (EditTextPreference)findPreference("hftime"); if (!LSystem.hapticAvailable()) hf.setEnabled(false); else hf.setChecked(LSystem.vibrStatus()); if (!SdCache.isCachePathAvailable()) sdcache.setEnabled(false); if ((SDCacheSize=SdCache.getSdCacheSize()) >= 128){ sdcache.setText(Integer.toString(SDCacheSize)); } noiseValue = editNoise.getText(); sensitivityValue = editSensitivity.getText(); softsensValue = editSoftsens.getText(); hftimeValue = editHftime.getText(); updateValues(); editNoise.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to noiseValue noiseValue = newValue.toString(); int noiseValueInt = Integer.parseInt(noiseValue); if(noiseValueInt < 20) noiseValue = "20"; else if(noiseValueInt > 75) noiseValue = "75"; if(ROOT) { if(ROOT && LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity"); LSystem.RemountROnly(); if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity")) Toast.makeText(context, "Sensitivity set correctly", 4000).show(); else Toast.makeText(context, "Error, unable to set noise", 4000).show(); } updateValues(); } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); } return true; } }); editSensitivity.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to sensitivityValue sensitivityValue = newValue.toString(); int sensitivityValueInt = Integer.parseInt(sensitivityValue); if(sensitivityValueInt < (20)) sensitivityValue = ("20"); else if (sensitivityValueInt>(75)) sensitivityValue=("75"); if(ROOT) { if(ROOT && LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity"); LSystem.RemountROnly(); if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity")) Toast.makeText(context, "Sensitivity set correctly", 4000).show(); else Toast.makeText(context, "Error, unable to set noise", 4000).show(); } updateValues(); } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); } return true; } }); editSoftsens.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to sensitivityValue softsensValue = newValue.toString(); int softsensValueInt = Integer.parseInt(softsensValue); if(softsensValueInt < (15)) softsensValue = ("15"); else if (softsensValueInt>(30)) softsensValue=("30"); if(ROOT) { if(ROOT && LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity"); LSystem.RemountROnly(); if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity")) Toast.makeText(context, "Sensitivity set correctly", 4000).show(); else Toast.makeText(context, "Error, unable to set noise", 4000).show(); } updateValues(); } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); } return true; } }); powerled.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { if (ROOT){ if (powerled.isChecked()) { LiquidSettings.runRootCommand("echo '0' > /sys/class/leds2/power"); LiquidSettings.runRootCommand("chmod 000 /sys/class/leds2/power"); }else{ LiquidSettings.runRootCommand("chmod 222 /sys/class/leds2/power"); } if (BatteryLED.setdisable(powerled.isChecked())){ return true; } else{ Toast.makeText(context, "Error while set Power LED disable", 4000).show(); return false; } }else { Toast.makeText(context, "Sorry, you need ROOT permissions", 4000).show(); return false; } } }); hf.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { if(ROOT){ if(LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo " + ((hf.isChecked()) ? Strings.getvibr() : Strings.getnovibr()) + " > /system/etc/init.d/06vibrate"); LiquidSettings.runRootCommand("echo " + ((hf.isChecked()==true) ? "1": "0") +" > /sys/module/avr/parameters/vibr"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06vibrate"); LSystem.RemountROnly(); Toast.makeText(context, "Haptic set on " + Boolean.toString(hf.isChecked()), 4000).show(); } else { Toast.makeText(context, "Error: unable to mount partition", 4000).show(); hf.setChecked(false); } } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); hf.setChecked(false); } return true; } }); editHftime.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to sensitivityValue hftimeValue = newValue.toString(); int hftimeValueInt = Integer.parseInt(hftimeValue); if(hftimeValueInt < (10)) hftimeValue = ("10"); else if (hftimeValueInt>(2000)) hftimeValue=("2000"); if(ROOT) { if(ROOT && LSystem.RemountRW()) { LiquidSettings.runRootCommand("echo "+Strings.getSens(sensitivityValue, noiseValue, softsensValue, hftimeValue)+" > /system/etc/init.d/06sensitivity"); LiquidSettings.runRootCommand("chmod +x /system/etc/init.d/06sensitivity"); LSystem.RemountROnly(); if (LiquidSettings.runRootCommand("./system/etc/init.d/06sensitivity")) Toast.makeText(context, "Sensitivity set correctly", 4000).show(); else Toast.makeText(context, "Error, unable to set noise", 4000).show(); } updateValues(); } else { Toast.makeText(context, "Sorry, you need ROOT permissions.", 4000).show(); } return true; } }); sdcache.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { public boolean onPreferenceChange(Preference preference, Object newValue) { if (!Strings.onlyNumber(newValue.toString())){ Toast.makeText(context, "You must enter a numeric value!", 4000).show(); return false; } //Check if the value is numeric, THEN assign it to sensitivityValue String newValueString = newValue.toString(); int newValueInt = Integer.parseInt(newValueString); if(newValueInt < 128) newValueInt = 128; else if (newValueInt > 4096) newValueInt = 4096; if (ROOT){ if (SdCache.setSDCache(newValueInt)){ Toast.makeText(context, "SD cache size set to " + newValueInt, 4000).show(); return true; }else{ Toast.makeText(context, "Error while setting SD Cache", 4000).show(); return false; } } else Toast.makeText(context, "Sorry you need root permissions", 4000).show(); return false; } }); networkmode.setOnPreferenceChangeListener(new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { NetworkMode.switchnetworkmode(myactivity); return true; } }); noprox.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { if (noprox.isChecked()) { parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32717"); }else{ parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32716"); } AlertDialog.Builder builder = new AlertDialog.Builder(myactivity); builder.setTitle("Reboot required"); builder.setCancelable(true); builder.setMessage("This option requires a reboot to be applied. Do you want to reboot now?"); builder.setPositiveButton("Reboot", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { LiquidSettings.runRootCommand("reboot"); } }); builder.setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); return true; } }); v6scripttweaker.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { try { Intent intent = new Intent(Intent.ACTION_MAIN); intent.setComponent(new ComponentName("jackpal.androidterm2", "jackpal.androidterm2.Term")); intent.putExtra("jackpal.androidterm.iInitialCommand", "su \r sh /system/xbin/V6SuperChargerLN.sh"); startActivity(intent); } catch (Exception e) { Toast.makeText(myactivity, "No terminal emulator app found", 4000).show(); } return true; } }); diskspace.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { final AlertDialog.Builder builder = new AlertDialog.Builder(myactivity); builder.setTitle("DiskSpace"); builder.setCancelable(true); builder.setMessage(DiskSpace.getdiskspace()); builder.setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); return true; } }); hotreboot.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { ProgressDialog.show(myactivity, "", "Rebooting...", true); LiquidSettings.runRootCommand("killall system_server"); return true; } }); donateclick.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { ConnectivityManager connManager = (ConnectivityManager)myactivity.getSystemService(Context.CONNECTIVITY_SERVICE); android.net.NetworkInfo netInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); android.net.NetworkInfo wifiInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (netInfo.getState() == android.net.NetworkInfo.State.CONNECTED || wifiInfo.getState() == android.net.NetworkInfo.State.CONNECTED ) { Intent myintent = new Intent (Intent.ACTION_VIEW); myintent.setClassName(context, Webview.class.getName()); startActivity(myintent); }else{ Toast.makeText(myactivity, "ERROR: NO CONNECTIONS!", 4000).show(); } return true; } }); forceupdate.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { //checkupdates(); new OTA_updates().checkupdates(myactivity, myactivity); return true; } }); updateonstart.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { if (!updateonstart.isChecked()) { parsebuildprop.editString("hw.acer.psensor_calib_min_base", "32717"); AlertDialog.Builder builder = new AlertDialog.Builder(myactivity); builder.setTitle("Are you sure?"); builder.setCancelable(true); builder.setMessage("It's very important to have the latest available updates! Please check this option only if you have problems launching app."); builder.setPositiveButton("Undo", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Editor editor = prefs.edit(); editor.putBoolean("updateonstart",true); updateonstart.setChecked(true); editor.commit(); } }); builder.setNegativeButton("Close", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }); builder.create().show(); } return true; } }); reportissue.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { ConnectivityManager connManager = (ConnectivityManager)myactivity.getSystemService(Context.CONNECTIVITY_SERVICE); android.net.NetworkInfo netInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); android.net.NetworkInfo wifiInfo= connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (netInfo.getState() == android.net.NetworkInfo.State.CONNECTED || wifiInfo.getState() == android.net.NetworkInfo.State.CONNECTED ) { ProgressDialog.show(myactivity, "Report an issue", "Loading issues list...", true); Intent myintent = new Intent (Intent.ACTION_VIEW); myintent.setClassName(myactivity, ReportIssue.class.getName()); startActivity(myintent); }else{ Toast.makeText(myactivity, "ERROR: NO CONNECTIONS!", 4000).show(); } return true; } }); menu_info.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { showhelp(); return true; } }); resetall.setOnPreferenceClickListener(new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Editor editor = prefs.edit(); editor.putBoolean("firststart", true); editor.commit(); new StartSystem().startsystem(myactivity); return true; } }); // fixled.setOnPreferenceClickListener(new OnPreferenceClickListener() { // // public boolean onPreferenceClick(Preference preference) { // return true; // } // }); if(prefs.getBoolean("updateonstart", true)){ //checkupdates(); new OTA_updates().checkupdates(myactivity,myactivity); } }
diff --git a/mote/sunspot/WalkDirection/src/org/sunspotworld/Main.java b/mote/sunspot/WalkDirection/src/org/sunspotworld/Main.java index f301da5..d148e20 100644 --- a/mote/sunspot/WalkDirection/src/org/sunspotworld/Main.java +++ b/mote/sunspot/WalkDirection/src/org/sunspotworld/Main.java @@ -1,209 +1,209 @@ package org.sunspotworld; import com.sun.spot.resources.Resources; import com.sun.spot.resources.transducers.ISwitch; import com.sun.spot.resources.transducers.ITriColorLEDArray; import com.sun.spot.resources.transducers.LEDColor; import com.sun.spot.resources.transducers.SwitchEvent; import com.sun.spot.sensorboard.EDemoBoard; import com.sun.spot.sensorboard.io.*; import com.sun.spot.util.Utils; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; public class Main extends MIDlet { //MULTICOLOR LEDs private ITriColorLEDArray leds = (ITriColorLEDArray) Resources.lookup(ITriColorLEDArray.class); private LEDColor[] colors = {LEDColor.RED, LEDColor.GREEN, LEDColor.BLUE}; //BUTTONS private ISwitch sw1 = (ISwitch) Resources.lookup(ISwitch.class, "SW1"); private ISwitch sw2 = (ISwitch) Resources.lookup(ISwitch.class, "SW2"); //STATES private static final int STATE_INITIALIZING = 0; private static final int STATE_SENSING = 1; private static final int STATE_TRANSMITTING = 2; private int state = STATE_INITIALIZING; private int motenum = -1; //WALK STATES private static final int WALK_NOTHING = 0; private static final int WALK_LEFT = 1; private static final int WALK_RIGHT = 2; private static final int WALK_WAITING = 5; //wait for reset //CONSTANTS private static final String DEST_MOTE = "0014.4F01.0000.0007"; //Mote connected to computer for collecting data public void switchReleased(SwitchEvent evt) { if (evt.getSwitch() == sw1) { //Blink binary mote num leds.setOff(); Utils.sleep(200); showCount(motenum, 0); Utils.sleep(1000); leds.setOff(); state = STATE_SENSING; } else { motenum++; showCount(motenum, 0); } } public void switchPressed(SwitchEvent evt) { } private void showCount(int count, int color) { for (int i = 7, bit = 1; i >= 0; i--, bit <<= 1) { if ((count & bit) != 0) { leds.getLED(i).setColor(colors[color]); leds.getLED(i).setOn(); } else { leds.getLED(i).setOff(); } } } private void showColor(int color) { leds.setColor(LEDColor.GREEN); leds.setOn(); } protected void startApp() throws MIDletStateChangeException { leds.setColor(colors[2]); leds.setOn(); Utils.sleep(1000); leds.setOff(); //This is in miliseconds. int readInterval = 500; int counter = 0; - boolean rightSensor, leftSensor; + boolean rightSensorEmpty, leftSensorEmpty; // ITriColorLED[] leds = EDemoBoard.getInstance().getLEDs(); IIOPin[] ioPins = EDemoBoard.getInstance().getIOPins(); leds.getLED(7).setRGB(255, 255, 255); int walkState = WALK_NOTHING; // 0 = nothing, 1 = walkLeft 2 = walkRight 5 = wait for reset. int lagTime = 8; int lsCount, rsCount; rsCount = 0; lsCount = 0; while (true) { switch (state) { case STATE_INITIALIZING: System.out.println("Initializing"); state = STATE_SENSING; break; case STATE_SENSING: //Constant LED to indicate running if (counter % 10 == 0) { if (leds.getLED(7).isOn()) { leds.getLED(7).setOff(); } else { leds.getLED(7).setOn(); } } - rightSensor = ioPins[0].getState(); - leftSensor = ioPins[1].getState(); + rightSensorEmpty = ioPins[0].getState(); + leftSensorEmpty = ioPins[1].getState(); - if (rightSensor && leftSensor) { + if (rightSensorEmpty && leftSensorEmpty) { if (walkState == WALK_WAITING) { System.out.println("Reset"); - walkState = WALK_WAITING; + walkState = WALK_NOTHING; rsCount = 0; lsCount = 0; } } if (walkState == WALK_NOTHING) { - if (!rightSensor && leftSensor) { + if (!rightSensorEmpty && leftSensorEmpty) { lsCount = lagTime; //System.out.println("WalkState 1"); walkState = WALK_LEFT; } - if (!leftSensor && rightSensor) { + if (!leftSensorEmpty && rightSensorEmpty) { //System.out.println("WalkState 2"); rsCount = lagTime; walkState = WALK_RIGHT; } - if (!leftSensor && !rightSensor) { + if (!leftSensorEmpty && !rightSensorEmpty) { walkState = WALK_WAITING; System.out.println("Too fast walk detected."); } } if (walkState == WALK_LEFT) { - if (!leftSensor) { + if (!leftSensorEmpty) { System.out.println("Walked left detected."); walkState = WALK_WAITING; lsCount = 0; } } if (walkState == WALK_RIGHT) { - if (!rightSensor) { + if (!rightSensorEmpty) { System.out.println("Walked right detected."); walkState = WALK_WAITING; rsCount = 0; } } if (rsCount > 0) { rsCount -= 1; } if (lsCount > 0) { lsCount -= 1; } if (rsCount == 0 && lsCount == 0 && (walkState == WALK_LEFT || walkState == WALK_RIGHT)) { System.out.print("Bad Event detected: "); System.out.println(walkState); walkState = WALK_WAITING; } // Go to sleep to conserve battery Utils.sleep(100); counter += 1; break; case STATE_TRANSMITTING: /*RadiostreamConnection conn = conn = (RadiostreamConnection)Connector.open("radiostream://"+DEST_MOTE+":100"); DataOutputStream dos = conn.openDataOutputStream(); try { dos.writeUTF("Hello"); dos.flush(); } catch (IOException e) { System.out.println ("Exception with connection to "+DEST_MOTE); } finally { dos.close(); conn.close(); }*/ break; } } } protected void pauseApp() { // This will never be called by the Squawk VM } protected void destroyApp(boolean arg0) throws MIDletStateChangeException { // Only called if startApp throws any exception other than MIDletStateChangeException } }
false
true
protected void startApp() throws MIDletStateChangeException { leds.setColor(colors[2]); leds.setOn(); Utils.sleep(1000); leds.setOff(); //This is in miliseconds. int readInterval = 500; int counter = 0; boolean rightSensor, leftSensor; // ITriColorLED[] leds = EDemoBoard.getInstance().getLEDs(); IIOPin[] ioPins = EDemoBoard.getInstance().getIOPins(); leds.getLED(7).setRGB(255, 255, 255); int walkState = WALK_NOTHING; // 0 = nothing, 1 = walkLeft 2 = walkRight 5 = wait for reset. int lagTime = 8; int lsCount, rsCount; rsCount = 0; lsCount = 0; while (true) { switch (state) { case STATE_INITIALIZING: System.out.println("Initializing"); state = STATE_SENSING; break; case STATE_SENSING: //Constant LED to indicate running if (counter % 10 == 0) { if (leds.getLED(7).isOn()) { leds.getLED(7).setOff(); } else { leds.getLED(7).setOn(); } } rightSensor = ioPins[0].getState(); leftSensor = ioPins[1].getState(); if (rightSensor && leftSensor) { if (walkState == WALK_WAITING) { System.out.println("Reset"); walkState = WALK_WAITING; rsCount = 0; lsCount = 0; } } if (walkState == WALK_NOTHING) { if (!rightSensor && leftSensor) { lsCount = lagTime; //System.out.println("WalkState 1"); walkState = WALK_LEFT; } if (!leftSensor && rightSensor) { //System.out.println("WalkState 2"); rsCount = lagTime; walkState = WALK_RIGHT; } if (!leftSensor && !rightSensor) { walkState = WALK_WAITING; System.out.println("Too fast walk detected."); } } if (walkState == WALK_LEFT) { if (!leftSensor) { System.out.println("Walked left detected."); walkState = WALK_WAITING; lsCount = 0; } } if (walkState == WALK_RIGHT) { if (!rightSensor) { System.out.println("Walked right detected."); walkState = WALK_WAITING; rsCount = 0; } } if (rsCount > 0) { rsCount -= 1; } if (lsCount > 0) { lsCount -= 1; } if (rsCount == 0 && lsCount == 0 && (walkState == WALK_LEFT || walkState == WALK_RIGHT)) { System.out.print("Bad Event detected: "); System.out.println(walkState); walkState = WALK_WAITING; } // Go to sleep to conserve battery Utils.sleep(100); counter += 1; break; case STATE_TRANSMITTING: /*RadiostreamConnection conn = conn = (RadiostreamConnection)Connector.open("radiostream://"+DEST_MOTE+":100"); DataOutputStream dos = conn.openDataOutputStream(); try { dos.writeUTF("Hello"); dos.flush(); } catch (IOException e) { System.out.println ("Exception with connection to "+DEST_MOTE); } finally { dos.close(); conn.close(); }*/ break; } } }
protected void startApp() throws MIDletStateChangeException { leds.setColor(colors[2]); leds.setOn(); Utils.sleep(1000); leds.setOff(); //This is in miliseconds. int readInterval = 500; int counter = 0; boolean rightSensorEmpty, leftSensorEmpty; // ITriColorLED[] leds = EDemoBoard.getInstance().getLEDs(); IIOPin[] ioPins = EDemoBoard.getInstance().getIOPins(); leds.getLED(7).setRGB(255, 255, 255); int walkState = WALK_NOTHING; // 0 = nothing, 1 = walkLeft 2 = walkRight 5 = wait for reset. int lagTime = 8; int lsCount, rsCount; rsCount = 0; lsCount = 0; while (true) { switch (state) { case STATE_INITIALIZING: System.out.println("Initializing"); state = STATE_SENSING; break; case STATE_SENSING: //Constant LED to indicate running if (counter % 10 == 0) { if (leds.getLED(7).isOn()) { leds.getLED(7).setOff(); } else { leds.getLED(7).setOn(); } } rightSensorEmpty = ioPins[0].getState(); leftSensorEmpty = ioPins[1].getState(); if (rightSensorEmpty && leftSensorEmpty) { if (walkState == WALK_WAITING) { System.out.println("Reset"); walkState = WALK_NOTHING; rsCount = 0; lsCount = 0; } } if (walkState == WALK_NOTHING) { if (!rightSensorEmpty && leftSensorEmpty) { lsCount = lagTime; //System.out.println("WalkState 1"); walkState = WALK_LEFT; } if (!leftSensorEmpty && rightSensorEmpty) { //System.out.println("WalkState 2"); rsCount = lagTime; walkState = WALK_RIGHT; } if (!leftSensorEmpty && !rightSensorEmpty) { walkState = WALK_WAITING; System.out.println("Too fast walk detected."); } } if (walkState == WALK_LEFT) { if (!leftSensorEmpty) { System.out.println("Walked left detected."); walkState = WALK_WAITING; lsCount = 0; } } if (walkState == WALK_RIGHT) { if (!rightSensorEmpty) { System.out.println("Walked right detected."); walkState = WALK_WAITING; rsCount = 0; } } if (rsCount > 0) { rsCount -= 1; } if (lsCount > 0) { lsCount -= 1; } if (rsCount == 0 && lsCount == 0 && (walkState == WALK_LEFT || walkState == WALK_RIGHT)) { System.out.print("Bad Event detected: "); System.out.println(walkState); walkState = WALK_WAITING; } // Go to sleep to conserve battery Utils.sleep(100); counter += 1; break; case STATE_TRANSMITTING: /*RadiostreamConnection conn = conn = (RadiostreamConnection)Connector.open("radiostream://"+DEST_MOTE+":100"); DataOutputStream dos = conn.openDataOutputStream(); try { dos.writeUTF("Hello"); dos.flush(); } catch (IOException e) { System.out.println ("Exception with connection to "+DEST_MOTE); } finally { dos.close(); conn.close(); }*/ break; } } }
diff --git a/chips/src/com/android/ex/chips/RecipientChip.java b/chips/src/com/android/ex/chips/RecipientChip.java index 41d950f..0f93a0d 100644 --- a/chips/src/com/android/ex/chips/RecipientChip.java +++ b/chips/src/com/android/ex/chips/RecipientChip.java @@ -1,112 +1,112 @@ /* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ex.chips; import android.graphics.drawable.Drawable; import android.text.TextUtils; import android.text.style.DynamicDrawableSpan; import android.text.style.ImageSpan; /** * RecipientChip defines an ImageSpan that contains information relevant to a * particular recipient. */ /* package */class RecipientChip extends ImageSpan { private final CharSequence mDisplay; private final CharSequence mValue; private final long mContactId; private final long mDataId; private RecipientEntry mEntry; private boolean mSelected = false; private CharSequence mOriginalText; public RecipientChip(Drawable drawable, RecipientEntry entry, int offset) { - super(drawable, DynamicDrawableSpan.ALIGN_BASELINE); + super(drawable, DynamicDrawableSpan.ALIGN_BOTTOM); mDisplay = entry.getDisplayName(); mValue = entry.getDestination().trim(); mContactId = entry.getContactId(); mDataId = entry.getDataId(); mEntry = entry; } /** * Set the selected state of the chip. * @param selected */ public void setSelected(boolean selected) { mSelected = selected; } /** * Return true if the chip is selected. */ public boolean isSelected() { return mSelected; } /** * Get the text displayed in the chip. */ public CharSequence getDisplay() { return mDisplay; } /** * Get the text value this chip represents. */ public CharSequence getValue() { return mValue; } /** * Get the id of the contact associated with this chip. */ public long getContactId() { return mContactId; } /** * Get the id of the data associated with this chip. */ public long getDataId() { return mDataId; } /** * Get associated RecipientEntry. */ public RecipientEntry getEntry() { return mEntry; } public void setOriginalText(String text) { if (!TextUtils.isEmpty(text)) { text = text.trim(); } mOriginalText = text; } public CharSequence getOriginalText() { return !TextUtils.isEmpty(mOriginalText) ? mOriginalText : mEntry.getDestination(); } }
true
true
public RecipientChip(Drawable drawable, RecipientEntry entry, int offset) { super(drawable, DynamicDrawableSpan.ALIGN_BASELINE); mDisplay = entry.getDisplayName(); mValue = entry.getDestination().trim(); mContactId = entry.getContactId(); mDataId = entry.getDataId(); mEntry = entry; }
public RecipientChip(Drawable drawable, RecipientEntry entry, int offset) { super(drawable, DynamicDrawableSpan.ALIGN_BOTTOM); mDisplay = entry.getDisplayName(); mValue = entry.getDestination().trim(); mContactId = entry.getContactId(); mDataId = entry.getDataId(); mEntry = entry; }
diff --git a/src/main/java/edu/gwu/raminfar/wiki/WikiSearch.java b/src/main/java/edu/gwu/raminfar/wiki/WikiSearch.java index 2c52437..e516d20 100644 --- a/src/main/java/edu/gwu/raminfar/wiki/WikiSearch.java +++ b/src/main/java/edu/gwu/raminfar/wiki/WikiSearch.java @@ -1,52 +1,52 @@ package edu.gwu.raminfar.wiki; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; import java.util.Collection; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; /** * Author: Amir Raminfar * Date: Oct 21, 2010 */ public class WikiSearch { private final static String SEARCH_URL = "http://en.wikipedia.org/w/index.php?search=%s&fulltext=Search"; private final String query; public WikiSearch(String query) { this.query = query.replaceAll(" ", "+").replaceAll("&", "%26"); } public Collection<WikiPage> parseResults() throws IOException { return parseResults(10); } - public Collection<WikiPage> parseResults(int max) throws IOException { + public Set<WikiPage> parseResults(int max) throws IOException { Set<WikiPage> results = new LinkedHashSet<WikiPage>(); String url = String.format(SEARCH_URL, query); Document doc = Jsoup.connect(url).get(); Elements elements = doc.select("ul.mw-search-results a"); - for (int i = 0, elementsSize = elements.size(); i < elementsSize && i < max; i++) { + for (int i = 0, elementsSize = elements.size(); i < elementsSize && results.size() < max; i++) { Element e = elements.get(i); WikiPage page = new WikiPage(e.absUrl("href")); if (!results.contains(page)) { results.add(page); } } return results; } public String getQuery() { return query; } }
false
true
public Collection<WikiPage> parseResults(int max) throws IOException { Set<WikiPage> results = new LinkedHashSet<WikiPage>(); String url = String.format(SEARCH_URL, query); Document doc = Jsoup.connect(url).get(); Elements elements = doc.select("ul.mw-search-results a"); for (int i = 0, elementsSize = elements.size(); i < elementsSize && i < max; i++) { Element e = elements.get(i); WikiPage page = new WikiPage(e.absUrl("href")); if (!results.contains(page)) { results.add(page); } } return results; }
public Set<WikiPage> parseResults(int max) throws IOException { Set<WikiPage> results = new LinkedHashSet<WikiPage>(); String url = String.format(SEARCH_URL, query); Document doc = Jsoup.connect(url).get(); Elements elements = doc.select("ul.mw-search-results a"); for (int i = 0, elementsSize = elements.size(); i < elementsSize && results.size() < max; i++) { Element e = elements.get(i); WikiPage page = new WikiPage(e.absUrl("href")); if (!results.contains(page)) { results.add(page); } } return results; }
diff --git a/src/com/fsck/k9/helper/MergeCursor.java b/src/com/fsck/k9/helper/MergeCursor.java index 39776e64..3325a6e3 100644 --- a/src/com/fsck/k9/helper/MergeCursor.java +++ b/src/com/fsck/k9/helper/MergeCursor.java @@ -1,463 +1,463 @@ /* * Copyright (C) 2012 The K-9 Dog Walkers * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.fsck.k9.helper; import java.util.Comparator; import android.annotation.TargetApi; import android.content.ContentResolver; import android.database.CharArrayBuffer; import android.database.ContentObserver; import android.database.Cursor; import android.database.DataSetObserver; import android.net.Uri; import android.os.Bundle; /** * This class can be used to combine multiple {@link Cursor}s into one. */ public class MergeCursor implements Cursor { /** * List of the cursors combined in this object. */ protected final Cursor[] mCursors; /** * The currently active cursor. */ protected Cursor mActiveCursor; /** * The index of the currently active cursor in {@link #mCursors}. * * @see #mActiveCursor */ protected int mActiveCursorIndex; /** * The cursor's current position. */ protected int mPosition; /** * Used to cache the value of {@link #getCount()}. */ private int mCount = -1; /** * The comparator that is used to decide how the individual cursors are merged. */ private final Comparator<Cursor> mComparator; /** * Constructor * * @param cursors * The list of cursors this {@code MultiCursor} should combine. * @param comparator * A comparator that is used to decide in what order the individual cursors are merged. */ public MergeCursor(Cursor[] cursors, Comparator<Cursor> comparator) { mCursors = cursors.clone(); mComparator = comparator; resetCursors(); } private void resetCursors() { mActiveCursorIndex = -1; mActiveCursor = null; mPosition = -1; for (int i = 0, len = mCursors.length; i < len; i++) { Cursor cursor = mCursors[i]; if (cursor != null) { cursor.moveToPosition(-1); if (mActiveCursor == null) { mActiveCursorIndex = i; mActiveCursor = mCursors[mActiveCursorIndex]; } } } } @Override public void close() { for (Cursor cursor : mCursors) { if (cursor != null) { cursor.close(); } } } @Override public void copyStringToBuffer(int columnIndex, CharArrayBuffer buffer) { mActiveCursor.copyStringToBuffer(columnIndex, buffer); } @Override public void deactivate() { for (Cursor cursor : mCursors) { if (cursor != null) { cursor.deactivate(); } } } @Override public byte[] getBlob(int columnIndex) { return mActiveCursor.getBlob(columnIndex); } @Override public int getColumnCount() { return mActiveCursor.getColumnCount(); } @Override public int getColumnIndex(String columnName) { return mActiveCursor.getColumnIndex(columnName); } @Override public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException { return mActiveCursor.getColumnIndexOrThrow(columnName); } @Override public String getColumnName(int columnIndex) { return mActiveCursor.getColumnName(columnIndex); } @Override public String[] getColumnNames() { return mActiveCursor.getColumnNames(); } @Override public int getCount() { // CursorLoaders seem to call getCount() a lot. So we're caching the aggregated count. if (mCount == -1) { int count = 0; for (Cursor cursor : mCursors) { if (cursor != null) { count += cursor.getCount(); } } mCount = count; } return mCount; } @Override public double getDouble(int columnIndex) { return mActiveCursor.getDouble(columnIndex); } @Override public float getFloat(int columnIndex) { return mActiveCursor.getFloat(columnIndex); } @Override public int getInt(int columnIndex) { return mActiveCursor.getInt(columnIndex); } @Override public long getLong(int columnIndex) { return mActiveCursor.getLong(columnIndex); } @Override public int getPosition() { return mPosition; } @Override public short getShort(int columnIndex) { return mActiveCursor.getShort(columnIndex); } @Override public String getString(int columnIndex) { return mActiveCursor.getString(columnIndex); } @TargetApi(11) @Override public int getType(int columnIndex) { return mActiveCursor.getType(columnIndex); } @Override public boolean getWantsAllOnMoveCalls() { return mActiveCursor.getWantsAllOnMoveCalls(); } @Override public boolean isAfterLast() { int count = getCount(); if (count == 0) { return true; } return (mPosition == count); } @Override public boolean isBeforeFirst() { if (getCount() == 0) { return true; } return (mPosition == -1); } @Override public boolean isClosed() { return mActiveCursor.isClosed(); } @Override public boolean isFirst() { if (getCount() == 0) { return false; } return (mPosition == 0); } @Override public boolean isLast() { int count = getCount(); if (count == 0) { return false; } return (mPosition == (count - 1)); } @Override public boolean isNull(int columnIndex) { return mActiveCursor.isNull(columnIndex); } @Override public boolean move(int offset) { return moveToPosition(mPosition + offset); } @Override public boolean moveToFirst() { return moveToPosition(0); } @Override public boolean moveToLast() { return moveToPosition(getCount() - 1); } @Override public boolean moveToNext() { int count = getCount(); if (mPosition == count) { return false; } if (mPosition == count - 1) { mActiveCursor.moveToNext(); mPosition++; return false; } int smallest = -1; for (int i = 0, len = mCursors.length; i < len; i++) { - if (mCursors[i] == null || mCursors[i].isLast()) { + if (mCursors[i] == null || mCursors[i].getCount() == 0 || mCursors[i].isLast()) { continue; } if (smallest == -1) { smallest = i; mCursors[smallest].moveToNext(); continue; } Cursor left = mCursors[smallest]; Cursor right = mCursors[i]; right.moveToNext(); int result = mComparator.compare(left, right); if (result > 0) { smallest = i; left.moveToPrevious(); } else { right.moveToPrevious(); } } mPosition++; if (smallest != -1) { mActiveCursorIndex = smallest; mActiveCursor = mCursors[mActiveCursorIndex]; } return true; } @Override public boolean moveToPosition(int position) { // Make sure position isn't past the end of the cursor final int count = getCount(); if (position >= count) { mPosition = count; return false; } // Make sure position isn't before the beginning of the cursor if (position < 0) { mPosition = -1; return false; } // Check for no-op moves, and skip the rest of the work for them if (position == mPosition) { return true; } if (position > mPosition) { for (int i = 0, end = position - mPosition; i < end; i++) { if (!moveToNext()) { return false; } } } else { for (int i = 0, end = mPosition - position; i < end; i++) { if (!moveToPrevious()) { return false; } } } return true; } @Override public boolean moveToPrevious() { if (mPosition < 0) { return false; } mActiveCursor.moveToPrevious(); if (mPosition == 0) { mPosition = -1; return false; } int greatest = -1; for (int i = 0, len = mCursors.length; i < len; i++) { if (mCursors[i] == null || mCursors[i].isBeforeFirst()) { continue; } if (greatest == -1) { greatest = i; continue; } Cursor left = mCursors[greatest]; Cursor right = mCursors[i]; int result = mComparator.compare(left, right); if (result <= 0) { greatest = i; } } mPosition--; if (greatest != -1) { mActiveCursorIndex = greatest; mActiveCursor = mCursors[mActiveCursorIndex]; } return true; } @Override public void registerContentObserver(ContentObserver observer) { for (Cursor cursor : mCursors) { cursor.registerContentObserver(observer); } } @Override public void registerDataSetObserver(DataSetObserver observer) { for (Cursor cursor : mCursors) { cursor.registerDataSetObserver(observer); } } @Deprecated @Override public boolean requery() { boolean success = true; for (Cursor cursor : mCursors) { success &= cursor.requery(); } return success; } @Override public void setNotificationUri(ContentResolver cr, Uri uri) { for (Cursor cursor : mCursors) { cursor.setNotificationUri(cr, uri); } } @Override public void unregisterContentObserver(ContentObserver observer) { for (Cursor cursor : mCursors) { cursor.unregisterContentObserver(observer); } } @Override public void unregisterDataSetObserver(DataSetObserver observer) { for (Cursor cursor : mCursors) { cursor.unregisterDataSetObserver(observer); } } @Override public Bundle getExtras() { throw new RuntimeException("Not implemented"); } @Override public Bundle respond(Bundle extras) { throw new RuntimeException("Not implemented"); } }
true
true
public boolean moveToNext() { int count = getCount(); if (mPosition == count) { return false; } if (mPosition == count - 1) { mActiveCursor.moveToNext(); mPosition++; return false; } int smallest = -1; for (int i = 0, len = mCursors.length; i < len; i++) { if (mCursors[i] == null || mCursors[i].isLast()) { continue; } if (smallest == -1) { smallest = i; mCursors[smallest].moveToNext(); continue; } Cursor left = mCursors[smallest]; Cursor right = mCursors[i]; right.moveToNext(); int result = mComparator.compare(left, right); if (result > 0) { smallest = i; left.moveToPrevious(); } else { right.moveToPrevious(); } } mPosition++; if (smallest != -1) { mActiveCursorIndex = smallest; mActiveCursor = mCursors[mActiveCursorIndex]; } return true; }
public boolean moveToNext() { int count = getCount(); if (mPosition == count) { return false; } if (mPosition == count - 1) { mActiveCursor.moveToNext(); mPosition++; return false; } int smallest = -1; for (int i = 0, len = mCursors.length; i < len; i++) { if (mCursors[i] == null || mCursors[i].getCount() == 0 || mCursors[i].isLast()) { continue; } if (smallest == -1) { smallest = i; mCursors[smallest].moveToNext(); continue; } Cursor left = mCursors[smallest]; Cursor right = mCursors[i]; right.moveToNext(); int result = mComparator.compare(left, right); if (result > 0) { smallest = i; left.moveToPrevious(); } else { right.moveToPrevious(); } } mPosition++; if (smallest != -1) { mActiveCursorIndex = smallest; mActiveCursor = mCursors[mActiveCursorIndex]; } return true; }
diff --git a/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java b/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java index 76624c6..b9aa769 100644 --- a/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java +++ b/src/main/java/com/github/kpacha/jkata/tennis/Tennis.java @@ -1,39 +1,39 @@ package com.github.kpacha.jkata.tennis; public class Tennis { private int playerOneScored = 0; private int playerTwoScored = 0; public String getScore() { if (isDeuce()) return "Deuce"; if (isAdvantagePlayerOne()) return "Advantage Player 1"; if (isAdvantagePlayerTwo()) return "Advantage Player 2"; - if (playerOneScored == 4) + if (playerOneScored > 3 && playerOneScored > playerTwoScored + 1) return "Player 1 wins"; return (15 * playerOneScored) + " - " + (15 * playerTwoScored); } private boolean isAdvantagePlayerOne() { return playerOneScored == playerTwoScored + 1 && playerOneScored > 3; } private boolean isAdvantagePlayerTwo() { return playerOneScored + 1 == playerTwoScored && playerTwoScored > 3; } private boolean isDeuce() { return playerOneScored == playerTwoScored && playerTwoScored > 2; } public void playerOneScores() { playerOneScored++; } public void playerTwoScores() { playerTwoScored++; } }
true
true
public String getScore() { if (isDeuce()) return "Deuce"; if (isAdvantagePlayerOne()) return "Advantage Player 1"; if (isAdvantagePlayerTwo()) return "Advantage Player 2"; if (playerOneScored == 4) return "Player 1 wins"; return (15 * playerOneScored) + " - " + (15 * playerTwoScored); }
public String getScore() { if (isDeuce()) return "Deuce"; if (isAdvantagePlayerOne()) return "Advantage Player 1"; if (isAdvantagePlayerTwo()) return "Advantage Player 2"; if (playerOneScored > 3 && playerOneScored > playerTwoScored + 1) return "Player 1 wins"; return (15 * playerOneScored) + " - " + (15 * playerTwoScored); }
diff --git a/src/org/eclipse/cdt/internal/core/ConsoleOutputSniffer.java b/src/org/eclipse/cdt/internal/core/ConsoleOutputSniffer.java index fcedffdc0..7506011b6 100644 --- a/src/org/eclipse/cdt/internal/core/ConsoleOutputSniffer.java +++ b/src/org/eclipse/cdt/internal/core/ConsoleOutputSniffer.java @@ -1,182 +1,188 @@ /******************************************************************************* * Copyright (c) 2004, 2005 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM - Initial API and implementation *******************************************************************************/ package org.eclipse.cdt.internal.core; import java.io.IOException; import java.io.OutputStream; import org.eclipse.cdt.core.IConsoleParser; /** * Intercepts an output to console and forwards it to console parsers for processing * * @author vhirsl */ public class ConsoleOutputSniffer { /* * Private class to sniffer the output stream for this snifffer. */ private class ConsoleOutputStream extends OutputStream { // Stream's private buffer for the stream's read contents. private StringBuffer currentLine = new StringBuffer(); private OutputStream outputStream = null; /** * @param consoleErrorStream */ public ConsoleOutputStream(OutputStream outputStream) { this.outputStream = outputStream; } /* (non-Javadoc) * @see java.io.OutputStream#write(int) */ public void write(int b) throws IOException { currentLine.append((char) b); checkLine(false); // Continue writing the bytes to the console's output. if (outputStream != null) { outputStream.write(b); } } /* (non-Javadoc) * @see java.io.OutputStream#write(byte[], int, int) */ public void write(byte[] b, int off, int len) throws IOException { if (b == null) { throw new NullPointerException(); } else if (off != 0 || (len < 0) || (len > b.length)) { throw new IndexOutOfBoundsException(); } else if (len == 0) { return; } currentLine.append(new String(b, 0, len)); checkLine(false); // Continue writing the bytes to the console's output. if (outputStream != null) outputStream.write(b, off, len); } /* (non-Javadoc) * @see java.io.OutputStream#close() */ public void close() throws IOException { checkLine(true); closeConsoleOutputStream(); } /* (non-Javadoc) * @see java.io.OutputStream#flush() */ public void flush() throws IOException { if (outputStream != null) { outputStream.flush(); } } /* * Checks to see if the already read input constitutes * a complete line (e.g. does the sniffing). If so, then * send it to processLine. * * @param flush */ private void checkLine(boolean flush) { String buffer = currentLine.toString(); int i = 0; while ((i = buffer.indexOf('\n')) != -1) { - String line = buffer.substring(0, i).trim(); // get rid of any trailing \r - if (line.length() > 0) + // get rid of any trailing whitespace but keep leading whitespaces (bug 199245) + int end= i; + while(end > 0 && buffer.charAt(end-1) <= ' ') { // see String.trim() + end--; + } + if (end > 0) { + String line = buffer.substring(0, end); processLine(line); + } buffer = buffer.substring(i + 1); // skip the \n and advance } currentLine.setLength(0); if (flush) { if (buffer.length() > 0) { processLine(buffer); } } else { currentLine.append(buffer); } } } // end ConsoleOutputStream class private int nOpens = 0; private OutputStream consoleOutputStream; private OutputStream consoleErrorStream; private IConsoleParser[] parsers; public ConsoleOutputSniffer(IConsoleParser[] parsers) { this.parsers = parsers; } public ConsoleOutputSniffer(OutputStream outputStream, OutputStream errorStream, IConsoleParser[] parsers) { this(parsers); this.consoleOutputStream = outputStream; this.consoleErrorStream = errorStream; } /** * Returns an output stream that will be sniffed. * This stream should be hooked up so the command * output stream goes into here. * * @return */ public OutputStream getOutputStream() { incNOpens(); return new ConsoleOutputStream(consoleOutputStream); } /** * Returns an error stream that will be sniffed. * This stream should be hooked up so the command * error stream goes into here. * * @return */ public OutputStream getErrorStream() { incNOpens(); return new ConsoleOutputStream(consoleErrorStream); } private synchronized void incNOpens() { nOpens++; } /* */ public synchronized void closeConsoleOutputStream() throws IOException { if (nOpens > 0 && --nOpens == 0) { for (int i = 0; i < parsers.length; ++i) { parsers[i].shutdown(); } } } /* * Processes the line by passing the line to the parsers. * * @param line */ private synchronized void processLine(String line) { for (int i = 0; i < parsers.length; ++i) { parsers[i].processLine(line); } } }
false
true
private void checkLine(boolean flush) { String buffer = currentLine.toString(); int i = 0; while ((i = buffer.indexOf('\n')) != -1) { String line = buffer.substring(0, i).trim(); // get rid of any trailing \r if (line.length() > 0) processLine(line); buffer = buffer.substring(i + 1); // skip the \n and advance } currentLine.setLength(0); if (flush) { if (buffer.length() > 0) { processLine(buffer); } } else { currentLine.append(buffer); } }
private void checkLine(boolean flush) { String buffer = currentLine.toString(); int i = 0; while ((i = buffer.indexOf('\n')) != -1) { // get rid of any trailing whitespace but keep leading whitespaces (bug 199245) int end= i; while(end > 0 && buffer.charAt(end-1) <= ' ') { // see String.trim() end--; } if (end > 0) { String line = buffer.substring(0, end); processLine(line); } buffer = buffer.substring(i + 1); // skip the \n and advance } currentLine.setLength(0); if (flush) { if (buffer.length() > 0) { processLine(buffer); } } else { currentLine.append(buffer); } }
diff --git a/surveyor/src/main/java/org/cpower/surveyor/CanadianTireSurvey.java b/surveyor/src/main/java/org/cpower/surveyor/CanadianTireSurvey.java index a8ec59f..f76e53a 100644 --- a/surveyor/src/main/java/org/cpower/surveyor/CanadianTireSurvey.java +++ b/surveyor/src/main/java/org/cpower/surveyor/CanadianTireSurvey.java @@ -1,76 +1,76 @@ package org.cpower.surveyor; import java.util.Map; import org.openqa.selenium.*; public class CanadianTireSurvey extends Survey { public CanadianTireSurvey(Map<String, String> map) { super(map); } @Override public void submit() throws Exception { driver.get("http://ww16.empathica.com/sxml/cantire/retailSurvey/landing.jsp"); driver.findElement(By.cssSelector("img")).click(); String[] time = map.get(TIME).split(":"); driver.findElement(By.id("tf_Hour")).clear(); driver.findElement(By.id("tf_Hour")).sendKeys(time[0]); driver.findElement(By.id("tf_Min")).clear(); driver.findElement(By.id("tf_Min")).sendKeys(time[1]); String[] price = map.get(PRICE).split("\\."); driver.findElement(By.id("tf_Dollar")).clear(); driver.findElement(By.id("tf_Dollar")).sendKeys(price[0]); driver.findElement(By.id("tf_Cent")).clear(); - driver.findElement(By.id("tf_Cent")).sendKeys(price[0]); + driver.findElement(By.id("tf_Cent")).sendKeys(price[1]); String[] code = map.get(CODE).split("-"); driver.findElement(By.id("tf_csi1")).clear(); driver.findElement(By.id("tf_csi1")).sendKeys(code[0]); driver.findElement(By.id("tf_csi2")).clear(); driver.findElement(By.id("tf_csi2")).sendKeys(code[1]); driver.findElement(By.id("tf_csi3")).clear(); driver.findElement(By.id("tf_csi3")).sendKeys(code[2]); driver.findElement(By.id("tf_csi4")).clear(); driver.findElement(By.id("tf_csi4")).sendKeys(code[3]); driver.findElement(By.cssSelector("#apDiv8 > a > img")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='SERVICE_VEHICLE'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='OV_SAT_NEW'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='SELF_CASH'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.name("CASHIER_THANKYOU")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='TEAM_CARE'])[3]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='EMPLOYEE_WOW'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='ADDITIONAL_QUESTIONS'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.name("GENDER")).click(); driver.findElement(By.name("AGE")).clear(); driver.findElement(By.name("AGE")).sendKeys("1982"); driver.findElement(By.xpath("(//input[@name='INCOME'])[6]")).click(); driver.findElement(By.xpath("(//input[@name='CHILDRENUAGE'])[2]")).click(); driver.findElement(By.xpath("(//input[@name='CTCREDITCARD'])[2]")).click(); driver.findElement(By.xpath("(//input[@name='PAYWITH'])[3]")).click(); driver.findElement(By.xpath("(//input[@name='CTROADASSISTMEMBER'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.name("FirstName")).clear(); driver.findElement(By.name("FirstName")).sendKeys(map.get(FIRST_NAME)); driver.findElement(By.name("LastName")).clear(); driver.findElement(By.name("LastName")).sendKeys(map.get(LAST_NAME)); driver.findElement(By.name("PostCode")).clear(); driver.findElement(By.name("PostCode")).sendKeys(map.get(POSTAL_CODE)); driver.findElement(By.name("TelephoneAreaCode")).clear(); driver.findElement(By.name("TelephoneAreaCode")).sendKeys(map.get(PHONE_AREA)); driver.findElement(By.name("TelephoneNumber")).clear(); driver.findElement(By.name("TelephoneNumber")).sendKeys(map.get(PHONE_LOCAL)); driver.findElement(By.cssSelector("img[alt=\"Send\"]")).click(); } }
true
true
public void submit() throws Exception { driver.get("http://ww16.empathica.com/sxml/cantire/retailSurvey/landing.jsp"); driver.findElement(By.cssSelector("img")).click(); String[] time = map.get(TIME).split(":"); driver.findElement(By.id("tf_Hour")).clear(); driver.findElement(By.id("tf_Hour")).sendKeys(time[0]); driver.findElement(By.id("tf_Min")).clear(); driver.findElement(By.id("tf_Min")).sendKeys(time[1]); String[] price = map.get(PRICE).split("\\."); driver.findElement(By.id("tf_Dollar")).clear(); driver.findElement(By.id("tf_Dollar")).sendKeys(price[0]); driver.findElement(By.id("tf_Cent")).clear(); driver.findElement(By.id("tf_Cent")).sendKeys(price[0]); String[] code = map.get(CODE).split("-"); driver.findElement(By.id("tf_csi1")).clear(); driver.findElement(By.id("tf_csi1")).sendKeys(code[0]); driver.findElement(By.id("tf_csi2")).clear(); driver.findElement(By.id("tf_csi2")).sendKeys(code[1]); driver.findElement(By.id("tf_csi3")).clear(); driver.findElement(By.id("tf_csi3")).sendKeys(code[2]); driver.findElement(By.id("tf_csi4")).clear(); driver.findElement(By.id("tf_csi4")).sendKeys(code[3]); driver.findElement(By.cssSelector("#apDiv8 > a > img")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='SERVICE_VEHICLE'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='OV_SAT_NEW'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='SELF_CASH'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.name("CASHIER_THANKYOU")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='TEAM_CARE'])[3]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='EMPLOYEE_WOW'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='ADDITIONAL_QUESTIONS'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.name("GENDER")).click(); driver.findElement(By.name("AGE")).clear(); driver.findElement(By.name("AGE")).sendKeys("1982"); driver.findElement(By.xpath("(//input[@name='INCOME'])[6]")).click(); driver.findElement(By.xpath("(//input[@name='CHILDRENUAGE'])[2]")).click(); driver.findElement(By.xpath("(//input[@name='CTCREDITCARD'])[2]")).click(); driver.findElement(By.xpath("(//input[@name='PAYWITH'])[3]")).click(); driver.findElement(By.xpath("(//input[@name='CTROADASSISTMEMBER'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.name("FirstName")).clear(); driver.findElement(By.name("FirstName")).sendKeys(map.get(FIRST_NAME)); driver.findElement(By.name("LastName")).clear(); driver.findElement(By.name("LastName")).sendKeys(map.get(LAST_NAME)); driver.findElement(By.name("PostCode")).clear(); driver.findElement(By.name("PostCode")).sendKeys(map.get(POSTAL_CODE)); driver.findElement(By.name("TelephoneAreaCode")).clear(); driver.findElement(By.name("TelephoneAreaCode")).sendKeys(map.get(PHONE_AREA)); driver.findElement(By.name("TelephoneNumber")).clear(); driver.findElement(By.name("TelephoneNumber")).sendKeys(map.get(PHONE_LOCAL)); driver.findElement(By.cssSelector("img[alt=\"Send\"]")).click(); }
public void submit() throws Exception { driver.get("http://ww16.empathica.com/sxml/cantire/retailSurvey/landing.jsp"); driver.findElement(By.cssSelector("img")).click(); String[] time = map.get(TIME).split(":"); driver.findElement(By.id("tf_Hour")).clear(); driver.findElement(By.id("tf_Hour")).sendKeys(time[0]); driver.findElement(By.id("tf_Min")).clear(); driver.findElement(By.id("tf_Min")).sendKeys(time[1]); String[] price = map.get(PRICE).split("\\."); driver.findElement(By.id("tf_Dollar")).clear(); driver.findElement(By.id("tf_Dollar")).sendKeys(price[0]); driver.findElement(By.id("tf_Cent")).clear(); driver.findElement(By.id("tf_Cent")).sendKeys(price[1]); String[] code = map.get(CODE).split("-"); driver.findElement(By.id("tf_csi1")).clear(); driver.findElement(By.id("tf_csi1")).sendKeys(code[0]); driver.findElement(By.id("tf_csi2")).clear(); driver.findElement(By.id("tf_csi2")).sendKeys(code[1]); driver.findElement(By.id("tf_csi3")).clear(); driver.findElement(By.id("tf_csi3")).sendKeys(code[2]); driver.findElement(By.id("tf_csi4")).clear(); driver.findElement(By.id("tf_csi4")).sendKeys(code[3]); driver.findElement(By.cssSelector("#apDiv8 > a > img")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='SERVICE_VEHICLE'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='OV_SAT_NEW'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='SELF_CASH'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.name("CASHIER_THANKYOU")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='TEAM_CARE'])[3]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='EMPLOYEE_WOW'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.xpath("(//input[@name='ADDITIONAL_QUESTIONS'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.name("GENDER")).click(); driver.findElement(By.name("AGE")).clear(); driver.findElement(By.name("AGE")).sendKeys("1982"); driver.findElement(By.xpath("(//input[@name='INCOME'])[6]")).click(); driver.findElement(By.xpath("(//input[@name='CHILDRENUAGE'])[2]")).click(); driver.findElement(By.xpath("(//input[@name='CTCREDITCARD'])[2]")).click(); driver.findElement(By.xpath("(//input[@name='PAYWITH'])[3]")).click(); driver.findElement(By.xpath("(//input[@name='CTROADASSISTMEMBER'])[2]")).click(); driver.findElement(By.cssSelector("img[alt=\"Next\"]")).click(); driver.findElement(By.name("FirstName")).clear(); driver.findElement(By.name("FirstName")).sendKeys(map.get(FIRST_NAME)); driver.findElement(By.name("LastName")).clear(); driver.findElement(By.name("LastName")).sendKeys(map.get(LAST_NAME)); driver.findElement(By.name("PostCode")).clear(); driver.findElement(By.name("PostCode")).sendKeys(map.get(POSTAL_CODE)); driver.findElement(By.name("TelephoneAreaCode")).clear(); driver.findElement(By.name("TelephoneAreaCode")).sendKeys(map.get(PHONE_AREA)); driver.findElement(By.name("TelephoneNumber")).clear(); driver.findElement(By.name("TelephoneNumber")).sendKeys(map.get(PHONE_LOCAL)); driver.findElement(By.cssSelector("img[alt=\"Send\"]")).click(); }
diff --git a/stripes/src/net/sourceforge/stripes/action/OnwardResolution.java b/stripes/src/net/sourceforge/stripes/action/OnwardResolution.java index 087dd0c5..21ba6143 100644 --- a/stripes/src/net/sourceforge/stripes/action/OnwardResolution.java +++ b/stripes/src/net/sourceforge/stripes/action/OnwardResolution.java @@ -1,175 +1,179 @@ /* Copyright 2005-2006 Tim Fennell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sourceforge.stripes.action; import java.util.HashMap; import java.util.Locale; import java.util.Map; import net.sourceforge.stripes.controller.StripesFilter; import net.sourceforge.stripes.format.Formatter; import net.sourceforge.stripes.util.UrlBuilder; /** * <p>Abstract class that provides a consistent API for all Resolutions that send the user onward to * another view - either by forwarding, redirecting or some other mechanism. Provides methods * for getting and setting the path that the user should be sent to next.</p> * * <p>The rather odd looking generic declaration on this class is called a self-bounding generic * type. The declaration allows methods in this class like {@link #addParameter(String, Object...)} * to return the appropriate type when accessed through subclasses. I.e. * {@code RedirectResolution.addParameter(String, Object...)} will return a reference of type * RedirectResolution instead of OnwardResolution.</p> * * @author Tim Fennell */ public abstract class OnwardResolution<T extends OnwardResolution<T>> { private String path; private Map<String,Object> parameters = new HashMap<String,Object>(); /** * Default constructor that takes the supplied path and stores it for use. * @param path the path to which the resolution should navigate */ public OnwardResolution(String path) { this.path = path; } /** * Constructor that will extract the url binding for the ActionBean class supplied and * use that as the path for the resolution. * * @param beanType a Class that represents an ActionBean */ public OnwardResolution(Class<? extends ActionBean> beanType) { this(StripesFilter.getConfiguration().getActionResolver().getUrlBinding(beanType)); } /** * Constructor that will extract the url binding for the ActionBean class supplied and * use that as the path for the resolution and adds a parameter to ensure that the * specified event is invoked. * * @param beanType a Class that represents an ActionBean * @param event the String name of the event to trigger on navigation */ public OnwardResolution(Class<? extends ActionBean> beanType, String event) { this(beanType); addParameter(event); } /** Accessor for the path that the user should be sent to. */ public String getPath() { return path; } /** Setter for the path that the user should be sent to. */ public void setPath(String path) { this.path = path; } /** * Method that will work for this class and subclasses; returns a String containing the * class name, and the path to which it will send the user. */ @Override public String toString() { return getClass().getSimpleName() + "{" + "path='" + path + "'" + "}"; } /** * <p>Adds a request parameter with zero or more values to the URL. Values may * be supplied using varargs, or alternatively by suppling a single value parameter which is * an instance of Collection.</p> * * <p>Note that this method is additive. Therefore writing things like * {@code builder.addParameter("p", "one").addParameter("p", "two");} * will add both {@code p=one} and {@code p=two} to the URL.</p> * * @param name the name of the URL parameter * @param values zero or more scalar values, or a single Collection * @return this Resolution so that methods can be chained */ @SuppressWarnings("unchecked") public T addParameter(String name, Object... values) { if (this.parameters.containsKey(name)) { - this.parameters.put(name, new Object[] {this.parameters.get(name), values}); + Object[] src = (Object[]) this.parameters.get(name); + Object[] dst = new Object[src.length + values.length]; + System.arraycopy(src, 0, dst, 0, src.length); + System.arraycopy(values, 0, dst, src.length, values.length); + this.parameters.put(name, dst); } else { this.parameters.put(name, values); } return (T) this; } /** * <p>Bulk adds one or more request parameters to the URL. Each entry in the Map * represents a single named parameter, with the values being either a scalar value, * an array or a Collection.</p> * * <p>Note that this method is additive. If a parameter with name X has already been * added and the map contains X as a key, the value(s) in the map will be added to the * URL as well as the previously held values for X.</p> * * @param parameters a Map of parameters as described above * @return this Resolution so that methods can be chained */ @SuppressWarnings("unchecked") public T addParameters(Map<String,? extends Object> parameters) { for (Map.Entry<String,? extends Object> entry : parameters.entrySet()) { addParameter(entry.getKey(), entry.getValue()); } return (T) this; } /** * <p>Provides access to the Map of parameters that has been accumulated so far * for this resolution. The reference returned is to the internal parameters * map! As such any changed made to the Map will be reflected in the Resolution, * and any subsequent calls to addParameter(s) will be reflected in the Map.</p> * * @return the Map of parameters for the resolution */ public Map<String, Object> getParameters() { return parameters; } /** * Constructs the URL for the resolution by taking the path and appending * any parameters supplied. * * @deprecated As of Stripes 1.5, this method has been replaced by * {@link #getUrl(Locale)}. */ @Deprecated public String getUrl() { return getUrl(Locale.getDefault()); } /** * Constructs the URL for the resolution by taking the path and appending any parameters * supplied. * * @param locale the locale to be used by {@link Formatter}s when formatting parameters */ public String getUrl(Locale locale) { UrlBuilder builder = new UrlBuilder(locale, path, false); builder.addParameters(this.parameters); return builder.toString(); } }
true
true
public T addParameter(String name, Object... values) { if (this.parameters.containsKey(name)) { this.parameters.put(name, new Object[] {this.parameters.get(name), values}); } else { this.parameters.put(name, values); } return (T) this; }
public T addParameter(String name, Object... values) { if (this.parameters.containsKey(name)) { Object[] src = (Object[]) this.parameters.get(name); Object[] dst = new Object[src.length + values.length]; System.arraycopy(src, 0, dst, 0, src.length); System.arraycopy(values, 0, dst, src.length, values.length); this.parameters.put(name, dst); } else { this.parameters.put(name, values); } return (T) this; }
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/console/JavaExceptionConsoleTracker.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/console/JavaExceptionConsoleTracker.java index e820e26b7..94b766a84 100644 --- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/console/JavaExceptionConsoleTracker.java +++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/console/JavaExceptionConsoleTracker.java @@ -1,40 +1,40 @@ /******************************************************************************* * Copyright (c) 2000, 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.debug.ui.console; import org.eclipse.jface.text.BadLocationException; import org.eclipse.ui.console.IHyperlink; import org.eclipse.ui.console.IOConsole; import org.eclipse.ui.console.PatternMatchEvent; /** * creates JavaExceptionHyperLinks * * @since 3.1 */ public class JavaExceptionConsoleTracker extends JavaConsoleTracker { /* (non-Javadoc) * @see org.eclipse.ui.console.IPatternMatchListenerDelegate#matchFound(org.eclipse.ui.console.PatternMatchEvent) */ public void matchFound(PatternMatchEvent event) { try { int offset = event.getOffset(); int length = event.getLength(); IOConsole console = getConsole(); String exceptionName; - exceptionName = console.getDocument().get(offset, length); + exceptionName = console.getDocument().get(offset, length - 1); IHyperlink link = new JavaExceptionHyperLink(console, exceptionName); - getConsole().addHyperlink(link, offset, length); + getConsole().addHyperlink(link, offset, length - 1); } catch (BadLocationException e) { } } }
false
true
public void matchFound(PatternMatchEvent event) { try { int offset = event.getOffset(); int length = event.getLength(); IOConsole console = getConsole(); String exceptionName; exceptionName = console.getDocument().get(offset, length); IHyperlink link = new JavaExceptionHyperLink(console, exceptionName); getConsole().addHyperlink(link, offset, length); } catch (BadLocationException e) { } }
public void matchFound(PatternMatchEvent event) { try { int offset = event.getOffset(); int length = event.getLength(); IOConsole console = getConsole(); String exceptionName; exceptionName = console.getDocument().get(offset, length - 1); IHyperlink link = new JavaExceptionHyperLink(console, exceptionName); getConsole().addHyperlink(link, offset, length - 1); } catch (BadLocationException e) { } }
diff --git a/tool/src/java/org/sakaiproject/evaluation/tool/ResponseAnswersBeanLocator.java b/tool/src/java/org/sakaiproject/evaluation/tool/ResponseAnswersBeanLocator.java index c082543a..58e1958f 100644 --- a/tool/src/java/org/sakaiproject/evaluation/tool/ResponseAnswersBeanLocator.java +++ b/tool/src/java/org/sakaiproject/evaluation/tool/ResponseAnswersBeanLocator.java @@ -1,40 +1,40 @@ /* * Created on 8 Feb 2007 */ package org.sakaiproject.evaluation.tool; import java.util.HashMap; import java.util.Map; import org.sakaiproject.evaluation.model.EvalResponse; import uk.org.ponder.beanutil.BeanLocator; public class ResponseAnswersBeanLocator implements BeanLocator { public static final String NEW_PREFIX = "new"; private ResponseBeanLocator responseBeanLocator; private Map delivered = new HashMap(); private LocalResponsesLogic localResponsesLogic; public void setLocalResponsesLogic(LocalResponsesLogic localResponsesLogic) { this.localResponsesLogic = localResponsesLogic; } public void setResponseBeanLocator(ResponseBeanLocator responseBeanLocator) { this.responseBeanLocator = responseBeanLocator; } public Object locateBean(String path) { BeanLocator togo = (BeanLocator) delivered.get(path); if (togo == null) { EvalResponse parent = (EvalResponse) responseBeanLocator.locateBean(path); - togo = new AnswersBeanLocator(parent, localResponsesLogic); + //togo = new AnswersBeanLocator(parent, localResponsesLogic); delivered.put(path, togo); } return togo; } }
true
true
public Object locateBean(String path) { BeanLocator togo = (BeanLocator) delivered.get(path); if (togo == null) { EvalResponse parent = (EvalResponse) responseBeanLocator.locateBean(path); togo = new AnswersBeanLocator(parent, localResponsesLogic); delivered.put(path, togo); } return togo; }
public Object locateBean(String path) { BeanLocator togo = (BeanLocator) delivered.get(path); if (togo == null) { EvalResponse parent = (EvalResponse) responseBeanLocator.locateBean(path); //togo = new AnswersBeanLocator(parent, localResponsesLogic); delivered.put(path, togo); } return togo; }
diff --git a/src/edu/wpi/first/wpilibj/templates/commands/RunClimber.java b/src/edu/wpi/first/wpilibj/templates/commands/RunClimber.java index cac9ebc..d1462f2 100644 --- a/src/edu/wpi/first/wpilibj/templates/commands/RunClimber.java +++ b/src/edu/wpi/first/wpilibj/templates/commands/RunClimber.java @@ -1,83 +1,85 @@ package edu.wpi.first.wpilibj.templates.commands; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import edu.wpi.first.wpilibj.templates.debugging.DebugInfoGroup; import edu.wpi.first.wpilibj.templates.debugging.Debuggable; import edu.wpi.first.wpilibj.templates.debugging.InfoState; import edu.wpi.first.wpilibj.templates.debugging.RobotDebugger; import edu.wpi.first.wpilibj.templates.variablestores.VstM; import edu.wpi.first.wpilibj.templates.vstj.VstJ; /** * */ public class RunClimber extends CommandBase implements Debuggable { private SendableChooser isClimbing; public RunClimber() { requires(climber); isClimbing = new SendableChooser(); } // Called just before this Command runs the first time protected void initialize() { climber.stop(); isClimbing.addDefault("Disable Climber", Boolean.FALSE); isClimbing.addObject("Enable Climber", Boolean.TRUE); SmartDashboard.putData("Climber", isClimbing); } // Called repeatedly when this Command is scheduled to run protected void execute() { checkEnabled(); if (isEnabled) { double climbSpeed = VstJ.getDefaultJoystick().getRawAxis(VstJ.getClimberAxisNumber()); climbSpeed *= 0.25; //The Following Code Won't Affect Anything If The Pressure Switches Are Not Attached/Not Pressed. if (climbSpeed != 0) { if (((VstM.Climber.climberState() == -1) != (climbSpeed < 0)) || ((VstM.Climber.climberState() == 1) != climbSpeed > 0)) { climbSpeed *= VstM.Climber.climberState(); } } climber.runLadder(climbSpeed); + }else{ + climber.runLadder(0); } RobotDebugger.push(climber); RobotDebugger.push(this); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return false; } // Called once after isFinished returns true protected void end() { climber.stop(); RobotDebugger.push(climber); } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { this.end(); isEnabled = false; RobotDebugger.push(this); } public DebugInfoGroup getStatus() { return new DebugInfoGroup(new InfoState("ClimberEnabled", isEnabled() ? "Enabled" : "Disabled")); } private boolean isEnabled; private void checkEnabled() { isEnabled = Boolean.TRUE == isClimbing.getSelected(); } private boolean isEnabled() { return isEnabled; } }
true
true
protected void execute() { checkEnabled(); if (isEnabled) { double climbSpeed = VstJ.getDefaultJoystick().getRawAxis(VstJ.getClimberAxisNumber()); climbSpeed *= 0.25; //The Following Code Won't Affect Anything If The Pressure Switches Are Not Attached/Not Pressed. if (climbSpeed != 0) { if (((VstM.Climber.climberState() == -1) != (climbSpeed < 0)) || ((VstM.Climber.climberState() == 1) != climbSpeed > 0)) { climbSpeed *= VstM.Climber.climberState(); } } climber.runLadder(climbSpeed); } RobotDebugger.push(climber); RobotDebugger.push(this); }
protected void execute() { checkEnabled(); if (isEnabled) { double climbSpeed = VstJ.getDefaultJoystick().getRawAxis(VstJ.getClimberAxisNumber()); climbSpeed *= 0.25; //The Following Code Won't Affect Anything If The Pressure Switches Are Not Attached/Not Pressed. if (climbSpeed != 0) { if (((VstM.Climber.climberState() == -1) != (climbSpeed < 0)) || ((VstM.Climber.climberState() == 1) != climbSpeed > 0)) { climbSpeed *= VstM.Climber.climberState(); } } climber.runLadder(climbSpeed); }else{ climber.runLadder(0); } RobotDebugger.push(climber); RobotDebugger.push(this); }
diff --git a/EscapeIR-Android/src/fr/umlv/escape/game/Wave.java b/EscapeIR-Android/src/fr/umlv/escape/game/Wave.java index 04647cd..37f60d7 100644 --- a/EscapeIR-Android/src/fr/umlv/escape/game/Wave.java +++ b/EscapeIR-Android/src/fr/umlv/escape/game/Wave.java @@ -1,49 +1,49 @@ package fr.umlv.escape.game; import java.util.ArrayList; import java.util.Iterator; import fr.umlv.escape.Objects; import fr.umlv.escape.ship.Ship; /** * Class that represent a wave of {@link Ship}. */ public class Wave { final String name; final ArrayList<Ship> shipList; /** * Constructor. * @param name The name of the wave. */ public Wave(String name){ Objects.requireNonNull(name); this.name=name; this.shipList=new ArrayList<Ship>(); } /** * Active and launch all {@link Ship} containing in the wave. */ public void startWave(){ - /*Iterator<Ship> iterShip=this.shipList.iterator(); + Iterator<Ship> iterShip=this.shipList.iterator(); while(iterShip.hasNext()){ Ship ship=iterShip.next(); Game.getTheGame().getFrontApplication().getBattleField().addShip(ship); ship.body.setActive(true); ship.move(); - }*/ + } } @Override public String toString(){ String res=this.name; Iterator<Ship> iterShip=this.shipList.iterator(); while(iterShip.hasNext()){ res+=" "+iterShip.next().toString(); } return res; } }
false
true
public void startWave(){ /*Iterator<Ship> iterShip=this.shipList.iterator(); while(iterShip.hasNext()){ Ship ship=iterShip.next(); Game.getTheGame().getFrontApplication().getBattleField().addShip(ship); ship.body.setActive(true); ship.move(); }*/ }
public void startWave(){ Iterator<Ship> iterShip=this.shipList.iterator(); while(iterShip.hasNext()){ Ship ship=iterShip.next(); Game.getTheGame().getFrontApplication().getBattleField().addShip(ship); ship.body.setActive(true); ship.move(); } }
diff --git a/src/gov/nih/ncgc/bard/tools/BardServletContextListener.java b/src/gov/nih/ncgc/bard/tools/BardServletContextListener.java index aee2d9a..093800e 100644 --- a/src/gov/nih/ncgc/bard/tools/BardServletContextListener.java +++ b/src/gov/nih/ncgc/bard/tools/BardServletContextListener.java @@ -1,66 +1,68 @@ package gov.nih.ncgc.bard.tools; import gov.nih.ncgc.bard.rest.BARDResource; import gov.nih.ncgc.bard.search.SolrSearch; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import java.net.InetAddress; import java.net.UnknownHostException; import java.sql.SQLException; /** * This class is specified in the container configuration file (web.xml) as a registered listener. * Methods handle initialization and destruction of application context. * * @author braistedjc */ public class BardServletContextListener implements ServletContextListener { DBUtils db; @Override public void contextInitialized(ServletContextEvent contextEvent) { db = new DBUtils(); BARDResource.setDb(db); SolrSearch.setDb(db); // should we initialize cache mgmt at all? - boolean initHazelcast = System.getProperty("initHazelcast").toLowerCase().equals("true"); + String sym = System.getProperty("initHazelcast"); + boolean initHazelcast = true; + if (sym != null) initHazelcast = sym.toLowerCase().equals("true"); // initialize cache management parameters if (initHazelcast) { ServletContext servletContext = contextEvent.getServletContext(); String cachePrefixes = servletContext.getInitParameter("cache-management-cache-prefix-list"); String cacheMgrNodes = servletContext.getInitParameter("cache-manager-cluster-nodes"); if (cachePrefixes != null && cacheMgrNodes != null) { DBUtils.initializeManagedCaches(cachePrefixes, cacheMgrNodes); } else { // if we don't have context, then try to initialize with the assumption that the // server host is a member of the HazelCast cluster, use the host ip or if that fails, localhost try { String host = InetAddress.getLocalHost().getHostAddress(); //if we don't have context, send empty cache prefix list, DBUtils.initializeManagedCaches("", host); } catch (UnknownHostException unknownHostExcept) { unknownHostExcept.printStackTrace(); DBUtils.initializeManagedCaches("", "localhost"); } } } // additional initialization can go here ... } @Override public void contextDestroyed(ServletContextEvent arg0) { //closes the cache manger DBUtils.shutdownCacheFlushManager(); DBUtils.flushCachePrefixNames = null; try { db.closeConnection(); } catch (SQLException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }
true
true
public void contextInitialized(ServletContextEvent contextEvent) { db = new DBUtils(); BARDResource.setDb(db); SolrSearch.setDb(db); // should we initialize cache mgmt at all? boolean initHazelcast = System.getProperty("initHazelcast").toLowerCase().equals("true"); // initialize cache management parameters if (initHazelcast) { ServletContext servletContext = contextEvent.getServletContext(); String cachePrefixes = servletContext.getInitParameter("cache-management-cache-prefix-list"); String cacheMgrNodes = servletContext.getInitParameter("cache-manager-cluster-nodes"); if (cachePrefixes != null && cacheMgrNodes != null) { DBUtils.initializeManagedCaches(cachePrefixes, cacheMgrNodes); } else { // if we don't have context, then try to initialize with the assumption that the // server host is a member of the HazelCast cluster, use the host ip or if that fails, localhost try { String host = InetAddress.getLocalHost().getHostAddress(); //if we don't have context, send empty cache prefix list, DBUtils.initializeManagedCaches("", host); } catch (UnknownHostException unknownHostExcept) { unknownHostExcept.printStackTrace(); DBUtils.initializeManagedCaches("", "localhost"); } } } // additional initialization can go here ... }
public void contextInitialized(ServletContextEvent contextEvent) { db = new DBUtils(); BARDResource.setDb(db); SolrSearch.setDb(db); // should we initialize cache mgmt at all? String sym = System.getProperty("initHazelcast"); boolean initHazelcast = true; if (sym != null) initHazelcast = sym.toLowerCase().equals("true"); // initialize cache management parameters if (initHazelcast) { ServletContext servletContext = contextEvent.getServletContext(); String cachePrefixes = servletContext.getInitParameter("cache-management-cache-prefix-list"); String cacheMgrNodes = servletContext.getInitParameter("cache-manager-cluster-nodes"); if (cachePrefixes != null && cacheMgrNodes != null) { DBUtils.initializeManagedCaches(cachePrefixes, cacheMgrNodes); } else { // if we don't have context, then try to initialize with the assumption that the // server host is a member of the HazelCast cluster, use the host ip or if that fails, localhost try { String host = InetAddress.getLocalHost().getHostAddress(); //if we don't have context, send empty cache prefix list, DBUtils.initializeManagedCaches("", host); } catch (UnknownHostException unknownHostExcept) { unknownHostExcept.printStackTrace(); DBUtils.initializeManagedCaches("", "localhost"); } } } // additional initialization can go here ... }
diff --git a/src/vialab/SMT/TouchClient.java b/src/vialab/SMT/TouchClient.java index 0471075..6b738ff 100644 --- a/src/vialab/SMT/TouchClient.java +++ b/src/vialab/SMT/TouchClient.java @@ -1,1719 +1,1711 @@ /* * Modified version of the TUIO processing library - part of the reacTIVision * project http://reactivision.sourceforge.net/ * * Copyright (c) 2005-2009 Martin Kaltenbrunner <[email protected]> * * This version Copyright (c) 2011 Erik Paluka, Christopher Collins - University * of Ontario Institute of Technology Mark Hancock - University of Waterloo * contact: [email protected] * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License Version 3 as published by the * Free Software Foundation. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this library; if not, write to the Free Software Foundation, Inc., 59 Temple * Place, Suite 330, Boston, MA 02111-1307 USA */ package vialab.SMT; import java.awt.Point; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Vector; import java.util.concurrent.CopyOnWriteArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.jbox2d.collision.shapes.PolygonShape; import org.jbox2d.common.Vec2; import org.jbox2d.dynamics.Body; import org.jbox2d.dynamics.BodyDef; import org.jbox2d.dynamics.World; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import processing.core.PApplet; import processing.core.PConstants; import processing.core.PImage; //import android.view.*; import TUIO.*; /** * The Core SMT class, it provides the TUIO/Touch Processing client * implementation, specifies the back-end source of Touches via TouchSource, and * SMT cannot be used without it. Use TouchClient to initialize SMT, and * add/remove zones from the sketch/application. * * @author Erik Paluka * @author Zach Cook * @version 1.0 */ public class TouchClient { static float box2dScale = 0.1f; static World world; private static int MAX_PATH_LENGTH = 50; protected static LinkedList<Process> tuioServerList = new LinkedList<Process>(); /** Processing PApplet */ protected static PApplet parent; /** Gesture Handler */ // private static GestureHandler handler; /** Tuio Client that listens for Tuio Messages via port 3333 UDP */ protected static LinkedList<TuioClient> tuioClientList = new LinkedList<TuioClient>(); /** The main zone list */ protected static CopyOnWriteArrayList<Zone> zoneList = new CopyOnWriteArrayList<Zone>(); /** Flag for drawing touch points */ protected static TouchDraw drawTouchPoints = TouchDraw.SMOOTH; /** Matrix used to test if the zone has gone off the screen */ // private PMatrix3D mTest = new PMatrix3D(); protected static SMTZonePicker picker; protected static SMTTuioListener listener; protected static SMTTouchManager manager; protected static Method touch; protected static Boolean warnUnimplemented; /** * This controls whether we give a warning for uncalled methods which use * one of the reserved method prefixes (draw,pickDraw,touch,etc and any that * have been added by calls to SMTUtilities.getZoneMethod() with a unique * prefix). * <P> * Default state is on. */ public static boolean warnUncalledMethods = true; /** * The renderer to use as a default for zones, can be P3D, P2D, OPENGL, etc, * upon TouchClient initialization this is set to the same as the PApplet's * renderer */ public static String defaultRenderer; /** TUIO adapter depending on which TouchSource is used */ static AndroidToTUIO att = null; static MouseToTUIO mtt = null; protected static LinkedList<BufferedReader> tuioServerErrList = new LinkedList<BufferedReader>(); protected static LinkedList<BufferedReader> tuioServerOutList = new LinkedList<BufferedReader>(); protected static LinkedList<BufferedWriter> tuioServerInList = new LinkedList<BufferedWriter>(); static Body groundBody; protected static ArrayList<Class<?>> extraClassList = new ArrayList<Class<?>>(); static boolean fastPicking = true; static Map<Integer, TouchSource> deviceMap = Collections .synchronizedMap(new LinkedHashMap<Integer, TouchSource>()); static int mainListenerPort; protected static boolean inShutdown = false; /** * Prevent TouchClient instantiation with private constructor */ private TouchClient() { } public static void setFastPicking(boolean fastPicking) { TouchClient.fastPicking = fastPicking; } /** * Calling this function overrides the default behavior of showing select * unimplemented based on defaults for each zone specified in loadMethods() * * @param warn * whether to warn when there are unimplemented methods for zones */ public static void setWarnUnimplemented(boolean warn) { TouchClient.warnUnimplemented = warn; } /* * Initializes the TouchClient, begins listening to a TUIO source on the * default port of 3333 */ /** * * Allows you to select the TouchSource backend from which to get * multi-touch events from * * @param parent * - PApplet: The Processing PApplet, usually just 'this' when * using the Processing IDE * * @param port * - int: The port to listen on * * @param source * -int: The source of touch events to listen to. One of: * TouchSource.MOUSE, TouchSource.TUIO_DEVICE, * TouchSource.ANDROID, TouchSource.WM_TOUCH, TouchSource.SMART */ public static void init(PApplet parent) { init(parent, 3333); } /** * Allows you to select the TouchSource backend from which to get * multi-touch events from * * @param parent * PApplet - The Processing PApplet, usually just 'this' when * using the Processing IDE * @param port * int - The port to listen on */ public static void init(PApplet parent, int port) { init(parent, port, TouchSource.TUIO_DEVICE); } /** * Allows you to select the TouchSource backend from which to get * multi-touch events from * * @param parent * PApplet - The Processing PApplet, usually just 'this' when * using the Processing IDE * @param source * enum TouchSource - The source of touch events to listen to. * One of: TouchSource.MOUSE, TouchSource.TUIO_DEVICE, * TouchSource.ANDROID, TouchSource.WM_TOUCH, TouchSource.SMART */ public static void init(PApplet parent, TouchSource source) { init(parent, 3333, source); } /** * Allows you to select the TouchSource backend from which to get * multi-touch events from * * @param parent * PApplet - The Processing PApplet, usually just 'this' when * using the Processing IDE * @param source * enum TouchSource - The source of touch events to listen to. * One of: TouchSource.MOUSE, TouchSource.TUIO_DEVICE, * TouchSource.ANDROID, TouchSource.WM_TOUCH, TouchSource.SMART * @param extraClasses * Class<?> - Classes that should be checked for method * definitions similar to PApplet for drawZoneName(), etc, but * PApplet takes precedence. */ public static void init(PApplet parent, TouchSource source, Class<?>... extraClasses) { init(parent, 3333, source, extraClasses); } /** * Allows you to select the TouchSource backend from which to get * multi-touch events from * * @param parent * PApplet - The Processing PApplet, usually just 'this' when * using the Processing IDE * * @param port * int - The port to listen on * * @param source * int - The source of touch events to listen to. One of: * TouchSource.MOUSE, TouchSource.TUIO_DEVICE, * TouchSource.ANDROID, TouchSource.WM_TOUCH, TouchSource.SMART */ private static void init(final PApplet parent, int port, TouchSource source, Class<?>... extraClasses) { if (parent == null) { System.err .println("Null parent PApplet, pass 'this' to TouchClient.init() instead of null"); return; } // As of now the toolkit only supports OpenGL if (!parent.g.isGL()) { System.out .println("SMT only supports using OpenGL renderers, please use either OPENGL, P2D, or P3D, in the size function e.g size(displayWidth, displayHeight, P3D);"); } if (System.getProperty("os.name").equals("Mac OS X")) { TouchClient.fastPicking = false; System.out .println("Defaulting to slow picking on OS X, if calling TouchClient.setFastPicking(true); after TouchClient.init() increases performance and doesn't cause bugs, please contact SMT's developers."); } touch = SMTUtilities.getPMethod(parent, "touch"); TouchClient.parent = parent; addMethodClasses(extraClasses); // set Zone.applet so that it is consistently set at this time, not // after a zone is constructed Zone.applet = parent; // parent.registerMethod("dispose", this); parent.registerMethod("draw", new TouchClient()); parent.registerMethod("pre", new TouchClient()); // handler = new GestureHandler(); picker = new SMTZonePicker(); defaultRenderer = parent.g.getClass().getName(); listener = new SMTTuioListener(); manager = new SMTTouchManager(listener, picker); TuioClient c = new TuioClient(port); c.connect(); while (!c.isConnected()) { c = new TuioClient(++port); c.connect(); } c.addTuioListener(listener); tuioClientList.add(c); System.out.println("TuioClient listening on port: " + port); mainListenerPort = port; switch (source) { case ANDROID: // this still uses the old method, should be re-implemented without // the socket att = new AndroidToTUIO(parent.width, parent.height, port); deviceMap.put(port, source); // parent.registerMethod("touchEvent", att); //when Processing // supports this break; case MOUSE: // this still uses the old method, should be re-implemented without // the socket mtt = new MouseToTUIO(parent.width, parent.height, port); deviceMap.put(port, source); parent.registerMethod("mouseEvent", mtt); break; case TUIO_DEVICE: break; case WM_TOUCH: if (System.getProperty("os.arch").equals("x86")) { TouchClient.runWinTouchTuioServer(false, "127.0.0.1", port); } else { TouchClient.runWinTouchTuioServer(true, "127.0.0.1", port); } deviceMap.put(port, source); break; case SMART: TouchClient.runSmart2TuioServer(); deviceMap.put(port, source); break; case LEAP: TouchClient.runLeapTuioServer(port); deviceMap.put(port, source); break; case MULTIPLE: // ANDROID if (System.getProperty("java.vm.name").equalsIgnoreCase("Dalvik")) { att = new AndroidToTUIO(parent.width, parent.height, port); deviceMap.put(port, TouchSource.ANDROID); // parent.registerMethod("touchEvent", att); //when Processing // supports this break; } else { // TUIO_DEVICE: // covered already by c deviceMap.put(port, TouchSource.TUIO_DEVICE); // WM_TOUCH: TuioClient c2 = new TuioClient(++port); c2.connect(); while (!c2.isConnected()) { c2 = new TuioClient(++port); c2.connect(); } c2.addTuioListener(new SMTProxyTuioListener(port, listener)); System.out.println("TuioClient listening on port: " + port); - // SMART: - if (System.getProperty("os.name").startsWith("Windows") - && System.getProperty("os.version").equals("6.2")) { - TouchClient.runSmart2TuioServer(); - deviceMap.put(3333, TouchSource.SMART); - System.out - .println("Falling back to Smart2Tuio backend for WM_TOUCH, ignore missing Smart SDK warning, also might fail if port 3333 unavailable"); - } - else if (System.getProperty("os.arch").equals("x86")) { + if (System.getProperty("os.arch").equals("x86")) { TouchClient.runWinTouchTuioServer(false, "127.0.0.1", port); deviceMap.put(port, TouchSource.WM_TOUCH); } else { TouchClient.runWinTouchTuioServer(true, "127.0.0.1", port); deviceMap.put(port, TouchSource.WM_TOUCH); } // LEAP: TuioClient c3 = new TuioClient(++port); c3.connect(); while (!c3.isConnected()) { c3 = new TuioClient(++port); c3.connect(); } c3.addTuioListener(new SMTProxyTuioListener(port, listener)); System.out.println("TuioClient listening on port: " + port); TouchClient.runLeapTuioServer(port); deviceMap.put(port, TouchSource.LEAP); // MOUSE: TuioClient c4 = new TuioClient(++port); c4.connect(); while (!c4.isConnected()) { c4 = new TuioClient(++port); c4.connect(); } c4.addTuioListener(new SMTProxyTuioListener(port, listener)); System.out.println("TuioClient listening on port: " + port); // this still uses the old method, should be re-implemented // without // the socket mtt = new MouseToTUIO(parent.width, parent.height, port); deviceMap.put(port, TouchSource.MOUSE); parent.registerMethod("mouseEvent", mtt); tuioClientList.add(c2); tuioClientList.add(c3); tuioClientList.add(c4); } break; default: break; } parent.hint(PConstants.DISABLE_OPTIMIZED_STROKE); /** * Disconnects the TuioClient when the PApplet is stopped. Shuts down * any threads, disconnect from the net, unload memory, etc. */ Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { TouchClient.inShutdown = true; if (warnUncalledMethods) { SMTUtilities.warnUncalledMethods(parent); } for (TuioClient t : tuioClientList) { if (t.isConnected()) { t.disconnect(); } } for (BufferedWriter w : tuioServerInList) { try { w.newLine(); w.flush(); } catch (IOException e) {} } try { Thread.sleep(500); } catch (InterruptedException e) {} for (Process tuioServer : tuioServerList) { if (tuioServer != null) { tuioServer.destroy(); } } } })); world = new World(new Vec2(0.0f, 0.0f), true); // top groundBody = createStaticBox(0, -10.0f, parent.width, 10.f); // bottom createStaticBox(0, parent.height + 10.0f, parent.width, 10.f); // left createStaticBox(-10.0f, 0, 10.0f, parent.height); // right createStaticBox(parent.width + 10.0f, 0, 10.0f, parent.height); } /** * This creates a static box to interact with the physics engine, collisions * will occur with Zones that have physics == true, keeping them on the * screen * * @param x * X-position * @param y * Y-position * @param w * Width * @param h * Height */ public static Body createStaticBox(float x, float y, float w, float h) { BodyDef boxDef = new BodyDef(); boxDef.position.set(TouchClient.box2dScale * (x + w / 2), TouchClient.box2dScale * (parent.height - (y + h / 2))); Body box = world.createBody(boxDef); PolygonShape boxShape = new PolygonShape(); boxShape.setAsBox(TouchClient.box2dScale * w / 2, TouchClient.box2dScale * h / 2); box.createFixture(boxShape, 0.0f); return box; } /** * Redirects the MotionEvent object to AndroidToTUIO, used because current * version of Processing (2.x) does not support registerMethod("touchEvent", * target). * * @param me * MotionEvent - the motion event triggered in Android * @return Should the event get consumed elsewhere or not */ public static boolean passAndroidTouchEvent(Object me) { return att.onTouchEvent(me); } /** * Returns the list of zones. * * @return zoneList */ public static Zone[] getZones() { return zoneList.toArray(new Zone[zoneList.size()]); } /** * Sets the flag for drawing touch points in the PApplet. Draws the touch * points if flag is set to true. * * @param drawTouchPoints * boolean - flag * @deprecated */ public static void setDrawTouchPoints(TouchDraw drawTouchPoints) { setTouchDraw(drawTouchPoints); } /** * Sets the flag for drawing touch points in the PApplet. Draws the touch * points if flag is set to true. Sets the maximum path length to draw to be * max_path_length * * @param drawTouchPoints * boolean - flag * * @param max_path_length * int - sets maximum path length to draw * @deprecated */ public static void setDrawTouchPoints(TouchDraw drawTouchPoints, int max_path_length) { setTouchDraw(drawTouchPoints, max_path_length); } /** * Sets the flag for drawing touch points in the PApplet. Draws the touch * points if flag is set to true. * * @param drawTouchPoints * boolean - flag */ public static void setTouchDraw(TouchDraw drawTouchPoints) { TouchClient.drawTouchPoints = drawTouchPoints; } /** * Sets the flag for drawing touch points in the PApplet. Draws the touch * points if flag is set to true. Sets the maximum path length to draw to be * max_path_length * * @param drawTouchPoints * boolean - flag * * @param max_path_length * int - sets maximum path length to draw */ public static void setTouchDraw(TouchDraw drawTouchPoints, int max_path_length) { TouchClient.drawTouchPoints = drawTouchPoints; TouchClient.MAX_PATH_LENGTH = max_path_length; } /** * Draws the touch points in the PApplet if flag is set to true. */ public static void drawSmoothTouchPoints() { parent.pushStyle(); for (Touch t : SMTTouchManager.currentTouchState) { parent.strokeWeight(3); long time = System.currentTimeMillis() - t.startTimeMillis; if (t.isAssigned() && time < 250) { parent.noFill(); parent.stroke(155, 255, 155, 100); parent.ellipse(t.x, t.y, 75 - time / 10, 75 - time / 10); } else if (!t.isAssigned() && time < 500) { { parent.noFill(); parent.stroke(255, 155, 155, 100); parent.ellipse(t.x, t.y, time / 10 + 50, time / 10 + 50); } } parent.noStroke(); parent.fill(0, 0, 0, 50); parent.ellipse(t.x, t.y, 40, 40); parent.fill(255, 255, 255, 50); if (t.isJointCursor) { parent.fill(0, 255, 0, 50); } parent.ellipse(t.x, t.y, 30, 30); parent.noFill(); parent.stroke(200, 240, 255, 50); Point[] path = t.getPathPoints(); if (path.length > 3) { for (int j = 3 + Math.max(0, path.length - (TouchClient.MAX_PATH_LENGTH + 2)); j < path.length; j++) { float weight = 10 - (path.length - j) / 5; if (weight >= 1) { parent.strokeWeight(weight); parent.bezier(path[j].x, path[j].y, path[j - 1].x, path[j - 1].y, path[j - 2].x, path[j - 2].y, path[j - 3].x, path[j - 3].y); } } } } parent.popStyle(); } /** * Draws all Touch objects and their path history, with some data to try to * help with debugging */ public static void drawDebugTouchPoints() { parent.pushStyle(); for (Touch t : SMTTouchManager.currentTouchState) { parent.fill(255); if (t.isJointCursor) { parent.fill(0, 255, 0); } parent.stroke(0); parent.ellipse(t.x, t.y, 30, 30); parent.line(t.x, t.y - 15, t.x, t.y + 15); parent.line(t.x - 15, t.y, t.x + 15, t.y); TuioPoint[] path = t.path.toArray(new TuioPoint[t.path.size()]); TuioPoint lastText = null; if (path.length > 3) { for (int j = 1 + Math.max(0, path.length - (TouchClient.MAX_PATH_LENGTH + 2)); j < path.length; j++) { String pointText = "#" + j + " x:" + path[j].getScreenX(parent.width) + " y:" + path[j].getScreenY(parent.height) + " t:" + path[j].getTuioTime().getTotalMilliseconds() + "ms"; parent.fill(255); parent.line(path[j].getScreenX(parent.width), path[j].getScreenY(parent.height), path[j - 1].getScreenX(parent.width), path[j - 1].getScreenY(parent.height)); parent.ellipse(path[j].getScreenX(parent.width), path[j].getScreenY(parent.height), 5, 5); if (lastText == null || Math.abs(path[j].getScreenY(parent.height) - lastText.getScreenY(parent.height)) > 13 || Math.abs(path[j].getScreenX(parent.width) - lastText.getScreenX(parent.width)) > parent .textWidth(pointText) * 1.5) { parent.fill(0); parent.textSize(12); parent.text(pointText, path[j].getScreenX(parent.width) + 5, path[j].getScreenY(parent.height)); lastText = path[j]; parent.fill(255, 0, 0); parent.ellipse(path[j].getScreenX(parent.width), path[j].getScreenY(parent.height), 5, 5); } } } } parent.popStyle(); } /** * Adds a zone(s) to the sketch/application. * * @param zones * - Zone: The zones to add to the sketch/application */ public static void add(Zone... zones) { for (Zone zone : zones) { if (zone != null) { // Zone is being added at top level, make sure its parent is set // to null, so that we draw it at TouchClient level // the zone will set parent afterwards when adding anyways, so // we should always do this to make sure we dont have issues // when a zone has not been removed from its parent (and so // parent!=null), and so is not drawn after being added to // TouchClient zone.parent = null; addToZoneList(zone); picker.add(zone); // make sure the matrix is up to date, these calls should not // occur if we do not call begin/endTouch once per // frame and once at Zone initialization zone.endTouch(); zone.beginTouch(); } else { System.err.println("Error: Added a null Zone"); } } } private static void addToZoneList(Zone zone) { if (!zoneList.contains(zone)) { zoneList.add(zone); } for (Zone child : zone.children) { addToZoneList(child); } } /** * This adds zones by creating them from XML specs, the XML needs "zone" * tags, and currently supports the following variables: name, x, y, width, * height, img * * @param xmlFilename * The XML file to read in for zone configuration * @return The array of zones created from the XML File */ public static Zone[] add(String xmlFilename) { List<Zone> zoneList = new ArrayList<Zone>(); try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(parent.createInput(xmlFilename)); NodeList zones = doc.getElementsByTagName("zone"); add(zones, zoneList); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (SAXException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return zoneList.toArray(new Zone[zoneList.size()]); } /** * This adds a set of zones to a parent Zone * * @param parent * The Zone to add the given zones to * @param zones * The zones to add to the parent as children */ public static void addChild(Zone parent, Zone... zones) { for (Zone z : zones) { if (parent != null) { parent.add(z); } } } /** * This adds a set of zones to a parent Zone * * @param parentName * The name of the Zone to add the given zones to * @param zones * The zones to add to the parent as children */ public static void addChild(String parentName, Zone... zones) { for (Zone z : zones) { if (get(parentName) != null) { get(parentName).add(z); } } } /** * This removes a set of zones to a parent Zone * * @param parent * The Zone to add the given zones to * @param zones * The zones to add to the parent as children */ public static void removeChild(Zone parent, Zone... zones) { for (Zone z : zones) { if (parent != null) { parent.remove(z); } } } /** * This removes a set of zones to a parent Zone * * @param parentName * The name of the Zone to add the given zones to * @param zones * The zones to add to the parent as children */ public static void removeChild(String parentName, Zone... zones) { for (Zone z : zones) { if (get(parentName) != null) { get(parentName).remove(z); } } } /** * This organizes the given zones into a grid configuration with the given * x, y, width, height, and spacing * * @param x * @param y * @param width * @param xSpace * @param ySpace * @param zones */ public static void grid(int x, int y, int width, int xSpace, int ySpace, Zone... zones) { int currentX = x; int currentY = y; int rowHeight = 0; for (Zone zone : zones) { if (currentX + zone.width > x + width) { currentX = x; currentY += rowHeight + ySpace; rowHeight = 0; } zone.setLocation(currentX, currentY); currentX += zone.width + xSpace; rowHeight = Math.max(rowHeight, zone.height); } } private static void add(NodeList zones, List<Zone> zoneList) { for (int i = 0; i < zones.getLength(); i++) { Node zoneNode = zones.item(i); if (zoneNode.getNodeType() == Node.ELEMENT_NODE && zoneNode.getNodeName().equalsIgnoreCase("zone")) { add(zoneNode, zoneList); } } } private static void add(Node node, List<Zone> zoneList) { NamedNodeMap map = node.getAttributes(); Node nameNode = map.getNamedItem("name"); Node xNode = map.getNamedItem("x"); Node yNode = map.getNamedItem("y"); Node widthNode = map.getNamedItem("width"); Node heightNode = map.getNamedItem("height"); Node imgNode = map.getNamedItem("img"); Zone zone; String name = null; int x, y, width, height; if (nameNode != null) { name = nameNode.getNodeValue(); } if (imgNode != null) { String imgFilename = imgNode.getNodeValue(); PImage img = parent.loadImage(imgFilename); if (xNode != null && yNode != null) { x = Integer.parseInt(xNode.getNodeValue()); y = Integer.parseInt(yNode.getNodeValue()); if (widthNode != null && heightNode != null) { width = Integer.parseInt(widthNode.getNodeValue()); height = Integer.parseInt(heightNode.getNodeValue()); zone = new ImageZone(name, img, x, y, width, height); } else { zone = new ImageZone(name, img, x, y); } } else { zone = new ImageZone(name, img); } } else { if (xNode != null && yNode != null && widthNode != null && heightNode != null) { x = Integer.parseInt(xNode.getNodeValue()); y = Integer.parseInt(yNode.getNodeValue()); width = Integer.parseInt(widthNode.getNodeValue()); height = Integer.parseInt(heightNode.getNodeValue()); zone = new Zone(name, x, y, width, height); } else { zone = new Zone(name); } } zoneList.add(zone); add(zone); add(node.getChildNodes(), zoneList); } /** * This removes the zone given from the TouchClient, meaning it will not be * drawn anymore or be assigned touches, but can be added back with a call * to add(zone); * * @param name * The name of the zone to remove * @return Whether all of the zones were removed successfully */ public static boolean remove(String name) { return remove(get(name)); } /** * This removes the zone given from the TouchClient, meaning it will not be * drawn anymore or be assigned touches, but can be added back with a call * to add(zone); * * @param zone * The zone to remove * @return Whether all of the zones were removed successfully */ public static boolean remove(Zone... zones) { boolean r = true; for (Zone zone : zones) { if (zone != null) { picker.remove(zone); if (!removeFromZoneList(zone)) { r = false; } } else { r = false; System.err.println("Error: Removed a null Zone"); } } return r; } private static boolean removeFromZoneList(Zone zone) { for (Zone child : zone.children) { removeFromZoneList(child); } // clear the touches from the Zone, so that it doesn't get pulled in by // the touches such as when putZoneOnTop() is called zone.unassignAll(); // destroy the Zones Body, so it does not collide with other Zones any // more if (zone.zoneBody != null) { world.destroyBody(zone.zoneBody); zone.zoneBody = null; zone.zoneFixture = null; zone.mJoint = null; } return zoneList.remove(zone); } /** * Performs the drawing of the zones in order. Zone on top-most layer gets * drawn last. Goes through the list on zones, pushes the current * transformation matrix, applies the zone's matrix, draws the zone, pops * the matrix, and when at the end of the list, it draws the touch points. */ public static void draw() { ArrayList<Zone> toDraw = new ArrayList<Zone>(); for (Zone zone : zoneList) { if (zone.getParent() == null) { toDraw.add(zone); } } // first extract order of all Zones to be drawn, then actually draw // them, so that re-parenting, etc can occur in a draw, and we do not // get ConcurrentModificationException for (Zone zone : toDraw) { zone.draw(); } switch (drawTouchPoints) { case DEBUG: drawDebugTouchPoints(); break; case SMOOTH: drawSmoothTouchPoints(); break; case NONE: break; } // PApplet.println(parent.color((float) 0)); // PApplet.println(parent.get(100, 100)); } /** * Draws a texture of the pickBuffer at the given x,y position with given * width and height * * @param x * - the x position to draw the pickBuffer image at * @param y * - the y position to draw the pickBuffer image at * @param w * - the width of the pickBuffer image to draw * @param h * - the height of the pickBuffer image to draw * @deprecated */ public static void drawPickBuffer(int x, int y, int w, int h) { // parent.g.image(picker.image, x, y, w, h); } /** * Returns a vector containing all the current TuioObjects. * * @return Vector<TuioObject> */ public static Vector<TuioObject> getTuioObjects() { return new Vector<TuioObject>(listener.getTuioObjects()); } /** * @return An array containing all touches that are currently NOT assigned * to zones */ public static Touch[] getUnassignedTouches() { Map<Long, Touch> touches = getTouchMap(); for (Zone zone : zoneList) { for (Touch touch : zone.getTouches()) { touches.remove(touch.sessionID); } } return touches.values().toArray(new Touch[touches.size()]); } /** * @return An array containing all touches that are currently assigned to * zones */ public static Touch[] getAssignedTouches() { List<Touch> touches = new ArrayList<Touch>(); for (Zone zone : zoneList) { for (Touch touch : zone.getTouches()) { touches.add(touch); } } return touches.toArray(new Touch[touches.size()]); } /** * @param zone * The zone to assign touches to * @param touches * The touches to assign to the zone, variable number of * arguments */ public static void assignTouches(Zone zone, Touch... touches) { zone.assign(touches); } /** * Returns a collection containing all the current Touches(TuioCursors). * * @return Collection<Touch> */ public static Collection<Touch> getTouchCollection() { return getTouchMap().values(); } /** * Returns a collection containing all the current Touches(TuioCursors). * * @return Touch[] containing all touches that are currently mapped */ public static Touch[] getTouches() { return getTouchMap().values().toArray(new Touch[getTouchMap().values().size()]); } /** * @return A Map<Long,Touch> indexing all touches by their session_id's */ public static Map<Long, Touch> getTouchMap() { return SMTTouchManager.currentTouchState.idToTouches; } // /** // * This method returns all the current touches that are not actively // * affecting any Zone. // * // * @return the array // */ // public static Touch[] getUnassignedTouches() { // Vector<TuioCursor> cursors = tuioClient.getTuioCursors(); // ArrayList<Touch> touches = new ArrayList<>(); // for (TuioCursor c : cursors) { // Zone z = picker.getZoneFromId(c.getSessionID()); // if (z == null) { // touches.add(new Touch(c)); // } // } // return touches.toArray(new Touch[touches.size()]); // } /** * @return An array of all zones that currently have touches/are active. */ public static Zone[] getActiveZones() { ArrayList<Zone> zones = new ArrayList<Zone>(); for (Zone zone : zoneList) { if (zone.isActive()) { zones.add(zone); } } return zones.toArray(new Zone[zones.size()]); } /** * @param zone * The zone to get the touches of * @return A Collection<Touch> containing all touches from the given zone */ public static Collection<Touch> getTouchCollectionFromZone(Zone zone) { return zone.getTouchCollection(); } /** * @param zone * The zone to get the touches of * @return A Touch[] containing all touches from the given zone */ public static Touch[] getTouchesFromZone(Zone zone) { return zone.getTouches(); } /** * Returns a the TuioObject associated with the session ID * * @param s_id * long - Session ID of the TuioObject * @return TuioObject */ public static TuioObject getTuioObject(long s_id) { return listener.getTuioObject(s_id); } /** * Returns the Touch(TuioCursor) associated with the session ID * * @param s_id * long - Session ID of the Touch(TuioCursor) * @return TuioCursor */ public static Touch getTouch(long s_id) { return SMTTouchManager.currentTouchState.getById(s_id); } /** * @param s_id * The session_id of the Touch to get the path start of * @return A new Touch containing the state of the touch at path start */ public static Touch getPathStartTouch(long s_id) { TuioCursor c = listener.getTuioCursor(s_id); Vector<TuioPoint> path = new Vector<TuioPoint>(c.getPath()); TuioPoint start = path.firstElement(); return new Touch(start.getTuioTime(), c.getSessionID(), c.getCursorID(), start.getX(), start.getY()); } /** * This creates a new Touch object from the last touch of a given Touch * object, the new Touch will not update. * <P> * It is easier to just create a new Touch with the given Touch object as * its parameter "new Touch(current)" where current is the Touch we want the * last touch of, so this is deprecated. * * @param current * The Touch to get the last touch from * @return A Touch containing the last touch, will not update, stays * consistent * @deprecated */ public static Touch getLastTouch(Touch current) { Vector<TuioPoint> path = current.path; if (path.size() > 1) { TuioPoint last = path.get(path.size() - 2); return new Touch(last.getTuioTime(), current.getSessionID(), current.getCursorID(), last.getX(), last.getY()); } return null; } /** * Returns the number of current Touches (TuioCursors) * * @return number of current touches */ public static int getTouchCount() { return listener.getTuioCursors().size(); } /** * Manipulates the zone's position if it is throw-able after it has been * released by a finger (cursor) Done before each call to draw. Uses the * zone's x and y friction values. */ public static void pre() { // TODO: provide some default assignment of touches manager.handleTouches(); if (mtt != null) { // update touches from mouseToTUIO joint cursors as they are a // special case and need to be shown to user for (Touch t : SMTTouchManager.currentTouchState) { t.isJointCursor = false; } for (Integer i : mtt.getJointCursors()) { SMTTouchManager.currentTouchState.getById(i).isJointCursor = true; } } parent.g.flush(); if (getTouches().length > 0) { SMTUtilities.invoke(touch, parent); } for (Zone zone : zoneList) { if (zone.getParent() != null) { // the parent should handle the touch calling continue; } if (zone.isChildActive()) { zone.touch(); } } updateStep(); // clear the background to get rid of anything from pre-draw parent.g.background(255); } /** * perform a step of physics using jbox2d, update bodies before and matrix * after of each Zone to keep the matrix and bodies synchronized */ private static void updateStep() { for (Zone z : zoneList) { if (z.physics) { // generate body and fixture for zone if they do not exist if (z.zoneBody == null && z.zoneFixture == null) { z.zoneBody = world.createBody(z.zoneBodyDef); z.zoneFixture = z.zoneBody.createFixture(z.zoneFixtureDef); } z.setBodyFromMatrix(); } else { // make sure to destroy body for Zones that do not have physics // on, as they should not collide with others if (z.zoneBody != null) { world.destroyBody(z.zoneBody); z.zoneBody = null; z.zoneFixture = null; z.mJoint = null; } } } world.step(1f / parent.frameRate, 8, 3); for (Zone z : zoneList) { if (z.physics) { z.setMatrixFromBody(); } } } /** * Runs a server that sends TUIO events using Windows 7 Touch events * * @param is64Bit * Whether to use the 64-bit version of the exe */ private static void runWinTouchTuioServer(boolean is64Bit, final String address, final int port) { try { File temp = File.createTempFile("temp", Long.toString(System.nanoTime())); if (!(temp.delete())) { throw new IOException("Could not delete temp file: " + temp.getAbsolutePath()); } if (!(temp.mkdir())) { throw new IOException("Could not create temp directory: " + temp.getAbsolutePath()); } BufferedInputStream src = new BufferedInputStream( TouchClient.class.getResourceAsStream(is64Bit ? "/resources/Touch2Tuio_x64.exe" : "/resources/Touch2Tuio.exe")); final File exeTempFile = new File(is64Bit ? temp.getAbsolutePath() + "\\Touch2Tuio_x64.exe" : temp.getAbsolutePath() + "\\Touch2Tuio.exe"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(exeTempFile)); byte[] tempexe = new byte[4 * 1024]; int rc; while ((rc = src.read(tempexe)) > 0) { out.write(tempexe, 0, rc); } src.close(); out.close(); exeTempFile.deleteOnExit(); BufferedInputStream dllsrc = new BufferedInputStream( TouchClient.class.getResourceAsStream(is64Bit ? "/resources/TouchHook_x64.dll" : "/resources/TouchHook.dll")); final File dllTempFile = new File(is64Bit ? temp.getAbsolutePath() + "\\TouchHook_x64.dll" : temp.getAbsolutePath() + "\\TouchHook.dll"); BufferedOutputStream outdll = new BufferedOutputStream( new FileOutputStream(dllTempFile)); byte[] tempdll = new byte[4 * 1024]; int rcdll; while ((rcdll = dllsrc.read(tempdll)) > 0) { outdll.write(tempdll, 0, rcdll); } dllsrc.close(); outdll.close(); dllTempFile.deleteOnExit(); Thread serverThread = new Thread() { @Override public void run() { try { Process tuioServer = Runtime.getRuntime().exec( exeTempFile.getAbsolutePath() + " " + parent.frame.getTitle() + " " + address + " " + port); BufferedReader tuioServerErr = new BufferedReader(new InputStreamReader( tuioServer.getErrorStream())); BufferedReader tuioServerOut = new BufferedReader(new InputStreamReader( tuioServer.getInputStream())); BufferedWriter tuioServerIn = new BufferedWriter(new OutputStreamWriter( tuioServer.getOutputStream())); tuioServerList.add(tuioServer); tuioServerErrList.add(tuioServerErr); tuioServerOutList.add(tuioServerOut); tuioServerInList.add(tuioServerIn); while (true) { if (tuioServerErr.ready()) { System.err.println("WM_TOUCH: " + tuioServerErr.readLine()); } if (tuioServerOut.ready()) { System.out.println("WM_TOUCH: " + tuioServerOut.readLine()); } try { tuioServer.exitValue(); if(!TouchClient.inShutdown){ System.err .println("WM_TOUCH Process died, is Visual C++ Redistributable for Visual Studio 2012 installed?"); break; } } catch (IllegalThreadStateException e) { // still running... sleep time Thread.sleep(100); } } } catch (IOException e) { System.err.println(e.getMessage()); } catch (Exception e) { System.err.println("TUIO Server stopped!"); } } }; serverThread.start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } private static void runSmart2TuioServer() { try { File temp = File.createTempFile("temp", Long.toString(System.nanoTime())); if (!(temp.delete())) { throw new IOException("Could not delete temp file: " + temp.getAbsolutePath()); } if (!(temp.mkdir())) { throw new IOException("Could not create temp directory: " + temp.getAbsolutePath()); } BufferedInputStream src = new BufferedInputStream( TouchClient.class.getResourceAsStream("/resources/SMARTtoTUIO2.exe")); final File exeTempFile = new File(temp.getAbsolutePath() + "\\SMARTtoTUIO2.exe"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(exeTempFile)); byte[] tempexe = new byte[4 * 1024]; int rc; while ((rc = src.read(tempexe)) > 0) { out.write(tempexe, 0, rc); } src.close(); out.close(); exeTempFile.deleteOnExit(); BufferedInputStream sdksrc = new BufferedInputStream( TouchClient.class.getResourceAsStream("/resources/SMARTTableSDK.Core.dll")); final File sdkTempFile = new File(temp.getAbsolutePath() + "\\SMARTTableSDK.Core.dll"); BufferedOutputStream outsdk = new BufferedOutputStream( new FileOutputStream(sdkTempFile)); byte[] tempsdk = new byte[4 * 1024]; int rcsdk; while ((rcsdk = sdksrc.read(tempsdk)) > 0) { outsdk.write(tempsdk, 0, rcsdk); } sdksrc.close(); outsdk.close(); sdkTempFile.deleteOnExit(); BufferedInputStream tuiosrc = new BufferedInputStream( TouchClient.class.getResourceAsStream("/resources/libTUIO.dll")); final File tuioTempFile = new File(temp.getAbsolutePath() + "\\libTUIO.dll"); BufferedOutputStream outtuio = new BufferedOutputStream(new FileOutputStream( tuioTempFile)); byte[] tempdll = new byte[4 * 1024]; int rctuio; while ((rctuio = tuiosrc.read(tempdll)) > 0) { outtuio.write(tempdll, 0, rctuio); } tuiosrc.close(); outtuio.close(); tuioTempFile.deleteOnExit(); Thread serverThread = new Thread() { @Override public void run() { try { Process tuioServer = Runtime.getRuntime().exec( exeTempFile.getAbsolutePath()); BufferedReader tuioServerErr = new BufferedReader(new InputStreamReader( tuioServer.getErrorStream())); BufferedReader tuioServerOut = new BufferedReader(new InputStreamReader( tuioServer.getInputStream())); BufferedWriter tuioServerIn = new BufferedWriter(new OutputStreamWriter( tuioServer.getOutputStream())); tuioServerList.add(tuioServer); tuioServerErrList.add(tuioServerErr); tuioServerOutList.add(tuioServerOut); tuioServerInList.add(tuioServerIn); while (true) { if (tuioServerErr.ready()) { System.err.println("SMART: " + tuioServerErr.readLine()); } if (tuioServerOut.ready()) { System.out.println("SMART: " + tuioServerOut.readLine()); } try { tuioServer.exitValue(); if(!TouchClient.inShutdown){ System.err.println("SMART Process died"); break; } } catch (IllegalThreadStateException e) { // still running... sleep time Thread.sleep(1000); } } } catch (IOException e) { System.err.println(e.getMessage()); } catch (Exception e) { System.err.println("SMARTtoTUIO2.exe Server stopped!"); } } }; serverThread.start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } /** * Runs a server that sends TUIO events using Windows 7 Touch events * * @param is64Bit * Whether to use the 64-bit version of the exe */ private static void runLeapTuioServer(final int port) { try { File temp = File.createTempFile("temp", Long.toString(System.nanoTime())); if (!(temp.delete())) { throw new IOException("Could not delete temp file: " + temp.getAbsolutePath()); } if (!(temp.mkdir())) { throw new IOException("Could not create temp directory: " + temp.getAbsolutePath()); } BufferedInputStream src = new BufferedInputStream( TouchClient.class.getResourceAsStream("/resources/motionLess.exe")); final File exeTempFile = new File(temp.getAbsolutePath() + "\\motionLess.exe"); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(exeTempFile)); byte[] tempexe = new byte[4 * 1024]; int rc; while ((rc = src.read(tempexe)) > 0) { out.write(tempexe, 0, rc); } src.close(); out.close(); exeTempFile.deleteOnExit(); BufferedInputStream dllsrc = new BufferedInputStream( TouchClient.class.getResourceAsStream("/resources/Leap.dll")); final File dllTempFile = new File(temp.getAbsolutePath() + "\\Leap.dll"); BufferedOutputStream outdll = new BufferedOutputStream( new FileOutputStream(dllTempFile)); byte[] tempdll = new byte[4 * 1024]; int rcdll; while ((rcdll = dllsrc.read(tempdll)) > 0) { outdll.write(tempdll, 0, rcdll); } dllsrc.close(); outdll.close(); dllTempFile.deleteOnExit(); Thread serverThread = new Thread() { @Override public void run() { try { Process tuioServer = Runtime.getRuntime().exec( exeTempFile.getAbsolutePath() + " " + port); BufferedReader tuioServerErr = new BufferedReader(new InputStreamReader( tuioServer.getErrorStream())); BufferedReader tuioServerOut = new BufferedReader(new InputStreamReader( tuioServer.getInputStream())); BufferedWriter tuioServerIn = new BufferedWriter(new OutputStreamWriter( tuioServer.getOutputStream())); tuioServerList.add(tuioServer); tuioServerErrList.add(tuioServerErr); tuioServerOutList.add(tuioServerOut); tuioServerInList.add(tuioServerIn); while (true) { if (tuioServerErr.ready()) { System.err.println("LEAP: " + tuioServerErr.readLine()); } if (tuioServerOut.ready()) { System.out.println("LEAP: " + tuioServerOut.readLine()); } try { tuioServer.exitValue(); if(!TouchClient.inShutdown){ System.err .println("LEAP Process died, is Visual C++ 2010 Redistributable (x86) installed?"); break; } } catch (IllegalThreadStateException e) { // still running... sleep time Thread.sleep(1000); } } } catch (IOException e) { System.err.println(e.getMessage()); } catch (Exception e) { System.err.println("TUIO Server stopped!"); } } }; serverThread.start(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } /** * Runs an exe from a path, presumably for translating native events to tuio * events */ public static void runExe(final String path) { Thread serverThread = new Thread() { @Override public void run() { int max_failures = 3; for (int i = 0; i < max_failures; i++) { try { Process tuioServer = Runtime.getRuntime().exec(path); BufferedReader tuioServerErr = new BufferedReader(new InputStreamReader( tuioServer.getErrorStream())); BufferedReader tuioServerOut = new BufferedReader(new InputStreamReader( tuioServer.getInputStream())); BufferedWriter tuioServerIn = new BufferedWriter(new OutputStreamWriter( tuioServer.getOutputStream())); tuioServerList.add(tuioServer); tuioServerErrList.add(tuioServerErr); tuioServerOutList.add(tuioServerOut); tuioServerInList.add(tuioServerIn); while (true) { if (tuioServerErr.ready()) { System.err.println(path + ": " + tuioServerErr.readLine()); } if (tuioServerOut.ready()) { System.out.println(path + ": " + tuioServerOut.readLine()); } Thread.sleep(1000); } } catch (IOException e) { System.err.println(e.getMessage()); break; } catch (Exception e) { System.err.println("Exe stopped!, restarting."); } } System.out.println("Stopped trying to run exe."); } }; serverThread.start(); } /** * @param zone * The zone to place on top of the others */ public static void putZoneOnTop(Zone zone) { if (zoneList.indexOf(zone) < zoneList.size() - 1) { if (zone.getParent() != null) { zone.getParent().putChildOnTop(zone); } zoneList.remove(zone); zoneList.add(zone); } } /** * This finds a zone by its name, returning the first zone with the given * name or null. * <P> * This will throw ClassCastException if the Zone is not an instance of the * given class , and non-applicable type compile errors when the given class * does not extend Zone. * * @param name * The name of the zone to find * @param type * a class type to cast the Zone to (e.g. Zone.class) * @return a Zone with the given name or null if it cannot be found */ @SuppressWarnings("unchecked") public static <T extends Zone> T get(String name, Class<T> type) { for (Zone z : zoneList) { if (z.name != null && z.name.equals(name)) { return (T) z; } } return null; } /** * This finds a zone by its name, returning the first zone with the given * name or null * * @param name * The name of the zone to find * @return a Zone with the given name or null if it cannot be found */ public static Zone get(String name) { return get(name, Zone.class); } /** * This adds objects to check for drawZoneName, touchZoneName, etc methods * in, similar to PApplet * * @param classes * The additional objects to check in for methods */ public static void addMethodClasses(Class<?>... classes) { for (Class<?> extraClass : classes) { extraClassList.add(extraClass); } } }
true
true
private static void init(final PApplet parent, int port, TouchSource source, Class<?>... extraClasses) { if (parent == null) { System.err .println("Null parent PApplet, pass 'this' to TouchClient.init() instead of null"); return; } // As of now the toolkit only supports OpenGL if (!parent.g.isGL()) { System.out .println("SMT only supports using OpenGL renderers, please use either OPENGL, P2D, or P3D, in the size function e.g size(displayWidth, displayHeight, P3D);"); } if (System.getProperty("os.name").equals("Mac OS X")) { TouchClient.fastPicking = false; System.out .println("Defaulting to slow picking on OS X, if calling TouchClient.setFastPicking(true); after TouchClient.init() increases performance and doesn't cause bugs, please contact SMT's developers."); } touch = SMTUtilities.getPMethod(parent, "touch"); TouchClient.parent = parent; addMethodClasses(extraClasses); // set Zone.applet so that it is consistently set at this time, not // after a zone is constructed Zone.applet = parent; // parent.registerMethod("dispose", this); parent.registerMethod("draw", new TouchClient()); parent.registerMethod("pre", new TouchClient()); // handler = new GestureHandler(); picker = new SMTZonePicker(); defaultRenderer = parent.g.getClass().getName(); listener = new SMTTuioListener(); manager = new SMTTouchManager(listener, picker); TuioClient c = new TuioClient(port); c.connect(); while (!c.isConnected()) { c = new TuioClient(++port); c.connect(); } c.addTuioListener(listener); tuioClientList.add(c); System.out.println("TuioClient listening on port: " + port); mainListenerPort = port; switch (source) { case ANDROID: // this still uses the old method, should be re-implemented without // the socket att = new AndroidToTUIO(parent.width, parent.height, port); deviceMap.put(port, source); // parent.registerMethod("touchEvent", att); //when Processing // supports this break; case MOUSE: // this still uses the old method, should be re-implemented without // the socket mtt = new MouseToTUIO(parent.width, parent.height, port); deviceMap.put(port, source); parent.registerMethod("mouseEvent", mtt); break; case TUIO_DEVICE: break; case WM_TOUCH: if (System.getProperty("os.arch").equals("x86")) { TouchClient.runWinTouchTuioServer(false, "127.0.0.1", port); } else { TouchClient.runWinTouchTuioServer(true, "127.0.0.1", port); } deviceMap.put(port, source); break; case SMART: TouchClient.runSmart2TuioServer(); deviceMap.put(port, source); break; case LEAP: TouchClient.runLeapTuioServer(port); deviceMap.put(port, source); break; case MULTIPLE: // ANDROID if (System.getProperty("java.vm.name").equalsIgnoreCase("Dalvik")) { att = new AndroidToTUIO(parent.width, parent.height, port); deviceMap.put(port, TouchSource.ANDROID); // parent.registerMethod("touchEvent", att); //when Processing // supports this break; } else { // TUIO_DEVICE: // covered already by c deviceMap.put(port, TouchSource.TUIO_DEVICE); // WM_TOUCH: TuioClient c2 = new TuioClient(++port); c2.connect(); while (!c2.isConnected()) { c2 = new TuioClient(++port); c2.connect(); } c2.addTuioListener(new SMTProxyTuioListener(port, listener)); System.out.println("TuioClient listening on port: " + port); // SMART: if (System.getProperty("os.name").startsWith("Windows") && System.getProperty("os.version").equals("6.2")) { TouchClient.runSmart2TuioServer(); deviceMap.put(3333, TouchSource.SMART); System.out .println("Falling back to Smart2Tuio backend for WM_TOUCH, ignore missing Smart SDK warning, also might fail if port 3333 unavailable"); } else if (System.getProperty("os.arch").equals("x86")) { TouchClient.runWinTouchTuioServer(false, "127.0.0.1", port); deviceMap.put(port, TouchSource.WM_TOUCH); } else { TouchClient.runWinTouchTuioServer(true, "127.0.0.1", port); deviceMap.put(port, TouchSource.WM_TOUCH); } // LEAP: TuioClient c3 = new TuioClient(++port); c3.connect(); while (!c3.isConnected()) { c3 = new TuioClient(++port); c3.connect(); } c3.addTuioListener(new SMTProxyTuioListener(port, listener)); System.out.println("TuioClient listening on port: " + port); TouchClient.runLeapTuioServer(port); deviceMap.put(port, TouchSource.LEAP); // MOUSE: TuioClient c4 = new TuioClient(++port); c4.connect(); while (!c4.isConnected()) { c4 = new TuioClient(++port); c4.connect(); } c4.addTuioListener(new SMTProxyTuioListener(port, listener)); System.out.println("TuioClient listening on port: " + port); // this still uses the old method, should be re-implemented // without // the socket mtt = new MouseToTUIO(parent.width, parent.height, port); deviceMap.put(port, TouchSource.MOUSE); parent.registerMethod("mouseEvent", mtt); tuioClientList.add(c2); tuioClientList.add(c3); tuioClientList.add(c4); } break; default: break; } parent.hint(PConstants.DISABLE_OPTIMIZED_STROKE); /** * Disconnects the TuioClient when the PApplet is stopped. Shuts down * any threads, disconnect from the net, unload memory, etc. */ Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { TouchClient.inShutdown = true; if (warnUncalledMethods) { SMTUtilities.warnUncalledMethods(parent); } for (TuioClient t : tuioClientList) { if (t.isConnected()) { t.disconnect(); } } for (BufferedWriter w : tuioServerInList) { try { w.newLine(); w.flush(); } catch (IOException e) {} } try { Thread.sleep(500); } catch (InterruptedException e) {} for (Process tuioServer : tuioServerList) { if (tuioServer != null) { tuioServer.destroy(); } } } })); world = new World(new Vec2(0.0f, 0.0f), true); // top groundBody = createStaticBox(0, -10.0f, parent.width, 10.f); // bottom createStaticBox(0, parent.height + 10.0f, parent.width, 10.f); // left createStaticBox(-10.0f, 0, 10.0f, parent.height); // right createStaticBox(parent.width + 10.0f, 0, 10.0f, parent.height); }
private static void init(final PApplet parent, int port, TouchSource source, Class<?>... extraClasses) { if (parent == null) { System.err .println("Null parent PApplet, pass 'this' to TouchClient.init() instead of null"); return; } // As of now the toolkit only supports OpenGL if (!parent.g.isGL()) { System.out .println("SMT only supports using OpenGL renderers, please use either OPENGL, P2D, or P3D, in the size function e.g size(displayWidth, displayHeight, P3D);"); } if (System.getProperty("os.name").equals("Mac OS X")) { TouchClient.fastPicking = false; System.out .println("Defaulting to slow picking on OS X, if calling TouchClient.setFastPicking(true); after TouchClient.init() increases performance and doesn't cause bugs, please contact SMT's developers."); } touch = SMTUtilities.getPMethod(parent, "touch"); TouchClient.parent = parent; addMethodClasses(extraClasses); // set Zone.applet so that it is consistently set at this time, not // after a zone is constructed Zone.applet = parent; // parent.registerMethod("dispose", this); parent.registerMethod("draw", new TouchClient()); parent.registerMethod("pre", new TouchClient()); // handler = new GestureHandler(); picker = new SMTZonePicker(); defaultRenderer = parent.g.getClass().getName(); listener = new SMTTuioListener(); manager = new SMTTouchManager(listener, picker); TuioClient c = new TuioClient(port); c.connect(); while (!c.isConnected()) { c = new TuioClient(++port); c.connect(); } c.addTuioListener(listener); tuioClientList.add(c); System.out.println("TuioClient listening on port: " + port); mainListenerPort = port; switch (source) { case ANDROID: // this still uses the old method, should be re-implemented without // the socket att = new AndroidToTUIO(parent.width, parent.height, port); deviceMap.put(port, source); // parent.registerMethod("touchEvent", att); //when Processing // supports this break; case MOUSE: // this still uses the old method, should be re-implemented without // the socket mtt = new MouseToTUIO(parent.width, parent.height, port); deviceMap.put(port, source); parent.registerMethod("mouseEvent", mtt); break; case TUIO_DEVICE: break; case WM_TOUCH: if (System.getProperty("os.arch").equals("x86")) { TouchClient.runWinTouchTuioServer(false, "127.0.0.1", port); } else { TouchClient.runWinTouchTuioServer(true, "127.0.0.1", port); } deviceMap.put(port, source); break; case SMART: TouchClient.runSmart2TuioServer(); deviceMap.put(port, source); break; case LEAP: TouchClient.runLeapTuioServer(port); deviceMap.put(port, source); break; case MULTIPLE: // ANDROID if (System.getProperty("java.vm.name").equalsIgnoreCase("Dalvik")) { att = new AndroidToTUIO(parent.width, parent.height, port); deviceMap.put(port, TouchSource.ANDROID); // parent.registerMethod("touchEvent", att); //when Processing // supports this break; } else { // TUIO_DEVICE: // covered already by c deviceMap.put(port, TouchSource.TUIO_DEVICE); // WM_TOUCH: TuioClient c2 = new TuioClient(++port); c2.connect(); while (!c2.isConnected()) { c2 = new TuioClient(++port); c2.connect(); } c2.addTuioListener(new SMTProxyTuioListener(port, listener)); System.out.println("TuioClient listening on port: " + port); if (System.getProperty("os.arch").equals("x86")) { TouchClient.runWinTouchTuioServer(false, "127.0.0.1", port); deviceMap.put(port, TouchSource.WM_TOUCH); } else { TouchClient.runWinTouchTuioServer(true, "127.0.0.1", port); deviceMap.put(port, TouchSource.WM_TOUCH); } // LEAP: TuioClient c3 = new TuioClient(++port); c3.connect(); while (!c3.isConnected()) { c3 = new TuioClient(++port); c3.connect(); } c3.addTuioListener(new SMTProxyTuioListener(port, listener)); System.out.println("TuioClient listening on port: " + port); TouchClient.runLeapTuioServer(port); deviceMap.put(port, TouchSource.LEAP); // MOUSE: TuioClient c4 = new TuioClient(++port); c4.connect(); while (!c4.isConnected()) { c4 = new TuioClient(++port); c4.connect(); } c4.addTuioListener(new SMTProxyTuioListener(port, listener)); System.out.println("TuioClient listening on port: " + port); // this still uses the old method, should be re-implemented // without // the socket mtt = new MouseToTUIO(parent.width, parent.height, port); deviceMap.put(port, TouchSource.MOUSE); parent.registerMethod("mouseEvent", mtt); tuioClientList.add(c2); tuioClientList.add(c3); tuioClientList.add(c4); } break; default: break; } parent.hint(PConstants.DISABLE_OPTIMIZED_STROKE); /** * Disconnects the TuioClient when the PApplet is stopped. Shuts down * any threads, disconnect from the net, unload memory, etc. */ Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { TouchClient.inShutdown = true; if (warnUncalledMethods) { SMTUtilities.warnUncalledMethods(parent); } for (TuioClient t : tuioClientList) { if (t.isConnected()) { t.disconnect(); } } for (BufferedWriter w : tuioServerInList) { try { w.newLine(); w.flush(); } catch (IOException e) {} } try { Thread.sleep(500); } catch (InterruptedException e) {} for (Process tuioServer : tuioServerList) { if (tuioServer != null) { tuioServer.destroy(); } } } })); world = new World(new Vec2(0.0f, 0.0f), true); // top groundBody = createStaticBox(0, -10.0f, parent.width, 10.f); // bottom createStaticBox(0, parent.height + 10.0f, parent.width, 10.f); // left createStaticBox(-10.0f, 0, 10.0f, parent.height); // right createStaticBox(parent.width + 10.0f, 0, 10.0f, parent.height); }
diff --git a/src/com/google/bitcoin/core/DiskBlockStore.java b/src/com/google/bitcoin/core/DiskBlockStore.java index 12c6cb8..6098828 100644 --- a/src/com/google/bitcoin/core/DiskBlockStore.java +++ b/src/com/google/bitcoin/core/DiskBlockStore.java @@ -1,164 +1,164 @@ /** * Copyright 2011 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.bitcoin.core; import java.io.*; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import static com.google.bitcoin.core.Utils.LOG; /** * Stores the block chain to disk but still holds it in memory. This is intended for desktop apps and tests. * Constrained environments like mobile phones probably won't want to or be able to store all the block headers in RAM. */ public class DiskBlockStore implements BlockStore { private FileOutputStream stream; private Map<Sha256Hash, StoredBlock> blockMap; private Sha256Hash chainHead; private NetworkParameters params; public DiskBlockStore(NetworkParameters params, File file) throws BlockStoreException { this.params = params; blockMap = new HashMap<Sha256Hash, StoredBlock>(); try { load(file); stream = new FileOutputStream(file, true); // Do append. } catch (IOException e) { LOG(e.toString()); createNewStore(params, file); } } private void createNewStore(NetworkParameters params, File file) throws BlockStoreException { // Create a new block store if the file wasn't found or anything went wrong whilst reading. blockMap.clear(); try { stream = new FileOutputStream(file, false); // Do not append, create fresh. stream.write(1); // Version. } catch (IOException e1) { // We could not load a block store nor could we create a new one! throw new BlockStoreException(e1); } try { // Set up the genesis block. When we start out fresh, it is by definition the top of the chain. Block genesis = params.genesisBlock.cloneAsHeader(); StoredBlock storedGenesis = new StoredBlock(genesis, genesis.getWork(), 0); this.chainHead = new Sha256Hash(storedGenesis.getHeader().getHash()); stream.write(this.chainHead.hash); put(storedGenesis); } catch (VerificationException e1) { throw new RuntimeException(e1); // Cannot happen. } catch (IOException e) { throw new BlockStoreException(e); } } private void load(File file) throws IOException, BlockStoreException { LOG("Reading block store from " + file.getAbsolutePath()); - FileInputStream input = new FileInputStream(file); + InputStream input = new BufferedInputStream(new FileInputStream(file)); // Read a version byte. int version = input.read(); if (version == -1) { // No such file or the file was empty. throw new FileNotFoundException(file.getName() + " does not exist or is empty"); } if (version != 1) { throw new BlockStoreException("Bad version number: " + version); } // Chain head pointer is the first thing in the file. byte[] chainHeadHash = new byte[32]; input.read(chainHeadHash); this.chainHead = new Sha256Hash(chainHeadHash); LOG("Read chain head from disk: " + this.chainHead); long now = System.currentTimeMillis(); // Rest of file is raw block headers. byte[] headerBytes = new byte[Block.HEADER_SIZE]; try { while (true) { // Read a block from disk. if (input.read(headerBytes) < 80) { // End of file. break; } // Parse it. Block b = new Block(params, headerBytes); // Look up the previous block it connects to. StoredBlock prev = get(b.getPrevBlockHash()); StoredBlock s; if (prev == null) { // First block in the stored chain has to be treated specially. if (b.equals(params.genesisBlock)) { s = new StoredBlock(params.genesisBlock.cloneAsHeader(), params.genesisBlock.getWork(), 0); } else { throw new BlockStoreException("Could not connect " + Utils.bytesToHexString(b.getHash()) + " to " + Utils.bytesToHexString(b.getPrevBlockHash())); } } else { // Don't try to verify the genesis block to avoid upsetting the unit tests. b.verify(); // Calculate its height and total chain work. s = prev.build(b); } // Save in memory. blockMap.put(new Sha256Hash(b.getHash()), s); } } catch (ProtocolException e) { // Corrupted file. throw new BlockStoreException(e); } catch (VerificationException e) { // Should not be able to happen unless the file contains bad blocks. throw new BlockStoreException(e); } long elapsed = System.currentTimeMillis() - now; LOG("Block chain read complete in " + elapsed + "ms"); } public synchronized void put(StoredBlock block) throws BlockStoreException { try { Sha256Hash hash = new Sha256Hash(block.getHeader().getHash()); assert blockMap.get(hash) == null : "Attempt to insert duplicate"; // Append to the end of the file. The other fields in StoredBlock will be recalculated when it's reloaded. byte[] bytes = block.getHeader().bitcoinSerialize(); stream.write(bytes); stream.flush(); blockMap.put(hash, block); } catch (IOException e) { throw new BlockStoreException(e); } } public synchronized StoredBlock get(byte[] hash) throws BlockStoreException { return blockMap.get(new Sha256Hash(hash)); } public synchronized StoredBlock getChainHead() throws BlockStoreException { return blockMap.get(chainHead); } public synchronized void setChainHead(StoredBlock chainHead) throws BlockStoreException { try { byte[] hash = chainHead.getHeader().getHash(); this.chainHead = new Sha256Hash(hash); // Write out new hash to the first 32 bytes of the file past one (first byte is version number). stream.getChannel().write(ByteBuffer.wrap(hash), 1); } catch (IOException e) { throw new BlockStoreException(e); } } }
true
true
private void load(File file) throws IOException, BlockStoreException { LOG("Reading block store from " + file.getAbsolutePath()); FileInputStream input = new FileInputStream(file); // Read a version byte. int version = input.read(); if (version == -1) { // No such file or the file was empty. throw new FileNotFoundException(file.getName() + " does not exist or is empty"); } if (version != 1) { throw new BlockStoreException("Bad version number: " + version); } // Chain head pointer is the first thing in the file. byte[] chainHeadHash = new byte[32]; input.read(chainHeadHash); this.chainHead = new Sha256Hash(chainHeadHash); LOG("Read chain head from disk: " + this.chainHead); long now = System.currentTimeMillis(); // Rest of file is raw block headers. byte[] headerBytes = new byte[Block.HEADER_SIZE]; try { while (true) { // Read a block from disk. if (input.read(headerBytes) < 80) { // End of file. break; } // Parse it. Block b = new Block(params, headerBytes); // Look up the previous block it connects to. StoredBlock prev = get(b.getPrevBlockHash()); StoredBlock s; if (prev == null) { // First block in the stored chain has to be treated specially. if (b.equals(params.genesisBlock)) { s = new StoredBlock(params.genesisBlock.cloneAsHeader(), params.genesisBlock.getWork(), 0); } else { throw new BlockStoreException("Could not connect " + Utils.bytesToHexString(b.getHash()) + " to " + Utils.bytesToHexString(b.getPrevBlockHash())); } } else { // Don't try to verify the genesis block to avoid upsetting the unit tests. b.verify(); // Calculate its height and total chain work. s = prev.build(b); } // Save in memory. blockMap.put(new Sha256Hash(b.getHash()), s); } } catch (ProtocolException e) { // Corrupted file. throw new BlockStoreException(e); } catch (VerificationException e) { // Should not be able to happen unless the file contains bad blocks. throw new BlockStoreException(e); } long elapsed = System.currentTimeMillis() - now; LOG("Block chain read complete in " + elapsed + "ms"); }
private void load(File file) throws IOException, BlockStoreException { LOG("Reading block store from " + file.getAbsolutePath()); InputStream input = new BufferedInputStream(new FileInputStream(file)); // Read a version byte. int version = input.read(); if (version == -1) { // No such file or the file was empty. throw new FileNotFoundException(file.getName() + " does not exist or is empty"); } if (version != 1) { throw new BlockStoreException("Bad version number: " + version); } // Chain head pointer is the first thing in the file. byte[] chainHeadHash = new byte[32]; input.read(chainHeadHash); this.chainHead = new Sha256Hash(chainHeadHash); LOG("Read chain head from disk: " + this.chainHead); long now = System.currentTimeMillis(); // Rest of file is raw block headers. byte[] headerBytes = new byte[Block.HEADER_SIZE]; try { while (true) { // Read a block from disk. if (input.read(headerBytes) < 80) { // End of file. break; } // Parse it. Block b = new Block(params, headerBytes); // Look up the previous block it connects to. StoredBlock prev = get(b.getPrevBlockHash()); StoredBlock s; if (prev == null) { // First block in the stored chain has to be treated specially. if (b.equals(params.genesisBlock)) { s = new StoredBlock(params.genesisBlock.cloneAsHeader(), params.genesisBlock.getWork(), 0); } else { throw new BlockStoreException("Could not connect " + Utils.bytesToHexString(b.getHash()) + " to " + Utils.bytesToHexString(b.getPrevBlockHash())); } } else { // Don't try to verify the genesis block to avoid upsetting the unit tests. b.verify(); // Calculate its height and total chain work. s = prev.build(b); } // Save in memory. blockMap.put(new Sha256Hash(b.getHash()), s); } } catch (ProtocolException e) { // Corrupted file. throw new BlockStoreException(e); } catch (VerificationException e) { // Should not be able to happen unless the file contains bad blocks. throw new BlockStoreException(e); } long elapsed = System.currentTimeMillis() - now; LOG("Block chain read complete in " + elapsed + "ms"); }
diff --git a/org.eclipse.stem.diseasemodels/src/org/eclipse/stem/diseasemodels/standard/impl/StandardDiseaseModelImpl.java b/org.eclipse.stem.diseasemodels/src/org/eclipse/stem/diseasemodels/standard/impl/StandardDiseaseModelImpl.java index 03ff9333..7a4e1bed 100644 --- a/org.eclipse.stem.diseasemodels/src/org/eclipse/stem/diseasemodels/standard/impl/StandardDiseaseModelImpl.java +++ b/org.eclipse.stem.diseasemodels/src/org/eclipse/stem/diseasemodels/standard/impl/StandardDiseaseModelImpl.java @@ -1,796 +1,797 @@ package org.eclipse.stem.diseasemodels.standard.impl; /******************************************************************************* * Copyright (c) 2006 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.stem.core.graph.DynamicLabel; import org.eclipse.stem.core.graph.IntegrationLabel; import org.eclipse.stem.core.graph.IntegrationLabelValue; import org.eclipse.stem.core.graph.Node; import org.eclipse.stem.core.graph.NodeLabel; import org.eclipse.stem.core.graph.SimpleDataExchangeLabelValue; import org.eclipse.stem.core.model.STEMTime; import org.eclipse.stem.definitions.labels.AreaLabel; import org.eclipse.stem.definitions.labels.PopulationLabel; import org.eclipse.stem.diseasemodels.Activator; import org.eclipse.stem.diseasemodels.standard.DiseaseModelLabel; import org.eclipse.stem.diseasemodels.standard.DiseaseModelLabelValue; import org.eclipse.stem.diseasemodels.standard.DiseaseModelState; import org.eclipse.stem.diseasemodels.standard.StandardDiseaseModel; import org.eclipse.stem.diseasemodels.standard.StandardDiseaseModelLabel; import org.eclipse.stem.diseasemodels.standard.StandardDiseaseModelLabelValue; import org.eclipse.stem.diseasemodels.standard.StandardDiseaseModelState; import org.eclipse.stem.diseasemodels.standard.StandardPackage; /** * <!-- begin-user-doc --> An implementation of the model object '<em><b>Disease Model</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.eclipse.stem.diseasemodels.standard.impl.StandardDiseaseModelImpl#getTotalPopulationCount <em>Total Population Count</em>}</li> * <li>{@link org.eclipse.stem.diseasemodels.standard.impl.StandardDiseaseModelImpl#getTotalPopulationCountReciprocal <em>Total Population Count Reciprocal</em>}</li> * <li>{@link org.eclipse.stem.diseasemodels.standard.impl.StandardDiseaseModelImpl#getTotalArea <em>Total Area</em>}</li> * <li>{@link org.eclipse.stem.diseasemodels.standard.impl.StandardDiseaseModelImpl#getReferencePopulationDensity <em>Reference Population Density</em>}</li> * </ul> * </p> * * @generated */ public abstract class StandardDiseaseModelImpl extends DiseaseModelImpl implements StandardDiseaseModel { /** * The default value of the '{@link #getTotalPopulationCount() <em>Total Population Count</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getTotalPopulationCount() * @generated * @ordered */ protected static final double TOTAL_POPULATION_COUNT_EDEFAULT = 0.0; /** * The cached value of the '{@link #getTotalPopulationCount() <em>Total Population Count</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getTotalPopulationCount() * @generated * @ordered */ protected double totalPopulationCount = TOTAL_POPULATION_COUNT_EDEFAULT; /** * The default value of the '{@link #getTotalPopulationCountReciprocal() <em>Total Population Count Reciprocal</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getTotalPopulationCountReciprocal() * @generated * @ordered */ protected static final double TOTAL_POPULATION_COUNT_RECIPROCAL_EDEFAULT = 0.0; /** * The cached value of the '{@link #getTotalPopulationCountReciprocal() <em>Total Population Count Reciprocal</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getTotalPopulationCountReciprocal() * @generated * @ordered */ protected double totalPopulationCountReciprocal = TOTAL_POPULATION_COUNT_RECIPROCAL_EDEFAULT; /** * The default value of the '{@link #getTotalArea() <em>Total Area</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getTotalArea() * @generated * @ordered */ protected static final double TOTAL_AREA_EDEFAULT = 0.0; /** * The cached value of the '{@link #getTotalArea() <em>Total Area</em>}' attribute. * <!-- begin-user-doc --> <!-- end-user-doc --> * @see #getTotalArea() * @generated * @ordered */ protected double totalArea = TOTAL_AREA_EDEFAULT; /** * The default value of the '{@link #getReferencePopulationDensity() <em>Reference Population Density</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getReferencePopulationDensity() * @generated * @ordered */ protected static final double REFERENCE_POPULATION_DENSITY_EDEFAULT = 100.0; /** * The cached value of the '{@link #getReferencePopulationDensity() <em>Reference Population Density</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getReferencePopulationDensity() * @generated * @ordered */ protected double referencePopulationDensity = REFERENCE_POPULATION_DENSITY_EDEFAULT; /** * We only need one of these. * * @see #updateLabels(STEMTime, long) */ protected StandardDiseaseModelLabelValue departures = (StandardDiseaseModelLabelValue) createDiseaseModelLabelValue(); /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ protected StandardDiseaseModelImpl() { super(); } /** * @param standardDiseaseModel * the StandardDiseaseModel disease model to be initialized * @param diseaseModelName * @param backgroundMortalityRate * @param immunityLossRate * @param incubationRate * @param nonLinearityCoefficient * @param timePeriod * @param populationIdentifier */ protected static StandardDiseaseModel initializeStandardDiseaseModel( final StandardDiseaseModel standardDiseaseModel, final String diseaseModelName, final double backgroundMortalityRate, final long timePeriod, final String populationIdentifier) { DiseaseModelImpl.initializeDiseaseModel(standardDiseaseModel, diseaseModelName, backgroundMortalityRate, timePeriod, populationIdentifier); return standardDiseaseModel; } // initializeStandardDiseaseModel /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return StandardPackage.Literals.STANDARD_DISEASE_MODEL; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public double getTotalPopulationCount() { return totalPopulationCount; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setTotalPopulationCount(double newTotalPopulationCount) { double oldTotalPopulationCount = totalPopulationCount; totalPopulationCount = newTotalPopulationCount; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, StandardPackage.STANDARD_DISEASE_MODEL__TOTAL_POPULATION_COUNT, oldTotalPopulationCount, totalPopulationCount)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public double getTotalPopulationCountReciprocal() { return totalPopulationCountReciprocal; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public double getTotalArea() { return totalArea; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ public void setTotalArea(double newTotalArea) { double oldTotalArea = totalArea; totalArea = newTotalArea; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, StandardPackage.STANDARD_DISEASE_MODEL__TOTAL_AREA, oldTotalArea, totalArea)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getReferencePopulationDensity() { return referencePopulationDensity; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setReferencePopulationDensity(double newReferencePopulationDensity) { double oldReferencePopulationDensity = referencePopulationDensity; referencePopulationDensity = newReferencePopulationDensity; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, StandardPackage.STANDARD_DISEASE_MODEL__REFERENCE_POPULATION_DENSITY, oldReferencePopulationDensity, referencePopulationDensity)); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ public void addToTotalPopulationCount(double populationCount) { setTotalPopulationCount(totalPopulationCount + populationCount); } // addToTotalPopulationCount /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ public double computeTotalPopulationCountReciprocal() { return totalPopulationCountReciprocal = 1.0 / totalPopulationCount; } // computeTotalPopulationCountReciprocal /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated NOT */ public void addToTotalArea(double area) { setTotalArea(totalArea + area); } // addToTotalArea /** * calculateDelta will use the current label values updated by * the disease model and upon return the delta label values * are set with an estimate of the derivatives to advance to the * next step * * @param time current time * @param timeDelta delta time step * @param labels The labels to update */ public void calculateDelta(STEMTime time, long timeDelta, EList<DynamicLabel> labels) { // Iterate through each of the labels we need to update. // Place holders to keep delta values. DiseaseModelLabelValue birthDeathsDelta = this.createDiseaseModelLabelValue(); DiseaseModelLabelValue diseaseDelta = this.createDiseaseModelLabelValue(); for (final Iterator<DynamicLabel> currentStateLabelIter = labels .iterator(); currentStateLabelIter.hasNext();) { final StandardDiseaseModelLabel diseaseLabel = (StandardDiseaseModelLabel) currentStateLabelIter .next(); assert diseaseLabel.getPopulationLabel().getPopulationIdentifier() .equals(getPopulationIdentifier()); // This current state of the disease for this label probed for the // next delta final StandardDiseaseModelLabelValue currentProbeState = (StandardDiseaseModelLabelValue)diseaseLabel .getProbeValue(); // 1) Compute Birth and Deaths state delta changes final StandardDiseaseModelLabelValue diseaseDeathDeltas = computeDiseaseDeathsDeltas(time, diseaseLabel, currentProbeState, timeDelta, birthDeathsDelta); // 2) Compute the delta changes caused by the Disease itself final StandardDiseaseModelLabelValue diseaseDeltas = computeDiseaseDeltas(time, currentProbeState, diseaseLabel, timeDelta, diseaseDelta); // Just capture the incidence that was passed on from computeTransistions final double incidence = diseaseDeltas.getIncidence(); /* * 5) Record the new state variable values. * * These will become the current state variable values at the end of * the current simulation cycle and before the next. */ // This is the delta disease label final StandardDiseaseModelLabelValue deltaState = (StandardDiseaseModelLabelValue)diseaseLabel .getDeltaValue(); // Reset the state deltaState.reset(); // 1) Add birth/death deltas and set the departures deltaState.add((IntegrationLabelValue)diseaseDeathDeltas); if(diseaseDeathDeltas.getDiseaseDeaths() > 0.0) deltaState.getDepartures().put(diseaseLabel.getNode(), diseaseDeathDeltas.getDiseaseDeaths()); // 2) Disease deltas deltaState.add((IntegrationLabelValue)diseaseDeltas); // and pass on the incidence deltaState.setIncidence(incidence); birthDeathsDelta.reset(); diseaseDelta.reset(); } // for } public void applyExternalDeltas(STEMTime time, long timeDelta, EList<DynamicLabel> labels) { for (final Iterator<DynamicLabel> currentStateLabelIter = labels .iterator(); currentStateLabelIter.hasNext();) { final StandardDiseaseModelLabel diseaseLabel = (StandardDiseaseModelLabel) currentStateLabelIter .next(); StandardDiseaseModelLabelValue myDelta = (StandardDiseaseModelLabelValue)diseaseLabel.getDeltaValue(); Node n = diseaseLabel.getNode(); // Find other labels on the node that wants to exchange data EList<NodeLabel> labs = n.getLabels(); for(NodeLabel l:labs) { if(l instanceof IntegrationLabel && !l.equals(diseaseLabel) && ((IntegrationLabel)l).getIdentifier().equals(diseaseLabel.getIdentifier())) { SimpleDataExchangeLabelValue sdeLabelValue = (SimpleDataExchangeLabelValue)((IntegrationLabel)l).getDeltaValue(); Map<Node, Double>arrivals = sdeLabelValue.getArrivals(); Map<Node, Double>departures = sdeLabelValue.getDepartures(); if(arrivals == null || departures == null) { Activator.logError("Error, null arrivals or departures for label "+l, new Exception()); continue; } // Arrivals - for(Node n2:arrivals.keySet()) { + for (Entry<Node,Double> entry : arrivals.entrySet()) { + //for(Node n2:arrivals.keySet()) { // Arrivals are births and goes into the S state if the node is the local node. - if(n2.equals(n)) - myDelta.setS(myDelta.getS() + arrivals.get(n2)); + if(entry.getKey().equals(n)) + myDelta.setS(myDelta.getS() + entry.getValue().doubleValue()); else { // For other nodes, it's migration of population - double inflow = arrivals.get(n2); + double inflow = entry.getValue().doubleValue(); // Find the corresponding disease label on the other node - for(NodeLabel nl:n2.getLabels()) + for(NodeLabel nl:entry.getKey().getLabels()) if(nl instanceof StandardDiseaseModelLabel && ((StandardDiseaseModelLabel)nl).getDecorator().equals(this)) { StandardDiseaseModelLabelValue value = (StandardDiseaseModelLabelValue)EcoreUtil.copy(((StandardDiseaseModelLabel)nl).getTempValue()); if(value.getPopulationCount() > 0.0) value.scale(inflow/value.getPopulationCount()); myDelta.add((IntegrationLabelValue)value); } } } // Departures for(Entry<Node,Double> entry : departures.entrySet()) { // Departures are either deaths or population moving to other nodes, hence we substract from the local node. StandardDiseaseModelLabelValue currentState = null; if(entry.getKey().equals(n)) currentState = (StandardDiseaseModelLabelValue)EcoreUtil.copy((StandardDiseaseModelLabelValue)diseaseLabel.getProbeValue()); // Should be safe to use probe value for deaths else currentState = (StandardDiseaseModelLabelValue)EcoreUtil.copy((StandardDiseaseModelLabelValue)diseaseLabel.getTempValue()); // Need to use temp value for migration or an inbalance will occyr double populationCount = currentState.getPopulationCount(); double outflow = entry.getValue().doubleValue(); double factor = outflow/populationCount; if(Double.isNaN(factor) || Double.isInfinite(factor)) factor = 0.0; //safe currentState.scale(factor); // Remember disease deaths since they will be overwritten by sub myDelta.sub((IntegrationLabelValue)currentState); } } } } } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case StandardPackage.STANDARD_DISEASE_MODEL__TOTAL_POPULATION_COUNT: return getTotalPopulationCount(); case StandardPackage.STANDARD_DISEASE_MODEL__TOTAL_POPULATION_COUNT_RECIPROCAL: return getTotalPopulationCountReciprocal(); case StandardPackage.STANDARD_DISEASE_MODEL__TOTAL_AREA: return getTotalArea(); case StandardPackage.STANDARD_DISEASE_MODEL__REFERENCE_POPULATION_DENSITY: return getReferencePopulationDensity(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case StandardPackage.STANDARD_DISEASE_MODEL__TOTAL_POPULATION_COUNT: setTotalPopulationCount((Double)newValue); return; case StandardPackage.STANDARD_DISEASE_MODEL__TOTAL_AREA: setTotalArea((Double)newValue); return; case StandardPackage.STANDARD_DISEASE_MODEL__REFERENCE_POPULATION_DENSITY: setReferencePopulationDensity((Double)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case StandardPackage.STANDARD_DISEASE_MODEL__TOTAL_POPULATION_COUNT: setTotalPopulationCount(TOTAL_POPULATION_COUNT_EDEFAULT); return; case StandardPackage.STANDARD_DISEASE_MODEL__TOTAL_AREA: setTotalArea(TOTAL_AREA_EDEFAULT); return; case StandardPackage.STANDARD_DISEASE_MODEL__REFERENCE_POPULATION_DENSITY: setReferencePopulationDensity(REFERENCE_POPULATION_DENSITY_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case StandardPackage.STANDARD_DISEASE_MODEL__TOTAL_POPULATION_COUNT: return totalPopulationCount != TOTAL_POPULATION_COUNT_EDEFAULT; case StandardPackage.STANDARD_DISEASE_MODEL__TOTAL_POPULATION_COUNT_RECIPROCAL: return totalPopulationCountReciprocal != TOTAL_POPULATION_COUNT_RECIPROCAL_EDEFAULT; case StandardPackage.STANDARD_DISEASE_MODEL__TOTAL_AREA: return totalArea != TOTAL_AREA_EDEFAULT; case StandardPackage.STANDARD_DISEASE_MODEL__REFERENCE_POPULATION_DENSITY: return referencePopulationDensity != REFERENCE_POPULATION_DENSITY_EDEFAULT; } return super.eIsSet(featureID); } /** * Standard disease models do not update the labels, it's the * task of the Solver to do that. * * Standard Disease Models * @see org.eclipse.stem.core.model.impl.DecoratorImpl#updateLabels(org.eclipse.stem.core.graph.Graph, * org.eclipse.stem.core.model.STEMTime) */ @Override public void updateLabels(final STEMTime time, final long timeDelta, int cycle) { throw new UnsupportedOperationException(); } /** * Populate the pipe system nodes initially */ /** * @see org.eclipse.stem.diseasemodels.standard.impl.DiseaseModelImpl#initializeDiseaseState(org.eclipse.stem.diseasemodels.standard.DiseaseModelState, * org.eclipse.stem.diseasemodels.standard.DiseaseModelLabel) */ @Override public DiseaseModelState initializeDiseaseState( final DiseaseModelState diseaseModelState, final DiseaseModelLabel diseaseModelLabel) { final PopulationLabel populationLabel = diseaseModelLabel .getPopulationLabel(); final double populationCount = populationLabel .getCurrentPopulationValue().getCount(); // Accumulate the population count in the disease model addToTotalPopulationCount(populationCount); double area = getArea(populationLabel); // If we have a bad data set it could be that the area would be // unspecified or zero. // Do we have a bad area value? if (area <= 0.0) { // Yes reportBadAreaValue(populationLabel, area); area = 1.0; } // if bad area value // Accumulate the area in the disease model so we'll know the total when // we do our next pass and compute the area ratio addToTotalArea(area); return diseaseModelState; } // initializeDiseaseState /** * Here we compute and set the ratio between the total area and the area * used for this {@link DiseaseModelLabel}. This value is used to determine * the <em>transmission scale factor</em>. * * @see #computeTransitions(StandardDiseaseModelLabelValue, * StandardDiseaseModelLabel, long) * @see org.eclipse.stem.diseasemodels.standard.impl.DiseaseModelImpl#initializeDiseaseState(org.eclipse.stem.diseasemodels.standard.DiseaseModelLabel) */ @Override public void initializeDiseaseState(final DiseaseModelLabel diseaseModelLabel) { final StandardDiseaseModelState sdms = (StandardDiseaseModelState) diseaseModelLabel .getDiseaseModelState(); // Is there a population ? if (totalPopulationCount > 0.0) { // Yes double area = getArea(diseaseModelLabel.getPopulationLabel()); // Do we have a bad area value? if (area <= 0.0) { // Yes reportBadAreaValue(diseaseModelLabel.getPopulationLabel(), area); area = 1.0; } // if bad area value final double ratio = getTotalArea() / area; sdms.setAreaRatio(ratio); } } // initializeDiseaseState /** * @param populationLabel * the population label that labels the node * @return the area of the node associated with the label */ public double getArea(final PopulationLabel populationLabel) { double retValue = 0.0; // The population label could have an area specified for the population // that we should use instead of the area of the region labeled by the // population label. This value would be specified if the population was // densely packed into a small area of the larger region, for instance // like a city in an otherwise large desert. retValue = populationLabel.getPopulatedArea(); // Is there an area specified for the population? if (retValue == 0.0) { // No // Ok, go find the area label and return the area of the region for (final Iterator<NodeLabel> labelIter = populationLabel.getNode() .getLabels().iterator(); labelIter.hasNext();) { final NodeLabel nodeLabel = labelIter.next(); // Is this an area label? if (nodeLabel instanceof AreaLabel) { // Yes final AreaLabel areaLabel = (AreaLabel) nodeLabel; retValue = areaLabel.getCurrentAreaValue().getArea(); break; } } // for } // If no population area specified return retValue; } // getArea /** * @param populationLabel * @param area */ private void reportBadAreaValue(final PopulationLabel populationLabel, double area) { // The bad value could be specified for the node or be an override // value specified for the population. // Is the bad value from the node? if (populationLabel.getPopulatedArea() == 0.0) { // Yes Activator.logError("The area value of \"" + area + "\" specified for \"" + populationLabel.getNode().toString() + "\" is not greater than zero (0.0)", null); } // if bad value for node area else { Activator.logError("The area value of \"" + area + "\" specified for the population \"" + populationLabel.getName() + "\" for the region \"" + populationLabel.getNode().toString() + "\" is not greater than zero (0.0)", null); } } // reportBadAreaValue /** * Perform disease model specific changes to the additions to each state and * to the deaths from each state. This method is used to perform stochastic * modifications to the next disease state. * * @param currentState * the current disease state */ public void doModelSpecificAdjustments( final StandardDiseaseModelLabelValue currentState) { // Do nothing here. Sub-classes override this method to make changes } // doModelSpecificAdjustments /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public boolean isDeterministic() { // TODO: implement this method // Ensure that you remove @generated or mark it @generated NOT throw new UnsupportedOperationException(); } /** * computeDiseaseDeltas. This method calculates the delta changes for each disease state depending * on disease parameters and mixing factors * * @param time * STEM time * @param currentState * the current state of the population * @param diseaseLabel * the disease label for which the state transitions are being * computed. * @param timeDelta * the time period (milliseconds) over which the population * members transition to new states * @param cycle * the simulation cycle we're in * @return a disease state label value that contains the delta changes in * population members for each state. */ public abstract StandardDiseaseModelLabelValue computeDiseaseDeltas( final STEMTime time, final StandardDiseaseModelLabelValue currentState, final StandardDiseaseModelLabel diseaseLabel, final long timeDelta, DiseaseModelLabelValue returnValue); /** * computeDiseaseDeathsDeltas Compute the delta vector resulting from disease deaths * * @param time * STEM time * @param diseaseLabel * @param currentLabelValue * the current label value of the disease model * @param timeDelta * the time period over which the population members die * @return the disease state label value that represents the number of * deaths in each state. */ public abstract StandardDiseaseModelLabelValue computeDiseaseDeathsDeltas( final STEMTime time, final StandardDiseaseModelLabel diseaseLabel, final StandardDiseaseModelLabelValue currentLabelValue, final long timeDelta, DiseaseModelLabelValue returnValue); /** * @param fractionToDepart * @param nextState * @return */ abstract protected StandardDiseaseModelLabelValue computeDepartures( double fractionToDepart, StandardDiseaseModelLabelValue nextState); @Override public void resetLabels() { super.resetLabels(); } // resetLabels /** * <!-- begin-user-doc --> <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (totalPopulationCount: "); //$NON-NLS-1$ result.append(totalPopulationCount); result.append(", totalPopulationCountReciprocal: "); //$NON-NLS-1$ result.append(totalPopulationCountReciprocal); result.append(", totalArea: "); //$NON-NLS-1$ result.append(totalArea); result.append(", referencePopulationDensity: "); //$NON-NLS-1$ result.append(referencePopulationDensity); result.append(')'); return result.toString(); } /** * @see org.eclipse.stem.diseasemodels.standard.impl.DiseaseModelImpl#sane() */ @Override public boolean sane() { boolean retValue = super.sane(); retValue = retValue && totalPopulationCount >= TOTAL_POPULATION_COUNT_EDEFAULT; assert retValue; retValue = retValue && !Double.isInfinite(totalPopulationCount); assert retValue; retValue = retValue && !Double.isNaN(totalPopulationCount); assert retValue; retValue = retValue && totalPopulationCountReciprocal >= TOTAL_POPULATION_COUNT_RECIPROCAL_EDEFAULT; assert retValue; retValue = retValue && !Double.isInfinite(totalPopulationCountReciprocal); assert retValue; retValue = retValue && !Double.isNaN(totalPopulationCountReciprocal); assert retValue; retValue = retValue && totalArea >= TOTAL_AREA_EDEFAULT; assert retValue; retValue = retValue && !Double.isInfinite(totalArea); assert retValue; retValue = retValue && !Double.isNaN(totalArea); assert retValue; return retValue; } // sane } // StandardDiseaseModelImpl
false
true
public void applyExternalDeltas(STEMTime time, long timeDelta, EList<DynamicLabel> labels) { for (final Iterator<DynamicLabel> currentStateLabelIter = labels .iterator(); currentStateLabelIter.hasNext();) { final StandardDiseaseModelLabel diseaseLabel = (StandardDiseaseModelLabel) currentStateLabelIter .next(); StandardDiseaseModelLabelValue myDelta = (StandardDiseaseModelLabelValue)diseaseLabel.getDeltaValue(); Node n = diseaseLabel.getNode(); // Find other labels on the node that wants to exchange data EList<NodeLabel> labs = n.getLabels(); for(NodeLabel l:labs) { if(l instanceof IntegrationLabel && !l.equals(diseaseLabel) && ((IntegrationLabel)l).getIdentifier().equals(diseaseLabel.getIdentifier())) { SimpleDataExchangeLabelValue sdeLabelValue = (SimpleDataExchangeLabelValue)((IntegrationLabel)l).getDeltaValue(); Map<Node, Double>arrivals = sdeLabelValue.getArrivals(); Map<Node, Double>departures = sdeLabelValue.getDepartures(); if(arrivals == null || departures == null) { Activator.logError("Error, null arrivals or departures for label "+l, new Exception()); continue; } // Arrivals for(Node n2:arrivals.keySet()) { // Arrivals are births and goes into the S state if the node is the local node. if(n2.equals(n)) myDelta.setS(myDelta.getS() + arrivals.get(n2)); else { // For other nodes, it's migration of population double inflow = arrivals.get(n2); // Find the corresponding disease label on the other node for(NodeLabel nl:n2.getLabels()) if(nl instanceof StandardDiseaseModelLabel && ((StandardDiseaseModelLabel)nl).getDecorator().equals(this)) { StandardDiseaseModelLabelValue value = (StandardDiseaseModelLabelValue)EcoreUtil.copy(((StandardDiseaseModelLabel)nl).getTempValue()); if(value.getPopulationCount() > 0.0) value.scale(inflow/value.getPopulationCount()); myDelta.add((IntegrationLabelValue)value); } } } // Departures for(Entry<Node,Double> entry : departures.entrySet()) { // Departures are either deaths or population moving to other nodes, hence we substract from the local node. StandardDiseaseModelLabelValue currentState = null; if(entry.getKey().equals(n)) currentState = (StandardDiseaseModelLabelValue)EcoreUtil.copy((StandardDiseaseModelLabelValue)diseaseLabel.getProbeValue()); // Should be safe to use probe value for deaths else currentState = (StandardDiseaseModelLabelValue)EcoreUtil.copy((StandardDiseaseModelLabelValue)diseaseLabel.getTempValue()); // Need to use temp value for migration or an inbalance will occyr double populationCount = currentState.getPopulationCount(); double outflow = entry.getValue().doubleValue(); double factor = outflow/populationCount; if(Double.isNaN(factor) || Double.isInfinite(factor)) factor = 0.0; //safe currentState.scale(factor); // Remember disease deaths since they will be overwritten by sub myDelta.sub((IntegrationLabelValue)currentState); } } } } }
public void applyExternalDeltas(STEMTime time, long timeDelta, EList<DynamicLabel> labels) { for (final Iterator<DynamicLabel> currentStateLabelIter = labels .iterator(); currentStateLabelIter.hasNext();) { final StandardDiseaseModelLabel diseaseLabel = (StandardDiseaseModelLabel) currentStateLabelIter .next(); StandardDiseaseModelLabelValue myDelta = (StandardDiseaseModelLabelValue)diseaseLabel.getDeltaValue(); Node n = diseaseLabel.getNode(); // Find other labels on the node that wants to exchange data EList<NodeLabel> labs = n.getLabels(); for(NodeLabel l:labs) { if(l instanceof IntegrationLabel && !l.equals(diseaseLabel) && ((IntegrationLabel)l).getIdentifier().equals(diseaseLabel.getIdentifier())) { SimpleDataExchangeLabelValue sdeLabelValue = (SimpleDataExchangeLabelValue)((IntegrationLabel)l).getDeltaValue(); Map<Node, Double>arrivals = sdeLabelValue.getArrivals(); Map<Node, Double>departures = sdeLabelValue.getDepartures(); if(arrivals == null || departures == null) { Activator.logError("Error, null arrivals or departures for label "+l, new Exception()); continue; } // Arrivals for (Entry<Node,Double> entry : arrivals.entrySet()) { //for(Node n2:arrivals.keySet()) { // Arrivals are births and goes into the S state if the node is the local node. if(entry.getKey().equals(n)) myDelta.setS(myDelta.getS() + entry.getValue().doubleValue()); else { // For other nodes, it's migration of population double inflow = entry.getValue().doubleValue(); // Find the corresponding disease label on the other node for(NodeLabel nl:entry.getKey().getLabels()) if(nl instanceof StandardDiseaseModelLabel && ((StandardDiseaseModelLabel)nl).getDecorator().equals(this)) { StandardDiseaseModelLabelValue value = (StandardDiseaseModelLabelValue)EcoreUtil.copy(((StandardDiseaseModelLabel)nl).getTempValue()); if(value.getPopulationCount() > 0.0) value.scale(inflow/value.getPopulationCount()); myDelta.add((IntegrationLabelValue)value); } } } // Departures for(Entry<Node,Double> entry : departures.entrySet()) { // Departures are either deaths or population moving to other nodes, hence we substract from the local node. StandardDiseaseModelLabelValue currentState = null; if(entry.getKey().equals(n)) currentState = (StandardDiseaseModelLabelValue)EcoreUtil.copy((StandardDiseaseModelLabelValue)diseaseLabel.getProbeValue()); // Should be safe to use probe value for deaths else currentState = (StandardDiseaseModelLabelValue)EcoreUtil.copy((StandardDiseaseModelLabelValue)diseaseLabel.getTempValue()); // Need to use temp value for migration or an inbalance will occyr double populationCount = currentState.getPopulationCount(); double outflow = entry.getValue().doubleValue(); double factor = outflow/populationCount; if(Double.isNaN(factor) || Double.isInfinite(factor)) factor = 0.0; //safe currentState.scale(factor); // Remember disease deaths since they will be overwritten by sub myDelta.sub((IntegrationLabelValue)currentState); } } } } }
diff --git a/jaspersand-servlet/src/main/java/com/berbatik/rudi/jaspersandservlet/JasperServlet.java b/jaspersand-servlet/src/main/java/com/berbatik/rudi/jaspersandservlet/JasperServlet.java index 857eb5b..e50423c 100644 --- a/jaspersand-servlet/src/main/java/com/berbatik/rudi/jaspersandservlet/JasperServlet.java +++ b/jaspersand-servlet/src/main/java/com/berbatik/rudi/jaspersandservlet/JasperServlet.java @@ -1,86 +1,86 @@ /** * */ package com.berbatik.rudi.jaspersandservlet; import java.io.IOException; import java.io.InputStream; import java.io.StringBufferInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.util.HashMap; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.jasperreports.engine.JasperCompileManager; import net.sf.jasperreports.engine.JasperExportManager; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.JasperRunManager; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author rudi * */ @SuppressWarnings("serial") @WebServlet(urlPatterns="/jasper/*") public class JasperServlet extends HttpServlet { private transient Logger log = LoggerFactory.getLogger(JasperServlet.class); private Connection jdbc; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // resp.getWriter().write("Hello world"); try { InputStream reportStream3 = getClass().getResourceAsStream("/sales_order.jrxml"); JasperReport report = JasperCompileManager.compileReport(reportStream3); InputStream reportStream2 = getClass().getResourceAsStream("/sales_order.jrxml"); final String reportStr = IOUtils.toString(reportStream2); log.info("JRXML {}", reportStr); // JasperRunManager. // InputStream reportStream = getClass().getResourceAsStream("/sales_order.jrxml"); StringBufferInputStream reportStream = new StringBufferInputStream(reportStr); Class.forName("com.mysql.jdbc.Driver"); jdbc = DriverManager.getConnection( "jdbc:mysql://localhost:3306/berbatik_magento?" + "user=root&password=bippo"); JasperPrint print = JasperFillManager.fillReport(report, new HashMap<String, Object>(), jdbc); // facesContext.responseComplete(); resp.setContentType("application/pdf"); // resp.setContentType("text/html"); // JasperRunManager.runReportToHtmlFile(sourceFileName, params, conn) - JasperRunManager.runReportToPdfStream(reportStream2, - resp.getOutputStream(), new HashMap<String, Object>(), jdbc); +// JasperRunManager.runReportToPdfStream(reportStream3, +// resp.getOutputStream(), new HashMap<String, Object>(), jdbc); // JasperRunManager.runReportToPdfStream(reportStream, // resp.getOutputStream(), new HashMap<String, Object>(), jdbc); JasperExportManager.exportReportToPdfStream(print, resp.getOutputStream()); // yang di bawah ini juga bisa, asalkan inputnya adalah object JasperReport // bukan Stream (baik file .jasper maupun .jrxml gagal) // byte[] output = JasperRunManager.runReportToPdf(report, // new HashMap<String, Object>(), jdbc); // resp.getOutputStream().write(output); jdbc.close(); resp.setStatus(200); } catch (Exception e) { throw new RuntimeException("Can't connect to berbatik_magento", e); } } }
true
true
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // resp.getWriter().write("Hello world"); try { InputStream reportStream3 = getClass().getResourceAsStream("/sales_order.jrxml"); JasperReport report = JasperCompileManager.compileReport(reportStream3); InputStream reportStream2 = getClass().getResourceAsStream("/sales_order.jrxml"); final String reportStr = IOUtils.toString(reportStream2); log.info("JRXML {}", reportStr); // JasperRunManager. // InputStream reportStream = getClass().getResourceAsStream("/sales_order.jrxml"); StringBufferInputStream reportStream = new StringBufferInputStream(reportStr); Class.forName("com.mysql.jdbc.Driver"); jdbc = DriverManager.getConnection( "jdbc:mysql://localhost:3306/berbatik_magento?" + "user=root&password=bippo"); JasperPrint print = JasperFillManager.fillReport(report, new HashMap<String, Object>(), jdbc); // facesContext.responseComplete(); resp.setContentType("application/pdf"); // resp.setContentType("text/html"); // JasperRunManager.runReportToHtmlFile(sourceFileName, params, conn) JasperRunManager.runReportToPdfStream(reportStream2, resp.getOutputStream(), new HashMap<String, Object>(), jdbc); // JasperRunManager.runReportToPdfStream(reportStream, // resp.getOutputStream(), new HashMap<String, Object>(), jdbc); JasperExportManager.exportReportToPdfStream(print, resp.getOutputStream()); // yang di bawah ini juga bisa, asalkan inputnya adalah object JasperReport // bukan Stream (baik file .jasper maupun .jrxml gagal) // byte[] output = JasperRunManager.runReportToPdf(report, // new HashMap<String, Object>(), jdbc); // resp.getOutputStream().write(output); jdbc.close(); resp.setStatus(200); } catch (Exception e) { throw new RuntimeException("Can't connect to berbatik_magento", e); } }
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // resp.getWriter().write("Hello world"); try { InputStream reportStream3 = getClass().getResourceAsStream("/sales_order.jrxml"); JasperReport report = JasperCompileManager.compileReport(reportStream3); InputStream reportStream2 = getClass().getResourceAsStream("/sales_order.jrxml"); final String reportStr = IOUtils.toString(reportStream2); log.info("JRXML {}", reportStr); // JasperRunManager. // InputStream reportStream = getClass().getResourceAsStream("/sales_order.jrxml"); StringBufferInputStream reportStream = new StringBufferInputStream(reportStr); Class.forName("com.mysql.jdbc.Driver"); jdbc = DriverManager.getConnection( "jdbc:mysql://localhost:3306/berbatik_magento?" + "user=root&password=bippo"); JasperPrint print = JasperFillManager.fillReport(report, new HashMap<String, Object>(), jdbc); // facesContext.responseComplete(); resp.setContentType("application/pdf"); // resp.setContentType("text/html"); // JasperRunManager.runReportToHtmlFile(sourceFileName, params, conn) // JasperRunManager.runReportToPdfStream(reportStream3, // resp.getOutputStream(), new HashMap<String, Object>(), jdbc); // JasperRunManager.runReportToPdfStream(reportStream, // resp.getOutputStream(), new HashMap<String, Object>(), jdbc); JasperExportManager.exportReportToPdfStream(print, resp.getOutputStream()); // yang di bawah ini juga bisa, asalkan inputnya adalah object JasperReport // bukan Stream (baik file .jasper maupun .jrxml gagal) // byte[] output = JasperRunManager.runReportToPdf(report, // new HashMap<String, Object>(), jdbc); // resp.getOutputStream().write(output); jdbc.close(); resp.setStatus(200); } catch (Exception e) { throw new RuntimeException("Can't connect to berbatik_magento", e); } }
diff --git a/src/com/example/androidtraining/CrimeListFragment.java b/src/com/example/androidtraining/CrimeListFragment.java index 3a30192..65b21d3 100644 --- a/src/com/example/androidtraining/CrimeListFragment.java +++ b/src/com/example/androidtraining/CrimeListFragment.java @@ -1,140 +1,140 @@ package com.example.androidtraining; import java.text.SimpleDateFormat; import java.util.ArrayList; import android.annotation.TargetApi; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.support.v4.app.ListFragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.ListView; import android.widget.TextView; public class CrimeListFragment extends ListFragment { private ArrayList<Crime> mCrimes; private boolean mSubtitleVisible; private static final String TAG = "CrimeListFragment"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); getActivity().setTitle(R.string.crimes_title); mCrimes = CrimeLab.get(getActivity()).getCrimes(); CrimeAdapter adapter = new CrimeAdapter(mCrimes); setListAdapter(adapter); setRetainInstance(true); mSubtitleVisible = false; } @Override public void onResume() { super.onResume(); ((CrimeAdapter)getListAdapter()).notifyDataSetChanged(); } @Override public void onListItemClick(ListView l, View v, int position, long id) { // Get the Crime from the adapter Crime c = ((CrimeAdapter)getListAdapter()).getItem(position); // Start CrimeActivity Intent i = new Intent(getActivity(), CrimePagerActivity.class); i.putExtra(CrimeFragment.EXTRA_CRIME_ID, c.getId()); startActivity(i); } @TargetApi(11) @Override public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) { View v = super.onCreateView(inflater, parent, savedInstanceState); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { if (mSubtitleVisible) { getActivity().getActionBar().setSubtitle(R.string.subtitle); } } return v; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { super.onCreateOptionsMenu(menu, inflater); inflater.inflate(R.menu.fragment_crime_list, menu); MenuItem showSubtitle = menu.findItem(R.id.menu_item_show_subtitle); if (mSubtitleVisible && showSubtitle != null) { showSubtitle.setTitle(R.string.hide_subtitle); } } @TargetApi(11) @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_new_crime: Crime crime = new Crime(); CrimeLab.get(getActivity()).addCrime(crime); Intent i = new Intent(getActivity(), CrimePagerActivity.class); i.putExtra(CrimeFragment.EXTRA_CRIME_ID, crime.getId()); startActivityForResult(i, 0); return true; case R.id.menu_item_show_subtitle: - if (getActivity().getActionBar().getSubtitle() == null) { - getActivity().getActionBar().setSubtitle(R.string.subtitle); + if (this.getActivity().getActionBar().getSubtitle() == null) { + this.getActivity().getActionBar().setSubtitle(R.string.subtitle); mSubtitleVisible = true; item.setTitle(R.string.hide_subtitle); } else { - getActivity().getActionBar().setSubtitle(null); + this.getActivity().getActionBar().setSubtitle(null); mSubtitleVisible = false; item.setTitle(R.string.show_subtitle); } return true; default: return super.onOptionsItemSelected(item); } } private class CrimeAdapter extends ArrayAdapter<Crime> { public CrimeAdapter(ArrayList<Crime> crimes) { super(getActivity(), 0, crimes); } @Override public View getView(int position, View convertView, ViewGroup parent) { // If we weren't given a view, inflate one if (convertView == null) { convertView = getActivity().getLayoutInflater() .inflate(R.layout.list_item_crime, null); } // Configure the view for this Crime Crime c = getItem(position); TextView titleTextView = (TextView)convertView.findViewById(R.id.crime_list_item_titleTextView); titleTextView.setText(c.getTitle()); TextView dateTextView = (TextView)convertView.findViewById(R.id.crime_list_item_dateTextView); dateTextView.setText(new SimpleDateFormat("EEEE, MMMM dd, yyyy hh:mm aaa").format(c.getDate()).toString()); CheckBox solvedCheckBox = (CheckBox)convertView.findViewById(R.id.crime_list_item_solvedCheckBox); solvedCheckBox.setChecked(c.isSolved()); return convertView; } } }
false
true
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_new_crime: Crime crime = new Crime(); CrimeLab.get(getActivity()).addCrime(crime); Intent i = new Intent(getActivity(), CrimePagerActivity.class); i.putExtra(CrimeFragment.EXTRA_CRIME_ID, crime.getId()); startActivityForResult(i, 0); return true; case R.id.menu_item_show_subtitle: if (getActivity().getActionBar().getSubtitle() == null) { getActivity().getActionBar().setSubtitle(R.string.subtitle); mSubtitleVisible = true; item.setTitle(R.string.hide_subtitle); } else { getActivity().getActionBar().setSubtitle(null); mSubtitleVisible = false; item.setTitle(R.string.show_subtitle); } return true; default: return super.onOptionsItemSelected(item); } }
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_new_crime: Crime crime = new Crime(); CrimeLab.get(getActivity()).addCrime(crime); Intent i = new Intent(getActivity(), CrimePagerActivity.class); i.putExtra(CrimeFragment.EXTRA_CRIME_ID, crime.getId()); startActivityForResult(i, 0); return true; case R.id.menu_item_show_subtitle: if (this.getActivity().getActionBar().getSubtitle() == null) { this.getActivity().getActionBar().setSubtitle(R.string.subtitle); mSubtitleVisible = true; item.setTitle(R.string.hide_subtitle); } else { this.getActivity().getActionBar().setSubtitle(null); mSubtitleVisible = false; item.setTitle(R.string.show_subtitle); } return true; default: return super.onOptionsItemSelected(item); } }
diff --git a/ide/eclipse/common/org.wso2.developerstudio.eclipse.maven/src/main/java/org/wso2/developerstudio/eclipse/maven/util/MavenUtils.java b/ide/eclipse/common/org.wso2.developerstudio.eclipse.maven/src/main/java/org/wso2/developerstudio/eclipse/maven/util/MavenUtils.java index 528d8df41..6cbab0dcc 100644 --- a/ide/eclipse/common/org.wso2.developerstudio.eclipse.maven/src/main/java/org/wso2/developerstudio/eclipse/maven/util/MavenUtils.java +++ b/ide/eclipse/common/org.wso2.developerstudio.eclipse.maven/src/main/java/org/wso2/developerstudio/eclipse/maven/util/MavenUtils.java @@ -1,611 +1,611 @@ package org.wso2.developerstudio.eclipse.maven.util; import org.apache.maven.model.Build; import org.apache.maven.model.Dependency; import org.apache.maven.model.Model; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginExecution; import org.apache.maven.model.Repository; import org.apache.maven.model.RepositoryPolicy; import org.apache.maven.model.io.xpp3.MavenXpp3Reader; import org.apache.maven.model.io.xpp3.MavenXpp3Writer; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaModelException; import org.wso2.developerstudio.eclipse.utils.file.FileUtils; import org.wso2.developerstudio.eclipse.utils.jdt.JavaLibraryBean; import org.wso2.developerstudio.eclipse.utils.jdt.JavaLibraryUtil; import org.wso2.developerstudio.eclipse.utils.jdt.JavaUtils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.regex.Pattern; public class MavenUtils { public static final String CAPP_SCOPE_PREFIX = "capp"; public static final String PROPERTY_CAPP_TYPE = "CApp.type"; public static MavenProject getMavenProject(File file) throws Exception { MavenXpp3Reader mavenXpp3Reader = new MavenXpp3Reader(); Model model; final FileInputStream stream = new FileInputStream(file); model = mavenXpp3Reader.read(stream); try { if (stream != null) { stream.close(); } } catch (IOException e) { // ignore, stream is already closed } return new MavenProject(model); } public static MavenProject getMavenProject(InputStream input) throws Exception { MavenXpp3Reader mavenXpp3Reader = new MavenXpp3Reader(); Model model; model = mavenXpp3Reader.read(input); return new MavenProject(model); } public static void saveMavenProject(MavenProject project, File file) throws Exception{ if (file.getParentFile()!=null){ file.getParentFile().mkdirs(); } MavenXpp3Writer mavenXpp3writer = new MavenXpp3Writer(); FileWriter fileWriter = new FileWriter(file); mavenXpp3writer.write(fileWriter, project.getModel()); fileWriter.close(); } public static MavenProject createMavenProject(String groupId, String artifactId, String version, String packagingType) { Model model = new Model(); model.setGroupId(groupId); model.setArtifactId(artifactId); model.setVersion(version); model.setModelVersion("4.0.0"); model.setName(artifactId); model.setDescription(artifactId); if (packagingType!=null){ model.setPackaging(packagingType); } return new MavenProject(model); } public static Xpp3Dom createMainConfigurationNode(Plugin plugin) { String tagName = "configuration"; Xpp3Dom configuration = createXpp3Node(tagName); plugin.setConfiguration(configuration); return configuration; } public static Xpp3Dom createMainConfigurationNode() { String tagName = "configuration"; return createXpp3Node(tagName); } public static Xpp3Dom createMainGoalsNode(Plugin plugin) { String tagName = "goals"; Xpp3Dom configuration = createXpp3Node(tagName); plugin.setGoals(configuration); return configuration; } public static Xpp3Dom createMainGoalsNode() { String tagName = "goals"; return createXpp3Node(tagName); } public static Xpp3Dom createXpp3Node(Xpp3Dom parent,String tagName) { Xpp3Dom node = createXpp3Node(tagName); parent.addChild(node); return node; } public static boolean removeXpp3Node(Xpp3Dom parent,Xpp3Dom child) { int removeIndex=-1; for(int i=0;i<parent.getChildCount();i++){ if (parent.getChild(i)==child){ removeIndex=i; break; } } if (removeIndex==-1){ return false; }else{ parent.removeChild(removeIndex); return true; } } public static Xpp3Dom createXpp3Node(String tagName) { Xpp3Dom node = new Xpp3Dom(tagName); return node; } public static Plugin createPluginEntry(MavenProject project, String groupId, String artifactId, String version,boolean isExtension){ Plugin plugin = new Plugin(); plugin.setGroupId(groupId); plugin.setArtifactId(artifactId); plugin.setVersion(version); if (isExtension){ plugin.setExtensions(true); } MavenUtils.createMainConfigurationNode(plugin); project.getBuild().addPlugin(plugin); return plugin; } public static boolean checkOldPluginEntry(MavenProject project, String groupId, String artifactId, String version) { List<Plugin> plugins = project.getBuild().getPlugins(); Iterator<Plugin> iterator = plugins.iterator(); boolean exists = false; while (iterator.hasNext()) { Plugin plugin = iterator.next(); if (plugin.getGroupId().equals(groupId) && plugin.getArtifactId().equals(artifactId)) { exists = true; if (!version.equalsIgnoreCase(plugin.getVersion())) { iterator.remove(); exists = false; } } } return exists; } public static String getMavenModuleRelativePath(File mavenModuleProject, File mavenProject){ File mavenModuleLocation=mavenModuleProject; if (mavenModuleProject.getName().equalsIgnoreCase("pom.xml")){ mavenModuleLocation=mavenModuleProject.getParentFile(); } File mavenLocation=mavenProject; if (mavenProject.getName().equalsIgnoreCase("pom.xml")){ mavenLocation=mavenProject.getParentFile(); } return FileUtils.getRelativePath(mavenModuleLocation, mavenLocation); } public static MavenProject updateMavenProjectWithJarBuilderPlugin(IProject project, String grpupID, String artifactID, String version, File mavenProjectSaveLocation) throws Exception{ MavenProject mavenProject = createMavenProject(grpupID, artifactID, version, "jar"); return updateMavenProjectWithJarBuilderPlugin(project, mavenProject, mavenProjectSaveLocation); } public static MavenProject updateMavenProjectWithBundleBuilderPlugin(IProject project, String grpupID, String artifactID, String version, File mavenProjectSaveLocation) throws Exception{ MavenProject mavenProject = createMavenProject(grpupID, artifactID, version, "bundle"); return updateMavenProjectWithBundleBuilderPlugin(project, mavenProject, mavenProjectSaveLocation); } public static MavenProject updateMavenProjectWithWarBuilderPlugin(IProject project, String grpupID, String artifactID, String version, File mavenProjectSaveLocation) throws Exception{ MavenProject mavenProject = createMavenProject(grpupID, artifactID, version, "war"); return updateMavenProjectWithWarBuilderPlugin(project, mavenProject, mavenProjectSaveLocation); } public static MavenProject updateMavenProjectWithBpelBuilderPlugin(IProject project, String grpupID, String artifactID, String version, File mavenProjectSaveLocation) throws Exception{ MavenProject mavenProject = createMavenProject(grpupID, artifactID, version, "bpel/workflow"); return updateMavenProjectWithBpelBuilderPlugin(project, mavenProject, mavenProjectSaveLocation); } public static MavenProject updateMavenProjectWithJarBuilderPlugin(IProject project, MavenProject mavenProject, File mavenProjectSaveLocation) throws Exception { initializeBuildModel(mavenProject); //TODO check if the configurations are already present //before trying to add again updateDependecyList(project, mavenProject); updateSourceFolder(project, mavenProject,mavenProjectSaveLocation); updateMavenRepo(mavenProject); addMavenJarPlugin(mavenProject); addMavenCompilerPlugin(mavenProject); return mavenProject; } public static MavenProject updateMavenProjectWithBundleBuilderPlugin(IProject project, MavenProject mavenProject, File mavenProjectSaveLocation) throws Exception { initializeBuildModel(mavenProject); // TODO check if the configurations are already present // before trying to add again updateDependecyList(project, mavenProject); updateSourceFolder(project, mavenProject, mavenProjectSaveLocation); updateMavenRepo(mavenProject); addMavenBundlePluginForCarbonUI(mavenProject,project); addMavenCompilerPlugin(mavenProject); addMavenDependency(mavenProject, createDependency("org.eclipse.osgi", "org.eclipse.osgi", "3.5.2.R35x_v20100126")); return mavenProject; } public static void updateMavenProjectWithCAppType(MavenProject mavenProject,String cappType){ mavenProject.getModel().addProperty(PROPERTY_CAPP_TYPE, cappType); } public static void updateMavenProjectWithSkipTests(MavenProject mavenProject){ mavenProject.getModel().addProperty("maven.test.skip","false"); } public static MavenProject updateMavenProjectWithWarBuilderPlugin(IProject project, MavenProject mavenProject, File mavenProjectSaveLocation) throws Exception { initializeBuildModel(mavenProject); // TODO check if the configurations are already present // before trying to add again updateDependecyList(project, mavenProject); updateSourceFolder(project, mavenProject, mavenProjectSaveLocation); updateMavenRepo(mavenProject); addMavenWarPlugin(mavenProject); addMavenCompilerPlugin(mavenProject); return mavenProject; } public static MavenProject updateMavenProjectWithBpelBuilderPlugin(IProject project, MavenProject mavenProject, File mavenProjectSaveLocation) throws Exception { initializeBuildModel(mavenProject); // TODO check if the configurations are already present // before trying to add again // updateDependecyList(project, mavenProject); // updateSourceFolder(project, mavenProject, mavenProjectSaveLocation); updateMavenRepo(mavenProject); addMavenBpelPlugin(mavenProject); // addMavenCompilerPlugin(mavenProject); return mavenProject; } private static void updateMavenRepo(MavenProject mavenProject){ List<Repository> newList=mavenProject.getModel().getRepositories(); List<Repository> existingRepositories = new ArrayList<Repository>(); for (Repository repository : newList) { existingRepositories.add(repository); } Repository repo = new Repository(); repo.setUrl("http://maven.wso2.org/nexus/content/groups/wso2-public/"); repo.setId("wso2-nexus"); RepositoryPolicy releasePolicy=new RepositoryPolicy(); releasePolicy.setEnabled(true); releasePolicy.setUpdatePolicy("daily"); releasePolicy.setChecksumPolicy("ignore"); repo.setReleases(releasePolicy); if(!existingRepositories.isEmpty()){ for (Repository repository : existingRepositories) { if(!repository.getUrl().equalsIgnoreCase(repo.getUrl())){ mavenProject.getModel().addRepository(repo); mavenProject.getModel().addPluginRepository(repo); } } }else{ mavenProject.getModel().addRepository(repo); mavenProject.getModel().addPluginRepository(repo); } } private static void updateSourceFolder(IProject project, MavenProject mavenProject, File mavenProjectSaveLocation) throws JavaModelException{ Plugin sourcePluginEntry = createPluginEntry(mavenProject, "org.codehaus.mojo", "build-helper-maven-plugin", "1.7", false); PluginExecution pluginExecution=new PluginExecution(); IPackageFragmentRoot[] sourceFoldersForProject = JavaUtils.getSourceFoldersForProject(project); if (sourceFoldersForProject.length > 0) { String sourceFolder = FileUtils.getRelativePath(mavenProjectSaveLocation.getParentFile(), sourceFoldersForProject[0].getResource() .getLocation() .toFile()).replaceAll(Pattern.quote(File.separator), "/"); mavenProject.getModel().getBuild().setSourceDirectory(sourceFolder); Xpp3Dom configurationNode = createMainConfigurationNode(); pluginExecution.setConfiguration(configurationNode); Xpp3Dom sourcesNode = createXpp3Node(configurationNode, "sources"); for (int i = 1; i < sourceFoldersForProject.length; i++) { IPackageFragmentRoot packageFragmentRoot = sourceFoldersForProject[i]; File sourceDirectory = packageFragmentRoot.getResource().getLocation().toFile(); String relativePath = FileUtils.getRelativePath(mavenProjectSaveLocation.getParentFile(), sourceDirectory).replaceAll(Pattern.quote(File.separator), "/"); Xpp3Dom sourceNode = createXpp3Node(sourcesNode, "source"); sourceNode.setValue(relativePath); } sourcePluginEntry.addExecution(pluginExecution); } } - private static void updateDependecyList(IProject project, MavenProject mavenProject) throws Exception { + public static void updateDependecyList(IProject project, MavenProject mavenProject) throws Exception { List<Dependency> existingDependencies = mavenProject.getModel().getDependencies(); // List<String> newDependencyStrings=new ArrayList<String>(); // List<String> existingDependencyStrings=new ArrayList<String>(); List<Dependency> newDependencyList = new ArrayList<Dependency>(); - boolean found=false; Map<String, JavaLibraryBean> dependencyInfoMap = JavaLibraryUtil.getDependencyInfoMap(project); Map<String, String> map = ProjectDependencyConstants.DEPENDENCY_MAP; for (JavaLibraryBean bean : dependencyInfoMap.values()) { if (bean.getVersion().contains("${")){ for(String path: map.keySet()) { bean.setVersion(bean.getVersion().replace(path, map.get(path))); } } Dependency dependency = new Dependency(); dependency.setArtifactId(bean.getArtifactId()); dependency.setGroupId(bean.getGroupId()); dependency.setVersion(bean.getVersion()); // String dependencyString = getDependencyString(dependency); // newDependencyStrings.add(dependencyString); newDependencyList.add(dependency); // if(!dependencies.contains(dependency)){ // dependencies.add(dependency); // } } // for (Dependency dependency : existingDependencies) { // String dependencyString = getDependencyString(dependency); // existingDependencyStrings.add(dependencyString); // } for (Dependency newDependency : newDependencyList) { + boolean found=false; for (Dependency existingDependency : existingDependencies) { if(newDependency.getArtifactId().equals(existingDependency.getArtifactId()) && newDependency.getGroupId().equals(existingDependency.getGroupId()) && newDependency.getVersion().equals(existingDependency.getVersion())){ found = true; } } if(!found){ existingDependencies.add(newDependency); } } // for (Dependency dependency : newDependencyList) { // String dependencyString = getDependencyString(dependency); // if (!newDependencyStrings.contains(dependencyString)){ // existingDependencies.add(dependency); // } // } addMavenDependency(mavenProject, existingDependencies); } public static void addMavenDependency(MavenProject mavenProject, List<Dependency> dependencies) { addMavenDependency(mavenProject,dependencies.toArray(new Dependency[]{})); } public static void addMavenDependency(MavenProject mavenProject, Dependency...dependencies){ List<String> dependencyStrings=new ArrayList<String>(); List<Dependency> currentDependencyList = mavenProject.getDependencies(); for (Dependency dependency : currentDependencyList) { String ds = getDependencyString(dependency); dependencyStrings.add(ds); } for (Dependency dependency : dependencies) { String dependencyString = getDependencyString(dependency); if (!dependencyStrings.contains(dependencyString)){ mavenProject.getDependencies().add(dependency); dependencyStrings.add(dependencyString); } } } private static String getDependencyString(Dependency dependency) { String ds=dependency.getGroupId()+":"+dependency.getArtifactId()+":"+dependency.getVersion()+":"+dependency.getType()+":"; return ds; } public static void addMavenJarPlugin(MavenProject mavenProject){ Plugin plugin; PluginExecution pluginExecution; plugin = MavenUtils.createPluginEntry(mavenProject, "org.apache.maven.plugins", "maven-jar-plugin", "2.2", false); pluginExecution=new PluginExecution(); pluginExecution.addGoal("jar"); pluginExecution.setPhase("package"); pluginExecution.setId("jar-create-execution"); plugin.addExecution(pluginExecution); } public static void updateWithMavenEclipsePlugin(File pomLocation, String[] buildCommands, String[] projectNatures) throws Exception{ Plugin plugin; MavenProject mavenProject = MavenUtils.getMavenProject(pomLocation); plugin = MavenUtils.createPluginEntry(mavenProject, "org.apache.maven.plugins", "maven-eclipse-plugin", "2.9", false); Xpp3Dom configurationNode = createMainConfigurationNode(); Xpp3Dom buildCommandsNode = createXpp3Node(configurationNode, "buildcommands"); for (String string : buildCommands) { Xpp3Dom buildCommand = createXpp3Node(buildCommandsNode, "buildcommand"); buildCommand.setValue(string); } Xpp3Dom projectNaturesNode = createXpp3Node(configurationNode, "projectnatures"); for (String string : projectNatures) { Xpp3Dom projectNature = createXpp3Node(projectNaturesNode, "projectnature"); projectNature.setValue(string); } plugin.setConfiguration(configurationNode); MavenUtils.saveMavenProject(mavenProject, pomLocation); } public static void addMavenBundlePluginForCarbonUI(MavenProject mavenProject, IProject eclipseProject){ // Plugin plugin; // PluginExecution pluginExecution; // plugin = MavenUtils.createPluginEntry(mavenProject, "org.apache.maven.plugins", "maven-jar-plugin", "2.2", false); // pluginExecution=new PluginExecution(); // pluginExecution.addGoal("jar"); // pluginExecution.setPhase("package"); // pluginExecution.setId("jar-create-execution"); // plugin.addExecution(pluginExecution); IFile manifestFile=eclipseProject.getFile("META-INF"+File.separator+"MANIFEST.MF"); Properties properties=new Properties(); try { properties.load(new FileInputStream(manifestFile.getLocation().toFile())); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Plugin plugin = MavenUtils.createPluginEntry(mavenProject, "org.apache.felix", "maven-bundle-plugin", "2.3.4", true); Xpp3Dom config=(Xpp3Dom)plugin.getConfiguration(); Xpp3Dom instructionNode = MavenUtils.createXpp3Node(config, "instructions"); Xpp3Dom symbolicNameNode = MavenUtils.createXpp3Node(instructionNode, "Bundle-SymbolicName"); symbolicNameNode.setValue(properties.getProperty("Bundle-SymbolicName")); Xpp3Dom bundleNameNode = MavenUtils.createXpp3Node(instructionNode, "Bundle-Name"); bundleNameNode.setValue(properties.getProperty("Bundle-Name")); Xpp3Dom activatorClassNode = MavenUtils.createXpp3Node(instructionNode, "Bundle-Activator"); activatorClassNode.setValue(properties.getProperty("Bundle-Activator")); Xpp3Dom includeNode = MavenUtils.createXpp3Node(instructionNode, "_include"); includeNode.setValue("META-INF/MANIFEST.MF"); Xpp3Dom exportPackageNode = MavenUtils.createXpp3Node(instructionNode, "Export-Package"); exportPackageNode.setValue(properties.getProperty("Export-Package","")); Xpp3Dom dynamicImportNode = MavenUtils.createXpp3Node(instructionNode, "DynamicImport-Package"); dynamicImportNode.setValue("*"); Xpp3Dom includeResourceNode = MavenUtils.createXpp3Node(instructionNode, "Include-Resource"); includeResourceNode.setValue("META-INF/component.xml = META-INF/component.xml,web = web"); } public static void addMavenWarPlugin(MavenProject mavenProject){ Plugin plugin; PluginExecution pluginExecution; plugin = MavenUtils.createPluginEntry(mavenProject, "org.apache.maven.plugins", "maven-war-plugin", "2.2", false); pluginExecution=new PluginExecution(); pluginExecution.addGoal("war"); pluginExecution.setPhase("package"); pluginExecution.setId("war"); plugin.addExecution(pluginExecution); Xpp3Dom config=(Xpp3Dom)plugin.getConfiguration(); Xpp3Dom warSourceDir=createXpp3Node(config, "warSourceDirectory"); warSourceDir.setValue("src/main/webapp"); mavenProject.getModel().addProperty(PROPERTY_CAPP_TYPE, "web/application"); } public static void addMavenBpelPlugin(MavenProject mavenProject){ Plugin plugin; PluginExecution pluginExecution; plugin = MavenUtils.createPluginEntry(mavenProject, "org.wso2.maven", "maven-bpel-plugin", "2.0.2", true); // pluginExecution=new PluginExecution(); // pluginExecution.addGoal("bpel"); // pluginExecution.setPhase("package"); // pluginExecution.setId("bpel"); // plugin.addExecution(pluginExecution) mavenProject.getModel().addProperty(PROPERTY_CAPP_TYPE, "bpel/workflow"); } public static void addMavenCompilerPlugin(MavenProject mavenProject){ Plugin plugin; plugin = MavenUtils.createPluginEntry(mavenProject, "org.apache.maven.plugins", "maven-compiler-plugin", "2.3.2" , false); Xpp3Dom configurationNode = createMainConfigurationNode(); Xpp3Dom sourceNode = createXpp3Node(configurationNode, "source"); sourceNode.setValue("1.5"); Xpp3Dom targetNode = createXpp3Node(configurationNode, "target"); targetNode.setValue("1.5"); plugin.setConfiguration(configurationNode); } public static MavenProject addMavenModulesToMavenProject(MavenProject mavenProject, File mavenProjectLocation, File[] moduleProjectLocations) throws Exception{ if(mavenProjectLocation.exists() && mavenProjectLocation.isDirectory()){ mavenProjectLocation = new File(mavenProjectLocation, "pom.xml"); } initializeBuildModel(mavenProject); updateModules(mavenProject, mavenProjectLocation, moduleProjectLocations); // saveMavenProject(mavenProject,mavenProjectLocation); return mavenProject; } private static void initializeBuildModel(MavenProject mavenProject) { Model model = mavenProject.getModel(); if (model.getBuild()!=null) { model.setBuild(new Build()); } } public static Dependency createDependency(String groupId, String artifactId){ return createDependency(groupId, artifactId, null); } public static Dependency createDependency(String groupId, String artifactId, String version){ return createDependency(groupId, artifactId, version, null); } public static Dependency createDependency(String groupId, String artifactId, String version, String scope){ return createDependency(groupId, artifactId, version, scope, null); } public static Dependency createDependency(String groupId, String artifactId, String version, String scope, String type){ return createDependency(groupId, artifactId, version, scope, type, null); } public static Dependency createDependency(String groupId, String artifactId, String version, String scope, String type, String systemPath) { Dependency dependency = new Dependency(); dependency.setGroupId(groupId); dependency.setArtifactId(artifactId); if (version!=null) { dependency.setVersion(version); } if (scope!=null) { dependency.setScope(scope); } if (systemPath!=null) { dependency.setSystemPath(systemPath); } if (type!=null) { dependency.setType(type); } return dependency; } private static void updateModules(MavenProject mavenProject, File mavenProjectLocation, File[] moduleProjectLocations) { String relativePath; for (File moduleLocation : moduleProjectLocations) { relativePath = FileUtils.getRelativePath(mavenProjectLocation.getParentFile(), moduleLocation.getParentFile()); if(!mavenProject.getModel().getModules().contains(relativePath)){ mavenProject.getModel().getModules().add(relativePath); } } } public static void updateMavenProjectWithWSO2Repository(MavenProject mavenProject){ Repository repo = new Repository(); repo.setUrl("http://maven.wso2.org/nexus/content/groups/wso2-public/"); repo.setId("wso2-maven2-repository-1"); mavenProject.getModel().addRepository(repo); mavenProject.getModel().addPluginRepository(repo); } public static void setSourceFolder(MavenProject mavenProject, String sourceDir){ mavenProject.getBuild().setSourceDirectory(sourceDir); } }
false
true
private static void updateDependecyList(IProject project, MavenProject mavenProject) throws Exception { List<Dependency> existingDependencies = mavenProject.getModel().getDependencies(); // List<String> newDependencyStrings=new ArrayList<String>(); // List<String> existingDependencyStrings=new ArrayList<String>(); List<Dependency> newDependencyList = new ArrayList<Dependency>(); boolean found=false; Map<String, JavaLibraryBean> dependencyInfoMap = JavaLibraryUtil.getDependencyInfoMap(project); Map<String, String> map = ProjectDependencyConstants.DEPENDENCY_MAP; for (JavaLibraryBean bean : dependencyInfoMap.values()) { if (bean.getVersion().contains("${")){ for(String path: map.keySet()) { bean.setVersion(bean.getVersion().replace(path, map.get(path))); } } Dependency dependency = new Dependency(); dependency.setArtifactId(bean.getArtifactId()); dependency.setGroupId(bean.getGroupId()); dependency.setVersion(bean.getVersion()); // String dependencyString = getDependencyString(dependency); // newDependencyStrings.add(dependencyString); newDependencyList.add(dependency); // if(!dependencies.contains(dependency)){ // dependencies.add(dependency); // } } // for (Dependency dependency : existingDependencies) { // String dependencyString = getDependencyString(dependency); // existingDependencyStrings.add(dependencyString); // } for (Dependency newDependency : newDependencyList) { for (Dependency existingDependency : existingDependencies) { if(newDependency.getArtifactId().equals(existingDependency.getArtifactId()) && newDependency.getGroupId().equals(existingDependency.getGroupId()) && newDependency.getVersion().equals(existingDependency.getVersion())){ found = true; } } if(!found){ existingDependencies.add(newDependency); } } // for (Dependency dependency : newDependencyList) { // String dependencyString = getDependencyString(dependency); // if (!newDependencyStrings.contains(dependencyString)){ // existingDependencies.add(dependency); // } // } addMavenDependency(mavenProject, existingDependencies); }
public static void updateDependecyList(IProject project, MavenProject mavenProject) throws Exception { List<Dependency> existingDependencies = mavenProject.getModel().getDependencies(); // List<String> newDependencyStrings=new ArrayList<String>(); // List<String> existingDependencyStrings=new ArrayList<String>(); List<Dependency> newDependencyList = new ArrayList<Dependency>(); Map<String, JavaLibraryBean> dependencyInfoMap = JavaLibraryUtil.getDependencyInfoMap(project); Map<String, String> map = ProjectDependencyConstants.DEPENDENCY_MAP; for (JavaLibraryBean bean : dependencyInfoMap.values()) { if (bean.getVersion().contains("${")){ for(String path: map.keySet()) { bean.setVersion(bean.getVersion().replace(path, map.get(path))); } } Dependency dependency = new Dependency(); dependency.setArtifactId(bean.getArtifactId()); dependency.setGroupId(bean.getGroupId()); dependency.setVersion(bean.getVersion()); // String dependencyString = getDependencyString(dependency); // newDependencyStrings.add(dependencyString); newDependencyList.add(dependency); // if(!dependencies.contains(dependency)){ // dependencies.add(dependency); // } } // for (Dependency dependency : existingDependencies) { // String dependencyString = getDependencyString(dependency); // existingDependencyStrings.add(dependencyString); // } for (Dependency newDependency : newDependencyList) { boolean found=false; for (Dependency existingDependency : existingDependencies) { if(newDependency.getArtifactId().equals(existingDependency.getArtifactId()) && newDependency.getGroupId().equals(existingDependency.getGroupId()) && newDependency.getVersion().equals(existingDependency.getVersion())){ found = true; } } if(!found){ existingDependencies.add(newDependency); } } // for (Dependency dependency : newDependencyList) { // String dependencyString = getDependencyString(dependency); // if (!newDependencyStrings.contains(dependencyString)){ // existingDependencies.add(dependency); // } // } addMavenDependency(mavenProject, existingDependencies); }
diff --git a/branches/kernel-1.1.x/kernel-private/src/main/java/org/sakaiproject/springframework/orm/hibernate/dialect/db2/DB2Dialect9.java b/branches/kernel-1.1.x/kernel-private/src/main/java/org/sakaiproject/springframework/orm/hibernate/dialect/db2/DB2Dialect9.java index f1c9e9ab..61b0309b 100644 --- a/branches/kernel-1.1.x/kernel-private/src/main/java/org/sakaiproject/springframework/orm/hibernate/dialect/db2/DB2Dialect9.java +++ b/branches/kernel-1.1.x/kernel-private/src/main/java/org/sakaiproject/springframework/orm/hibernate/dialect/db2/DB2Dialect9.java @@ -1,32 +1,32 @@ package org.sakaiproject.springframework.orm.hibernate.dialect.db2; import org.hibernate.dialect.DB2Dialect; import java.sql.Types; /** * Created by IntelliJ IDEA. * User: jbush * Date: May 23, 2007 * Time: 4:20:48 PM * To change this template use File | Settings | File Templates. */ public class DB2Dialect9 extends DB2Dialect { public DB2Dialect9() { super(); registerColumnType( Types.VARBINARY, "LONG VARCHAR FOR BIT DATA" ); registerColumnType( Types.VARCHAR, "clob(1000000000)" ); registerColumnType( Types.VARCHAR, 1000000000, "clob($l)" ); - registerColumnType( Types.VARCHAR, 32704, "varchar($l)" ); + registerColumnType( Types.VARCHAR, 3999, "varchar($l)" ); //according to the db2 docs the max for clob and blob should be 2147438647, but this isn't working for me // possibly something to do with how my database is configured ? registerColumnType( Types.CLOB, "clob(1000000000)" ); registerColumnType( Types.CLOB, 1000000000, "clob($l)" ); registerColumnType( Types.BLOB, "blob(1000000000)" ); registerColumnType( Types.BLOB, 1000000000, "blob($l)" ); } }
true
true
public DB2Dialect9() { super(); registerColumnType( Types.VARBINARY, "LONG VARCHAR FOR BIT DATA" ); registerColumnType( Types.VARCHAR, "clob(1000000000)" ); registerColumnType( Types.VARCHAR, 1000000000, "clob($l)" ); registerColumnType( Types.VARCHAR, 32704, "varchar($l)" ); //according to the db2 docs the max for clob and blob should be 2147438647, but this isn't working for me // possibly something to do with how my database is configured ? registerColumnType( Types.CLOB, "clob(1000000000)" ); registerColumnType( Types.CLOB, 1000000000, "clob($l)" ); registerColumnType( Types.BLOB, "blob(1000000000)" ); registerColumnType( Types.BLOB, 1000000000, "blob($l)" ); }
public DB2Dialect9() { super(); registerColumnType( Types.VARBINARY, "LONG VARCHAR FOR BIT DATA" ); registerColumnType( Types.VARCHAR, "clob(1000000000)" ); registerColumnType( Types.VARCHAR, 1000000000, "clob($l)" ); registerColumnType( Types.VARCHAR, 3999, "varchar($l)" ); //according to the db2 docs the max for clob and blob should be 2147438647, but this isn't working for me // possibly something to do with how my database is configured ? registerColumnType( Types.CLOB, "clob(1000000000)" ); registerColumnType( Types.CLOB, 1000000000, "clob($l)" ); registerColumnType( Types.BLOB, "blob(1000000000)" ); registerColumnType( Types.BLOB, 1000000000, "blob($l)" ); }
diff --git a/src/org/pathwayeditor/visualeditor/dataviewer/DataViewPanel.java b/src/org/pathwayeditor/visualeditor/dataviewer/DataViewPanel.java index f313f6f..4bd4f4c 100644 --- a/src/org/pathwayeditor/visualeditor/dataviewer/DataViewPanel.java +++ b/src/org/pathwayeditor/visualeditor/dataviewer/DataViewPanel.java @@ -1,191 +1,195 @@ package org.pathwayeditor.visualeditor.dataviewer; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.LinkedList; import java.util.List; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; public class DataViewPanel extends JPanel { private static final long serialVersionUID = 3602462091855803178L; private BorderLayout borderLayout1 = new BorderLayout(); private DataViewTableModel tableModel; private JScrollPane dataViewScrollPane = new JScrollPane(); private TableColumnModel tableColumnModel; private JTable dataViewTable; private javax.swing.JPanel actionPanel = new JPanel(); private transient List<DataViewListener> dataViewListeners = new LinkedList<DataViewListener>(); private ListSelectionModel selectionModel; private JButton prevButton; private JButton nextButton; public DataViewPanel(IRowDefn rowDefn) { tableModel = new DataViewTableModel(rowDefn); tableColumnModel = new DefaultTableColumnModel(); dataViewTable = new JTable(tableModel, tableColumnModel); dataViewTable.setAutoscrolls(true); selectionModel = dataViewTable.getSelectionModel(); selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); setColumnDefs(); this.setLayout(borderLayout1); dataViewScrollPane.getViewport().add(dataViewTable); this.add(dataViewScrollPane, java.awt.BorderLayout.CENTER); this.add(actionPanel, java.awt.BorderLayout.SOUTH); setupActionPanel(); dataViewTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); } private void setupActionPanel() { final JCheckBox irrelevantCheckBox = addCheckBox("Irrelevant"); final JCheckBox centralCheckBox = addCheckBox("Central OK"); final JCheckBox sateliteCheckBox = addCheckBox("Satelite OK"); irrelevantCheckBox.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent e) { if(!irrelevantCheckBox.isSelected()){ centralCheckBox.setSelected(false); sateliteCheckBox.setSelected(false); } } }); centralCheckBox.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent e) { if(centralCheckBox.isSelected()){ irrelevantCheckBox.setSelected(true); } } }); sateliteCheckBox.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent e) { if(sateliteCheckBox.isSelected()){ irrelevantCheckBox.setSelected(true); } } }); prevButton = new JButton("Previous"); this.actionPanel.add(prevButton); prevButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int currSelectionIdx = getCurrentSelection()-1; selectionModel.setSelectionInterval(currSelectionIdx, currSelectionIdx); + int scrollOffset = dataViewTable.getRowHeight()*getCurrentSelection(); + dataViewScrollPane.getVerticalScrollBar().setValue(scrollOffset); } }); nextButton = new JButton("Next"); this.actionPanel.add(nextButton); nextButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int currSelectionIdx = getCurrentSelection()+1; selectionModel.setSelectionInterval(currSelectionIdx, currSelectionIdx); + int scrollOffset = dataViewTable.getRowHeight()*getCurrentSelection(); + dataViewScrollPane.getVerticalScrollBar().setValue(scrollOffset); } }); this.selectionModel.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { checkNavigatorButtonEnablement(); } }); } private void checkNavigatorButtonEnablement(){ int currSelectionIdx = getCurrentSelection(); prevButton.setEnabled(currSelectionIdx > 0); nextButton.setEnabled(currSelectionIdx < tableModel.getRowCount()-1); } private JCheckBox addCheckBox(String labelText) { JLabel label = new JLabel(labelText); JCheckBox checkBox = new JCheckBox(); checkBox.setSelected(false); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(1, 2)); buttonPanel.add(label); buttonPanel.add(checkBox); this.actionPanel.add(buttonPanel); return checkBox; } private void setColumnDefs() { IRowDefn rowDefn = this.tableModel.getRowDefn(); for (int i = 0; i < rowDefn.getNumColumns(); i++) { TableColumn colDefn = new TableColumn(); colDefn.setHeaderValue(i); colDefn.setHeaderValue(rowDefn.getColumnHeader(i)); colDefn.setResizable(rowDefn.isColumnResizable(i)); colDefn.setPreferredWidth(rowDefn.getPreferredWidth(i)); if (rowDefn.getCustomRenderer(i) != null) { colDefn.setCellRenderer(rowDefn.getCustomRenderer(i)); } if (rowDefn.getCellEditor(i) != null) { colDefn.setCellEditor(rowDefn.getCellEditor(i)); } colDefn.setModelIndex(i); tableColumnModel.addColumn(colDefn); } } public void addDataViewListener(DataViewListener l) { this.dataViewListeners.add(l); } public void removeDataViewListener(DataViewListener l) { this.dataViewListeners.remove(l); } protected void fireRowInserted(DataViewEvent event) { for (DataViewListener listener : dataViewListeners) { listener.rowInserted(event); } } protected void fireRowDeleted(DataViewEvent event) { for (DataViewListener listener : dataViewListeners) { listener.rowDeleted(event); } } protected void fireViewSaved(DataViewEvent event) { for (DataViewListener listener : dataViewListeners) { listener.viewSaved(event); } } protected void fireViewReset(DataViewEvent event) { for (DataViewListener listener : dataViewListeners) { listener.viewReset(event); } } public DataViewTableModel getTableModel() { return this.tableModel; } private int getCurrentSelection(){ return selectionModel.getAnchorSelectionIndex(); } public void resetSelection() { selectionModel.setSelectionInterval(0, 0); } }
false
true
private void setupActionPanel() { final JCheckBox irrelevantCheckBox = addCheckBox("Irrelevant"); final JCheckBox centralCheckBox = addCheckBox("Central OK"); final JCheckBox sateliteCheckBox = addCheckBox("Satelite OK"); irrelevantCheckBox.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent e) { if(!irrelevantCheckBox.isSelected()){ centralCheckBox.setSelected(false); sateliteCheckBox.setSelected(false); } } }); centralCheckBox.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent e) { if(centralCheckBox.isSelected()){ irrelevantCheckBox.setSelected(true); } } }); sateliteCheckBox.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent e) { if(sateliteCheckBox.isSelected()){ irrelevantCheckBox.setSelected(true); } } }); prevButton = new JButton("Previous"); this.actionPanel.add(prevButton); prevButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int currSelectionIdx = getCurrentSelection()-1; selectionModel.setSelectionInterval(currSelectionIdx, currSelectionIdx); } }); nextButton = new JButton("Next"); this.actionPanel.add(nextButton); nextButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int currSelectionIdx = getCurrentSelection()+1; selectionModel.setSelectionInterval(currSelectionIdx, currSelectionIdx); } }); this.selectionModel.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { checkNavigatorButtonEnablement(); } }); }
private void setupActionPanel() { final JCheckBox irrelevantCheckBox = addCheckBox("Irrelevant"); final JCheckBox centralCheckBox = addCheckBox("Central OK"); final JCheckBox sateliteCheckBox = addCheckBox("Satelite OK"); irrelevantCheckBox.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent e) { if(!irrelevantCheckBox.isSelected()){ centralCheckBox.setSelected(false); sateliteCheckBox.setSelected(false); } } }); centralCheckBox.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent e) { if(centralCheckBox.isSelected()){ irrelevantCheckBox.setSelected(true); } } }); sateliteCheckBox.addChangeListener(new ChangeListener(){ @Override public void stateChanged(ChangeEvent e) { if(sateliteCheckBox.isSelected()){ irrelevantCheckBox.setSelected(true); } } }); prevButton = new JButton("Previous"); this.actionPanel.add(prevButton); prevButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int currSelectionIdx = getCurrentSelection()-1; selectionModel.setSelectionInterval(currSelectionIdx, currSelectionIdx); int scrollOffset = dataViewTable.getRowHeight()*getCurrentSelection(); dataViewScrollPane.getVerticalScrollBar().setValue(scrollOffset); } }); nextButton = new JButton("Next"); this.actionPanel.add(nextButton); nextButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { int currSelectionIdx = getCurrentSelection()+1; selectionModel.setSelectionInterval(currSelectionIdx, currSelectionIdx); int scrollOffset = dataViewTable.getRowHeight()*getCurrentSelection(); dataViewScrollPane.getVerticalScrollBar().setValue(scrollOffset); } }); this.selectionModel.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { checkNavigatorButtonEnablement(); } }); }
diff --git a/src/application/MySwerveFile.java b/src/application/MySwerveFile.java index 91cb90f..4e88f17 100644 --- a/src/application/MySwerveFile.java +++ b/src/application/MySwerveFile.java @@ -1,79 +1,79 @@ package application; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.List; import javax.swing.JFileChooser; import tools.Shape; public class MySwerveFile implements SwerveFile { File file; @Override public Object open(JFileChooser filename) { file = filename.getSelectedFile(); FileInputStream fileIn = null; ObjectInputStream in = null; Object o = null; try { fileIn = new FileInputStream(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { in = new ObjectInputStream(fileIn); o = in.readObject(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return o; } @Override public void save(JFileChooser filename, List<Shape> shapes) { file = filename.getSelectedFile(); - String path = file.getPath() + ".swerve"; + String path = file.getPath() ; if (!path.contains(".swerve")) - file = new File(path); + file = new File(path + ".swerve"); FileOutputStream fileOut = null; try { fileOut = new FileOutputStream(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(shapes); out.flush(); out.close(); //FileUtils.writeLines(file, shapes); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void close() { // TODO Auto-generated method stub } }
false
true
public void save(JFileChooser filename, List<Shape> shapes) { file = filename.getSelectedFile(); String path = file.getPath() + ".swerve"; if (!path.contains(".swerve")) file = new File(path); FileOutputStream fileOut = null; try { fileOut = new FileOutputStream(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(shapes); out.flush(); out.close(); //FileUtils.writeLines(file, shapes); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
public void save(JFileChooser filename, List<Shape> shapes) { file = filename.getSelectedFile(); String path = file.getPath() ; if (!path.contains(".swerve")) file = new File(path + ".swerve"); FileOutputStream fileOut = null; try { fileOut = new FileOutputStream(file); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(shapes); out.flush(); out.close(); //FileUtils.writeLines(file, shapes); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
diff --git a/src/main/java/com/googlecode/wmbutil/messages/XmlPayload.java b/src/main/java/com/googlecode/wmbutil/messages/XmlPayload.java index d9c403a..af5f75f 100644 --- a/src/main/java/com/googlecode/wmbutil/messages/XmlPayload.java +++ b/src/main/java/com/googlecode/wmbutil/messages/XmlPayload.java @@ -1,290 +1,290 @@ /* * Copyright 2007 (C) Callista Enterprise. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.googlecode.wmbutil.messages; import com.googlecode.wmbutil.NiceMbException; import com.googlecode.wmbutil.util.ElementUtil; import com.googlecode.wmbutil.util.XmlUtil; import com.ibm.broker.plugin.MbElement; import com.ibm.broker.plugin.MbException; import com.ibm.broker.plugin.MbMessage; import com.ibm.broker.plugin.MbXMLNS; import com.ibm.broker.plugin.MbXMLNSC; /** * Helper class for working with XML messages. * */ public class XmlPayload extends Payload { private static final String DEFAULT_PARSER = "XMLNS"; private XmlElement docElm; /** * Wraps a payload * * @param msg The message containing the XML payload * @param readOnly Specifies whether the payload will be wrapped as read only or not. * @return XML payload found in the message * @throws MbException */ public static XmlPayload wrap(MbMessage msg, boolean readOnly) throws MbException { MbElement elm = locateXmlBody(msg); if (elm == null) { throw new NiceMbException("Failed to find XML payload"); } return new XmlPayload(elm, readOnly); } /** * Creates an XMLNS payload as the last child, even if one already exists * * @param msg The message where to create an XML payload * @return A newly created XML payload * @throws MbException */ public static XmlPayload create(MbMessage msg) throws MbException { return create(msg, DEFAULT_PARSER); } /** * Creates a payload as the last child, even if one already exists * * @param msg The message where to create an XML payload * @param parser Specifies the payload parser * @return A newly created XML payload * @throws MbException */ public static XmlPayload create(MbMessage msg, String parser) throws MbException { MbElement elm = msg.getRootElement().createElementAsLastChild(parser); return new XmlPayload(elm, false); } /** * Wraps or creates a payload as the last child, even if one already exists * * @param msg The message where to look for/create an XML payload * @return An XML payload, existent or newly created * @throws MbException */ public static XmlPayload wrapOrCreate(MbMessage msg) throws MbException { return wrapOrCreate(msg, DEFAULT_PARSER); } /** * Wraps or creates a payload as the last child, even if one already exists * * @param msg The message where to look for/create an XML payload * @param parser Specifies the parser when creating a new payload * @return An XML payload, existent or newly created * @throws MbException */ public static XmlPayload wrapOrCreate(MbMessage msg, String parser) throws MbException { if (has(msg)) { return wrap(msg, false); } else { return create(msg, parser); } } /** * Removes (detaches) the first XML payload * * @param msg The message containing the XML payload * @return The detached payload * @throws MbException */ public static XmlPayload remove(MbMessage msg) throws MbException { MbElement elm = locateXmlBody(msg); if (elm != null) { elm.detach(); return new XmlPayload(elm, true); } else { throw new NiceMbException("Failed to find XML payload"); } } /** * Checks if a message contains an XML payload * * @param msg The message to check * @return True if there's an XML payload in the message * @throws MbException */ public static boolean has(MbMessage msg) throws MbException { MbElement elm = locateXmlBody(msg); return elm != null; } /** * Locates the XML body in a message * * @param msg The message to check * @return The XML body element of the message * @throws MbException */ private static MbElement locateXmlBody(MbMessage msg) throws MbException { MbElement elm = msg.getRootElement().getFirstElementByPath("/XMLNSC"); if (elm == null) { elm = msg.getRootElement().getFirstElementByPath("/XMLNS"); } if (elm == null) { elm = msg.getRootElement().getFirstElementByPath("/XML"); } if (elm == null) { elm = msg.getRootElement().getFirstElementByPath("/MRM"); } return elm; } /** * Class constructor * * @param elm * @param readOnly Specifies whether the payload is readonly * @throws MbException */ private XmlPayload(MbElement elm, boolean readOnly) throws MbException { super(elm, readOnly); if (ElementUtil.isMRM(getMbElement())) { docElm = new XmlElement(getMbElement(), isReadOnly()); } else { MbElement child = getMbElement().getFirstChild(); while (child != null) { // find first and only element if (XmlUtil.isElement(child)) { docElm = new XmlElement(child, isReadOnly()); break; } child = child.getNextSibling(); } } } /** * Returns the root element * * @return The root element * @throws MbException */ public XmlElement getRootElement() { return docElm; } /** * Creates a root element (without a namespace) * * @param name The root element name * @return The root element * @throws MbException */ public XmlElement createRootElement(String name) throws MbException { return createRootElement(null, name); } /** * Creates a root element (with a namespace) * * @param ns Element name space * @param name The root element name * @return The root element * @throws MbException */ public XmlElement createRootElement(String ns, String name) throws MbException { checkReadOnly(); MbElement elm; if (ElementUtil.isMRM(getMbElement())) { // for MRM, don't generate a root element elm = getMbElement(); } else { elm = getMbElement().createElementAsLastChild( XmlUtil.getFolderElementType(getMbElement())); elm.setName(name); if (ns != null) { elm.setNamespace(ns); } } docElm = new XmlElement(elm, isReadOnly()); return docElm; } /** * Declares a namespace in the root element * * @param prefix What prefix to use * @param ns The namespace string * @throws MbException */ public void declareNamespace(String prefix, String ns) throws MbException { checkReadOnly(); if (ElementUtil.isXML(docElm.getMbElement()) || ElementUtil.isXMLNS(docElm.getMbElement()) || ElementUtil.isXMLNSC(docElm.getMbElement())) { docElm.getMbElement().createElementAsFirstChild(MbXMLNS.NAMESPACE_DECL, prefix, ns) .setNamespace("xmlns"); } } /** * Creates an XML declaration in the payload even if one exists * * @param version XML version * @param encoding XML encoding * @param standalone Specifies whether standalone should be set to yes or no * @throws MbException */ public void createXmlDeclaration(String version, String encoding, boolean standalone) throws MbException { checkReadOnly(); MbElement elm = getMbElement(); if (ElementUtil.isXMLNSC(elm)) { MbElement xmlDecl = elm.createElementAsFirstChild(MbXMLNSC.XML_DECLARATION); xmlDecl.setName("XmlDeclaration"); xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Version", version); xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Encoding", encoding); if (standalone) { xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Standalone", "yes"); } else { xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Standalone", "no"); } } else if (ElementUtil.isXML(elm) || ElementUtil.isXMLNS(elm)) { MbElement xmlDecl = elm.createElementAsFirstChild(MbXMLNS.XML_DECL); xmlDecl.setName("XmlDeclaration"); xmlDecl.createElementAsLastChild(MbXMLNS.VERSION, "version", version); xmlDecl.createElementAsLastChild(MbXMLNS.ENCODING, "encoding", encoding); if (standalone) { - xmlDecl.createElementAsLastChild(MbXMLNS.STANDALONE, "standalone", "yes"); + xmlDecl.createElementAsLastChild(MbXMLNS.STANDALONE, "Standalone", "yes"); } else { xmlDecl.createElementAsLastChild(MbXMLNS.STANDALONE, "Standalone", "no"); } } else { throw new NiceMbException("Failed to create XML declaration for parser " + XmlUtil.getFolderElementType(elm)); } } }
true
true
public void createXmlDeclaration(String version, String encoding, boolean standalone) throws MbException { checkReadOnly(); MbElement elm = getMbElement(); if (ElementUtil.isXMLNSC(elm)) { MbElement xmlDecl = elm.createElementAsFirstChild(MbXMLNSC.XML_DECLARATION); xmlDecl.setName("XmlDeclaration"); xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Version", version); xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Encoding", encoding); if (standalone) { xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Standalone", "yes"); } else { xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Standalone", "no"); } } else if (ElementUtil.isXML(elm) || ElementUtil.isXMLNS(elm)) { MbElement xmlDecl = elm.createElementAsFirstChild(MbXMLNS.XML_DECL); xmlDecl.setName("XmlDeclaration"); xmlDecl.createElementAsLastChild(MbXMLNS.VERSION, "version", version); xmlDecl.createElementAsLastChild(MbXMLNS.ENCODING, "encoding", encoding); if (standalone) { xmlDecl.createElementAsLastChild(MbXMLNS.STANDALONE, "standalone", "yes"); } else { xmlDecl.createElementAsLastChild(MbXMLNS.STANDALONE, "Standalone", "no"); } } else { throw new NiceMbException("Failed to create XML declaration for parser " + XmlUtil.getFolderElementType(elm)); } }
public void createXmlDeclaration(String version, String encoding, boolean standalone) throws MbException { checkReadOnly(); MbElement elm = getMbElement(); if (ElementUtil.isXMLNSC(elm)) { MbElement xmlDecl = elm.createElementAsFirstChild(MbXMLNSC.XML_DECLARATION); xmlDecl.setName("XmlDeclaration"); xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Version", version); xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Encoding", encoding); if (standalone) { xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Standalone", "yes"); } else { xmlDecl.createElementAsLastChild(MbXMLNSC.ATTRIBUTE, "Standalone", "no"); } } else if (ElementUtil.isXML(elm) || ElementUtil.isXMLNS(elm)) { MbElement xmlDecl = elm.createElementAsFirstChild(MbXMLNS.XML_DECL); xmlDecl.setName("XmlDeclaration"); xmlDecl.createElementAsLastChild(MbXMLNS.VERSION, "version", version); xmlDecl.createElementAsLastChild(MbXMLNS.ENCODING, "encoding", encoding); if (standalone) { xmlDecl.createElementAsLastChild(MbXMLNS.STANDALONE, "Standalone", "yes"); } else { xmlDecl.createElementAsLastChild(MbXMLNS.STANDALONE, "Standalone", "no"); } } else { throw new NiceMbException("Failed to create XML declaration for parser " + XmlUtil.getFolderElementType(elm)); } }
diff --git a/src/minecraft/andrew/powersuits/modules/OmniWrenchModule.java b/src/minecraft/andrew/powersuits/modules/OmniWrenchModule.java index 692fe39..34efd75 100644 --- a/src/minecraft/andrew/powersuits/modules/OmniWrenchModule.java +++ b/src/minecraft/andrew/powersuits/modules/OmniWrenchModule.java @@ -1,142 +1,142 @@ package andrew.powersuits.modules; import ic2.api.IWrenchable; import ic2.api.energy.tile.IEnergySink; import ic2.api.energy.tile.IEnergySource; import java.util.List; import thermalexpansion.api.tileentity.IReconfigurableFacing; import net.machinemuse.api.IModularItem; import net.machinemuse.api.ModuleManager; import net.machinemuse.api.MuseCommonStrings; import net.machinemuse.api.MuseItemUtils; import net.machinemuse.api.electricity.ElectricItemUtils; import net.machinemuse.api.moduletrigger.IRightClickModule; import net.machinemuse.powersuits.item.ItemComponent; import net.machinemuse.powersuits.powermodule.PowerModuleBase; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; import andrew.powersuits.common.AddonUtils; import buildcraft.api.tools.IToolWrench; public class OmniWrenchModule extends PowerModuleBase implements IRightClickModule, IToolWrench { public static final String MODULE_OMNI_WRENCH = "Omni Wrench"; public static final String OMNI_WRENCH_ENERGY_CONSUMPTION = "Omni Wrench Energy Consumption"; public static final int[] SIDE_OPPOSITE = {1, 0, 3, 2, 5, 4}; public OmniWrenchModule(List<IModularItem> validItems) { super(validItems); addBaseProperty(OMNI_WRENCH_ENERGY_CONSUMPTION, 100); addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.controlCircuit, 1)); addInstallCost(MuseItemUtils.copyAndResize(ItemComponent.servoMotor, 2)); } @Override public String getTextureFile() { return "torchplacer"; } @Override public String getCategory() { return MuseCommonStrings.CATEGORY_SPECIAL; } @Override public String getName() { return MODULE_OMNI_WRENCH; } @Override public String getDescription() { return "A wrench which can interact with almost every mod."; } @Override public void onRightClick(EntityPlayer playerClicking, World world, ItemStack item) {} @Override public void onItemUse(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) {} @Override public boolean onItemUseFirst(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { int blockID = world.getBlockId(x, y, z); int meta = world.getBlockMetadata(x, y, z); TileEntity tile = world.getBlockTileEntity(x, y, z); if ((tile instanceof IWrenchable) && ElectricItemUtils.getPlayerEnergy(player) > 99) { IWrenchable wrenchTile = (IWrenchable)tile; if (player.isSneaking()) { side = SIDE_OPPOSITE[side]; } if ((side == wrenchTile.getFacing()) && (wrenchTile.wrenchCanRemove(player))) { ItemStack dropBlock = wrenchTile.getWrenchDrop(player); if (dropBlock != null) { world.setBlock(x, y, z, 0); if (AddonUtils.isServerWorld(world)) { float f = 0.7F; double i = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; double j = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; double k = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; EntityItem entity = new EntityItem(world, i + x, j + y, k + z, dropBlock); entity.delayBeforeCanPickup = 10; world.spawnEntityInWorld(entity); } } ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION)); return AddonUtils.isServerWorld(world); } if (AddonUtils.isServerWorld(world)) { if ((side == 0) || (side == 1)) { if (((wrenchTile instanceof IEnergySource)) && ((wrenchTile instanceof IEnergySink))) { wrenchTile.setFacing((short)side); - ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION)); } } else { wrenchTile.setFacing((short)side); } + ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION)); } return AddonUtils.isServerWorld(world); } if ((tile instanceof IReconfigurableFacing)) { if (AddonUtils.isServerWorld(world)) { ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION)); return ((IReconfigurableFacing)tile).rotateBlock(); } return false; } return false; } @Override public void onPlayerStoppedUsing(ItemStack itemStack, World world, EntityPlayer player, int par4) {} @Override public boolean canWrench(EntityPlayer player, int x, int y, int z) { return true; } @Override public void wrenchUsed(EntityPlayer player, int x, int y, int z) {} }
false
true
public boolean onItemUseFirst(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { int blockID = world.getBlockId(x, y, z); int meta = world.getBlockMetadata(x, y, z); TileEntity tile = world.getBlockTileEntity(x, y, z); if ((tile instanceof IWrenchable) && ElectricItemUtils.getPlayerEnergy(player) > 99) { IWrenchable wrenchTile = (IWrenchable)tile; if (player.isSneaking()) { side = SIDE_OPPOSITE[side]; } if ((side == wrenchTile.getFacing()) && (wrenchTile.wrenchCanRemove(player))) { ItemStack dropBlock = wrenchTile.getWrenchDrop(player); if (dropBlock != null) { world.setBlock(x, y, z, 0); if (AddonUtils.isServerWorld(world)) { float f = 0.7F; double i = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; double j = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; double k = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; EntityItem entity = new EntityItem(world, i + x, j + y, k + z, dropBlock); entity.delayBeforeCanPickup = 10; world.spawnEntityInWorld(entity); } } ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION)); return AddonUtils.isServerWorld(world); } if (AddonUtils.isServerWorld(world)) { if ((side == 0) || (side == 1)) { if (((wrenchTile instanceof IEnergySource)) && ((wrenchTile instanceof IEnergySink))) { wrenchTile.setFacing((short)side); ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION)); } } else { wrenchTile.setFacing((short)side); } } return AddonUtils.isServerWorld(world); } if ((tile instanceof IReconfigurableFacing)) { if (AddonUtils.isServerWorld(world)) { ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION)); return ((IReconfigurableFacing)tile).rotateBlock(); } return false; } return false; }
public boolean onItemUseFirst(ItemStack itemStack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ) { int blockID = world.getBlockId(x, y, z); int meta = world.getBlockMetadata(x, y, z); TileEntity tile = world.getBlockTileEntity(x, y, z); if ((tile instanceof IWrenchable) && ElectricItemUtils.getPlayerEnergy(player) > 99) { IWrenchable wrenchTile = (IWrenchable)tile; if (player.isSneaking()) { side = SIDE_OPPOSITE[side]; } if ((side == wrenchTile.getFacing()) && (wrenchTile.wrenchCanRemove(player))) { ItemStack dropBlock = wrenchTile.getWrenchDrop(player); if (dropBlock != null) { world.setBlock(x, y, z, 0); if (AddonUtils.isServerWorld(world)) { float f = 0.7F; double i = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; double j = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; double k = world.rand.nextFloat() * f + (1.0F - f) * 0.5D; EntityItem entity = new EntityItem(world, i + x, j + y, k + z, dropBlock); entity.delayBeforeCanPickup = 10; world.spawnEntityInWorld(entity); } } ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION)); return AddonUtils.isServerWorld(world); } if (AddonUtils.isServerWorld(world)) { if ((side == 0) || (side == 1)) { if (((wrenchTile instanceof IEnergySource)) && ((wrenchTile instanceof IEnergySink))) { wrenchTile.setFacing((short)side); } } else { wrenchTile.setFacing((short)side); } ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION)); } return AddonUtils.isServerWorld(world); } if ((tile instanceof IReconfigurableFacing)) { if (AddonUtils.isServerWorld(world)) { ElectricItemUtils.drainPlayerEnergy(player, ModuleManager.computeModularProperty(itemStack, OMNI_WRENCH_ENERGY_CONSUMPTION)); return ((IReconfigurableFacing)tile).rotateBlock(); } return false; } return false; }
diff --git a/app/utils/RoleCheck.java b/app/utils/RoleCheck.java index f10fcff7..4cd20f60 100644 --- a/app/utils/RoleCheck.java +++ b/app/utils/RoleCheck.java @@ -1,30 +1,30 @@ package utils; import models.Project; import models.ProjectUser; import models.enumeration.PermissionOperation; /** * @author "Hwi Ahn" * */ public class RoleCheck { /** * 해당 유저가 해당 프로젝트에서 해당 리소스에 대하여 해당 오퍼레이션을 행할 수 있는지 여부를 boolean 값으로 반환합니다. * * @param userId * @param projectId * @param resource * @param operation * @return */ public static boolean roleCheck(String userId, Long projectId, String resource, String operation) { if (Project.findById(projectId).share_option - && operation.equals(PermissionOperation.READ)) + && operation.equals(PermissionOperation.READ.operation())) return true; return ProjectUser.permissionCheck(Long.parseLong(userId), projectId, resource, operation); } }
true
true
public static boolean roleCheck(String userId, Long projectId, String resource, String operation) { if (Project.findById(projectId).share_option && operation.equals(PermissionOperation.READ)) return true; return ProjectUser.permissionCheck(Long.parseLong(userId), projectId, resource, operation); }
public static boolean roleCheck(String userId, Long projectId, String resource, String operation) { if (Project.findById(projectId).share_option && operation.equals(PermissionOperation.READ.operation())) return true; return ProjectUser.permissionCheck(Long.parseLong(userId), projectId, resource, operation); }
diff --git a/src/com/mistphizzle/donationpoints/plugin/Methods.java b/src/com/mistphizzle/donationpoints/plugin/Methods.java index 7733dc0..b75e294 100644 --- a/src/com/mistphizzle/donationpoints/plugin/Methods.java +++ b/src/com/mistphizzle/donationpoints/plugin/Methods.java @@ -1,326 +1,326 @@ package com.mistphizzle.donationpoints.plugin; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import net.milkbowl.vault.economy.Economy; import org.bukkit.command.CommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.RegisteredServiceProvider; import com.mistphizzle.donationpoints.plugin.Objects.Transaction; public class Methods { static DonationPoints plugin; public Methods(DonationPoints instance) { plugin = instance; } public static HashMap<String, Double> accounts = new HashMap<String, Double>(); public static void loadAccounts() { ResultSet rs2 = DBConnection.sql.readQuery("SELECT * FROM " + DBConnection.playerTable); try { if (!rs2.next()) { return; } do { accounts.put(rs2.getString("player"), rs2.getDouble("balance")); } while (rs2.next()); } catch (SQLException e) { e.printStackTrace(); } } public static Double getBalance(String accountName) { return accounts.get(accountName.toLowerCase()); } public static boolean hasAccount(String accountName) { return accounts.containsKey(accountName.toLowerCase()); } public static void createAccount(String accountName) { DBConnection.sql.modifyQuery("INSERT INTO " + DBConnection.playerTable + "(player, balance) VALUES ('" + accountName.toLowerCase() + "', 0)"); accounts.put(accountName.toLowerCase(), 0.0); } public static void addPoints (Double amount, String accountName) { Double balance = accounts.get(accountName.toLowerCase()); DBConnection.sql.modifyQuery("UPDATE " + DBConnection.playerTable + " SET balance = balance + " + amount + " WHERE player = '" + accountName.toLowerCase() + "';"); accounts.put(accountName.toLowerCase(), balance + amount); } public static void removePoints (Double amount, String accountName) { Double balance = accounts.get(accountName.toLowerCase()); DBConnection.sql.modifyQuery("UPDATE " + DBConnection.playerTable + " SET balance = balance - " + amount + " WHERE player = '" + accountName.toLowerCase() + "';"); accounts.put(accountName.toLowerCase(), balance - amount); } public static void setPoints (Double amount, String accountName) { DBConnection.sql.modifyQuery("UPDATE " + DBConnection.playerTable + " SET balance = " + amount + " WHERE player = '" + accountName.toLowerCase() + "';"); accounts.put(accountName.toLowerCase(), amount); } public static void logTransaction(Transaction tran) { DBConnection.sql.modifyQuery("INSERT INTO " + DBConnection.transactionTable + "(player, package, price, date, activated, expires, expiredate, expired, server) VALUES ('" + Transaction.getPlayer() + "', '" + Transaction.getPackageName() + "', " + Transaction.getPrice() + ", '" + Transaction.getDate() + "', '" + Transaction.getActivated() + "', '" + Transaction.getExpires() + "', '" + Transaction.getExpireDate() + "', '" + Transaction.hasExpired()+ "', '" + Transaction.getServer() + "');"); } public static void logTransaction(String player, Double price, String packageName, String date, String activated, String expires, String expiredate, String expired, String server) { DBConnection.sql.modifyQuery("INSERT INTO " + DBConnection.transactionTable + "(player, package, price, date, activated, expires, expiredate, expired, server) VALUES ('" + player + "', '" + packageName + "', " + price + ", '" + date + "', '" + activated + "', '" + expires + "', '" + expiredate + "', '" + expired + "', '" + server + "');"); } public static int getTotalPackagePurchased(String player, String pack) { ResultSet rs2 = DBConnection.sql.readQuery("SELECT * FROM " + DBConnection.transactionTable + " WHERE player = '" + player.toLowerCase() + "' AND package = '" + pack + "'"); int total = 0; try { while (rs2.next()) { total++; } } catch (SQLException e) { e.printStackTrace(); } return total; } public static boolean doesPackageExpire(String pack) { if (plugin.getConfig().getInt("packages." + pack + ".ExpireTime") != 0) return true; return false; } public static Date getCurrentDateAsDate() { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); String date2 = dateFormat.format(date); try { return dateFormat.parse(date2); } catch (Exception e) { e.printStackTrace(); } return null; } public static void checkForExpiredPackages() { ResultSet rs2 = DBConnection.sql.readQuery("SELECT * FROM " + DBConnection.transactionTable + " WHERE expired = 'false';"); try { if (!rs2.next()) return; DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); do { - String expireDate = rs2.getString("expiredate"); + String expireDate = rs2.getString("expiredate").replaceAll("-", "/"); if ("expiredate" != null) { // The package will expire. Date currentDate = Methods.getCurrentDateAsDate(); Date expireDate2 = null; try { expireDate2 = dateFormat.parse(expireDate); } catch (ParseException e) { DonationPoints.log.info("Unable to parse date: " + expireDate + ". Skipping Entry."); } if (expireDate2 == null) continue; long timeUntilExpiration = (expireDate2.getTime() - currentDate.getTime()); // Returns time if (timeUntilExpiration <= 0) { String user = rs2.getString("player"); String pack = rs2.getString("package"); List<String> commands = plugin.getConfig().getStringList("packages." + pack + ".expirecommands"); for (String cmd: commands) { plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), cmd.replace("%player", user)); } DBConnection.sql.modifyQuery("UPDATE " + DBConnection.transactionTable + " SET expired = 'true' WHERE player = '" + user + "' AND package = '" + pack + "';"); DonationPoints.log.info("Expired " + user + "'s " + pack + " package."); } } } while (rs2.next()); } catch (SQLException e) { e.printStackTrace(); } } public static boolean NeedActive(String player, String packageName) { ResultSet rs2 = DBConnection.sql.readQuery("SELECT * FROM " + DBConnection.transactionTable + " WHERE player LIKE '" + player + "' AND package = '" + packageName + "' AND activated = 'false';"); try { if (rs2.next()) { return true; } else { return false; } } catch (SQLException e) { e.printStackTrace(); } return true; } public static String getCurrentDate() { DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); Date date = new Date(); return dateFormat.format(date); } public static String colorize(String message) { return message.replaceAll("(?i)&([a-fk-or0-9])", "\u00A7$1"); } public static boolean hasPurchased(String player, String packName, String server) { ResultSet rs2 = DBConnection.sql.readQuery("SELECT * FROM " + DBConnection.transactionTable + " WHERE player = '" + player + "' AND package = '" + packName + "' AND SERVER = '" + server + "';"); try { if (rs2.next()) { return true; } else { return false; } } catch (SQLException e) { e.printStackTrace(); } return true; } public static double roundTwoDecimals(double d) { DecimalFormat twoDForm = new DecimalFormat("#.##"); return Double.valueOf(twoDForm.format(d)); } public static void purgeEmptyAccounts() { ResultSet rs2 = DBConnection.sql.readQuery("SELECT * FROM " + DBConnection.playerTable + " WHERE balance = 0"); try { if (rs2.next()) { DBConnection.sql.modifyQuery("DELETE FROM " + DBConnection.playerTable + " WHERE balance = 0"); } } catch (SQLException ex) { ex.printStackTrace(); } } public static boolean getPackageExists(String pack) { if (DonationPoints.instance.getConfig().getDouble("packages." + pack + ".price") == 0) { return false; } return true; } public static void linkFrame(String pack, Double x, Double y, Double z, String world, String server) { DBConnection.sql.modifyQuery("INSERT INTO " + DBConnection.frameTable + " (x,y,z,world,package,server) VALUES ('" + x + "','" + y + "','" + z + "','" + world + "','" + pack + "', '" + server + "');"); } public static boolean isFrameLinked(Double x, Double y, Double z, String world, String server) { ResultSet rs2 = DBConnection.sql.readQuery("SELECT * FROM " + DBConnection.frameTable + " WHERE x = '" + x + "' AND y = '" + y + "' AND z = '" + z + "' AND world = '" + world + "' AND server = '" + server + "';"); try { if (rs2.next()) { return true; } else { return false; } } catch (SQLException e) { e.printStackTrace(); } return false; } public static String getLinkedPackage(Double x, Double y, Double z, String world, String server) { String linkedPack = null; ResultSet rs2 = DBConnection.sql.readQuery("SELECT package FROM " + DBConnection.frameTable + " WHERE x = '" + x + "' AND y = '" + y + "' AND z = '" + z + "' AND world = '" + world + "' AND server = '" + server + "';"); try { if (rs2.next()) { linkedPack = rs2.getString("package"); return linkedPack; } } catch (SQLException e) { e.printStackTrace(); } return linkedPack; } public static void deleteAccount(String accountName) { DBConnection.sql.modifyQuery("DELETE FROM " + DBConnection.playerTable + " WHERE player = '" + accountName + "';"); accounts.remove(accountName); } public static void unlinkFrame(Double x, Double y, Double z, String world, String server) { DBConnection.sql.modifyQuery("DELETE FROM " + DBConnection.frameTable + " WHERE x = '" + x + "' AND y = '" + y + "' AND z = '" + z + "' AND world = '" + world + "' AND server = '"+ server + "';"); } public static boolean hasInventorySpace(Player player, int requiredSlots) { int emptySlots = 0; for (ItemStack i : player.getInventory().getContents()) { if (i == null) { emptySlots++; } } if (emptySlots >= requiredSlots) { return true; } return false; } public static Economy econ; public static boolean setupEconomy() { if (plugin.getServer().getPluginManager().getPlugin("Vault") == null) { return false; } RegisteredServiceProvider<Economy> rsp = plugin.getServer().getServicesManager().getRegistration(Economy.class); if (rsp == null) return false; econ = rsp.getProvider(); return econ != null; } public static boolean hasPermission(CommandSender player, String permission) { return DonationPoints.permission.has(player, permission); } public static void createExamplePackage() { FileConfiguration config = plugin.getConfig(); config.set("packages.ExamplePackage.UseVaultEconomy", false); config.set("packages.ExamplePackage.price", 100); config.set("packages.ExamplePackage.description", "This is an example package."); config.set("packages.ExamplePackage.limit", 0); config.set("packages.ExamplePackage.ActivateImmediately", true); config.set("packages.ExamplePackage.ExpireTime", 0); List<String> restrictToWorlds = new ArrayList<String>(); restrictToWorlds.add("world"); config.set("packages.ExamplePackage.RestrictToWorlds", restrictToWorlds); List<String> activationCommands = new ArrayList<String>(); activationCommands.add("say %player has purchased the Example package."); activationCommands.add("p:me purchased the Example Package."); config.set("packages.ExamplePackage.ActivationCommands", activationCommands); List<String> expirationCommands = new ArrayList<String>(); expirationCommands.add("say %player's Example Package has expired."); config.set("packages.ExamplePackage.ExpirationCommands", expirationCommands); List<String> preRequisites = new ArrayList<String>(); config.set("packages.ExamplePackage.PreRequisites", preRequisites); config.set("packages.ExamplePackage.RequiredInventorySpace", 0); plugin.saveConfig(); } public static boolean isPackMisconfigured(String packageName) { FileConfiguration config = plugin.getConfig(); if (config.get("packages." + packageName + ".UseVaultEconomy") == null) return true; if (config.get("packages." + packageName + ".price") == null) return true; if (config.getDouble("packages." + packageName + ".price") < 0) return true; if (config.getString("packages." + packageName + ".description") == null) return true; if (config.get("packages." + packageName + ".limit") == null) return true; if (config.getInt("packages." + packageName + ".limit") < 0) return true; if (config.get("packages." + packageName + ".ActivateImmediately") == null) return true; if (config.get("packages." + packageName + ".ExpireTime") == null) return true; if (config.getInt("packages." + packageName + ".ExpireTime") < 0) return true; if (config.get("packages." + packageName + ".ActivationCommands") == null) return true; return false; } }
true
true
public static void checkForExpiredPackages() { ResultSet rs2 = DBConnection.sql.readQuery("SELECT * FROM " + DBConnection.transactionTable + " WHERE expired = 'false';"); try { if (!rs2.next()) return; DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); do { String expireDate = rs2.getString("expiredate"); if ("expiredate" != null) { // The package will expire. Date currentDate = Methods.getCurrentDateAsDate(); Date expireDate2 = null; try { expireDate2 = dateFormat.parse(expireDate); } catch (ParseException e) { DonationPoints.log.info("Unable to parse date: " + expireDate + ". Skipping Entry."); } if (expireDate2 == null) continue; long timeUntilExpiration = (expireDate2.getTime() - currentDate.getTime()); // Returns time if (timeUntilExpiration <= 0) { String user = rs2.getString("player"); String pack = rs2.getString("package"); List<String> commands = plugin.getConfig().getStringList("packages." + pack + ".expirecommands"); for (String cmd: commands) { plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), cmd.replace("%player", user)); } DBConnection.sql.modifyQuery("UPDATE " + DBConnection.transactionTable + " SET expired = 'true' WHERE player = '" + user + "' AND package = '" + pack + "';"); DonationPoints.log.info("Expired " + user + "'s " + pack + " package."); } } } while (rs2.next()); } catch (SQLException e) { e.printStackTrace(); } }
public static void checkForExpiredPackages() { ResultSet rs2 = DBConnection.sql.readQuery("SELECT * FROM " + DBConnection.transactionTable + " WHERE expired = 'false';"); try { if (!rs2.next()) return; DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); do { String expireDate = rs2.getString("expiredate").replaceAll("-", "/"); if ("expiredate" != null) { // The package will expire. Date currentDate = Methods.getCurrentDateAsDate(); Date expireDate2 = null; try { expireDate2 = dateFormat.parse(expireDate); } catch (ParseException e) { DonationPoints.log.info("Unable to parse date: " + expireDate + ". Skipping Entry."); } if (expireDate2 == null) continue; long timeUntilExpiration = (expireDate2.getTime() - currentDate.getTime()); // Returns time if (timeUntilExpiration <= 0) { String user = rs2.getString("player"); String pack = rs2.getString("package"); List<String> commands = plugin.getConfig().getStringList("packages." + pack + ".expirecommands"); for (String cmd: commands) { plugin.getServer().dispatchCommand(plugin.getServer().getConsoleSender(), cmd.replace("%player", user)); } DBConnection.sql.modifyQuery("UPDATE " + DBConnection.transactionTable + " SET expired = 'true' WHERE player = '" + user + "' AND package = '" + pack + "';"); DonationPoints.log.info("Expired " + user + "'s " + pack + " package."); } } } while (rs2.next()); } catch (SQLException e) { e.printStackTrace(); } }
diff --git a/src/com/android/contacts/datepicker/DatePicker.java b/src/com/android/contacts/datepicker/DatePicker.java index fe2341526..d0510ab43 100644 --- a/src/com/android/contacts/datepicker/DatePicker.java +++ b/src/com/android/contacts/datepicker/DatePicker.java @@ -1,491 +1,489 @@ /* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.contacts.datepicker; // This is a fork of the standard Android DatePicker that additionally allows toggling the year // on/off. It uses some private API so that not everything has to be copied. import android.animation.LayoutTransition; import android.annotation.Widget; import android.content.Context; import android.content.res.TypedArray; import android.os.Parcel; import android.os.Parcelable; import android.text.format.DateFormat; import android.util.AttributeSet; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.NumberPicker; import android.widget.NumberPicker.OnValueChangeListener; import com.android.contacts.R; import java.text.DateFormatSymbols; import java.text.SimpleDateFormat; import java.util.Calendar; /** * A view for selecting a month / year / day based on a calendar like layout. * * <p>See the <a href="{@docRoot}resources/tutorials/views/hello-datepicker.html">Date Picker * tutorial</a>.</p> * * For a dialog using this view, see {@link android.app.DatePickerDialog}. */ @Widget public class DatePicker extends FrameLayout { /** Magic year that represents "no year" */ public static int NO_YEAR = 0; private static final int DEFAULT_START_YEAR = 1900; private static final int DEFAULT_END_YEAR = 2100; /* UI Components */ private final LinearLayout mPickerContainer; private final CheckBox mYearToggle; private final NumberPicker mDayPicker; private final NumberPicker mMonthPicker; private final NumberPicker mYearPicker; /** * How we notify users the date has changed. */ private OnDateChangedListener mOnDateChangedListener; private int mDay; private int mMonth; private int mYear; private boolean mYearOptional; private boolean mHasYear; /** * The callback used to indicate the user changes the date. */ public interface OnDateChangedListener { /** * @param view The view associated with this listener. * @param year The year that was set or {@link DatePicker#NO_YEAR} if no year was set * @param monthOfYear The month that was set (0-11) for compatibility * with {@link java.util.Calendar}. * @param dayOfMonth The day of the month that was set. */ void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth); } public DatePicker(Context context) { this(context, null); } public DatePicker(Context context, AttributeSet attrs) { this(context, attrs, 0); } public DatePicker(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.date_picker, this, true); mPickerContainer = (LinearLayout) findViewById(R.id.parent); mDayPicker = (NumberPicker) findViewById(R.id.day); mDayPicker.setFormatter(NumberPicker.getTwoDigitFormatter()); mDayPicker.setOnLongPressUpdateInterval(100); mDayPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { mDay = newVal; notifyDateChanged(); } }); mMonthPicker = (NumberPicker) findViewById(R.id.month); mMonthPicker.setFormatter(NumberPicker.getTwoDigitFormatter()); DateFormatSymbols dfs = new DateFormatSymbols(); String[] months = dfs.getShortMonths(); /* * If the user is in a locale where the month names are numeric, * use just the number instead of the "month" character for * consistency with the other fields. */ if (months[0].startsWith("1")) { for (int i = 0; i < months.length; i++) { months[i] = String.valueOf(i + 1); } - mMonthPicker.setMinValue(1); - mMonthPicker.setMaxValue(12); } else { - mMonthPicker.setMinValue(1); - mMonthPicker.setMaxValue(12); mMonthPicker.setDisplayedValues(months); } + mMonthPicker.setMinValue(1); + mMonthPicker.setMaxValue(12); mMonthPicker.setOnLongPressUpdateInterval(200); mMonthPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { /* We display the month 1-12 but store it 0-11 so always * subtract by one to ensure our internal state is always 0-11 */ mMonth = newVal - 1; // Adjust max day of the month adjustMaxDay(); notifyDateChanged(); updateDaySpinner(); } }); mYearPicker = (NumberPicker) findViewById(R.id.year); mYearPicker.setOnLongPressUpdateInterval(100); mYearPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { mYear = newVal; // Adjust max day for leap years if needed adjustMaxDay(); notifyDateChanged(); updateDaySpinner(); } }); mYearToggle = (CheckBox) findViewById(R.id.yearToggle); mYearToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mHasYear = isChecked; adjustMaxDay(); notifyDateChanged(); updateSpinners(); } }); // attributes TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.DatePicker); int mStartYear = a.getInt(com.android.internal.R.styleable.DatePicker_startYear, DEFAULT_START_YEAR); int mEndYear = a.getInt(com.android.internal.R.styleable.DatePicker_endYear, DEFAULT_END_YEAR); mYearPicker.setMinValue(mStartYear); mYearPicker.setMaxValue(mEndYear); a.recycle(); // initialize to current date Calendar cal = Calendar.getInstance(); init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null); // re-order the number pickers to match the current date format reorderPickers(months); mPickerContainer.setLayoutTransition(new LayoutTransition()); if (!isEnabled()) { setEnabled(false); } } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); mDayPicker.setEnabled(enabled); mMonthPicker.setEnabled(enabled); mYearPicker.setEnabled(enabled); } private void reorderPickers(String[] months) { java.text.DateFormat format; String order; /* * If the user is in a locale where the medium date format is * still numeric (Japanese and Czech, for example), respect * the date format order setting. Otherwise, use the order * that the locale says is appropriate for a spelled-out date. */ if (months[0].startsWith("1")) { format = DateFormat.getDateFormat(getContext()); } else { format = DateFormat.getMediumDateFormat(getContext()); } if (format instanceof SimpleDateFormat) { order = ((SimpleDateFormat) format).toPattern(); } else { // Shouldn't happen, but just in case. order = new String(DateFormat.getDateFormatOrder(getContext())); } /* Remove the 3 pickers from their parent and then add them back in the * required order. */ mPickerContainer.removeAllViews(); boolean quoted = false; boolean didDay = false, didMonth = false, didYear = false; for (int i = 0; i < order.length(); i++) { char c = order.charAt(i); if (c == '\'') { quoted = !quoted; } if (!quoted) { if (c == DateFormat.DATE && !didDay) { mPickerContainer.addView(mDayPicker); didDay = true; } else if ((c == DateFormat.MONTH || c == 'L') && !didMonth) { mPickerContainer.addView(mMonthPicker); didMonth = true; } else if (c == DateFormat.YEAR && !didYear) { mPickerContainer.addView (mYearPicker); didYear = true; } } } // Shouldn't happen, but just in case. if (!didMonth) { mPickerContainer.addView(mMonthPicker); } if (!didDay) { mPickerContainer.addView(mDayPicker); } if (!didYear) { mPickerContainer.addView(mYearPicker); } } public void updateDate(int year, int monthOfYear, int dayOfMonth) { if (mYear != year || mMonth != monthOfYear || mDay != dayOfMonth) { mYear = (mYearOptional && year == NO_YEAR) ? getCurrentYear() : year; mMonth = monthOfYear; mDay = dayOfMonth; updateSpinners(); reorderPickers(new DateFormatSymbols().getShortMonths()); notifyDateChanged(); } } private int getCurrentYear() { return Calendar.getInstance().get(Calendar.YEAR); } private static class SavedState extends BaseSavedState { private final int mYear; private final int mMonth; private final int mDay; private final boolean mHasYear; private final boolean mYearOptional; /** * Constructor called from {@link DatePicker#onSaveInstanceState()} */ private SavedState(Parcelable superState, int year, int month, int day, boolean hasYear, boolean yearOptional) { super(superState); mYear = year; mMonth = month; mDay = day; mHasYear = hasYear; mYearOptional = yearOptional; } /** * Constructor called from {@link #CREATOR} */ private SavedState(Parcel in) { super(in); mYear = in.readInt(); mMonth = in.readInt(); mDay = in.readInt(); mHasYear = in.readInt() != 0; mYearOptional = in.readInt() != 0; } public int getYear() { return mYear; } public int getMonth() { return mMonth; } public int getDay() { return mDay; } public boolean hasYear() { return mHasYear; } public boolean isYearOptional() { return mYearOptional; } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(mYear); dest.writeInt(mMonth); dest.writeInt(mDay); dest.writeInt(mHasYear ? 1 : 0); dest.writeInt(mYearOptional ? 1 : 0); } @SuppressWarnings("unused") public static final Parcelable.Creator<SavedState> CREATOR = new Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } /** * Override so we are in complete control of save / restore for this widget. */ @Override protected void dispatchRestoreInstanceState(SparseArray<Parcelable> container) { dispatchThawSelfOnly(container); } @Override protected Parcelable onSaveInstanceState() { Parcelable superState = super.onSaveInstanceState(); return new SavedState(superState, mYear, mMonth, mDay, mHasYear, mYearOptional); } @Override protected void onRestoreInstanceState(Parcelable state) { SavedState ss = (SavedState) state; super.onRestoreInstanceState(ss.getSuperState()); mYear = ss.getYear(); mMonth = ss.getMonth(); mDay = ss.getDay(); mHasYear = ss.hasYear(); mYearOptional = ss.isYearOptional(); updateSpinners(); } /** * Initialize the state. * @param year The initial year. * @param monthOfYear The initial month. * @param dayOfMonth The initial day of the month. * @param onDateChangedListener How user is notified date is changed by user, can be null. */ public void init(int year, int monthOfYear, int dayOfMonth, OnDateChangedListener onDateChangedListener) { init(year, monthOfYear, dayOfMonth, false, onDateChangedListener); } /** * Initialize the state. * @param year The initial year or {@link #NO_YEAR} if no year has been specified * @param monthOfYear The initial month. * @param dayOfMonth The initial day of the month. * @param yearOptional True if the user can toggle the year * @param onDateChangedListener How user is notified date is changed by user, can be null. */ public void init(int year, int monthOfYear, int dayOfMonth, boolean yearOptional, OnDateChangedListener onDateChangedListener) { mYear = (yearOptional && year == NO_YEAR) ? getCurrentYear() : year; mMonth = monthOfYear; mDay = dayOfMonth; mYearOptional = yearOptional; mHasYear = yearOptional ? (year != NO_YEAR) : true; mOnDateChangedListener = onDateChangedListener; updateSpinners(); } private void updateSpinners() { updateDaySpinner(); mYearToggle.setChecked(mHasYear); mYearToggle.setVisibility(mYearOptional ? View.VISIBLE : View.GONE); mYearPicker.setValue(mYear); mYearPicker.setVisibility(mHasYear ? View.VISIBLE : View.GONE); /* The month display uses 1-12 but our internal state stores it * 0-11 so add one when setting the display. */ mMonthPicker.setValue(mMonth + 1); } private void updateDaySpinner() { Calendar cal = Calendar.getInstance(); // if year was not set, use 2000 as it was a leap year cal.set(mHasYear ? mYear : 2000, mMonth, 1); int max = cal.getActualMaximum(Calendar.DAY_OF_MONTH); mDayPicker.setMinValue(1); mDayPicker.setMaxValue(max); mDayPicker.setValue(mDay); } public int getYear() { return (mYearOptional && !mHasYear) ? NO_YEAR : mYear; } public boolean isYearOptional() { return mYearOptional; } public int getMonth() { return mMonth; } public int getDayOfMonth() { return mDay; } private void adjustMaxDay(){ Calendar cal = Calendar.getInstance(); // if year was not set, use 2000 as it was a leap year cal.set(Calendar.YEAR, mHasYear ? mYear : 2000); cal.set(Calendar.MONTH, mMonth); int max = cal.getActualMaximum(Calendar.DAY_OF_MONTH); if (mDay > max) { mDay = max; } } private void notifyDateChanged() { if (mOnDateChangedListener != null) { int year = (mYearOptional && !mHasYear) ? NO_YEAR : mYear; mOnDateChangedListener.onDateChanged(DatePicker.this, year, mMonth, mDay); } } }
false
true
public DatePicker(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.date_picker, this, true); mPickerContainer = (LinearLayout) findViewById(R.id.parent); mDayPicker = (NumberPicker) findViewById(R.id.day); mDayPicker.setFormatter(NumberPicker.getTwoDigitFormatter()); mDayPicker.setOnLongPressUpdateInterval(100); mDayPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { mDay = newVal; notifyDateChanged(); } }); mMonthPicker = (NumberPicker) findViewById(R.id.month); mMonthPicker.setFormatter(NumberPicker.getTwoDigitFormatter()); DateFormatSymbols dfs = new DateFormatSymbols(); String[] months = dfs.getShortMonths(); /* * If the user is in a locale where the month names are numeric, * use just the number instead of the "month" character for * consistency with the other fields. */ if (months[0].startsWith("1")) { for (int i = 0; i < months.length; i++) { months[i] = String.valueOf(i + 1); } mMonthPicker.setMinValue(1); mMonthPicker.setMaxValue(12); } else { mMonthPicker.setMinValue(1); mMonthPicker.setMaxValue(12); mMonthPicker.setDisplayedValues(months); } mMonthPicker.setOnLongPressUpdateInterval(200); mMonthPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { /* We display the month 1-12 but store it 0-11 so always * subtract by one to ensure our internal state is always 0-11 */ mMonth = newVal - 1; // Adjust max day of the month adjustMaxDay(); notifyDateChanged(); updateDaySpinner(); } }); mYearPicker = (NumberPicker) findViewById(R.id.year); mYearPicker.setOnLongPressUpdateInterval(100); mYearPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { mYear = newVal; // Adjust max day for leap years if needed adjustMaxDay(); notifyDateChanged(); updateDaySpinner(); } }); mYearToggle = (CheckBox) findViewById(R.id.yearToggle); mYearToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mHasYear = isChecked; adjustMaxDay(); notifyDateChanged(); updateSpinners(); } }); // attributes TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.DatePicker); int mStartYear = a.getInt(com.android.internal.R.styleable.DatePicker_startYear, DEFAULT_START_YEAR); int mEndYear = a.getInt(com.android.internal.R.styleable.DatePicker_endYear, DEFAULT_END_YEAR); mYearPicker.setMinValue(mStartYear); mYearPicker.setMaxValue(mEndYear); a.recycle(); // initialize to current date Calendar cal = Calendar.getInstance(); init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null); // re-order the number pickers to match the current date format reorderPickers(months); mPickerContainer.setLayoutTransition(new LayoutTransition()); if (!isEnabled()) { setEnabled(false); } }
public DatePicker(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.date_picker, this, true); mPickerContainer = (LinearLayout) findViewById(R.id.parent); mDayPicker = (NumberPicker) findViewById(R.id.day); mDayPicker.setFormatter(NumberPicker.getTwoDigitFormatter()); mDayPicker.setOnLongPressUpdateInterval(100); mDayPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { mDay = newVal; notifyDateChanged(); } }); mMonthPicker = (NumberPicker) findViewById(R.id.month); mMonthPicker.setFormatter(NumberPicker.getTwoDigitFormatter()); DateFormatSymbols dfs = new DateFormatSymbols(); String[] months = dfs.getShortMonths(); /* * If the user is in a locale where the month names are numeric, * use just the number instead of the "month" character for * consistency with the other fields. */ if (months[0].startsWith("1")) { for (int i = 0; i < months.length; i++) { months[i] = String.valueOf(i + 1); } } else { mMonthPicker.setDisplayedValues(months); } mMonthPicker.setMinValue(1); mMonthPicker.setMaxValue(12); mMonthPicker.setOnLongPressUpdateInterval(200); mMonthPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { /* We display the month 1-12 but store it 0-11 so always * subtract by one to ensure our internal state is always 0-11 */ mMonth = newVal - 1; // Adjust max day of the month adjustMaxDay(); notifyDateChanged(); updateDaySpinner(); } }); mYearPicker = (NumberPicker) findViewById(R.id.year); mYearPicker.setOnLongPressUpdateInterval(100); mYearPicker.setOnValueChangedListener(new OnValueChangeListener() { @Override public void onValueChange(NumberPicker picker, int oldVal, int newVal) { mYear = newVal; // Adjust max day for leap years if needed adjustMaxDay(); notifyDateChanged(); updateDaySpinner(); } }); mYearToggle = (CheckBox) findViewById(R.id.yearToggle); mYearToggle.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { mHasYear = isChecked; adjustMaxDay(); notifyDateChanged(); updateSpinners(); } }); // attributes TypedArray a = context.obtainStyledAttributes(attrs, com.android.internal.R.styleable.DatePicker); int mStartYear = a.getInt(com.android.internal.R.styleable.DatePicker_startYear, DEFAULT_START_YEAR); int mEndYear = a.getInt(com.android.internal.R.styleable.DatePicker_endYear, DEFAULT_END_YEAR); mYearPicker.setMinValue(mStartYear); mYearPicker.setMaxValue(mEndYear); a.recycle(); // initialize to current date Calendar cal = Calendar.getInstance(); init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), null); // re-order the number pickers to match the current date format reorderPickers(months); mPickerContainer.setLayoutTransition(new LayoutTransition()); if (!isEnabled()) { setEnabled(false); } }
diff --git a/CSipSimple/src/com/csipsimple/service/MediaManager.java b/CSipSimple/src/com/csipsimple/service/MediaManager.java index dc70781f..0916a577 100644 --- a/CSipSimple/src/com/csipsimple/service/MediaManager.java +++ b/CSipSimple/src/com/csipsimple/service/MediaManager.java @@ -1,631 +1,634 @@ /** * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr) * This file is part of CSipSimple. * * CSipSimple is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * If you own a pjsip commercial license you can also redistribute it * and/or modify it under the terms of the GNU Lesser General Public License * as an android library. * * CSipSimple is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CSipSimple. If not, see <http://www.gnu.org/licenses/>. */ package com.csipsimple.service; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.media.AudioManager; import android.media.ToneGenerator; import android.net.NetworkInfo.DetailedState; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.net.wifi.WifiManager.WifiLock; import android.os.PowerManager; import android.os.PowerManager.WakeLock; import android.provider.Settings; import com.csipsimple.api.MediaState; import com.csipsimple.api.SipConfigManager; import com.csipsimple.api.SipManager; import com.csipsimple.service.SipService.SameThreadException; import com.csipsimple.service.SipService.SipRunnable; import com.csipsimple.utils.Compatibility; import com.csipsimple.utils.Log; import com.csipsimple.utils.Ringer; import com.csipsimple.utils.accessibility.AccessibilityWrapper; import com.csipsimple.utils.audio.AudioFocusWrapper; import com.csipsimple.utils.bluetooth.BluetoothWrapper; public class MediaManager { final private static String THIS_FILE = "MediaManager"; private SipService service; private AudioManager audioManager; private Ringer ringer; //Locks private WifiLock wifiLock; private WakeLock screenLock; private WakeLock cpuLock; // Media settings to save / resore private boolean isSetAudioMode = false; //By default we assume user want bluetooth. //If bluetooth is not available connection will never be done and then //UI will not show bluetooth is activated private boolean userWantBluetooth = false; private boolean userWantSpeaker = false; private boolean userWantMicrophoneMute = false; private Intent mediaStateChangedIntent; //Bluetooth related private BluetoothWrapper bluetoothWrapper; private AudioFocusWrapper audioFocusWrapper; private AccessibilityWrapper accessibilityManager; private SharedPreferences prefs; private boolean useSgsWrkAround = false; private boolean useWebRTCImpl = false; private boolean doFocusAudio = true; private static int modeSipInCall = AudioManager.MODE_NORMAL; public MediaManager(SipService aService) { service = aService; audioManager = (AudioManager) service.getSystemService(Context.AUDIO_SERVICE); prefs = service.getSharedPreferences("audio", Context.MODE_PRIVATE); //prefs = PreferenceManager.getDefaultSharedPreferences(service); accessibilityManager = AccessibilityWrapper.getInstance(); accessibilityManager.init(service); ringer = new Ringer(service); mediaStateChangedIntent = new Intent(SipManager.ACTION_SIP_MEDIA_CHANGED); //Try to reset if there were a crash in a call could restore previous settings restoreAudioState(); } public void startService() { if(bluetoothWrapper == null) { bluetoothWrapper = BluetoothWrapper.getInstance(); bluetoothWrapper.init(service, this); } if(audioFocusWrapper == null) { audioFocusWrapper = AudioFocusWrapper.getInstance(); audioFocusWrapper.init(service, audioManager); } modeSipInCall = service.getPrefs().getInCallMode(); useSgsWrkAround = service.getPrefs().getPreferenceBooleanValue(SipConfigManager.USE_SGS_CALL_HACK); useWebRTCImpl = service.getPrefs().getPreferenceBooleanValue(SipConfigManager.USE_WEBRTC_HACK); doFocusAudio = service.getPrefs().getPreferenceBooleanValue(SipConfigManager.DO_FOCUS_AUDIO); userWantBluetooth = service.getPrefs().getPreferenceBooleanValue(SipConfigManager.AUTO_CONNECT_BLUETOOTH); } public void stopService() { Log.i(THIS_FILE, "Remove media manager...."); if(bluetoothWrapper != null) { bluetoothWrapper.unregister(); } } private int getAudioTargetMode() { int targetMode = modeSipInCall; if(service.getPrefs().useModeApi()) { Log.d(THIS_FILE, "User want speaker now..."+userWantSpeaker); if(!service.getPrefs().generateForSetCall()) { return userWantSpeaker ? AudioManager.MODE_NORMAL : AudioManager.MODE_IN_CALL; }else { return userWantSpeaker ? AudioManager.MODE_IN_CALL: AudioManager.MODE_NORMAL ; } } if(userWantBluetooth) { targetMode = AudioManager.MODE_NORMAL; } Log.d(THIS_FILE, "Target mode... : " + targetMode); return targetMode; } public int validateAudioClockRate(int clockRate) { if(bluetoothWrapper != null && clockRate != 8000) { if(userWantBluetooth && bluetoothWrapper.canBluetooth()) { return -1; } } return 0; } public void setAudioInCall() { actualSetAudioInCall(); } public void unsetAudioInCall() { actualUnsetAudioInCall(); } /** * Set the audio mode as in call */ @SuppressWarnings("deprecation") private synchronized void actualSetAudioInCall() { //Ensure not already set if(isSetAudioMode) { return; } stopRing(); saveAudioState(); - //Set the rest of the phone in a better state to not interferate with current call - audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON); - audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF); - audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); + // Set the rest of the phone in a better state to not interferate with current call + // Do that only if we were not already in silent mode + if(audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) { + audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON); + audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF); + audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); + } //LOCKS //Wifi management if necessary ContentResolver ctntResolver = service.getContentResolver(); Settings.System.putInt(ctntResolver, Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER); //Acquire wifi lock WifiManager wman = (WifiManager) service.getSystemService(Context.WIFI_SERVICE); if(wifiLock == null) { wifiLock = wman.createWifiLock( (Compatibility.isCompatible(9)) ? 3 : WifiManager.WIFI_MODE_FULL, "com.csipsimple.InCallLock"); wifiLock.setReferenceCounted(false); } WifiInfo winfo = wman.getConnectionInfo(); if(winfo != null) { DetailedState dstate = WifiInfo.getDetailedStateOf(winfo.getSupplicantState()); //We assume that if obtaining ip addr, we are almost connected so can keep wifi lock if(dstate == DetailedState.OBTAINING_IPADDR || dstate == DetailedState.CONNECTED) { if(!wifiLock.isHeld()) { wifiLock.acquire(); } } //This wake lock purpose is to prevent PSP wifi mode if(service.getPrefs().getPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL)) { if(screenLock == null) { PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE); screenLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "com.csipsimple.onIncomingCall.SCREEN"); screenLock.setReferenceCounted(false); } //Ensure single lock if(!screenLock.isHeld()) { screenLock.acquire(); } } } if(cpuLock == null) { PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE); cpuLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.onIncomingCall.CPU"); cpuLock.setReferenceCounted(false); } if(!cpuLock.isHeld()) { cpuLock.acquire(); } if(!useWebRTCImpl) { //Audio routing int targetMode = getAudioTargetMode(); Log.d(THIS_FILE, "Set mode audio in call to "+targetMode); if(service.getPrefs().generateForSetCall()) { ToneGenerator toneGenerator = new ToneGenerator( AudioManager.STREAM_VOICE_CALL, 1); toneGenerator.startTone(41 /*ToneGenerator.TONE_CDMA_CONFIRM*/); toneGenerator.stopTone(); toneGenerator.release(); } //Set mode if(targetMode != AudioManager.MODE_IN_CALL && useSgsWrkAround) { //For galaxy S we need to set in call mode before to reset stack audioManager.setMode(AudioManager.MODE_IN_CALL); } audioManager.setMode(targetMode); //Routing if(service.getPrefs().useRoutingApi()) { audioManager.setRouting(targetMode, userWantSpeaker?AudioManager.ROUTE_SPEAKER:AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL); }else { audioManager.setSpeakerphoneOn(userWantSpeaker ? true : false); } audioManager.setMicrophoneMute(false); if(bluetoothWrapper != null && userWantBluetooth && bluetoothWrapper.canBluetooth()) { Log.d(THIS_FILE, "Try to enable bluetooth"); bluetoothWrapper.setBluetoothOn(true); } }else { //WebRTC implementation for routing int apiLevel = Compatibility.getApiLevel(); //SetAudioMode // ***IMPORTANT*** When the API level for honeycomb (H) has been // decided, // the condition should be changed to include API level 8 to H-1. if ( android.os.Build.BRAND.equalsIgnoreCase("Samsung") && (8 == apiLevel)) { // Set Samsung specific VoIP mode for 2.2 devices int mode = 4; audioManager.setMode(mode); if (audioManager.getMode() != mode) { Log.e(THIS_FILE, "Could not set audio mode for Samsung device"); } } //SetPlayoutSpeaker if ((3 == apiLevel) || (4 == apiLevel)) { // 1.5 and 1.6 devices if (userWantSpeaker) { // route audio to back speaker audioManager.setMode(AudioManager.MODE_NORMAL); } else { // route audio to earpiece audioManager.setMode(AudioManager.MODE_IN_CALL); } } else { // 2.x devices if ((android.os.Build.BRAND.equalsIgnoreCase("samsung")) && ((5 == apiLevel) || (6 == apiLevel) || (7 == apiLevel))) { // Samsung 2.0, 2.0.1 and 2.1 devices if (userWantSpeaker) { // route audio to back speaker audioManager.setMode(AudioManager.MODE_IN_CALL); audioManager.setSpeakerphoneOn(userWantSpeaker); } else { // route audio to earpiece audioManager.setSpeakerphoneOn(userWantSpeaker); audioManager.setMode(AudioManager.MODE_NORMAL); } } else { // Non-Samsung and Samsung 2.2 and up devices audioManager.setSpeakerphoneOn(userWantSpeaker); } } } //Set stream solo/volume/focus int inCallStream = Compatibility.getInCallStream(); if(doFocusAudio) { if(!accessibilityManager.isEnabled()) { audioManager.setStreamSolo(inCallStream, true); } audioFocusWrapper.focus(); } Log.d(THIS_FILE, "Initial volume level : " + service.getPrefs().getInitialVolumeLevel()); setStreamVolume(inCallStream, (int) (audioManager.getStreamMaxVolume(inCallStream) * service.getPrefs().getInitialVolumeLevel()), 0); isSetAudioMode = true; // System.gc(); } /** * Save current audio mode in order to be able to restore it once done */ @SuppressWarnings("deprecation") private synchronized void saveAudioState() { if( prefs.getBoolean("isSavedAudioState", false) ) { //If we have already set, do not set it again !!! return; } ContentResolver ctntResolver = service.getContentResolver(); Editor ed = prefs.edit(); ed.putInt("savedVibrateRing", audioManager.getVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER)); ed.putInt("savedVibradeNotif", audioManager.getVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION)); ed.putInt("savedRingerMode", audioManager.getRingerMode()); ed.putInt("savedWifiPolicy" , android.provider.Settings.System.getInt(ctntResolver, android.provider.Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT)); int inCallStream = Compatibility.getInCallStream(); ed.putInt("savedVolume", audioManager.getStreamVolume(inCallStream)); int targetMode = getAudioTargetMode(); if(service.getPrefs().useRoutingApi()) { ed.putInt("savedRoute", audioManager.getRouting(targetMode)); }else { ed.putBoolean("savedSpeakerPhone", audioManager.isSpeakerphoneOn()); } ed.putInt("savedMode", audioManager.getMode()); ed.putBoolean("isSavedAudioState", true); ed.commit(); } /** * Restore the state of the audio */ @SuppressWarnings("deprecation") private final synchronized void restoreAudioState() { if( !prefs.getBoolean("isSavedAudioState", false) ) { //If we have NEVER set, do not try to reset ! return; } ContentResolver ctntResolver = service.getContentResolver(); Settings.System.putInt(ctntResolver, Settings.System.WIFI_SLEEP_POLICY, prefs.getInt("savedWifiPolicy", Settings.System.WIFI_SLEEP_POLICY_DEFAULT)); audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, prefs.getInt("savedVibrateRing", AudioManager.VIBRATE_SETTING_ONLY_SILENT)); audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, prefs.getInt("savedVibradeNotif", AudioManager.VIBRATE_SETTING_OFF)); audioManager.setRingerMode(prefs.getInt("savedRingerMode", AudioManager.RINGER_MODE_NORMAL)); int inCallStream = Compatibility.getInCallStream(); setStreamVolume(inCallStream, prefs.getInt("savedVolume", (int)(audioManager.getStreamMaxVolume(inCallStream)*0.8) ), 0); int targetMode = getAudioTargetMode(); if(service.getPrefs().useRoutingApi()) { audioManager.setRouting(targetMode, prefs.getInt("savedRoute", AudioManager.ROUTE_SPEAKER), AudioManager.ROUTE_ALL); }else { audioManager.setSpeakerphoneOn(prefs.getBoolean("savedSpeakerPhone", false)); } audioManager.setMode(prefs.getInt("savedMode", AudioManager.MODE_NORMAL)); Editor ed = prefs.edit(); ed.putBoolean("isSavedAudioState", false); ed.commit(); } /** * Reset the audio mode */ private synchronized void actualUnsetAudioInCall() { if(!prefs.getBoolean("isSavedAudioState", false) || !isSetAudioMode) { return; } Log.d(THIS_FILE, "Unset Audio In call"); int inCallStream = Compatibility.getInCallStream(); if(bluetoothWrapper != null) { //This fixes the BT activation but... but... seems to introduce a lot of other issues //bluetoothWrapper.setBluetoothOn(true); Log.d(THIS_FILE, "Unset bt"); bluetoothWrapper.setBluetoothOn(false); } audioManager.setMicrophoneMute(false); if(doFocusAudio) { audioManager.setStreamSolo(inCallStream, false); audioFocusWrapper.unFocus(); } restoreAudioState(); if(wifiLock != null && wifiLock.isHeld()) { wifiLock.release(); } if(screenLock != null && screenLock.isHeld()) { Log.d(THIS_FILE, "Release screen lock"); screenLock.release(); } if(cpuLock != null && cpuLock.isHeld()) { cpuLock.release(); } isSetAudioMode = false; } /** * Start ringing announce for a given contact. * It will also focus audio for us. * @param remoteContact the contact to ring for. May resolve the contact ringtone if any. */ synchronized public void startRing(String remoteContact) { saveAudioState(); audioFocusWrapper.focus(); if(!ringer.isRinging()) { ringer.ring(remoteContact, service.getPrefs().getRingtone()); }else { Log.d(THIS_FILE, "Already ringing ...."); } } /** * Stop all ringing. <br/> * Warning, this will not unfocus audio. */ synchronized public void stopRing() { if(ringer.isRinging()) { ringer.stopRing(); } } /** * Stop call announcement. */ public void stopRingAndUnfocus() { stopRing(); audioFocusWrapper.unFocus(); } public void resetSettings() { userWantBluetooth = service.getPrefs().getPreferenceBooleanValue(SipConfigManager.AUTO_CONNECT_BLUETOOTH); userWantMicrophoneMute = false; userWantSpeaker = false; } public void toggleMute() throws SameThreadException { setMicrophoneMute(!userWantMicrophoneMute); } public void setMicrophoneMute(boolean on) { if(on != userWantMicrophoneMute ) { userWantMicrophoneMute = on; setSoftwareVolume(); broadcastMediaChanged(); } } public void setSpeakerphoneOn(boolean on) throws SameThreadException { if(service != null) { service.setNoSnd(); userWantSpeaker = on; service.setSnd(); } broadcastMediaChanged(); } public void setBluetoothOn(boolean on) throws SameThreadException { Log.d(THIS_FILE, "Set BT "+on); if(service != null) { service.setNoSnd(); userWantBluetooth = on; service.setSnd(); } broadcastMediaChanged(); } public MediaState getMediaState() { MediaState mediaState = new MediaState(); // Micro mediaState.isMicrophoneMute = userWantMicrophoneMute; mediaState.canMicrophoneMute = true; /*&& !mediaState.isBluetoothScoOn*/ //Compatibility.isCompatible(5); // Speaker mediaState.isSpeakerphoneOn = userWantSpeaker; mediaState.canSpeakerphoneOn = true && !mediaState.isBluetoothScoOn; //Compatibility.isCompatible(5); //Bluetooth if(bluetoothWrapper != null) { mediaState.isBluetoothScoOn = bluetoothWrapper.isBluetoothOn(); mediaState.canBluetoothSco = bluetoothWrapper.canBluetooth(); }else { mediaState.isBluetoothScoOn = false; mediaState.canBluetoothSco = false; } return mediaState; } /** * Change the audio volume amplification according to the fact we are using bluetooth */ public void setSoftwareVolume(){ if(service != null) { final boolean useBT = (bluetoothWrapper != null && bluetoothWrapper.isBluetoothOn()); String speaker_key = useBT ? SipConfigManager.SND_BT_SPEAKER_LEVEL : SipConfigManager.SND_SPEAKER_LEVEL; String mic_key = useBT ? SipConfigManager.SND_BT_MIC_LEVEL : SipConfigManager.SND_MIC_LEVEL; final float speakVolume = service.getPrefs().getPreferenceFloatValue(speaker_key); final float micVolume = userWantMicrophoneMute? 0 : service.getPrefs().getPreferenceFloatValue(mic_key); service.getExecutor().execute(new SipRunnable() { @Override protected void doRun() throws SameThreadException { service.confAdjustTxLevel(speakVolume); service.confAdjustRxLevel(micVolume); // Force the BT mode to normal if(useBT) { audioManager.setMode(AudioManager.MODE_NORMAL); } } }); } } public void broadcastMediaChanged() { service.sendBroadcast(mediaStateChangedIntent); } private static final String ACTION_AUDIO_VOLUME_UPDATE = "org.openintents.audio.action_volume_update"; private static final String EXTRA_STREAM_TYPE = "org.openintents.audio.extra_stream_type"; private static final String EXTRA_VOLUME_INDEX = "org.openintents.audio.extra_volume_index"; private static final String EXTRA_RINGER_MODE = "org.openintents.audio.extra_ringer_mode"; private static final int EXTRA_VALUE_UNKNOWN = -9999; private void broadcastVolumeWillBeUpdated(int streamType, int index) { Intent notificationIntent = new Intent(ACTION_AUDIO_VOLUME_UPDATE); notificationIntent.putExtra(EXTRA_STREAM_TYPE, streamType); notificationIntent.putExtra(EXTRA_VOLUME_INDEX, index); notificationIntent.putExtra(EXTRA_RINGER_MODE, EXTRA_VALUE_UNKNOWN); service.sendBroadcast(notificationIntent, null); } public void setStreamVolume(int streamType, int index, int flags) { broadcastVolumeWillBeUpdated(streamType, index); audioManager.setStreamVolume(streamType, index, flags); } public void adjustStreamVolume(int streamType, int direction, int flags) { broadcastVolumeWillBeUpdated(streamType, EXTRA_VALUE_UNKNOWN); audioManager.adjustStreamVolume(streamType, direction, flags); if(streamType == AudioManager.STREAM_RING) { // Update ringer ringer.updateRingerMode(); } int inCallStream = Compatibility.getInCallStream(); if(streamType == inCallStream) { int maxLevel = audioManager.getStreamMaxVolume(inCallStream); float modifiedLevel = (audioManager.getStreamVolume(inCallStream)/(float) maxLevel)*10.0f; // Update default stream level service.getPrefs().setPreferenceFloatValue(SipConfigManager.SND_STREAM_LEVEL, modifiedLevel); } } // Public accessor public boolean isUserWantMicrophoneMute() { return userWantMicrophoneMute; } }
true
true
private synchronized void actualSetAudioInCall() { //Ensure not already set if(isSetAudioMode) { return; } stopRing(); saveAudioState(); //Set the rest of the phone in a better state to not interferate with current call audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON); audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF); audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); //LOCKS //Wifi management if necessary ContentResolver ctntResolver = service.getContentResolver(); Settings.System.putInt(ctntResolver, Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER); //Acquire wifi lock WifiManager wman = (WifiManager) service.getSystemService(Context.WIFI_SERVICE); if(wifiLock == null) { wifiLock = wman.createWifiLock( (Compatibility.isCompatible(9)) ? 3 : WifiManager.WIFI_MODE_FULL, "com.csipsimple.InCallLock"); wifiLock.setReferenceCounted(false); } WifiInfo winfo = wman.getConnectionInfo(); if(winfo != null) { DetailedState dstate = WifiInfo.getDetailedStateOf(winfo.getSupplicantState()); //We assume that if obtaining ip addr, we are almost connected so can keep wifi lock if(dstate == DetailedState.OBTAINING_IPADDR || dstate == DetailedState.CONNECTED) { if(!wifiLock.isHeld()) { wifiLock.acquire(); } } //This wake lock purpose is to prevent PSP wifi mode if(service.getPrefs().getPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL)) { if(screenLock == null) { PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE); screenLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "com.csipsimple.onIncomingCall.SCREEN"); screenLock.setReferenceCounted(false); } //Ensure single lock if(!screenLock.isHeld()) { screenLock.acquire(); } } } if(cpuLock == null) { PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE); cpuLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.onIncomingCall.CPU"); cpuLock.setReferenceCounted(false); } if(!cpuLock.isHeld()) { cpuLock.acquire(); } if(!useWebRTCImpl) { //Audio routing int targetMode = getAudioTargetMode(); Log.d(THIS_FILE, "Set mode audio in call to "+targetMode); if(service.getPrefs().generateForSetCall()) { ToneGenerator toneGenerator = new ToneGenerator( AudioManager.STREAM_VOICE_CALL, 1); toneGenerator.startTone(41 /*ToneGenerator.TONE_CDMA_CONFIRM*/); toneGenerator.stopTone(); toneGenerator.release(); } //Set mode if(targetMode != AudioManager.MODE_IN_CALL && useSgsWrkAround) { //For galaxy S we need to set in call mode before to reset stack audioManager.setMode(AudioManager.MODE_IN_CALL); } audioManager.setMode(targetMode); //Routing if(service.getPrefs().useRoutingApi()) { audioManager.setRouting(targetMode, userWantSpeaker?AudioManager.ROUTE_SPEAKER:AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL); }else { audioManager.setSpeakerphoneOn(userWantSpeaker ? true : false); } audioManager.setMicrophoneMute(false); if(bluetoothWrapper != null && userWantBluetooth && bluetoothWrapper.canBluetooth()) { Log.d(THIS_FILE, "Try to enable bluetooth"); bluetoothWrapper.setBluetoothOn(true); } }else { //WebRTC implementation for routing int apiLevel = Compatibility.getApiLevel(); //SetAudioMode // ***IMPORTANT*** When the API level for honeycomb (H) has been // decided, // the condition should be changed to include API level 8 to H-1. if ( android.os.Build.BRAND.equalsIgnoreCase("Samsung") && (8 == apiLevel)) { // Set Samsung specific VoIP mode for 2.2 devices int mode = 4; audioManager.setMode(mode); if (audioManager.getMode() != mode) { Log.e(THIS_FILE, "Could not set audio mode for Samsung device"); } } //SetPlayoutSpeaker if ((3 == apiLevel) || (4 == apiLevel)) { // 1.5 and 1.6 devices if (userWantSpeaker) { // route audio to back speaker audioManager.setMode(AudioManager.MODE_NORMAL); } else { // route audio to earpiece audioManager.setMode(AudioManager.MODE_IN_CALL); } } else { // 2.x devices if ((android.os.Build.BRAND.equalsIgnoreCase("samsung")) && ((5 == apiLevel) || (6 == apiLevel) || (7 == apiLevel))) { // Samsung 2.0, 2.0.1 and 2.1 devices if (userWantSpeaker) { // route audio to back speaker audioManager.setMode(AudioManager.MODE_IN_CALL); audioManager.setSpeakerphoneOn(userWantSpeaker); } else { // route audio to earpiece audioManager.setSpeakerphoneOn(userWantSpeaker); audioManager.setMode(AudioManager.MODE_NORMAL); } } else { // Non-Samsung and Samsung 2.2 and up devices audioManager.setSpeakerphoneOn(userWantSpeaker); } } } //Set stream solo/volume/focus int inCallStream = Compatibility.getInCallStream(); if(doFocusAudio) { if(!accessibilityManager.isEnabled()) { audioManager.setStreamSolo(inCallStream, true); } audioFocusWrapper.focus(); } Log.d(THIS_FILE, "Initial volume level : " + service.getPrefs().getInitialVolumeLevel()); setStreamVolume(inCallStream, (int) (audioManager.getStreamMaxVolume(inCallStream) * service.getPrefs().getInitialVolumeLevel()), 0); isSetAudioMode = true; // System.gc(); }
private synchronized void actualSetAudioInCall() { //Ensure not already set if(isSetAudioMode) { return; } stopRing(); saveAudioState(); // Set the rest of the phone in a better state to not interferate with current call // Do that only if we were not already in silent mode if(audioManager.getRingerMode() != AudioManager.RINGER_MODE_SILENT) { audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON); audioManager.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF); audioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); } //LOCKS //Wifi management if necessary ContentResolver ctntResolver = service.getContentResolver(); Settings.System.putInt(ctntResolver, Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_NEVER); //Acquire wifi lock WifiManager wman = (WifiManager) service.getSystemService(Context.WIFI_SERVICE); if(wifiLock == null) { wifiLock = wman.createWifiLock( (Compatibility.isCompatible(9)) ? 3 : WifiManager.WIFI_MODE_FULL, "com.csipsimple.InCallLock"); wifiLock.setReferenceCounted(false); } WifiInfo winfo = wman.getConnectionInfo(); if(winfo != null) { DetailedState dstate = WifiInfo.getDetailedStateOf(winfo.getSupplicantState()); //We assume that if obtaining ip addr, we are almost connected so can keep wifi lock if(dstate == DetailedState.OBTAINING_IPADDR || dstate == DetailedState.CONNECTED) { if(!wifiLock.isHeld()) { wifiLock.acquire(); } } //This wake lock purpose is to prevent PSP wifi mode if(service.getPrefs().getPreferenceBooleanValue(SipConfigManager.KEEP_AWAKE_IN_CALL)) { if(screenLock == null) { PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE); screenLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "com.csipsimple.onIncomingCall.SCREEN"); screenLock.setReferenceCounted(false); } //Ensure single lock if(!screenLock.isHeld()) { screenLock.acquire(); } } } if(cpuLock == null) { PowerManager pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE); cpuLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "com.csipsimple.onIncomingCall.CPU"); cpuLock.setReferenceCounted(false); } if(!cpuLock.isHeld()) { cpuLock.acquire(); } if(!useWebRTCImpl) { //Audio routing int targetMode = getAudioTargetMode(); Log.d(THIS_FILE, "Set mode audio in call to "+targetMode); if(service.getPrefs().generateForSetCall()) { ToneGenerator toneGenerator = new ToneGenerator( AudioManager.STREAM_VOICE_CALL, 1); toneGenerator.startTone(41 /*ToneGenerator.TONE_CDMA_CONFIRM*/); toneGenerator.stopTone(); toneGenerator.release(); } //Set mode if(targetMode != AudioManager.MODE_IN_CALL && useSgsWrkAround) { //For galaxy S we need to set in call mode before to reset stack audioManager.setMode(AudioManager.MODE_IN_CALL); } audioManager.setMode(targetMode); //Routing if(service.getPrefs().useRoutingApi()) { audioManager.setRouting(targetMode, userWantSpeaker?AudioManager.ROUTE_SPEAKER:AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL); }else { audioManager.setSpeakerphoneOn(userWantSpeaker ? true : false); } audioManager.setMicrophoneMute(false); if(bluetoothWrapper != null && userWantBluetooth && bluetoothWrapper.canBluetooth()) { Log.d(THIS_FILE, "Try to enable bluetooth"); bluetoothWrapper.setBluetoothOn(true); } }else { //WebRTC implementation for routing int apiLevel = Compatibility.getApiLevel(); //SetAudioMode // ***IMPORTANT*** When the API level for honeycomb (H) has been // decided, // the condition should be changed to include API level 8 to H-1. if ( android.os.Build.BRAND.equalsIgnoreCase("Samsung") && (8 == apiLevel)) { // Set Samsung specific VoIP mode for 2.2 devices int mode = 4; audioManager.setMode(mode); if (audioManager.getMode() != mode) { Log.e(THIS_FILE, "Could not set audio mode for Samsung device"); } } //SetPlayoutSpeaker if ((3 == apiLevel) || (4 == apiLevel)) { // 1.5 and 1.6 devices if (userWantSpeaker) { // route audio to back speaker audioManager.setMode(AudioManager.MODE_NORMAL); } else { // route audio to earpiece audioManager.setMode(AudioManager.MODE_IN_CALL); } } else { // 2.x devices if ((android.os.Build.BRAND.equalsIgnoreCase("samsung")) && ((5 == apiLevel) || (6 == apiLevel) || (7 == apiLevel))) { // Samsung 2.0, 2.0.1 and 2.1 devices if (userWantSpeaker) { // route audio to back speaker audioManager.setMode(AudioManager.MODE_IN_CALL); audioManager.setSpeakerphoneOn(userWantSpeaker); } else { // route audio to earpiece audioManager.setSpeakerphoneOn(userWantSpeaker); audioManager.setMode(AudioManager.MODE_NORMAL); } } else { // Non-Samsung and Samsung 2.2 and up devices audioManager.setSpeakerphoneOn(userWantSpeaker); } } } //Set stream solo/volume/focus int inCallStream = Compatibility.getInCallStream(); if(doFocusAudio) { if(!accessibilityManager.isEnabled()) { audioManager.setStreamSolo(inCallStream, true); } audioFocusWrapper.focus(); } Log.d(THIS_FILE, "Initial volume level : " + service.getPrefs().getInitialVolumeLevel()); setStreamVolume(inCallStream, (int) (audioManager.getStreamMaxVolume(inCallStream) * service.getPrefs().getInitialVolumeLevel()), 0); isSetAudioMode = true; // System.gc(); }
diff --git a/RichClient/src/main/java/com/tihiy/rclint/implement/ControlPanel.java b/RichClient/src/main/java/com/tihiy/rclint/implement/ControlPanel.java index bcbda53..9be7ccd 100644 --- a/RichClient/src/main/java/com/tihiy/rclint/implement/ControlPanel.java +++ b/RichClient/src/main/java/com/tihiy/rclint/implement/ControlPanel.java @@ -1,207 +1,207 @@ package com.tihiy.rclint.implement; import com.tihiy.rclint.control.Controller; import com.tihiy.rclint.mvcAbstract.AbstractViewPanel; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.io.File; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; public class ControlPanel extends AbstractViewPanel { private final Controller mc; private File defaultPath; private File sourceFile; public ControlPanel(Controller mc) { this.mc = mc; setBorder(BorderFactory.createLineBorder(Color.BLUE)); setLayout(new GridBagLayout()); initComponent(); } private void initComponent(){ butChooseSignal = new JButton("Choose Signal"); butChooseFirstLayerSignal = new JButton("First Layer Signal"); butChooseBaseSignal = new JButton("Base signal"); butCalculate = new JButton("Calculate"); butDefault = new JButton("Default signal"); mainSizeA = new JTextField(); mainSizeB = new JTextField(); mainXShift = new JTextField(); mainYShift = new JTextField(); mainRSphere = new JTextField(); mainH = new JTextField(); firstSizeA = new JTextField(); firstSizeB = new JTextField(); butChooseSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { sourceFile = chooseFile(); mc.addSignal("sourceSignal", sourceFile); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }); butChooseFirstLayerSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { mc.addSignal("targetSignal", chooseFile()); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }); butChooseBaseSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { mc.addSignal("baseSignal", chooseFile()); } catch (IOException e1) { - e1.printStackTrace(); //hange body of catch statement use File | Settings | File Templates. + e1.printStackTrace(); // body of catch statement use File | Settings | File Templates. } } }); butCalculate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double[] main = {Double.valueOf(mainSizeA.getText()), Double.valueOf(mainSizeB.getText()), Double.valueOf(mainXShift.getText()), Double.valueOf(mainYShift.getText()), Double.valueOf(mainRSphere.getText()), Double.valueOf(mainH.getText())}; double[] first = {Double.valueOf(firstSizeA.getText()), Double.valueOf(firstSizeB.getText())}; File radiusFile = new File(defaultPath, "radius"+ getDate()+sourceFile.getName()); mc.calculate(main, first, radiusFile, null); } }); butDefault.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sourceFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\P1.txt"); File roFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\Ro.txt"); File baseFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\PB1.txt"); try { mc.addSignal("sourceSignal", sourceFile); mc.addSignal("targetSignal", roFile); mc.addSignal("baseSignal", baseFile); } catch (IOException e1) { e1.printStackTrace(); } double[] main = {0.04,0.02,0,0.037,0.045,0.019}; double[] first = {0.06, 0.03}; defaultPath = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716"); File radiusFile = new File(defaultPath, "radius"+getDate()+sourceFile.getName()); mc.calculate(main, first, radiusFile, getComment(roFile, baseFile, main, first)); } }); GridBagConstraints constraints = new GridBagConstraints(0,0, 1,1, 0,0, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(5,5,5,5), 0,0); add(butChooseSignal, constraints); constraints.gridy = 1; add(butChooseFirstLayerSignal, constraints); constraints.gridy = 2; add(butChooseBaseSignal, constraints); constraints.gridy = 3; add(butCalculate, constraints); constraints.gridy = 4; add(butDefault); constraints.gridy = 5; constraints.gridx = 0; constraints.insets = new Insets(0,5,0,5); add(new Label("Size A(main)"), constraints); constraints.gridx = 1; add(mainSizeA, constraints); constraints.gridy = 6; constraints.gridx = 0; add(new Label("Size B(main)"), constraints); constraints.gridx = 1; add(mainSizeB, constraints); constraints.gridy = 7; constraints.gridx = 0; add(new Label("Shift X(main)"), constraints); constraints.gridx = 1; add(mainXShift, constraints); constraints.gridy = 8; constraints.gridx = 0; add(new Label("Shift Y(main)"), constraints); constraints.gridx = 1; add(mainYShift, constraints); constraints.gridy = 9; constraints.gridx = 0; add(new Label("R sphere(main)"), constraints); constraints.gridx = 1; add(mainRSphere, constraints); constraints.gridy = 10; constraints.gridx = 0; add(new Label("H (main)"), constraints); constraints.gridx = 1; add(mainH, constraints); constraints.gridy = 11; constraints.gridx = 0; add(new Label("Size A(FL)"), constraints); constraints.gridx = 1; add(firstSizeA, constraints); constraints.gridy = 12; constraints.gridx = 0; add(new Label("Size B(FL)"), constraints); constraints.gridx = 1; add(firstSizeB, constraints); } @Override public void modelPropertyChange(PropertyChangeEvent evt) { } private JButton butChooseSignal; private JButton butChooseFirstLayerSignal; private JButton butChooseBaseSignal; private JButton butCalculate; private JButton butDefault; private JTextField mainSizeA; private JTextField mainSizeB; private JTextField mainXShift; private JTextField mainYShift; private JTextField mainRSphere; private JTextField mainH; private JTextField firstSizeA; private JTextField firstSizeB; private File chooseFile(){ JFileChooser fileChooser = new JFileChooser(); fileChooser.changeToParentDirectory(); fileChooser.setCurrentDirectory(new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716")); // defaultPath = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716"); if(defaultPath!=null){ fileChooser.setCurrentDirectory( defaultPath); } fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); fileChooser.showDialog(new JFrame(), "Choose signal!"); if(defaultPath==null){ defaultPath = fileChooser.getCurrentDirectory(); } return fileChooser.getSelectedFile(); } private static String getDate(){ Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat ("_yyyy_MM_dd_hh_mm_ss"); return ft.format(dNow); } private String getComment(File roFile, File baseFile, double[] main, double[] first){ String comment = "Pulse="+sourceFile.getName()+" Ro="+roFile.getName()+" Base="+baseFile.getName()+" "; comment += "pulseES:"; for(double d:main){ comment += " "+d; } comment += " baseES" + first[0]+" "+first[1]+" "; return comment; } }
true
true
private void initComponent(){ butChooseSignal = new JButton("Choose Signal"); butChooseFirstLayerSignal = new JButton("First Layer Signal"); butChooseBaseSignal = new JButton("Base signal"); butCalculate = new JButton("Calculate"); butDefault = new JButton("Default signal"); mainSizeA = new JTextField(); mainSizeB = new JTextField(); mainXShift = new JTextField(); mainYShift = new JTextField(); mainRSphere = new JTextField(); mainH = new JTextField(); firstSizeA = new JTextField(); firstSizeB = new JTextField(); butChooseSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { sourceFile = chooseFile(); mc.addSignal("sourceSignal", sourceFile); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }); butChooseFirstLayerSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { mc.addSignal("targetSignal", chooseFile()); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }); butChooseBaseSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { mc.addSignal("baseSignal", chooseFile()); } catch (IOException e1) { e1.printStackTrace(); //hange body of catch statement use File | Settings | File Templates. } } }); butCalculate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double[] main = {Double.valueOf(mainSizeA.getText()), Double.valueOf(mainSizeB.getText()), Double.valueOf(mainXShift.getText()), Double.valueOf(mainYShift.getText()), Double.valueOf(mainRSphere.getText()), Double.valueOf(mainH.getText())}; double[] first = {Double.valueOf(firstSizeA.getText()), Double.valueOf(firstSizeB.getText())}; File radiusFile = new File(defaultPath, "radius"+ getDate()+sourceFile.getName()); mc.calculate(main, first, radiusFile, null); } }); butDefault.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sourceFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\P1.txt"); File roFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\Ro.txt"); File baseFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\PB1.txt"); try { mc.addSignal("sourceSignal", sourceFile); mc.addSignal("targetSignal", roFile); mc.addSignal("baseSignal", baseFile); } catch (IOException e1) { e1.printStackTrace(); } double[] main = {0.04,0.02,0,0.037,0.045,0.019}; double[] first = {0.06, 0.03}; defaultPath = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716"); File radiusFile = new File(defaultPath, "radius"+getDate()+sourceFile.getName()); mc.calculate(main, first, radiusFile, getComment(roFile, baseFile, main, first)); } }); GridBagConstraints constraints = new GridBagConstraints(0,0, 1,1, 0,0, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(5,5,5,5), 0,0); add(butChooseSignal, constraints); constraints.gridy = 1; add(butChooseFirstLayerSignal, constraints); constraints.gridy = 2; add(butChooseBaseSignal, constraints); constraints.gridy = 3; add(butCalculate, constraints); constraints.gridy = 4; add(butDefault); constraints.gridy = 5; constraints.gridx = 0; constraints.insets = new Insets(0,5,0,5); add(new Label("Size A(main)"), constraints); constraints.gridx = 1; add(mainSizeA, constraints); constraints.gridy = 6; constraints.gridx = 0; add(new Label("Size B(main)"), constraints); constraints.gridx = 1; add(mainSizeB, constraints); constraints.gridy = 7; constraints.gridx = 0; add(new Label("Shift X(main)"), constraints); constraints.gridx = 1; add(mainXShift, constraints); constraints.gridy = 8; constraints.gridx = 0; add(new Label("Shift Y(main)"), constraints); constraints.gridx = 1; add(mainYShift, constraints); constraints.gridy = 9; constraints.gridx = 0; add(new Label("R sphere(main)"), constraints); constraints.gridx = 1; add(mainRSphere, constraints); constraints.gridy = 10; constraints.gridx = 0; add(new Label("H (main)"), constraints); constraints.gridx = 1; add(mainH, constraints); constraints.gridy = 11; constraints.gridx = 0; add(new Label("Size A(FL)"), constraints); constraints.gridx = 1; add(firstSizeA, constraints); constraints.gridy = 12; constraints.gridx = 0; add(new Label("Size B(FL)"), constraints); constraints.gridx = 1; add(firstSizeB, constraints); }
private void initComponent(){ butChooseSignal = new JButton("Choose Signal"); butChooseFirstLayerSignal = new JButton("First Layer Signal"); butChooseBaseSignal = new JButton("Base signal"); butCalculate = new JButton("Calculate"); butDefault = new JButton("Default signal"); mainSizeA = new JTextField(); mainSizeB = new JTextField(); mainXShift = new JTextField(); mainYShift = new JTextField(); mainRSphere = new JTextField(); mainH = new JTextField(); firstSizeA = new JTextField(); firstSizeB = new JTextField(); butChooseSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { sourceFile = chooseFile(); mc.addSignal("sourceSignal", sourceFile); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }); butChooseFirstLayerSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { mc.addSignal("targetSignal", chooseFile()); } catch (IOException e1) { e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }); butChooseBaseSignal.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { mc.addSignal("baseSignal", chooseFile()); } catch (IOException e1) { e1.printStackTrace(); // body of catch statement use File | Settings | File Templates. } } }); butCalculate.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { double[] main = {Double.valueOf(mainSizeA.getText()), Double.valueOf(mainSizeB.getText()), Double.valueOf(mainXShift.getText()), Double.valueOf(mainYShift.getText()), Double.valueOf(mainRSphere.getText()), Double.valueOf(mainH.getText())}; double[] first = {Double.valueOf(firstSizeA.getText()), Double.valueOf(firstSizeB.getText())}; File radiusFile = new File(defaultPath, "radius"+ getDate()+sourceFile.getName()); mc.calculate(main, first, radiusFile, null); } }); butDefault.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sourceFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\P1.txt"); File roFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\Ro.txt"); File baseFile = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716\\PB1.txt"); try { mc.addSignal("sourceSignal", sourceFile); mc.addSignal("targetSignal", roFile); mc.addSignal("baseSignal", baseFile); } catch (IOException e1) { e1.printStackTrace(); } double[] main = {0.04,0.02,0,0.037,0.045,0.019}; double[] first = {0.06, 0.03}; defaultPath = new File("C:\\Users\\Home\\Documents\\My Box Files\\Asp\\RoChange\\Rad 20130716"); File radiusFile = new File(defaultPath, "radius"+getDate()+sourceFile.getName()); mc.calculate(main, first, radiusFile, getComment(roFile, baseFile, main, first)); } }); GridBagConstraints constraints = new GridBagConstraints(0,0, 1,1, 0,0, GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(5,5,5,5), 0,0); add(butChooseSignal, constraints); constraints.gridy = 1; add(butChooseFirstLayerSignal, constraints); constraints.gridy = 2; add(butChooseBaseSignal, constraints); constraints.gridy = 3; add(butCalculate, constraints); constraints.gridy = 4; add(butDefault); constraints.gridy = 5; constraints.gridx = 0; constraints.insets = new Insets(0,5,0,5); add(new Label("Size A(main)"), constraints); constraints.gridx = 1; add(mainSizeA, constraints); constraints.gridy = 6; constraints.gridx = 0; add(new Label("Size B(main)"), constraints); constraints.gridx = 1; add(mainSizeB, constraints); constraints.gridy = 7; constraints.gridx = 0; add(new Label("Shift X(main)"), constraints); constraints.gridx = 1; add(mainXShift, constraints); constraints.gridy = 8; constraints.gridx = 0; add(new Label("Shift Y(main)"), constraints); constraints.gridx = 1; add(mainYShift, constraints); constraints.gridy = 9; constraints.gridx = 0; add(new Label("R sphere(main)"), constraints); constraints.gridx = 1; add(mainRSphere, constraints); constraints.gridy = 10; constraints.gridx = 0; add(new Label("H (main)"), constraints); constraints.gridx = 1; add(mainH, constraints); constraints.gridy = 11; constraints.gridx = 0; add(new Label("Size A(FL)"), constraints); constraints.gridx = 1; add(firstSizeA, constraints); constraints.gridy = 12; constraints.gridx = 0; add(new Label("Size B(FL)"), constraints); constraints.gridx = 1; add(firstSizeB, constraints); }
diff --git a/src/main/java/me/eccentric_nz/TARDIS/travel/TARDISArea.java b/src/main/java/me/eccentric_nz/TARDIS/travel/TARDISArea.java index 21c01467b..dc1b02ddd 100644 --- a/src/main/java/me/eccentric_nz/TARDIS/travel/TARDISArea.java +++ b/src/main/java/me/eccentric_nz/TARDIS/travel/TARDISArea.java @@ -1,202 +1,202 @@ /* * Copyright (C) 2013 eccentric_nz * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package me.eccentric_nz.TARDIS.travel; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import me.eccentric_nz.TARDIS.TARDIS; import me.eccentric_nz.TARDIS.database.ResultSetAreas; import me.eccentric_nz.TARDIS.database.ResultSetSave; import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; import org.bukkit.permissions.PermissionAttachmentInfo; /** * The control or console room of the Doctor's TARDIS is the space in which the * operation of the craft is usually effected. It is dominated by a large, * hexagonal console, typically in or near the middle of the room. * * @author eccentric_nz */ public class TARDISArea { private TARDIS plugin; public TARDISArea(TARDIS plugin) { this.plugin = plugin; } /** * Checks if a location is contained within any TARDIS area. * * @param l a location object to check. */ public boolean areaCheckInExisting(Location l) { boolean chk = true; String w = l.getWorld().getName(); HashMap<String, Object> where = new HashMap<String, Object>(); where.put("world", w); ResultSetAreas rsa = new ResultSetAreas(plugin, where, true); if (rsa.resultSet()) { ArrayList<HashMap<String, String>> data = rsa.getData(); for (HashMap<String, String> map : data) { int minx = plugin.utils.parseNum(map.get("minx")); int minz = plugin.utils.parseNum(map.get("minz")); int maxx = plugin.utils.parseNum(map.get("maxx")); int maxz = plugin.utils.parseNum(map.get("maxz")); // is clicked block within a defined TARDIS area? if (l.getX() <= maxx && l.getZ() <= maxz && l.getX() >= minx && l.getZ() >= minz) { chk = false; break; } } } return chk; } /** * Checks if a location is contained within a specific TARDIS area. * * @param a the TARDIS area to check in. * @param l a location object to check. */ public boolean areaCheckInExile(String a, Location l) { boolean chk = true; HashMap<String, Object> where = new HashMap<String, Object>(); where.put("area_name", a); ResultSetAreas rsa = new ResultSetAreas(plugin, where, false); if (rsa.resultSet()) { String w = rsa.getWorld(); String lw = l.getWorld().getName(); int minx = rsa.getMinx(); int minz = rsa.getMinz(); int maxx = rsa.getMaxx(); int maxz = rsa.getMaxz(); // is clicked block within a defined TARDIS area? if (w.equals(lw) && (l.getX() <= maxx && l.getZ() <= maxz && l.getX() >= minx && l.getZ() >= minz)) { chk = false; } } return chk; } /** * Checks if a player has permission to travel to a TARDIS area. * * @param p a player to check. * @param l a location object to check. */ public boolean areaCheckLocPlayer(Player p, Location l) { boolean chk = false; String w = l.getWorld().getName(); HashMap<String, Object> where = new HashMap<String, Object>(); where.put("world", w); ResultSetAreas rsa = new ResultSetAreas(plugin, where, true); int i = 1; if (rsa.resultSet()) { ArrayList<HashMap<String, String>> data = rsa.getData(); for (HashMap<String, String> map : data) { String n = map.get("area_name"); int minx = plugin.utils.parseNum(map.get("minx")); int minz = plugin.utils.parseNum(map.get("minz")); int maxx = plugin.utils.parseNum(map.get("maxx")); int maxz = plugin.utils.parseNum(map.get("maxz")); // is time travel destination within a defined TARDIS area? if (l.getX() <= maxx && l.getZ() <= maxz && l.getX() >= minx && l.getZ() >= minz) { // does the player have permmission to travel here if (!p.hasPermission("tardis.area." + n) || !p.isPermissionSet("tardis.area." + n)) { plugin.trackPerm.put(p.getName(), "tardis.area." + n); chk = true; break; } } i++; } } return chk; } /** * Gets the next available parking spot in a specified TARDIS area. * * @param a the TARDIS area to look in. */ public Location getNextSpot(String a) { Location location = null; // find the next available slot in this area HashMap<String, Object> where = new HashMap<String, Object>(); where.put("area_name", a); ResultSetAreas rsa = new ResultSetAreas(plugin, where, false); if (rsa.resultSet()) { int minx = rsa.getMinx(); int x = minx + 2; int minz = rsa.getMinz(); int z = minz + 2; int maxx = rsa.getMaxx(); int maxz = rsa.getMaxz(); String wStr = rsa.getWorld(); boolean chk = false; while (chk == false) { String queryLoc = wStr + ":" + x + ":%:" + z; ResultSetSave rs = new ResultSetSave(plugin, queryLoc); if (rs.resultSet()) { - if (x <= maxx) { + if (x + 5 <= maxx) { x += 5; } else { x = minx + 2; - if (z <= maxz) { + if (z + 5 <= maxz) { z += 5; } else { z = minz + 2; } } } else { chk = true; break; } } if (chk == true) { World w = plugin.getServer().getWorld(wStr); int y = rsa.getY(); if (y == 0) { y = w.getHighestBlockYAt(x, z); } location = w.getBlockAt(x, y, z).getLocation(); } } return location; } /** * Gets the TARDIS area a player is exiled to. * * @param p a player to check. */ public String getExileArea(Player p) { Set<PermissionAttachmentInfo> perms = p.getEffectivePermissions(); String area = ""; for (PermissionAttachmentInfo pai : perms) { if (pai.getPermission().contains("tardis.area")) { int len = pai.getPermission().length(); area = pai.getPermission().substring(12, len); } } return area; } }
false
true
public Location getNextSpot(String a) { Location location = null; // find the next available slot in this area HashMap<String, Object> where = new HashMap<String, Object>(); where.put("area_name", a); ResultSetAreas rsa = new ResultSetAreas(plugin, where, false); if (rsa.resultSet()) { int minx = rsa.getMinx(); int x = minx + 2; int minz = rsa.getMinz(); int z = minz + 2; int maxx = rsa.getMaxx(); int maxz = rsa.getMaxz(); String wStr = rsa.getWorld(); boolean chk = false; while (chk == false) { String queryLoc = wStr + ":" + x + ":%:" + z; ResultSetSave rs = new ResultSetSave(plugin, queryLoc); if (rs.resultSet()) { if (x <= maxx) { x += 5; } else { x = minx + 2; if (z <= maxz) { z += 5; } else { z = minz + 2; } } } else { chk = true; break; } } if (chk == true) { World w = plugin.getServer().getWorld(wStr); int y = rsa.getY(); if (y == 0) { y = w.getHighestBlockYAt(x, z); } location = w.getBlockAt(x, y, z).getLocation(); } } return location; }
public Location getNextSpot(String a) { Location location = null; // find the next available slot in this area HashMap<String, Object> where = new HashMap<String, Object>(); where.put("area_name", a); ResultSetAreas rsa = new ResultSetAreas(plugin, where, false); if (rsa.resultSet()) { int minx = rsa.getMinx(); int x = minx + 2; int minz = rsa.getMinz(); int z = minz + 2; int maxx = rsa.getMaxx(); int maxz = rsa.getMaxz(); String wStr = rsa.getWorld(); boolean chk = false; while (chk == false) { String queryLoc = wStr + ":" + x + ":%:" + z; ResultSetSave rs = new ResultSetSave(plugin, queryLoc); if (rs.resultSet()) { if (x + 5 <= maxx) { x += 5; } else { x = minx + 2; if (z + 5 <= maxz) { z += 5; } else { z = minz + 2; } } } else { chk = true; break; } } if (chk == true) { World w = plugin.getServer().getWorld(wStr); int y = rsa.getY(); if (y == 0) { y = w.getHighestBlockYAt(x, z); } location = w.getBlockAt(x, y, z).getLocation(); } } return location; }
diff --git a/src/di/kdd/buildmon/protocol/DistributedSystem.java b/src/di/kdd/buildmon/protocol/DistributedSystem.java index 72a8304..cc09738 100644 --- a/src/di/kdd/buildmon/protocol/DistributedSystem.java +++ b/src/di/kdd/buildmon/protocol/DistributedSystem.java @@ -1,100 +1,100 @@ package di.kdd.buildmon.protocol; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.Date; import android.app.Activity; import android.os.AsyncTask; import android.util.Log; import di.kdd.buildmon.MainActivity; import di.kdd.buildmon.protocol.exceptions.NotCaptainException; public class DistributedSystem extends AsyncTask<Void, Void, Boolean> implements IProtocol { private MainActivity view; private DistributedSystemNode node; private static final String TAG = "distributed system"; public DistributedSystem(MainActivity view) { this.view = view; } public void connect() { this.execute(); } /*** * Sends Knock-Knock messages to the first 255 local IP addresses and * according to if it will get a response or not, the node becomes * a peer or a Captain respectively. */ @Override protected Boolean doInBackground(Void... arg0) { Socket socket; String ipPrefix = "192.168.1."; //TODO FIXME android.os.Debug.waitForDebugger(); /* Look for the Captain in the first 255 local IP addresses */ //TODO parallelize it - for(int i = 1; i < 2; ++i) { + for(int i = 1; i < 256; ++i) { try{ Log.d(TAG, "Trying to connect to :" + ipPrefix + Integer.toString(i)); socket = new Socket(ipPrefix + Integer.toString(i), IProtocol.KNOCK_KNOCK_PORT); } catch(IOException e) { continue; } /* Captain found */ node = new PeerNode(socket); return true; } /* No response, I am the first node of the distributed system and the Captain */ node = new CaptainNode(); return false; } @Override protected void onPostExecute(Boolean becamePeer) { if(becamePeer) { view.showMessage("Connected as Peer"); } else { view.showMessage("Connected as Captain"); } } @Override public void computeBuildingSignature(Date from, Date to) throws NotCaptainException, IOException { if(node.isCaptain() == false) { throw new NotCaptainException(); } ((CaptainNode) node).computeBuildingSignature(from, to); } @Override public boolean isCaptain() { return node.isCaptain(); } @Override public String getCaptainIP() { return node.getCaptainIP(); } @Override public void end() { node.end(); } }
true
true
protected Boolean doInBackground(Void... arg0) { Socket socket; String ipPrefix = "192.168.1."; //TODO FIXME android.os.Debug.waitForDebugger(); /* Look for the Captain in the first 255 local IP addresses */ //TODO parallelize it for(int i = 1; i < 2; ++i) { try{ Log.d(TAG, "Trying to connect to :" + ipPrefix + Integer.toString(i)); socket = new Socket(ipPrefix + Integer.toString(i), IProtocol.KNOCK_KNOCK_PORT); } catch(IOException e) { continue; } /* Captain found */ node = new PeerNode(socket); return true; } /* No response, I am the first node of the distributed system and the Captain */ node = new CaptainNode(); return false; }
protected Boolean doInBackground(Void... arg0) { Socket socket; String ipPrefix = "192.168.1."; //TODO FIXME android.os.Debug.waitForDebugger(); /* Look for the Captain in the first 255 local IP addresses */ //TODO parallelize it for(int i = 1; i < 256; ++i) { try{ Log.d(TAG, "Trying to connect to :" + ipPrefix + Integer.toString(i)); socket = new Socket(ipPrefix + Integer.toString(i), IProtocol.KNOCK_KNOCK_PORT); } catch(IOException e) { continue; } /* Captain found */ node = new PeerNode(socket); return true; } /* No response, I am the first node of the distributed system and the Captain */ node = new CaptainNode(); return false; }
diff --git a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/utils/TreeUtils.java b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/utils/TreeUtils.java index 4f1c7ac4..66ef79ab 100644 --- a/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/utils/TreeUtils.java +++ b/software/ncitbrowser/src/java/gov/nih/nci/evs/browser/utils/TreeUtils.java @@ -1,2335 +1,2335 @@ package gov.nih.nci.evs.browser.utils; import java.util.*; import org.LexGrid.LexBIG.DataModel.Collections.*; import org.LexGrid.LexBIG.DataModel.Core.*; import org.LexGrid.LexBIG.Exceptions.*; import org.LexGrid.LexBIG.Extensions.Generic.*; import org.LexGrid.LexBIG.Extensions.Generic.LexBIGServiceConvenienceMethods.*; import org.LexGrid.LexBIG.LexBIGService.*; import org.LexGrid.LexBIG.Utility.*; import org.LexGrid.codingSchemes.*; import org.LexGrid.commonTypes.*; import org.LexGrid.naming.*; import org.LexGrid.concepts.*; import org.LexGrid.LexBIG.LexBIGService.CodedNodeSet.*; import org.apache.log4j.*; /** * Copyright: (c) 2004-2009 Mayo Foundation for Medical Education and * Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the * triple-shield Mayo logo are trademarks and service marks of MFMER. * * Except as contained in the copyright notice above, or as used to identify * MFMER as the author of this software, the trade names, trademarks, service * marks, or product names of the copyright holder shall not be used in * advertising, promotion or otherwise in connection with this software without * prior written authorization of the copyright holder. * * Licensed under the Eclipse Public License, Version 1.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * */ /** * <!-- LICENSE_TEXT_START --> * Copyright 2008,2009 NGIT. This software was developed in conjunction * with the National Cancer Institute, and so to the extent government * employees are co-authors, any rights in such works shall be subject * to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the disclaimer of Article 3, * below. Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * 2. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by NGIT and the National * Cancer Institute." If no such end-user documentation is to be * included, this acknowledgment shall appear in the software itself, * wherever such third-party acknowledgments normally appear. * 3. The names "The National Cancer Institute", "NCI" and "NGIT" must * not be used to endorse or promote products derived from this software. * 4. This license does not authorize the incorporation of this software * into any third party proprietary programs. This license does not * authorize the recipient to use any trademarks owned by either NCI * or NGIT * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED * WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE * DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, * NGIT, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * <!-- LICENSE_TEXT_END --> */ /** * @author EVS Team * @version 1.0 * * Note: This class is created based on Mayo's BuildTreForCode.java sample code * * Modification history * Initial modification [email protected] * */ /** * Attempts to provide a tree, based on a focus code, that includes the * following information: * * <pre> * - All paths from the hierarchy root to one or more focus codes. * - Immediate children of every node in path to root * - Indicator to show whether any unexpanded node can be further expanded * </pre> * * This example accepts two parameters... The first parameter is required, and * must contain at least one code in a comma-delimited list. A tree is produced * for each code. Time to produce the tree for each code is printed in * milliseconds. In order to factor out costs of startup and shutdown, resolving * multiple codes may offer a better overall estimate performance. * * The second parameter is optional, and can indicate a hierarchy ID to navigate * when resolving child nodes. If not provided, "is_a" is assumed. */ public class TreeUtils { private static Logger _logger = Logger.getLogger(TreeUtils.class); //static LocalNameList _noopList = Constructors.createLocalNameList("_noop_"); private static LocalNameList _noopList = new LocalNameList(); public TreeUtils() { } public HashMap getTreePathData(String scheme, String version, String hierarchyID, String code) throws LBException { return getTreePathData(scheme, version, hierarchyID, code, -1); } public HashMap getTreePathData(String scheme, String version, String hierarchyID, String code, int maxLevel) throws LBException { LexBIGService lbsvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbsvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbsvc); if (hierarchyID == null) hierarchyID = "is_a"; CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); SupportedHierarchy hierarchyDefn = getSupportedHierarchy(lbsvc, scheme, csvt, hierarchyID); return getTreePathData(lbsvc, lbscm, scheme, csvt, hierarchyDefn, code, maxLevel); } public HashMap getTreePathData(LexBIGService lbsvc, LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, SupportedHierarchy hierarchyDefn, String focusCode) throws LBException { return getTreePathData(lbsvc, lbscm, scheme, csvt, hierarchyDefn, focusCode, -1); } public HashMap getTreePathData(LexBIGService lbsvc, LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, SupportedHierarchy hierarchyDefn, String focusCode, int maxLevel) throws LBException { HashMap hmap = new HashMap(); TreeItem ti = new TreeItem("<Root>", "Root node"); long ms = System.currentTimeMillis(); int pathsResolved = 0; try { // Resolve 'is_a' hierarchy info. This example will // need to make some calls outside of what is covered // by existing convenience methods, but we use the // registered hierarchy to prevent need to hard code // relationship and direction info used on lookup ... String hierarchyID = hierarchyDefn.getLocalId(); String[] associationsToNavigate = hierarchyDefn.getAssociationNames(); boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable(); // Identify the set of all codes on path from root // to the focus code ... Map<String, EntityDescription> codesToDescriptions = new HashMap<String, EntityDescription>(); AssociationList pathsFromRoot = getPathsFromRoot(lbsvc, lbscm, scheme, csvt, hierarchyID, focusCode, codesToDescriptions, maxLevel); // Typically there will be one path, but handle multiple just in // case. Each path from root provides a 'backbone', from focus // code to root, for additional nodes to hang off of in our // printout. For every backbone node, one level of children is // printed, along with an indication of whether those nodes can // be expanded. for (Iterator<? extends Association> paths = pathsFromRoot.iterateAssociation(); paths.hasNext();) { addPathFromRoot(ti, lbsvc, lbscm, scheme, csvt, paths.next(), associationsToNavigate, associationsNavigatedFwd, codesToDescriptions); pathsResolved++; } } finally { _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms) + " to resolve " + pathsResolved + " paths from root."); } hmap.put(focusCode, ti); return hmap; } public void run(String scheme, String version, String hierarchyId, String focusCode) throws LBException { HashMap hmap = getTreePathData(scheme, version, hierarchyId, focusCode); Set keyset = hmap.keySet(); Object[] objs = keyset.toArray(); String code = (String) objs[0]; TreeItem ti = (TreeItem) hmap.get(code); printTree(ti, focusCode, 0); } public static void printTree(HashMap hmap) { if (hmap == null) { _logger.error("ERROR printTree -- hmap is null."); return; } Object[] objs = hmap.keySet().toArray(); String code = (String) objs[0]; TreeItem ti = (TreeItem) hmap.get(code); printTree(ti, code, 0); } protected void addPathFromRoot(TreeItem ti, LexBIGService lbsvc, LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, Association path, String[] associationsToNavigate, boolean associationsNavigatedFwd, Map<String, EntityDescription> codesToDescriptions) throws LBException { // First, add the branch point from the path ... ConceptReference branchRoot = path.getAssociationReference(); // =======================================================================v.50 String branchCode = branchRoot.getConceptCode(); String branchCodeDescription = codesToDescriptions.containsKey(branchCode) ? codesToDescriptions .get(branchCode).getContent() : getCodeDescription(lbsvc, scheme, csvt, branchCode); TreeItem branchPoint = new TreeItem(branchCode, branchCodeDescription); String branchNavText = getDirectionalLabel(lbscm, scheme, csvt, path, associationsNavigatedFwd); // Now process elements in the branch ... AssociatedConceptList concepts = path.getAssociatedConcepts(); for (int i = 0; i < concepts.getAssociatedConceptCount(); i++) { // Determine the next concept in the branch and // add a corresponding item to the tree. AssociatedConcept concept = concepts.getAssociatedConcept(i); String code = concept.getConceptCode(); TreeItem branchItem = new TreeItem(code, getCodeDescription(concept)); branchPoint.addChild(branchNavText, branchItem); // Recurse to process the remainder of the backbone ... AssociationList nextLevel = concept.getSourceOf(); if (nextLevel != null) { if (nextLevel.getAssociationCount() != 0) { // Add immediate children of the focus code with an // indication of sub-nodes (+). Codes already // processed as part of the path are ignored since // they are handled through recursion. addChildren(branchItem, lbsvc, lbscm, scheme, csvt, code, codesToDescriptions.keySet(), associationsToNavigate, associationsNavigatedFwd); // More levels left to process ... for (int j = 0; j < nextLevel.getAssociationCount(); j++) addPathFromRoot(branchPoint, lbsvc, lbscm, scheme, csvt, nextLevel.getAssociation(j), associationsToNavigate, associationsNavigatedFwd, codesToDescriptions); } else { // End of the line ... // Always add immediate children of the focus code, // in this case with no exclusions since we are moving // beyond the path to root and allowed to duplicate // nodes that may have occurred in the path to root. addChildren(branchItem, lbsvc, lbscm, scheme, csvt, code, Collections.EMPTY_SET, associationsToNavigate, associationsNavigatedFwd); } } else { // Add immediate children of the focus code with an // indication of sub-nodes (+). Codes already // processed as part of the path are ignored since // they are handled through recursion. addChildren(branchItem, lbsvc, lbscm, scheme, csvt, code, codesToDescriptions.keySet(), associationsToNavigate, associationsNavigatedFwd); } } // Add immediate children of the node being processed, // and indication of sub-nodes. addChildren(branchPoint, lbsvc, lbscm, scheme, csvt, branchCode, codesToDescriptions.keySet(), associationsToNavigate, associationsNavigatedFwd); // Add the populated tree item to those tracked from root. ti.addChild(branchNavText, branchPoint); } /** * Populate child nodes for a single branch of the tree, and indicates * whether further expansion (to grandchildren) is possible. */ protected void addChildren(TreeItem ti, LexBIGService lbsvc, LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, String branchRootCode, Set<String> codesToExclude, String[] associationsToNavigate, boolean associationsNavigatedFwd) throws LBException { // Resolve the next branch, representing children of the given // code, navigated according to the provided relationship and // direction. Resolve the children as a code graph, looking 2 // levels deep but leaving the final level unresolved. CodedNodeGraph cng = lbsvc.getNodeGraph(scheme, csvt, null); Boolean restrictToAnonymous = Boolean.FALSE; cng = cng.restrictToAnonymous(restrictToAnonymous); ConceptReference focus = Constructors.createConceptReference(branchRootCode, scheme); cng = cng.restrictToAssociations(Constructors .createNameAndValueList(associationsToNavigate), null); ResolvedConceptReferenceList branch = cng.resolveAsList(focus, associationsNavigatedFwd, // !associationsNavigatedFwd, -1, 2, noopList_, null, null, // null, -1, true); !associationsNavigatedFwd, -1, 2, _noopList, null, null, null, -1, false); // The resolved branch will be represented by the first node in // the resolved list. The node will be subdivided by source or // target associations (depending on direction). The associated // nodes define the children. for (Iterator<? extends ResolvedConceptReference> nodes = branch.iterateResolvedConceptReference(); nodes.hasNext();) { ResolvedConceptReference node = nodes.next(); AssociationList childAssociationList = associationsNavigatedFwd ? node.getSourceOf() : node .getTargetOf(); // KLO 091509 if (childAssociationList == null) return; // Process each association defining children ... for (Iterator<? extends Association> pathsToChildren = childAssociationList.iterateAssociation(); pathsToChildren .hasNext();) { Association child = pathsToChildren.next(); String childNavText = getDirectionalLabel(lbscm, scheme, csvt, child, associationsNavigatedFwd); // Each association may have multiple children ... AssociatedConceptList branchItemList = child.getAssociatedConcepts(); for (Iterator<? extends AssociatedConcept> branchNodes = branchItemList.iterateAssociatedConcept(); branchNodes .hasNext();) { AssociatedConcept branchItemNode = branchNodes.next(); String branchItemCode = branchItemNode.getConceptCode(); // Add here if not in the list of excluded codes. // This is also where we look to see if another level // was indicated to be available. If so, mark the // entry with a '+' to indicate it can be expanded. // if // (!branchItemNode.getReferencedEntry().getIsAnonymous()) { if (!branchItemCode.startsWith("@")) { if (!codesToExclude.contains(branchItemCode)) { TreeItem childItem = new TreeItem(branchItemCode, getCodeDescription(branchItemNode)); AssociationList grandchildBranch = associationsNavigatedFwd ? branchItemNode .getSourceOf() : branchItemNode .getTargetOf(); if (grandchildBranch != null) childItem._expandable = true; ti.addChild(childNavText, childItem); } } } } } } /** * Prints the given tree item, recursing through all branches. * * @param ti */ // protected void printTree(TreeItem ti, String focusCode, int depth) { public static void printTree(TreeItem ti, String focusCode, int depth) { StringBuffer indent = new StringBuffer(); for (int i = 0; i < depth * 2; i++) indent.append("| "); StringBuffer codeAndText = new StringBuffer(indent).append( focusCode.equals(ti._code) ? ">>>>" : "").append(ti._code) .append(':').append( ti._text.length() > 64 ? ti._text.substring(0, 62) + "..." : ti._text).append(ti._expandable ? " [+]" : ""); _logger.debug(codeAndText.toString()); indent.append("| "); for (String association : ti._assocToChildMap.keySet()) { _logger.debug(indent.toString() + association); List<TreeItem> children = ti._assocToChildMap.get(association); Collections.sort(children); for (TreeItem childItem : children) printTree(childItem, focusCode, depth + 1); } } // ///////////////////////////////////////////////////// // Helper Methods // ///////////////////////////////////////////////////// /** * Returns the entity description for the given code. */ protected static String getCodeDescription(LexBIGService lbsvc, String scheme, CodingSchemeVersionOrTag csvt, String code) throws LBException { CodedNodeSet cns = lbsvc.getCodingSchemeConcepts(scheme, csvt); cns = cns.restrictToCodes(Constructors.createConceptReferenceList(code, scheme)); ResolvedConceptReferenceList rcrl = null; try { rcrl = cns.resolveToList(null, _noopList, null, 1); } catch (Exception ex) { _logger .error("WARNING: TreeUtils getCodeDescription cns.resolveToList throws exceptions"); return "null"; } if (rcrl != null && rcrl.getResolvedConceptReferenceCount() > 0) { EntityDescription desc = rcrl.getResolvedConceptReference(0).getEntityDescription(); if (desc != null) return desc.getContent(); } return "<Not assigned>"; } /** * Returns the entity description for the given resolved concept reference. */ protected static String getCodeDescription(ResolvedConceptReference ref) throws LBException { EntityDescription desc = ref.getEntityDescription(); if (desc != null) return desc.getContent(); return "<Not assigned>"; } public static boolean isBlank(String str) { if ((str == null) || str.matches("^\\s*$")) { return true; } else { return false; } } /** * Returns the label to display for the given association and directional * indicator. */ protected static String getDirectionalLabel( LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, Association assoc, boolean navigatedFwd) throws LBException { String assocLabel = navigatedFwd ? lbscm.getAssociationForwardName(assoc .getAssociationName(), scheme, csvt) : lbscm .getAssociationReverseName(assoc.getAssociationName(), scheme, csvt); // if (StringUtils.isBlank(assocLabel)) if (isBlank(assocLabel)) assocLabel = (navigatedFwd ? "" : "[Inverse]") + assoc.getAssociationName(); return assocLabel; } /** * Resolves one or more paths from the hierarchy root to the given code * through a list of connected associations defined by the hierarchy. */ protected AssociationList getPathsFromRoot(LexBIGService lbsvc, LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, String hierarchyID, String focusCode, Map<String, EntityDescription> codesToDescriptions) throws LBException { return getPathsFromRoot(lbsvc, lbscm, scheme, csvt, hierarchyID, focusCode, codesToDescriptions, -1); } protected AssociationList getPathsFromRoot(LexBIGService lbsvc, LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, String hierarchyID, String focusCode, Map<String, EntityDescription> codesToDescriptions, int maxLevel) throws LBException { // Get paths from the focus code to the root from the // convenience method. All paths are resolved. If only // one path is required, it would be possible to use // HierarchyPathResolveOption.ONE to reduce processing // and improve overall performance. AssociationList pathToRoot = lbscm.getHierarchyPathToRoot(scheme, csvt, null, focusCode, false, HierarchyPathResolveOption.ALL, null); // But for purposes of this example we need to display info // in order coming from root direction. Process the paths to root // recursively to reverse the order for processing ... AssociationList pathFromRoot = new AssociationList(); for (int i = pathToRoot.getAssociationCount() - 1; i >= 0; i--) reverseAssoc(lbsvc, lbscm, scheme, csvt, pathToRoot .getAssociation(i), pathFromRoot, codesToDescriptions, maxLevel, 0); return pathFromRoot; } /** * Returns a description of the hierarchy defined by the given coding scheme * and matching the specified ID. */ protected static SupportedHierarchy getSupportedHierarchy( LexBIGService lbsvc, String scheme, CodingSchemeVersionOrTag csvt, String hierarchyID) throws LBException { CodingScheme cs = lbsvc.resolveCodingScheme(scheme, csvt); if (cs == null) { throw new LBResourceUnavailableException( "Coding scheme not found: " + scheme); } for (SupportedHierarchy h : cs.getMappings().getSupportedHierarchy()) if (h.getLocalId().equals(hierarchyID)) return h; throw new LBResourceUnavailableException("Hierarchy not defined: " + hierarchyID); } // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public boolean hasSubconcepts(String scheme, String version, String code) { HashMap hmap = getSubconcepts(scheme, version, code); if (hmap == null) return false; TreeItem item = (TreeItem) hmap.get(code); return item._expandable; } /* * public static HashMap getSubconcepts(String scheme, String version, * String code) { if (scheme.compareTo("NCI Thesaurus") == 0) { return * getAssociatedConcepts(scheme, version, code, "subClassOf", false); } * * else if (scheme.indexOf("MedDRA") != -1) { return * getAssociatedConcepts(scheme, version, code, "CHD", true); } * * CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if * (version != null) csvt.setVersion(version); * * try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); * LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) * lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); * lbscm.setLexBIGService(lbSvc); * * CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt); if (cs == * null) return null; Mappings mappings = cs.getMappings(); * SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); if * (hierarchies == null || hierarchies.length == 0) return null; * * SupportedHierarchy hierarchyDefn = hierarchies[0]; String hier_id = * hierarchyDefn.getLocalId(); * * String[] associationsToNavigate = hierarchyDefn.getAssociationNames(); * //String assocName = hier_id;//associationsToNavigate[0]; String * assocName = associationsToNavigate[0]; * * if (assocName.compareTo("part_of") == 0) assocName = "is_a"; * * boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable(); * * if (assocName.compareTo("PAR") == 0) associationsNavigatedFwd = false; * //if (assocName.compareTo("subClassOf") == 0) associationsNavigatedFwd = * false; //return getAssociatedConcepts(scheme, version, code, assocName, * associationsNavigatedFwd); return getAssociatedConcepts(lbSvc, lbscm, * scheme, version, code, assocName, associationsNavigatedFwd); } catch * (Exception ex) { return null; } } * * * public static HashMap getSuperconcepts(String scheme, String version, * String code) { if (scheme.compareTo("NCI Thesaurus") == 0) { return * getAssociatedConcepts(scheme, version, code, "subClassOf", true); } * * else if (scheme.indexOf("MedDRA") != -1) { return * getAssociatedConcepts(scheme, version, code, "CHD", false); } * * CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if * (version != null) csvt.setVersion(version); * * try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); * LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) * lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); * lbscm.setLexBIGService(lbSvc); * * CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt); if (cs == * null) return null; Mappings mappings = cs.getMappings(); * SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); if * (hierarchies == null || hierarchies.length == 0) return null; * * SupportedHierarchy hierarchyDefn = hierarchies[0]; String[] * associationsToNavigate = hierarchyDefn.getAssociationNames(); //String * assocName = hier_id;//associationsToNavigate[0]; String assocName = * associationsToNavigate[0]; * * if (assocName.compareTo("part_of") == 0) assocName = "is_a"; * * boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable(); * * if (assocName.compareTo("PAR") == 0) associationsNavigatedFwd = false; * * return getAssociatedConcepts(scheme, version, code, assocName, * !associationsNavigatedFwd); } catch (Exception ex) { return null; } } */ public static HashMap getSubconcepts(String scheme, String version, String code) { if (scheme.compareTo("NCI Thesaurus") == 0) { return getAssociatedConcepts(scheme, version, code, "subClassOf", false); } CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt); if (cs == null) return null; Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); if (hierarchies == null || hierarchies.length == 0) return null; SupportedHierarchy hierarchyDefn = hierarchies[0]; String hier_id = hierarchyDefn.getLocalId(); String[] associationsToNavigate = hierarchyDefn.getAssociationNames(); // for (int i=0; i<associationsToNavigate.length; i++) { // _logger.debug("(*) associationsToNavigate: " + // associationsToNavigate[i]); // } // String assocName = hier_id;//associationsToNavigate[0]; // String assocName = associationsToNavigate[0]; // if (assocName.compareTo("part_of") == 0) assocName = "is_a"; boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable(); if (associationsToNavigate != null && associationsToNavigate.length == 1) { if (associationsToNavigate[0].compareTo("subClassOf") == 0) { return getAssociatedConcepts(scheme, version, code, "subClassOf", false); } } // if (assocName.compareTo("PAR") == 0) associationsNavigatedFwd = // false; // if (assocName.compareTo("subClassOf") == 0) // associationsNavigatedFwd = false; // return getAssociatedConcepts(scheme, version, code, assocName, // associationsNavigatedFwd); // return getAssociatedConcepts(lbSvc, lbscm, scheme, version, code, // assocName, associationsNavigatedFwd); return getAssociatedConcepts(lbSvc, lbscm, scheme, version, code, associationsToNavigate, associationsNavigatedFwd); } catch (Exception ex) { return null; } } public static HashMap getSuperconcepts(String scheme, String version, String code) { /* * if (scheme.compareTo("NCI Thesaurus") == 0) { return * getAssociatedConcepts(scheme, version, code, "subClassOf", true); } */ /* * else if (scheme.indexOf("MedDRA") != -1) { return * getAssociatedConcepts(scheme, version, code, "CHD", false); } */ CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt); if (cs == null) return null; Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); if (hierarchies == null || hierarchies.length == 0) return null; SupportedHierarchy hierarchyDefn = hierarchies[0]; String[] associationsToNavigate = hierarchyDefn.getAssociationNames(); // String assocName = hier_id;//associationsToNavigate[0]; // String assocName = associationsToNavigate[0]; for (int i = 0; i < associationsToNavigate.length; i++) { _logger.debug("(*) associationsToNavigate: " + associationsToNavigate[i]); } // if (assocName.compareTo("part_of") == 0) assocName = "is_a"; boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable(); // if (assocName.compareTo("PAR") == 0) associationsNavigatedFwd = // false; // return getAssociatedConcepts(scheme, version, code, assocName, // !associationsNavigatedFwd); if (associationsToNavigate != null && associationsToNavigate.length == 1) { if (associationsToNavigate[0].compareTo("subClassOf") == 0) { return getAssociatedConcepts(scheme, version, code, "subClassOf", true); } } return getAssociatedConcepts(scheme, version, code, associationsToNavigate, !associationsNavigatedFwd); } catch (Exception ex) { return null; } } /* * public static HashMap getSuperconcepts(String scheme, String version, * String code) { CodingSchemeVersionOrTag csvt = new * CodingSchemeVersionOrTag(); if (version != null) * csvt.setVersion(version); * * try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); * LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) * lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); * lbscm.setLexBIGService(lbSvc); * * CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt); if (cs == * null) return null; Mappings mappings = cs.getMappings(); * SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); if * (hierarchies == null || hierarchies.length == 0) return null; * SupportedHierarchy hierarchyDefn = hierarchies[0]; String hier_id = * hierarchyDefn.getLocalId(); String[] associationsToNavigate = * hierarchyDefn.getAssociationNames(); String assocName = * associationsToNavigate[0]; boolean associationsNavigatedFwd = * hierarchyDefn.getIsForwardNavigable(); return * getAssociatedConcepts(scheme, version, code, assocName, * !associationsNavigatedFwd); } catch (Exception ex) { return null; } } */ protected static Association processForAnonomousNodes(Association assoc) { if (assoc == null) return null; // clone Association except associatedConcepts Association temp = new Association(); temp.setAssociatedData(assoc.getAssociatedData()); temp.setAssociationName(assoc.getAssociationName()); temp.setAssociationReference(assoc.getAssociationReference()); temp.setDirectionalName(assoc.getDirectionalName()); temp.setAssociatedConcepts(new AssociatedConceptList()); for (int i = 0; i < assoc.getAssociatedConcepts() .getAssociatedConceptCount(); i++) { // Conditionals to deal with anonymous nodes and UMLS top nodes // "V-X" // The first three allow UMLS traversal to top node. // The last two are specific to owl anonymous nodes which can act // like false // top nodes. /* * if(assoc.getAssociatedConcepts().getAssociatedConcept(i). * getReferencedEntry() != null) { * _logger.debug(assoc.getAssociatedConcepts * ().getAssociatedConcept(i) * .getReferencedEntry().getEntityDescription().getContent() + * " === IsAnonymous? " + * assoc.getAssociatedConcepts().getAssociatedConcept(i) * .getReferencedEntry().getIsAnonymous()); } else {_logger.debug( * "assoc.getAssociatedConcepts().getAssociatedConcept(i).getReferencedEntry() == null" * ); } */ /* * if (assoc.getAssociatedConcepts().getAssociatedConcept(i) * .getReferencedEntry() != null && * assoc.getAssociatedConcepts().getAssociatedConcept(i) * .getReferencedEntry().getIsAnonymous() != false) { // do nothing * (NCI Thesaurus) } */ if (assoc.getAssociatedConcepts().getAssociatedConcept(i) .getReferencedEntry() != null && assoc.getAssociatedConcepts().getAssociatedConcept(i) .getReferencedEntry().getIsAnonymous() != null && assoc.getAssociatedConcepts().getAssociatedConcept(i) .getReferencedEntry().getIsAnonymous() != false && !assoc.getAssociatedConcepts().getAssociatedConcept(i) .getConceptCode().equals("@") && !assoc.getAssociatedConcepts().getAssociatedConcept(i) .getConceptCode().equals("@@")) { // do nothing } else { temp.getAssociatedConcepts().addAssociatedConcept( assoc.getAssociatedConcepts().getAssociatedConcept(i)); } } return temp; } /* * public static HashMap getAssociatedConcepts(String scheme, String * version, String code, String assocName, boolean direction) { HashMap hmap * = new HashMap(); TreeItem ti = null; long ms = * System.currentTimeMillis(); * * Set<String> codesToExclude = Collections.EMPTY_SET; * * CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if * (version != null) csvt.setVersion(version); ResolvedConceptReferenceList * matches = null; Vector v = new Vector(); try { LexBIGService lbSvc = * RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods * lbscm = (LexBIGServiceConvenienceMethods) lbSvc * .getGenericExtension("LexBIGServiceConvenienceMethods"); * lbscm.setLexBIGService(lbSvc); * * String name = getCodeDescription(lbSvc, scheme, csvt, code); ti = new * TreeItem(code, name); ti.expandable = false; * * CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); * ConceptReference focus = Constructors.createConceptReference(code, * scheme); cng = cng.restrictToAssociations(Constructors * .createNameAndValueList(assocName), null); boolean * associationsNavigatedFwd = direction; * * // To remove anonymous classes (KLO, 091009), the resolveCodedEntryDepth * parameter cannot be set to -1. * * ResolvedConceptReferenceList branch = null; try { branch = * cng.resolveAsList(focus, associationsNavigatedFwd, * //!associationsNavigatedFwd, -1, 2, noopList_, null, null, null, -1, * true); !associationsNavigatedFwd, 1, 2, noopList_, null, null, null, -1, * false); * * } catch (Exception e) { * _logger.error("TreeUtils getAssociatedConcepts throws exceptions."); * return null; } * * for (Iterator<ResolvedConceptReference> nodes = branch * .iterateResolvedConceptReference(); nodes.hasNext();) { * ResolvedConceptReference node = nodes.next(); AssociationList * childAssociationList = null; * * //AssociationList childAssociationList = associationsNavigatedFwd ? * node.getSourceOf(): node.getTargetOf(); * * if (associationsNavigatedFwd) { childAssociationList = * node.getSourceOf(); } else { childAssociationList = node.getTargetOf(); } * * if (childAssociationList != null) { // Process each association defining * children ... for (Iterator<Association> pathsToChildren = * childAssociationList .iterateAssociation(); pathsToChildren.hasNext();) { * Association child = pathsToChildren.next(); //KLO 091009 remove anonymous * nodes * * child = processForAnonomousNodes(child); * * * String childNavText = getDirectionalLabel(lbscm, scheme, csvt, child, * associationsNavigatedFwd); * * // Each association may have multiple children ... AssociatedConceptList * branchItemList = child .getAssociatedConcepts(); * * * * List child_list = new ArrayList(); for (Iterator<AssociatedConcept> * branchNodes = branchItemList .iterateAssociatedConcept(); * branchNodes.hasNext();) { AssociatedConcept branchItemNode = * branchNodes.next(); child_list.add(branchItemNode); } * * SortUtils.quickSort(child_list); * * for (int i = 0; i < child_list.size(); i++) { AssociatedConcept * branchItemNode = (AssociatedConcept) child_list .get(i); String * branchItemCode = branchItemNode.getConceptCode(); // Add here if not in * the list of excluded codes. // This is also where we look to see if * another level // was indicated to be available. If so, mark the // entry * with a '+' to indicate it can be expanded. if * (!codesToExclude.contains(branchItemCode)) { TreeItem childItem = new * TreeItem(branchItemCode, getCodeDescription(branchItemNode)); * ti.expandable = true; AssociationList grandchildBranch = * associationsNavigatedFwd ? branchItemNode .getSourceOf() : * branchItemNode.getTargetOf(); if (grandchildBranch != null) * childItem.expandable = true; ti.addChild(childNavText, childItem); } } } * } else { _logger.warn("WARNING: childAssociationList == null."); } } * hmap.put(code, ti); } catch (Exception ex) { ex.printStackTrace(); } * _logger.debug("Run time (milliseconds) getSubconcepts: " + * (System.currentTimeMillis() - ms) + " to resolve "); return hmap; } */ public static HashMap getAssociatedConcepts(String scheme, String version, String code, String assocName, boolean direction) { try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); return getAssociatedConcepts(lbSvc, lbscm, scheme, version, code, assocName, direction); } catch (Exception ex) { return null; } } public static HashMap getAssociatedConcepts(LexBIGService lbSvc, LexBIGServiceConvenienceMethods lbscm, String scheme, String version, String code, String assocName, boolean direction) { HashMap hmap = new HashMap(); TreeItem ti = null; long ms = System.currentTimeMillis(); Set<String> codesToExclude = Collections.EMPTY_SET; CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { Entity concept = getConceptByCode(scheme, version, null, code); if (concept == null) return null; String entityCodeNamespace = concept.getEntityCodeNamespace(); //System.out.println("getEntityCodeNamespace returns: " + concept.getEntityCodeNamespace()); ConceptReference focus = ConvenienceMethods.createConceptReference(code, scheme); focus.setCodingSchemeName(entityCodeNamespace); String name = concept.getEntityDescription().getContent();//getCodeDescription(lbSvc, scheme, csvt, code); //String name = getCodeDescription(lbSvc, scheme, csvt, code); ti = new TreeItem(code, name); ti._expandable = false; CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); Boolean restrictToAnonymous = Boolean.FALSE; cng = cng.restrictToAnonymous(restrictToAnonymous); //ConceptReference focus = // Constructors.createConceptReference(code, scheme); cng = cng.restrictToAssociations(Constructors .createNameAndValueList(assocName), null); boolean associationsNavigatedFwd = direction; // To remove anonymous classes (KLO, 091009), the // resolveCodedEntryDepth parameter cannot be set to -1. // Alternative -- use code to determine whether the class is // anonymous ResolvedConceptReferenceList branch = null; try { branch = cng.resolveAsList(focus, associationsNavigatedFwd, // !associationsNavigatedFwd, 1, 2, noopList_, null, // null, null, -1, false); !associationsNavigatedFwd, -1, 2, _noopList, null, null, null, -1, false); } catch (Exception e) { _logger .error("TreeUtils getAssociatedConcepts throws exceptions."); return null; } for (Iterator<? extends ResolvedConceptReference> nodes = branch.iterateResolvedConceptReference(); nodes.hasNext();) { ResolvedConceptReference node = nodes.next(); AssociationList childAssociationList = null; // AssociationList childAssociationList = // associationsNavigatedFwd ? node.getSourceOf(): // node.getTargetOf(); if (associationsNavigatedFwd) { childAssociationList = node.getSourceOf(); } else { childAssociationList = node.getTargetOf(); } if (childAssociationList != null) { // Process each association defining children ... for (Iterator<? extends Association> pathsToChildren = childAssociationList.iterateAssociation(); pathsToChildren .hasNext();) { Association child = pathsToChildren.next(); // KLO 091009 remove anonymous nodes child = processForAnonomousNodes(child); String childNavText = getDirectionalLabel(lbscm, scheme, csvt, child, associationsNavigatedFwd); // Each association may have multiple children ... AssociatedConceptList branchItemList = child.getAssociatedConcepts(); /* * for (Iterator<AssociatedConcept> branchNodes = * branchItemList.iterateAssociatedConcept(); * branchNodes .hasNext();) { AssociatedConcept * branchItemNode = branchNodes.next(); */ List child_list = new ArrayList(); for (Iterator<? extends AssociatedConcept> branchNodes = branchItemList.iterateAssociatedConcept(); branchNodes .hasNext();) { AssociatedConcept branchItemNode = branchNodes.next(); child_list.add(branchItemNode); } SortUtils.quickSort(child_list); for (int i = 0; i < child_list.size(); i++) { AssociatedConcept branchItemNode = (AssociatedConcept) child_list.get(i); String branchItemCode = branchItemNode.getConceptCode(); if (!branchItemCode.startsWith("@")) { // Add here if not in the list of excluded // codes. // This is also where we look to see if another // level // was indicated to be available. If so, mark // the // entry with a '+' to indicate it can be // expanded. if (!codesToExclude.contains(branchItemCode)) { TreeItem childItem = new TreeItem(branchItemCode, getCodeDescription(branchItemNode)); ti._expandable = true; AssociationList grandchildBranch = associationsNavigatedFwd ? branchItemNode .getSourceOf() : branchItemNode.getTargetOf(); if (grandchildBranch != null) childItem._expandable = true; ti.addChild(childNavText, childItem); } } } } } else { _logger.warn("WARNING: childAssociationList == null."); } } hmap.put(code, ti); } catch (Exception ex) { ex.printStackTrace(); } _logger.debug("Run time (milliseconds) getSubconcepts: " + (System.currentTimeMillis() - ms) + " to resolve "); return hmap; } public static HashMap getAssociatedConcepts(String scheme, String version, String code, String[] assocNames, boolean direction) { try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); return getAssociatedConcepts(lbSvc, lbscm, scheme, version, code, assocNames, direction); } catch (Exception ex) { return null; } } public static HashMap getAssociatedConcepts(LexBIGService lbSvc, LexBIGServiceConvenienceMethods lbscm, String scheme, String version, String code, String[] assocNames, boolean direction) { HashMap hmap = new HashMap(); TreeItem ti = null; long ms = System.currentTimeMillis(); Set<String> codesToExclude = Collections.EMPTY_SET; CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { Entity concept = getConceptByCode(scheme, version, null, code); if (concept == null) return null; String entityCodeNamespace = concept.getEntityCodeNamespace(); //System.out.println("getEntityCodeNamespace returns: " + concept.getEntityCodeNamespace()); ConceptReference focus = ConvenienceMethods.createConceptReference(code, scheme); focus.setCodingSchemeName(entityCodeNamespace); String name = concept.getEntityDescription().getContent();//getCodeDescription(lbSvc, scheme, csvt, code); //String name = getCodeDescription(lbSvc, scheme, csvt, code); ti = new TreeItem(code, name); ti._expandable = false; CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); Boolean restrictToAnonymous = Boolean.FALSE; cng = cng.restrictToAnonymous(restrictToAnonymous); //ConceptReference focus = // Constructors.createConceptReference(code, scheme); cng = cng.restrictToAssociations(Constructors .createNameAndValueList(assocNames), null); boolean associationsNavigatedFwd = direction; // To remove anonymous classes (KLO, 091009), the // resolveCodedEntryDepth parameter cannot be set to -1. // Alternative -- use code to determine whether the class is // anonymous ResolvedConceptReferenceList branch = null; try { branch = cng.resolveAsList(focus, associationsNavigatedFwd, // !associationsNavigatedFwd, 1, 2, noopList_, null, // null, null, -1, false); !associationsNavigatedFwd, -1, 2, _noopList, null, null, null, -1, false); } catch (Exception e) { _logger .error("TreeUtils getAssociatedConcepts throws exceptions."); return null; } for (Iterator<? extends ResolvedConceptReference> nodes = branch.iterateResolvedConceptReference(); nodes.hasNext();) { ResolvedConceptReference node = nodes.next(); AssociationList childAssociationList = null; // AssociationList childAssociationList = // associationsNavigatedFwd ? node.getSourceOf(): // node.getTargetOf(); if (associationsNavigatedFwd) { childAssociationList = node.getSourceOf(); } else { childAssociationList = node.getTargetOf(); } if (childAssociationList != null) { // Process each association defining children ... for (Iterator<? extends Association> pathsToChildren = childAssociationList.iterateAssociation(); pathsToChildren .hasNext();) { Association child = pathsToChildren.next(); // KLO 091009 remove anonymous nodes - child = processForAnonomousNodes(child); + //child = processForAnonomousNodes(child); String childNavText = getDirectionalLabel(lbscm, scheme, csvt, child, associationsNavigatedFwd); // Each association may have multiple children ... AssociatedConceptList branchItemList = child.getAssociatedConcepts(); /* * for (Iterator<AssociatedConcept> branchNodes = * branchItemList.iterateAssociatedConcept(); * branchNodes .hasNext();) { AssociatedConcept * branchItemNode = branchNodes.next(); */ List child_list = new ArrayList(); for (Iterator<? extends AssociatedConcept> branchNodes = branchItemList.iterateAssociatedConcept(); branchNodes .hasNext();) { AssociatedConcept branchItemNode = branchNodes.next(); child_list.add(branchItemNode); } SortUtils.quickSort(child_list); for (int i = 0; i < child_list.size(); i++) { AssociatedConcept branchItemNode = (AssociatedConcept) child_list.get(i); String branchItemCode = branchItemNode.getConceptCode(); if (!branchItemCode.startsWith("@")) { // Add here if not in the list of excluded // codes. // This is also where we look to see if another // level // was indicated to be available. If so, mark // the // entry with a '+' to indicate it can be // expanded. if (!codesToExclude.contains(branchItemCode)) { TreeItem childItem = new TreeItem(branchItemCode, getCodeDescription(branchItemNode)); ti._expandable = true; AssociationList grandchildBranch = associationsNavigatedFwd ? branchItemNode .getSourceOf() : branchItemNode.getTargetOf(); if (grandchildBranch != null) childItem._expandable = true; ti.addChild(childNavText, childItem); } } } } } else { _logger.warn("WARNING: childAssociationList == null."); } } hmap.put(code, ti); } catch (Exception ex) { ex.printStackTrace(); } _logger.debug("Run time (milliseconds) getSubconcepts: " + (System.currentTimeMillis() - ms) + " to resolve "); return hmap; } public HashMap getAssociationSources(String scheme, String version, String code, String assocName) { return getAssociatedConcepts(scheme, version, code, assocName, false); } public HashMap getAssociationTargets(String scheme, String version, String code, String assocName) { return getAssociatedConcepts(scheme, version, code, assocName, true); } // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Configurable tree size (MAXIMUM_TREE_LEVEL) // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static ConceptReferenceList createConceptReferenceList( String[] codes, String codingSchemeName) { if (codes == null) { return null; } ConceptReferenceList list = new ConceptReferenceList(); for (int i = 0; i < codes.length; i++) { ConceptReference cr = new ConceptReference(); cr.setCodingSchemeName(codingSchemeName); cr.setConceptCode(codes[i]); list.addConceptReference(cr); } return list; } public static Entity getConceptByCode(String codingSchemeName, String vers, String ltag, String code) { try { LexBIGService lbSvc = new RemoteServerUtil().createLexBIGService(); if (lbSvc == null) { _logger.warn("lbSvc == null???"); return null; } CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(vers); ConceptReferenceList crefs = createConceptReferenceList(new String[] { code }, codingSchemeName); CodedNodeSet cns = null; try { cns = lbSvc.getCodingSchemeConcepts(codingSchemeName, versionOrTag); } catch (Exception e1) { e1.printStackTrace(); } cns = cns.restrictToCodes(crefs); ResolvedConceptReferenceList matches = cns.resolveToList(null, null, null, 1); if (matches == null) { _logger.warn("Concept not found."); return null; } // Analyze the result ... if (matches.getResolvedConceptReferenceCount() > 0) { ResolvedConceptReference ref = (ResolvedConceptReference) matches .enumerateResolvedConceptReference().nextElement(); Entity entry = ref.getReferencedEntry(); return entry; } } catch (Exception e) { e.printStackTrace(); return null; } return null; } public static NameAndValueList createNameAndValueList(String[] names, String[] values) { NameAndValueList nvList = new NameAndValueList(); for (int i = 0; i < names.length; i++) { NameAndValue nv = new NameAndValue(); nv.setName(names[i]); if (values != null) { nv.setContent(values[i]); } nvList.addNameAndValue(nv); } return nvList; } protected AssociationList reverseAssoc(LexBIGService lbsvc, LexBIGServiceConvenienceMethods lbscm, String scheme, CodingSchemeVersionOrTag csvt, Association assoc, AssociationList addTo, Map<String, EntityDescription> codeToEntityDescriptionMap, int maxLevel, int currLevel) throws LBException { if (maxLevel != -1 && currLevel >= maxLevel) return addTo; ConceptReference acRef = assoc.getAssociationReference(); AssociatedConcept acFromRef = new AssociatedConcept(); // ===============================================================================v5.0 acFromRef.setConceptCode(acRef.getConceptCode()); AssociationList acSources = new AssociationList(); acFromRef.setIsNavigable(Boolean.TRUE); acFromRef.setSourceOf(acSources); // Use cached description if available (should be cached // for all but original root) ... if (codeToEntityDescriptionMap.containsKey(acRef.getConceptCode())) acFromRef.setEntityDescription(codeToEntityDescriptionMap.get(acRef .getConceptCode())); // Otherwise retrieve on demand ... else acFromRef.setEntityDescription(Constructors .createEntityDescription(getCodeDescription(lbsvc, scheme, csvt, acRef.getConceptCode()))); AssociatedConceptList acl = assoc.getAssociatedConcepts(); for (AssociatedConcept ac : acl.getAssociatedConcept()) { // Create reverse association (same non-directional name) Association rAssoc = new Association(); rAssoc.setAssociationName(assoc.getAssociationName()); // On reverse, old associated concept is new reference point. ConceptReference ref = new ConceptReference(); // ===============================================================================v5.0 // ref.setCodingSchemeName(ac.getCodingSchemeName()); ref.setConceptCode(ac.getConceptCode()); rAssoc.setAssociationReference(ref); // And old reference is new associated concept. AssociatedConceptList rAcl = new AssociatedConceptList(); rAcl.addAssociatedConcept(acFromRef); rAssoc.setAssociatedConcepts(rAcl); // Set reverse directional name, if available. String dirName = assoc.getDirectionalName(); if (dirName != null) try { rAssoc.setDirectionalName(lbscm.isForwardName(scheme, csvt, dirName) ? lbscm.getAssociationReverseName(assoc .getAssociationName(), scheme, csvt) : lbscm .getAssociationReverseName(assoc.getAssociationName(), scheme, csvt)); } catch (LBException e) { } // Save code desc for future reference when setting up // concept references in recursive calls ... codeToEntityDescriptionMap.put(ac.getConceptCode(), ac .getEntityDescription()); AssociationList sourceOf = ac.getSourceOf(); if (sourceOf != null) for (Association sourceAssoc : sourceOf.getAssociation()) { AssociationList pos = reverseAssoc(lbsvc, lbscm, scheme, csvt, sourceAssoc, addTo, codeToEntityDescriptionMap, maxLevel, currLevel + 1); pos.addAssociation(rAssoc); } else addTo.addAssociation(rAssoc); } return acSources; } public Vector getHierarchyAssociationId(String scheme, String version) { Vector association_vec = new Vector(); try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); // Will handle secured ontologies later. CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); versionOrTag.setVersion(version); CodingScheme cs = lbSvc.resolveCodingScheme(scheme, versionOrTag); Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); for (int k = 0; k < hierarchies.length; k++) { java.lang.String[] ids = hierarchies[k].getAssociationNames(); for (int i = 0; i < ids.length; i++) { if (!association_vec.contains(ids[i])) { association_vec.add(ids[i]); } } } } catch (Exception ex) { ex.printStackTrace(); } return association_vec; } public String getHierarchyAssociationId(String scheme, String version, int index) { try { Vector hierarchicalAssoName_vec = getHierarchyAssociationId(scheme, version); if (hierarchicalAssoName_vec != null && hierarchicalAssoName_vec.size() > 0) { String hierarchicalAssoName = (String) hierarchicalAssoName_vec.elementAt(0); return hierarchicalAssoName; } } catch (Exception ex) { ex.printStackTrace(); } return null; } public List getTopNodes(TreeItem ti) { List list = new ArrayList(); getTopNodes(ti, list, 0, 1); return list; } public void getTopNodes(TreeItem ti, List list, int currLevel, int maxLevel) { if (list == null) list = new ArrayList(); if (currLevel > maxLevel) return; if (ti._assocToChildMap.keySet().size() > 0) { if (ti._text.compareTo("Root node") != 0) { ResolvedConceptReference rcr = new ResolvedConceptReference(); rcr.setConceptCode(ti._code); EntityDescription entityDescription = new EntityDescription(); entityDescription.setContent(ti._text); rcr.setEntityDescription(entityDescription); // _logger.debug("Root: " + ti.text); list.add(rcr); } } for (String association : ti._assocToChildMap.keySet()) { List<TreeItem> children = ti._assocToChildMap.get(association); Collections.sort(children); for (TreeItem childItem : children) { getTopNodes(childItem, list, currLevel + 1, maxLevel); } } } public void dumpTree(HashMap hmap, String focusCode, int level) { try { Set keyset = hmap.keySet(); Object[] objs = keyset.toArray(); String code = (String) objs[0]; TreeItem ti = (TreeItem) hmap.get(code); for (String association : ti._assocToChildMap.keySet()) { _logger.debug("\nassociation: " + association); List<TreeItem> children = ti._assocToChildMap.get(association); for (TreeItem childItem : children) { _logger.debug(childItem._text + "(" + childItem._code + ")"); int knt = 0; if (childItem._expandable) { knt = 1; _logger.debug("\tnode.expandable"); printTree(childItem, focusCode, level); List list = getTopNodes(childItem); for (int i = 0; i < list.size(); i++) { Object obj = list.get(i); String nd_code = ""; String nd_name = ""; if (obj instanceof ResolvedConceptReference) { ResolvedConceptReference node = (ResolvedConceptReference) list.get(i); nd_code = node.getConceptCode(); nd_name = node.getEntityDescription().getContent(); } else if (obj instanceof Entity) { Entity node = (Entity) list.get(i); nd_code = node.getEntityCode(); nd_name = node.getEntityDescription().getContent(); } _logger.debug("TOP NODE: " + nd_name + " (" + nd_code + ")"); } } else { _logger.debug("\tnode.NOT expandable"); } } } } catch (Exception e) { } } // ==================================================================================================================== public static String[] getHierarchyIDs(String codingScheme, CodingSchemeVersionOrTag versionOrTag) throws LBException { String[] hier = null; Set<String> ids = new HashSet<String>(); SupportedHierarchy[] sh = null; try { sh = getSupportedHierarchies(codingScheme, versionOrTag); if (sh != null) { for (int i = 0; i < sh.length; i++) { ids.add(sh[i].getLocalId()); } // Cache and return the new value ... hier = ids.toArray(new String[ids.size()]); } } catch (Exception ex) { ex.printStackTrace(); } return hier; } protected static SupportedHierarchy[] getSupportedHierarchies( String codingScheme, CodingSchemeVersionOrTag versionOrTag) throws LBException { CodingScheme cs = null; try { cs = getCodingScheme(codingScheme, versionOrTag); } catch (Exception ex) { } if (cs == null) { throw new LBResourceUnavailableException( "Coding scheme not found -- " + codingScheme); } Mappings mappings = cs.getMappings(); return mappings.getSupportedHierarchy(); } protected static CodingScheme getCodingScheme(String codingScheme, CodingSchemeVersionOrTag versionOrTag) throws LBException { CodingScheme cs = null; try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); cs = lbSvc.resolveCodingScheme(codingScheme, versionOrTag); } catch (Exception ex) { ex.printStackTrace(); } return cs; } public static String getHierarchyID(String codingScheme, String version) { CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (version != null) versionOrTag.setVersion(version); try { String[] ids = getHierarchyIDs(codingScheme, versionOrTag); if (ids.length > 0) return ids[0]; } catch (Exception e) { } return null; } public static ResolvedConceptReferenceList getHierarchyRoots( String codingScheme, String version) { System.out.println("scheme: " + codingScheme); System.out.println("version: " + version); CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (version != null) versionOrTag.setVersion(version); try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); String hierarchyID = getHierarchyID(codingScheme, version); System.out.println("hierarchyID: " + hierarchyID); ResolvedConceptReferenceList rcrl = lbscm.getHierarchyRoots(codingScheme, versionOrTag, hierarchyID); if (rcrl == null) { System.out.println("lbscm.getHierarchyRoots: codingScheme " + codingScheme); System.out.println("lbscm.getHierarchyRoots: version " + version); System.out.println("lbscm.getHierarchyRoots returns NULL???"); } return rcrl; } catch (Exception ex) { ex.printStackTrace(); System.out.println("lbscm.getHierarchyRoots throws exception???"); return null; } } // //////////////////////////////////////////////////////////////////////////////////////////////////// public void traverseUp(LexBIGService lbsvc, LexBIGServiceConvenienceMethods lbscm, java.lang.String codingScheme, CodingSchemeVersionOrTag versionOrTag, java.lang.String hierarchyID, java.lang.String conceptCode, TreeItem root, TreeItem ti, Set<String> codesToExclude, String[] associationsToNavigate, boolean associationsNavigatedFwd, Set<String> visited_links, HashMap<String, TreeItem> visited_nodes, int maxLevel, int currLevel) { if (maxLevel != -1 && currLevel >= maxLevel) { root.addChild("CHD", ti); root._expandable = true; return; } boolean resolveConcepts = false; NameAndValueList associationQualifiers = null; try { AssociationList list = null; list = lbscm.getHierarchyLevelPrev(codingScheme, versionOrTag, hierarchyID, conceptCode, resolveConcepts, associationQualifiers); int parent_knt = 0; if (list != null && list.getAssociationCount() > 0) { Association[] associations = list.getAssociation(); for (int k = 0; k < associations.length; k++) { Association association = associations[k]; AssociatedConceptList acl = association.getAssociatedConcepts(); for (int i = 0; i < acl.getAssociatedConceptCount(); i++) { // child_knt = child_knt + // acl.getAssociatedConceptCount(); // Determine the next concept in the branch and // add a corresponding item to the tree. AssociatedConcept concept = acl.getAssociatedConcept(i); String parentCode = concept.getConceptCode(); String link = conceptCode + "|" + parentCode; if (!visited_links.contains(link)) { visited_links.add(link); // _logger.debug( getCodeDescription(concept) + "(" // + parentCode + ")"); TreeItem branchItem = null; if (visited_nodes.containsKey(parentCode)) { branchItem = (TreeItem) visited_nodes.get(parentCode); } else { branchItem = new TreeItem(parentCode, getCodeDescription(concept)); branchItem._expandable = false; visited_nodes.put(parentCode, branchItem); } try { codesToExclude.add(conceptCode); addChildren(branchItem, lbsvc, lbscm, codingScheme, versionOrTag, parentCode, codesToExclude, associationsToNavigate, associationsNavigatedFwd); } catch (Exception ex) { } branchItem.addChild("CHD", ti); parent_knt++; // ti.addChild("PAR", branchItem); branchItem._expandable = true; traverseUp(lbsvc, lbscm, codingScheme, versionOrTag, hierarchyID, parentCode, root, branchItem, codesToExclude, associationsToNavigate, associationsNavigatedFwd, visited_links, visited_nodes, maxLevel, currLevel + 1); } } } } if (parent_knt == 0) { root.addChild("CHD", ti); root._expandable = true; } } catch (Exception e) { e.printStackTrace(); } } public HashMap getTreePathData2(String scheme, String version, String code, int maxLevel) { HashMap hmap = new HashMap(); TreeItem root = new TreeItem("<Root>", "Root node"); root._expandable = false; long ms = System.currentTimeMillis(); Set<String> codesToExclude = new HashSet<String>(); HashMap<String, TreeItem> visited_nodes = new HashMap<String, TreeItem>(); Set<String> visited_links = new HashSet<String>(); CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); CodingSchemeVersionOrTag versionOrTag = new CodingSchemeVersionOrTag(); if (version != null) versionOrTag.setVersion(version); CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt); if (cs == null) return null; Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); if (hierarchies == null || hierarchies.length == 0) return null; SupportedHierarchy hierarchyDefn = hierarchies[0]; String hierarchyID = hierarchyDefn.getLocalId(); String[] associationsToNavigate = hierarchyDefn.getAssociationNames(); boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable(); String name = getCodeDescription(lbSvc, scheme, csvt, code); TreeItem ti = new TreeItem(code, name); // ti.expandable = false; ti._expandable = hasSubconcepts(scheme, version, code); _logger.debug(name + "(" + code + ")"); traverseUp(lbSvc, lbscm, scheme, csvt, hierarchyID, code, root, ti, codesToExclude, associationsToNavigate, associationsNavigatedFwd, visited_links, visited_nodes, maxLevel, 0); } catch (Exception ex) { ex.printStackTrace(); } finally { _logger.debug("Run time (milliseconds): " + (System.currentTimeMillis() - ms) + " to resolve " // + pathsResolved + " paths from root."); + " paths from root."); } hmap.put(code, root); return hmap; } // //////////////////////////////////////////////////////////////////////////////////////////////////// public List getHierarchyRoots(String scheme, String version, String hierarchyID) throws LBException { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); // HL7 scheme = DataUtils.searchFormalName(scheme); return getHierarchyRoots(scheme, csvt, hierarchyID); } public List getHierarchyRoots(String scheme, CodingSchemeVersionOrTag csvt, String hierarchyID) throws LBException { /* * // HL7 patch if (scheme.indexOf("HL7") != -1) { return * getTreeRoots(scheme, csvt, hierarchyID); } */ int maxDepth = 1; LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme, csvt, hierarchyID); for (int i = 0; i < roots.getResolvedConceptReferenceCount(); i++) { ResolvedConceptReference rcr = roots.getResolvedConceptReference(i); // _logger.debug("getHierarchyRoots rcr.getConceptCode(): " + // rcr.getConceptCode()); Entity c = rcr.getReferencedEntry(); if (c != null) { rcr.setConceptCode(c.getEntityCode()); } else { _logger .debug("getHierarchyRoots rcr.getReferencedEntry() returns null."); } if (rcr.getEntityDescription() == null) { _logger .debug("getHierarchyRoots rcr.getEntityDescription() == null."); String name = TreeUtils.getCodeDescription(lbSvc, scheme, csvt, rcr .getConceptCode()); if (name == null) name = rcr.getConceptCode();// HL7 EntityDescription e = new EntityDescription(); e.setContent(name); rcr.setEntityDescription(e); } else if (rcr.getEntityDescription().getContent() == null) { _logger .debug("getHierarchyRoots rcr.getEntityDescription().getContent() == null."); String name = TreeUtils.getCodeDescription(lbSvc, scheme, csvt, rcr .getConceptCode()); if (name == null) name = rcr.getConceptCode();// HL7 EntityDescription e = new EntityDescription(); e.setContent(name); rcr.setEntityDescription(e); } } List list = ResolvedConceptReferenceList2List(roots); SortUtils.quickSort(list); return list; } // ///////////////////////////////////////////////////////////////////////////////////////////////////// public List search(LexBIGService lbSvc, LexBIGServiceConvenienceMethods lbscm, String codingSchemeName, String t, String algorithm) throws Exception { LexBIGService lbs = RemoteServerUtil.createLexBIGService(); CodedNodeSet cns = lbs.getCodingSchemeConcepts(codingSchemeName, null); cns = cns.restrictToMatchingDesignations(t, SearchDesignationOption.ALL, algorithm, null); ResolvedConceptReferenceList list = null; int knt = 0; try { list = cns.resolveToList(null, null, null, 500);// .getResolvedConceptReference(); if (list == null) return null; return ResolvedConceptReferenceList2List(list); } catch (Exception ex) { ex.printStackTrace(); } if (knt == 0) _logger.debug("No match."); _logger.debug("\n\n"); return new ArrayList(); } // For HL7 (not yet used, pending Mayo resolution) public List getTreeRoots(String scheme, CodingSchemeVersionOrTag csvt, String hierarchyID) throws LBException { int maxDepth = 1; LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); ResolvedConceptReferenceList roots = lbscm.getHierarchyRoots(scheme, csvt, hierarchyID); ResolvedConceptReferenceList modified_roots = new ResolvedConceptReferenceList(); int knt0 = 0; int knt = 0; for (int i = 0; i < roots.getResolvedConceptReferenceCount(); i++) { ResolvedConceptReference rcr = roots.getResolvedConceptReference(i); // _logger.debug("getHierarchyRoots rcr.getConceptCode(): " + // rcr.getConceptCode()); Entity c = rcr.getReferencedEntry(); if (c != null) { rcr.setConceptCode(c.getEntityCode()); } else { _logger .debug("WARNING: getHierarchyRoots rcr.getReferencedEntry() returns null."); } if (rcr.getEntityDescription() == null) { String name = getCodeDescription(lbSvc, scheme, csvt, rcr .getConceptCode()); if (name == null) { name = "<Not Assigned> (code: " + rcr.getConceptCode() + ")";// HL7 } EntityDescription e = new EntityDescription(); e.setContent(name); rcr.setEntityDescription(e); } else if (rcr.getEntityDescription().getContent() == null) { _logger .debug("getHierarchyRoots rcr.getEntityDescription().getContent() == null."); String name = TreeUtils.getCodeDescription(lbSvc, scheme, csvt, rcr .getConceptCode()); if (name == null) { name = "<Not Assigned> (code: " + rcr.getConceptCode() + ")";// HL7 } EntityDescription e = new EntityDescription(); e.setContent(name); rcr.setEntityDescription(e); } List list = new ArrayList(); try { list = search(lbSvc, lbscm, scheme, rcr.getEntityDescription() .getContent(), "exactMatch"); } catch (Exception ex) { } if (list.size() == 0) knt0++; else if (list.size() > 1) knt++; if (list.size() != 0) { ResolvedConceptReference rc = (ResolvedConceptReference) list.get(0); modified_roots.addResolvedConceptReference(rc); } else { modified_roots.addResolvedConceptReference(rcr); } } List list = ResolvedConceptReferenceList2List(modified_roots); SortUtils.quickSort(list); return list; } public List ResolvedConceptReferenceList2List( ResolvedConceptReferenceList rcrl) { ArrayList list = new ArrayList(); for (int i = 0; i < rcrl.getResolvedConceptReferenceCount(); i++) { ResolvedConceptReference rcr = rcrl.getResolvedConceptReference(i); list.add(rcr); } return list; } public static String[] getAssociationsToNavigate(String scheme, String version) { CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt); if (cs == null) return null; Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); if (hierarchies == null || hierarchies.length == 0) return null; SupportedHierarchy hierarchyDefn = hierarchies[0]; String hier_id = hierarchyDefn.getLocalId(); String[] associationsToNavigate = hierarchyDefn.getAssociationNames(); return associationsToNavigate; } catch (Exception ex) { } return null; } // ArrayList subconceptList = new ArrayList(); public static ArrayList getSubconceptNamesAndCodes(String scheme, String version, String code) { // eturned bar delimited name|code ArrayList list = new ArrayList(); CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); long ms = System.currentTimeMillis(); try { LexBIGService lbSvc = RemoteServerUtil.createLexBIGService(); LexBIGServiceConvenienceMethods lbscm = (LexBIGServiceConvenienceMethods) lbSvc .getGenericExtension("LexBIGServiceConvenienceMethods"); lbscm.setLexBIGService(lbSvc); CodingScheme cs = lbSvc.resolveCodingScheme(scheme, csvt); if (cs == null) return null; Mappings mappings = cs.getMappings(); SupportedHierarchy[] hierarchies = mappings.getSupportedHierarchy(); if (hierarchies == null || hierarchies.length == 0) return null; SupportedHierarchy hierarchyDefn = hierarchies[0]; String hier_id = hierarchyDefn.getLocalId(); String[] associationsToNavigate = hierarchyDefn.getAssociationNames(); boolean associationsNavigatedFwd = hierarchyDefn.getIsForwardNavigable(); NameAndValueList nameAndValueList = createNameAndValueList(associationsToNavigate, null); ResolvedConceptReferenceList matches = null; try { CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); Boolean restrictToAnonymous = Boolean.FALSE; cng = cng.restrictToAnonymous(restrictToAnonymous); NameAndValueList nameAndValueList_qualifier = null; cng = cng.restrictToAssociations(nameAndValueList, nameAndValueList_qualifier); Entity concept = getConceptByCode(scheme, version, null, code); if (concept != null) { String entityCodeNamespace = concept.getEntityCodeNamespace(); //System.out.println("getEntityCodeNamespace returns: " + concept.getEntityCodeNamespace()); ConceptReference focus = ConvenienceMethods.createConceptReference(code, scheme); focus.setCodingSchemeName(entityCodeNamespace); //String name = concept.getEntityDescription().getContent();//getCodeDescription(lbSvc, scheme, csvt, code); //ConceptReference graphFocus = // ConvenienceMethods.createConceptReference(code, scheme); matches = cng.resolveAsList(focus, associationsNavigatedFwd, !associationsNavigatedFwd, 1, 1, new LocalNameList(), null, null, -1); } } catch (Exception ex) { ex.printStackTrace(); } // Analyze the result ... if (matches != null && matches.getResolvedConceptReferenceCount() > 0) { ResolvedConceptReference ref = (ResolvedConceptReference) matches .enumerateResolvedConceptReference().nextElement(); if (ref != null) { AssociationList sourceof = ref.getSourceOf(); if (!associationsNavigatedFwd) sourceof = ref.getTargetOf(); if (sourceof != null) { Association[] associations = sourceof.getAssociation(); if (associations != null) { for (int i = 0; i < associations.length; i++) { Association assoc = associations[i]; if (assoc != null) { if (assoc.getAssociatedConcepts() != null) { AssociatedConcept[] acl = assoc.getAssociatedConcepts() .getAssociatedConcept(); if (acl != null) { for (int j = 0; j < acl.length; j++) { AssociatedConcept ac = acl[j]; // KLO, 030110 if (ac != null && ac.getConceptCode() .indexOf("@") == -1) { EntityDescription ed = ac .getEntityDescription(); if (ed != null) { list .add(ed .getContent() + "|" + ac .getConceptCode()); } } } } } } } } } } } } catch (Exception ex) { ex.printStackTrace(); } _logger.debug("Run time (milliseconds) getSubconcepts: " + (System.currentTimeMillis() - ms) + " to resolve "); SortUtils.quickSort(list); return list; } public static void relabelTreeNodes(HashMap hmap) { Iterator it = hmap.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); TreeItem ti = (TreeItem) hmap.get(key); for (String association : ti._assocToChildMap.keySet()) { List<TreeItem> children = ti._assocToChildMap.get(association); for (TreeItem childItem : children) { String code = childItem._code; String text = childItem._text; //childItem._text = childItem._code + " (" + text + ")"; childItem._text = childItem._code; } } } } public static HashMap combine(HashMap hmap1, HashMap hmap2) { if (hmap1 == null) { System.out.println("(********) hmap1 == null" ); } if (hmap2 == null) { System.out.println("(********) hmap2 == null" ); } if (hmap1 == null && hmap2 == null) return null; if (hmap1 == null && hmap2 != null) return hmap2; if (hmap2 == null && hmap1 != null) return hmap1; TreeItem ti = new TreeItem("<Root>", "Root node"); ti._expandable = false; TreeItem root = null; Iterator it = hmap1.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); root = (TreeItem) hmap1.get(key); if (root != null) { for (String association : root._assocToChildMap.keySet()) { List<TreeItem> children = root._assocToChildMap.get(association); for (TreeItem childItem : children) { ti.addChild(association, childItem); ti._expandable = true; } } } } it = hmap2.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); root = (TreeItem) hmap2.get(key); if (root != null) { for (String association : root._assocToChildMap.keySet()) { List<TreeItem> children = root._assocToChildMap.get(association); for (TreeItem childItem : children) { ti.addChild(association, childItem); ti._expandable = true; } } } } HashMap hmap = new HashMap(); hmap.put("<Root>", ti); return hmap; } public static void main(String[] args) { String url = "http://lexevsapi-dev.nci.nih.gov/lexevsapi42"; url = "http://lexevsapi-qa.nci.nih.gov/lexevsapi50"; HashMap hmap = null; String scheme = "NCI Thesaurus"; String version = null; String code = "C26709"; TreeUtils test = new TreeUtils(); // hmap = test.getSubconcepts(scheme, version, code); // test.printTree(hmap); code = "C2910"; code = "C9335"; String hierarchyID = test.getHierarchyID(scheme, null); _logger.debug("(*) " + scheme + " Hierarchy ID: " + hierarchyID); hmap = test.getSubconcepts(scheme, version, code); test.printTree(hmap); _logger .debug("============================================================="); scheme = "Gene Ontology"; code = "GO:0008150"; hierarchyID = test.getHierarchyID(scheme, null); _logger.debug("Hierarchy ID: " + hierarchyID); hmap = test.getSubconcepts(scheme, version, code); test.printTree(hmap); _logger .debug("============================================================="); scheme = "HL7 Reference Information Model "; code = "AcknowledgementType"; hierarchyID = test.getHierarchyID(scheme, null); _logger.debug("Hierarchy ID: " + hierarchyID); hmap = test.getSubconcepts(scheme, version, code); test.printTree(hmap); } }
true
true
public static HashMap getAssociatedConcepts(LexBIGService lbSvc, LexBIGServiceConvenienceMethods lbscm, String scheme, String version, String code, String[] assocNames, boolean direction) { HashMap hmap = new HashMap(); TreeItem ti = null; long ms = System.currentTimeMillis(); Set<String> codesToExclude = Collections.EMPTY_SET; CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { Entity concept = getConceptByCode(scheme, version, null, code); if (concept == null) return null; String entityCodeNamespace = concept.getEntityCodeNamespace(); //System.out.println("getEntityCodeNamespace returns: " + concept.getEntityCodeNamespace()); ConceptReference focus = ConvenienceMethods.createConceptReference(code, scheme); focus.setCodingSchemeName(entityCodeNamespace); String name = concept.getEntityDescription().getContent();//getCodeDescription(lbSvc, scheme, csvt, code); //String name = getCodeDescription(lbSvc, scheme, csvt, code); ti = new TreeItem(code, name); ti._expandable = false; CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); Boolean restrictToAnonymous = Boolean.FALSE; cng = cng.restrictToAnonymous(restrictToAnonymous); //ConceptReference focus = // Constructors.createConceptReference(code, scheme); cng = cng.restrictToAssociations(Constructors .createNameAndValueList(assocNames), null); boolean associationsNavigatedFwd = direction; // To remove anonymous classes (KLO, 091009), the // resolveCodedEntryDepth parameter cannot be set to -1. // Alternative -- use code to determine whether the class is // anonymous ResolvedConceptReferenceList branch = null; try { branch = cng.resolveAsList(focus, associationsNavigatedFwd, // !associationsNavigatedFwd, 1, 2, noopList_, null, // null, null, -1, false); !associationsNavigatedFwd, -1, 2, _noopList, null, null, null, -1, false); } catch (Exception e) { _logger .error("TreeUtils getAssociatedConcepts throws exceptions."); return null; } for (Iterator<? extends ResolvedConceptReference> nodes = branch.iterateResolvedConceptReference(); nodes.hasNext();) { ResolvedConceptReference node = nodes.next(); AssociationList childAssociationList = null; // AssociationList childAssociationList = // associationsNavigatedFwd ? node.getSourceOf(): // node.getTargetOf(); if (associationsNavigatedFwd) { childAssociationList = node.getSourceOf(); } else { childAssociationList = node.getTargetOf(); } if (childAssociationList != null) { // Process each association defining children ... for (Iterator<? extends Association> pathsToChildren = childAssociationList.iterateAssociation(); pathsToChildren .hasNext();) { Association child = pathsToChildren.next(); // KLO 091009 remove anonymous nodes child = processForAnonomousNodes(child); String childNavText = getDirectionalLabel(lbscm, scheme, csvt, child, associationsNavigatedFwd); // Each association may have multiple children ... AssociatedConceptList branchItemList = child.getAssociatedConcepts(); /* * for (Iterator<AssociatedConcept> branchNodes = * branchItemList.iterateAssociatedConcept(); * branchNodes .hasNext();) { AssociatedConcept * branchItemNode = branchNodes.next(); */ List child_list = new ArrayList(); for (Iterator<? extends AssociatedConcept> branchNodes = branchItemList.iterateAssociatedConcept(); branchNodes .hasNext();) { AssociatedConcept branchItemNode = branchNodes.next(); child_list.add(branchItemNode); } SortUtils.quickSort(child_list); for (int i = 0; i < child_list.size(); i++) { AssociatedConcept branchItemNode = (AssociatedConcept) child_list.get(i); String branchItemCode = branchItemNode.getConceptCode(); if (!branchItemCode.startsWith("@")) { // Add here if not in the list of excluded // codes. // This is also where we look to see if another // level // was indicated to be available. If so, mark // the // entry with a '+' to indicate it can be // expanded. if (!codesToExclude.contains(branchItemCode)) { TreeItem childItem = new TreeItem(branchItemCode, getCodeDescription(branchItemNode)); ti._expandable = true; AssociationList grandchildBranch = associationsNavigatedFwd ? branchItemNode .getSourceOf() : branchItemNode.getTargetOf(); if (grandchildBranch != null) childItem._expandable = true; ti.addChild(childNavText, childItem); } } } } } else { _logger.warn("WARNING: childAssociationList == null."); } } hmap.put(code, ti); } catch (Exception ex) { ex.printStackTrace(); } _logger.debug("Run time (milliseconds) getSubconcepts: " + (System.currentTimeMillis() - ms) + " to resolve "); return hmap; }
public static HashMap getAssociatedConcepts(LexBIGService lbSvc, LexBIGServiceConvenienceMethods lbscm, String scheme, String version, String code, String[] assocNames, boolean direction) { HashMap hmap = new HashMap(); TreeItem ti = null; long ms = System.currentTimeMillis(); Set<String> codesToExclude = Collections.EMPTY_SET; CodingSchemeVersionOrTag csvt = new CodingSchemeVersionOrTag(); if (version != null) csvt.setVersion(version); ResolvedConceptReferenceList matches = null; Vector v = new Vector(); try { Entity concept = getConceptByCode(scheme, version, null, code); if (concept == null) return null; String entityCodeNamespace = concept.getEntityCodeNamespace(); //System.out.println("getEntityCodeNamespace returns: " + concept.getEntityCodeNamespace()); ConceptReference focus = ConvenienceMethods.createConceptReference(code, scheme); focus.setCodingSchemeName(entityCodeNamespace); String name = concept.getEntityDescription().getContent();//getCodeDescription(lbSvc, scheme, csvt, code); //String name = getCodeDescription(lbSvc, scheme, csvt, code); ti = new TreeItem(code, name); ti._expandable = false; CodedNodeGraph cng = lbSvc.getNodeGraph(scheme, csvt, null); Boolean restrictToAnonymous = Boolean.FALSE; cng = cng.restrictToAnonymous(restrictToAnonymous); //ConceptReference focus = // Constructors.createConceptReference(code, scheme); cng = cng.restrictToAssociations(Constructors .createNameAndValueList(assocNames), null); boolean associationsNavigatedFwd = direction; // To remove anonymous classes (KLO, 091009), the // resolveCodedEntryDepth parameter cannot be set to -1. // Alternative -- use code to determine whether the class is // anonymous ResolvedConceptReferenceList branch = null; try { branch = cng.resolveAsList(focus, associationsNavigatedFwd, // !associationsNavigatedFwd, 1, 2, noopList_, null, // null, null, -1, false); !associationsNavigatedFwd, -1, 2, _noopList, null, null, null, -1, false); } catch (Exception e) { _logger .error("TreeUtils getAssociatedConcepts throws exceptions."); return null; } for (Iterator<? extends ResolvedConceptReference> nodes = branch.iterateResolvedConceptReference(); nodes.hasNext();) { ResolvedConceptReference node = nodes.next(); AssociationList childAssociationList = null; // AssociationList childAssociationList = // associationsNavigatedFwd ? node.getSourceOf(): // node.getTargetOf(); if (associationsNavigatedFwd) { childAssociationList = node.getSourceOf(); } else { childAssociationList = node.getTargetOf(); } if (childAssociationList != null) { // Process each association defining children ... for (Iterator<? extends Association> pathsToChildren = childAssociationList.iterateAssociation(); pathsToChildren .hasNext();) { Association child = pathsToChildren.next(); // KLO 091009 remove anonymous nodes //child = processForAnonomousNodes(child); String childNavText = getDirectionalLabel(lbscm, scheme, csvt, child, associationsNavigatedFwd); // Each association may have multiple children ... AssociatedConceptList branchItemList = child.getAssociatedConcepts(); /* * for (Iterator<AssociatedConcept> branchNodes = * branchItemList.iterateAssociatedConcept(); * branchNodes .hasNext();) { AssociatedConcept * branchItemNode = branchNodes.next(); */ List child_list = new ArrayList(); for (Iterator<? extends AssociatedConcept> branchNodes = branchItemList.iterateAssociatedConcept(); branchNodes .hasNext();) { AssociatedConcept branchItemNode = branchNodes.next(); child_list.add(branchItemNode); } SortUtils.quickSort(child_list); for (int i = 0; i < child_list.size(); i++) { AssociatedConcept branchItemNode = (AssociatedConcept) child_list.get(i); String branchItemCode = branchItemNode.getConceptCode(); if (!branchItemCode.startsWith("@")) { // Add here if not in the list of excluded // codes. // This is also where we look to see if another // level // was indicated to be available. If so, mark // the // entry with a '+' to indicate it can be // expanded. if (!codesToExclude.contains(branchItemCode)) { TreeItem childItem = new TreeItem(branchItemCode, getCodeDescription(branchItemNode)); ti._expandable = true; AssociationList grandchildBranch = associationsNavigatedFwd ? branchItemNode .getSourceOf() : branchItemNode.getTargetOf(); if (grandchildBranch != null) childItem._expandable = true; ti.addChild(childNavText, childItem); } } } } } else { _logger.warn("WARNING: childAssociationList == null."); } } hmap.put(code, ti); } catch (Exception ex) { ex.printStackTrace(); } _logger.debug("Run time (milliseconds) getSubconcepts: " + (System.currentTimeMillis() - ms) + " to resolve "); return hmap; }
diff --git a/src/main/java/com/notnoop/c2dm/C2DMNotificationBuilder.java b/src/main/java/com/notnoop/c2dm/C2DMNotificationBuilder.java index 37e597b..f8dde98 100644 --- a/src/main/java/com/notnoop/c2dm/C2DMNotificationBuilder.java +++ b/src/main/java/com/notnoop/c2dm/C2DMNotificationBuilder.java @@ -1,107 +1,107 @@ /* * Copyright 2011, Mahmood Ali. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Mahmood Ali. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.notnoop.c2dm; import java.util.ArrayList; import java.util.List; import com.notnoop.c2dm.internal.Pair; /** * Represents a builder for constructing the notifications requests, * as specified by * <a href="http://code.google.com/android/c2dm/index.html#server">Android * Cloud to Device Messaging Framework documentation</a>: * */ public class C2DMNotificationBuilder { private String collapseKey; private boolean delayWhileIdle; private List<Pair<String, String>> data = new ArrayList<Pair<String, String>>(); public C2DMNotificationBuilder() {} /** * Sets the collapse key for the notification. * * An arbitrary string that is used to collapse a group of like messages when the device is offline, so that only the last message gets sent to the client. This is intended to avoid sending too many messages to the phone when it comes back online. Note that since there is no guarantee of the order in which messages get sent, the "last" message may not actually be the last message sent by the application server. * * The field is required * * @return this */ public C2DMNotificationBuilder collapseKey(String collapseKey) { this.collapseKey = collapseKey; return this; } /** * Sets the delay while idle flag for the message. * * indicates that the message should not be sent immediately if the device is idle. The server will wait for the device to become active, and then only the last message for each collapse_key value will be sent. * * Default value is false. * * @return this */ public C2DMNotificationBuilder delayWhileIdle(boolean delayWhileIdle) { this.delayWhileIdle = delayWhileIdle; return this; } /** * Appends an application specific payload data entry. * * Payload data, expressed as key-value pairs. If present, it will be included in the Intent as application data, with the <key>. There is no limit on the number of key/value pairs, though there is a limit on the total size of the message. * * This field is optional. * * @return this */ public C2DMNotificationBuilder data(String name, String value) { data.add(Pair.of("data." + name, value)); return this; } private void checkInitialization() { - if (collapseKey != null) { + if (collapseKey == null) { throw new IllegalStateException("Collapse Key is required and missing"); } } /** * Returns a fully initialized notification object */ public C2DMNotification build() { checkInitialization(); return new C2DMNotification(collapseKey, delayWhileIdle, data); } }
true
true
private void checkInitialization() { if (collapseKey != null) { throw new IllegalStateException("Collapse Key is required and missing"); } }
private void checkInitialization() { if (collapseKey == null) { throw new IllegalStateException("Collapse Key is required and missing"); } }
diff --git a/src/me/libraryaddict/disguise/BaseDisguiseCommand.java b/src/me/libraryaddict/disguise/BaseDisguiseCommand.java index 07103a0..c1413c8 100644 --- a/src/me/libraryaddict/disguise/BaseDisguiseCommand.java +++ b/src/me/libraryaddict/disguise/BaseDisguiseCommand.java @@ -1,186 +1,186 @@ package me.libraryaddict.disguise; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import me.libraryaddict.disguise.disguisetypes.Disguise; import me.libraryaddict.disguise.disguisetypes.DisguiseType; import me.libraryaddict.disguise.disguisetypes.MiscDisguise; import me.libraryaddict.disguise.disguisetypes.MobDisguise; import me.libraryaddict.disguise.disguisetypes.PlayerDisguise; import net.minecraft.v1_6_R3.org.bouncycastle.util.Arrays; import org.apache.commons.lang3.ArrayUtils; import org.bukkit.ChatColor; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public abstract class BaseDisguiseCommand implements CommandExecutor { protected ArrayList<String> getAllowedDisguises(CommandSender sender, String permissionNode) { ArrayList<String> names = new ArrayList<String>(); for (DisguiseType type : DisguiseType.values()) { String name = type.name().toLowerCase(); if (sender.hasPermission("libsdisguises." + permissionNode + ".*") || sender.hasPermission("libsdisguises." + permissionNode + "." + name)) names.add(name); } Collections.sort(names, String.CASE_INSENSITIVE_ORDER); return names; } protected boolean isNumeric(String string) { try { Integer.parseInt(string); return true; } catch (Exception ex) { return false; } } protected boolean isDouble(String string) { try { Float.parseFloat(string); return true; } catch (Exception ex) { return false; } } protected abstract void sendCommandUsage(CommandSender sender); /** * Returns the disguise if it all parsed correctly. Returns a exception with a complete message if it didn't. The * commandsender is purely used for checking permissions. Would defeat the purpose otherwise. To reach this point, the * disguise has been feed a proper disguisetype. */ protected Disguise parseDisguise(CommandSender sender, String[] args) throws Exception { String permissionNode = getClass().getSimpleName().replace("Command", "").toLowerCase(); ArrayList<String> allowedDisguises = getAllowedDisguises(sender, permissionNode); if (allowedDisguises.isEmpty()) { throw new Exception(ChatColor.RED + "You are forbidden to use this command."); } if (args.length == 0) { sendCommandUsage(sender); throw new Exception(); } DisguiseType disguiseType = null; for (DisguiseType type : DisguiseType.values()) { if (args[0].equalsIgnoreCase(type.name()) || type.name().replace("_", "").equalsIgnoreCase(args[0])) { disguiseType = type; break; } } if (disguiseType == null) { throw new Exception(ChatColor.RED + "Error! The disguise " + ChatColor.GREEN + args[0] + ChatColor.RED + " doesn't exist!"); } - if (!allowedDisguises.contains(args[0].toLowerCase())) { + if (!allowedDisguises.contains(disguiseType.name().toLowerCase())) { throw new Exception(ChatColor.RED + "You are forbidden to use this disguise!"); } Disguise disguise = null; // How many args to skip due to the disugise being constructed int toSkip = 1; // Time to start constructing the disguise. // We will need to check between all 3 kinds of disguises if (disguiseType.isPlayer()) {// If he is doing a player disguise if (args.length == 1) { // He needs to give the player name throw new Exception(ChatColor.RED + "Error! You need to give a player name!"); } else { // Construct the player disguise disguise = new PlayerDisguise(ChatColor.translateAlternateColorCodes('&', args[1])); toSkip++; } } else { if (disguiseType.isMob()) { // Its a mob, use the mob constructor boolean adult = true; if (args.length > 1) { if (args[1].equalsIgnoreCase("true") || args[1].equalsIgnoreCase("false")) { adult = "false".equalsIgnoreCase(args[1]); toSkip++; } } disguise = new MobDisguise(disguiseType, adult); } else if (disguiseType.isMisc()) { // Its a misc, we are going to use the MiscDisguise constructor. int miscId = -1; int miscData = -1; if (args.length > 1) { // They have defined more arguements! // If the first arg is a number if (isNumeric(args[1])) { miscId = Integer.parseInt(args[1]); toSkip++; // If they also defined a data value if (args.length > 2) { if (isNumeric(args[2])) { miscData = Integer.parseInt(args[2]); toSkip++; } } } } // Construct the disguise disguise = new MiscDisguise(disguiseType, true, miscId, miscData); } } // Copy strings to their new range String[] newArgs = new String[args.length - toSkip]; for (int i = toSkip; i < args.length; i++) { newArgs[i - toSkip] = args[i]; } args = newArgs; // Don't throw a error about uneven methods names and values so we can throw the error about what is unknown later. for (int i = 0; i < args.length; i += 2) { String methodName = args[i]; if (i + 1 >= args.length) { throw new Exception(ChatColor.RED + "No value was given for " + methodName); } String valueString = args[i + 1]; Method methodToUse = null; Object value = null; for (Method method : disguise.getWatcher().getClass().getMethods()) { if (!method.getName().startsWith("get") && method.getName().equalsIgnoreCase(methodName)) { methodToUse = method; methodName = method.getName(); Class<?>[] types = method.getParameterTypes(); if (types.length == 1) { Class param = types[0]; if (float.class == param || double.class == param || int.class == param) { if (isDouble(valueString)) { float obj = Float.parseFloat(valueString); if (param == float.class) { value = (float) obj; } else if (param == int.class) { value = (int) obj; } else if (param == double.class) { value = (double) obj; } } else { throw new Exception(ChatColor.RED + "Expected a number, received " + valueString + " instead for " + methodName); } } else if (boolean.class == param) { if (!("true".equalsIgnoreCase(valueString) || "false".equalsIgnoreCase(valueString))) throw new Exception(ChatColor.RED + "Expected true/false, received " + valueString + " instead for " + methodName); value = (boolean) "true".equalsIgnoreCase(valueString); } else if (param == String.class) { value = ChatColor.translateAlternateColorCodes('&', valueString); } } break; } } if (methodToUse == null) { throw new Exception(ChatColor.RED + "Cannot find option " + methodName); } methodToUse.invoke(disguise.getWatcher(), value); } // Alright. We've constructed our disguise. return disguise; } }
true
true
protected Disguise parseDisguise(CommandSender sender, String[] args) throws Exception { String permissionNode = getClass().getSimpleName().replace("Command", "").toLowerCase(); ArrayList<String> allowedDisguises = getAllowedDisguises(sender, permissionNode); if (allowedDisguises.isEmpty()) { throw new Exception(ChatColor.RED + "You are forbidden to use this command."); } if (args.length == 0) { sendCommandUsage(sender); throw new Exception(); } DisguiseType disguiseType = null; for (DisguiseType type : DisguiseType.values()) { if (args[0].equalsIgnoreCase(type.name()) || type.name().replace("_", "").equalsIgnoreCase(args[0])) { disguiseType = type; break; } } if (disguiseType == null) { throw new Exception(ChatColor.RED + "Error! The disguise " + ChatColor.GREEN + args[0] + ChatColor.RED + " doesn't exist!"); } if (!allowedDisguises.contains(args[0].toLowerCase())) { throw new Exception(ChatColor.RED + "You are forbidden to use this disguise!"); } Disguise disguise = null; // How many args to skip due to the disugise being constructed int toSkip = 1; // Time to start constructing the disguise. // We will need to check between all 3 kinds of disguises if (disguiseType.isPlayer()) {// If he is doing a player disguise if (args.length == 1) { // He needs to give the player name throw new Exception(ChatColor.RED + "Error! You need to give a player name!"); } else { // Construct the player disguise disguise = new PlayerDisguise(ChatColor.translateAlternateColorCodes('&', args[1])); toSkip++; } } else { if (disguiseType.isMob()) { // Its a mob, use the mob constructor boolean adult = true; if (args.length > 1) { if (args[1].equalsIgnoreCase("true") || args[1].equalsIgnoreCase("false")) { adult = "false".equalsIgnoreCase(args[1]); toSkip++; } } disguise = new MobDisguise(disguiseType, adult); } else if (disguiseType.isMisc()) { // Its a misc, we are going to use the MiscDisguise constructor. int miscId = -1; int miscData = -1; if (args.length > 1) { // They have defined more arguements! // If the first arg is a number if (isNumeric(args[1])) { miscId = Integer.parseInt(args[1]); toSkip++; // If they also defined a data value if (args.length > 2) { if (isNumeric(args[2])) { miscData = Integer.parseInt(args[2]); toSkip++; } } } } // Construct the disguise disguise = new MiscDisguise(disguiseType, true, miscId, miscData); } } // Copy strings to their new range String[] newArgs = new String[args.length - toSkip]; for (int i = toSkip; i < args.length; i++) { newArgs[i - toSkip] = args[i]; } args = newArgs; // Don't throw a error about uneven methods names and values so we can throw the error about what is unknown later. for (int i = 0; i < args.length; i += 2) { String methodName = args[i]; if (i + 1 >= args.length) { throw new Exception(ChatColor.RED + "No value was given for " + methodName); } String valueString = args[i + 1]; Method methodToUse = null; Object value = null; for (Method method : disguise.getWatcher().getClass().getMethods()) { if (!method.getName().startsWith("get") && method.getName().equalsIgnoreCase(methodName)) { methodToUse = method; methodName = method.getName(); Class<?>[] types = method.getParameterTypes(); if (types.length == 1) { Class param = types[0]; if (float.class == param || double.class == param || int.class == param) { if (isDouble(valueString)) { float obj = Float.parseFloat(valueString); if (param == float.class) { value = (float) obj; } else if (param == int.class) { value = (int) obj; } else if (param == double.class) { value = (double) obj; } } else { throw new Exception(ChatColor.RED + "Expected a number, received " + valueString + " instead for " + methodName); } } else if (boolean.class == param) { if (!("true".equalsIgnoreCase(valueString) || "false".equalsIgnoreCase(valueString))) throw new Exception(ChatColor.RED + "Expected true/false, received " + valueString + " instead for " + methodName); value = (boolean) "true".equalsIgnoreCase(valueString); } else if (param == String.class) { value = ChatColor.translateAlternateColorCodes('&', valueString); } } break; } } if (methodToUse == null) { throw new Exception(ChatColor.RED + "Cannot find option " + methodName); } methodToUse.invoke(disguise.getWatcher(), value); } // Alright. We've constructed our disguise. return disguise; }
protected Disguise parseDisguise(CommandSender sender, String[] args) throws Exception { String permissionNode = getClass().getSimpleName().replace("Command", "").toLowerCase(); ArrayList<String> allowedDisguises = getAllowedDisguises(sender, permissionNode); if (allowedDisguises.isEmpty()) { throw new Exception(ChatColor.RED + "You are forbidden to use this command."); } if (args.length == 0) { sendCommandUsage(sender); throw new Exception(); } DisguiseType disguiseType = null; for (DisguiseType type : DisguiseType.values()) { if (args[0].equalsIgnoreCase(type.name()) || type.name().replace("_", "").equalsIgnoreCase(args[0])) { disguiseType = type; break; } } if (disguiseType == null) { throw new Exception(ChatColor.RED + "Error! The disguise " + ChatColor.GREEN + args[0] + ChatColor.RED + " doesn't exist!"); } if (!allowedDisguises.contains(disguiseType.name().toLowerCase())) { throw new Exception(ChatColor.RED + "You are forbidden to use this disguise!"); } Disguise disguise = null; // How many args to skip due to the disugise being constructed int toSkip = 1; // Time to start constructing the disguise. // We will need to check between all 3 kinds of disguises if (disguiseType.isPlayer()) {// If he is doing a player disguise if (args.length == 1) { // He needs to give the player name throw new Exception(ChatColor.RED + "Error! You need to give a player name!"); } else { // Construct the player disguise disguise = new PlayerDisguise(ChatColor.translateAlternateColorCodes('&', args[1])); toSkip++; } } else { if (disguiseType.isMob()) { // Its a mob, use the mob constructor boolean adult = true; if (args.length > 1) { if (args[1].equalsIgnoreCase("true") || args[1].equalsIgnoreCase("false")) { adult = "false".equalsIgnoreCase(args[1]); toSkip++; } } disguise = new MobDisguise(disguiseType, adult); } else if (disguiseType.isMisc()) { // Its a misc, we are going to use the MiscDisguise constructor. int miscId = -1; int miscData = -1; if (args.length > 1) { // They have defined more arguements! // If the first arg is a number if (isNumeric(args[1])) { miscId = Integer.parseInt(args[1]); toSkip++; // If they also defined a data value if (args.length > 2) { if (isNumeric(args[2])) { miscData = Integer.parseInt(args[2]); toSkip++; } } } } // Construct the disguise disguise = new MiscDisguise(disguiseType, true, miscId, miscData); } } // Copy strings to their new range String[] newArgs = new String[args.length - toSkip]; for (int i = toSkip; i < args.length; i++) { newArgs[i - toSkip] = args[i]; } args = newArgs; // Don't throw a error about uneven methods names and values so we can throw the error about what is unknown later. for (int i = 0; i < args.length; i += 2) { String methodName = args[i]; if (i + 1 >= args.length) { throw new Exception(ChatColor.RED + "No value was given for " + methodName); } String valueString = args[i + 1]; Method methodToUse = null; Object value = null; for (Method method : disguise.getWatcher().getClass().getMethods()) { if (!method.getName().startsWith("get") && method.getName().equalsIgnoreCase(methodName)) { methodToUse = method; methodName = method.getName(); Class<?>[] types = method.getParameterTypes(); if (types.length == 1) { Class param = types[0]; if (float.class == param || double.class == param || int.class == param) { if (isDouble(valueString)) { float obj = Float.parseFloat(valueString); if (param == float.class) { value = (float) obj; } else if (param == int.class) { value = (int) obj; } else if (param == double.class) { value = (double) obj; } } else { throw new Exception(ChatColor.RED + "Expected a number, received " + valueString + " instead for " + methodName); } } else if (boolean.class == param) { if (!("true".equalsIgnoreCase(valueString) || "false".equalsIgnoreCase(valueString))) throw new Exception(ChatColor.RED + "Expected true/false, received " + valueString + " instead for " + methodName); value = (boolean) "true".equalsIgnoreCase(valueString); } else if (param == String.class) { value = ChatColor.translateAlternateColorCodes('&', valueString); } } break; } } if (methodToUse == null) { throw new Exception(ChatColor.RED + "Cannot find option " + methodName); } methodToUse.invoke(disguise.getWatcher(), value); } // Alright. We've constructed our disguise. return disguise; }
diff --git a/src/org/mozilla/javascript/NativeJavaObject.java b/src/org/mozilla/javascript/NativeJavaObject.java index c7506ccf..5b545f7f 100644 --- a/src/org/mozilla/javascript/NativeJavaObject.java +++ b/src/org/mozilla/javascript/NativeJavaObject.java @@ -1,1002 +1,1002 @@ /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Rhino code, released * May 6, 1999. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1997-2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Norris Boyd * Igor Bukanov * Frank Mitchell * Mike Shaver * Kemal Bayram * * Alternatively, the contents of this file may be used under the terms of * the GNU General Public License Version 2 or later (the "GPL"), in which * case the provisions of the GPL are applicable instead of those above. If * you wish to allow use of your version of this file only under the terms of * the GPL and not to allow others to use your version of this file under the * MPL, indicate your decision by deleting the provisions above and replacing * them with the notice and other provisions required by the GPL. If you do * not delete the provisions above, a recipient may use your version of this * file under either the MPL or the GPL. * * ***** END LICENSE BLOCK ***** */ package org.mozilla.javascript; import java.io.*; import java.lang.reflect.*; import java.util.Map; import java.util.Date; /** * This class reflects non-Array Java objects into the JavaScript environment. It * reflect fields directly, and uses NativeJavaMethod objects to reflect (possibly * overloaded) methods.<p> * * @author Mike Shaver * @see NativeJavaArray * @see NativeJavaPackage * @see NativeJavaClass */ public class NativeJavaObject implements Scriptable, Wrapper, Serializable { static final long serialVersionUID = -6948590651130498591L; public NativeJavaObject() { } public NativeJavaObject(Scriptable scope, Object javaObject, Class<?> staticType) { this(scope, javaObject, staticType, false); } public NativeJavaObject(Scriptable scope, Object javaObject, Class<?> staticType, boolean isAdapter) { this.parent = scope; this.javaObject = javaObject; this.staticType = staticType; this.isAdapter = isAdapter; initMembers(); } protected void initMembers() { Class<?> dynamicType; if (javaObject != null) { dynamicType = javaObject.getClass(); } else { dynamicType = staticType; } members = JavaMembers.lookupClass(parent, dynamicType, staticType, isAdapter); fieldAndMethods = members.getFieldAndMethodsObjects(this, javaObject, false); } public boolean has(String name, Scriptable start) { return members.has(name, false); } public boolean has(int index, Scriptable start) { return false; } public Object get(String name, Scriptable start) { if (fieldAndMethods != null) { Object result = fieldAndMethods.get(name); if (result != null) { return result; } } // TODO: passing 'this' as the scope is bogus since it has // no parent scope return members.get(this, name, javaObject, false); } public Object get(int index, Scriptable start) { throw members.reportMemberNotFound(Integer.toString(index)); } public void put(String name, Scriptable start, Object value) { // We could be asked to modify the value of a property in the // prototype. Since we can't add a property to a Java object, // we modify it in the prototype rather than copy it down. if (prototype == null || members.has(name, false)) members.put(this, name, javaObject, value, false); else prototype.put(name, prototype, value); } public void put(int index, Scriptable start, Object value) { throw members.reportMemberNotFound(Integer.toString(index)); } public boolean hasInstance(Scriptable value) { // This is an instance of a Java class, so always return false return false; } public void delete(String name) { } public void delete(int index) { } public Scriptable getPrototype() { if (prototype == null && javaObject instanceof String) { return ScriptableObject.getClassPrototype(parent, "String"); } return prototype; } /** * Sets the prototype of the object. */ public void setPrototype(Scriptable m) { prototype = m; } /** * Returns the parent (enclosing) scope of the object. */ public Scriptable getParentScope() { return parent; } /** * Sets the parent (enclosing) scope of the object. */ public void setParentScope(Scriptable m) { parent = m; } public Object[] getIds() { return members.getIds(false); } /** @deprecated Use {@link Context#getWrapFactory()} together with calling {@link WrapFactory#wrap(Context, Scriptable, Object, Class)} */ public static Object wrap(Scriptable scope, Object obj, Class<?> staticType) { Context cx = Context.getContext(); return cx.getWrapFactory().wrap(cx, scope, obj, staticType); } public Object unwrap() { return javaObject; } public String getClassName() { return "JavaObject"; } public Object getDefaultValue(Class<?> hint) { Object value; if (hint == null) { if (javaObject instanceof Boolean) { hint = ScriptRuntime.BooleanClass; } } if (hint == null || hint == ScriptRuntime.StringClass) { value = javaObject.toString(); } else { String converterName; if (hint == ScriptRuntime.BooleanClass) { converterName = "booleanValue"; } else if (hint == ScriptRuntime.NumberClass) { converterName = "doubleValue"; } else { throw Context.reportRuntimeError0("msg.default.value"); } Object converterObject = get(converterName, this); if (converterObject instanceof Function) { Function f = (Function)converterObject; value = f.call(Context.getContext(), f.getParentScope(), this, ScriptRuntime.emptyArgs); } else { if (hint == ScriptRuntime.NumberClass && javaObject instanceof Boolean) { boolean b = ((Boolean)javaObject).booleanValue(); value = ScriptRuntime.wrapNumber(b ? 1.0 : 0.0); } else { value = javaObject.toString(); } } } return value; } /** * Determine whether we can/should convert between the given type and the * desired one. This should be superceded by a conversion-cost calculation * function, but for now I'll hide behind precedent. */ public static boolean canConvert(Object fromObj, Class<?> to) { int weight = getConversionWeight(fromObj, to); return (weight < CONVERSION_NONE); } private static final int JSTYPE_UNDEFINED = 0; // undefined type private static final int JSTYPE_NULL = 1; // null private static final int JSTYPE_BOOLEAN = 2; // boolean private static final int JSTYPE_NUMBER = 3; // number private static final int JSTYPE_STRING = 4; // string private static final int JSTYPE_JAVA_CLASS = 5; // JavaClass private static final int JSTYPE_JAVA_OBJECT = 6; // JavaObject private static final int JSTYPE_JAVA_ARRAY = 7; // JavaArray private static final int JSTYPE_OBJECT = 8; // Scriptable static final byte CONVERSION_TRIVIAL = 1; static final byte CONVERSION_NONTRIVIAL = 0; static final byte CONVERSION_NONE = 99; /** * Derive a ranking based on how "natural" the conversion is. * The special value CONVERSION_NONE means no conversion is possible, * and CONVERSION_NONTRIVIAL signals that more type conformance testing * is required. * Based on * <a href="http://www.mozilla.org/js/liveconnect/lc3_method_overloading.html"> * "preferred method conversions" from Live Connect 3</a> */ static int getConversionWeight(Object fromObj, Class<?> to) { int fromCode = getJSTypeCode(fromObj); switch (fromCode) { case JSTYPE_UNDEFINED: if (to == ScriptRuntime.StringClass || to == ScriptRuntime.ObjectClass) { return 1; } break; case JSTYPE_NULL: if (!to.isPrimitive()) { return 1; } break; case JSTYPE_BOOLEAN: // "boolean" is #1 if (to == Boolean.TYPE) { return 1; } else if (to == ScriptRuntime.BooleanClass) { return 2; } else if (to == ScriptRuntime.ObjectClass) { return 3; } else if (to == ScriptRuntime.StringClass) { return 4; } break; case JSTYPE_NUMBER: if (to.isPrimitive()) { if (to == Double.TYPE) { return 1; } else if (to != Boolean.TYPE) { return 1 + getSizeRank(to); } } else { if (to == ScriptRuntime.StringClass) { // native numbers are #1-8 return 9; } else if (to == ScriptRuntime.ObjectClass) { return 10; } else if (ScriptRuntime.NumberClass.isAssignableFrom(to)) { // "double" is #1 return 2; } } break; case JSTYPE_STRING: if (to == ScriptRuntime.StringClass) { return 1; } else if (to.isInstance(fromObj)) { return 2; } else if (to.isPrimitive()) { if (to == Character.TYPE) { return 3; } else if (to != Boolean.TYPE) { return 4; } } break; case JSTYPE_JAVA_CLASS: if (to == ScriptRuntime.ClassClass) { return 1; } else if (to == ScriptRuntime.ObjectClass) { return 3; } else if (to == ScriptRuntime.StringClass) { return 4; } break; case JSTYPE_JAVA_OBJECT: case JSTYPE_JAVA_ARRAY: Object javaObj = fromObj; if (javaObj instanceof Wrapper) { javaObj = ((Wrapper)javaObj).unwrap(); } if (to.isInstance(javaObj)) { return CONVERSION_NONTRIVIAL; } if (to == ScriptRuntime.StringClass) { return 2; } else if (to.isPrimitive() && to != Boolean.TYPE) { return (fromCode == JSTYPE_JAVA_ARRAY) ? CONVERSION_NONE : 2 + getSizeRank(to); } break; case JSTYPE_OBJECT: // Other objects takes #1-#3 spots if (to == fromObj.getClass()) { // No conversion required return 1; } if (to.isArray()) { if (fromObj instanceof NativeArray) { // This is a native array conversion to a java array // Array conversions are all equal, and preferable to object // and string conversion, per LC3. return 1; } } else if (to == ScriptRuntime.ObjectClass) { return 2; } else if (to == ScriptRuntime.StringClass) { return 3; } else if (to == ScriptRuntime.DateClass) { if (fromObj instanceof NativeDate) { // This is a native date to java date conversion return 1; } } else if (to.isInterface()) { if (fromObj instanceof Function) { // See comments in coerceType if (to.getMethods().length == 1) { return 1; } } return 11; } else if (to.isPrimitive() && to != Boolean.TYPE) { return 3 + getSizeRank(to); } break; } return CONVERSION_NONE; } static int getSizeRank(Class<?> aType) { if (aType == Double.TYPE) { return 1; } else if (aType == Float.TYPE) { return 2; } else if (aType == Long.TYPE) { return 3; } else if (aType == Integer.TYPE) { return 4; } else if (aType == Short.TYPE) { return 5; } else if (aType == Character.TYPE) { return 6; } else if (aType == Byte.TYPE) { return 7; } else if (aType == Boolean.TYPE) { return CONVERSION_NONE; } else { return 8; } } private static int getJSTypeCode(Object value) { if (value == null) { return JSTYPE_NULL; } else if (value == Undefined.instance) { return JSTYPE_UNDEFINED; } else if (value instanceof String) { return JSTYPE_STRING; } else if (value instanceof Number) { return JSTYPE_NUMBER; } else if (value instanceof Boolean) { return JSTYPE_BOOLEAN; } else if (value instanceof Scriptable) { if (value instanceof NativeJavaClass) { return JSTYPE_JAVA_CLASS; } else if (value instanceof NativeJavaArray) { return JSTYPE_JAVA_ARRAY; } else if (value instanceof Wrapper) { return JSTYPE_JAVA_OBJECT; } else { return JSTYPE_OBJECT; } } else if (value instanceof Class) { return JSTYPE_JAVA_CLASS; } else { Class<?> valueClass = value.getClass(); if (valueClass.isArray()) { return JSTYPE_JAVA_ARRAY; } else { return JSTYPE_JAVA_OBJECT; } } } /** * Not intended for public use. Callers should use the * public API Context.toType. * @deprecated as of 1.5 Release 4 * @see org.mozilla.javascript.Context#jsToJava(Object, Class) */ public static Object coerceType(Class<?> type, Object value) { return coerceTypeImpl(type, value); } /** * Type-munging for field setting and method invocation. * Conforms to LC3 specification */ static Object coerceTypeImpl(Class<?> type, Object value) { if (value != null && value.getClass() == type) { return value; } switch (getJSTypeCode(value)) { case JSTYPE_NULL: // raise error if type.isPrimitive() if (type.isPrimitive()) { reportConversionError(value, type); } return null; case JSTYPE_UNDEFINED: if (type == ScriptRuntime.StringClass || type == ScriptRuntime.ObjectClass) { return "undefined"; } else { reportConversionError("undefined", type); } break; case JSTYPE_BOOLEAN: // Under LC3, only JS Booleans can be coerced into a Boolean value if (type == Boolean.TYPE || type == ScriptRuntime.BooleanClass || type == ScriptRuntime.ObjectClass) { return value; } else if (type == ScriptRuntime.StringClass) { return value.toString(); } else { reportConversionError(value, type); } break; case JSTYPE_NUMBER: if (type == ScriptRuntime.StringClass) { return ScriptRuntime.toString(value); } else if (type == ScriptRuntime.ObjectClass) { return coerceToNumber(Double.TYPE, value); } else if ((type.isPrimitive() && type != Boolean.TYPE) || ScriptRuntime.NumberClass.isAssignableFrom(type)) { return coerceToNumber(type, value); } else { reportConversionError(value, type); } break; case JSTYPE_STRING: if (type == ScriptRuntime.StringClass || type.isInstance(value)) { return value; } else if (type == Character.TYPE || type == ScriptRuntime.CharacterClass) { // Special case for converting a single char string to a // character // Placed here because it applies *only* to JS strings, // not other JS objects converted to strings if (((String)value).length() == 1) { return new Character(((String)value).charAt(0)); } else { return coerceToNumber(type, value); } } else if ((type.isPrimitive() && type != Boolean.TYPE) || ScriptRuntime.NumberClass.isAssignableFrom(type)) { return coerceToNumber(type, value); } else { reportConversionError(value, type); } break; case JSTYPE_JAVA_CLASS: if (value instanceof Wrapper) { value = ((Wrapper)value).unwrap(); } if (type == ScriptRuntime.ClassClass || type == ScriptRuntime.ObjectClass) { return value; } else if (type == ScriptRuntime.StringClass) { return value.toString(); } else { reportConversionError(value, type); } break; case JSTYPE_JAVA_OBJECT: case JSTYPE_JAVA_ARRAY: if (value instanceof Wrapper) { value = ((Wrapper)value).unwrap(); } if (type.isPrimitive()) { if (type == Boolean.TYPE) { reportConversionError(value, type); } return coerceToNumber(type, value); } else { if (type == ScriptRuntime.StringClass) { return value.toString(); } else { if (type.isInstance(value)) { return value; } else { reportConversionError(value, type); } } } break; case JSTYPE_OBJECT: if (type == ScriptRuntime.StringClass) { return ScriptRuntime.toString(value); } else if (type.isPrimitive()) { if (type == Boolean.TYPE) { reportConversionError(value, type); } return coerceToNumber(type, value); } else if (type.isInstance(value)) { return value; } else if (type == ScriptRuntime.DateClass && value instanceof NativeDate) { double time = ((NativeDate)value).getJSTimeValue(); // XXX: This will replace NaN by 0 return new Date((long)time); } else if (type.isArray() && value instanceof NativeArray) { // Make a new java array, and coerce the JS array components // to the target (component) type. NativeArray array = (NativeArray) value; long length = array.getLength(); Class<?> arrayType = type.getComponentType(); Object Result = Array.newInstance(arrayType, (int)length); for (int i = 0 ; i < length ; ++i) { try { Array.set(Result, i, coerceType(arrayType, array.get(i, array))); } catch (EvaluatorException ee) { reportConversionError(value, type); } } return Result; } else if (value instanceof Wrapper) { value = ((Wrapper)value).unwrap(); if (type.isInstance(value)) return value; reportConversionError(value, type); } else if (type.isInterface() && value instanceof Callable) { // Try to use function as implementation of Java interface. // - // XXX: Curently only instances of ScriptableObject are + // XXX: Currently only instances of ScriptableObject are // supported since the resulting interface proxies should // be reused next time conversion is made and generic // Callable has no storage for it. Weak references can // address it but for now use this restriction. if (value instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject)value; Object key = Kit.makeHashKeyFromPair( COERCED_INTERFACE_KEY, type); Object old = so.getAssociatedValue(key); if (old != null) { // Function was already wrapped return old; } Context cx = Context.getContext(); Object glue = InterfaceAdapter.create(cx, type, (Callable)value); // Store for later retrival glue = so.associateValue(key, glue); return glue; } reportConversionError(value, type); } else { reportConversionError(value, type); } break; } return value; } private static Object coerceToNumber(Class<?> type, Object value) { Class<?> valueClass = value.getClass(); // Character if (type == Character.TYPE || type == ScriptRuntime.CharacterClass) { if (valueClass == ScriptRuntime.CharacterClass) { return value; } return new Character((char)toInteger(value, ScriptRuntime.CharacterClass, Character.MIN_VALUE, Character.MAX_VALUE)); } // Double, Float if (type == ScriptRuntime.ObjectClass || type == ScriptRuntime.DoubleClass || type == Double.TYPE) { return valueClass == ScriptRuntime.DoubleClass ? value : new Double(toDouble(value)); } if (type == ScriptRuntime.FloatClass || type == Float.TYPE) { if (valueClass == ScriptRuntime.FloatClass) { return value; } else { double number = toDouble(value); if (Double.isInfinite(number) || Double.isNaN(number) || number == 0.0) { return new Float((float)number); } else { double absNumber = Math.abs(number); if (absNumber < Float.MIN_VALUE) { return new Float((number > 0.0) ? +0.0 : -0.0); } else if (absNumber > Float.MAX_VALUE) { return new Float((number > 0.0) ? Float.POSITIVE_INFINITY : Float.NEGATIVE_INFINITY); } else { return new Float((float)number); } } } } // Integer, Long, Short, Byte if (type == ScriptRuntime.IntegerClass || type == Integer.TYPE) { if (valueClass == ScriptRuntime.IntegerClass) { return value; } else { return new Integer((int)toInteger(value, ScriptRuntime.IntegerClass, Integer.MIN_VALUE, Integer.MAX_VALUE)); } } if (type == ScriptRuntime.LongClass || type == Long.TYPE) { if (valueClass == ScriptRuntime.LongClass) { return value; } else { /* Long values cannot be expressed exactly in doubles. * We thus use the largest and smallest double value that * has a value expressible as a long value. We build these * numerical values from their hexidecimal representations * to avoid any problems caused by attempting to parse a * decimal representation. */ final double max = Double.longBitsToDouble(0x43dfffffffffffffL); final double min = Double.longBitsToDouble(0xc3e0000000000000L); return new Long(toInteger(value, ScriptRuntime.LongClass, min, max)); } } if (type == ScriptRuntime.ShortClass || type == Short.TYPE) { if (valueClass == ScriptRuntime.ShortClass) { return value; } else { return new Short((short)toInteger(value, ScriptRuntime.ShortClass, Short.MIN_VALUE, Short.MAX_VALUE)); } } if (type == ScriptRuntime.ByteClass || type == Byte.TYPE) { if (valueClass == ScriptRuntime.ByteClass) { return value; } else { return new Byte((byte)toInteger(value, ScriptRuntime.ByteClass, Byte.MIN_VALUE, Byte.MAX_VALUE)); } } return new Double(toDouble(value)); } private static double toDouble(Object value) { if (value instanceof Number) { return ((Number)value).doubleValue(); } else if (value instanceof String) { return ScriptRuntime.toNumber((String)value); } else if (value instanceof Scriptable) { if (value instanceof Wrapper) { // XXX: optimize tail-recursion? return toDouble(((Wrapper)value).unwrap()); } else { return ScriptRuntime.toNumber(value); } } else { Method meth; try { meth = value.getClass().getMethod("doubleValue", (Class [])null); } catch (NoSuchMethodException e) { meth = null; } catch (SecurityException e) { meth = null; } if (meth != null) { try { return ((Number)meth.invoke(value, (Object [])null)).doubleValue(); } catch (IllegalAccessException e) { // XXX: ignore, or error message? reportConversionError(value, Double.TYPE); } catch (InvocationTargetException e) { // XXX: ignore, or error message? reportConversionError(value, Double.TYPE); } } return ScriptRuntime.toNumber(value.toString()); } } private static long toInteger(Object value, Class<?> type, double min, double max) { double d = toDouble(value); if (Double.isInfinite(d) || Double.isNaN(d)) { // Convert to string first, for more readable message reportConversionError(ScriptRuntime.toString(value), type); } if (d > 0.0) { d = Math.floor(d); } else { d = Math.ceil(d); } if (d < min || d > max) { // Convert to string first, for more readable message reportConversionError(ScriptRuntime.toString(value), type); } return (long)d; } static void reportConversionError(Object value, Class<?> type) { // It uses String.valueOf(value), not value.toString() since // value can be null, bug 282447. throw Context.reportRuntimeError2( "msg.conversion.not.allowed", String.valueOf(value), JavaMembers.javaSignature(type)); } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeBoolean(isAdapter); if (isAdapter) { if (adapter_writeAdapterObject == null) { throw new IOException(); } Object[] args = { javaObject, out }; try { adapter_writeAdapterObject.invoke(null, args); } catch (Exception ex) { throw new IOException(); } } else { out.writeObject(javaObject); } if (staticType != null) { out.writeObject(staticType.getClass().getName()); } else { out.writeObject(null); } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); isAdapter = in.readBoolean(); if (isAdapter) { if (adapter_readAdapterObject == null) throw new ClassNotFoundException(); Object[] args = { this, in }; try { javaObject = adapter_readAdapterObject.invoke(null, args); } catch (Exception ex) { throw new IOException(); } } else { javaObject = in.readObject(); } String className = (String)in.readObject(); if (className != null) { staticType = Class.forName(className); } else { staticType = null; } initMembers(); } /** * The prototype of this object. */ protected Scriptable prototype; /** * The parent scope of this object. */ protected Scriptable parent; protected transient Object javaObject; protected transient Class<?> staticType; protected transient JavaMembers members; private transient Map<String,FieldAndMethods> fieldAndMethods; private transient boolean isAdapter; private static final Object COERCED_INTERFACE_KEY = new Object(); private static Method adapter_writeAdapterObject; private static Method adapter_readAdapterObject; static { // Reflection in java is verbose Class<?>[] sig2 = new Class[2]; Class<?> cl = Kit.classOrNull("org.mozilla.javascript.JavaAdapter"); if (cl != null) { try { sig2[0] = ScriptRuntime.ObjectClass; sig2[1] = Kit.classOrNull("java.io.ObjectOutputStream"); adapter_writeAdapterObject = cl.getMethod("writeAdapterObject", sig2); sig2[0] = ScriptRuntime.ScriptableClass; sig2[1] = Kit.classOrNull("java.io.ObjectInputStream"); adapter_readAdapterObject = cl.getMethod("readAdapterObject", sig2); } catch (Exception ex) { adapter_writeAdapterObject = null; adapter_readAdapterObject = null; } } } }
true
true
static Object coerceTypeImpl(Class<?> type, Object value) { if (value != null && value.getClass() == type) { return value; } switch (getJSTypeCode(value)) { case JSTYPE_NULL: // raise error if type.isPrimitive() if (type.isPrimitive()) { reportConversionError(value, type); } return null; case JSTYPE_UNDEFINED: if (type == ScriptRuntime.StringClass || type == ScriptRuntime.ObjectClass) { return "undefined"; } else { reportConversionError("undefined", type); } break; case JSTYPE_BOOLEAN: // Under LC3, only JS Booleans can be coerced into a Boolean value if (type == Boolean.TYPE || type == ScriptRuntime.BooleanClass || type == ScriptRuntime.ObjectClass) { return value; } else if (type == ScriptRuntime.StringClass) { return value.toString(); } else { reportConversionError(value, type); } break; case JSTYPE_NUMBER: if (type == ScriptRuntime.StringClass) { return ScriptRuntime.toString(value); } else if (type == ScriptRuntime.ObjectClass) { return coerceToNumber(Double.TYPE, value); } else if ((type.isPrimitive() && type != Boolean.TYPE) || ScriptRuntime.NumberClass.isAssignableFrom(type)) { return coerceToNumber(type, value); } else { reportConversionError(value, type); } break; case JSTYPE_STRING: if (type == ScriptRuntime.StringClass || type.isInstance(value)) { return value; } else if (type == Character.TYPE || type == ScriptRuntime.CharacterClass) { // Special case for converting a single char string to a // character // Placed here because it applies *only* to JS strings, // not other JS objects converted to strings if (((String)value).length() == 1) { return new Character(((String)value).charAt(0)); } else { return coerceToNumber(type, value); } } else if ((type.isPrimitive() && type != Boolean.TYPE) || ScriptRuntime.NumberClass.isAssignableFrom(type)) { return coerceToNumber(type, value); } else { reportConversionError(value, type); } break; case JSTYPE_JAVA_CLASS: if (value instanceof Wrapper) { value = ((Wrapper)value).unwrap(); } if (type == ScriptRuntime.ClassClass || type == ScriptRuntime.ObjectClass) { return value; } else if (type == ScriptRuntime.StringClass) { return value.toString(); } else { reportConversionError(value, type); } break; case JSTYPE_JAVA_OBJECT: case JSTYPE_JAVA_ARRAY: if (value instanceof Wrapper) { value = ((Wrapper)value).unwrap(); } if (type.isPrimitive()) { if (type == Boolean.TYPE) { reportConversionError(value, type); } return coerceToNumber(type, value); } else { if (type == ScriptRuntime.StringClass) { return value.toString(); } else { if (type.isInstance(value)) { return value; } else { reportConversionError(value, type); } } } break; case JSTYPE_OBJECT: if (type == ScriptRuntime.StringClass) { return ScriptRuntime.toString(value); } else if (type.isPrimitive()) { if (type == Boolean.TYPE) { reportConversionError(value, type); } return coerceToNumber(type, value); } else if (type.isInstance(value)) { return value; } else if (type == ScriptRuntime.DateClass && value instanceof NativeDate) { double time = ((NativeDate)value).getJSTimeValue(); // XXX: This will replace NaN by 0 return new Date((long)time); } else if (type.isArray() && value instanceof NativeArray) { // Make a new java array, and coerce the JS array components // to the target (component) type. NativeArray array = (NativeArray) value; long length = array.getLength(); Class<?> arrayType = type.getComponentType(); Object Result = Array.newInstance(arrayType, (int)length); for (int i = 0 ; i < length ; ++i) { try { Array.set(Result, i, coerceType(arrayType, array.get(i, array))); } catch (EvaluatorException ee) { reportConversionError(value, type); } } return Result; } else if (value instanceof Wrapper) { value = ((Wrapper)value).unwrap(); if (type.isInstance(value)) return value; reportConversionError(value, type); } else if (type.isInterface() && value instanceof Callable) { // Try to use function as implementation of Java interface. // // XXX: Curently only instances of ScriptableObject are // supported since the resulting interface proxies should // be reused next time conversion is made and generic // Callable has no storage for it. Weak references can // address it but for now use this restriction. if (value instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject)value; Object key = Kit.makeHashKeyFromPair( COERCED_INTERFACE_KEY, type); Object old = so.getAssociatedValue(key); if (old != null) { // Function was already wrapped return old; } Context cx = Context.getContext(); Object glue = InterfaceAdapter.create(cx, type, (Callable)value); // Store for later retrival glue = so.associateValue(key, glue); return glue; } reportConversionError(value, type); } else { reportConversionError(value, type); } break; } return value; }
static Object coerceTypeImpl(Class<?> type, Object value) { if (value != null && value.getClass() == type) { return value; } switch (getJSTypeCode(value)) { case JSTYPE_NULL: // raise error if type.isPrimitive() if (type.isPrimitive()) { reportConversionError(value, type); } return null; case JSTYPE_UNDEFINED: if (type == ScriptRuntime.StringClass || type == ScriptRuntime.ObjectClass) { return "undefined"; } else { reportConversionError("undefined", type); } break; case JSTYPE_BOOLEAN: // Under LC3, only JS Booleans can be coerced into a Boolean value if (type == Boolean.TYPE || type == ScriptRuntime.BooleanClass || type == ScriptRuntime.ObjectClass) { return value; } else if (type == ScriptRuntime.StringClass) { return value.toString(); } else { reportConversionError(value, type); } break; case JSTYPE_NUMBER: if (type == ScriptRuntime.StringClass) { return ScriptRuntime.toString(value); } else if (type == ScriptRuntime.ObjectClass) { return coerceToNumber(Double.TYPE, value); } else if ((type.isPrimitive() && type != Boolean.TYPE) || ScriptRuntime.NumberClass.isAssignableFrom(type)) { return coerceToNumber(type, value); } else { reportConversionError(value, type); } break; case JSTYPE_STRING: if (type == ScriptRuntime.StringClass || type.isInstance(value)) { return value; } else if (type == Character.TYPE || type == ScriptRuntime.CharacterClass) { // Special case for converting a single char string to a // character // Placed here because it applies *only* to JS strings, // not other JS objects converted to strings if (((String)value).length() == 1) { return new Character(((String)value).charAt(0)); } else { return coerceToNumber(type, value); } } else if ((type.isPrimitive() && type != Boolean.TYPE) || ScriptRuntime.NumberClass.isAssignableFrom(type)) { return coerceToNumber(type, value); } else { reportConversionError(value, type); } break; case JSTYPE_JAVA_CLASS: if (value instanceof Wrapper) { value = ((Wrapper)value).unwrap(); } if (type == ScriptRuntime.ClassClass || type == ScriptRuntime.ObjectClass) { return value; } else if (type == ScriptRuntime.StringClass) { return value.toString(); } else { reportConversionError(value, type); } break; case JSTYPE_JAVA_OBJECT: case JSTYPE_JAVA_ARRAY: if (value instanceof Wrapper) { value = ((Wrapper)value).unwrap(); } if (type.isPrimitive()) { if (type == Boolean.TYPE) { reportConversionError(value, type); } return coerceToNumber(type, value); } else { if (type == ScriptRuntime.StringClass) { return value.toString(); } else { if (type.isInstance(value)) { return value; } else { reportConversionError(value, type); } } } break; case JSTYPE_OBJECT: if (type == ScriptRuntime.StringClass) { return ScriptRuntime.toString(value); } else if (type.isPrimitive()) { if (type == Boolean.TYPE) { reportConversionError(value, type); } return coerceToNumber(type, value); } else if (type.isInstance(value)) { return value; } else if (type == ScriptRuntime.DateClass && value instanceof NativeDate) { double time = ((NativeDate)value).getJSTimeValue(); // XXX: This will replace NaN by 0 return new Date((long)time); } else if (type.isArray() && value instanceof NativeArray) { // Make a new java array, and coerce the JS array components // to the target (component) type. NativeArray array = (NativeArray) value; long length = array.getLength(); Class<?> arrayType = type.getComponentType(); Object Result = Array.newInstance(arrayType, (int)length); for (int i = 0 ; i < length ; ++i) { try { Array.set(Result, i, coerceType(arrayType, array.get(i, array))); } catch (EvaluatorException ee) { reportConversionError(value, type); } } return Result; } else if (value instanceof Wrapper) { value = ((Wrapper)value).unwrap(); if (type.isInstance(value)) return value; reportConversionError(value, type); } else if (type.isInterface() && value instanceof Callable) { // Try to use function as implementation of Java interface. // // XXX: Currently only instances of ScriptableObject are // supported since the resulting interface proxies should // be reused next time conversion is made and generic // Callable has no storage for it. Weak references can // address it but for now use this restriction. if (value instanceof ScriptableObject) { ScriptableObject so = (ScriptableObject)value; Object key = Kit.makeHashKeyFromPair( COERCED_INTERFACE_KEY, type); Object old = so.getAssociatedValue(key); if (old != null) { // Function was already wrapped return old; } Context cx = Context.getContext(); Object glue = InterfaceAdapter.create(cx, type, (Callable)value); // Store for later retrival glue = so.associateValue(key, glue); return glue; } reportConversionError(value, type); } else { reportConversionError(value, type); } break; } return value; }
diff --git a/test/freemail/wot/IdentityMatcherTest.java b/test/freemail/wot/IdentityMatcherTest.java index 33844ce..7fe4cbf 100644 --- a/test/freemail/wot/IdentityMatcherTest.java +++ b/test/freemail/wot/IdentityMatcherTest.java @@ -1,87 +1,87 @@ /* * IdentityMatcherTest.java * This file is part of Freemail * Copyright (C) 2011 Martin Nyhus * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package freemail.wot; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import freemail.wot.Identity; import freemail.wot.OwnIdentity; import freemail.wot.WoTConnection; import freenet.pluginmanager.PluginNotFoundException; import junit.framework.TestCase; public class IdentityMatcherTest extends TestCase { private static final Identity identity = new Identity("D3MrAR-AVMqKJRjXnpKW2guW9z1mw5GZ9BB15mYVkVc", "SSK@D3MrAR-AVMqKJRjXnpKW2guW9z1mw5GZ9BB15mYVkVc,xgddjFHx2S~5U6PeFkwqO5V~1gZngFLoM-xaoMKSBI8,AQACAAE", "zidel"); public void testFullIdentityMatch() throws PluginNotFoundException { IdentityMatcher identityMatcher = new IdentityMatcher(new FakeWoTConnection()); String recipient = identity.getNickname() + "@" + identity.getIdentityID() + ".freemail"; Set<String> recipients = new HashSet<String>(); recipients.add(recipient); EnumSet<IdentityMatcher.MatchMethod> set = EnumSet.allOf(IdentityMatcher.MatchMethod.class); Map<String, List<Identity>> matches = identityMatcher.matchIdentities(recipients, identity.getIdentityID(), set); assert (matches.size() == 1); - assert (matches.get(recipient).equals(identity)); + assert (matches.get(recipient).get(0).equals(identity)); } private class FakeWoTConnection implements WoTConnection { @Override public List<OwnIdentity> getAllOwnIdentities() { return new LinkedList<OwnIdentity>(); } @Override public Set<Identity> getAllTrustedIdentities(String trusterId) { Set<Identity> set = new HashSet<Identity>(); set.add(identity); return set; } @Override public Set<Identity> getAllUntrustedIdentities(String trusterId) { return new HashSet<Identity>(); } @Override public Identity getIdentity(String identityID, String trusterID) { throw new UnsupportedOperationException(); } @Override public boolean setProperty(String identityID, String key, String value) { throw new UnsupportedOperationException(); } @Override public String getProperty(String identityID, String key) { throw new UnsupportedOperationException(); } } }
true
true
public void testFullIdentityMatch() throws PluginNotFoundException { IdentityMatcher identityMatcher = new IdentityMatcher(new FakeWoTConnection()); String recipient = identity.getNickname() + "@" + identity.getIdentityID() + ".freemail"; Set<String> recipients = new HashSet<String>(); recipients.add(recipient); EnumSet<IdentityMatcher.MatchMethod> set = EnumSet.allOf(IdentityMatcher.MatchMethod.class); Map<String, List<Identity>> matches = identityMatcher.matchIdentities(recipients, identity.getIdentityID(), set); assert (matches.size() == 1); assert (matches.get(recipient).equals(identity)); }
public void testFullIdentityMatch() throws PluginNotFoundException { IdentityMatcher identityMatcher = new IdentityMatcher(new FakeWoTConnection()); String recipient = identity.getNickname() + "@" + identity.getIdentityID() + ".freemail"; Set<String> recipients = new HashSet<String>(); recipients.add(recipient); EnumSet<IdentityMatcher.MatchMethod> set = EnumSet.allOf(IdentityMatcher.MatchMethod.class); Map<String, List<Identity>> matches = identityMatcher.matchIdentities(recipients, identity.getIdentityID(), set); assert (matches.size() == 1); assert (matches.get(recipient).get(0).equals(identity)); }
diff --git a/src/cz/muni/stanse/automatonchecker/CheckerErrorBuilder.java b/src/cz/muni/stanse/automatonchecker/CheckerErrorBuilder.java index 8bd6305..ccae035 100644 --- a/src/cz/muni/stanse/automatonchecker/CheckerErrorBuilder.java +++ b/src/cz/muni/stanse/automatonchecker/CheckerErrorBuilder.java @@ -1,90 +1,98 @@ /** * @file CheckerErrorBuilder.java * @brief Implements final class CheckerErrorBuilder which is responsible to * compute all checker errors which can be translated from automata * states at PaternLocations. * * Copyright (c) 2008-2009 Marek Trtik * * Licensed under GPLv2. */ package cz.muni.stanse.automatonchecker; import cz.muni.stanse.checker.CheckerError; import cz.muni.stanse.checker.ErrorTrace; import cz.muni.stanse.utils.CFGTraversal; import java.util.HashMap; import java.util.LinkedList; /** * @brief Provides static method buildErrorList which compute the checker-errors * from automata states at PattenLocations assigned to matching source * code locacions by use of error transition rules defined in XML * automata definition file. * * Class is not intended to be instantiated. * * @see cz.muni.stanse.checker.CheckerError * @see cz.muni.stanse.automatonchecker.AutomatonChecker */ final class CheckerErrorBuilder { // package-private section /** * @brief Computes a list of all checker-errors, which can be recognized by * error transition rules (defined in XML automata definition file) * from automata states at PattenLocations assigned to matching * source code locacions. * * @param edgeLocationDictionary Dictionary, which provides mapping from * CFGNodes (i.e. reference to souce code * locations) to related PatternLocations. * @return List of checker-errors recognized from automata states at * PatternLocations. */ static LinkedList<CheckerError> buildErrorList(final HashMap<cz.muni.stanse.codestructures.CFGNode, PatternLocation> edgeLocationDictionary) { final LinkedList<CheckerError> errorsList = new LinkedList<CheckerError>(); for (PatternLocation location : edgeLocationDictionary.values()) errorsList.addAll(buildErrorsInLocation(location, edgeLocationDictionary)); return errorsList; } // private section private static LinkedList<CheckerError> buildErrorsInLocation( final PatternLocation location, final HashMap<cz.muni.stanse.codestructures.CFGNode,PatternLocation> edgeLocationDictionary) { final LinkedList<CheckerError> errorsList = new LinkedList<CheckerError>(); for (ErrorRule rule : location.getErrorRules()) if (rule.checkForError(location.getProcessedAutomataStates())) { final LinkedList<ErrorTrace> traces = CFGTraversal.traverseCFGPathsBackward( location.getCFG(),location.getCFGreferenceNode(), (new ErrorTracesListCreator(rule,edgeLocationDictionary, location.getCFGreferenceNode(), location.getCFG()))).getErrorTracesList(); + // Next condition eliminates cyclic dependances of two + // error locations (diferent). These locations have same error + // rule and theirs methods checkForError() returns true (so they + // are both error locations). But their cyclic dependancy + // disables to find starting nodes of theirs error traces -> + // both error traces returned will be empty. + if (traces.isEmpty()) + continue; final String shortDesc = rule.getErrorDescription(); final String fullDesc = "in function '" + location.getCFG().getFunctionName() + "' " + shortDesc + " [traces: " + traces.size() + "]"; errorsList.add(new CheckerError(shortDesc,fullDesc, rule.getErrorLevel(),traces)); } return errorsList; } private CheckerErrorBuilder() { } }
true
true
private static LinkedList<CheckerError> buildErrorsInLocation( final PatternLocation location, final HashMap<cz.muni.stanse.codestructures.CFGNode,PatternLocation> edgeLocationDictionary) { final LinkedList<CheckerError> errorsList = new LinkedList<CheckerError>(); for (ErrorRule rule : location.getErrorRules()) if (rule.checkForError(location.getProcessedAutomataStates())) { final LinkedList<ErrorTrace> traces = CFGTraversal.traverseCFGPathsBackward( location.getCFG(),location.getCFGreferenceNode(), (new ErrorTracesListCreator(rule,edgeLocationDictionary, location.getCFGreferenceNode(), location.getCFG()))).getErrorTracesList(); final String shortDesc = rule.getErrorDescription(); final String fullDesc = "in function '" + location.getCFG().getFunctionName() + "' " + shortDesc + " [traces: " + traces.size() + "]"; errorsList.add(new CheckerError(shortDesc,fullDesc, rule.getErrorLevel(),traces)); } return errorsList; }
private static LinkedList<CheckerError> buildErrorsInLocation( final PatternLocation location, final HashMap<cz.muni.stanse.codestructures.CFGNode,PatternLocation> edgeLocationDictionary) { final LinkedList<CheckerError> errorsList = new LinkedList<CheckerError>(); for (ErrorRule rule : location.getErrorRules()) if (rule.checkForError(location.getProcessedAutomataStates())) { final LinkedList<ErrorTrace> traces = CFGTraversal.traverseCFGPathsBackward( location.getCFG(),location.getCFGreferenceNode(), (new ErrorTracesListCreator(rule,edgeLocationDictionary, location.getCFGreferenceNode(), location.getCFG()))).getErrorTracesList(); // Next condition eliminates cyclic dependances of two // error locations (diferent). These locations have same error // rule and theirs methods checkForError() returns true (so they // are both error locations). But their cyclic dependancy // disables to find starting nodes of theirs error traces -> // both error traces returned will be empty. if (traces.isEmpty()) continue; final String shortDesc = rule.getErrorDescription(); final String fullDesc = "in function '" + location.getCFG().getFunctionName() + "' " + shortDesc + " [traces: " + traces.size() + "]"; errorsList.add(new CheckerError(shortDesc,fullDesc, rule.getErrorLevel(),traces)); } return errorsList; }
diff --git a/main/src/com/google/refine/model/recon/ReconConfig.java b/main/src/com/google/refine/model/recon/ReconConfig.java index aacef0b7..43b57d74 100644 --- a/main/src/com/google/refine/model/recon/ReconConfig.java +++ b/main/src/com/google/refine/model/recon/ReconConfig.java @@ -1,95 +1,95 @@ package com.google.refine.model.recon; import java.io.Writer; import java.lang.reflect.Method; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; import org.json.JSONException; import org.json.JSONObject; import org.json.JSONWriter; import com.google.refine.Jsonizable; import com.google.refine.model.Cell; import com.google.refine.model.Project; import com.google.refine.model.Recon; import com.google.refine.model.Row; import edu.mit.simile.butterfly.ButterflyModule; abstract public class ReconConfig implements Jsonizable { static final public Map<String, List<Class<? extends ReconConfig>>> s_opNameToClass = new HashMap<String, List<Class<? extends ReconConfig>>>(); static final public Map<Class<? extends ReconConfig>, String> s_opClassToName = new HashMap<Class<? extends ReconConfig>, String>(); static public void registerReconConfig(ButterflyModule module, String name, Class<? extends ReconConfig> klass) { String key = module.getName() + "/" + name; s_opClassToName.put(klass, key); List<Class<? extends ReconConfig>> classes = s_opNameToClass.get(key); if (classes == null) { classes = new LinkedList<Class<? extends ReconConfig>>(); s_opNameToClass.put(key, classes); } classes.add(klass); } static public ReconConfig reconstruct(JSONObject obj) throws Exception { try { String mode = obj.getString("mode"); // Backward compatibility - if ("extend".equals(mode) || "strict".equals("mode")) { + if ("extend".equals(mode) || "strict".equals(mode)) { mode = "freebase/" + mode; } else if ("heuristic".equals(mode)) { mode = "core/standard-service"; // legacy } else if (!mode.contains("/")) { mode = "core/" + mode; } List<Class<? extends ReconConfig>> classes = s_opNameToClass.get(mode); if (classes != null && classes.size() > 0) { Class<? extends ReconConfig> klass = classes.get(classes.size() - 1); Method reconstruct = klass.getMethod("reconstruct", JSONObject.class); if (reconstruct != null) { return (ReconConfig) reconstruct.invoke(null, obj); } } } catch (Exception e) { e.printStackTrace(); } return null; } abstract public int getBatchSize(); abstract public String getBriefDescription(Project project, String columnName); abstract public ReconJob createJob( Project project, int rowIndex, Row row, String columnName, Cell cell ); abstract public List<Recon> batchRecon(List<ReconJob> jobs, long historyEntryID); abstract public Recon createNewRecon(long historyEntryID); public void save(Writer writer) { JSONWriter jsonWriter = new JSONWriter(writer); try { write(jsonWriter, new Properties()); } catch (JSONException e) { e.printStackTrace(); } } }
true
true
static public ReconConfig reconstruct(JSONObject obj) throws Exception { try { String mode = obj.getString("mode"); // Backward compatibility if ("extend".equals(mode) || "strict".equals("mode")) { mode = "freebase/" + mode; } else if ("heuristic".equals(mode)) { mode = "core/standard-service"; // legacy } else if (!mode.contains("/")) { mode = "core/" + mode; } List<Class<? extends ReconConfig>> classes = s_opNameToClass.get(mode); if (classes != null && classes.size() > 0) { Class<? extends ReconConfig> klass = classes.get(classes.size() - 1); Method reconstruct = klass.getMethod("reconstruct", JSONObject.class); if (reconstruct != null) { return (ReconConfig) reconstruct.invoke(null, obj); } } } catch (Exception e) { e.printStackTrace(); } return null; }
static public ReconConfig reconstruct(JSONObject obj) throws Exception { try { String mode = obj.getString("mode"); // Backward compatibility if ("extend".equals(mode) || "strict".equals(mode)) { mode = "freebase/" + mode; } else if ("heuristic".equals(mode)) { mode = "core/standard-service"; // legacy } else if (!mode.contains("/")) { mode = "core/" + mode; } List<Class<? extends ReconConfig>> classes = s_opNameToClass.get(mode); if (classes != null && classes.size() > 0) { Class<? extends ReconConfig> klass = classes.get(classes.size() - 1); Method reconstruct = klass.getMethod("reconstruct", JSONObject.class); if (reconstruct != null) { return (ReconConfig) reconstruct.invoke(null, obj); } } } catch (Exception e) { e.printStackTrace(); } return null; }
diff --git a/MipsCompiler/src/mainCompiler.java b/MipsCompiler/src/mainCompiler.java index 0c28fde..7e7bbe2 100644 --- a/MipsCompiler/src/mainCompiler.java +++ b/MipsCompiler/src/mainCompiler.java @@ -1,703 +1,703 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.Scanner; import java.util.regex.*; import java.lang.String; /** * * @author Troxel */ public class mainCompiler { /** * @param args * the command line arguments */ public static void main(String[] args) { // TODO code application logic here String labelRegex = "^[a-zA-Z_]+:"; Pattern label = Pattern.compile(labelRegex); Pattern register = Pattern.compile("^\\$[0-9]?[0-9]"); HashMap labelLoc = new HashMap(); int instCount = 0; int byteLine = 0; int lastByte = 0; int maxMem = 0; ArrayList<int[]> memplacement = new ArrayList<int[]>(); String filename = ""; try { filename = args[0]; } catch (Exception e) { Scanner consolein = new Scanner(System.in); System.out .println("Give the path or filename of source code to compile:"); filename = consolein.next(); consolein.close(); } boolean data = false; File infile = new File(filename); String[] tempParams = infile.getName().split("\\.(?=[^\\.]+$)"); String temp = tempParams[0]; File exeFile = new File(temp + ".exe.mif"); File memFile = new File(temp + ".mem.mif"); // Create file if it doesn't already exist try { exeFile.createNewFile(); Scanner input = new Scanner(infile); FileWriter fw; FileWriter memfw; try { String instruction = ""; int code = 0; ArrayList<String> instructionLines = new ArrayList<String>(); ArrayList<String> origInstruction = new ArrayList<String>(); ArrayList<String[]> Symbols = new ArrayList<String[]>(); String parameters = ""; String[] params; int index; int lineNum = 0; // initialize memory file writers memfw = new FileWriter(memFile); PrintWriter mempw = new PrintWriter(memfw); mempw.print("WIDTH = 32; \r\n-- data width \r\n" + "DEPTH = 256; \r\n-- number of memory slots \r\n" + "-- thus, the total size is 256 x 32 bits\r\n" + "ADDRESS_RADIX = HEX; \r\nDATA_RADIX = HEX; \r\n" + "CONTENT BEGIN \r\n"); // initialize executable file writers fw = new FileWriter(exeFile); PrintWriter pw = new PrintWriter(fw); pw.print("WIDTH = 32; \r\n-- data width \r\n" + "DEPTH = 256; \r\n-- number of memory slots \r\n" + "-- thus, the total size is 256 x 32 bits\r\n" + "ADDRESS_RADIX = HEX; \r\nDATA_RADIX = HEX; \r\n" + "CONTENT BEGIN \r\n"); code = 0; // start reading the file while (input.hasNextLine()) { params = input.nextLine().split("#"); if (params.length > 0) { instruction = params[0].trim(); } else { instruction = ""; } if (instruction.contains(".data")) { data = true; lineNum++; instCount++; byteLine = 0; } if (!data) { if (instruction.contains(":")) { params = instruction.split(":"); index = ContainsSymbol(Symbols, params[0].trim()); if (index > -1) { if (Symbols.get(index)[1].contains("-1")) { Symbols.set( index, new String[] { params[0].trim(), String.valueOf(lineNum * 4) }); } else { System.out.println("Symbol error (Line: " + lineNum + "): Symbol already exists."); } } else { Symbols.add(new String[] { params[0], String.valueOf(lineNum * 4) }); } if (params.length > 1) { instruction = params[1].trim(); } else { instruction = ""; } } if (instruction.length() > 0) { instructionLines.add(instruction); origInstruction.add(instruction); parameters = instruction.split(" ", 2)[1].trim(); params = parameters.split(","); for (int i = 0; i < params.length; i++) { if (!(params[i].trim().startsWith("$")) && !isNumber(params[i].trim())) { index = ContainsSymbol(Symbols, params[i].trim()); if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1] .contains("-1")) { instructionLines .set(lineNum, instructionLines .get(lineNum) .replace( Symbols.get(index)[0], Symbols.get(index)[1])); } } else { Symbols.add(new String[] { params[i].trim(), "-1" }); } } } lineNum++; instCount++; } } else { if (instruction.contains(":")) { params = instruction.split(":"); index = ContainsSymbol(Symbols, params[0].trim()); if (index > -1) { if (Symbols.get(index)[1].contains("-1")) { Symbols.set(index, new String[] { params[0].trim(), String.valueOf(byteLine/4) }); } else { System.out.println("Symbol error (Line: " + lineNum + "): Symbol already exists."); } } else { Symbols.add(new String[] { params[0], String.valueOf(byteLine/4) }); } if (params.length > 1) { instruction = params[1].trim(); } else { instruction = ""; } } if (instruction.length() > 0) { params = instruction.split(" ", 2); switch (params[0]) { case ".ascii": temp = params[0].replaceAll("\"", ""); for (int i = 0; i < temp.length(); i++) { code |= ((byte) temp.charAt(i)) << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } } if (byteLine % 4 != 0) { memplacement.add(new int[] { byteLine/4, code }); code = 0; lastByte = byteLine/4; } break; case ".byte": code |= Integer.valueOf(params[1].trim()) .intValue() << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } break; case ".word": code = Integer.valueOf(params[1].trim()).intValue(); byteLine += 4; memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; break; case ".asciiz": temp = params[1].replaceAll("\"", "") + ((char) (0)); for (int i = 0; i < temp.length(); i++) { code |= ((byte) temp.charAt(i)) << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } } break; case "org": memplacement.add(new int[] { byteLine - byteLine % 4, code }); code = 0; byteLine = Integer.valueOf(params[1].trim()) .intValue(); break; default: } } } } if (byteLine % 4 != 0 && byteLine - 4 != lastByte) { memplacement.add(new int[] { byteLine - (byteLine % 4), code }); code = 0; } for (int i = 0; i <= 256; i = i + 4) { mempw.printf("%02x : %08x; -- %s\r\n", i / 4, GetWord(memplacement, i), i); } for (lineNum = 0; lineNum < instructionLines.size(); lineNum++) { instruction = instructionLines.get(lineNum); System.out.println(origInstruction.get(lineNum)); parameters = instruction.split(" ", 2)[1].trim(); instruction = instruction.split(" ", 2)[0].trim(); params = parameters.split(","); for (int i = 0; i < params.length; i++) { if (!(params[i].trim().startsWith("$")) && !isNumber(params[i].trim())) { if (params[i].contains("(")) { index = ContainsSymbol(Symbols, params[i] .trim().split("\\(")[0]); if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1].contains("-1")) { params[i] = params[i].replace( Symbols.get(index)[0], Symbols.get(index)[1]); } } else { System.out.println("ERROR Symbol " + params[i].trim() + " does not exist."); } if (!(params[i].trim().split("\\(")[1] .startsWith("$")) && !isNumber(params[i].trim().split( "\\(")[1].replace(")", ""))) { index = ContainsSymbol(Symbols, params[i] .trim().split("\\(")[1].replace( ")", "")); } } else { index = ContainsSymbol(Symbols, params[i].trim()); } if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1].contains("-1")) { params[i] = params[i].replace( Symbols.get(index)[0], Symbols.get(index)[1]); } } else { System.out .println("ERROR Symbol " + params[i].trim() + " does not exist."); } } } try { code = 0; switch (instruction) { // R-Type case "add": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x20; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "and": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x24; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jalr": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= 0x09; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jr": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= 0x08; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "nor": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x27; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "or": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sll": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 6; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sllv": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 21; code |= 0x04; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "slt": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x2A; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "srl": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[2].trim()) - .intValue() << 5; + .intValue() << 6; code |= 0x02; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sub": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x22; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "xor": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; // I-Type case "addi": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 8 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "andi": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 12 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "beq": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= (Integer.valueOf(params[2].trim()) .intValue()/4 - lineNum -1) & 0xFFFF; code |= 4 << 26; // origInstruction = origInstruction.split(" ")[0] + // origInstruction.split(" ")[1] + // origInstruction.split(" ")[2] + // (labelLoc.get(origInstruction.split(" ")[3])).toString(); pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "bne": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= (Integer.valueOf(params[2].trim()) .intValue()/4 - lineNum -1) & 0xFFFF; code |= 0x05 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lb": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x20 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lh": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x21 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lui": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x0F << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "li": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= (byte) (Integer.valueOf(params[1].trim()) .intValue() & 0xFF); code |= 0x0F << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); lineNum++; code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= (byte) ((Integer.valueOf(params[1].trim()) .intValue() >> 8) & 0xFF); code |= 0x0D << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lw": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].trim().split("\\(")[0]) .intValue(); code |= Integer.valueOf( params[1].trim().split("\\(")[1].replace( ")", "").replace("$", "")) .intValue() << 21; code |= 0x23 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "ori": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 0x0D << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sw": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].trim().split("\\(")[0]) .intValue(); code |= Integer.valueOf( params[1].trim().split("\\(")[1].replace( ")", "").replace("$", "")) .intValue() << 21; code |= 0x2B << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; // J-Type case "j": code = Integer.valueOf(params[0].trim()).intValue() << 2; code |= 2 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jal": code = Integer.valueOf(params[0].trim()).intValue() << 2; code |= 3 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "nop": code = 0; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); default: if (!(instruction.startsWith("#"))) { System.out.println("Error reading instruction"); } } } catch (Exception e) { e.printStackTrace(); System.out.println("Syntax Error Line " + lineNum); } } // Finish the files pw.print("END;\r\n"); mempw.print("END;\r\n"); // close the writers pw.close(); mempw.close(); try { memfw.close(); fw.close(); } catch (IOException e) { System.out.println("Could not Close FileWriter"); } } catch (IOException e) { System.out.println("Could not open FileWriter"); fw = null; } } catch (IOException e) { System.out.println("File couldn't be created"); } } private static int ContainsSymbol(ArrayList<String[]> symbols, String target) { for (int i = 0; i < symbols.size(); i++) { if (symbols.get(i)[0].contains(target)) { return i; } } return -1; } private static String getLabel(ArrayList<String[]> symbols, int address){ for(int i = 0; i < symbols.size(); i++){ if (symbols.get(i)[1].equals(String.valueOf(address))){ return symbols.get(i)[0]+": "; } } return ""; } private static int GetWord(ArrayList<int[]> codes, int target) { for (int i = 0; i < codes.size(); i++) { if (codes.get(i)[0] == target) { return codes.get(i)[1]; } } return 0; } public static boolean isNumber(String sCheck) { try { double num = Double.parseDouble(sCheck); } catch (NumberFormatException nfe) { return false; } return true; } }
true
true
public static void main(String[] args) { // TODO code application logic here String labelRegex = "^[a-zA-Z_]+:"; Pattern label = Pattern.compile(labelRegex); Pattern register = Pattern.compile("^\\$[0-9]?[0-9]"); HashMap labelLoc = new HashMap(); int instCount = 0; int byteLine = 0; int lastByte = 0; int maxMem = 0; ArrayList<int[]> memplacement = new ArrayList<int[]>(); String filename = ""; try { filename = args[0]; } catch (Exception e) { Scanner consolein = new Scanner(System.in); System.out .println("Give the path or filename of source code to compile:"); filename = consolein.next(); consolein.close(); } boolean data = false; File infile = new File(filename); String[] tempParams = infile.getName().split("\\.(?=[^\\.]+$)"); String temp = tempParams[0]; File exeFile = new File(temp + ".exe.mif"); File memFile = new File(temp + ".mem.mif"); // Create file if it doesn't already exist try { exeFile.createNewFile(); Scanner input = new Scanner(infile); FileWriter fw; FileWriter memfw; try { String instruction = ""; int code = 0; ArrayList<String> instructionLines = new ArrayList<String>(); ArrayList<String> origInstruction = new ArrayList<String>(); ArrayList<String[]> Symbols = new ArrayList<String[]>(); String parameters = ""; String[] params; int index; int lineNum = 0; // initialize memory file writers memfw = new FileWriter(memFile); PrintWriter mempw = new PrintWriter(memfw); mempw.print("WIDTH = 32; \r\n-- data width \r\n" + "DEPTH = 256; \r\n-- number of memory slots \r\n" + "-- thus, the total size is 256 x 32 bits\r\n" + "ADDRESS_RADIX = HEX; \r\nDATA_RADIX = HEX; \r\n" + "CONTENT BEGIN \r\n"); // initialize executable file writers fw = new FileWriter(exeFile); PrintWriter pw = new PrintWriter(fw); pw.print("WIDTH = 32; \r\n-- data width \r\n" + "DEPTH = 256; \r\n-- number of memory slots \r\n" + "-- thus, the total size is 256 x 32 bits\r\n" + "ADDRESS_RADIX = HEX; \r\nDATA_RADIX = HEX; \r\n" + "CONTENT BEGIN \r\n"); code = 0; // start reading the file while (input.hasNextLine()) { params = input.nextLine().split("#"); if (params.length > 0) { instruction = params[0].trim(); } else { instruction = ""; } if (instruction.contains(".data")) { data = true; lineNum++; instCount++; byteLine = 0; } if (!data) { if (instruction.contains(":")) { params = instruction.split(":"); index = ContainsSymbol(Symbols, params[0].trim()); if (index > -1) { if (Symbols.get(index)[1].contains("-1")) { Symbols.set( index, new String[] { params[0].trim(), String.valueOf(lineNum * 4) }); } else { System.out.println("Symbol error (Line: " + lineNum + "): Symbol already exists."); } } else { Symbols.add(new String[] { params[0], String.valueOf(lineNum * 4) }); } if (params.length > 1) { instruction = params[1].trim(); } else { instruction = ""; } } if (instruction.length() > 0) { instructionLines.add(instruction); origInstruction.add(instruction); parameters = instruction.split(" ", 2)[1].trim(); params = parameters.split(","); for (int i = 0; i < params.length; i++) { if (!(params[i].trim().startsWith("$")) && !isNumber(params[i].trim())) { index = ContainsSymbol(Symbols, params[i].trim()); if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1] .contains("-1")) { instructionLines .set(lineNum, instructionLines .get(lineNum) .replace( Symbols.get(index)[0], Symbols.get(index)[1])); } } else { Symbols.add(new String[] { params[i].trim(), "-1" }); } } } lineNum++; instCount++; } } else { if (instruction.contains(":")) { params = instruction.split(":"); index = ContainsSymbol(Symbols, params[0].trim()); if (index > -1) { if (Symbols.get(index)[1].contains("-1")) { Symbols.set(index, new String[] { params[0].trim(), String.valueOf(byteLine/4) }); } else { System.out.println("Symbol error (Line: " + lineNum + "): Symbol already exists."); } } else { Symbols.add(new String[] { params[0], String.valueOf(byteLine/4) }); } if (params.length > 1) { instruction = params[1].trim(); } else { instruction = ""; } } if (instruction.length() > 0) { params = instruction.split(" ", 2); switch (params[0]) { case ".ascii": temp = params[0].replaceAll("\"", ""); for (int i = 0; i < temp.length(); i++) { code |= ((byte) temp.charAt(i)) << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } } if (byteLine % 4 != 0) { memplacement.add(new int[] { byteLine/4, code }); code = 0; lastByte = byteLine/4; } break; case ".byte": code |= Integer.valueOf(params[1].trim()) .intValue() << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } break; case ".word": code = Integer.valueOf(params[1].trim()).intValue(); byteLine += 4; memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; break; case ".asciiz": temp = params[1].replaceAll("\"", "") + ((char) (0)); for (int i = 0; i < temp.length(); i++) { code |= ((byte) temp.charAt(i)) << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } } break; case "org": memplacement.add(new int[] { byteLine - byteLine % 4, code }); code = 0; byteLine = Integer.valueOf(params[1].trim()) .intValue(); break; default: } } } } if (byteLine % 4 != 0 && byteLine - 4 != lastByte) { memplacement.add(new int[] { byteLine - (byteLine % 4), code }); code = 0; } for (int i = 0; i <= 256; i = i + 4) { mempw.printf("%02x : %08x; -- %s\r\n", i / 4, GetWord(memplacement, i), i); } for (lineNum = 0; lineNum < instructionLines.size(); lineNum++) { instruction = instructionLines.get(lineNum); System.out.println(origInstruction.get(lineNum)); parameters = instruction.split(" ", 2)[1].trim(); instruction = instruction.split(" ", 2)[0].trim(); params = parameters.split(","); for (int i = 0; i < params.length; i++) { if (!(params[i].trim().startsWith("$")) && !isNumber(params[i].trim())) { if (params[i].contains("(")) { index = ContainsSymbol(Symbols, params[i] .trim().split("\\(")[0]); if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1].contains("-1")) { params[i] = params[i].replace( Symbols.get(index)[0], Symbols.get(index)[1]); } } else { System.out.println("ERROR Symbol " + params[i].trim() + " does not exist."); } if (!(params[i].trim().split("\\(")[1] .startsWith("$")) && !isNumber(params[i].trim().split( "\\(")[1].replace(")", ""))) { index = ContainsSymbol(Symbols, params[i] .trim().split("\\(")[1].replace( ")", "")); } } else { index = ContainsSymbol(Symbols, params[i].trim()); } if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1].contains("-1")) { params[i] = params[i].replace( Symbols.get(index)[0], Symbols.get(index)[1]); } } else { System.out .println("ERROR Symbol " + params[i].trim() + " does not exist."); } } } try { code = 0; switch (instruction) { // R-Type case "add": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x20; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "and": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x24; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jalr": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= 0x09; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jr": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= 0x08; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "nor": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x27; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "or": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sll": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 6; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sllv": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 21; code |= 0x04; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "slt": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x2A; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "srl": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[2].trim()) .intValue() << 5; code |= 0x02; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sub": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x22; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "xor": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; // I-Type case "addi": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 8 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "andi": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 12 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "beq": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= (Integer.valueOf(params[2].trim()) .intValue()/4 - lineNum -1) & 0xFFFF; code |= 4 << 26; // origInstruction = origInstruction.split(" ")[0] + // origInstruction.split(" ")[1] + // origInstruction.split(" ")[2] + // (labelLoc.get(origInstruction.split(" ")[3])).toString(); pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "bne": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= (Integer.valueOf(params[2].trim()) .intValue()/4 - lineNum -1) & 0xFFFF; code |= 0x05 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lb": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x20 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lh": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x21 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lui": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x0F << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "li": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= (byte) (Integer.valueOf(params[1].trim()) .intValue() & 0xFF); code |= 0x0F << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); lineNum++; code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= (byte) ((Integer.valueOf(params[1].trim()) .intValue() >> 8) & 0xFF); code |= 0x0D << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lw": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].trim().split("\\(")[0]) .intValue(); code |= Integer.valueOf( params[1].trim().split("\\(")[1].replace( ")", "").replace("$", "")) .intValue() << 21; code |= 0x23 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "ori": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 0x0D << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sw": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].trim().split("\\(")[0]) .intValue(); code |= Integer.valueOf( params[1].trim().split("\\(")[1].replace( ")", "").replace("$", "")) .intValue() << 21; code |= 0x2B << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; // J-Type case "j": code = Integer.valueOf(params[0].trim()).intValue() << 2; code |= 2 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jal": code = Integer.valueOf(params[0].trim()).intValue() << 2; code |= 3 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "nop": code = 0; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); default: if (!(instruction.startsWith("#"))) { System.out.println("Error reading instruction"); } } } catch (Exception e) { e.printStackTrace(); System.out.println("Syntax Error Line " + lineNum); } } // Finish the files pw.print("END;\r\n"); mempw.print("END;\r\n"); // close the writers pw.close(); mempw.close(); try { memfw.close(); fw.close(); } catch (IOException e) { System.out.println("Could not Close FileWriter"); } } catch (IOException e) { System.out.println("Could not open FileWriter"); fw = null; } } catch (IOException e) { System.out.println("File couldn't be created"); } }
public static void main(String[] args) { // TODO code application logic here String labelRegex = "^[a-zA-Z_]+:"; Pattern label = Pattern.compile(labelRegex); Pattern register = Pattern.compile("^\\$[0-9]?[0-9]"); HashMap labelLoc = new HashMap(); int instCount = 0; int byteLine = 0; int lastByte = 0; int maxMem = 0; ArrayList<int[]> memplacement = new ArrayList<int[]>(); String filename = ""; try { filename = args[0]; } catch (Exception e) { Scanner consolein = new Scanner(System.in); System.out .println("Give the path or filename of source code to compile:"); filename = consolein.next(); consolein.close(); } boolean data = false; File infile = new File(filename); String[] tempParams = infile.getName().split("\\.(?=[^\\.]+$)"); String temp = tempParams[0]; File exeFile = new File(temp + ".exe.mif"); File memFile = new File(temp + ".mem.mif"); // Create file if it doesn't already exist try { exeFile.createNewFile(); Scanner input = new Scanner(infile); FileWriter fw; FileWriter memfw; try { String instruction = ""; int code = 0; ArrayList<String> instructionLines = new ArrayList<String>(); ArrayList<String> origInstruction = new ArrayList<String>(); ArrayList<String[]> Symbols = new ArrayList<String[]>(); String parameters = ""; String[] params; int index; int lineNum = 0; // initialize memory file writers memfw = new FileWriter(memFile); PrintWriter mempw = new PrintWriter(memfw); mempw.print("WIDTH = 32; \r\n-- data width \r\n" + "DEPTH = 256; \r\n-- number of memory slots \r\n" + "-- thus, the total size is 256 x 32 bits\r\n" + "ADDRESS_RADIX = HEX; \r\nDATA_RADIX = HEX; \r\n" + "CONTENT BEGIN \r\n"); // initialize executable file writers fw = new FileWriter(exeFile); PrintWriter pw = new PrintWriter(fw); pw.print("WIDTH = 32; \r\n-- data width \r\n" + "DEPTH = 256; \r\n-- number of memory slots \r\n" + "-- thus, the total size is 256 x 32 bits\r\n" + "ADDRESS_RADIX = HEX; \r\nDATA_RADIX = HEX; \r\n" + "CONTENT BEGIN \r\n"); code = 0; // start reading the file while (input.hasNextLine()) { params = input.nextLine().split("#"); if (params.length > 0) { instruction = params[0].trim(); } else { instruction = ""; } if (instruction.contains(".data")) { data = true; lineNum++; instCount++; byteLine = 0; } if (!data) { if (instruction.contains(":")) { params = instruction.split(":"); index = ContainsSymbol(Symbols, params[0].trim()); if (index > -1) { if (Symbols.get(index)[1].contains("-1")) { Symbols.set( index, new String[] { params[0].trim(), String.valueOf(lineNum * 4) }); } else { System.out.println("Symbol error (Line: " + lineNum + "): Symbol already exists."); } } else { Symbols.add(new String[] { params[0], String.valueOf(lineNum * 4) }); } if (params.length > 1) { instruction = params[1].trim(); } else { instruction = ""; } } if (instruction.length() > 0) { instructionLines.add(instruction); origInstruction.add(instruction); parameters = instruction.split(" ", 2)[1].trim(); params = parameters.split(","); for (int i = 0; i < params.length; i++) { if (!(params[i].trim().startsWith("$")) && !isNumber(params[i].trim())) { index = ContainsSymbol(Symbols, params[i].trim()); if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1] .contains("-1")) { instructionLines .set(lineNum, instructionLines .get(lineNum) .replace( Symbols.get(index)[0], Symbols.get(index)[1])); } } else { Symbols.add(new String[] { params[i].trim(), "-1" }); } } } lineNum++; instCount++; } } else { if (instruction.contains(":")) { params = instruction.split(":"); index = ContainsSymbol(Symbols, params[0].trim()); if (index > -1) { if (Symbols.get(index)[1].contains("-1")) { Symbols.set(index, new String[] { params[0].trim(), String.valueOf(byteLine/4) }); } else { System.out.println("Symbol error (Line: " + lineNum + "): Symbol already exists."); } } else { Symbols.add(new String[] { params[0], String.valueOf(byteLine/4) }); } if (params.length > 1) { instruction = params[1].trim(); } else { instruction = ""; } } if (instruction.length() > 0) { params = instruction.split(" ", 2); switch (params[0]) { case ".ascii": temp = params[0].replaceAll("\"", ""); for (int i = 0; i < temp.length(); i++) { code |= ((byte) temp.charAt(i)) << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } } if (byteLine % 4 != 0) { memplacement.add(new int[] { byteLine/4, code }); code = 0; lastByte = byteLine/4; } break; case ".byte": code |= Integer.valueOf(params[1].trim()) .intValue() << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } break; case ".word": code = Integer.valueOf(params[1].trim()).intValue(); byteLine += 4; memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; break; case ".asciiz": temp = params[1].replaceAll("\"", "") + ((char) (0)); for (int i = 0; i < temp.length(); i++) { code |= ((byte) temp.charAt(i)) << ((3 - byteLine % 4) * 8); byteLine++; if (byteLine % 4 == 0) { memplacement.add(new int[] { byteLine - 4, code }); code = 0; lastByte = byteLine - 4; } } break; case "org": memplacement.add(new int[] { byteLine - byteLine % 4, code }); code = 0; byteLine = Integer.valueOf(params[1].trim()) .intValue(); break; default: } } } } if (byteLine % 4 != 0 && byteLine - 4 != lastByte) { memplacement.add(new int[] { byteLine - (byteLine % 4), code }); code = 0; } for (int i = 0; i <= 256; i = i + 4) { mempw.printf("%02x : %08x; -- %s\r\n", i / 4, GetWord(memplacement, i), i); } for (lineNum = 0; lineNum < instructionLines.size(); lineNum++) { instruction = instructionLines.get(lineNum); System.out.println(origInstruction.get(lineNum)); parameters = instruction.split(" ", 2)[1].trim(); instruction = instruction.split(" ", 2)[0].trim(); params = parameters.split(","); for (int i = 0; i < params.length; i++) { if (!(params[i].trim().startsWith("$")) && !isNumber(params[i].trim())) { if (params[i].contains("(")) { index = ContainsSymbol(Symbols, params[i] .trim().split("\\(")[0]); if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1].contains("-1")) { params[i] = params[i].replace( Symbols.get(index)[0], Symbols.get(index)[1]); } } else { System.out.println("ERROR Symbol " + params[i].trim() + " does not exist."); } if (!(params[i].trim().split("\\(")[1] .startsWith("$")) && !isNumber(params[i].trim().split( "\\(")[1].replace(")", ""))) { index = ContainsSymbol(Symbols, params[i] .trim().split("\\(")[1].replace( ")", "")); } } else { index = ContainsSymbol(Symbols, params[i].trim()); } if (index > -1 && index < Symbols.size()) { if (!Symbols.get(index)[1].contains("-1")) { params[i] = params[i].replace( Symbols.get(index)[0], Symbols.get(index)[1]); } } else { System.out .println("ERROR Symbol " + params[i].trim() + " does not exist."); } } } try { code = 0; switch (instruction) { // R-Type case "add": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x20; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "and": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x24; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jalr": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= 0x09; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jr": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= 0x08; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "nor": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x27; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "or": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sll": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 6; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sllv": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 21; code |= 0x04; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "slt": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x2A; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "srl": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[2].trim()) .intValue() << 6; code |= 0x02; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sub": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x22; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "xor": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 11; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[2].replace("$", "").trim()) .intValue() << 16; code |= 0x25; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; // I-Type case "addi": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 8 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "andi": code = Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 12 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "beq": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= (Integer.valueOf(params[2].trim()) .intValue()/4 - lineNum -1) & 0xFFFF; code |= 4 << 26; // origInstruction = origInstruction.split(" ")[0] + // origInstruction.split(" ")[1] + // origInstruction.split(" ")[2] + // (labelLoc.get(origInstruction.split(" ")[3])).toString(); pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "bne": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 16; code |= (Integer.valueOf(params[2].trim()) .intValue()/4 - lineNum -1) & 0xFFFF; code |= 0x05 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lb": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x20 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lh": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x21 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lui": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf(params[1].trim()) .intValue(); code |= 0x0F << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "li": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= (byte) (Integer.valueOf(params[1].trim()) .intValue() & 0xFF); code |= 0x0F << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); lineNum++; code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 21; code |= (byte) ((Integer.valueOf(params[1].trim()) .intValue() >> 8) & 0xFF); code |= 0x0D << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "lw": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].trim().split("\\(")[0]) .intValue(); code |= Integer.valueOf( params[1].trim().split("\\(")[1].replace( ")", "").replace("$", "")) .intValue() << 21; code |= 0x23 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "ori": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].replace("$", "").trim()) .intValue() << 21; code |= Integer.valueOf(params[2].trim()) .intValue(); code |= 0x0D << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "sw": code |= Integer.valueOf( params[0].replace("$", "").trim()) .intValue() << 16; code |= Integer.valueOf( params[1].trim().split("\\(")[0]) .intValue(); code |= Integer.valueOf( params[1].trim().split("\\(")[1].replace( ")", "").replace("$", "")) .intValue() << 21; code |= 0x2B << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; // J-Type case "j": code = Integer.valueOf(params[0].trim()).intValue() << 2; code |= 2 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "jal": code = Integer.valueOf(params[0].trim()).intValue() << 2; code |= 3 << 26; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); break; case "nop": code = 0; pw.printf("%02x : %08x; -- %s %s\r\n", lineNum, code, getLabel(Symbols, lineNum*4), origInstruction.get(lineNum)); default: if (!(instruction.startsWith("#"))) { System.out.println("Error reading instruction"); } } } catch (Exception e) { e.printStackTrace(); System.out.println("Syntax Error Line " + lineNum); } } // Finish the files pw.print("END;\r\n"); mempw.print("END;\r\n"); // close the writers pw.close(); mempw.close(); try { memfw.close(); fw.close(); } catch (IOException e) { System.out.println("Could not Close FileWriter"); } } catch (IOException e) { System.out.println("Could not open FileWriter"); fw = null; } } catch (IOException e) { System.out.println("File couldn't be created"); } }
diff --git a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/VariableDeclarationStatementInfo.java b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/VariableDeclarationStatementInfo.java index 45a6420c..676db0e3 100644 --- a/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/VariableDeclarationStatementInfo.java +++ b/main/src/jp/ac/osaka_u/ist/sel/metricstool/main/data/target/VariableDeclarationStatementInfo.java @@ -1,192 +1,192 @@ package jp.ac.osaka_u.ist.sel.metricstool.main.data.target; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; /** * �ϐ��錾���̏���ۗL����N���X * * @author t-miyake * */ @SuppressWarnings("serial") public class VariableDeclarationStatementInfo extends SingleStatementInfo implements ConditionInfo { /** * �錾����Ă���ϐ��C���������C�ʒu����^���ď����� * �錾����Ă���ϐ�������������Ă���ꍇ�C���̃R���X�g���N�^���g�p���� * * @param variableDeclaration �錾����Ă��郍�[�J���ϐ� * @param initializationExpression �������� * @param fromLine �J�n�s * @param fromColumn �J�n�� * @param toLine �I���s * @param toColumn �I���� */ public VariableDeclarationStatementInfo(final LocalVariableUsageInfo variableDeclaration, final ExpressionInfo initializationExpression, final int fromLine, final int fromColumn, final int toLine, final int toColumn) { super(variableDeclaration.getUsedVariable().getDefinitionUnit(), fromLine, fromColumn, toLine, toColumn); if (null == variableDeclaration) { throw new IllegalArgumentException("declaredVariable is null"); } this.variableDeclaration = variableDeclaration; this.variableDeclaration.setOwnerExecutableElement(this); this.variableDeclaration.getUsedVariable().setDeclarationStatement(this); if (null != initializationExpression) { this.initializationExpression = initializationExpression; } else { final LocalSpaceInfo ownerSpace = variableDeclaration.getUsedVariable() .getDefinitionUnit(); // ownerSpaceInfo�����\�b�h�܂��̓R���X�g���N�^�̎� if (ownerSpace instanceof CallableUnitInfo) { this.initializationExpression = new EmptyExpressionInfo( (CallableUnitInfo) ownerSpace, toLine, toColumn - 1, toLine, toColumn - 1); } // ownerSpaceInfo���u���b�N���̎� else if (ownerSpace instanceof BlockInfo) { final CallableUnitInfo ownerMethod = ((BlockInfo) ownerSpace).getOwnerMethod(); - this.initializationExpression = new EmptyExpressionInfo(null, toLine, toColumn - 1, + this.initializationExpression = new EmptyExpressionInfo(ownerMethod, toLine, toColumn - 1, toLine, toColumn - 1); } // ����ȊO�̎��̓G���[ else{ throw new IllegalStateException(); } } this.initializationExpression.setOwnerExecutableElement(this); } /** * ���̐錾���Ő錾����Ă���ϐ���Ԃ� * * @return ���̐錾���Ő錾����Ă���ϐ� */ public final LocalVariableInfo getDeclaredLocalVariable() { return this.variableDeclaration.getUsedVariable(); } /** * �錾���̕ϐ��g�p��Ԃ� * @return �錾���̕ϐ��g�p */ public final LocalVariableUsageInfo getDeclaration() { return this.variableDeclaration; } /** * �錾����Ă���ϐ��̏���������Ԃ� * * @return �錾����Ă���ϐ��̏��������D����������Ă��ꍇ��null */ public final ExpressionInfo getInitializationExpression() { return this.initializationExpression; } /** * �錾����Ă���ϐ�������������Ă��邩�ǂ�����Ԃ� * * @return �錾����Ă���ϐ�������������Ă����true */ public boolean isInitialized() { return !(this.initializationExpression instanceof EmptyExpressionInfo); } @Override public Set<VariableUsageInfo<? extends VariableInfo<? extends UnitInfo>>> getVariableUsages() { final Set<VariableUsageInfo<? extends VariableInfo<? extends UnitInfo>>> usages = new TreeSet<VariableUsageInfo<? extends VariableInfo<? extends UnitInfo>>>(); usages.add(this.variableDeclaration); if (this.isInitialized()) { usages.addAll(this.getInitializationExpression().getVariableUsages()); } return Collections.unmodifiableSet(usages); } /** * ��`���ꂽ�ϐ���Set��Ԃ� * * @return ��`���ꂽ�ϐ���Set */ @Override public Set<VariableInfo<? extends UnitInfo>> getDefinedVariables() { final Set<VariableInfo<? extends UnitInfo>> definedVariables = new HashSet<VariableInfo<? extends UnitInfo>>(); definedVariables.add(this.getDeclaredLocalVariable()); return Collections.unmodifiableSet(definedVariables); } /** * �Ăяo����Set��Ԃ� * * @return �Ăяo����Set */ @Override public Set<CallInfo<?>> getCalls() { return this.isInitialized() ? this.getInitializationExpression().getCalls() : CallInfo.EmptySet; } /** * ���̕ϐ��錾���̃e�L�X�g�\���iString�^�j��Ԃ� * * @return ���̕ϐ��錾���̃e�L�X�g�\���iString�^�j */ @Override public String getText() { final StringBuilder sb = new StringBuilder(); final LocalVariableInfo variable = this.getDeclaredLocalVariable(); final TypeInfo type = variable.getType(); sb.append(type.getTypeName()); sb.append(" "); sb.append(variable.getName()); if (this.isInitialized()) { sb.append(" = "); final ExpressionInfo expression = this.getInitializationExpression(); sb.append(expression.getText()); } sb.append(";"); return sb.toString(); } /** * �錾����Ă���ϐ��̌^��Ԃ� * @return �錾����Ă���ϐ��̌^ */ public TypeInfo getType() { return this.variableDeclaration.getType(); } /** * �錾����Ă���ϐ���\���t�B�[���h */ private final LocalVariableUsageInfo variableDeclaration; /** * �錾����Ă���ϐ��̏���������\���t�B�[���h */ private final ExpressionInfo initializationExpression; }
true
true
public VariableDeclarationStatementInfo(final LocalVariableUsageInfo variableDeclaration, final ExpressionInfo initializationExpression, final int fromLine, final int fromColumn, final int toLine, final int toColumn) { super(variableDeclaration.getUsedVariable().getDefinitionUnit(), fromLine, fromColumn, toLine, toColumn); if (null == variableDeclaration) { throw new IllegalArgumentException("declaredVariable is null"); } this.variableDeclaration = variableDeclaration; this.variableDeclaration.setOwnerExecutableElement(this); this.variableDeclaration.getUsedVariable().setDeclarationStatement(this); if (null != initializationExpression) { this.initializationExpression = initializationExpression; } else { final LocalSpaceInfo ownerSpace = variableDeclaration.getUsedVariable() .getDefinitionUnit(); // ownerSpaceInfo�����\�b�h�܂��̓R���X�g���N�^�̎� if (ownerSpace instanceof CallableUnitInfo) { this.initializationExpression = new EmptyExpressionInfo( (CallableUnitInfo) ownerSpace, toLine, toColumn - 1, toLine, toColumn - 1); } // ownerSpaceInfo���u���b�N���̎� else if (ownerSpace instanceof BlockInfo) { final CallableUnitInfo ownerMethod = ((BlockInfo) ownerSpace).getOwnerMethod(); this.initializationExpression = new EmptyExpressionInfo(null, toLine, toColumn - 1, toLine, toColumn - 1); } // ����ȊO�̎��̓G���[ else{ throw new IllegalStateException(); } } this.initializationExpression.setOwnerExecutableElement(this); }
public VariableDeclarationStatementInfo(final LocalVariableUsageInfo variableDeclaration, final ExpressionInfo initializationExpression, final int fromLine, final int fromColumn, final int toLine, final int toColumn) { super(variableDeclaration.getUsedVariable().getDefinitionUnit(), fromLine, fromColumn, toLine, toColumn); if (null == variableDeclaration) { throw new IllegalArgumentException("declaredVariable is null"); } this.variableDeclaration = variableDeclaration; this.variableDeclaration.setOwnerExecutableElement(this); this.variableDeclaration.getUsedVariable().setDeclarationStatement(this); if (null != initializationExpression) { this.initializationExpression = initializationExpression; } else { final LocalSpaceInfo ownerSpace = variableDeclaration.getUsedVariable() .getDefinitionUnit(); // ownerSpaceInfo�����\�b�h�܂��̓R���X�g���N�^�̎� if (ownerSpace instanceof CallableUnitInfo) { this.initializationExpression = new EmptyExpressionInfo( (CallableUnitInfo) ownerSpace, toLine, toColumn - 1, toLine, toColumn - 1); } // ownerSpaceInfo���u���b�N���̎� else if (ownerSpace instanceof BlockInfo) { final CallableUnitInfo ownerMethod = ((BlockInfo) ownerSpace).getOwnerMethod(); this.initializationExpression = new EmptyExpressionInfo(ownerMethod, toLine, toColumn - 1, toLine, toColumn - 1); } // ����ȊO�̎��̓G���[ else{ throw new IllegalStateException(); } } this.initializationExpression.setOwnerExecutableElement(this); }
diff --git a/src/main/java/me/iffa/bananaspace/commands/SpaceHelpCommand.java b/src/main/java/me/iffa/bananaspace/commands/SpaceHelpCommand.java index 10e0b98..c66a5b1 100644 --- a/src/main/java/me/iffa/bananaspace/commands/SpaceHelpCommand.java +++ b/src/main/java/me/iffa/bananaspace/commands/SpaceHelpCommand.java @@ -1,39 +1,40 @@ // Package Declaration package me.iffa.bananaspace.commands; // BananaSpace Imports import me.iffa.bananaspace.BananaSpace; // Bukkit Imports import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; /** * Represents "/space help". * * @author iffa */ public class SpaceHelpCommand extends SpaceCommand { /** * Constructor of SpaceHelpCommand. * * @param plugin BananaSpace instance * @param sender Command sender * @param args Command arguments */ public SpaceHelpCommand(BananaSpace plugin, CommandSender sender, String[] args) { super(plugin, sender, args); } /** * Does the command. */ @Override public void command() { - sender.sendMessage(ChatColor.GREEN + "[BananaSpace] Usage:"); + sender.sendMessage(ChatColor.DARK_GREEN + "[BananaSpace] Usage:"); sender.sendMessage(ChatColor.GREEN + "/space enter [world] - Go to space (default world or given one)"); sender.sendMessage(ChatColor.GREEN + "/space back - Leave space or go back where you were in space"); sender.sendMessage(ChatColor.GREEN + "/space list - Brings up a list of all space worlds"); sender.sendMessage(ChatColor.GREEN + "/space help - Brings up this help message"); + sender.sendMessage(ChatColor.GREEN + "/space about - About BananaSpace"); } }
false
true
public void command() { sender.sendMessage(ChatColor.GREEN + "[BananaSpace] Usage:"); sender.sendMessage(ChatColor.GREEN + "/space enter [world] - Go to space (default world or given one)"); sender.sendMessage(ChatColor.GREEN + "/space back - Leave space or go back where you were in space"); sender.sendMessage(ChatColor.GREEN + "/space list - Brings up a list of all space worlds"); sender.sendMessage(ChatColor.GREEN + "/space help - Brings up this help message"); }
public void command() { sender.sendMessage(ChatColor.DARK_GREEN + "[BananaSpace] Usage:"); sender.sendMessage(ChatColor.GREEN + "/space enter [world] - Go to space (default world or given one)"); sender.sendMessage(ChatColor.GREEN + "/space back - Leave space or go back where you were in space"); sender.sendMessage(ChatColor.GREEN + "/space list - Brings up a list of all space worlds"); sender.sendMessage(ChatColor.GREEN + "/space help - Brings up this help message"); sender.sendMessage(ChatColor.GREEN + "/space about - About BananaSpace"); }
diff --git a/drools-planner-core/src/main/java/org/drools/planner/core/score/director/drools/DroolsScoreDirector.java b/drools-planner-core/src/main/java/org/drools/planner/core/score/director/drools/DroolsScoreDirector.java index 91786556..2efd8c85 100644 --- a/drools-planner-core/src/main/java/org/drools/planner/core/score/director/drools/DroolsScoreDirector.java +++ b/drools-planner-core/src/main/java/org/drools/planner/core/score/director/drools/DroolsScoreDirector.java @@ -1,254 +1,254 @@ /* * Copyright 2011 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.planner.core.score.director.drools; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; import org.drools.ClassObjectFilter; import org.drools.FactHandle; import org.drools.RuleBase; import org.drools.StatefulSession; import org.drools.WorkingMemory; import org.drools.planner.core.score.Score; import org.drools.planner.core.score.director.AbstractScoreDirector; import org.drools.planner.core.score.director.ScoreDirector; import org.drools.planner.core.score.holder.ScoreHolder; import org.drools.planner.core.score.constraint.ConstraintOccurrence; import org.drools.planner.core.solution.Solution; /** * Drools implementation of {@link ScoreDirector}, which directs the Rule Engine to calculate the {@link Score} * of the {@link Solution} workingSolution. * @see ScoreDirector */ public class DroolsScoreDirector extends AbstractScoreDirector<DroolsScoreDirectorFactory> { public static final String GLOBAL_SCORE_HOLDER_KEY = "scoreHolder"; protected StatefulSession workingMemory; protected ScoreHolder workingScoreHolder; public DroolsScoreDirector(DroolsScoreDirectorFactory scoreDirectorFactory) { super(scoreDirectorFactory); } protected RuleBase getRuleBase() { return scoreDirectorFactory.getRuleBase(); } /** * @return never null */ public WorkingMemory getWorkingMemory() { return workingMemory; } // ************************************************************************ // Complex methods // ************************************************************************ @Override public void setWorkingSolution(Solution workingSolution) { super.setWorkingSolution(workingSolution); resetWorkingMemory(); } private void resetWorkingMemory() { if (workingMemory != null) { workingMemory.dispose(); } workingMemory = getRuleBase().newStatefulSession(); workingScoreHolder = getScoreDefinition().buildScoreHolder(); workingMemory.setGlobal(GLOBAL_SCORE_HOLDER_KEY, workingScoreHolder); // TODO Adjust when uninitialized entities from getWorkingFacts get added automatically too (and call afterEntityAdded) for (Object fact : getWorkingFacts()) { workingMemory.insert(fact); } } public Collection<Object> getWorkingFacts() { return getSolutionDescriptor().getAllFacts(workingSolution); } // public void beforeEntityAdded(Object entity) // Do nothing @Override public void afterEntityAdded(Object entity) { super.afterEntityAdded(entity); if (entity == null) { throw new IllegalArgumentException("The entity (" + entity + ") cannot be added to the ScoreDirector."); } if (!getSolutionDescriptor().hasPlanningEntityDescriptor(entity.getClass())) { throw new IllegalArgumentException("The entity (" + entity + ") of class (" + entity.getClass() + ") is not a configured @PlanningEntity."); } workingMemory.insert(entity); } // public void beforeAllVariablesChanged(Object entity) // Do nothing @Override public void afterAllVariablesChanged(Object entity) { super.afterAllVariablesChanged(entity); FactHandle factHandle = workingMemory.getFactHandle(entity); if (factHandle == null) { throw new IllegalArgumentException("The entity (" + entity + ") was never added to this ScoreDirector."); } workingMemory.update(factHandle, entity); } // public void beforeVariableChanged(Object entity, String variableName) // Do nothing @Override public void afterVariableChanged(Object entity, String variableName) { super.afterVariableChanged(entity, variableName); FactHandle factHandle = workingMemory.getFactHandle(entity); if (factHandle == null) { throw new IllegalArgumentException("The entity (" + entity + ") was never added to this ScoreDirector."); } workingMemory.update(factHandle, entity); } // public void beforeEntityRemoved(Object entity) // Do nothing @Override public void afterEntityRemoved(Object entity) { super.afterEntityRemoved(entity); FactHandle factHandle = workingMemory.getFactHandle(entity); if (factHandle == null) { throw new IllegalArgumentException("The entity (" + entity + ") was never added to this ScoreDirector."); } workingMemory.retract(factHandle); } // public void beforeProblemFactAdded(Object problemFact) // Do nothing @Override public void afterProblemFactAdded(Object problemFact) { super.afterProblemFactAdded(problemFact); workingMemory.insert(problemFact); } // public void beforeProblemFactChanged(Object problemFact) // Do nothing @Override public void afterProblemFactChanged(Object problemFact) { super.afterProblemFactChanged(problemFact); FactHandle factHandle = workingMemory.getFactHandle(problemFact); if (factHandle == null) { throw new IllegalArgumentException("The problemFact (" + problemFact + ") was never added to this ScoreDirector."); } workingMemory.update(factHandle, problemFact); } // public void beforeProblemFactRemoved(Object problemFact) // Do nothing @Override public void afterProblemFactRemoved(Object problemFact) { super.afterProblemFactRemoved(problemFact); FactHandle factHandle = workingMemory.getFactHandle(problemFact); if (factHandle == null) { throw new IllegalArgumentException("The problemFact (" + problemFact + ") was never added to this ScoreDirector."); } workingMemory.retract(factHandle); } public Score calculateScore() { workingMemory.fireAllRules(); Score score = workingScoreHolder.extractScore(); setCalculatedScore(score); return score; } protected String buildScoreCorruptionAnalysis(ScoreDirector uncorruptedScoreDirector) { DroolsScoreDirector uncorruptedDroolsScoreDirector = (DroolsScoreDirector) uncorruptedScoreDirector; Set<ConstraintOccurrence> workingConstraintOccurrenceSet = new LinkedHashSet<ConstraintOccurrence>(); Iterator<ConstraintOccurrence> workingIt = (Iterator<ConstraintOccurrence>) workingMemory.iterateObjects( new ClassObjectFilter(ConstraintOccurrence.class)); while (workingIt.hasNext()) { workingConstraintOccurrenceSet.add(workingIt.next()); } Set<ConstraintOccurrence> uncorruptedConstraintOccurrenceSet = new LinkedHashSet<ConstraintOccurrence>(); Iterator<ConstraintOccurrence> uncorruptedIt = (Iterator<ConstraintOccurrence>) uncorruptedDroolsScoreDirector.getWorkingMemory().iterateObjects( new ClassObjectFilter(ConstraintOccurrence.class)); while (uncorruptedIt.hasNext()) { uncorruptedConstraintOccurrenceSet.add(uncorruptedIt.next()); }; Set<Object> excessSet = new LinkedHashSet<Object>(workingConstraintOccurrenceSet); excessSet.removeAll(uncorruptedConstraintOccurrenceSet); Set<Object> lackingSet = new LinkedHashSet<Object>(uncorruptedConstraintOccurrenceSet); lackingSet.removeAll(workingConstraintOccurrenceSet); int CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT = 10; StringBuilder analysis = new StringBuilder(); if (!excessSet.isEmpty()) { analysis.append(" The workingMemory has ").append(excessSet.size()) .append(" ConstraintOccurrence(s) in excess:\n"); int count = 0; for (Object o : excessSet) { if (count >= CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT) { analysis.append(" ... ").append(excessSet.size() - CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT) .append(" more\n"); break; } analysis.append(" ").append(o.toString()).append("\n"); count++; } } if (!lackingSet.isEmpty()) { - analysis.append(" The workingMemory has ").append(excessSet.size()) + analysis.append(" The workingMemory has ").append(lackingSet.size()) .append(" ConstraintOccurrence(s) lacking:\n"); int count = 0; for (Object o : lackingSet) { if (count >= CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT) { analysis.append(" ... ").append(lackingSet.size() - CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT) .append(" more\n"); break; } analysis.append(" ").append(o.toString()).append("\n"); count++; } } if (excessSet.isEmpty() && lackingSet.isEmpty()) { analysis.append(" Check the score rules. No ConstraintOccurrence(s) in excess or lacking." + " Possibly some logically inserted score rules do not extend ConstraintOccurrence.\n" + " Consider making them extend ConstraintOccurrence" + " or just reuse the build-in ConstraintOccurrence implementations."); } else { analysis.append(" Check the score rules who created those ConstraintOccurrences." + " Verify that each ConstraintOccurrence's causes and weight is correct."); } return analysis.toString(); } @Override public void dispose() { if (workingMemory != null) { workingMemory.dispose(); workingMemory = null; } } }
true
true
protected String buildScoreCorruptionAnalysis(ScoreDirector uncorruptedScoreDirector) { DroolsScoreDirector uncorruptedDroolsScoreDirector = (DroolsScoreDirector) uncorruptedScoreDirector; Set<ConstraintOccurrence> workingConstraintOccurrenceSet = new LinkedHashSet<ConstraintOccurrence>(); Iterator<ConstraintOccurrence> workingIt = (Iterator<ConstraintOccurrence>) workingMemory.iterateObjects( new ClassObjectFilter(ConstraintOccurrence.class)); while (workingIt.hasNext()) { workingConstraintOccurrenceSet.add(workingIt.next()); } Set<ConstraintOccurrence> uncorruptedConstraintOccurrenceSet = new LinkedHashSet<ConstraintOccurrence>(); Iterator<ConstraintOccurrence> uncorruptedIt = (Iterator<ConstraintOccurrence>) uncorruptedDroolsScoreDirector.getWorkingMemory().iterateObjects( new ClassObjectFilter(ConstraintOccurrence.class)); while (uncorruptedIt.hasNext()) { uncorruptedConstraintOccurrenceSet.add(uncorruptedIt.next()); }; Set<Object> excessSet = new LinkedHashSet<Object>(workingConstraintOccurrenceSet); excessSet.removeAll(uncorruptedConstraintOccurrenceSet); Set<Object> lackingSet = new LinkedHashSet<Object>(uncorruptedConstraintOccurrenceSet); lackingSet.removeAll(workingConstraintOccurrenceSet); int CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT = 10; StringBuilder analysis = new StringBuilder(); if (!excessSet.isEmpty()) { analysis.append(" The workingMemory has ").append(excessSet.size()) .append(" ConstraintOccurrence(s) in excess:\n"); int count = 0; for (Object o : excessSet) { if (count >= CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT) { analysis.append(" ... ").append(excessSet.size() - CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT) .append(" more\n"); break; } analysis.append(" ").append(o.toString()).append("\n"); count++; } } if (!lackingSet.isEmpty()) { analysis.append(" The workingMemory has ").append(excessSet.size()) .append(" ConstraintOccurrence(s) lacking:\n"); int count = 0; for (Object o : lackingSet) { if (count >= CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT) { analysis.append(" ... ").append(lackingSet.size() - CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT) .append(" more\n"); break; } analysis.append(" ").append(o.toString()).append("\n"); count++; } } if (excessSet.isEmpty() && lackingSet.isEmpty()) { analysis.append(" Check the score rules. No ConstraintOccurrence(s) in excess or lacking." + " Possibly some logically inserted score rules do not extend ConstraintOccurrence.\n" + " Consider making them extend ConstraintOccurrence" + " or just reuse the build-in ConstraintOccurrence implementations."); } else { analysis.append(" Check the score rules who created those ConstraintOccurrences." + " Verify that each ConstraintOccurrence's causes and weight is correct."); } return analysis.toString(); }
protected String buildScoreCorruptionAnalysis(ScoreDirector uncorruptedScoreDirector) { DroolsScoreDirector uncorruptedDroolsScoreDirector = (DroolsScoreDirector) uncorruptedScoreDirector; Set<ConstraintOccurrence> workingConstraintOccurrenceSet = new LinkedHashSet<ConstraintOccurrence>(); Iterator<ConstraintOccurrence> workingIt = (Iterator<ConstraintOccurrence>) workingMemory.iterateObjects( new ClassObjectFilter(ConstraintOccurrence.class)); while (workingIt.hasNext()) { workingConstraintOccurrenceSet.add(workingIt.next()); } Set<ConstraintOccurrence> uncorruptedConstraintOccurrenceSet = new LinkedHashSet<ConstraintOccurrence>(); Iterator<ConstraintOccurrence> uncorruptedIt = (Iterator<ConstraintOccurrence>) uncorruptedDroolsScoreDirector.getWorkingMemory().iterateObjects( new ClassObjectFilter(ConstraintOccurrence.class)); while (uncorruptedIt.hasNext()) { uncorruptedConstraintOccurrenceSet.add(uncorruptedIt.next()); }; Set<Object> excessSet = new LinkedHashSet<Object>(workingConstraintOccurrenceSet); excessSet.removeAll(uncorruptedConstraintOccurrenceSet); Set<Object> lackingSet = new LinkedHashSet<Object>(uncorruptedConstraintOccurrenceSet); lackingSet.removeAll(workingConstraintOccurrenceSet); int CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT = 10; StringBuilder analysis = new StringBuilder(); if (!excessSet.isEmpty()) { analysis.append(" The workingMemory has ").append(excessSet.size()) .append(" ConstraintOccurrence(s) in excess:\n"); int count = 0; for (Object o : excessSet) { if (count >= CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT) { analysis.append(" ... ").append(excessSet.size() - CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT) .append(" more\n"); break; } analysis.append(" ").append(o.toString()).append("\n"); count++; } } if (!lackingSet.isEmpty()) { analysis.append(" The workingMemory has ").append(lackingSet.size()) .append(" ConstraintOccurrence(s) lacking:\n"); int count = 0; for (Object o : lackingSet) { if (count >= CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT) { analysis.append(" ... ").append(lackingSet.size() - CONSTRAINT_OCCURRENCE_DISPLAY_LIMIT) .append(" more\n"); break; } analysis.append(" ").append(o.toString()).append("\n"); count++; } } if (excessSet.isEmpty() && lackingSet.isEmpty()) { analysis.append(" Check the score rules. No ConstraintOccurrence(s) in excess or lacking." + " Possibly some logically inserted score rules do not extend ConstraintOccurrence.\n" + " Consider making them extend ConstraintOccurrence" + " or just reuse the build-in ConstraintOccurrence implementations."); } else { analysis.append(" Check the score rules who created those ConstraintOccurrences." + " Verify that each ConstraintOccurrence's causes and weight is correct."); } return analysis.toString(); }
diff --git a/src/java/com/altaworks/magnolia/GrailsTemplateRegistry.java b/src/java/com/altaworks/magnolia/GrailsTemplateRegistry.java index 20053a0..b6fb9e4 100644 --- a/src/java/com/altaworks/magnolia/GrailsTemplateRegistry.java +++ b/src/java/com/altaworks/magnolia/GrailsTemplateRegistry.java @@ -1,49 +1,60 @@ package com.altaworks.magnolia; import info.magnolia.cms.beans.config.ContentRepository; import info.magnolia.cms.core.Content; import info.magnolia.cms.core.HierarchyManager; import info.magnolia.context.MgnlContext; import info.magnolia.module.blossom.support.RepositoryUtils; import info.magnolia.module.blossom.template.BlossomTemplate; import info.magnolia.module.blossom.template.BlossomTemplateDescription; import info.magnolia.module.blossom.template.DefaultBlossomTemplateRegistry; import info.magnolia.module.blossom.template.TemplateDescriptionBuilder; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.InitializingBean; import javax.jcr.RepositoryException; /** * @author Åke Argéus */ public class GrailsTemplateRegistry extends DefaultBlossomTemplateRegistry implements InitializingBean { private static final String TEMPLATES_PATH = "/modules/blossom/templates/autodetected"; @Override protected void writeTemplateDefinition(BlossomTemplateDescription templateDescription) throws RepositoryException { HierarchyManager hierarchyManager = MgnlContext.getSystemContext().getHierarchyManager(ContentRepository.CONFIG); if (!hierarchyManager.isExist(TEMPLATES_PATH + "/" + templateDescription.getName())) { Content configNode = RepositoryUtils.createContentNode(hierarchyManager, TEMPLATES_PATH, templateDescription.getName()); configNode.createNodeData("name", templateDescription.getName()); configNode.createNodeData("title", templateDescription.getTitle()); configNode.createNodeData("description", templateDescription.getDescription()); configNode.createNodeData("visible", templateDescription.isVisible()); if (StringUtils.isNotBlank(templateDescription.getI18nBasename())) configNode.createNodeData("i18nBasename", templateDescription.getI18nBasename()); configNode.createNodeData("type", "blossom"); configNode.createNodeData("class", BlossomTemplate.class.getName()); configNode.getParent().save(); + }else{ + Content configNode = RepositoryUtils.createContentNode(hierarchyManager, TEMPLATES_PATH, templateDescription.getName()); + configNode.setNodeData("name", templateDescription.getName()); + configNode.setNodeData("title", templateDescription.getTitle()); + configNode.setNodeData("description", templateDescription.getDescription()); + configNode.setNodeData("visible", templateDescription.isVisible()); + if (StringUtils.isNotBlank(templateDescription.getI18nBasename())) + configNode.setNodeData("i18nBasename", templateDescription.getI18nBasename()); + configNode.setNodeData("type", "blossom"); + configNode.setNodeData("class", BlossomTemplate.class.getName()); + configNode.getParent().save(); } } public void afterPropertiesSet() throws Exception { HierarchyManager hierarchyManager = MgnlContext.getSystemContext().getHierarchyManager(ContentRepository.CONFIG); RepositoryUtils.deleteContent(hierarchyManager, TEMPLATES_PATH); if (descriptionBuilder == null) descriptionBuilder = new TemplateDescriptionBuilder(); } }
true
true
protected void writeTemplateDefinition(BlossomTemplateDescription templateDescription) throws RepositoryException { HierarchyManager hierarchyManager = MgnlContext.getSystemContext().getHierarchyManager(ContentRepository.CONFIG); if (!hierarchyManager.isExist(TEMPLATES_PATH + "/" + templateDescription.getName())) { Content configNode = RepositoryUtils.createContentNode(hierarchyManager, TEMPLATES_PATH, templateDescription.getName()); configNode.createNodeData("name", templateDescription.getName()); configNode.createNodeData("title", templateDescription.getTitle()); configNode.createNodeData("description", templateDescription.getDescription()); configNode.createNodeData("visible", templateDescription.isVisible()); if (StringUtils.isNotBlank(templateDescription.getI18nBasename())) configNode.createNodeData("i18nBasename", templateDescription.getI18nBasename()); configNode.createNodeData("type", "blossom"); configNode.createNodeData("class", BlossomTemplate.class.getName()); configNode.getParent().save(); } }
protected void writeTemplateDefinition(BlossomTemplateDescription templateDescription) throws RepositoryException { HierarchyManager hierarchyManager = MgnlContext.getSystemContext().getHierarchyManager(ContentRepository.CONFIG); if (!hierarchyManager.isExist(TEMPLATES_PATH + "/" + templateDescription.getName())) { Content configNode = RepositoryUtils.createContentNode(hierarchyManager, TEMPLATES_PATH, templateDescription.getName()); configNode.createNodeData("name", templateDescription.getName()); configNode.createNodeData("title", templateDescription.getTitle()); configNode.createNodeData("description", templateDescription.getDescription()); configNode.createNodeData("visible", templateDescription.isVisible()); if (StringUtils.isNotBlank(templateDescription.getI18nBasename())) configNode.createNodeData("i18nBasename", templateDescription.getI18nBasename()); configNode.createNodeData("type", "blossom"); configNode.createNodeData("class", BlossomTemplate.class.getName()); configNode.getParent().save(); }else{ Content configNode = RepositoryUtils.createContentNode(hierarchyManager, TEMPLATES_PATH, templateDescription.getName()); configNode.setNodeData("name", templateDescription.getName()); configNode.setNodeData("title", templateDescription.getTitle()); configNode.setNodeData("description", templateDescription.getDescription()); configNode.setNodeData("visible", templateDescription.isVisible()); if (StringUtils.isNotBlank(templateDescription.getI18nBasename())) configNode.setNodeData("i18nBasename", templateDescription.getI18nBasename()); configNode.setNodeData("type", "blossom"); configNode.setNodeData("class", BlossomTemplate.class.getName()); configNode.getParent().save(); } }
diff --git a/src/main/java/org/candlepin/pinsetter/tasks/UnpauseJob.java b/src/main/java/org/candlepin/pinsetter/tasks/UnpauseJob.java index 2a6e13cb5..e6979e134 100644 --- a/src/main/java/org/candlepin/pinsetter/tasks/UnpauseJob.java +++ b/src/main/java/org/candlepin/pinsetter/tasks/UnpauseJob.java @@ -1,84 +1,84 @@ /** * Copyright (c) 2009 - 2012 Red Hat, Inc. * * This software is licensed to you under the GNU General Public License, * version 2 (GPLv2). There is NO WARRANTY for this software, express or * implied, including the implied warranties of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 * along with this software; if not, see * http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt. * * Red Hat trademarks are not licensed under GPLv2. No permission is * granted to use or replicate Red Hat trademarks that are incorporated * in this software or its documentation. */ package org.candlepin.pinsetter.tasks; import org.candlepin.model.JobCurator; import org.candlepin.pinsetter.core.PinsetterKernel; import org.candlepin.pinsetter.core.model.JobStatus; import org.candlepin.pinsetter.core.model.JobStatus.JobState; import com.google.inject.Inject; import com.google.inject.persist.UnitOfWork; import org.hibernate.HibernateException; import org.quartz.DisallowConcurrentExecution; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * UnpauseJob prompts each paused job to check if it * is safe to continue executing every 5 seconds. The polling * approach isn't as fast or efficient as allowing blocking jobs * to trigger the next in line, but this avoids concurrency * and locking problems */ @DisallowConcurrentExecution public class UnpauseJob extends KingpinJob { private static Logger log = LoggerFactory.getLogger(UnpauseJob.class); public static final String DEFAULT_SCHEDULE = "0/5 * * * * ?"; //every five seconds private JobCurator jobCurator; private PinsetterKernel pinsetterKernel; @Inject public UnpauseJob(JobCurator jobCurator, PinsetterKernel pinsetterKernel, UnitOfWork unitOfWork) { super(unitOfWork); this.jobCurator = jobCurator; this.pinsetterKernel = pinsetterKernel; } @Override public void toExecute(JobExecutionContext ctx) throws JobExecutionException { List<JobStatus> waitingJobs; try { waitingJobs = jobCurator.findWaitingJobs(); } catch (HibernateException e) { log.error("Cannot execute query: ", e); throw new JobExecutionException(e); } for (JobStatus j : waitingJobs) { try { boolean schedule = (Boolean) j.getJobClass() .getMethod("isSchedulable", JobCurator.class, JobStatus.class) .invoke(null, jobCurator, j); if (schedule) { log.debug("Triggering waiting job: " + j.getId()); pinsetterKernel.addTrigger(j); j.setState(JobState.CREATED); jobCurator.merge(j); } } catch (Exception e) { - log.debug("Failed to schedule waiting job: " + j.getId(), e); + log.error("Failed to schedule waiting job: " + j.getId(), e); } } } }
true
true
public void toExecute(JobExecutionContext ctx) throws JobExecutionException { List<JobStatus> waitingJobs; try { waitingJobs = jobCurator.findWaitingJobs(); } catch (HibernateException e) { log.error("Cannot execute query: ", e); throw new JobExecutionException(e); } for (JobStatus j : waitingJobs) { try { boolean schedule = (Boolean) j.getJobClass() .getMethod("isSchedulable", JobCurator.class, JobStatus.class) .invoke(null, jobCurator, j); if (schedule) { log.debug("Triggering waiting job: " + j.getId()); pinsetterKernel.addTrigger(j); j.setState(JobState.CREATED); jobCurator.merge(j); } } catch (Exception e) { log.debug("Failed to schedule waiting job: " + j.getId(), e); } } }
public void toExecute(JobExecutionContext ctx) throws JobExecutionException { List<JobStatus> waitingJobs; try { waitingJobs = jobCurator.findWaitingJobs(); } catch (HibernateException e) { log.error("Cannot execute query: ", e); throw new JobExecutionException(e); } for (JobStatus j : waitingJobs) { try { boolean schedule = (Boolean) j.getJobClass() .getMethod("isSchedulable", JobCurator.class, JobStatus.class) .invoke(null, jobCurator, j); if (schedule) { log.debug("Triggering waiting job: " + j.getId()); pinsetterKernel.addTrigger(j); j.setState(JobState.CREATED); jobCurator.merge(j); } } catch (Exception e) { log.error("Failed to schedule waiting job: " + j.getId(), e); } } }
diff --git a/src/org/jruby/util/Convert.java b/src/org/jruby/util/Convert.java index 1b78554fd..e056e249f 100644 --- a/src/org/jruby/util/Convert.java +++ b/src/org/jruby/util/Convert.java @@ -1,2315 +1,2315 @@ /***** BEGIN LICENSE BLOCK ***** * Version: CPL 1.0/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Common Public * License Version 1.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.eclipse.org/legal/cpl-v10.html * * Software distributed under the License is distributed on an "AS * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or * implied. See the License for the specific language governing * rights and limitations under the License. * * Copyright (C) 2007 William N. Dortch <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the CPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the CPL, the GPL or the LGPL. ***** END LICENSE BLOCK *****/ package org.jruby.util; import java.math.BigInteger; import org.jruby.RubyNumeric.InvalidIntegerException; import org.jruby.RubyNumeric.NumberTooLargeException; /** * @author Bill Dortch * * Primitive conversions adapted from java.lang.Integer/Long/Double (C) Sun Microsystems, Inc. * */ public class Convert { /** * Returns a <code>ByteList</code> object representing the * specified integer. The argument is converted to signed decimal * representation and returned as a ByteList. * * @param i an integer to be converted. * @return a ByteList representation of the argument in base&nbsp;10. */ public static final ByteList intToByteList(int i) { if (i == Integer.MIN_VALUE) return new ByteList((byte[])MIN_INT_BYTE_ARRAY.clone(),false); int size = (i < 0) ? arraySize(-i) + 1 : arraySize(i); byte[] buf = new byte[size]; getCharBytes(i, size, buf); return new ByteList(buf,false); } public static final byte[] intToByteArray(int i) { if (i == Integer.MIN_VALUE) return (byte[])MIN_INT_BYTE_ARRAY.clone(); int size = (i < 0) ? arraySize(-i) + 1 : arraySize(i); byte[] buf = new byte[size]; getCharBytes(i, size, buf); return buf; } /** * Returns a <code>ByteList</code> object representing the * specified integer, using the specified radix. The argument is * converted to signed decimal representation and returned as a ByteList. * * @param i an integer to be converted. * @param radix the radix to use in the ByteList representation. * @return a ByteList representation of the argument in the specified radix. */ public static final ByteList intToByteList(int i, int radix) { if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) radix = 10; if (radix == 10) return intToByteList(i); // much faster for base 10 byte buf[] = new byte[33]; boolean negative = (i < 0); int charPos = 32; if (!negative) { i = -i; } while (i <= -radix) { buf[charPos--] = DIGITS[-(i % radix)]; i = i / radix; } buf[charPos] = DIGITS[-i]; if (negative) { buf[--charPos] = '-'; } return new ByteList(buf, charPos, (33 - charPos)); } public static final byte[] intToByteArray(int i, int radix, boolean upper) { if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) radix = 10; if (radix == 10) return intToByteArray(i); // much faster for base 10 byte buf[] = new byte[33]; byte[] digits = upper ? UCDIGITS : DIGITS; boolean negative = (i < 0); int charPos = 32; if (!negative) { i = -i; } while (i <= -radix) { buf[charPos--] = digits[-(i % radix)]; i = i / radix; } buf[charPos] = digits[-i]; if (negative) { buf[--charPos] = '-'; } int len = 33 - charPos; byte[] out = new byte[len]; System.arraycopy(buf,charPos,out,0,len); return out; } /** * Returns a <code>ByteList</code> object representing the specified * <code>long</code>. The argument is converted to signed decimal * representation and returned as a ByteList. * * @param i a <code>long</code> to be converted. * @return a ByteList representation of the argument in base&nbsp;10. */ public static final ByteList longToByteList(long i) { if (i == Long.MIN_VALUE) return new ByteList((byte[])MIN_LONG_BYTE_ARRAY.clone(),false); // int version is slightly faster, use if possible if (i <= Integer.MAX_VALUE && i >= Integer.MIN_VALUE) return intToByteList((int)i); int size = (i < 0) ? arraySize(-i) + 1 : arraySize(i); byte[] buf = new byte[size]; getCharBytes(i, size, buf); return new ByteList(buf,false); } public static final byte[] longToByteArray(long i) { if (i == Long.MIN_VALUE) return (byte[])MIN_LONG_BYTE_ARRAY.clone(); // int version is slightly faster, use if possible if (i <= Integer.MAX_VALUE && i >= Integer.MIN_VALUE) return intToByteArray((int)i); int size = (i < 0) ? arraySize(-i) + 1 : arraySize(i); byte[] buf = new byte[size]; getCharBytes(i, size, buf); return buf; } public static final ByteList longToByteList(long i, int radix) { if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) radix = 10; if (radix == 10) return longToByteList(i); // much faster for base 10 byte[] buf = new byte[65]; int charPos = 64; boolean negative = (i < 0); if (!negative) { i = -i; } while (i <= -radix) { buf[charPos--] = DIGITS[(int)(-(i % radix))]; i = i / radix; } buf[charPos] = DIGITS[(int)(-i)]; if (negative) { buf[--charPos] = '-'; } return new ByteList(buf, charPos, (65 - charPos)); } public static final byte[] longToByteArray(long i, int radix, boolean upper) { if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) radix = 10; if (radix == 10) return longToByteArray(i); // much faster for base 10 byte[] buf = new byte[65]; byte[] digits = upper ? UCDIGITS : DIGITS; int charPos = 64; boolean negative = (i < 0); if (!negative) { i = -i; } while (i <= -radix) { buf[charPos--] = digits[(int)(-(i % radix))]; i = i / radix; } buf[charPos] = digits[(int)(-i)]; if (negative) { buf[--charPos] = '-'; } int len = 65 - charPos; byte[] out = new byte[len]; System.arraycopy(buf,charPos,out,0,len); return out; } public static final byte[] intToCharBytes(int i) { if (i == Integer.MIN_VALUE) return (byte[])MIN_INT_BYTE_ARRAY.clone(); int size = (i < 0) ? arraySize(-i) + 1 : arraySize(i); byte[] buf = new byte[size]; getCharBytes(i, size, buf); return buf; } public static final byte[] longToCharBytes(long i) { if (i == Long.MIN_VALUE) return (byte[])MIN_LONG_BYTE_ARRAY.clone(); int size = (i < 0) ? arraySize(-i) + 1 : arraySize(i); byte[] buf = new byte[size]; getCharBytes(i, size, buf); return buf; } public static final char[] longToChars(long i) { if (i == Long.MIN_VALUE) return (char[])MIN_LONG_CHAR_ARRAY.clone(); int size = (i < 0) ? arraySize(-i) + 1 : arraySize(i); char[] buf = new char[size]; getChars(i, size, buf); return buf; } /** * Places characters representing the integer i into the * character array buf. The characters are placed into * the buffer backwards starting with the least significant * digit at the specified index (exclusive), and working * backwards from there. * * Will fail if i == Integer.MIN_VALUE */ public static final void getCharBytes(int i, int index, byte[] buf) { int q, r; int charPos = index; byte sign = 0; if (i < 0) { sign = '-'; i = -i; } // Generate two digits per iteration while (i >= 65536) { q = i / 100; // really: r = i - (q * 100); r = i - ((q << 6) + (q << 5) + (q << 2)); i = q; buf [--charPos] = DIGIT_ONES[r]; buf [--charPos] =DIGIT_TENS[r]; } // Fall thru to fast mode for smaller numbers // assert(i <= 65536, i); for (;;) { q = (i * 52429) >>> (16+3); r = i - ((q << 3) + (q << 1)); // r = i-(q*10) ... buf [--charPos] = DIGITS[r]; i = q; if (i == 0) break; } if (sign != 0) { buf [--charPos] = sign; } } /** * Places characters representing the integer i into the * character array buf. The characters are placed into * the buffer backwards starting with the least significant * digit at the specified index (exclusive), and working * backwards from there. * * Will fail if i == Long.MIN_VALUE */ public static final void getCharBytes(long i, int index, byte[] buf) { long q; int r; int charPos = index; byte sign = 0; if (i < 0) { sign = '-'; i = -i; } // Get 2 digits/iteration using longs until quotient fits into an int while (i > Integer.MAX_VALUE) { q = i / 100; // really: r = i - (q * 100); r = (int)(i - ((q << 6) + (q << 5) + (q << 2))); i = q; buf[--charPos] = DIGIT_ONES[r]; buf[--charPos] =DIGIT_TENS[r]; } // Get 2 digits/iteration using ints int q2; int i2 = (int)i; while (i2 >= 65536) { q2 = i2 / 100; // really: r = i2 - (q * 100); r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2)); i2 = q2; buf[--charPos] = DIGIT_ONES[r]; buf[--charPos] =DIGIT_TENS[r]; } // Fall thru to fast mode for smaller numbers // assert(i2 <= 65536, i2); for (;;) { q2 = (i2 * 52429) >>> (16+3); r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ... buf[--charPos] = DIGITS[r]; i2 = q2; if (i2 == 0) break; } if (sign != 0) { buf[--charPos] = sign; } } public static final void getChars(long i, int index, char[] buf) { long q; int r; int charPos = index; char sign = 0; if (i < 0) { sign = '-'; i = -i; } // Get 2 digits/iteration using longs until quotient fits into an int while (i > Integer.MAX_VALUE) { q = i / 100; // really: r = i - (q * 100); r = (int)(i - ((q << 6) + (q << 5) + (q << 2))); i = q; buf[--charPos] = CDIGIT_ONES[r]; buf[--charPos] = CDIGIT_TENS[r]; } // Get 2 digits/iteration using ints int q2; int i2 = (int)i; while (i2 >= 65536) { q2 = i2 / 100; // really: r = i2 - (q * 100); r = i2 - ((q2 << 6) + (q2 << 5) + (q2 << 2)); i2 = q2; buf[--charPos] = CDIGIT_ONES[r]; buf[--charPos] = CDIGIT_TENS[r]; } // Fall thru to fast mode for smaller numbers // assert(i2 <= 65536, i2); for (;;) { q2 = (i2 * 52429) >>> (16+3); r = i2 - ((q2 << 3) + (q2 << 1)); // r = i2-(q2*10) ... buf[--charPos] = CDIGITS[r]; i2 = q2; if (i2 == 0) break; } if (sign != 0) { buf[--charPos] = sign; } } /** * Requires positive x. * For negative numbers, reverse the sign before calling and add one to * the result (for the '-' sign). */ public static final int arraySize(long x) { long p = 10; for (int i=1; i<19; i++) { if (x < p) return i; p = 10*p; } return 19; } /** * Requires positive x. * For negative numbers, reverse the sign before calling and add one to * the result (for the '-' sign). */ public static final int arraySize(int x) { for (int i=0; ; i++) if (x <= SIZE_TABLE[i]) return i+1; } // the following group of conversions to binary/octal/hex // is mostly for use by the new sprintf code public static final byte[] intToBinaryBytes(int i) { return intToUnsignedBytes(i, 1, false); } public static final byte[] intToOctalBytes(int i) { return intToUnsignedBytes(i, 3, false); } public static final byte[] intToHexBytes(int i) { return intToUnsignedBytes(i, 4, false); } public static final byte[] intToHexBytes(int i, boolean upper) { return intToUnsignedBytes(i, 4, upper); } public static final ByteList intToBinaryByteList(int i) { return new ByteList(intToUnsignedBytes(i, 1, false)); } public static final ByteList intToOctalByteList(int i) { return new ByteList(intToUnsignedBytes(i, 3, false)); } public static final ByteList intToHexByteList(int i) { return new ByteList(intToUnsignedBytes(i, 4, false)); } public static final ByteList intToHexByteList(int i, boolean upper) { return new ByteList(intToUnsignedBytes(i, 4, upper)); } public static final byte[] longToBinaryBytes(long i) { return longToUnsignedBytes(i, 1, false); } public static final byte[] longToOctalBytes(long i) { return longToUnsignedBytes(i, 3, false); } public static final byte[] longToHexBytes(long i) { return longToUnsignedBytes(i, 4, false); } public static final byte[] longToHexBytes(long i, boolean upper) { return longToUnsignedBytes(i, 4, true); } public static final ByteList longToBinaryByteList(long i) { return new ByteList(longToUnsignedBytes(i, 1, false)); } public static final ByteList longToOctalByteList(long i) { return new ByteList(longToUnsignedBytes(i, 3, false)); } public static final ByteList longToHexByteList(long i) { return new ByteList(longToUnsignedBytes(i, 4, false)); } public static final ByteList longToHexByteList(long i, boolean upper) { return new ByteList(longToUnsignedBytes(i, 4, upper)); } /** * Convert the integer to an unsigned number. * The character bytes are right-aligned in the 32-byte result. */ public static final byte[] intToRawUnsignedBytes(int i, int shift) { byte[] buf = new byte[32]; int charPos = 32; int radix = 1 << shift; int mask = radix - 1; do { buf[--charPos] = DIGITS[i & mask]; i >>>= shift; } while (i != 0); return buf; } /** * Convert the integer to an unsigned number. * The result array is sized to fit the actual character length. */ public static final byte[] intToUnsignedBytes(int i, int shift, boolean upper) { byte[] buf = new byte[32]; int charPos = 32; int radix = 1 << shift; int mask = radix - 1; byte[] digits = upper ? UCDIGITS : DIGITS; do { buf[--charPos] = digits[i & mask]; i >>>= shift; } while (i != 0); int length = 32 - charPos; byte[] result = new byte[length]; System.arraycopy(buf,charPos,result,0,length); return result; } /** * Convert the long to an unsigned number. * The character bytes are right-aligned in the 64-byte result. */ public static final byte[] longToRawUnsignedBytes(long i, int shift) { byte[] buf = new byte[64]; int charPos = 64; int radix = 1 << shift; long mask = radix - 1; do { buf[--charPos] = DIGITS[(int)(i & mask)]; i >>>= shift; } while (i != 0); return buf; } /** * Convert the long to an unsigned number. * The result array is sized to fit the actual character length. */ public static final byte[] longToUnsignedBytes(long i, int shift, boolean upper) { byte[] buf = new byte[64]; int charPos = 64; int radix = 1 << shift; long mask = radix - 1; byte[] digits = upper ? UCDIGITS : DIGITS; do { buf[--charPos] = digits[(int)(i & mask)]; i >>>= shift; } while (i != 0); int length = 64 - charPos; byte[] result = new byte[length]; System.arraycopy(buf,charPos,result,0,length); return result; } /** * Converts a ByteList to a primitive long value, using the specified * base. If base is zero, defaults to 10 unless a base specifier is encountered * (e.g., '0x'). Follows Ruby rules for converting Strings to Integers. Will fail * with NumberFormatException if the number is too large for a long. If the * raise flag is set, will also fail on certain formatting errors (zero-length * array; zero-length excluding sign; no valid digits). * * @param bytes * @param buflen the effective length of the array (may be less than bytes.length) * @param base * @param raise * @return * @throws NumberFormatException */ public static final long byteListToLong(ByteList bytes, int base, boolean raise) { return byteArrayToLong(bytes.unsafeBytes(),bytes.length(),base,raise); } public static final long byteListToLong(ByteList bytes, int base) { return byteArrayToLong(bytes.unsafeBytes(),bytes.length(),base,false); } // for base 10 ByteList public static final long byteListToLong(ByteList bytes) { return byteArrayToLong(bytes.unsafeBytes(),bytes.length(),10,false); } /** * Converts a ByteList to a BigInteger value, using the specified base. * If base is zero, defaults to 10 unless a base specifier is encountered * (e.g., '0x'). Follows Ruby rules for converting Strings to Integers. Will * fail with NumberFormatException on certain formatting errors (zero-length * array; zero-length excluding sign; no valid digits). * <p> * Intended to be called after byteListToLong if that method fails. * * @param bytes * @param buflen the effective length of the array (may be less than bytes.length) * @param base * @return * @throws NumberFormatException, IllegalArgumentException */ public static final BigInteger byteListToBigInteger(ByteList bytes, int base, boolean raise) { return byteArrayToBigInteger(bytes.unsafeBytes(),bytes.length(),base,raise); } public static final BigInteger byteListToBigInteger(ByteList bytes, int base) { return byteArrayToBigInteger(bytes.unsafeBytes(),bytes.length(),base,false); } // for base 10 ByteList public static final BigInteger byteListToBigInteger(ByteList bytes) { return byteArrayToBigInteger(bytes.unsafeBytes(),bytes.length(),10,false); } /** * Converts a byte array to a primitive long value, using the specified * base. If base is zero, defaults to 10 unless a base specifier is encountered * (e.g., '0x'). Follows Ruby rules for converting Strings to Integers. Will fail * with NumberFormatException if the number is too large for a long. If the * raise flag is set, will also fail on certain formatting errors (zero-length * array; zero-length excluding sign; no valid digits). * * @param bytes * @param buflen the effective length of the array (may be less than bytes.length) * @param base * @param strict * @return * @throws NumberFormatException, IllegalArgumentException */ public static final long byteArrayToLong(byte[] bytes, int buflen, int base, boolean strict) { final int SCOMPLETE = 0; final int SBEGIN = 1; final int SSIGN = 2; final int SZERO = 3; final int SPOST_SIGN = 4; final int SDIGITS = 5; final int SDIGIT = 6; final int SDIGIT_STRICT = 7; final int SDIGIT_USC = 8; final int SEOD_STRICT = 13; final int SEOF = 14; final int SERR_NOT_STRICT = 17; final int SERR_TOO_BIG = 18; final int FLAG_NEGATIVE = 1 << 0; final int FLAG_DIGIT = 1 << 1; final int FLAG_UNDERSCORE = 1 << 2; final int FLAG_WHITESPACE = 1 << 3; if (bytes == null) { throw new IllegalArgumentException("null bytes"); } if (buflen < 0 || buflen > bytes.length) { throw new IllegalArgumentException("invalid buflen specified"); } int radix = base == 0 ? 10 : base; if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { throw new IllegalArgumentException("illegal radix " + radix); } if (buflen == 0) { throw new InvalidIntegerException(); } int i = 0; byte ival; int flags = 0; long limit = -Long.MAX_VALUE; long result = 0; long multmin = 0; int digit; int state = SBEGIN; while (state != SCOMPLETE) { states: switch(state) { case SBEGIN: if (strict) { for (; i < buflen && bytes[i] <= ' '; i++) ; } else { for (; i < buflen && ((ival = bytes[i]) <= ' ' || ival == '_'); i++) ; } state = i < buflen ? SSIGN : SEOF; break; case SSIGN: switch(bytes[i]) { case '-': flags |= FLAG_NEGATIVE; limit = Long.MIN_VALUE; case '+': if (++i >= buflen) { state = SEOF; } else if (bytes[i] == '0') { state = SZERO; } else { state = SPOST_SIGN; } break states; case '0': state = SZERO; break states; default: state = SDIGITS; break states; } case SZERO: if (++i >= buflen) { state = SCOMPLETE; break; } switch (bytes[i]) { case 'x': case 'X': if (base == 0 || base == 16) { radix = 16; state = ++i >= buflen ? SEOF : SPOST_SIGN; } else { state = SDIGITS; } break states; case 'b': case 'B': if (base == 0 || base == 2) { radix = 2; state = ++i >= buflen ? SEOF : SPOST_SIGN; } else { state = SDIGITS; } break states; default: if (base == 0 || base == 8) { radix = 8; } flags |= FLAG_DIGIT; state = SDIGITS; break states; } case SPOST_SIGN: if (strict) { int ibefore = i; for (; i < buflen && bytes[i] <= ' '; i++) ; if (ibefore != i) { // set this to enforce no-underscore rule (though I think // it's an MRI bug) flags |= FLAG_WHITESPACE; } } else { for ( ; i < buflen && ((ival = bytes[i]) <= ' ' || ival == '_'); i++) { if (ival == '_') { if ((flags & FLAG_WHITESPACE) != 0) { throw new InvalidIntegerException(); } flags |= FLAG_UNDERSCORE; } else { if ((flags & FLAG_UNDERSCORE) != 0) { throw new InvalidIntegerException(); } flags |= FLAG_WHITESPACE; } } } state = i < buflen ? SDIGITS : SEOF; break; case SDIGITS: digit = Character.digit((char) bytes[i],radix); if (digit < 0) { state = strict ? SEOD_STRICT : SEOF; break; } result = -digit; if (++i >= buflen) { state = SCOMPLETE; break; } multmin = limit / radix; flags = (flags | FLAG_DIGIT) & ~FLAG_UNDERSCORE; state = strict ? SDIGIT_STRICT : SDIGIT; break; case SDIGIT: while ((digit = Character.digit((char) bytes[i],radix)) >= 0) { if (result < multmin || ((result *= radix) < limit + digit)) { state = SERR_TOO_BIG; break states; } result -= digit; if (++i >= buflen) { state = SCOMPLETE; break states; } } state = bytes[i++] == '_' ? SDIGIT_USC : SEOF; break; case SDIGIT_USC: for ( ; i < buflen && bytes[i] == '_'; i++) ; state = i < buflen ? SDIGIT : SEOF; break; case SDIGIT_STRICT: while ((digit = Character.digit((char) bytes[i],radix)) >= 0) { if (result < multmin || ((result *= radix) < limit + digit)) { state = SERR_TOO_BIG; break states; } result -= digit; if (++i >= buflen) { state = SCOMPLETE; break states; } flags &= ~FLAG_UNDERSCORE; } if (bytes[i] == '_') { if ((flags & (FLAG_UNDERSCORE | FLAG_WHITESPACE)) != 0) { state = SERR_NOT_STRICT; break; } flags |= FLAG_UNDERSCORE; state = ++i >= buflen ? SEOD_STRICT : SDIGIT_STRICT; } else { state = SEOD_STRICT; } break; case SEOD_STRICT: if ((flags & FLAG_UNDERSCORE)!= 0) { state = SERR_NOT_STRICT; break; } for ( ; i < buflen && bytes[i] <= ' '; i++ ); state = i < buflen ? SERR_NOT_STRICT : SCOMPLETE; break; case SEOF: if ((flags & FLAG_DIGIT) == 0) { throw new InvalidIntegerException("no digits supplied"); } state = SCOMPLETE; break; case SERR_TOO_BIG: throw new NumberTooLargeException("can't convert to long"); case SERR_NOT_STRICT: throw new InvalidIntegerException("does not meet strict criteria"); } // switch } //while if ((flags & FLAG_NEGATIVE) == 0) { return -result; } else { return result; } } /** * Converts a byte array to a BigInteger value, using the specified base. * If base is zero, defaults to 10 unless a base specifier is encountered * (e.g., '0x'). Follows Ruby rules for converting Strings to Integers. Will * fail with NumberFormatException on certain formatting errors (zero-length * array; zero-length excluding sign; no valid digits). * <p> * Intended to be called after byteArrayToLong if that method fails. * * @param bytes * @param buflen the effective length of the array (may be less than bytes.length) * @param base * @return * @throws NumberFormatException, IllegalArgumentException */ public static final BigInteger byteArrayToBigInteger(byte[] bytes, int buflen, int base, boolean strict) { final int SCOMPLETE = 0; final int SBEGIN = 1; final int SSIGN = 2; final int SZERO = 3; final int SPOST_SIGN = 4; final int SDIGITS = 5; final int SDIGIT = 6; final int SDIGIT_STRICT = 7; final int SDIGIT_USC = 8; final int SEOD_STRICT = 13; final int SEOF = 14; final int SERR_NOT_STRICT = 17; final int FLAG_NEGATIVE = 1 << 0; final int FLAG_DIGIT = 1 << 1; final int FLAG_UNDERSCORE = 1 << 2; final int FLAG_WHITESPACE = 1 << 3; if (bytes == null) { throw new IllegalArgumentException("null bytes"); } if (buflen < 0 || buflen > bytes.length) { throw new IllegalArgumentException("invalid buflen specified"); } int radix = base == 0 ? 10 : base; if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { throw new IllegalArgumentException("illegal radix " + radix); } if (buflen == 0) { throw new InvalidIntegerException(); } int i = 0; byte ival; int flags = 0; int digit; int offset = 0; char[] chars = null; int state = SBEGIN; while (state != SCOMPLETE) { states: switch(state) { case SBEGIN: if (strict) { for (; i < buflen && bytes[i] <= ' '; i++) ; } else { for (; i < buflen && ((ival = bytes[i]) <= ' ' || ival == '_'); i++) ; } state = i < buflen ? SSIGN : SEOF; break; case SSIGN: switch(bytes[i]) { case '-': flags |= FLAG_NEGATIVE; case '+': if (++i >= buflen) { state = SEOF; } else if (bytes[i] == '0') { state = SZERO; } else { state = SPOST_SIGN; } break states; case '0': state = SZERO; break states; default: state = SDIGITS; break states; } case SZERO: if (++i >= buflen) { state = SCOMPLETE; break; } switch (bytes[i]) { case 'x': case 'X': if (base == 0 || base == 16) { radix = 16; state = ++i >= buflen ? SEOF : SPOST_SIGN; } else { state = SDIGITS; } break states; case 'b': case 'B': if (base == 0 || base == 2) { radix = 2; state = ++i >= buflen ? SEOF : SPOST_SIGN; } else { state = SDIGITS; } break states; default: if (base == 0 || base == 8) { radix = 8; } flags |= FLAG_DIGIT; state = SDIGITS; break states; } case SPOST_SIGN: if (strict) { int ibefore = i; for (; i < buflen && bytes[i] <= ' '; i++) ; if (ibefore != i) { // set this to enforce no-underscore rule (though I think // it's an MRI bug) flags |= FLAG_WHITESPACE; } } else { for ( ; i < buflen && ((ival = bytes[i]) <= ' ' || ival == '_'); i++) { if (ival == '_') { if ((flags & FLAG_WHITESPACE) != 0) { throw new InvalidIntegerException(); } flags |= FLAG_UNDERSCORE; } else { if ((flags & FLAG_UNDERSCORE) != 0) { throw new InvalidIntegerException(); } flags |= FLAG_WHITESPACE; } } } state = i < buflen ? SDIGITS : SEOF; break; case SDIGITS: digit = Character.digit((char) bytes[i],radix); if (digit < 0) { state = strict ? SEOD_STRICT : SEOF; break; } if ((flags & FLAG_NEGATIVE) == 0) { chars = new char[buflen - i]; chars[0] = (char)bytes[i]; offset = 1; } else { chars = new char[buflen - i + 1]; chars[0] = '-'; chars[1] = (char)bytes[i]; offset = 2; } if (++i >= buflen) { state = SCOMPLETE; break; } flags = (flags | FLAG_DIGIT) & ~FLAG_UNDERSCORE; state = strict ? SDIGIT_STRICT : SDIGIT; break; case SDIGIT: while ((digit = Character.digit((char) bytes[i],radix)) >= 0) { chars[offset++] = (char)bytes[i]; if (++i >= buflen) { state = SCOMPLETE; break states; } } state = bytes[i++] == '_' ? SDIGIT_USC : SEOF; break; case SDIGIT_USC: for ( ; i < buflen && bytes[i] == '_'; i++) ; state = i < buflen ? SDIGIT : SEOF; break; case SDIGIT_STRICT: while ((digit = Character.digit((char)bytes[i],radix)) >= 0) { chars[offset++] = (char)bytes[i]; if (++i >= buflen) { state = SCOMPLETE; break states; } flags &= ~FLAG_UNDERSCORE; } if (bytes[i] == '_') { if ((flags & (FLAG_UNDERSCORE | FLAG_WHITESPACE)) != 0) { state = SERR_NOT_STRICT; break; } flags |= FLAG_UNDERSCORE; state = ++i >= buflen ? SEOD_STRICT : SDIGIT_STRICT; } else { state = SEOD_STRICT; } break; case SEOD_STRICT: if ((flags & FLAG_UNDERSCORE)!= 0) { state = SERR_NOT_STRICT; break; } for ( ; i < buflen && bytes[i] <= ' '; i++ ); state = i < buflen ? SERR_NOT_STRICT : SCOMPLETE; break; case SEOF: if ((flags & FLAG_DIGIT) == 0) { throw new InvalidIntegerException("no digits supplied"); } state = SCOMPLETE; break; case SERR_NOT_STRICT: throw new InvalidIntegerException("does not meet strict criteria"); } // switch } //while if (chars == null) { // 0, won't happen if byteArrayToLong called first return BIG_INT_ZERO; } else { return new BigInteger(new String(chars,0,offset),radix); } } /** * Converts a ByteList containing a RubyString representation of a double * value to a double. Equivalent to Double.parseDouble(String s), but accounts for * embedded underscore characters, as permitted in Ruby strings (single underscores * allowed between digits in strict mode, multiple in non-strict mode). * * @param bytes the ByteList containing the RubyString value to convert * @param strict if true, strict rules (as required by Float(str)) are enforced; * otherwise, the laxer rules of str.to_f are employed. * @return the converted double value */ public static final double byteListToDouble(ByteList bytes, boolean strict) { return byteArrayToDouble(bytes.unsafeBytes(),bytes.length(),strict); } public static final double byteListToDouble(ByteList bytes) { return byteArrayToDouble(bytes.unsafeBytes(),bytes.length(),false); } /** * Converts a byte array containing a RubyString representation of a double * value to a double. Equivalent to Double.parseDouble(String s), but accounts for * embedded underscore characters, as permitted in Ruby strings (single underscores * allowed between digits in strict mode, multiple in non-strict mode). * * @param bytes the array containing the RubyString value to convert * @param buflen the length of the array to be used * @param strict if true, strict rules (as required by Float(str)) are enforced; * otherwise, the laxer rules of str.to_f are employed. * @return the converted double value */ public static final double byteArrayToDouble(byte[] bytes, int buflen, boolean strict) { // Simple cases ( abs(exponent) <= 22 [up to 37 depending on significand length]) // are converted directly, which is considerably faster than creating a Java // String and passing it to Double.parseDouble() (which in turn passes it to // sun.misc.FloatingDecimal); the latter approach involves 5 object allocations // (3 arrays + String + FloatingDecimal) and 3 array copies, two of them one byte/char // at a time (here and in FloatingDecimal). // However, the latter approach is employed for more difficult cases (generally // speaking, those that require rounding). (The code for the difficult cases is // quite involved; see sun.misc.FloatingDecimal.java if you're interested.) // states final int SCOMPLETE = 0; final int SBEGIN = 1; // remove leading whitespace (includes _ for lax) final int SSIGN = 2; // get sign, if any // optimistic pass - calculate value as digits are processed final int SOPTDIGIT = 3; // digits - lax rules final int SOPTDECDIGIT = 4; // decimal digits - lax rules final int SOPTEXP = 9; // exponent sign/digits - lax rules final int SOPTDIGIT_STRICT = 6; // digits - strict rules final int SOPTDECDIGIT_STRICT = 7; // decimal digits - strict rules final int SOPTEXP_STRICT = 8; // exponent sign/digits - strict rules final int SOPTCALC = 5; // complete calculation if possible // fallback pass - gather chars into array and pass to Double.parseDouble() final int SDIGIT = 10; // digits - lax rules final int SDECDIGIT = 11; // decimal digits - lax rules final int SEXP = 12; // exponent sign/digits - lax rules final int SDIGIT_STRICT = 13; // digits - strict rules final int SDECDIGIT_STRICT = 14; // decimal digits - strict rules final int SEXP_STRICT = 15; // exponent sign/digits - strict rules final int SERR_NOT_STRICT = 16; // largest abs(exponent) we can (potentially) handle without // calling Double.parseDouble() (aka sun.misc.FloatingDecimal) final int MAX_EXP = MAX_DECIMAL_DIGITS + MAX_SMALL_10; // (37) if (bytes == null) { throw new IllegalArgumentException("null bytes"); } if (buflen < 0 || buflen > bytes.length) { throw new IllegalArgumentException("invalid buflen specified"); } // TODO: get rid of this (lax returns 0.0, strict will throw) if (buflen == 0) { throw new NumberFormatException(); } int i = 0; byte ival; boolean negative = false; // fields used for direct (optimistic) calculation int nDigits = 0; // number of significant digits, updated as parsed int nTrailingZeroes = 0; // zeroes that may go to significand or exponent int decPos = -1; // offset of decimal pt from start (-1 -> no decimal) long significand = 0; // significand, updated as parsed int exponent = 0; // exponent, updated as parsed // fields used for fallback (send to Double.parseDouble()) int startPos = 0; // start of digits (or . if no leading digits) char[] chars = null; int offset = 0; int lastValidOffset = 0; int state = SBEGIN; while (state != SCOMPLETE) { states: switch(state) { case SBEGIN: if (strict) { for (; i < buflen && bytes[i] <= ' '; i++) ; } else { for (; i < buflen && ((ival = bytes[i]) <= ' ' || ival == '_'); i++) ; } if ( i >= buflen) { state = strict ? SERR_NOT_STRICT : SCOMPLETE; break; } // drop through for sign case SSIGN: switch(bytes[i]) { case '-': negative = true; case '+': if (++i >= buflen) { // TODO: turn off the negative? will return -0.0 in lax mode state = strict ? SERR_NOT_STRICT : SCOMPLETE; break states; } } // switch startPos = i; // will use this if we have to go back the slow way if (strict) { state = SOPTDIGIT_STRICT; break; } // drop through for non-strict digits case SOPTDIGIT: // first char must be digit or decimal point switch(ival = bytes[i++]) { case '0': // ignore leading zeroes break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': significand = (long)((int)ival-(int)'0'); nDigits = 1; break; // switch case '.': state = SOPTDECDIGIT; break states; default: // no digits, go calc (will return +/- 0.0 for lax) state = SOPTCALC; break states; } // switch for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': // ignore leading zeroes if (nDigits > 0) { // just save a count of zeroes for now; if no digit // ends up following them, they'll be applied to the // exponent rather than the significand (and our max // length for optimistic calc). nTrailingZeroes++; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': // ok, got a non-zero, have to own up to our horded zeroes if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { // oh, well, it was worth a try. go let // Double/FloatingDecimal handle it state = SDIGIT; break states; } case '.': state = SOPTDECDIGIT; break states; case 'e': case 'E': state = SOPTEXP; break states; case '_': // ignore break; // switch default: // end of parseable data, go to calc state = SOPTCALC; break states; } // switch } // for state = SOPTCALC; break; case SOPTDECDIGIT: decPos = nDigits + nTrailingZeroes; for ( ; i < buflen && bytes[i] == '_'; i++ ) ; // first non_underscore char must be digit if (i < buflen) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } else { exponent--; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } default: // no dec digits, end of parseable data, go to calc state = SOPTCALC; break states; } // switch } // if for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } else { exponent--; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } case 'e': case 'E': state = SOPTEXP; break states; case '_': // ignore break; // switch default: // end of parseable data, go to calc state = SOPTCALC; break states; } // switch } // for // no exponent, so drop through for calculation case SOPTCALC: // calculation for simple (and typical) case, // adapted from sun.misc.FloatingDecimal if (nDigits == 0) { return negative ? -0.0d : 0.0d; } if (decPos < 0) { exponent += nTrailingZeroes; } else { exponent += decPos - nDigits; } double dValue = (double)significand; if (exponent == 0 || dValue == 0.0) { return negative ? -dValue : dValue; } else if ( exponent >= 0 ){ if ( exponent <= MAX_SMALL_10 ){ dValue *= SMALL_10_POWERS[exponent]; return negative ? -dValue : dValue; } int slop = MAX_DECIMAL_DIGITS - nDigits; if ( exponent <= MAX_SMALL_10+slop ){ dValue = (dValue * SMALL_10_POWERS[slop]) * SMALL_10_POWERS[exponent-slop]; return negative ? -dValue : dValue; } } else { // TODO: it's not clear to me why, in FloatingDecimal, the // "slop" calculation performed above for positive exponents // isn't used for negative exponents as well. Will find out... if ( exponent >= -MAX_SMALL_10 ){ dValue = dValue / SMALL_10_POWERS[-exponent]; return negative ? -dValue : dValue; } } // difficult case, send to Double/FloatingDecimal state = SDIGIT; break; case SOPTEXP: { // lax (str.to_f) allows underscores between e/E and sign for ( ; i < buflen && bytes[i] == '_' ; i++ ) ; if (i >= buflen) { state = SOPTCALC; break; } int expSign = 1; int expSpec = 0; switch (bytes[i]) { case '-': expSign = -1; case '+': if (++i >= buflen) { state = SOPTCALC; break states; } } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if ((expSpec = expSpec * 10 + ((int)ival-(int)'0')) >= MAX_EXP) { // too big for us state = SDIGIT; break states; } break; //switch case '_': break; //switch default: exponent += expSign * expSpec; state = SOPTCALC; break states; } } exponent += expSign * expSpec; state = SOPTCALC; break; } // block case SOPTDIGIT_STRICT: // first char must be digit or decimal point switch(ival = bytes[i++]) { case '0': break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': significand = (long)((int)ival-(int)'0'); nDigits = 1; break; // switch case '.': state = SOPTDECDIGIT_STRICT; break states; default: // no digits, error state = SERR_NOT_STRICT; break states; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } case '.': state = SOPTDECDIGIT_STRICT; break states; case 'e': case 'E': state = SOPTEXP_STRICT; break states; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; // switch default: // only whitespace allowed after value for strict - for ( ; i < buflen && bytes[i++] <= ' '; ); + for ( ; i < buflen && bytes[i] <= ' '; i++ ); state = i < buflen ? SERR_NOT_STRICT : SOPTCALC; break states; } // switch } // for // no more data, OK for strict to go calc state = SOPTCALC; break; case SOPTDECDIGIT_STRICT: decPos = nDigits + nTrailingZeroes; // first char must be digit if (i < buflen) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } else { exponent--; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } default: // no dec digits after '.', error for strict state = SERR_NOT_STRICT; break states; } // switch } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } else { exponent--; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } case 'e': case 'E': state = SOPTEXP_STRICT; break states; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; // switch default: // only whitespace allowed after value for strict - for ( ; i < buflen && bytes[i++] <= ' '; ); + for ( ; i < buflen && bytes[i] <= ' '; i++); state = i < buflen ? SERR_NOT_STRICT : SOPTCALC; break states; } // switch } // for // no more data, OK for strict to go calc state = SOPTCALC; break; case SOPTEXP_STRICT: { int expSign = 1; int expSpec = 0; if ( i < buflen) { switch (bytes[i]) { case '-': expSign = -1; case '+': if (++i >= buflen) { state = SERR_NOT_STRICT; break states; } } } else { state = SERR_NOT_STRICT; break; } // must be at least one digit for strict if ( i < buflen ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': expSpec = (int)ival-(int)'0'; break; //switch default: state = SERR_NOT_STRICT; break states; } } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if ((expSpec = expSpec * 10 + ((int)ival-(int)'0')) >= MAX_EXP) { // too big for us state = SDIGIT; break states; } break; //switch case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; //switch default: exponent += expSign * expSpec; // only whitespace allowed after value for strict - for ( ; i < buflen && bytes[i++] <= ' '; ); + for ( ; i < buflen && bytes[i] <= ' '; i++); state = i < buflen ? SERR_NOT_STRICT : SOPTCALC; break states; } // switch } // for exponent += expSign * expSpec; state = SOPTCALC; break; } // block // fallback, copy non-whitespace chars to char buffer and send // to Double.parseDouble() (front for sun.misc.FloatingDecimal) case SDIGIT: i = startPos; if (negative) { chars = new char[buflen - i + 1]; chars[0] = '-'; offset = 1; } else { chars = new char[buflen - i]; } if (strict) { state = SDIGIT_STRICT; break; } // first char must be digit or decimal point if (i < buflen) { switch(ival = bytes[i++]) { case '0': // ignore leading zeroes break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case '.': state = SDECDIGIT; break states; default: state = SCOMPLETE; break states; } // switch } // if for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case '.': state = SDECDIGIT; break states; case 'e': case 'E': state = SEXP; break states; case '_': break; // switch default: state = SCOMPLETE; break states; } // switch } // for state = SCOMPLETE; break; case SDECDIGIT: chars[offset++] = '.'; for ( ; i < buflen && bytes[i] == '_'; i++) ; if ( i < buflen) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch default: state = SCOMPLETE; break states; } // switch } // if for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case 'e': case 'E': state = SEXP; break states; case '_': break; // switch default: state = SCOMPLETE; break states; } // switch } // for state = SCOMPLETE; break; case SEXP: chars[offset++] = 'E'; for ( ; i < buflen && bytes[i] == '_'; i++) ; if (i >= buflen) { state = SCOMPLETE; break; } switch(bytes[i]) { case '-': case '+': chars[offset++] = (char)bytes[i]; if (++i >= buflen) { state = SCOMPLETE; break states; } } for ( ; i < buflen; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; case '_': break; default: state = SCOMPLETE; break states; } } state = SCOMPLETE; break; case SDIGIT_STRICT: // first char must be digit or decimal point if (i < buflen) { switch(ival = bytes[i++]) { case '0': // ignore leading zeroes break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case '.': state = SDECDIGIT_STRICT; break states; default: state = SERR_NOT_STRICT; break states; } // switch } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case '.': state = SDECDIGIT_STRICT; break states; case 'e': case 'E': state = SEXP_STRICT; break states; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; //switch default: // only whitespace allowed after value for strict - for ( ; i < buflen && bytes[i++] <= ' '; ) ; + for ( ; i < buflen && bytes[i] <= ' '; i++) ; state = i < buflen ? SERR_NOT_STRICT : SCOMPLETE; break states; } // switch } // for state = SCOMPLETE; break; case SDECDIGIT_STRICT: chars[offset++] = '.'; if ( i < buflen) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch default: state = SERR_NOT_STRICT; break states; } // switch } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case 'e': case 'E': state = SEXP_STRICT; break states; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; //switch default: - for ( ; i < buflen && bytes[i++] <= ' '; ) ; + for ( ; i < buflen && bytes[i] <= ' '; i++) ; state = i < buflen ? SERR_NOT_STRICT : SCOMPLETE; break states; } // switch } // for state = SCOMPLETE; break; case SEXP_STRICT: chars[offset++] = 'E'; if ( i < buflen ) { switch (bytes[i]) { case '-': case '+': chars[offset++] = (char)bytes[i]; if (++i >= buflen) { state = SERR_NOT_STRICT; break states; } } } else { state = SERR_NOT_STRICT; break; } // must be at least one digit for strict if ( i < buflen ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; //switch default: state = SERR_NOT_STRICT; break states; } } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; //switch default: - for ( ; i < buflen && bytes[i++] <= ' '; ) ; + for ( ; i < buflen && bytes[i] <= ' '; i++) ; state = i < buflen ? SERR_NOT_STRICT : SCOMPLETE; break states; } } state = SCOMPLETE; break; case SERR_NOT_STRICT: throw new NumberFormatException("does not meet strict criteria"); } // switch } //while if (chars == null || lastValidOffset == 0) { return 0.0; } else { return Double.parseDouble(new String(chars,0,lastValidOffset)); } } public static final byte[] doubleToByteArray(double d) { // TODO: develop an efficient method to do this directly and avoid all // the excess array allocating/copying (since we'll need to parse this // result anyway to format it for output). See sun.misc.FloatingDecimal. return ByteList.plain(Double.toString(d)); } public static final byte[] twosComplementToBinaryBytes(byte[] in) { return twosComplementToUnsignedBytes(in,1,false); } public static final byte[] twosComplementToOctalBytes(byte[] in) { return twosComplementToUnsignedBytes(in,3,false); } public static final byte[] twosComplementToHexBytes(byte[] in, boolean upper) { return twosComplementToUnsignedBytes(in,4,upper); } // shift is power of 2, so 1 = binary, 3 - octal, 4 = hex, anyhing // larger will error. public static final byte[] twosComplementToUnsignedBytes(byte[] in, int shift, boolean upper) { if (shift < 1 || shift > 4) { throw new IllegalArgumentException("shift value must be 1-4"); } int ilen = in.length; int olen = (ilen * 8 + shift - 1 ) / shift; byte[] out = new byte[olen]; int mask = (1 << shift) - 1; byte[] digits = upper ? UCDIGITS : DIGITS; int bitbuf = 0; int bitcnt = 0; for (int i = ilen, o = olen; --o >= 0; ) { if (bitcnt < shift) { bitbuf |= ((int)in[--i] & (int)0xff) << bitcnt; bitcnt += 8; } out[o] = digits[bitbuf & mask]; bitbuf >>= shift; bitcnt -= shift; } return out; } // The following two methods, used in conjunction, provide the // equivalent of String#trim() public static final int skipLeadingWhitespace(byte[] bytes){ int length = bytes.length; int start = 0; for ( ; start < length && bytes[start] <= ' '; start++) ; return start; } public static final int skipTrailingWhitespace(byte[] bytes) { int stop = bytes.length - 1; for ( ; stop >= 0 && bytes[stop] <= ' '; stop-- ) ; return stop + 1; } /** * Trims whitespace (any bytes <= 0x20) from the beginning and end * of the array. This is equivalent to String#trim for byte arrays. If * no bytes are trimmed, the original array is returned. * * @param bytes the array to be trimmed * @return the trimmed array if trimming performed, otherwise the original array */ public static final byte[] trim (byte[] bytes) { if (bytes.length == 0) return bytes; int start = skipLeadingWhitespace(bytes); if (start >= bytes.length) { return EMPTY_BYTES; } int stop = skipTrailingWhitespace(bytes); int length = stop - start; if (length == bytes.length) return bytes; byte[] trimmed = new byte[length]; System.arraycopy(bytes,0,trimmed,0,length); return trimmed; } /** * Deletes the byte at the specified position, shifting all bytes * to the right of it left by one byte. If the copy flag is set, * a new array (one byte shorter) will be created and the original * will remain unchanged; otherwise, the last byte of the array is * set to zero. * * @param bytes the array to 'delete' a byte from * @param pos the offset of the byte to delete * @param copy if true, a new copy of the array will be created, with * the original preserved */ public static final byte[] delete(byte[] bytes, int pos, boolean copy) { int buflen = bytes.length; int newlen = buflen - 1; if (pos < 0 || pos > newlen) { throw new IllegalArgumentException("illegal position for delete"); } int src = pos + 1; if (copy) { if (newlen == 0) { return EMPTY_BYTES; } byte[] newbytes = new byte[newlen]; if (pos == 0) { System.arraycopy(bytes,1,newbytes,0,newlen); } else { System.arraycopy(bytes,0,newbytes,0,pos); System.arraycopy(bytes,src,newbytes,pos,newlen-pos); } return newbytes; } else { if (newlen > 0) { System.arraycopy(bytes,src,bytes,pos,buflen-src); bytes[newlen] = 0; } else { bytes[newlen-1] = 0; } return bytes; } } public static final byte[] delete(byte[] bytes, int pos, int length, boolean copy) { if (length < 0) { throw new IllegalArgumentException("illegal length for delete"); } int buflen = bytes.length; if (length == 0 || buflen == 0 ) { return bytes; } int newlen = buflen - length; int newpos = pos + length; if (pos < 0 || newpos > buflen) { throw new IllegalArgumentException("illegal position for delete"); } if (copy) { if (newlen == 0) { return EMPTY_BYTES; } byte[] newbytes = new byte[newlen]; if (pos == 0) { System.arraycopy(bytes,length,newbytes,0,newlen); } else if (pos == newlen) { System.arraycopy(bytes,0,newbytes,0,newlen); } else { System.arraycopy(bytes,0,newbytes,0,pos); System.arraycopy(bytes,newpos,newbytes,pos,buflen-newpos); } return newbytes; } else { if (newlen > 0) { System.arraycopy(bytes,newpos,bytes,pos,buflen-newpos); } fill(bytes,newlen,buflen-newlen,(byte)0); return bytes; } } /** * Inserts a single byte at the specified position. If copy is specified, creates * a new array one byte longer; otherwise shifts bytes in the existing array by one, * dropping the last byte. * * @param bytes * @param pos * @param value * @param copy * @return new array if copy was specified, otherwise the original array */ public static final byte[] insert(byte[] bytes, int pos, byte value, boolean copy) { int buflen = bytes.length; if (pos < 0 || pos > buflen) { throw new IllegalArgumentException("illegal position for insert"); } if (copy) { byte[] newbytes = new byte[buflen+1]; if (pos == 0) { System.arraycopy(bytes,0,newbytes,1,buflen); newbytes[0] = value; } else if (pos == buflen) { System.arraycopy(bytes,0,newbytes,0,buflen); newbytes[buflen] = value; } else { System.arraycopy(bytes,0,newbytes,0,pos); System.arraycopy(bytes,pos,newbytes,pos+1,buflen-pos); newbytes[pos] = value; } return newbytes; } else { if (pos == buflen) { throw new IllegalArgumentException("illegal position for insert with no copy"); } if (pos > buflen - 1) { System.arraycopy(bytes,pos,bytes,pos+1,buflen-pos-1); } bytes[pos] = value; return bytes; } } /** * Inserts the value array at the specified position. If copy is specified, creates a * new array, length == bytes.length + value.length. Otherwise, displaces bytes in * the exisiting array, shifting them right by value.length and dropping value.length * bytes from the end of the array. * * @param bytes * @param pos * @param value * @param copy * @return new array if copy was specified, otherwise the original array */ public static final byte[] insert(byte[] bytes, int pos, byte[] value, boolean copy) { int buflen = bytes.length; if (pos < 0 || pos > buflen) { throw new IllegalArgumentException("illegal position for insert"); } int vlen = value.length; if (copy) { int newlen = buflen + vlen; byte[] newbytes = new byte[newlen]; if (pos == 0) { System.arraycopy(value,0,newbytes,0,vlen); System.arraycopy(bytes,0,newbytes,vlen,buflen); } else if (pos == buflen) { System.arraycopy(bytes,0,newbytes,0,buflen); System.arraycopy(value,0,newbytes,buflen,vlen); } else { System.arraycopy(bytes,0,newbytes,0,pos); System.arraycopy(value,0,newbytes,pos,vlen); System.arraycopy(bytes,pos,newbytes,pos+vlen,buflen-pos); } return newbytes; } else { int displace = pos + vlen; if (displace > buflen) { throw new IllegalArgumentException("inserted array won't fit in target array"); } if (pos == 0) { System.arraycopy(bytes,0,bytes,vlen,buflen-vlen); System.arraycopy(value,0,bytes,0,vlen); } else if (displace == buflen) { System.arraycopy(value,0,bytes,pos,vlen); } else { System.arraycopy(bytes,pos,bytes,displace,buflen-displace); System.arraycopy(value,0,bytes,pos,vlen); } return bytes; } } public static final byte[] append(byte[] bytes, byte value) { int buflen = bytes.length; byte[] newbytes = new byte[buflen + 1]; System.arraycopy(bytes,0,newbytes,0,buflen); bytes[buflen] = value; return bytes; } /** * Fills the array with the specified value, starting at the specified position, * for the specified length. No exception is thrown if length is too big; in that * case the array will be filled to the end. * * @param bytes * @param pos * @param length * @param value * @return */ public static final byte[] fill(byte[] bytes, int pos, int length, byte value) { if (length < 0) { throw new IllegalArgumentException("illegal length for fill"); } int buflen = bytes.length; int stop = pos + length; if (stop > buflen) stop = buflen; for ( ; pos < stop; pos++) { bytes[pos] = value; } return bytes; } /** * Returns a copy of the array, or the array itelf if its length == 0. * * @param bytes * @return */ public static final byte[] copy(byte[] bytes) { int buflen = bytes.length; if (buflen == 0) return bytes; byte[] newbytes = new byte[buflen]; System.arraycopy(bytes,0,newbytes,0,buflen); return newbytes; } private static final long[] LONG_10_POWERS = { 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L, 10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L, 1000000000000000L, 10000000000000000L, 100000000000000000L }; private static final Long LONG_ZERO = new Long(0); private static final BigInteger BIG_INT_ZERO = BigInteger.valueOf(0L); private static final byte[] EMPTY_BYTES = {}; private static final byte[] MIN_INT_BYTE_ARRAY = { '-','2','1','4','7','4','8','3','6','4','8' }; private static final byte[] MIN_LONG_BYTE_ARRAY = { '-','9','2','2','3','3','7','2','0','3','6','8','5','4','7','7','5','8','0','8' }; private static final char[] MIN_LONG_CHAR_ARRAY = { '-','9','2','2','3','3','7','2','0','3','6','8','5','4','7','7','5','8','0','8' }; // Tables from java.lang.Integer, converted to byte (used in java.lang.Long as well) private static final int[] SIZE_TABLE = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999, Integer.MAX_VALUE }; private static final byte[] DIGITS = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' }; private static final byte[] UCDIGITS = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'A' , 'B' , 'C' , 'D' , 'E' , 'F' , 'G' , 'H' , 'I' , 'J' , 'K' , 'L' , 'M' , 'N' , 'O' , 'P' , 'Q' , 'R' , 'S' , 'T' , 'U' , 'V' , 'W' , 'X' , 'Y' , 'Z' }; private static final byte[] DIGIT_TENS = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', } ; private static final byte[] DIGIT_ONES = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', } ; private static final char[] CDIGITS = { '0' , '1' , '2' , '3' , '4' , '5' , '6' , '7' , '8' , '9' , 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' , 'q' , 'r' , 's' , 't' , 'u' , 'v' , 'w' , 'x' , 'y' , 'z' }; private static final char [] CDIGIT_TENS = { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '1', '1', '1', '1', '1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '2', '2', '2', '2', '2', '2', '3', '3', '3', '3', '3', '3', '3', '3', '3', '3', '4', '4', '4', '4', '4', '4', '4', '4', '4', '4', '5', '5', '5', '5', '5', '5', '5', '5', '5', '5', '6', '6', '6', '6', '6', '6', '6', '6', '6', '6', '7', '7', '7', '7', '7', '7', '7', '7', '7', '7', '8', '8', '8', '8', '8', '8', '8', '8', '8', '8', '9', '9', '9', '9', '9', '9', '9', '9', '9', '9', } ; private static final char [] CDIGIT_ONES = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', } ; /* * All the positive powers of 10 that can be * represented exactly in double/float. * (From sun.misc.FloatingDecimal.java) */ private static final double[] SMALL_10_POWERS = { 1.0e0, 1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5, 1.0e6, 1.0e7, 1.0e8, 1.0e9, 1.0e10, 1.0e11, 1.0e12, 1.0e13, 1.0e14, 1.0e15, 1.0e16, 1.0e17, 1.0e18, 1.0e19, 1.0e20, 1.0e21, 1.0e22 }; private static final int MAX_SMALL_10 = SMALL_10_POWERS.length - 1; private static final int MAX_DECIMAL_DIGITS = 15; private static final int BIG_DECIMAL_EXPONENT = 324; private static final int INT_DECIMAL_DIGITS = 9; }
false
true
public static final double byteArrayToDouble(byte[] bytes, int buflen, boolean strict) { // Simple cases ( abs(exponent) <= 22 [up to 37 depending on significand length]) // are converted directly, which is considerably faster than creating a Java // String and passing it to Double.parseDouble() (which in turn passes it to // sun.misc.FloatingDecimal); the latter approach involves 5 object allocations // (3 arrays + String + FloatingDecimal) and 3 array copies, two of them one byte/char // at a time (here and in FloatingDecimal). // However, the latter approach is employed for more difficult cases (generally // speaking, those that require rounding). (The code for the difficult cases is // quite involved; see sun.misc.FloatingDecimal.java if you're interested.) // states final int SCOMPLETE = 0; final int SBEGIN = 1; // remove leading whitespace (includes _ for lax) final int SSIGN = 2; // get sign, if any // optimistic pass - calculate value as digits are processed final int SOPTDIGIT = 3; // digits - lax rules final int SOPTDECDIGIT = 4; // decimal digits - lax rules final int SOPTEXP = 9; // exponent sign/digits - lax rules final int SOPTDIGIT_STRICT = 6; // digits - strict rules final int SOPTDECDIGIT_STRICT = 7; // decimal digits - strict rules final int SOPTEXP_STRICT = 8; // exponent sign/digits - strict rules final int SOPTCALC = 5; // complete calculation if possible // fallback pass - gather chars into array and pass to Double.parseDouble() final int SDIGIT = 10; // digits - lax rules final int SDECDIGIT = 11; // decimal digits - lax rules final int SEXP = 12; // exponent sign/digits - lax rules final int SDIGIT_STRICT = 13; // digits - strict rules final int SDECDIGIT_STRICT = 14; // decimal digits - strict rules final int SEXP_STRICT = 15; // exponent sign/digits - strict rules final int SERR_NOT_STRICT = 16; // largest abs(exponent) we can (potentially) handle without // calling Double.parseDouble() (aka sun.misc.FloatingDecimal) final int MAX_EXP = MAX_DECIMAL_DIGITS + MAX_SMALL_10; // (37) if (bytes == null) { throw new IllegalArgumentException("null bytes"); } if (buflen < 0 || buflen > bytes.length) { throw new IllegalArgumentException("invalid buflen specified"); } // TODO: get rid of this (lax returns 0.0, strict will throw) if (buflen == 0) { throw new NumberFormatException(); } int i = 0; byte ival; boolean negative = false; // fields used for direct (optimistic) calculation int nDigits = 0; // number of significant digits, updated as parsed int nTrailingZeroes = 0; // zeroes that may go to significand or exponent int decPos = -1; // offset of decimal pt from start (-1 -> no decimal) long significand = 0; // significand, updated as parsed int exponent = 0; // exponent, updated as parsed // fields used for fallback (send to Double.parseDouble()) int startPos = 0; // start of digits (or . if no leading digits) char[] chars = null; int offset = 0; int lastValidOffset = 0; int state = SBEGIN; while (state != SCOMPLETE) { states: switch(state) { case SBEGIN: if (strict) { for (; i < buflen && bytes[i] <= ' '; i++) ; } else { for (; i < buflen && ((ival = bytes[i]) <= ' ' || ival == '_'); i++) ; } if ( i >= buflen) { state = strict ? SERR_NOT_STRICT : SCOMPLETE; break; } // drop through for sign case SSIGN: switch(bytes[i]) { case '-': negative = true; case '+': if (++i >= buflen) { // TODO: turn off the negative? will return -0.0 in lax mode state = strict ? SERR_NOT_STRICT : SCOMPLETE; break states; } } // switch startPos = i; // will use this if we have to go back the slow way if (strict) { state = SOPTDIGIT_STRICT; break; } // drop through for non-strict digits case SOPTDIGIT: // first char must be digit or decimal point switch(ival = bytes[i++]) { case '0': // ignore leading zeroes break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': significand = (long)((int)ival-(int)'0'); nDigits = 1; break; // switch case '.': state = SOPTDECDIGIT; break states; default: // no digits, go calc (will return +/- 0.0 for lax) state = SOPTCALC; break states; } // switch for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': // ignore leading zeroes if (nDigits > 0) { // just save a count of zeroes for now; if no digit // ends up following them, they'll be applied to the // exponent rather than the significand (and our max // length for optimistic calc). nTrailingZeroes++; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': // ok, got a non-zero, have to own up to our horded zeroes if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { // oh, well, it was worth a try. go let // Double/FloatingDecimal handle it state = SDIGIT; break states; } case '.': state = SOPTDECDIGIT; break states; case 'e': case 'E': state = SOPTEXP; break states; case '_': // ignore break; // switch default: // end of parseable data, go to calc state = SOPTCALC; break states; } // switch } // for state = SOPTCALC; break; case SOPTDECDIGIT: decPos = nDigits + nTrailingZeroes; for ( ; i < buflen && bytes[i] == '_'; i++ ) ; // first non_underscore char must be digit if (i < buflen) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } else { exponent--; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } default: // no dec digits, end of parseable data, go to calc state = SOPTCALC; break states; } // switch } // if for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } else { exponent--; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } case 'e': case 'E': state = SOPTEXP; break states; case '_': // ignore break; // switch default: // end of parseable data, go to calc state = SOPTCALC; break states; } // switch } // for // no exponent, so drop through for calculation case SOPTCALC: // calculation for simple (and typical) case, // adapted from sun.misc.FloatingDecimal if (nDigits == 0) { return negative ? -0.0d : 0.0d; } if (decPos < 0) { exponent += nTrailingZeroes; } else { exponent += decPos - nDigits; } double dValue = (double)significand; if (exponent == 0 || dValue == 0.0) { return negative ? -dValue : dValue; } else if ( exponent >= 0 ){ if ( exponent <= MAX_SMALL_10 ){ dValue *= SMALL_10_POWERS[exponent]; return negative ? -dValue : dValue; } int slop = MAX_DECIMAL_DIGITS - nDigits; if ( exponent <= MAX_SMALL_10+slop ){ dValue = (dValue * SMALL_10_POWERS[slop]) * SMALL_10_POWERS[exponent-slop]; return negative ? -dValue : dValue; } } else { // TODO: it's not clear to me why, in FloatingDecimal, the // "slop" calculation performed above for positive exponents // isn't used for negative exponents as well. Will find out... if ( exponent >= -MAX_SMALL_10 ){ dValue = dValue / SMALL_10_POWERS[-exponent]; return negative ? -dValue : dValue; } } // difficult case, send to Double/FloatingDecimal state = SDIGIT; break; case SOPTEXP: { // lax (str.to_f) allows underscores between e/E and sign for ( ; i < buflen && bytes[i] == '_' ; i++ ) ; if (i >= buflen) { state = SOPTCALC; break; } int expSign = 1; int expSpec = 0; switch (bytes[i]) { case '-': expSign = -1; case '+': if (++i >= buflen) { state = SOPTCALC; break states; } } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if ((expSpec = expSpec * 10 + ((int)ival-(int)'0')) >= MAX_EXP) { // too big for us state = SDIGIT; break states; } break; //switch case '_': break; //switch default: exponent += expSign * expSpec; state = SOPTCALC; break states; } } exponent += expSign * expSpec; state = SOPTCALC; break; } // block case SOPTDIGIT_STRICT: // first char must be digit or decimal point switch(ival = bytes[i++]) { case '0': break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': significand = (long)((int)ival-(int)'0'); nDigits = 1; break; // switch case '.': state = SOPTDECDIGIT_STRICT; break states; default: // no digits, error state = SERR_NOT_STRICT; break states; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } case '.': state = SOPTDECDIGIT_STRICT; break states; case 'e': case 'E': state = SOPTEXP_STRICT; break states; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; // switch default: // only whitespace allowed after value for strict for ( ; i < buflen && bytes[i++] <= ' '; ); state = i < buflen ? SERR_NOT_STRICT : SOPTCALC; break states; } // switch } // for // no more data, OK for strict to go calc state = SOPTCALC; break; case SOPTDECDIGIT_STRICT: decPos = nDigits + nTrailingZeroes; // first char must be digit if (i < buflen) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } else { exponent--; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } default: // no dec digits after '.', error for strict state = SERR_NOT_STRICT; break states; } // switch } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } else { exponent--; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } case 'e': case 'E': state = SOPTEXP_STRICT; break states; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; // switch default: // only whitespace allowed after value for strict for ( ; i < buflen && bytes[i++] <= ' '; ); state = i < buflen ? SERR_NOT_STRICT : SOPTCALC; break states; } // switch } // for // no more data, OK for strict to go calc state = SOPTCALC; break; case SOPTEXP_STRICT: { int expSign = 1; int expSpec = 0; if ( i < buflen) { switch (bytes[i]) { case '-': expSign = -1; case '+': if (++i >= buflen) { state = SERR_NOT_STRICT; break states; } } } else { state = SERR_NOT_STRICT; break; } // must be at least one digit for strict if ( i < buflen ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': expSpec = (int)ival-(int)'0'; break; //switch default: state = SERR_NOT_STRICT; break states; } } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if ((expSpec = expSpec * 10 + ((int)ival-(int)'0')) >= MAX_EXP) { // too big for us state = SDIGIT; break states; } break; //switch case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; //switch default: exponent += expSign * expSpec; // only whitespace allowed after value for strict for ( ; i < buflen && bytes[i++] <= ' '; ); state = i < buflen ? SERR_NOT_STRICT : SOPTCALC; break states; } // switch } // for exponent += expSign * expSpec; state = SOPTCALC; break; } // block // fallback, copy non-whitespace chars to char buffer and send // to Double.parseDouble() (front for sun.misc.FloatingDecimal) case SDIGIT: i = startPos; if (negative) { chars = new char[buflen - i + 1]; chars[0] = '-'; offset = 1; } else { chars = new char[buflen - i]; } if (strict) { state = SDIGIT_STRICT; break; } // first char must be digit or decimal point if (i < buflen) { switch(ival = bytes[i++]) { case '0': // ignore leading zeroes break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case '.': state = SDECDIGIT; break states; default: state = SCOMPLETE; break states; } // switch } // if for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case '.': state = SDECDIGIT; break states; case 'e': case 'E': state = SEXP; break states; case '_': break; // switch default: state = SCOMPLETE; break states; } // switch } // for state = SCOMPLETE; break; case SDECDIGIT: chars[offset++] = '.'; for ( ; i < buflen && bytes[i] == '_'; i++) ; if ( i < buflen) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch default: state = SCOMPLETE; break states; } // switch } // if for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case 'e': case 'E': state = SEXP; break states; case '_': break; // switch default: state = SCOMPLETE; break states; } // switch } // for state = SCOMPLETE; break; case SEXP: chars[offset++] = 'E'; for ( ; i < buflen && bytes[i] == '_'; i++) ; if (i >= buflen) { state = SCOMPLETE; break; } switch(bytes[i]) { case '-': case '+': chars[offset++] = (char)bytes[i]; if (++i >= buflen) { state = SCOMPLETE; break states; } } for ( ; i < buflen; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; case '_': break; default: state = SCOMPLETE; break states; } } state = SCOMPLETE; break; case SDIGIT_STRICT: // first char must be digit or decimal point if (i < buflen) { switch(ival = bytes[i++]) { case '0': // ignore leading zeroes break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case '.': state = SDECDIGIT_STRICT; break states; default: state = SERR_NOT_STRICT; break states; } // switch } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case '.': state = SDECDIGIT_STRICT; break states; case 'e': case 'E': state = SEXP_STRICT; break states; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; //switch default: // only whitespace allowed after value for strict for ( ; i < buflen && bytes[i++] <= ' '; ) ; state = i < buflen ? SERR_NOT_STRICT : SCOMPLETE; break states; } // switch } // for state = SCOMPLETE; break; case SDECDIGIT_STRICT: chars[offset++] = '.'; if ( i < buflen) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch default: state = SERR_NOT_STRICT; break states; } // switch } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case 'e': case 'E': state = SEXP_STRICT; break states; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; //switch default: for ( ; i < buflen && bytes[i++] <= ' '; ) ; state = i < buflen ? SERR_NOT_STRICT : SCOMPLETE; break states; } // switch } // for state = SCOMPLETE; break; case SEXP_STRICT: chars[offset++] = 'E'; if ( i < buflen ) { switch (bytes[i]) { case '-': case '+': chars[offset++] = (char)bytes[i]; if (++i >= buflen) { state = SERR_NOT_STRICT; break states; } } } else { state = SERR_NOT_STRICT; break; } // must be at least one digit for strict if ( i < buflen ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; //switch default: state = SERR_NOT_STRICT; break states; } } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; //switch default: for ( ; i < buflen && bytes[i++] <= ' '; ) ; state = i < buflen ? SERR_NOT_STRICT : SCOMPLETE; break states; } } state = SCOMPLETE; break; case SERR_NOT_STRICT: throw new NumberFormatException("does not meet strict criteria"); } // switch } //while if (chars == null || lastValidOffset == 0) { return 0.0; } else { return Double.parseDouble(new String(chars,0,lastValidOffset)); } }
public static final double byteArrayToDouble(byte[] bytes, int buflen, boolean strict) { // Simple cases ( abs(exponent) <= 22 [up to 37 depending on significand length]) // are converted directly, which is considerably faster than creating a Java // String and passing it to Double.parseDouble() (which in turn passes it to // sun.misc.FloatingDecimal); the latter approach involves 5 object allocations // (3 arrays + String + FloatingDecimal) and 3 array copies, two of them one byte/char // at a time (here and in FloatingDecimal). // However, the latter approach is employed for more difficult cases (generally // speaking, those that require rounding). (The code for the difficult cases is // quite involved; see sun.misc.FloatingDecimal.java if you're interested.) // states final int SCOMPLETE = 0; final int SBEGIN = 1; // remove leading whitespace (includes _ for lax) final int SSIGN = 2; // get sign, if any // optimistic pass - calculate value as digits are processed final int SOPTDIGIT = 3; // digits - lax rules final int SOPTDECDIGIT = 4; // decimal digits - lax rules final int SOPTEXP = 9; // exponent sign/digits - lax rules final int SOPTDIGIT_STRICT = 6; // digits - strict rules final int SOPTDECDIGIT_STRICT = 7; // decimal digits - strict rules final int SOPTEXP_STRICT = 8; // exponent sign/digits - strict rules final int SOPTCALC = 5; // complete calculation if possible // fallback pass - gather chars into array and pass to Double.parseDouble() final int SDIGIT = 10; // digits - lax rules final int SDECDIGIT = 11; // decimal digits - lax rules final int SEXP = 12; // exponent sign/digits - lax rules final int SDIGIT_STRICT = 13; // digits - strict rules final int SDECDIGIT_STRICT = 14; // decimal digits - strict rules final int SEXP_STRICT = 15; // exponent sign/digits - strict rules final int SERR_NOT_STRICT = 16; // largest abs(exponent) we can (potentially) handle without // calling Double.parseDouble() (aka sun.misc.FloatingDecimal) final int MAX_EXP = MAX_DECIMAL_DIGITS + MAX_SMALL_10; // (37) if (bytes == null) { throw new IllegalArgumentException("null bytes"); } if (buflen < 0 || buflen > bytes.length) { throw new IllegalArgumentException("invalid buflen specified"); } // TODO: get rid of this (lax returns 0.0, strict will throw) if (buflen == 0) { throw new NumberFormatException(); } int i = 0; byte ival; boolean negative = false; // fields used for direct (optimistic) calculation int nDigits = 0; // number of significant digits, updated as parsed int nTrailingZeroes = 0; // zeroes that may go to significand or exponent int decPos = -1; // offset of decimal pt from start (-1 -> no decimal) long significand = 0; // significand, updated as parsed int exponent = 0; // exponent, updated as parsed // fields used for fallback (send to Double.parseDouble()) int startPos = 0; // start of digits (or . if no leading digits) char[] chars = null; int offset = 0; int lastValidOffset = 0; int state = SBEGIN; while (state != SCOMPLETE) { states: switch(state) { case SBEGIN: if (strict) { for (; i < buflen && bytes[i] <= ' '; i++) ; } else { for (; i < buflen && ((ival = bytes[i]) <= ' ' || ival == '_'); i++) ; } if ( i >= buflen) { state = strict ? SERR_NOT_STRICT : SCOMPLETE; break; } // drop through for sign case SSIGN: switch(bytes[i]) { case '-': negative = true; case '+': if (++i >= buflen) { // TODO: turn off the negative? will return -0.0 in lax mode state = strict ? SERR_NOT_STRICT : SCOMPLETE; break states; } } // switch startPos = i; // will use this if we have to go back the slow way if (strict) { state = SOPTDIGIT_STRICT; break; } // drop through for non-strict digits case SOPTDIGIT: // first char must be digit or decimal point switch(ival = bytes[i++]) { case '0': // ignore leading zeroes break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': significand = (long)((int)ival-(int)'0'); nDigits = 1; break; // switch case '.': state = SOPTDECDIGIT; break states; default: // no digits, go calc (will return +/- 0.0 for lax) state = SOPTCALC; break states; } // switch for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': // ignore leading zeroes if (nDigits > 0) { // just save a count of zeroes for now; if no digit // ends up following them, they'll be applied to the // exponent rather than the significand (and our max // length for optimistic calc). nTrailingZeroes++; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': // ok, got a non-zero, have to own up to our horded zeroes if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { // oh, well, it was worth a try. go let // Double/FloatingDecimal handle it state = SDIGIT; break states; } case '.': state = SOPTDECDIGIT; break states; case 'e': case 'E': state = SOPTEXP; break states; case '_': // ignore break; // switch default: // end of parseable data, go to calc state = SOPTCALC; break states; } // switch } // for state = SOPTCALC; break; case SOPTDECDIGIT: decPos = nDigits + nTrailingZeroes; for ( ; i < buflen && bytes[i] == '_'; i++ ) ; // first non_underscore char must be digit if (i < buflen) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } else { exponent--; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } default: // no dec digits, end of parseable data, go to calc state = SOPTCALC; break states; } // switch } // if for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } else { exponent--; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } case 'e': case 'E': state = SOPTEXP; break states; case '_': // ignore break; // switch default: // end of parseable data, go to calc state = SOPTCALC; break states; } // switch } // for // no exponent, so drop through for calculation case SOPTCALC: // calculation for simple (and typical) case, // adapted from sun.misc.FloatingDecimal if (nDigits == 0) { return negative ? -0.0d : 0.0d; } if (decPos < 0) { exponent += nTrailingZeroes; } else { exponent += decPos - nDigits; } double dValue = (double)significand; if (exponent == 0 || dValue == 0.0) { return negative ? -dValue : dValue; } else if ( exponent >= 0 ){ if ( exponent <= MAX_SMALL_10 ){ dValue *= SMALL_10_POWERS[exponent]; return negative ? -dValue : dValue; } int slop = MAX_DECIMAL_DIGITS - nDigits; if ( exponent <= MAX_SMALL_10+slop ){ dValue = (dValue * SMALL_10_POWERS[slop]) * SMALL_10_POWERS[exponent-slop]; return negative ? -dValue : dValue; } } else { // TODO: it's not clear to me why, in FloatingDecimal, the // "slop" calculation performed above for positive exponents // isn't used for negative exponents as well. Will find out... if ( exponent >= -MAX_SMALL_10 ){ dValue = dValue / SMALL_10_POWERS[-exponent]; return negative ? -dValue : dValue; } } // difficult case, send to Double/FloatingDecimal state = SDIGIT; break; case SOPTEXP: { // lax (str.to_f) allows underscores between e/E and sign for ( ; i < buflen && bytes[i] == '_' ; i++ ) ; if (i >= buflen) { state = SOPTCALC; break; } int expSign = 1; int expSpec = 0; switch (bytes[i]) { case '-': expSign = -1; case '+': if (++i >= buflen) { state = SOPTCALC; break states; } } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if ((expSpec = expSpec * 10 + ((int)ival-(int)'0')) >= MAX_EXP) { // too big for us state = SDIGIT; break states; } break; //switch case '_': break; //switch default: exponent += expSign * expSpec; state = SOPTCALC; break states; } } exponent += expSign * expSpec; state = SOPTCALC; break; } // block case SOPTDIGIT_STRICT: // first char must be digit or decimal point switch(ival = bytes[i++]) { case '0': break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': significand = (long)((int)ival-(int)'0'); nDigits = 1; break; // switch case '.': state = SOPTDECDIGIT_STRICT; break states; default: // no digits, error state = SERR_NOT_STRICT; break states; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } case '.': state = SOPTDECDIGIT_STRICT; break states; case 'e': case 'E': state = SOPTEXP_STRICT; break states; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; // switch default: // only whitespace allowed after value for strict for ( ; i < buflen && bytes[i] <= ' '; i++ ); state = i < buflen ? SERR_NOT_STRICT : SOPTCALC; break states; } // switch } // for // no more data, OK for strict to go calc state = SOPTCALC; break; case SOPTDECDIGIT_STRICT: decPos = nDigits + nTrailingZeroes; // first char must be digit if (i < buflen) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } else { exponent--; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } default: // no dec digits after '.', error for strict state = SERR_NOT_STRICT; break states; } // switch } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': if (nDigits > 0) { nTrailingZeroes++; } else { exponent--; } break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (nTrailingZeroes > 0) { if ((nDigits += nTrailingZeroes) < MAX_DECIMAL_DIGITS) { significand *= LONG_10_POWERS[nTrailingZeroes]; nTrailingZeroes = 0; } // else catch oversize below } if (nDigits++ < MAX_DECIMAL_DIGITS) { significand = significand*10L + (long)((int)ival-(int)'0'); break; // switch } else { state = SDIGIT; break states; } case 'e': case 'E': state = SOPTEXP_STRICT; break states; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; // switch default: // only whitespace allowed after value for strict for ( ; i < buflen && bytes[i] <= ' '; i++); state = i < buflen ? SERR_NOT_STRICT : SOPTCALC; break states; } // switch } // for // no more data, OK for strict to go calc state = SOPTCALC; break; case SOPTEXP_STRICT: { int expSign = 1; int expSpec = 0; if ( i < buflen) { switch (bytes[i]) { case '-': expSign = -1; case '+': if (++i >= buflen) { state = SERR_NOT_STRICT; break states; } } } else { state = SERR_NOT_STRICT; break; } // must be at least one digit for strict if ( i < buflen ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': expSpec = (int)ival-(int)'0'; break; //switch default: state = SERR_NOT_STRICT; break states; } } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if ((expSpec = expSpec * 10 + ((int)ival-(int)'0')) >= MAX_EXP) { // too big for us state = SDIGIT; break states; } break; //switch case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; //switch default: exponent += expSign * expSpec; // only whitespace allowed after value for strict for ( ; i < buflen && bytes[i] <= ' '; i++); state = i < buflen ? SERR_NOT_STRICT : SOPTCALC; break states; } // switch } // for exponent += expSign * expSpec; state = SOPTCALC; break; } // block // fallback, copy non-whitespace chars to char buffer and send // to Double.parseDouble() (front for sun.misc.FloatingDecimal) case SDIGIT: i = startPos; if (negative) { chars = new char[buflen - i + 1]; chars[0] = '-'; offset = 1; } else { chars = new char[buflen - i]; } if (strict) { state = SDIGIT_STRICT; break; } // first char must be digit or decimal point if (i < buflen) { switch(ival = bytes[i++]) { case '0': // ignore leading zeroes break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case '.': state = SDECDIGIT; break states; default: state = SCOMPLETE; break states; } // switch } // if for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case '.': state = SDECDIGIT; break states; case 'e': case 'E': state = SEXP; break states; case '_': break; // switch default: state = SCOMPLETE; break states; } // switch } // for state = SCOMPLETE; break; case SDECDIGIT: chars[offset++] = '.'; for ( ; i < buflen && bytes[i] == '_'; i++) ; if ( i < buflen) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch default: state = SCOMPLETE; break states; } // switch } // if for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case 'e': case 'E': state = SEXP; break states; case '_': break; // switch default: state = SCOMPLETE; break states; } // switch } // for state = SCOMPLETE; break; case SEXP: chars[offset++] = 'E'; for ( ; i < buflen && bytes[i] == '_'; i++) ; if (i >= buflen) { state = SCOMPLETE; break; } switch(bytes[i]) { case '-': case '+': chars[offset++] = (char)bytes[i]; if (++i >= buflen) { state = SCOMPLETE; break states; } } for ( ; i < buflen; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; case '_': break; default: state = SCOMPLETE; break states; } } state = SCOMPLETE; break; case SDIGIT_STRICT: // first char must be digit or decimal point if (i < buflen) { switch(ival = bytes[i++]) { case '0': // ignore leading zeroes break; // switch case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case '.': state = SDECDIGIT_STRICT; break states; default: state = SERR_NOT_STRICT; break states; } // switch } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case '.': state = SDECDIGIT_STRICT; break states; case 'e': case 'E': state = SEXP_STRICT; break states; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; //switch default: // only whitespace allowed after value for strict for ( ; i < buflen && bytes[i] <= ' '; i++) ; state = i < buflen ? SERR_NOT_STRICT : SCOMPLETE; break states; } // switch } // for state = SCOMPLETE; break; case SDECDIGIT_STRICT: chars[offset++] = '.'; if ( i < buflen) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch default: state = SERR_NOT_STRICT; break states; } // switch } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; // switch case 'e': case 'E': state = SEXP_STRICT; break states; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; //switch default: for ( ; i < buflen && bytes[i] <= ' '; i++) ; state = i < buflen ? SERR_NOT_STRICT : SCOMPLETE; break states; } // switch } // for state = SCOMPLETE; break; case SEXP_STRICT: chars[offset++] = 'E'; if ( i < buflen ) { switch (bytes[i]) { case '-': case '+': chars[offset++] = (char)bytes[i]; if (++i >= buflen) { state = SERR_NOT_STRICT; break states; } } } else { state = SERR_NOT_STRICT; break; } // must be at least one digit for strict if ( i < buflen ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; //switch default: state = SERR_NOT_STRICT; break states; } } else { state = SERR_NOT_STRICT; break; } for ( ; i < buflen ; ) { switch(ival = bytes[i++]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': chars[offset++] = (char)ival; lastValidOffset = offset; break; case '_': if (i >= buflen || bytes[i] < '0' || bytes[i] > '9') { state = SERR_NOT_STRICT; break states; } break; //switch default: for ( ; i < buflen && bytes[i] <= ' '; i++) ; state = i < buflen ? SERR_NOT_STRICT : SCOMPLETE; break states; } } state = SCOMPLETE; break; case SERR_NOT_STRICT: throw new NumberFormatException("does not meet strict criteria"); } // switch } //while if (chars == null || lastValidOffset == 0) { return 0.0; } else { return Double.parseDouble(new String(chars,0,lastValidOffset)); } }
diff --git a/hale/eu.esdihumboldt.hale.io.xsd.test/src/eu/esdihumboldt/hale/io/xsd/reader/XmlSchemaReaderTest.java b/hale/eu.esdihumboldt.hale.io.xsd.test/src/eu/esdihumboldt/hale/io/xsd/reader/XmlSchemaReaderTest.java index 0cecf1041..cf82969a7 100644 --- a/hale/eu.esdihumboldt.hale.io.xsd.test/src/eu/esdihumboldt/hale/io/xsd/reader/XmlSchemaReaderTest.java +++ b/hale/eu.esdihumboldt.hale.io.xsd.test/src/eu/esdihumboldt/hale/io/xsd/reader/XmlSchemaReaderTest.java @@ -1,107 +1,107 @@ /* * HUMBOLDT: A Framework for Data Harmonisation and Service Integration. * EU Integrated Project #030962 01.10.2006 - 30.09.2010 * * For more information on the project, please refer to the this web site: * http://www.esdi-humboldt.eu * * LICENSE: For information on the license under which this program is * available, please refer to http:/www.esdi-humboldt.eu/license.html#core * (c) the HUMBOLDT Consortium, 2007 to 2011. */ package eu.esdihumboldt.hale.io.xsd.reader; import static org.junit.Assert.*; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Collection; import javax.xml.namespace.QName; import org.junit.Test; import eu.esdihumboldt.hale.core.io.IOProviderConfigurationException; import eu.esdihumboldt.hale.core.io.supplier.DefaultInputSupplier; import eu.esdihumboldt.hale.core.io.supplier.LocatableInputSupplier; import eu.esdihumboldt.hale.io.xsd.XmlSchemaIO; import eu.esdihumboldt.hale.io.xsd.reader.internal.XmlElement; import eu.esdihumboldt.hale.io.xsd.reader.internal.XmlIndex; import eu.esdihumboldt.hale.schema.model.PropertyDefinition; import eu.esdihumboldt.hale.schema.model.Schema; import eu.esdihumboldt.hale.schema.model.TypeDefinition; import eu.esdihumboldt.hale.schema.model.impl.DefaultTypeIndex; /** * Tests for XML schema reading * @author Simon Templer */ public class XmlSchemaReaderTest { /** * Test reading a simple XML schema * @throws Exception if reading the schema fails */ @Test public void testRead_shiporder() throws Exception { URI location = getClass().getResource("/testdata/shiporder/shiporder.xsd").toURI(); LocatableInputSupplier<? extends InputStream> input = new DefaultInputSupplier(location ); XmlIndex schema = (XmlIndex) readSchema(input); String ns = "http://www.example.com"; assertEquals(ns , schema.getNamespace()); // shiporder element assertEquals(1, schema.getElements().size()); XmlElement shiporder = schema.getElements().values().iterator().next(); assertNotNull(shiporder); assertEquals("shiporder", shiporder.getName().getLocalPart()); // shiporder type TypeDefinition shiporderType = shiporder.getType(); assertNotNull(shiporderType); Collection<? extends PropertyDefinition> properties = shiporderType.getProperties(); assertEquals(4, properties.size()); // orderperson PropertyDefinition orderperson = shiporderType.getProperty(new QName(ns, "orderperson")); assertNotNull(orderperson); // shipto PropertyDefinition shipto = shiporderType.getProperty(new QName(ns, "shipto")); assertNotNull(shipto); // item PropertyDefinition item = shiporderType.getProperty(new QName(ns, "item")); assertNotNull(item); // orderid - PropertyDefinition orderid = shiporderType.getProperty(new QName(ns, "orderid")); + PropertyDefinition orderid = shiporderType.getProperty(new QName("orderid")); assertNotNull(orderid); } /** * Reads a schema * * @param input the input supplier * @return the schema * @throws IOProviderConfigurationException if the configuration of the * reader is invalid * @throws IOException if reading the schema fails */ private Schema readSchema(LocatableInputSupplier<? extends InputStream> input) throws IOProviderConfigurationException, IOException { XmlSchemaReader reader = new XmlSchemaReader(); reader.setContentType(XmlSchemaIO.XSD_CT); reader.setSharedTypes(new DefaultTypeIndex()); reader.setSource(input); reader.validate(); reader.execute(null); return reader.getSchema(); } }
true
true
public void testRead_shiporder() throws Exception { URI location = getClass().getResource("/testdata/shiporder/shiporder.xsd").toURI(); LocatableInputSupplier<? extends InputStream> input = new DefaultInputSupplier(location ); XmlIndex schema = (XmlIndex) readSchema(input); String ns = "http://www.example.com"; assertEquals(ns , schema.getNamespace()); // shiporder element assertEquals(1, schema.getElements().size()); XmlElement shiporder = schema.getElements().values().iterator().next(); assertNotNull(shiporder); assertEquals("shiporder", shiporder.getName().getLocalPart()); // shiporder type TypeDefinition shiporderType = shiporder.getType(); assertNotNull(shiporderType); Collection<? extends PropertyDefinition> properties = shiporderType.getProperties(); assertEquals(4, properties.size()); // orderperson PropertyDefinition orderperson = shiporderType.getProperty(new QName(ns, "orderperson")); assertNotNull(orderperson); // shipto PropertyDefinition shipto = shiporderType.getProperty(new QName(ns, "shipto")); assertNotNull(shipto); // item PropertyDefinition item = shiporderType.getProperty(new QName(ns, "item")); assertNotNull(item); // orderid PropertyDefinition orderid = shiporderType.getProperty(new QName(ns, "orderid")); assertNotNull(orderid); }
public void testRead_shiporder() throws Exception { URI location = getClass().getResource("/testdata/shiporder/shiporder.xsd").toURI(); LocatableInputSupplier<? extends InputStream> input = new DefaultInputSupplier(location ); XmlIndex schema = (XmlIndex) readSchema(input); String ns = "http://www.example.com"; assertEquals(ns , schema.getNamespace()); // shiporder element assertEquals(1, schema.getElements().size()); XmlElement shiporder = schema.getElements().values().iterator().next(); assertNotNull(shiporder); assertEquals("shiporder", shiporder.getName().getLocalPart()); // shiporder type TypeDefinition shiporderType = shiporder.getType(); assertNotNull(shiporderType); Collection<? extends PropertyDefinition> properties = shiporderType.getProperties(); assertEquals(4, properties.size()); // orderperson PropertyDefinition orderperson = shiporderType.getProperty(new QName(ns, "orderperson")); assertNotNull(orderperson); // shipto PropertyDefinition shipto = shiporderType.getProperty(new QName(ns, "shipto")); assertNotNull(shipto); // item PropertyDefinition item = shiporderType.getProperty(new QName(ns, "item")); assertNotNull(item); // orderid PropertyDefinition orderid = shiporderType.getProperty(new QName("orderid")); assertNotNull(orderid); }
diff --git a/javasvn/src/org/tmatesoft/svn/core/internal/wc/SVNFileType.java b/javasvn/src/org/tmatesoft/svn/core/internal/wc/SVNFileType.java index bc54c5982..86b259f2b 100644 --- a/javasvn/src/org/tmatesoft/svn/core/internal/wc/SVNFileType.java +++ b/javasvn/src/org/tmatesoft/svn/core/internal/wc/SVNFileType.java @@ -1,108 +1,108 @@ /* * ==================================================================== * Copyright (c) 2004 TMate Software Ltd. All rights reserved. * * This software is licensed as described in the file COPYING, which you should * have received as part of this distribution. The terms are also available at * http://tmate.org/svn/license.html. If newer versions of this license are * posted there, you may use a newer version instead, at your option. * ==================================================================== */ package org.tmatesoft.svn.core.internal.wc; import java.io.File; import java.io.IOException; import org.tmatesoft.svn.core.SVNNodeKind; /** * @version 1.0 * @author TMate Software Ltd. */ public class SVNFileType { public static final SVNFileType UNKNOWN = new SVNFileType(0); public static final SVNFileType NONE = new SVNFileType(1); public static final SVNFileType FILE = new SVNFileType(2); public static final SVNFileType SYMLINK = new SVNFileType(3); public static final SVNFileType DIRECTORY = new SVNFileType(4); private int myType; private SVNFileType(int type) { myType = type; } public String toString() { switch(myType) { case 0: return "unknown"; case 1: return "none"; case 2: return "file"; case 3: return "symlink"; case 4: return "directory"; } return Integer.toString(myType); } public static SVNFileType getType(File file) { if (file == null) { return SVNFileType.UNKNOWN; } if (!SVNFileUtil.isWindows) { String absolutePath = file.getAbsolutePath(); String canonicalPath; try { canonicalPath = file.getCanonicalPath(); } catch (IOException e) { canonicalPath = file.getAbsolutePath(); } if (!file.exists()) { - File[] children = file.getParentFile().listFiles(); + File[] children = file.getParentFile() != null ? file.getParentFile().listFiles() : null; for (int i = 0; children != null && i < children.length; i++) { File child = children[i]; if (child.getName().equals(file.getName())) { if (SVNFileUtil.isSymlink(file)) { return SVNFileType.SYMLINK; } } } } else if (!absolutePath.equals(canonicalPath) && SVNFileUtil.isSymlink(file)) { return SVNFileType.SYMLINK; } } if (file.isFile()) { return SVNFileType.FILE; } else if (file.isDirectory()) { return SVNFileType.DIRECTORY; } else if (!file.exists()) { return SVNFileType.NONE; } return SVNFileType.UNKNOWN; } public static boolean equals(SVNFileType type, SVNNodeKind nodeKind) { if (nodeKind == SVNNodeKind.DIR) { return type == SVNFileType.DIRECTORY; } else if (nodeKind == SVNNodeKind.FILE) { return type == SVNFileType.FILE || type == SVNFileType.SYMLINK; } else if (nodeKind == SVNNodeKind.NONE) { return type == SVNFileType.NONE; } else if (nodeKind == SVNNodeKind.UNKNOWN) { return type == SVNFileType.UNKNOWN; } return false; } public int getID() { return myType; } public boolean isFile() { return this == SVNFileType.FILE || this == SVNFileType.SYMLINK; } }
true
true
public static SVNFileType getType(File file) { if (file == null) { return SVNFileType.UNKNOWN; } if (!SVNFileUtil.isWindows) { String absolutePath = file.getAbsolutePath(); String canonicalPath; try { canonicalPath = file.getCanonicalPath(); } catch (IOException e) { canonicalPath = file.getAbsolutePath(); } if (!file.exists()) { File[] children = file.getParentFile().listFiles(); for (int i = 0; children != null && i < children.length; i++) { File child = children[i]; if (child.getName().equals(file.getName())) { if (SVNFileUtil.isSymlink(file)) { return SVNFileType.SYMLINK; } } } } else if (!absolutePath.equals(canonicalPath) && SVNFileUtil.isSymlink(file)) { return SVNFileType.SYMLINK; } } if (file.isFile()) { return SVNFileType.FILE; } else if (file.isDirectory()) { return SVNFileType.DIRECTORY; } else if (!file.exists()) { return SVNFileType.NONE; } return SVNFileType.UNKNOWN; }
public static SVNFileType getType(File file) { if (file == null) { return SVNFileType.UNKNOWN; } if (!SVNFileUtil.isWindows) { String absolutePath = file.getAbsolutePath(); String canonicalPath; try { canonicalPath = file.getCanonicalPath(); } catch (IOException e) { canonicalPath = file.getAbsolutePath(); } if (!file.exists()) { File[] children = file.getParentFile() != null ? file.getParentFile().listFiles() : null; for (int i = 0; children != null && i < children.length; i++) { File child = children[i]; if (child.getName().equals(file.getName())) { if (SVNFileUtil.isSymlink(file)) { return SVNFileType.SYMLINK; } } } } else if (!absolutePath.equals(canonicalPath) && SVNFileUtil.isSymlink(file)) { return SVNFileType.SYMLINK; } } if (file.isFile()) { return SVNFileType.FILE; } else if (file.isDirectory()) { return SVNFileType.DIRECTORY; } else if (!file.exists()) { return SVNFileType.NONE; } return SVNFileType.UNKNOWN; }
diff --git a/ffxieq/src/com/github/kanata3249/ffxieq/android/db/FFXIDatabase.java b/ffxieq/src/com/github/kanata3249/ffxieq/android/db/FFXIDatabase.java index 5562d81..a5f3ea1 100644 --- a/ffxieq/src/com/github/kanata3249/ffxieq/android/db/FFXIDatabase.java +++ b/ffxieq/src/com/github/kanata3249/ffxieq/android/db/FFXIDatabase.java @@ -1,309 +1,313 @@ /* Copyright 2011 kanata3249 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.github.kanata3249.ffxieq.android.db; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.channels.FileChannel; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import com.github.kanata3249.ffxi.*; import com.github.kanata3249.ffxi.status.StatusType; import com.github.kanata3249.ffxieq.Atma; import com.github.kanata3249.ffxieq.Combination; import com.github.kanata3249.ffxieq.Equipment; import com.github.kanata3249.ffxieq.JobTrait; import android.content.Context; import android.content.res.AssetManager; import android.database.Cursor; import android.database.sqlite.*; import android.os.Environment; public class FFXIDatabase extends SQLiteOpenHelper implements FFXIDAO { public static final String DB_NAME = "ffxieq.db"; public static final String DB_NAME_ASSET = "ffxieq.zip"; public static String DB_PATH; public static String SD_PATH; static final Character[][] RaceToStatusRank = { // TODO This table should be read from DB. // HP MP STR DEX VIT AGI INT MND CHR 0:A 1:B 2:C 3:D 4:E 5:F 6:G { 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D' }, // Hum { 'C', 'E', 'B', 'E', 'C', 'F', 'F', 'B', 'D' }, // Elv { 'G', 'A', 'F', 'D', 'E', 'C', 'A', 'E', 'D' }, // Tar { 'D', 'D', 'E', 'A', 'E', 'B', 'D', 'E', 'F' }, // Mit { 'A', 'G', 'C', 'D', 'A', 'E', 'E', 'D', 'F' }, // Gal }; String [][] JobToRank; Context mContext; HPTable mHpTable; MPTable mMpTable; JobRankTable mJobRankTable; StatusTable mStatusTable; SkillCapTable mSkillCapTable; EquipmentTable mEquipmentTable; AtmaTable mAtmaTable; JobTraitTable mJobTraitTable; MeritPointTable mMeritPointTable; StringTable mStringTable; boolean mUseExternalDB; String mDBPath; // Constructor public FFXIDatabase(Context context, boolean useExternal) { super(context, DB_NAME, null, 1); DB_PATH = Environment.getDataDirectory() + "/data/" + context.getPackageName() + "/databases/"; SD_PATH = Environment.getExternalStorageDirectory() + "/" + context.getPackageName() + "/"; mContext = context; mHpTable = new HPTable(); mMpTable = new MPTable(); mJobRankTable = new JobRankTable(); mSkillCapTable = new SkillCapTable(); mStatusTable = new StatusTable(); mEquipmentTable = new EquipmentTable(); mAtmaTable = new AtmaTable(); mJobTraitTable = new JobTraitTable(); mMeritPointTable = new MeritPointTable(); mStringTable = new StringTable(); if (useExternal) mDBPath = SD_PATH; else mDBPath = DB_PATH; mUseExternalDB = useExternal; if (checkDatabase(mDBPath)) { try { copyDatabaseFromAssets(mDBPath); } catch (IOException e) { } } } static public String getDBPath(boolean useExternalDB) { String path; if (DB_PATH == null) return DB_NAME; if (useExternalDB) { path = SD_PATH + DB_NAME; } else { path = DB_PATH + DB_NAME; } return path; } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } @Override public synchronized SQLiteDatabase getWritableDatabase() { SQLiteException e = new SQLiteException(); throw e; } public boolean checkDatabase(String pathToCheck) { File in = new File(pathToCheck + DB_NAME); if (in.isFile()) return false; return true; } public void copyDatabaseFromAssets(String pathToCopy) throws IOException { InputStream in = mContext.getAssets().open(DB_NAME_ASSET, AssetManager.ACCESS_STREAMING); ZipInputStream zipIn = new ZipInputStream(in); ZipEntry zipEntry = zipIn.getNextEntry(); if (pathToCopy == null) { if (mUseExternalDB) pathToCopy = SD_PATH; else pathToCopy = DB_PATH; } File outDir = new File(pathToCopy); - SQLiteDatabase db; + try { + SQLiteDatabase db; - db = getReadableDatabase(); - if (db != null) - db.close(); + db = getReadableDatabase(); + if (db != null) + db.close(); + } catch (SQLiteException e) { + // ignore this + } outDir.mkdir(); while (zipEntry != null) { byte[] buffer = new byte[4096]; int size; if (zipEntry.getName().equalsIgnoreCase(DB_NAME)) { OutputStream out = new FileOutputStream(pathToCopy + zipEntry.getName()); while ((size = zipIn.read(buffer, 0, buffer.length)) > -1) { out.write(buffer, 0, size); } out.flush(); out.close(); File to = new File(pathToCopy + zipEntry.getName()); to.setLastModified(zipEntry.getTime()); } zipIn.closeEntry(); zipEntry = zipIn.getNextEntry(); } zipIn.close(); in.close(); } public void copyDatabaseFromSD() throws IOException { File outDir = new File(DB_PATH); SQLiteDatabase db; db = getReadableDatabase(); if (db != null) db.close(); outDir.mkdir(); FileChannel channelSource = new FileInputStream(SD_PATH + DB_NAME).getChannel(); FileChannel channelTarget = new FileOutputStream(DB_PATH + DB_NAME).getChannel(); channelSource.transferTo(0, channelSource.size(), channelTarget); channelSource.close(); channelTarget.close(); // Copy last modified File from = new File(SD_PATH + DB_NAME); File to = new File(DB_PATH + DB_NAME); to.setLastModified(from.lastModified()); } public void copyDatabaseToSD() throws IOException { File outDir = new File(SD_PATH); outDir.mkdir(); FileChannel channelSource = new FileInputStream(DB_PATH + DB_NAME).getChannel(); FileChannel channelTarget = new FileOutputStream(SD_PATH + DB_NAME).getChannel(); channelSource.transferTo(0, channelSource.size(), channelTarget); channelSource.close(); channelTarget.close(); // Copy last modified File from = new File(DB_PATH + DB_NAME); File to = new File(SD_PATH + DB_NAME); to.setLastModified(from.lastModified()); } public boolean setUseExternalDB(boolean useExternalDB) { if (useExternalDB == mUseExternalDB) return true; try { if (useExternalDB) { copyDatabaseToSD(); getReadableDatabase().close(); File oldDB = new File(DB_PATH + DB_NAME); oldDB.delete(); } else { copyDatabaseFromSD(); getReadableDatabase().close(); File oldDB = new File(SD_PATH + DB_NAME); oldDB.delete(); } mUseExternalDB = useExternalDB; return true; } catch (IOException e) { return false; } } // DA methods public String jobToRank(int job, StatusType type) { String ret; if (JobToRank == null) JobToRank = mJobRankTable.buildJobRankTable(getReadableDatabase()); ret = JobToRank[job][type.ordinal()]; if (ret == null) { ret = "-"; } return ret; } public int getHP(int race, int job, int joblevel, int subjob, int subjoblevel) { return mHpTable.getHP(getReadableDatabase(), RaceToStatusRank[race][StatusType.HP.ordinal()].toString(), jobToRank(job, StatusType.HP), joblevel, jobToRank(subjob, StatusType.HP), subjoblevel); } public int getMP(int race, int job, int joblevel, int subjob, int subjoblevel) { return mMpTable.getMP(getReadableDatabase(), RaceToStatusRank[race][StatusType.MP.ordinal()].toString(), jobToRank(job, StatusType.MP), joblevel, jobToRank(subjob, StatusType.MP), subjoblevel); } public int getStatus(StatusType type, int race, int job, int joblevel, int subjob, int subjoblevel) { return mStatusTable.getStatus(getReadableDatabase(), RaceToStatusRank[race][type.ordinal()].toString(), jobToRank(job, type), joblevel, jobToRank(subjob, type), subjoblevel); } public int getSkillCap(StatusType type, int job, int joblevel, int subjob, int subjoblevel) { return mSkillCapTable.getSkillCap(getReadableDatabase(), jobToRank(job, type), joblevel, jobToRank(subjob, type), subjoblevel); } public String getString(int id) { return mStringTable.getString(getReadableDatabase(), (long)id); } public Equipment instantiateEquipment(long id) { return mEquipmentTable.newInstance(this, getReadableDatabase(), id, -1); } public Atma instantiateAtma(long id) { return mAtmaTable.newInstance(this, getReadableDatabase(), id); } public JobTrait[] getJobTraits(int job, int level) { return mJobTraitTable.getJobTraits(this, getReadableDatabase(), getString(FFXIString.JOB_DB_WAR + job), level); } public Combination instantiateCombination(long combiID, int numMatches) { return mEquipmentTable.newCombinationInstance(this, getReadableDatabase(), combiID, numMatches); } public Combination searchCombination(String names[]) { return mEquipmentTable.searchCombinationAndNewInstance(this, getReadableDatabase(), names); } public Cursor getEquipmentCursor(int part, int race, int job, int level, String[] columns, String orderBy, String filter) { return mEquipmentTable.getCursor(this, getReadableDatabase(), part, race, job, level, columns, orderBy, filter); } public Cursor getAtmaCursor(String[] columns, String orderBy, String filter) { return mAtmaTable.getCursor(this, getReadableDatabase(), columns, orderBy, filter); } public String[] getJobSpecificMeritPointItems(int job, int category) { return mMeritPointTable.getJobSpecificMeritPointItems(this, getReadableDatabase(), getString(FFXIString.JOB_DB_WAR + job), category); } public long[] getJobSpecificMeritPointItemIds(int job, int category) { return mMeritPointTable.getJobSpecificMeritPointItemIds(this, getReadableDatabase(), getString(FFXIString.JOB_DB_WAR + job), category); } public JobTrait instantiateMeritPointJobTrait(long id, int level) { return mMeritPointTable.newInstance(this, getReadableDatabase(), id, level); } }
false
true
public void copyDatabaseFromAssets(String pathToCopy) throws IOException { InputStream in = mContext.getAssets().open(DB_NAME_ASSET, AssetManager.ACCESS_STREAMING); ZipInputStream zipIn = new ZipInputStream(in); ZipEntry zipEntry = zipIn.getNextEntry(); if (pathToCopy == null) { if (mUseExternalDB) pathToCopy = SD_PATH; else pathToCopy = DB_PATH; } File outDir = new File(pathToCopy); SQLiteDatabase db; db = getReadableDatabase(); if (db != null) db.close(); outDir.mkdir(); while (zipEntry != null) { byte[] buffer = new byte[4096]; int size; if (zipEntry.getName().equalsIgnoreCase(DB_NAME)) { OutputStream out = new FileOutputStream(pathToCopy + zipEntry.getName()); while ((size = zipIn.read(buffer, 0, buffer.length)) > -1) { out.write(buffer, 0, size); } out.flush(); out.close(); File to = new File(pathToCopy + zipEntry.getName()); to.setLastModified(zipEntry.getTime()); } zipIn.closeEntry(); zipEntry = zipIn.getNextEntry(); } zipIn.close(); in.close(); }
public void copyDatabaseFromAssets(String pathToCopy) throws IOException { InputStream in = mContext.getAssets().open(DB_NAME_ASSET, AssetManager.ACCESS_STREAMING); ZipInputStream zipIn = new ZipInputStream(in); ZipEntry zipEntry = zipIn.getNextEntry(); if (pathToCopy == null) { if (mUseExternalDB) pathToCopy = SD_PATH; else pathToCopy = DB_PATH; } File outDir = new File(pathToCopy); try { SQLiteDatabase db; db = getReadableDatabase(); if (db != null) db.close(); } catch (SQLiteException e) { // ignore this } outDir.mkdir(); while (zipEntry != null) { byte[] buffer = new byte[4096]; int size; if (zipEntry.getName().equalsIgnoreCase(DB_NAME)) { OutputStream out = new FileOutputStream(pathToCopy + zipEntry.getName()); while ((size = zipIn.read(buffer, 0, buffer.length)) > -1) { out.write(buffer, 0, size); } out.flush(); out.close(); File to = new File(pathToCopy + zipEntry.getName()); to.setLastModified(zipEntry.getTime()); } zipIn.closeEntry(); zipEntry = zipIn.getNextEntry(); } zipIn.close(); in.close(); }
diff --git a/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/ContentRepresentationGet.java b/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/ContentRepresentationGet.java index a7420c7ab..6136e9c4b 100644 --- a/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/ContentRepresentationGet.java +++ b/activiti-webapp-rest/src/main/java/org/activiti/rest/api/cycle/ContentRepresentationGet.java @@ -1,100 +1,100 @@ /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.activiti.rest.api.cycle; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.http.HttpSession; import org.activiti.cycle.ContentRepresentation; import org.activiti.cycle.CycleDefaultMimeType; import org.activiti.cycle.CycleService; import org.activiti.cycle.RenderInfo; import org.activiti.cycle.RepositoryArtifact; import org.activiti.cycle.impl.CycleServiceImpl; import org.activiti.cycle.impl.transform.TransformationException; import org.activiti.rest.util.ActivitiRequest; import org.activiti.rest.util.ActivitiWebScript; import org.springframework.extensions.webscripts.Cache; import org.springframework.extensions.webscripts.Status; /** * * @author Nils Preusker ([email protected]) */ public class ContentRepresentationGet extends ActivitiWebScript { private static Logger log = Logger.getLogger(ContentRepresentationGet.class.getName()); private CycleService cycleService; private void init(ActivitiRequest req) { String cuid = req.getCurrentUserId(); HttpSession session = req.getHttpServletRequest().getSession(true); this.cycleService = CycleServiceImpl.getCycleService(cuid, session); } @Override protected void executeWebScript(ActivitiRequest req, Status status, Cache cache, Map<String, Object> model) { init(req); String connectorId = req.getMandatoryString("connectorId"); String artifactId = req.getString("artifactId"); String representationId = req.getString("representationId"); RepositoryArtifact artifact = this.cycleService.getRepositoryArtifact(connectorId, artifactId); // Get representation by id to determine whether it is an image... try { model.put("connectorId", connectorId); model.put("artifactId", artifactId); ContentRepresentation contentRepresentation = artifact.getArtifactType().getContentRepresentation(representationId); switch (contentRepresentation.getRenderInfo()) { case IMAGE: case HTML: // For images and HTML we don't need to send the content, the URL will // be put together in the UI // and the content will be requested via ContentGet. break; case HTML_REFERENCE: case BINARY: case CODE: case TEXT_PLAIN: String content = this.cycleService.getContent(connectorId, artifactId, contentRepresentation.getId()).asString(); model.put("content", content); } model.put("renderInfo", contentRepresentation.getRenderInfo().name()); model.put("contentRepresentationId", contentRepresentation.getId()); model.put("contentType", contentRepresentation.getMimeType().getContentType()); } catch (TransformationException e) { // Show errors that occur during transformations as HTML in the UI model.put("renderInfo", RenderInfo.HTML); - model.put("contentRepresentationId", "Exception"); + model.put("contentRepresentationId", representationId); model.put("content", e.getRenderContent()); model.put("contentType", CycleDefaultMimeType.HTML.getContentType()); } catch (Exception ex) { log.log(Level.WARNING, "Exception while loading content representation", ex); // TODO:Better concept how this is handled in the GUI StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); String stackTrace = "Exception while accessing content. Details:\n\n" + sw.toString(); model.put("exception", stackTrace); } } }
true
true
protected void executeWebScript(ActivitiRequest req, Status status, Cache cache, Map<String, Object> model) { init(req); String connectorId = req.getMandatoryString("connectorId"); String artifactId = req.getString("artifactId"); String representationId = req.getString("representationId"); RepositoryArtifact artifact = this.cycleService.getRepositoryArtifact(connectorId, artifactId); // Get representation by id to determine whether it is an image... try { model.put("connectorId", connectorId); model.put("artifactId", artifactId); ContentRepresentation contentRepresentation = artifact.getArtifactType().getContentRepresentation(representationId); switch (contentRepresentation.getRenderInfo()) { case IMAGE: case HTML: // For images and HTML we don't need to send the content, the URL will // be put together in the UI // and the content will be requested via ContentGet. break; case HTML_REFERENCE: case BINARY: case CODE: case TEXT_PLAIN: String content = this.cycleService.getContent(connectorId, artifactId, contentRepresentation.getId()).asString(); model.put("content", content); } model.put("renderInfo", contentRepresentation.getRenderInfo().name()); model.put("contentRepresentationId", contentRepresentation.getId()); model.put("contentType", contentRepresentation.getMimeType().getContentType()); } catch (TransformationException e) { // Show errors that occur during transformations as HTML in the UI model.put("renderInfo", RenderInfo.HTML); model.put("contentRepresentationId", "Exception"); model.put("content", e.getRenderContent()); model.put("contentType", CycleDefaultMimeType.HTML.getContentType()); } catch (Exception ex) { log.log(Level.WARNING, "Exception while loading content representation", ex); // TODO:Better concept how this is handled in the GUI StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); String stackTrace = "Exception while accessing content. Details:\n\n" + sw.toString(); model.put("exception", stackTrace); } }
protected void executeWebScript(ActivitiRequest req, Status status, Cache cache, Map<String, Object> model) { init(req); String connectorId = req.getMandatoryString("connectorId"); String artifactId = req.getString("artifactId"); String representationId = req.getString("representationId"); RepositoryArtifact artifact = this.cycleService.getRepositoryArtifact(connectorId, artifactId); // Get representation by id to determine whether it is an image... try { model.put("connectorId", connectorId); model.put("artifactId", artifactId); ContentRepresentation contentRepresentation = artifact.getArtifactType().getContentRepresentation(representationId); switch (contentRepresentation.getRenderInfo()) { case IMAGE: case HTML: // For images and HTML we don't need to send the content, the URL will // be put together in the UI // and the content will be requested via ContentGet. break; case HTML_REFERENCE: case BINARY: case CODE: case TEXT_PLAIN: String content = this.cycleService.getContent(connectorId, artifactId, contentRepresentation.getId()).asString(); model.put("content", content); } model.put("renderInfo", contentRepresentation.getRenderInfo().name()); model.put("contentRepresentationId", contentRepresentation.getId()); model.put("contentType", contentRepresentation.getMimeType().getContentType()); } catch (TransformationException e) { // Show errors that occur during transformations as HTML in the UI model.put("renderInfo", RenderInfo.HTML); model.put("contentRepresentationId", representationId); model.put("content", e.getRenderContent()); model.put("contentType", CycleDefaultMimeType.HTML.getContentType()); } catch (Exception ex) { log.log(Level.WARNING, "Exception while loading content representation", ex); // TODO:Better concept how this is handled in the GUI StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); String stackTrace = "Exception while accessing content. Details:\n\n" + sw.toString(); model.put("exception", stackTrace); } }
diff --git a/jsf/components/component/src/org/icefaces/mobi/component/contentstack/ContentStackRenderer.java b/jsf/components/component/src/org/icefaces/mobi/component/contentstack/ContentStackRenderer.java index 06706cae6..39c318b92 100644 --- a/jsf/components/component/src/org/icefaces/mobi/component/contentstack/ContentStackRenderer.java +++ b/jsf/components/component/src/org/icefaces/mobi/component/contentstack/ContentStackRenderer.java @@ -1,202 +1,202 @@ /* * Copyright 2004-2013 ICEsoft Technologies Canada Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.icefaces.mobi.component.contentstack; import static org.icemobile.util.HTML.CLASS_ATTR; import java.io.IOException; import java.util.Iterator; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.context.ResponseWriter; import org.icefaces.mobi.component.contentnavbar.ContentNavBar; import org.icefaces.mobi.component.contentpane.ContentPane; import org.icefaces.mobi.renderkit.BaseLayoutRenderer; import org.icefaces.mobi.utils.HTML; import org.icefaces.mobi.utils.JSFUtils; import org.icefaces.mobi.utils.MobiJSFUtils; public class ContentStackRenderer extends BaseLayoutRenderer { private static final Logger logger = Logger.getLogger(ContentStackRenderer.class.getName()); private static final String JS_LIBRARY = "org.icefaces.component.layoutmenu"; @Override public void decode(FacesContext facesContext, UIComponent component) { ContentStack stack = (ContentStack) component; String clientId = stack.getClientId(facesContext); Map<String, String> params = facesContext.getExternalContext().getRequestParameterMap(); // ajax behavior comes from ContentStackMenu which sends the currently selected value String indexStr = params.get(clientId + "_hidden"); String newStr = params.get(clientId); if (newStr !=null){ logger.info("submitted "+newStr+" from request"); } String oldIndex = stack.getCurrentId(); if( null != indexStr) { //find the activeIndex and set it if (!oldIndex.equals(indexStr)){ stack.setCurrentId(indexStr); /* do we want to queue an event for panel change in stack? */ // component.queueEvent(new ValueChangeEvent(component, oldIndex, indexStr)) ; } } } public void encodeBegin(FacesContext facesContext, UIComponent uiComponent)throws IOException { ResponseWriter writer = facesContext.getResponseWriter(); String clientId = uiComponent.getClientId(facesContext); ContentStack container = (ContentStack) uiComponent; /* can use stack with contentNavBar so may need to write out javascript for menu */ if ((container.getContentMenuId() == null) && hasNavBarChild(container)!=null){ container.setNavBar(true); } else { container.setNavBar(false); } /* write out root tag. For current incarnation html5 semantic markup is ignored */ writer.startElement(HTML.DIV_ELEM, uiComponent); writer.writeAttribute(HTML.ID_ATTR, clientId, HTML.ID_ATTR); //if layoutMenu is used then another div with panes Id is used if (container.getContentMenuId()!=null){ if (null == container.getSingleView()){ UIComponent stackMenuComp = JSFUtils.findChildComponent(uiComponent, container.getContentMenuId()); if (stackMenuComp !=null){ container.setSingleView(true); }else { container.setSingleView(false); } } boolean singleView = container.getSingleView(); if (singleView){ writer.writeAttribute("class", ContentStack.CONTAINER_SINGLEVIEW_CLASS, null); } writer.startElement(HTML.DIV_ELEM, uiComponent); writer.writeAttribute(HTML.ID_ATTR, clientId+"_panes", HTML.ID_ATTR); if (singleView){ writer.writeAttribute("class", ContentStack.PANES_SINGLEVIEW_CLASS, "class" ); } } if (container.hasNavBar()){ writer.startElement(HTML.DIV_ELEM, uiComponent); writer.writeAttribute(HTML.ID_ATTR, clientId+"_panes", HTML.ID_ATTR); } } public boolean getRendersChildren() { return true; } public void encodeChildren(FacesContext facesContext, UIComponent uiComponent) throws IOException{ //all children must be of type contentPane which takes care of rendering it's children...or not for (UIComponent child : uiComponent.getChildren()) { if (!(child instanceof ContentPane) && logger.isLoggable(Level.FINER)){ logger.finer("all children must be of type ContentPane"); return; } } //if don't find the one asked for just show the first one. or just leave all hidden?? TODO super.renderChildren(facesContext, uiComponent); } public void encodeEnd(FacesContext facesContext, UIComponent uiComponent) throws IOException { ResponseWriter writer = facesContext.getResponseWriter(); ContentStack stack = (ContentStack) uiComponent; this.encodeHidden(facesContext, uiComponent); writer.endElement(HTML.DIV_ELEM); if (stack.getContentMenuId() !=null || stack.hasNavBar()){ encodeScript(facesContext, uiComponent); writer.endElement(HTML.DIV_ELEM); } } private void encodeScript(FacesContext facesContext, UIComponent uiComponent) throws IOException{ //need to initialize the component on the page and can also ResponseWriter writer = facesContext.getResponseWriter(); ContentStack stack = (ContentStack) uiComponent; String clientId = stack.getClientId(facesContext); writer.startElement("span", uiComponent); writer.writeAttribute(CLASS_ATTR, "mobi-hidden", null); writer.writeAttribute("id", clientId+"_initScr", "id"); writer.startElement("script", uiComponent); writer.writeAttribute("type", "text/javascript", null); String selectedPaneId = stack.getSelectedId(); boolean client = false; int hashcode = MobiJSFUtils.generateHashCode(System.currentTimeMillis()); StringBuilder sb = new StringBuilder("mobi.layoutMenu.initClient('").append(clientId).append("'"); sb.append(",{stackId: '").append(clientId).append("'"); sb.append(",selectedId: '").append(selectedPaneId).append("'"); sb.append(", single: ").append(stack.getSingleView()); sb.append(",hash: ").append(hashcode); ContentPane selPane = null; - if( selectedPaneId == null || selectedPaneId.length() > 0 ){ + if( selectedPaneId == null || selectedPaneId.length() == 0 ){ //auto-select the first contentPane selectedPaneId = stack.getChildren().get(0).getId(); } selPane = (ContentPane)stack.findComponent(selectedPaneId); //if the selectedPaneId is not valid, auto-select the first contentPane if( selPane == null ){ selPane = (ContentPane)stack.getChildren().get(0); selectedPaneId = selPane.getId(); } if (null != selPane){ String selectedPaneClientId = null; selectedPaneClientId = selPane.getClientId(facesContext); sb.append(",selClientId: '").append(selectedPaneClientId).append("'"); client = selPane.isClient(); } String contentMenuId = stack.getContentMenuId(); if (contentMenuId !=null && contentMenuId.length() > 0){ UIComponent menu = stack.findComponent(contentMenuId); String homeId = null; if (null!=menu){ homeId = menu.getClientId(facesContext); } sb.append(",home: '").append(homeId).append("'"); } sb.append(",client: ").append(client); sb.append("});"); writer.write(sb.toString()); writer.endElement("script"); writer.endElement("span"); } private UIComponent hasNavBarChild( UIComponent comp) { if (comp instanceof ContentNavBar){ return comp; } UIComponent child = null; UIComponent retComp = null; Iterator children = comp.getFacetsAndChildren(); while (children.hasNext() && (retComp==null)){ child = (UIComponent)children.next(); if (child instanceof ContentNavBar){ retComp = child; break; } retComp = hasNavBarChild(child); if (retComp !=null){ break; } } return retComp; } }
true
true
private void encodeScript(FacesContext facesContext, UIComponent uiComponent) throws IOException{ //need to initialize the component on the page and can also ResponseWriter writer = facesContext.getResponseWriter(); ContentStack stack = (ContentStack) uiComponent; String clientId = stack.getClientId(facesContext); writer.startElement("span", uiComponent); writer.writeAttribute(CLASS_ATTR, "mobi-hidden", null); writer.writeAttribute("id", clientId+"_initScr", "id"); writer.startElement("script", uiComponent); writer.writeAttribute("type", "text/javascript", null); String selectedPaneId = stack.getSelectedId(); boolean client = false; int hashcode = MobiJSFUtils.generateHashCode(System.currentTimeMillis()); StringBuilder sb = new StringBuilder("mobi.layoutMenu.initClient('").append(clientId).append("'"); sb.append(",{stackId: '").append(clientId).append("'"); sb.append(",selectedId: '").append(selectedPaneId).append("'"); sb.append(", single: ").append(stack.getSingleView()); sb.append(",hash: ").append(hashcode); ContentPane selPane = null; if( selectedPaneId == null || selectedPaneId.length() > 0 ){ //auto-select the first contentPane selectedPaneId = stack.getChildren().get(0).getId(); } selPane = (ContentPane)stack.findComponent(selectedPaneId); //if the selectedPaneId is not valid, auto-select the first contentPane if( selPane == null ){ selPane = (ContentPane)stack.getChildren().get(0); selectedPaneId = selPane.getId(); } if (null != selPane){ String selectedPaneClientId = null; selectedPaneClientId = selPane.getClientId(facesContext); sb.append(",selClientId: '").append(selectedPaneClientId).append("'"); client = selPane.isClient(); } String contentMenuId = stack.getContentMenuId(); if (contentMenuId !=null && contentMenuId.length() > 0){ UIComponent menu = stack.findComponent(contentMenuId); String homeId = null; if (null!=menu){ homeId = menu.getClientId(facesContext); } sb.append(",home: '").append(homeId).append("'"); } sb.append(",client: ").append(client); sb.append("});"); writer.write(sb.toString()); writer.endElement("script"); writer.endElement("span"); }
private void encodeScript(FacesContext facesContext, UIComponent uiComponent) throws IOException{ //need to initialize the component on the page and can also ResponseWriter writer = facesContext.getResponseWriter(); ContentStack stack = (ContentStack) uiComponent; String clientId = stack.getClientId(facesContext); writer.startElement("span", uiComponent); writer.writeAttribute(CLASS_ATTR, "mobi-hidden", null); writer.writeAttribute("id", clientId+"_initScr", "id"); writer.startElement("script", uiComponent); writer.writeAttribute("type", "text/javascript", null); String selectedPaneId = stack.getSelectedId(); boolean client = false; int hashcode = MobiJSFUtils.generateHashCode(System.currentTimeMillis()); StringBuilder sb = new StringBuilder("mobi.layoutMenu.initClient('").append(clientId).append("'"); sb.append(",{stackId: '").append(clientId).append("'"); sb.append(",selectedId: '").append(selectedPaneId).append("'"); sb.append(", single: ").append(stack.getSingleView()); sb.append(",hash: ").append(hashcode); ContentPane selPane = null; if( selectedPaneId == null || selectedPaneId.length() == 0 ){ //auto-select the first contentPane selectedPaneId = stack.getChildren().get(0).getId(); } selPane = (ContentPane)stack.findComponent(selectedPaneId); //if the selectedPaneId is not valid, auto-select the first contentPane if( selPane == null ){ selPane = (ContentPane)stack.getChildren().get(0); selectedPaneId = selPane.getId(); } if (null != selPane){ String selectedPaneClientId = null; selectedPaneClientId = selPane.getClientId(facesContext); sb.append(",selClientId: '").append(selectedPaneClientId).append("'"); client = selPane.isClient(); } String contentMenuId = stack.getContentMenuId(); if (contentMenuId !=null && contentMenuId.length() > 0){ UIComponent menu = stack.findComponent(contentMenuId); String homeId = null; if (null!=menu){ homeId = menu.getClientId(facesContext); } sb.append(",home: '").append(homeId).append("'"); } sb.append(",client: ").append(client); sb.append("});"); writer.write(sb.toString()); writer.endElement("script"); writer.endElement("span"); }
diff --git a/test/regression/SoTimeout.java b/test/regression/SoTimeout.java index c0e657841..033a4c399 100644 --- a/test/regression/SoTimeout.java +++ b/test/regression/SoTimeout.java @@ -1,84 +1,85 @@ /** * Test socket timeouts for accept and read for simple stream sockets * * @author Godmar Back <[email protected]> */ import java.net.*; import java.io.*; public class SoTimeout { public static void main(String av[]) throws Exception { final String foo = "foo"; int tryport = 45054; ServerSocket server; for(;;++tryport) { try { server = new ServerSocket(tryport); break; } catch (IOException _) {} } final int port = tryport; Thread watchdog = new Thread() { public void run() { try { Thread.sleep(10000); } catch (InterruptedException _) { } System.out.println("Failure: Time out."); System.exit(-1); } }; watchdog.start(); Thread t = new Thread() { public void run() { try { Socket s = new Socket(InetAddress.getLocalHost(), port); try { Thread.sleep(3000); } catch (InterruptedException e) { System.out.println("Failure " + e); } PrintWriter p = new PrintWriter(s.getOutputStream()); p.println(foo); p.close(); } catch (Exception e) { System.out.println("Failure " + e); } } }; server.setSoTimeout(1000); Socket rsocket = null; try { rsocket = server.accept(); } catch (InterruptedIOException e) { // System.out.println(e); System.out.println("Success 1."); } t.start(); rsocket = server.accept(); System.out.println("Success 2."); rsocket.setSoTimeout(2000); // NB: 2 * 2000 > 3000 InputStream is = rsocket.getInputStream(); LineNumberReader r = new LineNumberReader(new InputStreamReader(is)); byte []b = null; try { r.readLine(); } catch (InterruptedIOException e) { // System.out.println(e); System.out.println("Success 3."); } String s = r.readLine(); if (s.equals(foo)) { System.out.println("Success 4."); } + System.exit(0); } } /* Expected Output: Success 1. Success 2. Success 3. Success 4. */
true
true
public static void main(String av[]) throws Exception { final String foo = "foo"; int tryport = 45054; ServerSocket server; for(;;++tryport) { try { server = new ServerSocket(tryport); break; } catch (IOException _) {} } final int port = tryport; Thread watchdog = new Thread() { public void run() { try { Thread.sleep(10000); } catch (InterruptedException _) { } System.out.println("Failure: Time out."); System.exit(-1); } }; watchdog.start(); Thread t = new Thread() { public void run() { try { Socket s = new Socket(InetAddress.getLocalHost(), port); try { Thread.sleep(3000); } catch (InterruptedException e) { System.out.println("Failure " + e); } PrintWriter p = new PrintWriter(s.getOutputStream()); p.println(foo); p.close(); } catch (Exception e) { System.out.println("Failure " + e); } } }; server.setSoTimeout(1000); Socket rsocket = null; try { rsocket = server.accept(); } catch (InterruptedIOException e) { // System.out.println(e); System.out.println("Success 1."); } t.start(); rsocket = server.accept(); System.out.println("Success 2."); rsocket.setSoTimeout(2000); // NB: 2 * 2000 > 3000 InputStream is = rsocket.getInputStream(); LineNumberReader r = new LineNumberReader(new InputStreamReader(is)); byte []b = null; try { r.readLine(); } catch (InterruptedIOException e) { // System.out.println(e); System.out.println("Success 3."); } String s = r.readLine(); if (s.equals(foo)) { System.out.println("Success 4."); } }
public static void main(String av[]) throws Exception { final String foo = "foo"; int tryport = 45054; ServerSocket server; for(;;++tryport) { try { server = new ServerSocket(tryport); break; } catch (IOException _) {} } final int port = tryport; Thread watchdog = new Thread() { public void run() { try { Thread.sleep(10000); } catch (InterruptedException _) { } System.out.println("Failure: Time out."); System.exit(-1); } }; watchdog.start(); Thread t = new Thread() { public void run() { try { Socket s = new Socket(InetAddress.getLocalHost(), port); try { Thread.sleep(3000); } catch (InterruptedException e) { System.out.println("Failure " + e); } PrintWriter p = new PrintWriter(s.getOutputStream()); p.println(foo); p.close(); } catch (Exception e) { System.out.println("Failure " + e); } } }; server.setSoTimeout(1000); Socket rsocket = null; try { rsocket = server.accept(); } catch (InterruptedIOException e) { // System.out.println(e); System.out.println("Success 1."); } t.start(); rsocket = server.accept(); System.out.println("Success 2."); rsocket.setSoTimeout(2000); // NB: 2 * 2000 > 3000 InputStream is = rsocket.getInputStream(); LineNumberReader r = new LineNumberReader(new InputStreamReader(is)); byte []b = null; try { r.readLine(); } catch (InterruptedIOException e) { // System.out.println(e); System.out.println("Success 3."); } String s = r.readLine(); if (s.equals(foo)) { System.out.println("Success 4."); } System.exit(0); }
diff --git a/src/com/aragaer/jtt/JTTHour.java b/src/com/aragaer/jtt/JTTHour.java index 0abc6d5..9293105 100644 --- a/src/com/aragaer/jtt/JTTHour.java +++ b/src/com/aragaer/jtt/JTTHour.java @@ -1,102 +1,102 @@ package com.aragaer.jtt; import android.os.Parcel; import android.os.Parcelable; public class JTTHour implements Parcelable { public static final int QUARTERS = 4; public static final int PARTS = 10; // split quarter to that much parts public static final int HOUR_PARTS = QUARTERS * PARTS; private static final int DAY_QUARTERS = 12 * QUARTERS; public static final String Glyphs[] = { "酉", "戌", "亥", "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申" }; public boolean isNight; public int num; // 0 to 11, where 0 is hour of Cock and 11 is hour of Monkey public int quarter; // 0 to 3 public int quarter_parts; // 0 to PARTS public JTTHour(int num) { this(num, QUARTERS / 2, 0); } public JTTHour(int n, int q, int f) { this.setTo(n, q, f); } // Instead of reallocation, reuse existing object public void setTo(int n, int q, int f) { num = n; isNight = n < 6; quarter = q; quarter_parts = f; } public static final Parcelable.Creator<JTTHour> CREATOR = new Parcelable.Creator<JTTHour>() { public JTTHour createFromParcel(Parcel in) { return new JTTHour(in); } public JTTHour[] newArray(int size) { return new JTTHour[size]; } }; private JTTHour(Parcel in) { unwrap(in.readInt(), this); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(wrap()); } /* * Wrapped value is a single integer denoting the JTT * Wrapping: * Wrapped value is a number of hour parts passed since last sunset * To calculate it we use SHIFTED_QUARTER * SHIFTED_QUARTER is number of quarters passed since last sunset * It is "shifted" because at sunset quarter number is QUARTERS/2 * SHIFTED_QUARTER = (HOUR * QUARTERS + QUARTER + QUARTER_SHIFT) % DAY_QUARTERS * WRAPPED = SHIFTED_QUARTER * PARTS + PART * * Unwrapping: * PART = WRAPPED % PARTS * SHIFTED_QUARTER = WRAPPED / PARTS * QUARTER = (SHIFTED_QUARTER + QUARTERS / 2) % QUARTERS * HOUR = (SHIFTED_QUARTER + QUARTERS / 2) / QUARTERS */ /* I'd do simple subtraction, but it can get bad near zero since % keeps sign */ private static final int QUARTER_SHIFT = DAY_QUARTERS - QUARTERS / 2; public static int wrap(int n, int q, int p) { final int shifted_q = (n * QUARTERS + q + QUARTER_SHIFT) % DAY_QUARTERS; return shifted_q * PARTS + p; } /* wrap self */ public int wrap() { return wrap(num, quarter, quarter_parts); } public static JTTHour unwrap(int wrapped) { return unwrap(wrapped, null); } public static JTTHour unwrap(int wrapped, JTTHour reuse) { if (reuse == null) reuse = new JTTHour(0); final int unshifted_q = wrapped / PARTS + QUARTERS / 2; // that is shifted_q + shift back - reuse.setTo(unshifted_q / QUARTERS, unshifted_q % QUARTERS, wrapped % PARTS); + reuse.setTo(unshifted_q / QUARTERS % 12, unshifted_q % QUARTERS, wrapped % PARTS); return reuse; } }
true
true
public static JTTHour unwrap(int wrapped, JTTHour reuse) { if (reuse == null) reuse = new JTTHour(0); final int unshifted_q = wrapped / PARTS + QUARTERS / 2; // that is shifted_q + shift back reuse.setTo(unshifted_q / QUARTERS, unshifted_q % QUARTERS, wrapped % PARTS); return reuse; }
public static JTTHour unwrap(int wrapped, JTTHour reuse) { if (reuse == null) reuse = new JTTHour(0); final int unshifted_q = wrapped / PARTS + QUARTERS / 2; // that is shifted_q + shift back reuse.setTo(unshifted_q / QUARTERS % 12, unshifted_q % QUARTERS, wrapped % PARTS); return reuse; }
diff --git a/app/com/shopservice/queries/ProductQuery.java b/app/com/shopservice/queries/ProductQuery.java index eb7baae..2bc7582 100644 --- a/app/com/shopservice/queries/ProductQuery.java +++ b/app/com/shopservice/queries/ProductQuery.java @@ -1,47 +1,42 @@ package com.shopservice.queries; import com.shopservice.domain.Product; import java.io.UnsupportedEncodingException; import java.sql.ResultSet; import java.sql.SQLException; /** * Created with IntelliJ IDEA. * User: neuser50 * Date: 26.08.13 * Time: 16:25 * To change this template use File | Settings | File Templates. */ public abstract class ProductQuery implements Query<Product> { protected String clientId; protected ProductQuery(String clientId) { this.clientId = clientId; } @Override public Product fill(ResultSet resultSet) throws SQLException { Product product = new Product(); product.id = resultSet.getString("id"); product.categoryName = resultSet.getString("categoryName"); product.manufacturer = resultSet.getString("manufacturer"); -// product.name = resultSet.getString("name"); - try { - product.name = new String(resultSet.getBytes("name"), "windows-1251"); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } + product.name = resultSet.getString("name"); product.price = resultSet.getDouble("price"); //product.available = resultSet.getBoolean("available"); product.shortDescription = resultSet.getString("shortDescription"); product.description = resultSet.getString("description"); //product.warranty = resultSet.getString("warranty"); product.url = resultSet.getString("url"); product.imageUrl = resultSet.getString("imageUrl"); product.categoryId = resultSet.getString("categoryId"); return product; } }
true
true
public Product fill(ResultSet resultSet) throws SQLException { Product product = new Product(); product.id = resultSet.getString("id"); product.categoryName = resultSet.getString("categoryName"); product.manufacturer = resultSet.getString("manufacturer"); // product.name = resultSet.getString("name"); try { product.name = new String(resultSet.getBytes("name"), "windows-1251"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } product.price = resultSet.getDouble("price"); //product.available = resultSet.getBoolean("available"); product.shortDescription = resultSet.getString("shortDescription"); product.description = resultSet.getString("description"); //product.warranty = resultSet.getString("warranty"); product.url = resultSet.getString("url"); product.imageUrl = resultSet.getString("imageUrl"); product.categoryId = resultSet.getString("categoryId"); return product; }
public Product fill(ResultSet resultSet) throws SQLException { Product product = new Product(); product.id = resultSet.getString("id"); product.categoryName = resultSet.getString("categoryName"); product.manufacturer = resultSet.getString("manufacturer"); product.name = resultSet.getString("name"); product.price = resultSet.getDouble("price"); //product.available = resultSet.getBoolean("available"); product.shortDescription = resultSet.getString("shortDescription"); product.description = resultSet.getString("description"); //product.warranty = resultSet.getString("warranty"); product.url = resultSet.getString("url"); product.imageUrl = resultSet.getString("imageUrl"); product.categoryId = resultSet.getString("categoryId"); return product; }
diff --git a/src/net/sf/gogui/go/Move.java b/src/net/sf/gogui/go/Move.java index 4cf14202..b09f9ca6 100644 --- a/src/net/sf/gogui/go/Move.java +++ b/src/net/sf/gogui/go/Move.java @@ -1,136 +1,136 @@ //---------------------------------------------------------------------------- // $Id$ // $Source$ //---------------------------------------------------------------------------- package net.sf.gogui.go; import java.util.Vector; //---------------------------------------------------------------------------- /** Move. Contains a point (null for pass move) and a color. The color is usually black or white, but empty can be used for removing a stone on the board. This class is immutable, references are unique. */ public final class Move { public static Move create(GoPoint point, GoColor color) { if (point == null) { if (color == GoColor.BLACK) return s_passBlack; else if (color == GoColor.WHITE) return s_passWhite; else if (color == GoColor.EMPTY) assert(false); } int x = point.getX(); int y = point.getY(); - int max = Math.max(x, y) + 1; + int max = Math.max(x, y); if (max >= s_size) grow(max + 1); if (color == GoColor.BLACK) return s_movesBlack[x][y]; else if (color == GoColor.WHITE) return s_movesWhite[x][y]; else return s_movesEmpty[x][y]; } /** Fill a list of moves with pass moves. The resulting list will contain all moves of the original list in the same order, but ensure it starts with a move of color toMove and have no subsequent moves of the same color. */ public static Vector fillPasses(Vector moves, GoColor toMove) { Vector result = new Vector(moves.size() * 2); if (moves.size() == 0) return result; for (int i = 0; i < moves.size(); ++i) { Move move = (Move)moves.get(i); if (move.getColor() != toMove) result.add(new Move(null, toMove)); result.add(move); toMove = move.getColor().otherColor(); } return result; } public GoColor getColor() { return m_color; } public GoPoint getPoint() { return m_point; } public String toString() { if (m_point == null) return (m_color.toString() + " pass"); else return (m_color.toString() + " " + m_point.toString()); } private static int s_size; private static Move s_passBlack; private static Move s_passWhite; private static Move[][] s_movesBlack; private static Move[][] s_movesEmpty; private static Move[][] s_movesWhite; private final GoColor m_color; private final GoPoint m_point; static { s_passBlack = new Move(null, GoColor.BLACK); s_passWhite = new Move(null, GoColor.WHITE); s_size = 0; grow(19); }; private static void grow(int size) { assert(size > s_size); s_movesBlack = grow(size, GoColor.BLACK, s_movesBlack); s_movesWhite = grow(size, GoColor.WHITE, s_movesWhite); s_movesEmpty = grow(size, GoColor.WHITE, s_movesEmpty); s_size = size; } private static Move[][] grow(int size, GoColor color, Move[][] moves) { assert(size > s_size); Move[][] result = new Move[size][size]; for (int x = 0; x < size; ++x) for (int y = 0; y < size; ++y) if (x < s_size && y < s_size) result[x][y] = moves[x][y]; else result[x][y] = new Move(GoPoint.create(x, y), color); return result; } private Move(GoPoint point, GoColor color) { m_point = point; m_color = color; } } //----------------------------------------------------------------------------
true
true
public static Move create(GoPoint point, GoColor color) { if (point == null) { if (color == GoColor.BLACK) return s_passBlack; else if (color == GoColor.WHITE) return s_passWhite; else if (color == GoColor.EMPTY) assert(false); } int x = point.getX(); int y = point.getY(); int max = Math.max(x, y) + 1; if (max >= s_size) grow(max + 1); if (color == GoColor.BLACK) return s_movesBlack[x][y]; else if (color == GoColor.WHITE) return s_movesWhite[x][y]; else return s_movesEmpty[x][y]; }
public static Move create(GoPoint point, GoColor color) { if (point == null) { if (color == GoColor.BLACK) return s_passBlack; else if (color == GoColor.WHITE) return s_passWhite; else if (color == GoColor.EMPTY) assert(false); } int x = point.getX(); int y = point.getY(); int max = Math.max(x, y); if (max >= s_size) grow(max + 1); if (color == GoColor.BLACK) return s_movesBlack[x][y]; else if (color == GoColor.WHITE) return s_movesWhite[x][y]; else return s_movesEmpty[x][y]; }
diff --git a/app/models/SessionTranslator.java b/app/models/SessionTranslator.java index b9a2ee4..6a96aef 100644 --- a/app/models/SessionTranslator.java +++ b/app/models/SessionTranslator.java @@ -1,93 +1,93 @@ package models; import models.domain.external.IncogitoSession; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * User: Knut Haugen <[email protected]> * 2011-09-24 */ public class SessionTranslator { static Map<String, String> replacements = new HashMap<String, String>(){ { put("Ã¥", "å"); put("ø", "ø"); put("æ", "æ"); put("é", "é"); put("ö", "ö"); put("Ã\u0098", "Ø"); put("ä", "ä"); put("â\u0080\u0099", "’"); put("Ã", "Ö"); } }; public static List<IncogitoSession> translateSessions(List<HashMap<String, Object>> sessions) { List<IncogitoSession> sessionObjects = new ArrayList<IncogitoSession>(); for(Map<String, Object> v : sessions) { sessionObjects.add(createSession(v)); } return sessionObjects; } private static IncogitoSession createSession(Map<String, Object> v) { IncogitoSession session = new IncogitoSession("", "", 0); try { session = new IncogitoSession(toUTF8(v, "title"), toUTF8(v, "bodyHtml"), getYear(v)); for(Map<String, Object> values : getSpeakers(v)) { session.addSpeaker(toUTF8(values, "name"), - toUTF8(v, "bioHtml"), + toUTF8(values, "bioHtml"), (String) values.get("photoUrl")); } return session; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return session; } private static int getYear(Map<String, Object> v) { Map<String, Object> end = (Map<String, Object>) v.get("end"); return (Integer) end.get("year"); } private static List<Map<String, Object>> getSpeakers(Map<String, Object> v) { return (List<Map<String, Object>>) v.get("speakers"); } private static String toUTF8(Map<String, Object> v, String key) throws UnsupportedEncodingException { if(! v.containsKey(key)) { return ""; } if(null == v.get(key)) { return ""; } String iso = (String) v.get(key); iso = replaceCrapCharset(iso); return new String(iso.getBytes("UTF-8")); } private static String replaceCrapCharset(String iso) { String ret = iso; for(Map.Entry<String, String> e : replacements.entrySet()) { ret = ret.replaceAll(e.getKey(), e.getValue()); } return ret; } }
true
true
private static IncogitoSession createSession(Map<String, Object> v) { IncogitoSession session = new IncogitoSession("", "", 0); try { session = new IncogitoSession(toUTF8(v, "title"), toUTF8(v, "bodyHtml"), getYear(v)); for(Map<String, Object> values : getSpeakers(v)) { session.addSpeaker(toUTF8(values, "name"), toUTF8(v, "bioHtml"), (String) values.get("photoUrl")); } return session; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return session; }
private static IncogitoSession createSession(Map<String, Object> v) { IncogitoSession session = new IncogitoSession("", "", 0); try { session = new IncogitoSession(toUTF8(v, "title"), toUTF8(v, "bodyHtml"), getYear(v)); for(Map<String, Object> values : getSpeakers(v)) { session.addSpeaker(toUTF8(values, "name"), toUTF8(values, "bioHtml"), (String) values.get("photoUrl")); } return session; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return session; }
diff --git a/impl/src/net/jxta/impl/endpoint/servlethttp/HttpClientMessenger.java b/impl/src/net/jxta/impl/endpoint/servlethttp/HttpClientMessenger.java index daa1f07..24a65ee 100644 --- a/impl/src/net/jxta/impl/endpoint/servlethttp/HttpClientMessenger.java +++ b/impl/src/net/jxta/impl/endpoint/servlethttp/HttpClientMessenger.java @@ -1,907 +1,909 @@ /* * Copyright (c) 2001-2007 Sun Microsystems, Inc. All rights reserved. * * The Sun Project JXTA(TM) Software License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. The end-user documentation included with the redistribution, if any, must * include the following acknowledgment: "This product includes software * developed by Sun Microsystems, Inc. for JXTA(TM) technology." * Alternately, this acknowledgment may appear in the software itself, if * and wherever such third-party acknowledgments normally appear. * * 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA" must * not be used to endorse or promote products derived from this software * without prior written permission. For written permission, please contact * Project JXTA at http://www.jxta.org. * * 5. Products derived from this software may not be called "JXTA", nor may * "JXTA" appear in their name, without prior written permission of Sun. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SUN * MICROSYSTEMS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * JXTA is a registered trademark of Sun Microsystems, Inc. in the United * States and other countries. * * Please see the license information page at : * <http://www.jxta.org/project/www/license.html> for instructions on use of * the license in source files. * * ==================================================================== * * This software consists of voluntary contributions made by many individuals * on behalf of Project JXTA. For more information on Project JXTA, please see * http://www.jxta.org. * * This license is based on the BSD license adopted by the Apache Foundation. */ package net.jxta.impl.endpoint.servlethttp; import net.jxta.document.MimeMediaType; import net.jxta.endpoint.EndpointAddress; import net.jxta.endpoint.Message; import net.jxta.endpoint.MessageElement; import net.jxta.endpoint.StringMessageElement; import net.jxta.endpoint.WireFormatMessage; import net.jxta.endpoint.WireFormatMessageFactory; import net.jxta.impl.endpoint.BlockingMessenger; import net.jxta.impl.endpoint.EndpointServiceImpl; import net.jxta.impl.endpoint.transportMeter.TransportBindingMeter; import net.jxta.impl.endpoint.transportMeter.TransportMeterBuildSettings; import net.jxta.impl.util.TimeUtils; import net.jxta.logging.Logging; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.SocketTimeoutException; import java.net.URL; import java.util.logging.Level; import java.util.logging.Logger; /** * Simple messenger that simply posts a message to a URL. * * <p/>URL/HttpURLConnection is used, so (depending on your JDK) you will get * reasonably good persistent connection management. */ final class HttpClientMessenger extends BlockingMessenger { /** * Logger. */ private final static transient Logger LOG = Logger.getLogger(HttpClientMessenger.class.getName()); /** * Minimum amount of time between poll */ private final static int MIMIMUM_POLL_INTERVAL = (int) (5 * TimeUtils.ASECOND); /** * Amount of time to wait for connections to open. */ private final static int CONNECT_TIMEOUT = (int) (15 * TimeUtils.ASECOND); /** * Amount of time we are willing to wait for responses. This is the amount * of time between our finishing sending a message or beginning a poll and * the beginning of receipt of a response. */ private final static int RESPONSE_TIMEOUT = (int) (2 * TimeUtils.AMINUTE); /** * Amount of time we are willing to accept for additional responses. This * is the total amount of time we are willing to wait after receiving an * initial response message whether additional responses are sent or not. * This setting governs the latency with which we switch back and forth * between sending and receiving messages. */ private final static int EXTRA_RESPONSE_TIMEOUT = (int) (2 * TimeUtils.AMINUTE); /** * Messenger idle timeout. */ private final static long MESSENGER_IDLE_TIMEOUT = 15 * TimeUtils.AMINUTE; /** * Number of attempts we will attempt to make connections. */ private final static int CONNECT_RETRIES = 2; /** * Warn only once about obsolete proxies. */ private static boolean neverWarned = true; /** * The URL we send messages to. */ private final URL senderURL; /** * The ServletHttpTransport that created this object. */ private final ServletHttpTransport servletHttpTransport; /** * The Return Address element we will add to all messages we send. */ private final MessageElement srcAddressElement; /** * The logical destination address of this messenger. */ private final EndpointAddress logicalDest; private TransportBindingMeter transportBindingMeter; /** * The last time at which we successfully received or sent a message. */ private transient long lastUsed = TimeUtils.timeNow(); /** * Poller that we use to get our messages. */ private MessagePoller poller = null; /** * Constructs the messenger. * * @param servletHttpTransport The transport this messenger will work for. * @param srcAddr The source address. * @param destAddr The destination address. */ HttpClientMessenger(ServletHttpTransport servletHttpTransport, EndpointAddress srcAddr, EndpointAddress destAddr) throws IOException { // We do use self destruction. super(servletHttpTransport.getEndpointService().getGroup().getPeerGroupID(), destAddr, true); this.servletHttpTransport = servletHttpTransport; EndpointAddress srcAddress = srcAddr; this.srcAddressElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NAME, srcAddr.toString(), null); String protoAddr = destAddr.getProtocolAddress(); String host; int port; int lastColon = protoAddr.lastIndexOf(':'); if ((-1 == lastColon) || (lastColon < protoAddr.lastIndexOf(']')) || ((lastColon + 1) == protoAddr.length())) { // There's no port or it's an IPv6 addr with no port or the colon is the last character. host = protoAddr; port = 80; } else { host = protoAddr.substring(0, lastColon); port = Integer.parseInt(protoAddr.substring(lastColon + 1)); } senderURL = new URL("http", host, port, "/"); logicalDest = retreiveLogicalDestinationAddress(); // Start receiving messages from the other peer poller = new MessagePoller(srcAddr.getProtocolAddress(), destAddr); if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { LOG.info("New messenger : " + this ); } } /* * The cost of just having a finalize routine is high. The finalizer is * a bottleneck and can delay garbage collection all the way to heap * exhaustion. Leave this comment as a reminder to future maintainers. * Below is the reason why finalize is not needed here. * * These messengers (normally) never go to the application layer. Endpoint * code does call close when necessary. protected void finalize() { } */ /** * {@inheritDoc} * <p/> * A simple implementation for debugging. <b>Do not parse the String * returned. All of the information is available in other (simpler) ways.</b> */ public String toString() { StringBuilder result = new StringBuilder(super.toString()); result.append(" {"); result.append(getDestinationAddress()); result.append(" / "); result.append(getLogicalDestinationAddress()); result.append("}"); return result.toString(); } /** * {@inheritDoc} */ @Override public synchronized void closeImpl() { if (isClosed()) { return; } super.close(); if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Close messenger to " + senderURL); } MessagePoller stopPoller = poller; poller = null; if (null != stopPoller) { stopPoller.stop(); } } /** * {@inheritDoc} */ @Override public void sendMessageBImpl(Message message, String service, String serviceParam) throws IOException { if (isClosed()) { IOException failure = new IOException("Messenger was closed, it cannot be used to send messages."); if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.log(Level.WARNING, "Messenger was closed, it cannot be used to send messages.", failure); } throw failure; } // clone the message before modifying it. message = message.clone(); // Set the message with the appropriate src and dest address message.replaceMessageElement(EndpointServiceImpl.MESSAGE_SOURCE_NS, srcAddressElement); EndpointAddress destAddressToUse = getDestAddressToUse(service, serviceParam); MessageElement dstAddressElement = new StringMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NAME, destAddressToUse.toString(), null); message.replaceMessageElement(EndpointServiceImpl.MESSAGE_DESTINATION_NS, dstAddressElement); try { doSend(message); } catch (IOException e) { // close this messenger close(); // rethrow the exception throw e; } } /** * {@inheritDoc} */ @Override public EndpointAddress getLogicalDestinationImpl() { return logicalDest; } /** * {@inheritDoc} */ @Override public boolean isIdleImpl() { return isClosed() || (TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), lastUsed) > MESSENGER_IDLE_TIMEOUT); } /** * Connects to the http server and retrieves the Logical Destination Address */ private EndpointAddress retreiveLogicalDestinationAddress() throws IOException { long beginConnectTime = 0; long connectTime = 0; if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Ping (" + senderURL + ")"); } if (TransportMeterBuildSettings.TRANSPORT_METERING) { beginConnectTime = TimeUtils.timeNow(); } // open a connection to the other end HttpURLConnection urlConn = (HttpURLConnection) senderURL.openConnection(); urlConn.setRequestMethod("GET"); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setAllowUserInteraction(false); urlConn.setUseCaches(false); urlConn.setConnectTimeout(CONNECT_TIMEOUT); urlConn.setReadTimeout(CONNECT_TIMEOUT); try { // this is where the connection is actually made, if not already // connected. If we can't connect, assume it is dead int code = urlConn.getResponseCode(); if (code != HttpURLConnection.HTTP_OK) { if (TransportMeterBuildSettings.TRANSPORT_METERING) { transportBindingMeter = servletHttpTransport.getTransportBindingMeter(null, getDestinationAddress()); if (transportBindingMeter != null) { transportBindingMeter.connectionFailed(true, TimeUtils.timeNow() - beginConnectTime); } } throw new IOException("Message not accepted: HTTP status " + "code=" + code + " reason=" + urlConn.getResponseMessage()); } // check for a returned peerId int msglength = urlConn.getContentLength(); if (msglength <= 0) { throw new IOException("Ping response was empty."); } InputStream inputStream = urlConn.getInputStream(); // read the peerId byte[] uniqueIdBytes = new byte[msglength]; int bytesRead = 0; while (bytesRead < msglength) { int thisRead = inputStream.read(uniqueIdBytes, bytesRead, msglength - bytesRead); if (thisRead < 0) { break; } bytesRead += thisRead; } if (bytesRead < msglength) { throw new IOException("Content ended before promised Content length"); } String uniqueIdString; try { uniqueIdString = new String(uniqueIdBytes, "UTF-8"); } catch (UnsupportedEncodingException never) { // utf-8 is always available, but we handle it anyway. uniqueIdString = new String(uniqueIdBytes); } if (TransportMeterBuildSettings.TRANSPORT_METERING) { connectTime = TimeUtils.timeNow(); transportBindingMeter = servletHttpTransport.getTransportBindingMeter(uniqueIdString, getDestinationAddress()); if (transportBindingMeter != null) { transportBindingMeter.connectionEstablished(true, connectTime - beginConnectTime); transportBindingMeter.ping(connectTime); transportBindingMeter.connectionClosed(true, connectTime - beginConnectTime); } } EndpointAddress remoteAddress = new EndpointAddress("jxta", uniqueIdString.trim(), null, null); if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Ping (" + senderURL + ") -> " + remoteAddress); } return remoteAddress; } catch (IOException failure) { if (TransportMeterBuildSettings.TRANSPORT_METERING) { connectTime = TimeUtils.timeNow(); transportBindingMeter = servletHttpTransport.getTransportBindingMeter(null, getDestinationAddress()); if (transportBindingMeter != null) { transportBindingMeter.connectionFailed(true, connectTime - beginConnectTime); } } if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.warning("Ping (" + senderURL + ") -> failed"); } throw failure; } } /** * Connects to the http server and POSTs the message */ private void doSend(Message msg) throws IOException { long beginConnectTime = 0; long connectTime = 0; if (TransportMeterBuildSettings.TRANSPORT_METERING) { beginConnectTime = TimeUtils.timeNow(); } WireFormatMessage serialed = WireFormatMessageFactory.toWire(msg, EndpointServiceImpl.DEFAULT_MESSAGE_TYPE, null); for (int connectAttempt = 1; connectAttempt <= CONNECT_RETRIES; connectAttempt++) { if (connectAttempt > 1) { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Retrying connection to " + senderURL); } } // open a connection to the other end HttpURLConnection urlConn = (HttpURLConnection) senderURL.openConnection(); try { urlConn.setRequestMethod("POST"); urlConn.setDoOutput(true); urlConn.setDoInput(true); urlConn.setAllowUserInteraction(false); urlConn.setUseCaches(false); urlConn.setConnectTimeout(CONNECT_TIMEOUT); urlConn.setReadTimeout(CONNECT_TIMEOUT); // FIXME 20040907 bondolo Should set message encoding http header. urlConn.setRequestProperty("content-length", Long.toString(serialed.getByteLength())); urlConn.setRequestProperty("content-type", serialed.getMimeType().toString()); // send the message OutputStream out = urlConn.getOutputStream(); if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { connectTime = TimeUtils.timeNow(); transportBindingMeter.connectionEstablished(true, connectTime - beginConnectTime); } serialed.sendToStream(out); out.flush(); int responseCode; try { responseCode = urlConn.getResponseCode(); } catch (SocketTimeoutException expired) { // maybe a retry will help. continue; } catch (IOException ioe) { // Could not connect. This seems to happen a lot with a loaded HTTP 1.0 // proxy. Apparently, HttpUrlConnection can be fooled by the proxy // in believing that the connection is still open and thus breaks // when attempting to make a second transaction. We should not have to but it // seems that it befalls us to retry. if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("HTTP 1.0 proxy seems in use"); } // maybe a retry will help. continue; } // NOTE: If the proxy closed the connection 1.0 style without returning // a status line, we do not get an exception: we get a -1 response code. // Apparently, proxies no-longer do that anymore. Just in case, we issue a // warning and treat it as OK.71 if (responseCode == -1) { if (neverWarned && Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.warning("Obsolete HTTP proxy does not issue HTTP_OK response. Assuming OK"); neverWarned = false; } responseCode = HttpURLConnection.HTTP_OK; } if (responseCode != HttpURLConnection.HTTP_OK) { if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.dataSent(true, serialed.getByteLength()); transportBindingMeter.connectionDropped(true, TimeUtils.timeNow() - beginConnectTime); } throw new IOException( "Message not accepted: HTTP status " + "code=" + responseCode + " reason=" + urlConn.getResponseMessage()); } if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { long messageSentTime = TimeUtils.timeNow(); transportBindingMeter.messageSent(true, msg, messageSentTime - connectTime, serialed.getByteLength()); transportBindingMeter.connectionClosed(true, messageSentTime - beginConnectTime); } // note that we successfully sent a message lastUsed = TimeUtils.timeNow(); return; } finally { // This does prevent the creation of an infinite number of connections // if we happen to be going through a 1.0-only proxy or connect to a server // that still does not set content length to zero for the response. With this, at // least we close them (they eventualy close anyway because the other side closes // them but it takes too much time). If content-length is set, then jdk ignores // the disconnect AND reuses the connection, which is what we want. urlConn.disconnect(); } } throw new IOException("Failed sending " + msg + " to " + senderURL); } /** * Polls for messages sent to us. */ private class MessagePoller implements Runnable { /** * If <tt>true</tt> then this poller is stopped or stopping. */ private volatile boolean stopped = false; /** * The thread that does the work. */ private Thread pollerThread; /** * The URL we poll for messages. */ private final URL pollingURL; MessagePoller(String pollAddress, EndpointAddress destAddr) { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("new MessagePoller for " + senderURL); } /* * query string is of the format ?{response timeout},{extra response timeout},{dest address} * * The timeout's are expressed in milliseconds. -1 means do not wait * at all, 0 means wait forever. */ try { pollingURL = new URL(senderURL, "/" + pollAddress + "?" + Integer.toString(RESPONSE_TIMEOUT) + "," + Integer.toString(EXTRA_RESPONSE_TIMEOUT) + "," + destAddr); } catch (MalformedURLException badAddr) { IllegalArgumentException failure = new IllegalArgumentException("Could not construct polling URL"); failure.initCause(badAddr); throw failure; } pollerThread = new Thread(this, "HttpClientMessenger poller for " + senderURL); pollerThread.setDaemon(true); pollerThread.start(); } protected void stop() { if (stopped) { return; } if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { LOG.info("Stop polling for " + senderURL); } stopped = true; // Here, we are forced to abandon this object open. Because we could // get blocked forever trying to close it. It will rot away after // the current read returns. The best we can do is interrupt the // thread; unlikely to have an effect per the current. // HttpURLConnection implementation. Thread stopPoller = pollerThread; if (null != stopPoller) { stopPoller.interrupt(); } } /** * Returns {@code true} if this messenger is stopped otherwise * {@code false}. * * @return returns {@code true} if this messenger is stopped otherwise * {@code false}. */ protected boolean isStopped() { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine(this + " " + senderURL + " --> " + (stopped ? "stopped" : "running")); } return stopped; } /** * {@inheritDoc} * * <p/>Connects to the http server and waits for messages to be received and processes them. */ public void run() { try { long beginConnectTime = 0; long connectTime = 0; long noReconnectBefore = 0; HttpURLConnection conn = null; if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { LOG.info("Message polling beings for " + pollingURL); } int connectAttempt = 1; // get messages until the messenger is closed while (!isStopped()) { if (conn == null) { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Opening new connection to " + pollingURL); } conn = (HttpURLConnection) pollingURL.openConnection(); // Incomming data channel conn.setRequestMethod("GET"); conn.setDoOutput(false); conn.setDoInput(true); conn.setAllowUserInteraction(false); conn.setUseCaches(false); conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(RESPONSE_TIMEOUT); if (TransportMeterBuildSettings.TRANSPORT_METERING) { beginConnectTime = TimeUtils.timeNow(); } // Loop back and try again to connect continue; } long untilNextConnect = TimeUtils.toRelativeTimeMillis(noReconnectBefore); try { if (untilNextConnect > 0) { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Delaying for " + untilNextConnect + "ms before reconnect to " + senderURL); } Thread.sleep(untilNextConnect); } } catch (InterruptedException woken) { Thread.interrupted(); continue; } InputStream inputStream; MimeMediaType messageType; try { if (connectAttempt > 1) { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Reconnect attempt for " + senderURL); } } // Always connect (no cost if connected). conn.connect(); if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Waiting for response code from " + senderURL); } int responseCode = conn.getResponseCode(); if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { LOG.finer( "Response " + responseCode + " for Connection : " + senderURL + "\n\tContent-Type : " + conn.getHeaderField("Content-Type") + "\tContent-Length : " + conn.getHeaderField("Content-Length") + "\tTransfer-Encoding : " + conn.getHeaderField("Transfer-Encoding")); } connectTime = TimeUtils.timeNow(); noReconnectBefore = TimeUtils.toAbsoluteTimeMillis(MIMIMUM_POLL_INTERVAL, connectTime); - if (0 == conn.getContentLength()) { - continue; - } + if (0 == conn.getContentLength()) { + conn.disconnect(); + conn = null; + continue; + } if (HttpURLConnection.HTTP_NO_CONTENT == responseCode) { // the connection timed out. if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionClosed(true, TimeUtils.toRelativeTimeMillis(beginConnectTime, connectTime)); } conn = null; continue; } if (responseCode != HttpURLConnection.HTTP_OK) { if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionClosed(true, TimeUtils.timeNow() - beginConnectTime); } throw new IOException("HTTP Failure: " + conn.getResponseCode() + " : " + conn.getResponseMessage()); } String contentType = conn.getHeaderField("Content-Type"); if (null == contentType) { // XXX 20051219 bondolo Figure out why the mime type is not always set. messageType = EndpointServiceImpl.DEFAULT_MESSAGE_TYPE; } else { messageType = MimeMediaType.valueOf(contentType); } // FIXME 20040907 bondolo Should get message content-encoding from http header. inputStream = conn.getInputStream(); // reset connection attempt. connectAttempt = 1; } catch (InterruptedIOException broken) { // We don't know where it was interrupted. Restart connection. Thread.interrupted(); if (connectAttempt > CONNECT_RETRIES) { if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.warning("Unable to connect to " + senderURL); } stop(); break; } else { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Failed connecting to " + senderURL); } if (null != conn) { conn.disconnect(); } conn = null; connectAttempt++; continue; } } catch (IOException ioe) { if (connectAttempt > CONNECT_RETRIES) { if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.log(Level.WARNING, "Unable to connect to " + senderURL, ioe); } stop(); break; } else { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Failed connecting to " + senderURL); } if (null != conn) { conn.disconnect(); } conn = null; connectAttempt++; continue; } } // start receiving messages try { while (!isStopped() && (TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), connectTime) < RESPONSE_TIMEOUT)) { // read a message! long messageReceiveStart = TimeUtils.timeNow(); Message incomingMsg; incomingMsg = WireFormatMessageFactory.fromWire(inputStream, messageType, null); if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.messageReceived(true, incomingMsg, incomingMsg.getByteLength(), TimeUtils.timeNow() - messageReceiveStart); } if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Received " + incomingMsg + " from " + senderURL); } servletHttpTransport.executor.execute(new MessageProcessor(incomingMsg)); // note that we received a message lastUsed = TimeUtils.timeNow(); } if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionClosed(true, TimeUtils.timeNow() - beginConnectTime); } } catch (EOFException e) { // Connection ran out of messages. let it go. conn = null; } catch (InterruptedIOException broken) { if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionDropped(true, TimeUtils.timeNow() - beginConnectTime); } // We don't know where it was interrupted. Restart connection. Thread.interrupted(); if (null != conn) { conn.disconnect(); } conn = null; } catch (IOException e) { if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionDropped(true, TimeUtils.timeNow() - beginConnectTime); } // If we managed to get down here, it is really an error. // However, being disconnected from the server, for // whatever reason, is a common place event. No need to // clutter the screen with scary messages. When the // message layer believes it's serious, it prints the // scary message already. if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Failed to read message from " + senderURL, e); } // Time to call this connection dead. stop(); break; } finally { try { inputStream.close(); } catch (IOException ignored) { //ignored } } } } catch (Throwable argh) { if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { LOG.log(Level.SEVERE, "Poller exiting because of uncaught exception", argh); } stop(); } finally { pollerThread = null; } if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { LOG.info("Message polling stopped for " + senderURL); } } } /** * A small class for processing individual messages. */ private class MessageProcessor implements Runnable { private Message msg; MessageProcessor(Message msg) { this.msg = msg; } public void run() { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Demuxing " + msg + " from " + senderURL); } servletHttpTransport.getEndpointService().demux(msg); } } }
true
true
public void run() { try { long beginConnectTime = 0; long connectTime = 0; long noReconnectBefore = 0; HttpURLConnection conn = null; if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { LOG.info("Message polling beings for " + pollingURL); } int connectAttempt = 1; // get messages until the messenger is closed while (!isStopped()) { if (conn == null) { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Opening new connection to " + pollingURL); } conn = (HttpURLConnection) pollingURL.openConnection(); // Incomming data channel conn.setRequestMethod("GET"); conn.setDoOutput(false); conn.setDoInput(true); conn.setAllowUserInteraction(false); conn.setUseCaches(false); conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(RESPONSE_TIMEOUT); if (TransportMeterBuildSettings.TRANSPORT_METERING) { beginConnectTime = TimeUtils.timeNow(); } // Loop back and try again to connect continue; } long untilNextConnect = TimeUtils.toRelativeTimeMillis(noReconnectBefore); try { if (untilNextConnect > 0) { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Delaying for " + untilNextConnect + "ms before reconnect to " + senderURL); } Thread.sleep(untilNextConnect); } } catch (InterruptedException woken) { Thread.interrupted(); continue; } InputStream inputStream; MimeMediaType messageType; try { if (connectAttempt > 1) { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Reconnect attempt for " + senderURL); } } // Always connect (no cost if connected). conn.connect(); if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Waiting for response code from " + senderURL); } int responseCode = conn.getResponseCode(); if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { LOG.finer( "Response " + responseCode + " for Connection : " + senderURL + "\n\tContent-Type : " + conn.getHeaderField("Content-Type") + "\tContent-Length : " + conn.getHeaderField("Content-Length") + "\tTransfer-Encoding : " + conn.getHeaderField("Transfer-Encoding")); } connectTime = TimeUtils.timeNow(); noReconnectBefore = TimeUtils.toAbsoluteTimeMillis(MIMIMUM_POLL_INTERVAL, connectTime); if (0 == conn.getContentLength()) { continue; } if (HttpURLConnection.HTTP_NO_CONTENT == responseCode) { // the connection timed out. if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionClosed(true, TimeUtils.toRelativeTimeMillis(beginConnectTime, connectTime)); } conn = null; continue; } if (responseCode != HttpURLConnection.HTTP_OK) { if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionClosed(true, TimeUtils.timeNow() - beginConnectTime); } throw new IOException("HTTP Failure: " + conn.getResponseCode() + " : " + conn.getResponseMessage()); } String contentType = conn.getHeaderField("Content-Type"); if (null == contentType) { // XXX 20051219 bondolo Figure out why the mime type is not always set. messageType = EndpointServiceImpl.DEFAULT_MESSAGE_TYPE; } else { messageType = MimeMediaType.valueOf(contentType); } // FIXME 20040907 bondolo Should get message content-encoding from http header. inputStream = conn.getInputStream(); // reset connection attempt. connectAttempt = 1; } catch (InterruptedIOException broken) { // We don't know where it was interrupted. Restart connection. Thread.interrupted(); if (connectAttempt > CONNECT_RETRIES) { if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.warning("Unable to connect to " + senderURL); } stop(); break; } else { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Failed connecting to " + senderURL); } if (null != conn) { conn.disconnect(); } conn = null; connectAttempt++; continue; } } catch (IOException ioe) { if (connectAttempt > CONNECT_RETRIES) { if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.log(Level.WARNING, "Unable to connect to " + senderURL, ioe); } stop(); break; } else { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Failed connecting to " + senderURL); } if (null != conn) { conn.disconnect(); } conn = null; connectAttempt++; continue; } } // start receiving messages try { while (!isStopped() && (TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), connectTime) < RESPONSE_TIMEOUT)) { // read a message! long messageReceiveStart = TimeUtils.timeNow(); Message incomingMsg; incomingMsg = WireFormatMessageFactory.fromWire(inputStream, messageType, null); if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.messageReceived(true, incomingMsg, incomingMsg.getByteLength(), TimeUtils.timeNow() - messageReceiveStart); } if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Received " + incomingMsg + " from " + senderURL); } servletHttpTransport.executor.execute(new MessageProcessor(incomingMsg)); // note that we received a message lastUsed = TimeUtils.timeNow(); } if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionClosed(true, TimeUtils.timeNow() - beginConnectTime); } } catch (EOFException e) { // Connection ran out of messages. let it go. conn = null; } catch (InterruptedIOException broken) { if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionDropped(true, TimeUtils.timeNow() - beginConnectTime); } // We don't know where it was interrupted. Restart connection. Thread.interrupted(); if (null != conn) { conn.disconnect(); } conn = null; } catch (IOException e) { if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionDropped(true, TimeUtils.timeNow() - beginConnectTime); } // If we managed to get down here, it is really an error. // However, being disconnected from the server, for // whatever reason, is a common place event. No need to // clutter the screen with scary messages. When the // message layer believes it's serious, it prints the // scary message already. if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Failed to read message from " + senderURL, e); } // Time to call this connection dead. stop(); break; } finally { try { inputStream.close(); } catch (IOException ignored) { //ignored } } } } catch (Throwable argh) { if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { LOG.log(Level.SEVERE, "Poller exiting because of uncaught exception", argh); } stop(); } finally { pollerThread = null; } if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { LOG.info("Message polling stopped for " + senderURL); } }
public void run() { try { long beginConnectTime = 0; long connectTime = 0; long noReconnectBefore = 0; HttpURLConnection conn = null; if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { LOG.info("Message polling beings for " + pollingURL); } int connectAttempt = 1; // get messages until the messenger is closed while (!isStopped()) { if (conn == null) { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Opening new connection to " + pollingURL); } conn = (HttpURLConnection) pollingURL.openConnection(); // Incomming data channel conn.setRequestMethod("GET"); conn.setDoOutput(false); conn.setDoInput(true); conn.setAllowUserInteraction(false); conn.setUseCaches(false); conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(RESPONSE_TIMEOUT); if (TransportMeterBuildSettings.TRANSPORT_METERING) { beginConnectTime = TimeUtils.timeNow(); } // Loop back and try again to connect continue; } long untilNextConnect = TimeUtils.toRelativeTimeMillis(noReconnectBefore); try { if (untilNextConnect > 0) { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Delaying for " + untilNextConnect + "ms before reconnect to " + senderURL); } Thread.sleep(untilNextConnect); } } catch (InterruptedException woken) { Thread.interrupted(); continue; } InputStream inputStream; MimeMediaType messageType; try { if (connectAttempt > 1) { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Reconnect attempt for " + senderURL); } } // Always connect (no cost if connected). conn.connect(); if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Waiting for response code from " + senderURL); } int responseCode = conn.getResponseCode(); if (Logging.SHOW_FINER && LOG.isLoggable(Level.FINER)) { LOG.finer( "Response " + responseCode + " for Connection : " + senderURL + "\n\tContent-Type : " + conn.getHeaderField("Content-Type") + "\tContent-Length : " + conn.getHeaderField("Content-Length") + "\tTransfer-Encoding : " + conn.getHeaderField("Transfer-Encoding")); } connectTime = TimeUtils.timeNow(); noReconnectBefore = TimeUtils.toAbsoluteTimeMillis(MIMIMUM_POLL_INTERVAL, connectTime); if (0 == conn.getContentLength()) { conn.disconnect(); conn = null; continue; } if (HttpURLConnection.HTTP_NO_CONTENT == responseCode) { // the connection timed out. if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionClosed(true, TimeUtils.toRelativeTimeMillis(beginConnectTime, connectTime)); } conn = null; continue; } if (responseCode != HttpURLConnection.HTTP_OK) { if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionClosed(true, TimeUtils.timeNow() - beginConnectTime); } throw new IOException("HTTP Failure: " + conn.getResponseCode() + " : " + conn.getResponseMessage()); } String contentType = conn.getHeaderField("Content-Type"); if (null == contentType) { // XXX 20051219 bondolo Figure out why the mime type is not always set. messageType = EndpointServiceImpl.DEFAULT_MESSAGE_TYPE; } else { messageType = MimeMediaType.valueOf(contentType); } // FIXME 20040907 bondolo Should get message content-encoding from http header. inputStream = conn.getInputStream(); // reset connection attempt. connectAttempt = 1; } catch (InterruptedIOException broken) { // We don't know where it was interrupted. Restart connection. Thread.interrupted(); if (connectAttempt > CONNECT_RETRIES) { if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.warning("Unable to connect to " + senderURL); } stop(); break; } else { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Failed connecting to " + senderURL); } if (null != conn) { conn.disconnect(); } conn = null; connectAttempt++; continue; } } catch (IOException ioe) { if (connectAttempt > CONNECT_RETRIES) { if (Logging.SHOW_WARNING && LOG.isLoggable(Level.WARNING)) { LOG.log(Level.WARNING, "Unable to connect to " + senderURL, ioe); } stop(); break; } else { if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Failed connecting to " + senderURL); } if (null != conn) { conn.disconnect(); } conn = null; connectAttempt++; continue; } } // start receiving messages try { while (!isStopped() && (TimeUtils.toRelativeTimeMillis(TimeUtils.timeNow(), connectTime) < RESPONSE_TIMEOUT)) { // read a message! long messageReceiveStart = TimeUtils.timeNow(); Message incomingMsg; incomingMsg = WireFormatMessageFactory.fromWire(inputStream, messageType, null); if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.messageReceived(true, incomingMsg, incomingMsg.getByteLength(), TimeUtils.timeNow() - messageReceiveStart); } if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.fine("Received " + incomingMsg + " from " + senderURL); } servletHttpTransport.executor.execute(new MessageProcessor(incomingMsg)); // note that we received a message lastUsed = TimeUtils.timeNow(); } if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionClosed(true, TimeUtils.timeNow() - beginConnectTime); } } catch (EOFException e) { // Connection ran out of messages. let it go. conn = null; } catch (InterruptedIOException broken) { if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionDropped(true, TimeUtils.timeNow() - beginConnectTime); } // We don't know where it was interrupted. Restart connection. Thread.interrupted(); if (null != conn) { conn.disconnect(); } conn = null; } catch (IOException e) { if (TransportMeterBuildSettings.TRANSPORT_METERING && (transportBindingMeter != null)) { transportBindingMeter.connectionDropped(true, TimeUtils.timeNow() - beginConnectTime); } // If we managed to get down here, it is really an error. // However, being disconnected from the server, for // whatever reason, is a common place event. No need to // clutter the screen with scary messages. When the // message layer believes it's serious, it prints the // scary message already. if (Logging.SHOW_FINE && LOG.isLoggable(Level.FINE)) { LOG.log(Level.FINE, "Failed to read message from " + senderURL, e); } // Time to call this connection dead. stop(); break; } finally { try { inputStream.close(); } catch (IOException ignored) { //ignored } } } } catch (Throwable argh) { if (Logging.SHOW_SEVERE && LOG.isLoggable(Level.SEVERE)) { LOG.log(Level.SEVERE, "Poller exiting because of uncaught exception", argh); } stop(); } finally { pollerThread = null; } if (Logging.SHOW_INFO && LOG.isLoggable(Level.INFO)) { LOG.info("Message polling stopped for " + senderURL); } }
diff --git a/webapp/app/controllers/modules2/SplinesV1PullProcessor.java b/webapp/app/controllers/modules2/SplinesV1PullProcessor.java index 0df7cece..74a71f47 100644 --- a/webapp/app/controllers/modules2/SplinesV1PullProcessor.java +++ b/webapp/app/controllers/modules2/SplinesV1PullProcessor.java @@ -1,17 +1,19 @@ package controllers.modules2; public class SplinesV1PullProcessor extends SplinesPullProcessor { @Override protected int getNumParams() { return 2; } protected long calculateOffset() { Long startTime = params.getStart(); + if(startTime == null) + return 0; long offset = startTime % interval; return offset; } }
true
true
protected long calculateOffset() { Long startTime = params.getStart(); long offset = startTime % interval; return offset; }
protected long calculateOffset() { Long startTime = params.getStart(); if(startTime == null) return 0; long offset = startTime % interval; return offset; }
diff --git a/branches/andpet/GeoBeagle/src/com/google/code/geobeagle/activity/cachelist/presenter/CacheListAdapter.java b/branches/andpet/GeoBeagle/src/com/google/code/geobeagle/activity/cachelist/presenter/CacheListAdapter.java index 5334028f..bf3228f8 100644 --- a/branches/andpet/GeoBeagle/src/com/google/code/geobeagle/activity/cachelist/presenter/CacheListAdapter.java +++ b/branches/andpet/GeoBeagle/src/com/google/code/geobeagle/activity/cachelist/presenter/CacheListAdapter.java @@ -1,93 +1,94 @@ package com.google.code.geobeagle.activity.cachelist.presenter; import com.google.code.geobeagle.Geocache; import com.google.code.geobeagle.GeocacheList; import com.google.code.geobeagle.Refresher; import com.google.code.geobeagle.database.CachesProviderToggler; import com.google.code.geobeagle.database.DistanceAndBearing; import com.google.code.geobeagle.database.DistanceAndBearing.IDistanceAndBearingProvider; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; /** Feeds the caches in a CachesProvider to the GUI list view */ public class CacheListAdapter extends BaseAdapter implements Refresher { private final CachesProviderToggler mProvider; private final IDistanceAndBearingProvider mDistances; private final GeocacheSummaryRowInflater mGeocacheSummaryRowInflater; private final TitleUpdater mTitleUpdater; private GeocacheList mListData; private float mAzimuth; private boolean mUpdatesEnabled = true; public CacheListAdapter(CachesProviderToggler provider, IDistanceAndBearingProvider distances, GeocacheSummaryRowInflater inflater, - TitleUpdater titleUpdater) { + TitleUpdater titleUpdater, GeocacheList listData) { mProvider = provider; mGeocacheSummaryRowInflater = inflater; mTitleUpdater = titleUpdater; mDistances = distances; + mListData = listData; } public void enableUpdates(boolean enable) { mUpdatesEnabled = enable; refresh(); } public void setAzimuth (float azimuth) { mAzimuth = azimuth; } /** Updates the GUI from the Provider if necessary */ @Override public void refresh() { if (!mUpdatesEnabled || !mProvider.hasChanged()) { return; } forceRefresh(); } public void forceRefresh() { //TODO: Take this back? //mProvider.resetChanged(); mListData = mProvider.getCaches(); mTitleUpdater.refresh(); notifyDataSetChanged(); } public int getCount() { if (mListData == null) return 0; return mListData.size(); } public Object getItem(int position) { return position; } public long getItemId(int position) { return position; } /** Get the geocache for a certain row in the displayed list, starting with zero */ public Geocache getGeocacheAt(int position) { if (mListData == null) return null; Geocache cache = mListData.get(position); return cache; } public View getView(int position, View convertView, ViewGroup parent) { if (mListData == null) return null; //What happens in this case? View view = mGeocacheSummaryRowInflater.inflate(convertView); Geocache cache = mListData.get(position); DistanceAndBearing geocacheVector = mDistances.getDistanceAndBearing(cache); mGeocacheSummaryRowInflater.setData(view, geocacheVector, mAzimuth); return view; } }
false
true
public CacheListAdapter(CachesProviderToggler provider, IDistanceAndBearingProvider distances, GeocacheSummaryRowInflater inflater, TitleUpdater titleUpdater) { mProvider = provider; mGeocacheSummaryRowInflater = inflater; mTitleUpdater = titleUpdater; mDistances = distances; }
public CacheListAdapter(CachesProviderToggler provider, IDistanceAndBearingProvider distances, GeocacheSummaryRowInflater inflater, TitleUpdater titleUpdater, GeocacheList listData) { mProvider = provider; mGeocacheSummaryRowInflater = inflater; mTitleUpdater = titleUpdater; mDistances = distances; mListData = listData; }
diff --git a/component/identity/src/main/java/org/exoplatform/services/organization/idm/UserProfileDAOImpl.java b/component/identity/src/main/java/org/exoplatform/services/organization/idm/UserProfileDAOImpl.java index 5ca9fa951..2efad72b7 100644 --- a/component/identity/src/main/java/org/exoplatform/services/organization/idm/UserProfileDAOImpl.java +++ b/component/identity/src/main/java/org/exoplatform/services/organization/idm/UserProfileDAOImpl.java @@ -1,330 +1,338 @@ /** * Copyright (C) 2009 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.exoplatform.services.organization.idm; import org.exoplatform.services.cache.CacheService; import org.exoplatform.services.cache.ExoCache; import org.exoplatform.services.organization.UserProfile; import org.exoplatform.services.organization.UserProfileEventListener; import org.exoplatform.services.organization.UserProfileHandler; import org.exoplatform.services.organization.impl.UserProfileImpl; import org.picketlink.idm.api.Attribute; import org.picketlink.idm.api.IdentitySession; import org.picketlink.idm.impl.api.SimpleAttribute; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /* * @author <a href="mailto:boleslaw.dawidowicz at redhat.com">Boleslaw Dawidowicz</a> */ public class UserProfileDAOImpl implements UserProfileHandler { private static Logger log = LoggerFactory.getLogger(UserProfileDAOImpl.class); static private UserProfile NOT_FOUND = new UserProfileImpl(); private PicketLinkIDMService service_; private List<UserProfileEventListener> listeners_; private PicketLinkIDMOrganizationServiceImpl orgService; public UserProfileDAOImpl(PicketLinkIDMOrganizationServiceImpl orgService, PicketLinkIDMService service) throws Exception { service_ = service; listeners_ = new ArrayList<UserProfileEventListener>(3); this.orgService = orgService; } public void addUserProfileEventListener(UserProfileEventListener listener) { listeners_.add(listener); } final public UserProfile createUserProfileInstance() { return new UserProfileImpl(); } public UserProfile createUserProfileInstance(String userName) { return new UserProfileImpl(userName); } // void createUserProfileEntry(UserProfile up, IdentitySession session) throws Exception // { // UserProfileData upd = new UserProfileData(); // upd.setUserProfile(up); // session.save(upd); // session.flush(); // cache_.remove(up.getUserName()); // } public void saveUserProfile(UserProfile profile, boolean broadcast) throws Exception { if (broadcast) { preSave(profile, true); } setProfile(profile.getUserName(), profile); if (broadcast) { postSave(profile, true); } } public UserProfile removeUserProfile(String userName, boolean broadcast) throws Exception { UserProfile profile = getProfile(userName); if (profile != null) { try { if (broadcast) { preDelete(profile); } removeProfile(userName, profile); if (broadcast) { postDelete(profile); } return profile; } catch (Exception exp) { return null; } } return null; } public UserProfile findUserProfileByName(String userName) throws Exception { org.picketlink.idm.api.User foundUser = null; try { foundUser = getIdentitySession().getPersistenceManager().findUser(userName); } catch (Exception e) { //TODO: log.info("Identity operation error: ", e); } if (foundUser == null) { return null; } UserProfile up = getProfile(userName); // if (up == null) { up = NOT_FOUND; } // Just to avoid to return a shared object between many threads // that would not be thread safe nor corrct if (up == NOT_FOUND) { // julien : integration bug fix // Return an empty profile to avoid NPE in portal // Should clarify what do do (maybe portal should care about returned value) UserProfileImpl profile = new UserProfileImpl(); profile.setUserName(userName); return profile; } else { return up; } } public Collection findUserProfiles() throws Exception { return null; } private void preSave(UserProfile profile, boolean isNew) throws Exception { for (UserProfileEventListener listener : listeners_) { listener.preSave(profile, isNew); } } private void postSave(UserProfile profile, boolean isNew) throws Exception { for (UserProfileEventListener listener : listeners_) { listener.postSave(profile, isNew); } } private void preDelete(UserProfile profile) throws Exception { for (UserProfileEventListener listener : listeners_) { listener.preDelete(profile); } } private void postDelete(UserProfile profile) throws Exception { for (UserProfileEventListener listener : listeners_) { listener.postDelete(profile); } } public UserProfile getProfile(String userName) throws Exception { Object u = null; try { u = getIdentitySession().getPersistenceManager().findUser(userName); } catch (Exception e) { //TODO: log.info("Identity operation error: ", e); } if (u == null) { return null; } Map<String, Attribute> attrs = new HashMap(); try { attrs = getIdentitySession().getAttributesManager().getAttributes(userName); } catch (Exception e) { //TODO: log.info("Identity operation error: ", e); } if (attrs == null || attrs.isEmpty()) { return null; } Map<String, String> filteredAttrs = new HashMap<String, String>(); for (String key : attrs.keySet()) { // Check if attribute is part of User interface data if (!UserDAOImpl.USER_NON_PROFILE_KEYS.contains(key)) { - filteredAttrs.put(key, attrs.get(key).getValue().toString()); + Object value = attrs.get(key).getValue(); + if (value != null) + { + filteredAttrs.put(key, value.toString()); + } + else + { + filteredAttrs.put(key, null); + } } } if (filteredAttrs.isEmpty()) { return null; } UserProfile profile = new UserProfileImpl(userName, filteredAttrs); return profile; } public void setProfile(String userName, UserProfile profile) throws Exception { Map<String, String> profileAttrs = profile.getUserInfoMap(); Set<Attribute> attrs = new HashSet<Attribute>(); for (Map.Entry<String, String> entry : profileAttrs.entrySet()) { attrs.add(new SimpleAttribute(entry.getKey(), entry.getValue())); } Attribute[] attrArray = new Attribute[attrs.size()]; attrArray = attrs.toArray(attrArray); try { getIdentitySession().getAttributesManager().updateAttributes(userName, attrArray); } catch (Exception e) { //TODO: log.info("Identity operation error: ", e); } } public void removeProfile(String userName, UserProfile profile) throws Exception { Map<String, String> profileAttrs = profile.getUserInfoMap(); String[] attrKeys = new String[profileAttrs.keySet().size()]; attrKeys = profileAttrs.keySet().toArray(attrKeys); try { getIdentitySession().getAttributesManager().removeAttributes(userName, attrKeys); } catch (Exception e) { //TODO: log.info("Identity operation error: ", e); } } private IdentitySession getIdentitySession() throws Exception { return service_.getIdentitySession(); } }
true
true
public UserProfile getProfile(String userName) throws Exception { Object u = null; try { u = getIdentitySession().getPersistenceManager().findUser(userName); } catch (Exception e) { //TODO: log.info("Identity operation error: ", e); } if (u == null) { return null; } Map<String, Attribute> attrs = new HashMap(); try { attrs = getIdentitySession().getAttributesManager().getAttributes(userName); } catch (Exception e) { //TODO: log.info("Identity operation error: ", e); } if (attrs == null || attrs.isEmpty()) { return null; } Map<String, String> filteredAttrs = new HashMap<String, String>(); for (String key : attrs.keySet()) { // Check if attribute is part of User interface data if (!UserDAOImpl.USER_NON_PROFILE_KEYS.contains(key)) { filteredAttrs.put(key, attrs.get(key).getValue().toString()); } } if (filteredAttrs.isEmpty()) { return null; } UserProfile profile = new UserProfileImpl(userName, filteredAttrs); return profile; }
public UserProfile getProfile(String userName) throws Exception { Object u = null; try { u = getIdentitySession().getPersistenceManager().findUser(userName); } catch (Exception e) { //TODO: log.info("Identity operation error: ", e); } if (u == null) { return null; } Map<String, Attribute> attrs = new HashMap(); try { attrs = getIdentitySession().getAttributesManager().getAttributes(userName); } catch (Exception e) { //TODO: log.info("Identity operation error: ", e); } if (attrs == null || attrs.isEmpty()) { return null; } Map<String, String> filteredAttrs = new HashMap<String, String>(); for (String key : attrs.keySet()) { // Check if attribute is part of User interface data if (!UserDAOImpl.USER_NON_PROFILE_KEYS.contains(key)) { Object value = attrs.get(key).getValue(); if (value != null) { filteredAttrs.put(key, value.toString()); } else { filteredAttrs.put(key, null); } } } if (filteredAttrs.isEmpty()) { return null; } UserProfile profile = new UserProfileImpl(userName, filteredAttrs); return profile; }
diff --git a/luni/src/main/java/java/nio/HeapByteBuffer.java b/luni/src/main/java/java/nio/HeapByteBuffer.java index 211811565..a01c9d864 100644 --- a/luni/src/main/java/java/nio/HeapByteBuffer.java +++ b/luni/src/main/java/java/nio/HeapByteBuffer.java @@ -1,269 +1,269 @@ /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package java.nio; import org.apache.harmony.luni.platform.OSMemory; /** * HeapByteBuffer, ReadWriteHeapByteBuffer and ReadOnlyHeapByteBuffer compose * the implementation of array based byte buffers. * <p> * HeapByteBuffer implements all the shared readonly methods and is extended by * the other two classes. * </p> * <p> * All methods are marked final for runtime performance. * </p> * */ abstract class HeapByteBuffer extends BaseByteBuffer { protected final byte[] backingArray; protected final int offset; HeapByteBuffer(byte[] backingArray) { this(backingArray, backingArray.length, 0); } HeapByteBuffer(int capacity) { this(new byte[capacity], capacity, 0); } HeapByteBuffer(byte[] backingArray, int capacity, int offset) { super(capacity, null); this.backingArray = backingArray; this.offset = offset; if (offset + capacity > backingArray.length) { throw new IndexOutOfBoundsException(); } } @Override public final ByteBuffer get(byte[] dst, int dstOffset, int byteCount) { checkGetBounds(1, dst.length, dstOffset, byteCount); System.arraycopy(backingArray, offset + position, dst, dstOffset, byteCount); position += byteCount; return this; } final void get(char[] dst, int dstOffset, int charCount) { int byteCount = checkGetBounds(SIZEOF_CHAR, dst.length, dstOffset, charCount); OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SIZEOF_CHAR, order.needsSwap); position += byteCount; } final void get(double[] dst, int dstOffset, int doubleCount) { int byteCount = checkGetBounds(SIZEOF_DOUBLE, dst.length, dstOffset, doubleCount); OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SIZEOF_DOUBLE, order.needsSwap); position += byteCount; } final void get(float[] dst, int dstOffset, int floatCount) { int byteCount = checkGetBounds(SIZEOF_FLOAT, dst.length, dstOffset, floatCount); OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SIZEOF_FLOAT, order.needsSwap); position += byteCount; } final void get(int[] dst, int dstOffset, int intCount) { int byteCount = checkGetBounds(SIZEOF_INT, dst.length, dstOffset, intCount); OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SIZEOF_INT, order.needsSwap); position += byteCount; } final void get(long[] dst, int dstOffset, int longCount) { int byteCount = checkGetBounds(SIZEOF_LONG, dst.length, dstOffset, longCount); OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SIZEOF_LONG, order.needsSwap); position += byteCount; } final void get(short[] dst, int dstOffset, int shortCount) { int byteCount = checkGetBounds(SIZEOF_SHORT, dst.length, dstOffset, shortCount); OSMemory.unsafeBulkGet(dst, dstOffset, byteCount, backingArray, offset + position, SIZEOF_SHORT, order.needsSwap); position += byteCount; } @Override public final byte get() { if (position == limit) { throw new BufferUnderflowException(); } return backingArray[offset + position++]; } @Override public final byte get(int index) { if (index < 0 || index >= limit) { throw new IndexOutOfBoundsException(); } return backingArray[offset + index]; } @Override public final char getChar() { int newPosition = position + SIZEOF_CHAR; if (newPosition > limit) { throw new BufferUnderflowException(); } char result = (char) loadShort(position); position = newPosition; return result; } @Override public final char getChar(int index) { if (index < 0 || index + SIZEOF_CHAR > limit) { throw new IndexOutOfBoundsException(); } return (char) loadShort(index); } @Override public final double getDouble() { return Double.longBitsToDouble(getLong()); } @Override public final double getDouble(int index) { return Double.longBitsToDouble(getLong(index)); } @Override public final float getFloat() { return Float.intBitsToFloat(getInt()); } @Override public final float getFloat(int index) { return Float.intBitsToFloat(getInt(index)); } @Override public final int getInt() { int newPosition = position + SIZEOF_INT; if (newPosition > limit) { throw new BufferUnderflowException(); } int result = loadInt(position); position = newPosition; return result; } @Override public final int getInt(int index) { if (index < 0 || index + SIZEOF_INT > limit) { throw new IndexOutOfBoundsException(); } return loadInt(index); } @Override public final long getLong() { int newPosition = position + SIZEOF_LONG; if (newPosition > limit) { throw new BufferUnderflowException(); } long result = loadLong(position); position = newPosition; return result; } @Override public final long getLong(int index) { if (index < 0 || index + SIZEOF_LONG > limit) { throw new IndexOutOfBoundsException(); } return loadLong(index); } @Override public final short getShort() { int newPosition = position + SIZEOF_SHORT; if (newPosition > limit) { throw new BufferUnderflowException(); } short result = loadShort(position); position = newPosition; return result; } @Override public final short getShort(int index) { if (index < 0 || index + SIZEOF_SHORT > limit) { throw new IndexOutOfBoundsException(); } return loadShort(index); } @Override public final boolean isDirect() { return false; } private final int loadInt(int index) { int baseOffset = offset + index; if (order == ByteOrder.BIG_ENDIAN) { return (((backingArray[baseOffset++] & 0xff) << 24) | ((backingArray[baseOffset++] & 0xff) << 16) | ((backingArray[baseOffset++] & 0xff) << 8) | ((backingArray[baseOffset ] & 0xff) << 0)); } else { return (((backingArray[baseOffset++] & 0xff) << 0) | ((backingArray[baseOffset++] & 0xff) << 8) | ((backingArray[baseOffset++] & 0xff) << 16) | ((backingArray[baseOffset ] & 0xff) << 24)); } } private final long loadLong(int index) { int baseOffset = offset + index; if (order == ByteOrder.BIG_ENDIAN) { int h = ((backingArray[baseOffset++] & 0xff) << 24) | ((backingArray[baseOffset++] & 0xff) << 16) | ((backingArray[baseOffset++] & 0xff) << 8) | ((backingArray[baseOffset++] & 0xff) << 0); int l = ((backingArray[baseOffset++] & 0xff) << 24) | ((backingArray[baseOffset++] & 0xff) << 16) | ((backingArray[baseOffset++] & 0xff) << 8) | ((backingArray[baseOffset ] & 0xff) << 0); - return (((long) h) << 32) | l; + return (((long) h) << 32L) | ((long) l) & 0xffffffffL; } else { int l = ((backingArray[baseOffset++] & 0xff) << 0) | ((backingArray[baseOffset++] & 0xff) << 8) | ((backingArray[baseOffset++] & 0xff) << 16) | ((backingArray[baseOffset++] & 0xff) << 24); int h = ((backingArray[baseOffset++] & 0xff) << 0) | ((backingArray[baseOffset++] & 0xff) << 8) | ((backingArray[baseOffset++] & 0xff) << 16) | ((backingArray[baseOffset ] & 0xff) << 24); - return (((long) h) << 32) | l; + return (((long) h) << 32L) | ((long) l) & 0xffffffffL; } } private final short loadShort(int index) { int baseOffset = offset + index; if (order == ByteOrder.BIG_ENDIAN) { return (short) ((backingArray[baseOffset] << 8) | (backingArray[baseOffset + 1] & 0xff)); } else { return (short) ((backingArray[baseOffset + 1] << 8) | (backingArray[baseOffset] & 0xff)); } } }
false
true
private final long loadLong(int index) { int baseOffset = offset + index; if (order == ByteOrder.BIG_ENDIAN) { int h = ((backingArray[baseOffset++] & 0xff) << 24) | ((backingArray[baseOffset++] & 0xff) << 16) | ((backingArray[baseOffset++] & 0xff) << 8) | ((backingArray[baseOffset++] & 0xff) << 0); int l = ((backingArray[baseOffset++] & 0xff) << 24) | ((backingArray[baseOffset++] & 0xff) << 16) | ((backingArray[baseOffset++] & 0xff) << 8) | ((backingArray[baseOffset ] & 0xff) << 0); return (((long) h) << 32) | l; } else { int l = ((backingArray[baseOffset++] & 0xff) << 0) | ((backingArray[baseOffset++] & 0xff) << 8) | ((backingArray[baseOffset++] & 0xff) << 16) | ((backingArray[baseOffset++] & 0xff) << 24); int h = ((backingArray[baseOffset++] & 0xff) << 0) | ((backingArray[baseOffset++] & 0xff) << 8) | ((backingArray[baseOffset++] & 0xff) << 16) | ((backingArray[baseOffset ] & 0xff) << 24); return (((long) h) << 32) | l; } }
private final long loadLong(int index) { int baseOffset = offset + index; if (order == ByteOrder.BIG_ENDIAN) { int h = ((backingArray[baseOffset++] & 0xff) << 24) | ((backingArray[baseOffset++] & 0xff) << 16) | ((backingArray[baseOffset++] & 0xff) << 8) | ((backingArray[baseOffset++] & 0xff) << 0); int l = ((backingArray[baseOffset++] & 0xff) << 24) | ((backingArray[baseOffset++] & 0xff) << 16) | ((backingArray[baseOffset++] & 0xff) << 8) | ((backingArray[baseOffset ] & 0xff) << 0); return (((long) h) << 32L) | ((long) l) & 0xffffffffL; } else { int l = ((backingArray[baseOffset++] & 0xff) << 0) | ((backingArray[baseOffset++] & 0xff) << 8) | ((backingArray[baseOffset++] & 0xff) << 16) | ((backingArray[baseOffset++] & 0xff) << 24); int h = ((backingArray[baseOffset++] & 0xff) << 0) | ((backingArray[baseOffset++] & 0xff) << 8) | ((backingArray[baseOffset++] & 0xff) << 16) | ((backingArray[baseOffset ] & 0xff) << 24); return (((long) h) << 32L) | ((long) l) & 0xffffffffL; } }
diff --git a/src/gwt/src/org/rstudio/core/client/command/KeyboardShortcut.java b/src/gwt/src/org/rstudio/core/client/command/KeyboardShortcut.java index 275dd32f8d..ff0f46315e 100644 --- a/src/gwt/src/org/rstudio/core/client/command/KeyboardShortcut.java +++ b/src/gwt/src/org/rstudio/core/client/command/KeyboardShortcut.java @@ -1,138 +1,138 @@ /* * KeyboardShortcut.java * * Copyright (C) 2009-12 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.core.client.command; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.KeyCodes; import org.rstudio.core.client.BrowseCap; public class KeyboardShortcut { public KeyboardShortcut(int keycode) { this(KeyboardShortcut.NONE, keycode); } public KeyboardShortcut(int modifiers, int keycode) { modifiers_ = modifiers; keycode_ = keycode; } @Override public boolean equals(Object o) { if (o == null) return false; KeyboardShortcut that = (KeyboardShortcut) o; return keycode_ == that.keycode_ && modifiers_ == that.modifiers_; } @Override public int hashCode() { int result = modifiers_; result = (result << 8) + keycode_; return result; } @Override public String toString() { return toString(false); } public String toString(boolean pretty) { if (BrowseCap.hasMetaKey() && pretty) { return ((modifiers_ & CTRL) == CTRL ? "&#8963;" : "") + ((modifiers_ & SHIFT) == SHIFT ? "&#8679;" : "") + ((modifiers_ & ALT) == ALT ? "&#8997;" : "") + ((modifiers_ & META) == META ? "&#8984;" : "") + getKeyName(true); } else { return ((modifiers_ & CTRL) == CTRL ? "Ctrl+" : "") + ((modifiers_ & SHIFT) == SHIFT ? "Shift+" : "") + ((modifiers_ & ALT) == ALT ? "Alt+" : "") + ((modifiers_ & META) == META ? "Meta+" : "") + getKeyName(pretty); } } private String getKeyName(boolean pretty) { boolean macStyle = BrowseCap.hasMetaKey() && pretty; if (keycode_ == KeyCodes.KEY_ENTER) return macStyle ? "&#8617;" : "Enter"; else if (keycode_ == KeyCodes.KEY_LEFT) return macStyle ? "&#8592;" : "Left"; else if (keycode_ == KeyCodes.KEY_RIGHT) return macStyle ? "&#8594;" : "Right"; else if (keycode_ == KeyCodes.KEY_UP) return macStyle ? "&#8593;" : "Up"; else if (keycode_ == KeyCodes.KEY_DOWN) return macStyle ? "&#8595;" : "Down"; else if (keycode_ == KeyCodes.KEY_TAB) return macStyle ? "&#8677;" : "Tab"; else if (keycode_ == KeyCodes.KEY_PAGEUP) return pretty ? "PgUp" : "PageUp"; else if (keycode_ == KeyCodes.KEY_PAGEDOWN) return pretty ? "PgDn" : "PageDown"; else if (keycode_ == 191) return "/"; else if (keycode_ == 192) return "`"; else if (keycode_ == 190) return "."; else if (keycode_ == 187) return "="; else if (keycode_ == 188) return "<"; else if (keycode_ >= 112 && keycode_ <= 123) return "F" + (keycode_ - 111); else if (keycode_ == 8) - return "Backspace"; + return macStyle ? "&#9003;" : "Backspace"; return Character.toUpperCase((char)keycode_) + ""; } public static int getModifierValue(NativeEvent e) { int modifiers = 0; if (e.getAltKey()) modifiers += ALT; if (e.getCtrlKey()) modifiers += CTRL; if (e.getMetaKey()) modifiers += META; if (e.getShiftKey()) modifiers += SHIFT; return modifiers; } private final int modifiers_; private final int keycode_; public static final int NONE = 0; public static final int ALT = 1; public static final int CTRL = 2; public static final int META = 4; public static final int SHIFT = 8; }
true
true
private String getKeyName(boolean pretty) { boolean macStyle = BrowseCap.hasMetaKey() && pretty; if (keycode_ == KeyCodes.KEY_ENTER) return macStyle ? "&#8617;" : "Enter"; else if (keycode_ == KeyCodes.KEY_LEFT) return macStyle ? "&#8592;" : "Left"; else if (keycode_ == KeyCodes.KEY_RIGHT) return macStyle ? "&#8594;" : "Right"; else if (keycode_ == KeyCodes.KEY_UP) return macStyle ? "&#8593;" : "Up"; else if (keycode_ == KeyCodes.KEY_DOWN) return macStyle ? "&#8595;" : "Down"; else if (keycode_ == KeyCodes.KEY_TAB) return macStyle ? "&#8677;" : "Tab"; else if (keycode_ == KeyCodes.KEY_PAGEUP) return pretty ? "PgUp" : "PageUp"; else if (keycode_ == KeyCodes.KEY_PAGEDOWN) return pretty ? "PgDn" : "PageDown"; else if (keycode_ == 191) return "/"; else if (keycode_ == 192) return "`"; else if (keycode_ == 190) return "."; else if (keycode_ == 187) return "="; else if (keycode_ == 188) return "<"; else if (keycode_ >= 112 && keycode_ <= 123) return "F" + (keycode_ - 111); else if (keycode_ == 8) return "Backspace"; return Character.toUpperCase((char)keycode_) + ""; }
private String getKeyName(boolean pretty) { boolean macStyle = BrowseCap.hasMetaKey() && pretty; if (keycode_ == KeyCodes.KEY_ENTER) return macStyle ? "&#8617;" : "Enter"; else if (keycode_ == KeyCodes.KEY_LEFT) return macStyle ? "&#8592;" : "Left"; else if (keycode_ == KeyCodes.KEY_RIGHT) return macStyle ? "&#8594;" : "Right"; else if (keycode_ == KeyCodes.KEY_UP) return macStyle ? "&#8593;" : "Up"; else if (keycode_ == KeyCodes.KEY_DOWN) return macStyle ? "&#8595;" : "Down"; else if (keycode_ == KeyCodes.KEY_TAB) return macStyle ? "&#8677;" : "Tab"; else if (keycode_ == KeyCodes.KEY_PAGEUP) return pretty ? "PgUp" : "PageUp"; else if (keycode_ == KeyCodes.KEY_PAGEDOWN) return pretty ? "PgDn" : "PageDown"; else if (keycode_ == 191) return "/"; else if (keycode_ == 192) return "`"; else if (keycode_ == 190) return "."; else if (keycode_ == 187) return "="; else if (keycode_ == 188) return "<"; else if (keycode_ >= 112 && keycode_ <= 123) return "F" + (keycode_ - 111); else if (keycode_ == 8) return macStyle ? "&#9003;" : "Backspace"; return Character.toUpperCase((char)keycode_) + ""; }
diff --git a/src/java/org/rapidcontext/core/security/SecurityContext.java b/src/java/org/rapidcontext/core/security/SecurityContext.java index 9ca1ea1..5dd45c0 100644 --- a/src/java/org/rapidcontext/core/security/SecurityContext.java +++ b/src/java/org/rapidcontext/core/security/SecurityContext.java @@ -1,542 +1,542 @@ /* * RapidContext <http://www.rapidcontext.com/> * Copyright (c) 2007-2010 Per Cederberg & Dynabyte AB. * All rights reserved. * * This program is free software: you can redistribute it and/or * modify it under the terms of the BSD license. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the RapidContext LICENSE.txt file for more details. */ package org.rapidcontext.core.security; import java.util.HashMap; import java.util.logging.Logger; import org.apache.commons.lang.time.DateUtils; import org.rapidcontext.core.data.Dict; import org.rapidcontext.core.proc.Procedure; import org.rapidcontext.core.storage.Path; import org.rapidcontext.core.storage.Storage; import org.rapidcontext.core.storage.StorageException; import org.rapidcontext.util.ArrayUtil; import org.rapidcontext.util.BinaryUtil; /** * The application security context. This class provides static * methods for authentication and resource authorization. It stores * the currently authenticated user in a thread-local storage, so * user credentials must be provided separately for each execution * thread. It is important that the manager is initialized before * any authentication calls are made, or they will fail.<p> * * The security context handles the anonymous and "system" users * specially. The built-in roles "Admin" and "Default" are also * handled in a special way. * * @author Per Cederberg * @version 1.0 */ public class SecurityContext { /** * The class logger. */ private static final Logger LOG = Logger.getLogger(SecurityContext.class.getName()); /** * The user authentication realm. */ // TODO: setup user realm in some non-hardcoded way public static final String REALM = "RapidContext"; /** * The user object storage path. */ public static final Path USER_PATH = new Path("/user/"); /** * The role object storage path. */ public static final Path ROLE_PATH = new Path("/role/"); /** * The data storage used for reading and writing configuration * data. */ private static Storage dataStorage = null; /** * The map of all roles. The map is indexed by the role names and * contains role objects. */ private static HashMap roles = new HashMap(); /** * The map of all users. The map is indexed by the user names and * contains user objects. */ private static HashMap users = new HashMap(); /** * The currently authenticated users. This is a thread-local * variable containing one user object per thread. If the value * is set to null, no user is currently authenticated for the * thread. */ private static ThreadLocal authUser = new ThreadLocal(); /** * Initializes the security context. It can be called multiple * times in order to re-read the configuration data from the * data storage. The data store specified will be used for * reading and writing users and roles both during initialization * and later. * * @param storage the data storage to use * * @throws StorageException if the storage couldn't be read or * written */ public static void init(Storage storage) throws StorageException { Object[] objs; Role role; User user; dataStorage = storage; roles.clear(); users.clear(); objs = dataStorage.loadAll(ROLE_PATH); for (int i = 0; i < objs.length; i++) { if (objs[i] instanceof Dict) { role = new Role((Dict) objs[i]); roles.put(role.getName().toLowerCase(), role); } } // TODO: Create default/anonymous role? // TODO: What if there are many users? objs = dataStorage.loadAll(USER_PATH); for (int i = 0; i < objs.length; i++) { if (objs[i] instanceof Dict) { user = new User((Dict) objs[i]); users.put(user.getName(), user); } } if (users.size() <= 0) { LOG.info("creating default 'admin' user"); user = new User("admin"); - user.setDescription("Default administrator user."); + user.setDescription("Default administrator user"); user.setEnabled(true); user.setRoles(new String[] { "Admin" }); storeUser(user); users.put("admin", user); } // TODO: create default system user? } /** * Returns the currently authenticated user for this thread. * * @return the currently authenticated user, or * null if no user is currently authenticated */ public static User currentUser() { return (User) authUser.get(); } /** * Checks if the currently authenticated user has access to an * object. * * @param obj the object to check * * @return true if the current user has access, or * false otherwise */ public static boolean hasAccess(Object obj) { return hasAccess(obj, null); } /** * Checks if the currently authenticated user has access to an * object. * * @param obj the object to check * @param caller the caller procedure, or null for none * * @return true if the current user has access, or * false otherwise */ public static boolean hasAccess(Object obj, String caller) { if (obj instanceof Restricted) { return ((Restricted) obj).hasAccess(); } else if (obj instanceof Procedure) { return hasAccess("procedure", ((Procedure) obj).getName(), caller); } else { return true; } } /** * Checks if the currently authenticated user has access to an * object. * * @param type the object type * @param name the object name * * @return true if the current user has access, or * false otherwise */ public static boolean hasAccess(String type, String name) { return hasAccess(type, name, null); } /** * Checks if the currently authenticated user has access to an * object. * * @param type the object type * @param name the object name * @param caller the caller procedure, or null for none * * @return true if the current user has access, or * false otherwise */ public static boolean hasAccess(String type, String name, String caller) { String[] list; Role role; if (hasAdmin()) { return true; } else if (currentUser() != null) { // TODO: Should verify objects with Restricted interface here // (eg procedures), since users may have no roles... list = currentUser().getRoles(); for (int i = 0; i < list.length; i++) { role = getRole(list[i]); if (role != null && role.hasAccess(type, name, caller)) { return true; } } return false; } else { // TODO: support anonymous access (Default role) return false; } } /** * Checks if the currently authenticated user has admin access. * * @return true if the current user has admin access, or * false otherwise */ public static boolean hasAdmin() { User user = currentUser(); return user != null && user.hasRole("Admin"); } /** * Creates a unique number to be used once for hashing. * * @return the unique hash number */ public static String nonce() { return String.valueOf(System.currentTimeMillis()); } /** * Verifies that the specified nonce is sufficiently recently * generated to be acceptable. * * @param nonce the nonce to check * * @throws SecurityException if the nonce was invalid */ public static void verifyNonce(String nonce) throws SecurityException { try { long since = System.currentTimeMillis() - Long.parseLong(nonce); if (since > DateUtils.MILLIS_PER_MINUTE * 240) { LOG.info("stale authentication one-off number"); throw new SecurityException("stale authentication one-off number"); } } catch (NumberFormatException e) { LOG.info("invalid authentication one-off number"); throw new SecurityException("invalid authentication one-off number"); } } /** * Authenticates the specified user. This method will verify * that the user exists and is enabled. It should only be called * if a previous user authentication can be trusted, either via * a cookie, command-line login or similar. After a successful * authentication the current user will be set to the specified * user. * * @param name the user name * * @throws SecurityException if the user failed authentication */ public static void auth(String name) throws SecurityException { User user = (User) users.get(name); String msg; if (user == null) { msg = "user " + name + " does not exist"; LOG.info("failed authentication: " + msg); throw new SecurityException(msg); } else if (!user.isEnabled()) { msg = "user " + name + " is disabled"; LOG.info("failed authentication: " + msg); throw new SecurityException(msg); } authUser.set(user); } /** * Authenticates the specified used with an MD5 two-step hash. * This method will verify that the user exists, is enabled and * that the password hash plus the specified suffix will MD5 hash * to the specified string, After a successful authentication the * current user will be set to the specified user. * * @param name the user name * @param suffix the user password hash suffix to append * @param hash the expected hashed result * * @throws Exception if the user failed authentication */ public static void authHash(String name, String suffix, String hash) throws Exception { User user = (User) users.get(name); String test; String msg; if (user == null) { msg = "user " + name + " does not exist"; LOG.info("failed authentication: " + msg); throw new SecurityException(msg); } else if (!user.isEnabled()) { msg = "user " + name + " is disabled"; LOG.info("failed authentication: " + msg); throw new SecurityException(msg); } test = BinaryUtil.hashMD5(user.getPasswordHash() + suffix); if (user.getPasswordHash().length() > 0 && !test.equals(hash)) { msg = "invalid password for user " + name; LOG.info("failed authentication: " + msg + ", expected: " + test + ", received: " + hash); throw new SecurityException(msg); } authUser.set(user); } /** * Removes any previous authentication. I.e. the current user * will be reset to the anonymous user. */ public static void authClear() { authUser.set(null); } /** * Returns all role names. * * @return all role names */ public static String[] getRoleNames() { return ArrayUtil.stringKeys(roles); } /** * Returns the role for the specified name. * * @param name the role name * * @return the role object, or * null if not found */ public static Role getRole(String name) { return (Role) roles.get(name.toLowerCase()); } /** * Saves a role to the application data store. This method will * verify that the current user has the Admin role before writing * the role data. * * @param role the role to save * * @throws StorageException if the data couldn't be written * @throws SecurityException if the current user doesn't have * admin access */ public static void saveRole(Role role) throws StorageException, SecurityException { String name = role.getName().toLowerCase(); try { if (!hasAdmin()) { LOG.info("failed to modify role " + role.getName() + ": user " + SecurityContext.currentUser() + " lacks admin privileges"); throw new SecurityException("Permission denied"); } else if (name.equals("admin")) { LOG.info("failed to modify role " + role.getName() + ": role is built-in and read-only"); throw new SecurityException("Permission denied"); } storeRole(role); } finally { Role newRole = loadRole(name); if (newRole == null) { roles.remove(name); } else { roles.put(name, newRole); } } } /** * Returns all user names. * * @return all user names */ public static String[] getUserNames() { return ArrayUtil.stringKeys(users); } /** * Returns the user for the specified user name. * * @param name the user name * * @return the user object, or * null if not found */ public static User getUser(String name) { return (User) users.get(name); } /** * Saves a user to the application data store. * * @param user the user to save * * @throws StorageException if the data couldn't be written * @throws SecurityException if the current user doesn't have * admin access */ public static void saveUser(User user) throws StorageException, SecurityException { String name = user.getName(); try { if (!hasAdmin()) { LOG.info("failed to modify user " + name + ": user " + SecurityContext.currentUser() + " lacks admin privileges"); throw new SecurityException("Permission denied"); } storeUser(user); } finally { User newUser = loadUser(name); if (newUser == null) { user.setEnabled(false); users.remove(name); } else { users.put(name, newUser); } } } /** * Updates the current user password in the application data store. * * @param password the new user password * * @throws StorageException if the data couldn't be written * @throws SecurityException if the current user isn't logged in */ public static void updatePassword(String password) throws StorageException, SecurityException { User user = SecurityContext.currentUser(); if (user == null) { LOG.info("failed to modify user password: user not logged in"); throw new SecurityException("Permission denied"); } user.setPassword(password); storeUser(user); } /** * Loads a user object. * * @param name the user name * * @return the user object, or * null if not found * * @throws StorageException if the data couldn't be read */ private static User loadUser(String name) throws StorageException { Path path = USER_PATH.child(name, false); Dict dict = (Dict) dataStorage.load(path); return (dict == null) ? null : new User(dict); } /** * Stores a user object. * * @param user the user to store * * @throws StorageException if the data couldn't be written */ private static void storeUser(User user) throws StorageException { Path path = USER_PATH.child(user.getName(), false); dataStorage.store(path, user.getData()); } /** * Loads a role object. * * @param name the role name * * @return the role object, or * null if not found * * @throws StorageException if the data couldn't be read */ private static Role loadRole(String name) throws StorageException { Path path = ROLE_PATH.child(name, false); Dict dict = (Dict) dataStorage.load(path); return (dict == null) ? null : new Role(dict); } /** * Stores a role object. * * @param role the role to store * * @throws StorageException if the data couldn't be written */ private static void storeRole(Role role) throws StorageException { Path path = ROLE_PATH.child(role.getName(), false); dataStorage.store(path, role.getData()); } }
true
true
public static void init(Storage storage) throws StorageException { Object[] objs; Role role; User user; dataStorage = storage; roles.clear(); users.clear(); objs = dataStorage.loadAll(ROLE_PATH); for (int i = 0; i < objs.length; i++) { if (objs[i] instanceof Dict) { role = new Role((Dict) objs[i]); roles.put(role.getName().toLowerCase(), role); } } // TODO: Create default/anonymous role? // TODO: What if there are many users? objs = dataStorage.loadAll(USER_PATH); for (int i = 0; i < objs.length; i++) { if (objs[i] instanceof Dict) { user = new User((Dict) objs[i]); users.put(user.getName(), user); } } if (users.size() <= 0) { LOG.info("creating default 'admin' user"); user = new User("admin"); user.setDescription("Default administrator user."); user.setEnabled(true); user.setRoles(new String[] { "Admin" }); storeUser(user); users.put("admin", user); } // TODO: create default system user? }
public static void init(Storage storage) throws StorageException { Object[] objs; Role role; User user; dataStorage = storage; roles.clear(); users.clear(); objs = dataStorage.loadAll(ROLE_PATH); for (int i = 0; i < objs.length; i++) { if (objs[i] instanceof Dict) { role = new Role((Dict) objs[i]); roles.put(role.getName().toLowerCase(), role); } } // TODO: Create default/anonymous role? // TODO: What if there are many users? objs = dataStorage.loadAll(USER_PATH); for (int i = 0; i < objs.length; i++) { if (objs[i] instanceof Dict) { user = new User((Dict) objs[i]); users.put(user.getName(), user); } } if (users.size() <= 0) { LOG.info("creating default 'admin' user"); user = new User("admin"); user.setDescription("Default administrator user"); user.setEnabled(true); user.setRoles(new String[] { "Admin" }); storeUser(user); users.put("admin", user); } // TODO: create default system user? }
diff --git a/plugins/dk.itu.big_red/src/dk/itu/big_red/model/assistants/SignatureChangeValidator.java b/plugins/dk.itu.big_red/src/dk/itu/big_red/model/assistants/SignatureChangeValidator.java index d29a92b1..b349a7ec 100644 --- a/plugins/dk.itu.big_red/src/dk/itu/big_red/model/assistants/SignatureChangeValidator.java +++ b/plugins/dk.itu.big_red/src/dk/itu/big_red/model/assistants/SignatureChangeValidator.java @@ -1,91 +1,95 @@ package dk.itu.big_red.model.assistants; import dk.itu.big_red.model.Colourable.ChangeFillColour; import dk.itu.big_red.model.Colourable.ChangeOutlineColour; import dk.itu.big_red.model.Control.ChangeAddPort; import dk.itu.big_red.model.Control.ChangeDefaultSize; import dk.itu.big_red.model.Control.ChangeKind; import dk.itu.big_red.model.Control.ChangeLabel; import dk.itu.big_red.model.Control.ChangeName; import dk.itu.big_red.model.Control.ChangePoints; import dk.itu.big_red.model.Control.ChangeRemovePort; import dk.itu.big_red.model.Control.ChangeResizable; import dk.itu.big_red.model.Control.ChangeShape; import dk.itu.big_red.model.ModelObject.ChangeComment; import dk.itu.big_red.model.PortSpec.ChangeDistance; import dk.itu.big_red.model.PortSpec.ChangeSegment; import dk.itu.big_red.model.PortSpec; import dk.itu.big_red.model.Signature; import dk.itu.big_red.model.Signature.ChangeAddControl; import dk.itu.big_red.model.Signature.ChangeRemoveControl; import dk.itu.big_red.model.changes.Change; import dk.itu.big_red.model.changes.ChangeGroup; import dk.itu.big_red.model.changes.ChangeRejectedException; import dk.itu.big_red.model.changes.ChangeValidator; public class SignatureChangeValidator extends ChangeValidator<Signature> { private final SignatureScratchpad scratch; private Change activeChange = null; public SignatureChangeValidator(Signature changeable) { super(changeable); scratch = new SignatureScratchpad(changeable); } @Override public void tryValidateChange(Change b) throws ChangeRejectedException { activeChange = b; scratch.clear(); _tryValidateChange(b); activeChange = null; } protected void rejectChange(String rationale) throws ChangeRejectedException { super.rejectChange(activeChange, rationale); } private void _tryValidateChange(Change b) throws ChangeRejectedException { if (!b.isReady()) { rejectChange("The Change is not ready"); } else if (b instanceof ChangeGroup) { for (Change c : (ChangeGroup)b) tryValidateChange(c); } else if (b instanceof ChangeFillColour || b instanceof ChangeOutlineColour || b instanceof ChangeComment) { /* do nothing */ } else if (b instanceof ChangeAddControl) { ChangeAddControl c = (ChangeAddControl)b; scratch.addControl(c.control); } else if (b instanceof ChangeRemoveControl) { ChangeRemoveControl c = (ChangeRemoveControl)b; scratch.removeControl(c.control); } else if (b instanceof ChangeAddPort) { ChangeAddPort c = (ChangeAddPort)b; scratch.addPortFor(c.getCreator(), c.port); } else if (b instanceof ChangeRemovePort) { ChangeRemovePort c = (ChangeRemovePort)b; scratch.removePortFor(c.getCreator(), c.port); } else if (b instanceof ChangeShape || b instanceof ChangeLabel || b instanceof ChangeResizable || b instanceof ChangeDefaultSize || b instanceof ChangeKind || b instanceof ChangeSegment || - b instanceof ChangePoints || - b instanceof PortSpec.ChangeName) { + b instanceof ChangePoints) { /* do nothing, yet */ + } else if (b instanceof PortSpec.ChangeName) { + PortSpec.ChangeName c = (PortSpec.ChangeName)b; + if (c.name.trim().length() == 0) + rejectChange(b, "Port names must not be empty"); } else if (b instanceof ChangeDistance) { ChangeDistance c = (ChangeDistance)b; if (c.distance < 0 || c.distance >= 1.0) rejectChange(b, "The distance value is invalid"); } else if (b instanceof ChangeName) { ChangeName c = (ChangeName)b; if (c.name.trim().length() == 0) rejectChange(b, "Control names must not be empty"); + scratch.setNameFor(c.getCreator(), c.name); } else rejectChange("The change was not recognised by the validator"); } }
false
true
private void _tryValidateChange(Change b) throws ChangeRejectedException { if (!b.isReady()) { rejectChange("The Change is not ready"); } else if (b instanceof ChangeGroup) { for (Change c : (ChangeGroup)b) tryValidateChange(c); } else if (b instanceof ChangeFillColour || b instanceof ChangeOutlineColour || b instanceof ChangeComment) { /* do nothing */ } else if (b instanceof ChangeAddControl) { ChangeAddControl c = (ChangeAddControl)b; scratch.addControl(c.control); } else if (b instanceof ChangeRemoveControl) { ChangeRemoveControl c = (ChangeRemoveControl)b; scratch.removeControl(c.control); } else if (b instanceof ChangeAddPort) { ChangeAddPort c = (ChangeAddPort)b; scratch.addPortFor(c.getCreator(), c.port); } else if (b instanceof ChangeRemovePort) { ChangeRemovePort c = (ChangeRemovePort)b; scratch.removePortFor(c.getCreator(), c.port); } else if (b instanceof ChangeShape || b instanceof ChangeLabel || b instanceof ChangeResizable || b instanceof ChangeDefaultSize || b instanceof ChangeKind || b instanceof ChangeSegment || b instanceof ChangePoints || b instanceof PortSpec.ChangeName) { /* do nothing, yet */ } else if (b instanceof ChangeDistance) { ChangeDistance c = (ChangeDistance)b; if (c.distance < 0 || c.distance >= 1.0) rejectChange(b, "The distance value is invalid"); } else if (b instanceof ChangeName) { ChangeName c = (ChangeName)b; if (c.name.trim().length() == 0) rejectChange(b, "Control names must not be empty"); } else rejectChange("The change was not recognised by the validator"); }
private void _tryValidateChange(Change b) throws ChangeRejectedException { if (!b.isReady()) { rejectChange("The Change is not ready"); } else if (b instanceof ChangeGroup) { for (Change c : (ChangeGroup)b) tryValidateChange(c); } else if (b instanceof ChangeFillColour || b instanceof ChangeOutlineColour || b instanceof ChangeComment) { /* do nothing */ } else if (b instanceof ChangeAddControl) { ChangeAddControl c = (ChangeAddControl)b; scratch.addControl(c.control); } else if (b instanceof ChangeRemoveControl) { ChangeRemoveControl c = (ChangeRemoveControl)b; scratch.removeControl(c.control); } else if (b instanceof ChangeAddPort) { ChangeAddPort c = (ChangeAddPort)b; scratch.addPortFor(c.getCreator(), c.port); } else if (b instanceof ChangeRemovePort) { ChangeRemovePort c = (ChangeRemovePort)b; scratch.removePortFor(c.getCreator(), c.port); } else if (b instanceof ChangeShape || b instanceof ChangeLabel || b instanceof ChangeResizable || b instanceof ChangeDefaultSize || b instanceof ChangeKind || b instanceof ChangeSegment || b instanceof ChangePoints) { /* do nothing, yet */ } else if (b instanceof PortSpec.ChangeName) { PortSpec.ChangeName c = (PortSpec.ChangeName)b; if (c.name.trim().length() == 0) rejectChange(b, "Port names must not be empty"); } else if (b instanceof ChangeDistance) { ChangeDistance c = (ChangeDistance)b; if (c.distance < 0 || c.distance >= 1.0) rejectChange(b, "The distance value is invalid"); } else if (b instanceof ChangeName) { ChangeName c = (ChangeName)b; if (c.name.trim().length() == 0) rejectChange(b, "Control names must not be empty"); scratch.setNameFor(c.getCreator(), c.name); } else rejectChange("The change was not recognised by the validator"); }
diff --git a/src/com/ModDamage/Events/Death.java b/src/com/ModDamage/Events/Death.java index 764b02c..9e25158 100644 --- a/src/com/ModDamage/Events/Death.java +++ b/src/com/ModDamage/Events/Death.java @@ -1,53 +1,54 @@ package com.ModDamage.Events; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.PlayerDeathEvent; import com.ModDamage.MDEvent; import com.ModDamage.ModDamage; import com.ModDamage.EventInfo.EventData; import com.ModDamage.EventInfo.EventInfo; import com.ModDamage.EventInfo.SimpleEventInfo; import com.ModDamage.Matchables.DamageType; public class Death extends MDEvent implements Listener { public Death() { super(myInfo); } static final EventInfo myInfo = Damage.myInfo.chain(new SimpleEventInfo( Integer.class, "experience", "-default")); @EventHandler(priority=EventPriority.HIGHEST) public void onEntityDeath(EntityDeathEvent event) { if(!ModDamage.isEnabled) return; if(disableDeathMessages && event instanceof PlayerDeathEvent) ((PlayerDeathEvent)event).setDeathMessage(null); Entity entity = event.getEntity(); EventData damageData = Damage.getEventData(((LivingEntity) entity).getLastDamageCause()); if(damageData == null) // for instance, /butcher often does this damageData = Damage.myInfo.makeData( null, null, entity, entity.getWorld(), DamageType.UNKNOWN, - 0 + 0, + null ); EventData data = myInfo.makeChainedData(damageData, event.getDroppedExp()); runRoutines(data); event.setDroppedExp(data.get(Integer.class, data.start)); } }
true
true
public void onEntityDeath(EntityDeathEvent event) { if(!ModDamage.isEnabled) return; if(disableDeathMessages && event instanceof PlayerDeathEvent) ((PlayerDeathEvent)event).setDeathMessage(null); Entity entity = event.getEntity(); EventData damageData = Damage.getEventData(((LivingEntity) entity).getLastDamageCause()); if(damageData == null) // for instance, /butcher often does this damageData = Damage.myInfo.makeData( null, null, entity, entity.getWorld(), DamageType.UNKNOWN, 0 ); EventData data = myInfo.makeChainedData(damageData, event.getDroppedExp()); runRoutines(data); event.setDroppedExp(data.get(Integer.class, data.start)); }
public void onEntityDeath(EntityDeathEvent event) { if(!ModDamage.isEnabled) return; if(disableDeathMessages && event instanceof PlayerDeathEvent) ((PlayerDeathEvent)event).setDeathMessage(null); Entity entity = event.getEntity(); EventData damageData = Damage.getEventData(((LivingEntity) entity).getLastDamageCause()); if(damageData == null) // for instance, /butcher often does this damageData = Damage.myInfo.makeData( null, null, entity, entity.getWorld(), DamageType.UNKNOWN, 0, null ); EventData data = myInfo.makeChainedData(damageData, event.getDroppedExp()); runRoutines(data); event.setDroppedExp(data.get(Integer.class, data.start)); }
diff --git a/db/src/main/java/com/psddev/dari/db/ReferentialText.java b/db/src/main/java/com/psddev/dari/db/ReferentialText.java index 63de69fe..5840815d 100644 --- a/db/src/main/java/com/psddev/dari/db/ReferentialText.java +++ b/db/src/main/java/com/psddev/dari/db/ReferentialText.java @@ -1,455 +1,455 @@ package com.psddev.dari.db; import java.util.AbstractList; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.nodes.Node; import org.jsoup.nodes.TextNode; import org.jsoup.parser.Tag; import com.psddev.dari.util.ErrorUtils; import com.psddev.dari.util.ObjectUtils; import com.psddev.dari.util.StringUtils; /** Contains strings and references to other objects. */ public class ReferentialText extends AbstractList<Object> { private static final Tag BR_TAG = Tag.valueOf("br"); private static final Tag DIV_TAG = Tag.valueOf("div"); private static final Tag P_TAG = Tag.valueOf("p"); private final List<Object> list = new ArrayList<Object>(); /** * Creates an empty instance. */ public ReferentialText() { } private static void addByBoundary( List<Object> list, String html, String boundary, List<Reference> references) { int previousBoundaryAt = 0; for (int boundaryAt = previousBoundaryAt; (boundaryAt = html.indexOf(boundary, previousBoundaryAt)) >= 0; previousBoundaryAt = boundaryAt + boundary.length()) { list.add(html.substring(previousBoundaryAt, boundaryAt)); list.add(references.get(list.size() / 2)); } list.add(html.substring(previousBoundaryAt)); } /** * Parses the given {@code html} and adds all HTML strings and references * found within. * * @param html If {@code null}, does nothing. */ public void addHtml(String html) { if (html == null) { return; } Document document = Jsoup.parseBodyFragment(html); Element body = document.body(); document.outputSettings().prettyPrint(false); // Remove Microsoft-specific tags. for (Element element : body.select("*")) { String tagName = element.tagName(); if (tagName.startsWith("o:")) { element.unwrap(); } else if (tagName.equals("span")) { if (element.attributes().size() == 0 || element.attr("class").contains("Mso") || element.hasAttr("color")) { element.unwrap(); } } } // Convert '<p>text</p>' to 'text<br><br>'. for (Element p : body.getElementsByTag("p")) { if (p.hasText()) { p.appendChild(new Element(BR_TAG, "")); p.appendChild(new Element(BR_TAG, "")); p.unwrap(); // Remove empty paragraphs. } else { p.remove(); } } // Find mistakes in <a> hrefs. for (Element a : body.getElementsByTag("a")) { String href = a.attr("href"); if (!ObjectUtils.isBlank(href)) { a.attr("href", href.replaceAll("^(?:(?:https?:/?/?)*(https?://))?", "$1")); } } // Find object references. List<Reference> references = new ArrayList<Reference>(); String boundary = UUID.randomUUID().toString(); for (Element enhancement : body.getElementsByClass("enhancement")) { if (!enhancement.hasClass("state-removing")) { Reference reference = null; String referenceData = enhancement.dataset().remove("reference"); if (!StringUtils.isBlank(referenceData)) { Map<?, ?> referenceMap = (Map<?, ?>) ObjectUtils.fromJson(referenceData); UUID id = ObjectUtils.to(UUID.class, referenceMap.get("_id")); UUID typeId = ObjectUtils.to(UUID.class, referenceMap.get("_type")); ObjectType type = Database.Static.getDefault().getEnvironment().getTypeById(typeId); if (type != null) { Object referenceObject = type.createObject(id); if (referenceObject instanceof Reference) { reference = (Reference) referenceObject; } } if (reference == null) { reference = new Reference(); } for (Map.Entry<?, ?> entry : referenceMap.entrySet()) { reference.getState().put(entry.getKey().toString(), entry.getValue()); } } if (reference != null) { references.add(reference); enhancement.before(boundary); } } enhancement.remove(); } StringBuilder cleaned = new StringBuilder(); for (Node child : body.childNodes()) { cleaned.append(child.toString()); } addByBoundary(this, cleaned.toString(), boundary, references); } /** * Creates an instance from the given {@code html}. * * @param html If {@code null}, creates an empty instance. */ public ReferentialText(String html, boolean finalDraft) { addHtml(html); } /** * Returns a mixed list of well-formed HTML strings and object references * that have been converted to publishable forms. * * @return Never {@code null}. */ public List<Object> toPublishables() { // Concatenate the items so that it can be fed into an HTML parser. StringBuilder html = new StringBuilder(); String boundary = UUID.randomUUID().toString(); List<Reference> references = new ArrayList<Reference>(); for (Object item : this) { if (item != null) { if (item instanceof Reference) { html.append(boundary); references.add((Reference) item); } else { html.append(item.toString()); } } } Document document = Jsoup.parseBodyFragment(html.toString()); Element body = document.body(); document.outputSettings().prettyPrint(false); // Remove editorial markups. body.getElementsByTag("del").remove(); body.getElementsByTag("ins").unwrap(); body.getElementsByClass("rte").remove(); body.select("code[data-annotations]").remove(); // Convert 'text<br><br>' to '<p>text</p>'. for (Element br : body.getElementsByTag("br")) { Element previousBr = null; // Find the closest previous <br> without any intervening content. for (Node previousNode = br; (previousNode = previousNode.previousSibling()) != null; ) { if (previousNode instanceof Element) { Element previousElement = (Element) previousNode; if (BR_TAG.equals(previousElement.tag())) { previousBr = previousElement; } break; } if (previousNode instanceof TextNode && !((TextNode) previousNode).isBlank()) { break; } } if (previousBr == null) { continue; } List<Node> paragraphChildren = new ArrayList<Node>(); for (Node previous = previousBr; (previous = previous.previousSibling()) != null; ) { if (previous instanceof Element && ((Element) previous).isBlock()) { break; } else { paragraphChildren.add(previous); } } Element paragraph = new Element(P_TAG, ""); for (Node child : paragraphChildren) { child.remove(); paragraph.prependChild(child.clone()); } br.before(paragraph); br.remove(); previousBr.remove(); } // Convert inline text after <p>s into paragraphs. for (Element paragraph : body.getElementsByTag(P_TAG.getName())) { Node next = paragraph; while ((next = next.nextSibling()) != null) { if (!(next instanceof TextNode && ((TextNode) next).isBlank())) { break; } } if (next != null) { List<Node> paragraphChildren = new ArrayList<Node>(); do { if (next instanceof Element && ((Element) next).isBlock()) { break; } else { paragraphChildren.add(next); } } while ((next = next.nextSibling()) != null); if (!paragraphChildren.isEmpty()) { Element lastParagraph = new Element(P_TAG, ""); for (Node child : paragraphChildren) { child.remove(); lastParagraph.appendChild(child.clone()); } paragraph.after(lastParagraph); } } } // Convert '<div>text<div><div><br></div>' to '<p>text</p>' List<Element> divs = new ArrayList<Element>(); DIV: for (Element div : body.getElementsByTag("div")) { Element brDiv = nextTag(DIV_TAG, div); if (brDiv == null) { continue; } // '<div><br></div>'? boolean sawBr = false; for (Node child : brDiv.childNodes()) { if (child instanceof TextNode) { - if (((TextNode) child).isBlank()) { + if (!((TextNode) child).isBlank()) { continue DIV; } } else if (child instanceof Element && BR_TAG.equals(((Element) child).tag())) { if (sawBr) { continue DIV; } else { sawBr = true; } } else { continue DIV; } } divs.add(div); div.tagName("p"); brDiv.remove(); } for (Element div : divs) { div = nextTag(DIV_TAG, div); if (div != null) { div.tagName("p"); } } // Unwrap nested '<p>'s. for (Element paragraph : body.getElementsByTag(P_TAG.getName())) { if (paragraph.getElementsByTag(P_TAG.getName()).size() > 1) { paragraph.unwrap(); } } // Remove empty paragraphs and stringify. StringBuilder cleaned = new StringBuilder(); for (Node child : body.childNodes()) { if (child instanceof Element) { Element childElement = (Element) child; if (P_TAG.equals(childElement.tag()) && !childElement.hasText()) { continue; } } cleaned.append(child.toString()); } List<Object> publishables = new ArrayList<Object>(); addByBoundary(publishables, cleaned.toString(), boundary, references); return publishables; } // Find the closest next tag without any intervening content. private Element nextTag(Tag tag, Element current) { Element nextTag = null; for (Node nextNode = current; (nextNode = nextNode.nextSibling()) != null; ) { if (nextNode instanceof Element) { Element nextElement = (Element) nextNode; if (tag.equals(nextElement.tag())) { nextTag = nextElement; } break; } if (nextNode instanceof TextNode && !((TextNode) nextNode).isBlank()) { break; } } return nextTag; } // --- AbstractList support --- private Object checkItem(Object item) { ErrorUtils.errorIfNull(item, "item"); if (item instanceof Reference) { return item; } else if (item instanceof Map) { Reference ref = null; UUID id = ObjectUtils.to(UUID.class, ((Map<?, ?>) item).get("_id")); UUID typeId = ObjectUtils.to(UUID.class, ((Map<?, ?>) item).get("_type")); ObjectType type = Database.Static.getDefault().getEnvironment().getTypeById(typeId); if (type != null) { Object object = type.createObject(id); if (object instanceof Reference) { ref = (Reference) object; } } if (ref == null) { ref = new Reference(); } for (Map.Entry<?, ?> entry : ((Map<?, ?>) item).entrySet()) { Object key = entry.getKey(); ref.getState().put(key != null ? key.toString() : null, entry.getValue()); } return ref; } else { return item.toString(); } } @Override public void add(int index, Object item) { list.add(index, checkItem(item)); } @Override public Object get(int index) { return list.get(index); } @Override public Object remove(int index) { return list.remove(index); } @Override public Object set(int index, Object item) { return list.set(index, checkItem(item)); } @Override public int size() { return list.size(); } }
true
true
public List<Object> toPublishables() { // Concatenate the items so that it can be fed into an HTML parser. StringBuilder html = new StringBuilder(); String boundary = UUID.randomUUID().toString(); List<Reference> references = new ArrayList<Reference>(); for (Object item : this) { if (item != null) { if (item instanceof Reference) { html.append(boundary); references.add((Reference) item); } else { html.append(item.toString()); } } } Document document = Jsoup.parseBodyFragment(html.toString()); Element body = document.body(); document.outputSettings().prettyPrint(false); // Remove editorial markups. body.getElementsByTag("del").remove(); body.getElementsByTag("ins").unwrap(); body.getElementsByClass("rte").remove(); body.select("code[data-annotations]").remove(); // Convert 'text<br><br>' to '<p>text</p>'. for (Element br : body.getElementsByTag("br")) { Element previousBr = null; // Find the closest previous <br> without any intervening content. for (Node previousNode = br; (previousNode = previousNode.previousSibling()) != null; ) { if (previousNode instanceof Element) { Element previousElement = (Element) previousNode; if (BR_TAG.equals(previousElement.tag())) { previousBr = previousElement; } break; } if (previousNode instanceof TextNode && !((TextNode) previousNode).isBlank()) { break; } } if (previousBr == null) { continue; } List<Node> paragraphChildren = new ArrayList<Node>(); for (Node previous = previousBr; (previous = previous.previousSibling()) != null; ) { if (previous instanceof Element && ((Element) previous).isBlock()) { break; } else { paragraphChildren.add(previous); } } Element paragraph = new Element(P_TAG, ""); for (Node child : paragraphChildren) { child.remove(); paragraph.prependChild(child.clone()); } br.before(paragraph); br.remove(); previousBr.remove(); } // Convert inline text after <p>s into paragraphs. for (Element paragraph : body.getElementsByTag(P_TAG.getName())) { Node next = paragraph; while ((next = next.nextSibling()) != null) { if (!(next instanceof TextNode && ((TextNode) next).isBlank())) { break; } } if (next != null) { List<Node> paragraphChildren = new ArrayList<Node>(); do { if (next instanceof Element && ((Element) next).isBlock()) { break; } else { paragraphChildren.add(next); } } while ((next = next.nextSibling()) != null); if (!paragraphChildren.isEmpty()) { Element lastParagraph = new Element(P_TAG, ""); for (Node child : paragraphChildren) { child.remove(); lastParagraph.appendChild(child.clone()); } paragraph.after(lastParagraph); } } } // Convert '<div>text<div><div><br></div>' to '<p>text</p>' List<Element> divs = new ArrayList<Element>(); DIV: for (Element div : body.getElementsByTag("div")) { Element brDiv = nextTag(DIV_TAG, div); if (brDiv == null) { continue; } // '<div><br></div>'? boolean sawBr = false; for (Node child : brDiv.childNodes()) { if (child instanceof TextNode) { if (((TextNode) child).isBlank()) { continue DIV; } } else if (child instanceof Element && BR_TAG.equals(((Element) child).tag())) { if (sawBr) { continue DIV; } else { sawBr = true; } } else { continue DIV; } } divs.add(div); div.tagName("p"); brDiv.remove(); } for (Element div : divs) { div = nextTag(DIV_TAG, div); if (div != null) { div.tagName("p"); } } // Unwrap nested '<p>'s. for (Element paragraph : body.getElementsByTag(P_TAG.getName())) { if (paragraph.getElementsByTag(P_TAG.getName()).size() > 1) { paragraph.unwrap(); } } // Remove empty paragraphs and stringify. StringBuilder cleaned = new StringBuilder(); for (Node child : body.childNodes()) { if (child instanceof Element) { Element childElement = (Element) child; if (P_TAG.equals(childElement.tag()) && !childElement.hasText()) { continue; } } cleaned.append(child.toString()); } List<Object> publishables = new ArrayList<Object>(); addByBoundary(publishables, cleaned.toString(), boundary, references); return publishables; }
public List<Object> toPublishables() { // Concatenate the items so that it can be fed into an HTML parser. StringBuilder html = new StringBuilder(); String boundary = UUID.randomUUID().toString(); List<Reference> references = new ArrayList<Reference>(); for (Object item : this) { if (item != null) { if (item instanceof Reference) { html.append(boundary); references.add((Reference) item); } else { html.append(item.toString()); } } } Document document = Jsoup.parseBodyFragment(html.toString()); Element body = document.body(); document.outputSettings().prettyPrint(false); // Remove editorial markups. body.getElementsByTag("del").remove(); body.getElementsByTag("ins").unwrap(); body.getElementsByClass("rte").remove(); body.select("code[data-annotations]").remove(); // Convert 'text<br><br>' to '<p>text</p>'. for (Element br : body.getElementsByTag("br")) { Element previousBr = null; // Find the closest previous <br> without any intervening content. for (Node previousNode = br; (previousNode = previousNode.previousSibling()) != null; ) { if (previousNode instanceof Element) { Element previousElement = (Element) previousNode; if (BR_TAG.equals(previousElement.tag())) { previousBr = previousElement; } break; } if (previousNode instanceof TextNode && !((TextNode) previousNode).isBlank()) { break; } } if (previousBr == null) { continue; } List<Node> paragraphChildren = new ArrayList<Node>(); for (Node previous = previousBr; (previous = previous.previousSibling()) != null; ) { if (previous instanceof Element && ((Element) previous).isBlock()) { break; } else { paragraphChildren.add(previous); } } Element paragraph = new Element(P_TAG, ""); for (Node child : paragraphChildren) { child.remove(); paragraph.prependChild(child.clone()); } br.before(paragraph); br.remove(); previousBr.remove(); } // Convert inline text after <p>s into paragraphs. for (Element paragraph : body.getElementsByTag(P_TAG.getName())) { Node next = paragraph; while ((next = next.nextSibling()) != null) { if (!(next instanceof TextNode && ((TextNode) next).isBlank())) { break; } } if (next != null) { List<Node> paragraphChildren = new ArrayList<Node>(); do { if (next instanceof Element && ((Element) next).isBlock()) { break; } else { paragraphChildren.add(next); } } while ((next = next.nextSibling()) != null); if (!paragraphChildren.isEmpty()) { Element lastParagraph = new Element(P_TAG, ""); for (Node child : paragraphChildren) { child.remove(); lastParagraph.appendChild(child.clone()); } paragraph.after(lastParagraph); } } } // Convert '<div>text<div><div><br></div>' to '<p>text</p>' List<Element> divs = new ArrayList<Element>(); DIV: for (Element div : body.getElementsByTag("div")) { Element brDiv = nextTag(DIV_TAG, div); if (brDiv == null) { continue; } // '<div><br></div>'? boolean sawBr = false; for (Node child : brDiv.childNodes()) { if (child instanceof TextNode) { if (!((TextNode) child).isBlank()) { continue DIV; } } else if (child instanceof Element && BR_TAG.equals(((Element) child).tag())) { if (sawBr) { continue DIV; } else { sawBr = true; } } else { continue DIV; } } divs.add(div); div.tagName("p"); brDiv.remove(); } for (Element div : divs) { div = nextTag(DIV_TAG, div); if (div != null) { div.tagName("p"); } } // Unwrap nested '<p>'s. for (Element paragraph : body.getElementsByTag(P_TAG.getName())) { if (paragraph.getElementsByTag(P_TAG.getName()).size() > 1) { paragraph.unwrap(); } } // Remove empty paragraphs and stringify. StringBuilder cleaned = new StringBuilder(); for (Node child : body.childNodes()) { if (child instanceof Element) { Element childElement = (Element) child; if (P_TAG.equals(childElement.tag()) && !childElement.hasText()) { continue; } } cleaned.append(child.toString()); } List<Object> publishables = new ArrayList<Object>(); addByBoundary(publishables, cleaned.toString(), boundary, references); return publishables; }
diff --git a/core/http/server/src/main/java/org/openrdf/http/server/ExceptionWriter.java b/core/http/server/src/main/java/org/openrdf/http/server/ExceptionWriter.java index 178444a5d..bda783aed 100644 --- a/core/http/server/src/main/java/org/openrdf/http/server/ExceptionWriter.java +++ b/core/http/server/src/main/java/org/openrdf/http/server/ExceptionWriter.java @@ -1,147 +1,147 @@ /* * Copyright Aduna (http://www.aduna-software.com/) (c) 2007-2009. * * Licensed under the Aduna BSD-style license. */ package org.openrdf.http.server; import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST; import java.io.PrintWriter; import java.util.Collections; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.servlet.HandlerExceptionResolver; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.View; import org.xml.sax.SAXParseException; import org.openrdf.http.protocol.error.ErrorInfo; import org.openrdf.http.protocol.error.ErrorType; import org.openrdf.http.protocol.exceptions.ClientHTTPException; import org.openrdf.http.protocol.exceptions.HTTPException; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.UnsupportedQueryLanguageException; import org.openrdf.rio.RDFParseException; /** * Simple resolver for Exceptions: returns the correct response code and message * to the client. * * @author Herko ter Horst * @author James Leigh */ public class ExceptionWriter implements HandlerExceptionResolver, View { private static final String THROWABLE_KEY = "throwable"; private final Logger logger = LoggerFactory.getLogger(this.getClass()); /*----------------------------------------* * HandlerExceptionResolver functionality * *----------------------------------------*/ public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) { logger.trace("ExceptionWriter.resolveException() called"); Throwable t = exception; if (exception instanceof IllegalStateException && exception.getCause() != null) { // Spring wraps exceptions in IllegalStateException: Unexpected // exception thrown t = exception.getCause(); } return new ModelAndView(this, Collections.singletonMap(THROWABLE_KEY, t)); } /*--------------------* * View functionality * *--------------------*/ public String getContentType() { return "text/plain;charset=UTF-8"; } @SuppressWarnings("unchecked") public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { Throwable t = (Throwable)model.get(THROWABLE_KEY); int statusCode; String errMsg; HTTPException httpExc = findHTTPException(t); if (httpExc != null) { statusCode = httpExc.getStatusCode(); errMsg = httpExc.getMessage(); - if (t instanceof ClientHTTPException) { + if (httpExc instanceof ClientHTTPException) { logger.info("Client sent bad request ({}): {}", statusCode, errMsg); } else { logger.error("Error while handling request ({}): {}", statusCode, errMsg); } } else if (t instanceof RDFParseException) { ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_DATA, t.getMessage()); statusCode = SC_BAD_REQUEST; errMsg = errInfo.toString(); logger.info("Client sent bad request ({})", errMsg); } else if (t instanceof SAXParseException) { ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_DATA, t.getMessage()); statusCode = SC_BAD_REQUEST; errMsg = errInfo.toString(); logger.info("Client sent bad request ({})", errMsg); } else if (t instanceof UnsupportedQueryLanguageException) { ErrorInfo errInfo = new ErrorInfo(ErrorType.UNSUPPORTED_QUERY_LANGUAGE, t.getMessage()); statusCode = SC_BAD_REQUEST; errMsg = errInfo.toString(); logger.info("Client sent bad request ({})", errMsg); } else if (t instanceof MalformedQueryException) { ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_QUERY, t.getMessage()); statusCode = SC_BAD_REQUEST; errMsg = errInfo.toString(); logger.info("Client sent bad request ({})", errMsg); } else { statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; errMsg = t.getMessage(); logger.error("Unexpected error while handling request", t); } response.setStatus(statusCode); if (response.getContentType() == null) { // there seems to be a bug in spring that causes getContentType() to be ignored response.setContentType(getContentType()); } PrintWriter writer = response.getWriter(); try { writer.println(errMsg); } finally { writer.close(); } } private HTTPException findHTTPException(Throwable t) { while (t != null && !(t instanceof HTTPException)) { t = t.getCause(); } return (HTTPException)t; } }
true
true
public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { Throwable t = (Throwable)model.get(THROWABLE_KEY); int statusCode; String errMsg; HTTPException httpExc = findHTTPException(t); if (httpExc != null) { statusCode = httpExc.getStatusCode(); errMsg = httpExc.getMessage(); if (t instanceof ClientHTTPException) { logger.info("Client sent bad request ({}): {}", statusCode, errMsg); } else { logger.error("Error while handling request ({}): {}", statusCode, errMsg); } } else if (t instanceof RDFParseException) { ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_DATA, t.getMessage()); statusCode = SC_BAD_REQUEST; errMsg = errInfo.toString(); logger.info("Client sent bad request ({})", errMsg); } else if (t instanceof SAXParseException) { ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_DATA, t.getMessage()); statusCode = SC_BAD_REQUEST; errMsg = errInfo.toString(); logger.info("Client sent bad request ({})", errMsg); } else if (t instanceof UnsupportedQueryLanguageException) { ErrorInfo errInfo = new ErrorInfo(ErrorType.UNSUPPORTED_QUERY_LANGUAGE, t.getMessage()); statusCode = SC_BAD_REQUEST; errMsg = errInfo.toString(); logger.info("Client sent bad request ({})", errMsg); } else if (t instanceof MalformedQueryException) { ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_QUERY, t.getMessage()); statusCode = SC_BAD_REQUEST; errMsg = errInfo.toString(); logger.info("Client sent bad request ({})", errMsg); } else { statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; errMsg = t.getMessage(); logger.error("Unexpected error while handling request", t); } response.setStatus(statusCode); if (response.getContentType() == null) { // there seems to be a bug in spring that causes getContentType() to be ignored response.setContentType(getContentType()); } PrintWriter writer = response.getWriter(); try { writer.println(errMsg); } finally { writer.close(); } }
public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception { Throwable t = (Throwable)model.get(THROWABLE_KEY); int statusCode; String errMsg; HTTPException httpExc = findHTTPException(t); if (httpExc != null) { statusCode = httpExc.getStatusCode(); errMsg = httpExc.getMessage(); if (httpExc instanceof ClientHTTPException) { logger.info("Client sent bad request ({}): {}", statusCode, errMsg); } else { logger.error("Error while handling request ({}): {}", statusCode, errMsg); } } else if (t instanceof RDFParseException) { ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_DATA, t.getMessage()); statusCode = SC_BAD_REQUEST; errMsg = errInfo.toString(); logger.info("Client sent bad request ({})", errMsg); } else if (t instanceof SAXParseException) { ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_DATA, t.getMessage()); statusCode = SC_BAD_REQUEST; errMsg = errInfo.toString(); logger.info("Client sent bad request ({})", errMsg); } else if (t instanceof UnsupportedQueryLanguageException) { ErrorInfo errInfo = new ErrorInfo(ErrorType.UNSUPPORTED_QUERY_LANGUAGE, t.getMessage()); statusCode = SC_BAD_REQUEST; errMsg = errInfo.toString(); logger.info("Client sent bad request ({})", errMsg); } else if (t instanceof MalformedQueryException) { ErrorInfo errInfo = new ErrorInfo(ErrorType.MALFORMED_QUERY, t.getMessage()); statusCode = SC_BAD_REQUEST; errMsg = errInfo.toString(); logger.info("Client sent bad request ({})", errMsg); } else { statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; errMsg = t.getMessage(); logger.error("Unexpected error while handling request", t); } response.setStatus(statusCode); if (response.getContentType() == null) { // there seems to be a bug in spring that causes getContentType() to be ignored response.setContentType(getContentType()); } PrintWriter writer = response.getWriter(); try { writer.println(errMsg); } finally { writer.close(); } }
diff --git a/RequirementManager/src/edu/wpi/cs/wpisuitetng/modules/RequirementManager/models/Requirement.java b/RequirementManager/src/edu/wpi/cs/wpisuitetng/modules/RequirementManager/models/Requirement.java index 5552211c..b7782b97 100644 --- a/RequirementManager/src/edu/wpi/cs/wpisuitetng/modules/RequirementManager/models/Requirement.java +++ b/RequirementManager/src/edu/wpi/cs/wpisuitetng/modules/RequirementManager/models/Requirement.java @@ -1,581 +1,581 @@ package edu.wpi.cs.wpisuitetng.modules.RequirementManager.models; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import edu.wpi.cs.wpisuitetng.modules.AbstractModel; import edu.wpi.cs.wpisuitetng.modules.RequirementManager.models.characteristics.AcceptanceTest; import edu.wpi.cs.wpisuitetng.modules.RequirementManager.models.characteristics.Attachment; import edu.wpi.cs.wpisuitetng.modules.RequirementManager.models.characteristics.DevelopmentTask; import edu.wpi.cs.wpisuitetng.modules.RequirementManager.models.characteristics.Iteration; import edu.wpi.cs.wpisuitetng.modules.RequirementManager.models.characteristics.Note; import edu.wpi.cs.wpisuitetng.modules.RequirementManager.models.characteristics.RequirementPriority; import edu.wpi.cs.wpisuitetng.modules.RequirementManager.models.characteristics.RequirementStatus; import edu.wpi.cs.wpisuitetng.modules.RequirementManager.models.characteristics.RequirementType; import edu.wpi.cs.wpisuitetng.modules.RequirementManager.models.characteristics.TransactionHistory; /** * Basic Requirement class * * @author david * */ public class Requirement extends AbstractModel { /** the ID of the requirement */ private int id; //TODO: move ID stuff to server side? /** the name of the requirement */ private String name; /** the release number of the requirement */ private String release; /** the project status of the requirement */ private RequirementStatus status; /** the priority of the requirement */ private RequirementPriority priority; /** a short description of the requirement */ private String description; /** the estimated amount of time to complete the requirement */ private int estimate; /** the actual effort of completing the requirement */ private int actualEffort; /** a flag indicating if the requirement is active or deleted */ private boolean activeStatus; /** history of transactions of the requirement */ private TransactionHistory history; /** the type of the requirement */ private RequirementType type; /** subrequirements that must be completed before the current requirement is considered complete */ private List<Requirement> subRequirements; /** notes associated with the requirement */ private List<Note> notes; /** iteration the requirement is assigned to */ private Iteration iteration; /** team members the requirement is assigned to * need to figure out the class of a user name, then use that instead of TeamMember */ private List<String> assignedTo; /** development tasks associated with the requirement */ private List<DevelopmentTask> tasks; /** acceptance tests associated with the requirement */ private List<AcceptanceTest> tests; /** attachments associated with the requirement */ private List<Attachment> attachments; /** * Constructs a Requirement with default characteristics */ public Requirement() { super(); name = description = ""; release = ""; status = RequirementStatus.NEW; priority = RequirementPriority.BLANK; estimate = actualEffort = 0; activeStatus = true; history = new TransactionHistory(); - setIteration(new Iteration("Backlog")); + iteration = (new Iteration("Backlog")); type = RequirementType.BLANK; notes = new ArrayList<Note>(); tasks = new ArrayList<DevelopmentTask>(); tests = new ArrayList<AcceptanceTest>(); attachments = new ArrayList<Attachment>(); } /** * Construct a Requirement with required properties provided and others set to default * * @param id The ID number of the requirement * @param name The name of the requirement * @param description A short description of the requirement */ // need to phase out supplying the ID public Requirement(int id, String name, String description) { this(); this.id = id; this.name = name; this.description = description; } /** * Constructs a requirement from the provided characteristics * * @param id The ID number of the requirement * @param name The name of the requirement * @param release The release number of the requirement * @param status The status of the requirement * @param description A short description of the requirement * @param estimate The estimated time required by the task. This is in a point system decided by the user * @param effort The estimated amount of work required by the requirement. * @deprecated */ @Deprecated public Requirement(int id, String name, String release, RequirementStatus status, RequirementPriority priority, String description, int estimate, int effort){ this.id = id; this.name = name; this.release = release; this.status = status; this.priority = priority; this.description = description; this.estimate = estimate; this.actualEffort = effort; } /** * Returns an instance of Requirement constructed using the given * Requirement encoded as a JSON string. * * @param the JSON-encoded Requirement to deserialize * @return the Requirement contained in the given JSON */ public static Requirement fromJson(String json) { final Gson parser = new Gson(); return parser.fromJson(json, Requirement.class); } /** /**Getter for id * * @return the id */ public int getId() { return id; } /**Setter for the id * * @param id the id to set */ public void setId(int id) { this.id = id; } /**getter for the id * * @return the name */ public String getName() { return name; } /**setter for the name * * @param name the name to set */ public void setName(String name) { this.name = name; if(name.length() > 100) this.name = name.substring(0, 100); } /**getter for the name * * @return the release */ public String getRelease() { return release; } /**Setter for the release number * * @param release the release to set */ public void setRelease(String release) { this.release = release; } /**Getter for the release number * * @return the status */ public RequirementStatus getStatus() { return status; } /**Setter for the status * * @param status the status to set */ public void setStatus(RequirementStatus status) { if (status != this.status){ String originalStatus = this.status.name(); String newStatus = status.name(); String message = ("Changed status from " + originalStatus + " to " + newStatus); this.history.add(message); } this.status = status; } /**Getter for the description * * @return the description */ public String getDescription() { return description; } /**Setter for the description * * @param description the description to set */ public void setDescription(String description) { this.description = description; } /**Getter for the estimate * * @return the estimate */ public int getEstimate() { return estimate; } /**Setter for the estimate * * @param estimate the estimate to set */ public void setEstimate(int estimate) { this.estimate = estimate; } /**Getter for the estimate * * @return the effort */ public int getEffort() { return actualEffort; } /**Setter for the effort * * @param effort the effort to set */ public void setEffort(int effort) { this.actualEffort = effort; } /**Getter for the priority * * @return the priority */ public RequirementPriority getPriority() { return priority; } /**Setter for the priority * * @param priority the priority to set */ public void setPriority(RequirementPriority priority) { if (priority != this.priority){ String originalPriority = this.priority.name(); String newPriority = priority.name(); String message = ("Changed priority from " + originalPriority + " to " + newPriority); this.history.add(message); } this.priority = priority; } /**Getter for the type * * @return the type */ public RequirementType getType() { return type; } /**Setter for the type * * @param type the type to set the requirement to */ public void setType(RequirementType type) { this.type = type; } /**Getter for the sub-requirements * * @return a list of the sub-requirements */ public List<Requirement> getSubRequirements(){ return subRequirements; } /**Method to add a requirement to the list of sub-requirements * * @param requirement Requirement to add */ public void addSubRequirement(Requirement subRequirement){ this.subRequirements.add(subRequirement); } /** Method to remove a requirement to the list of sub-requirements * * @param id The id of the requirement to be remove from the list of sub-requirements */ public void removeSubRequirement (int id){ // iterate through the list looking for the requirement to remove for (int i=0; i < this.subRequirements.size(); i++){ if (subRequirements.get(i).getId() == id){ // remove the id subRequirements.remove(i); break; } } } /** Getter for the notes * * @return the list of notes associated with the requirement */ public List<Note> getNotes(){ return notes; } /** Method to add a note to the list of notes * * @param note The note to add to the list */ public void addNote(Note note){ notes.add(note); } /** Method to remove a note from a list of notes * * @param id The id of the note to be deleted */ public void removeNote(int id){ // iterate through the list looking for the note to remove for (int i=0; i < this.notes.size(); i++){ if (notes.get(i).getId() == id){ // remove the id notes.remove(i); break; } } } /** Getter for the list of development tasks * * @return the list of development tasks */ public List<DevelopmentTask> getTasks(){ return tasks; } /** Method to add a development task * * @param task the task to be added to the list of development tasks */ public void addTask(DevelopmentTask task){ tasks.add(task); } /** Method to remove a development task * * @param */ public void removeTask(int id){ // iterate through the list looking for the note to remove for (int i=0; i < this.tasks.size(); i++){ if (tasks.get(i).getId() == id){ // remove the id tasks.remove(i); break; } } } /** Getter for AcceptanceTests * * @return the list of acceptance tests for the requirement */ public List<AcceptanceTest> getTests(){ return tests; } /** Method for adding an Acceptance Test * * @param test the acceptance test to implement */ public void addTest(AcceptanceTest test){ tests.add(test); } /** Method for removing an Acceptance Test * * @param id the id of the test to remove */ public void removeTest(int id){ // iterate through the list looking for the note to remove for (int i=0; i < this.tests.size(); i++){ if (tests.get(i).getId() == id){ // remove the id tests.remove(i); break; } } } /** Getter for attachments * * @return the list of attachments */ public List<Attachment> getAttachments(){ return attachments; } /** Method to add an attachment * * @param attachment Attachment to add */ public void addAttachment(Attachment attachment){ attachments.add(attachment); } /** Method to remove an attachment * * @param id ID of the attachment to be removed */ public void removeAttachment(int id){ // iterate through the list looking for the note to remove for (int i=0; i < this.attachments.size(); i++){ if (attachments.get(i).getId() == id){ // remove the id attachments.remove(i); break; } } } /** Getter for Iteration. Currently deals in Strings, but will deal with Iterations in the future * * @return a string representing the iteration it has been assigned to */ public Iteration getIteration() { return iteration; } /** Setter for iteration. Currently deals with strings, but will deal with Iterations in the future. * * @param iteration the iteration to assign the requirement to */ public void setIteration(Iteration newIteration) { if(this.iteration == null) this.iteration = newIteration; if (!this.iteration.equals(newIteration)){ String originalIteration = this.iteration.toString(); String newIterationString = newIteration.toString(); String message = ("Moved from " + originalIteration + " to " + newIterationString); this.history.add(message); } this.iteration = newIteration; } /** Getter for AssignedTo * * @return the list of strings representing the users for whom the requirement has been assigned to. */ public List<String> getAssignedTo() { return assignedTo; } /**Setter for assignedTo * * @param assignedTo the list of strings representing the people who the requirement is assigned to. */ public void setAssignedTo(List<String> assignedTo) { this.assignedTo = assignedTo; } /**Sets a flag in the requirement to indicate it's deleted */ public void remove() { this.activeStatus = false; } @Override public void save() { // TODO Auto-generated method stub } @Override public void delete() { // TODO Auto-generated method stub } @Override /**This returns a Json encoded String representation of this requirement object. * * @return a Json encoded String representation of this requirement * */ public String toJSON() { return new Gson().toJson(this, Requirement.class); } /** * Returns an array of Requirements parsed from the given JSON-encoded * string. * * @param a string containing a JSON-encoded array of Requirement * @return an array of Requirement deserialzied from the given JSON string */ public static Requirement[] fromJsonArray(String json) { final Gson parser = new Gson(); return parser.fromJson(json, Requirement[].class); } @Override public Boolean identify(Object o) { // TODO Auto-generated method stub return null; } @Override public String toString() { return this.getName(); } /** * Returns whether the requirement has been deleted. * @return delete status of the requirement. */ public boolean isDeleted() { return !activeStatus; } /** The getter for Transaction History * * @return a TransdactionHistory for this requirement */ public TransactionHistory getHistory() { return history; } /** The Setter for TransactionHistory * * @param history The history to assign to the requirement */ public void setHistory(TransactionHistory history) { this.history = history; } }
true
true
public Requirement() { super(); name = description = ""; release = ""; status = RequirementStatus.NEW; priority = RequirementPriority.BLANK; estimate = actualEffort = 0; activeStatus = true; history = new TransactionHistory(); setIteration(new Iteration("Backlog")); type = RequirementType.BLANK; notes = new ArrayList<Note>(); tasks = new ArrayList<DevelopmentTask>(); tests = new ArrayList<AcceptanceTest>(); attachments = new ArrayList<Attachment>(); }
public Requirement() { super(); name = description = ""; release = ""; status = RequirementStatus.NEW; priority = RequirementPriority.BLANK; estimate = actualEffort = 0; activeStatus = true; history = new TransactionHistory(); iteration = (new Iteration("Backlog")); type = RequirementType.BLANK; notes = new ArrayList<Note>(); tasks = new ArrayList<DevelopmentTask>(); tests = new ArrayList<AcceptanceTest>(); attachments = new ArrayList<Attachment>(); }
diff --git a/hale/eu.esdihumboldt.hale.io.gml.test/src/eu/esdihumboldt/hale/io/gml/reader/internal/GmlInstanceCollectionTest.java b/hale/eu.esdihumboldt.hale.io.gml.test/src/eu/esdihumboldt/hale/io/gml/reader/internal/GmlInstanceCollectionTest.java index 6eb5a79da..c7f7b76b2 100644 --- a/hale/eu.esdihumboldt.hale.io.gml.test/src/eu/esdihumboldt/hale/io/gml/reader/internal/GmlInstanceCollectionTest.java +++ b/hale/eu.esdihumboldt.hale.io.gml.test/src/eu/esdihumboldt/hale/io/gml/reader/internal/GmlInstanceCollectionTest.java @@ -1,144 +1,144 @@ /* * HUMBOLDT: A Framework for Data Harmonisation and Service Integration. * EU Integrated Project #030962 01.10.2006 - 30.09.2010 * * For more information on the project, please refer to the this web site: * http://www.esdi-humboldt.eu * * LICENSE: For information on the license under which this program is * available, please refer to http:/www.esdi-humboldt.eu/license.html#core * (c) the HUMBOLDT Consortium, 2007 to 2010. */ package eu.esdihumboldt.hale.io.gml.reader.internal; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.net.URI; import javax.xml.namespace.QName; import org.junit.Test; import eu.esdihumboldt.hale.core.io.IOProviderConfigurationException; import eu.esdihumboldt.hale.core.io.report.IOReport; import eu.esdihumboldt.hale.core.io.supplier.DefaultInputSupplier; import eu.esdihumboldt.hale.instance.model.Instance; import eu.esdihumboldt.hale.instance.model.ResourceIterator; import eu.esdihumboldt.hale.io.xsd.reader.XmlSchemaReader; import eu.esdihumboldt.hale.schema.io.SchemaReader; import eu.esdihumboldt.hale.schema.model.Schema; /** * Tests for {@link GmlInstanceCollection} * * @author Simon Templer * @partner 01 / Fraunhofer Institute for Computer Graphics Research */ @SuppressWarnings("restriction") public class GmlInstanceCollectionTest { /** * Test loading a simple XML file with one instance * * @throws Exception if an error occurs */ @Test public void testLoadShiporder() throws Exception { GmlInstanceCollection instances = loadInstances( getClass().getResource("/data/shiporder/shiporder.xsd").toURI(), getClass().getResource("/data/shiporder/shiporder.xml").toURI()); String ns = "http://www.example.com"; ResourceIterator<Instance> it = instances.iterator(); assertTrue(it.hasNext()); Instance instance = it.next(); assertNotNull(instance); Object[] orderid = instance.getProperty(new QName("orderid")); // attribute form not qualified assertNotNull(orderid); assertEquals(1, orderid.length); assertEquals("889923", orderid[0]); Object[] orderperson = instance.getProperty(new QName(ns, "orderperson")); assertNotNull(orderperson); assertEquals(1, orderperson.length); assertEquals("John Smith", orderperson[0]); Object[] shipto = instance.getProperty(new QName(ns, "shipto")); assertNotNull(shipto); assertEquals(1, shipto.length); assertTrue(shipto[0] instanceof Instance); Instance shipto1 = (Instance) shipto[0]; Object[] shiptoName = shipto1.getProperty(new QName(ns, "name")); assertNotNull(shiptoName); assertEquals(1, shiptoName.length); assertEquals("Ola Nordmann", shiptoName[0]); Object[] shiptoAddress = shipto1.getProperty(new QName(ns, "address")); assertNotNull(shiptoAddress); assertEquals(1, shiptoAddress.length); assertEquals("Langgt 23", shiptoAddress[0]); Object[] shiptoCity = shipto1.getProperty(new QName(ns, "city")); assertNotNull(shiptoCity); assertEquals(1, shiptoCity.length); assertEquals("4000 Stavanger", shiptoCity[0]); Object[] shiptoCountry = shipto1.getProperty(new QName(ns, "country")); assertNotNull(shiptoCountry); assertEquals(1, shiptoCountry.length); assertEquals("Norway", shiptoCountry[0]); // items Object[] items = instance.getProperty(new QName(ns, "item")); assertNotNull(items); assertEquals(2, items.length); // item 1 Object item1 = items[0]; assertTrue(item1 instanceof Instance); Object[] title1 = ((Instance) item1).getProperty(new QName(ns, "title")); assertNotNull(title1); assertEquals(1, title1.length); assertEquals("Empire Burlesque", title1[0]); // item 2 Object item2 = items[1]; assertTrue(item2 instanceof Instance); - Object[] title2 = ((Instance) item1).getProperty(new QName(ns, "title")); + Object[] title2 = ((Instance) item2).getProperty(new QName(ns, "title")); assertNotNull(title2); assertEquals(1, title2.length); assertEquals("Hide your heart", title2[0]); // only one object assertFalse(it.hasNext()); it.dispose(); } private GmlInstanceCollection loadInstances(URI schemaLocation, URI xmlLocation) throws IOException, IOProviderConfigurationException { SchemaReader reader = new XmlSchemaReader(); reader.setSharedTypes(null); reader.setSource(new DefaultInputSupplier(schemaLocation)); IOReport schemaReport = reader.execute(null); assertTrue(schemaReport.isSuccess()); Schema sourceSchema = reader.getSchema(); return new GmlInstanceCollection( new DefaultInputSupplier(xmlLocation), sourceSchema, null); //XXX content type currently not needed } }
true
true
public void testLoadShiporder() throws Exception { GmlInstanceCollection instances = loadInstances( getClass().getResource("/data/shiporder/shiporder.xsd").toURI(), getClass().getResource("/data/shiporder/shiporder.xml").toURI()); String ns = "http://www.example.com"; ResourceIterator<Instance> it = instances.iterator(); assertTrue(it.hasNext()); Instance instance = it.next(); assertNotNull(instance); Object[] orderid = instance.getProperty(new QName("orderid")); // attribute form not qualified assertNotNull(orderid); assertEquals(1, orderid.length); assertEquals("889923", orderid[0]); Object[] orderperson = instance.getProperty(new QName(ns, "orderperson")); assertNotNull(orderperson); assertEquals(1, orderperson.length); assertEquals("John Smith", orderperson[0]); Object[] shipto = instance.getProperty(new QName(ns, "shipto")); assertNotNull(shipto); assertEquals(1, shipto.length); assertTrue(shipto[0] instanceof Instance); Instance shipto1 = (Instance) shipto[0]; Object[] shiptoName = shipto1.getProperty(new QName(ns, "name")); assertNotNull(shiptoName); assertEquals(1, shiptoName.length); assertEquals("Ola Nordmann", shiptoName[0]); Object[] shiptoAddress = shipto1.getProperty(new QName(ns, "address")); assertNotNull(shiptoAddress); assertEquals(1, shiptoAddress.length); assertEquals("Langgt 23", shiptoAddress[0]); Object[] shiptoCity = shipto1.getProperty(new QName(ns, "city")); assertNotNull(shiptoCity); assertEquals(1, shiptoCity.length); assertEquals("4000 Stavanger", shiptoCity[0]); Object[] shiptoCountry = shipto1.getProperty(new QName(ns, "country")); assertNotNull(shiptoCountry); assertEquals(1, shiptoCountry.length); assertEquals("Norway", shiptoCountry[0]); // items Object[] items = instance.getProperty(new QName(ns, "item")); assertNotNull(items); assertEquals(2, items.length); // item 1 Object item1 = items[0]; assertTrue(item1 instanceof Instance); Object[] title1 = ((Instance) item1).getProperty(new QName(ns, "title")); assertNotNull(title1); assertEquals(1, title1.length); assertEquals("Empire Burlesque", title1[0]); // item 2 Object item2 = items[1]; assertTrue(item2 instanceof Instance); Object[] title2 = ((Instance) item1).getProperty(new QName(ns, "title")); assertNotNull(title2); assertEquals(1, title2.length); assertEquals("Hide your heart", title2[0]); // only one object assertFalse(it.hasNext()); it.dispose(); }
public void testLoadShiporder() throws Exception { GmlInstanceCollection instances = loadInstances( getClass().getResource("/data/shiporder/shiporder.xsd").toURI(), getClass().getResource("/data/shiporder/shiporder.xml").toURI()); String ns = "http://www.example.com"; ResourceIterator<Instance> it = instances.iterator(); assertTrue(it.hasNext()); Instance instance = it.next(); assertNotNull(instance); Object[] orderid = instance.getProperty(new QName("orderid")); // attribute form not qualified assertNotNull(orderid); assertEquals(1, orderid.length); assertEquals("889923", orderid[0]); Object[] orderperson = instance.getProperty(new QName(ns, "orderperson")); assertNotNull(orderperson); assertEquals(1, orderperson.length); assertEquals("John Smith", orderperson[0]); Object[] shipto = instance.getProperty(new QName(ns, "shipto")); assertNotNull(shipto); assertEquals(1, shipto.length); assertTrue(shipto[0] instanceof Instance); Instance shipto1 = (Instance) shipto[0]; Object[] shiptoName = shipto1.getProperty(new QName(ns, "name")); assertNotNull(shiptoName); assertEquals(1, shiptoName.length); assertEquals("Ola Nordmann", shiptoName[0]); Object[] shiptoAddress = shipto1.getProperty(new QName(ns, "address")); assertNotNull(shiptoAddress); assertEquals(1, shiptoAddress.length); assertEquals("Langgt 23", shiptoAddress[0]); Object[] shiptoCity = shipto1.getProperty(new QName(ns, "city")); assertNotNull(shiptoCity); assertEquals(1, shiptoCity.length); assertEquals("4000 Stavanger", shiptoCity[0]); Object[] shiptoCountry = shipto1.getProperty(new QName(ns, "country")); assertNotNull(shiptoCountry); assertEquals(1, shiptoCountry.length); assertEquals("Norway", shiptoCountry[0]); // items Object[] items = instance.getProperty(new QName(ns, "item")); assertNotNull(items); assertEquals(2, items.length); // item 1 Object item1 = items[0]; assertTrue(item1 instanceof Instance); Object[] title1 = ((Instance) item1).getProperty(new QName(ns, "title")); assertNotNull(title1); assertEquals(1, title1.length); assertEquals("Empire Burlesque", title1[0]); // item 2 Object item2 = items[1]; assertTrue(item2 instanceof Instance); Object[] title2 = ((Instance) item2).getProperty(new QName(ns, "title")); assertNotNull(title2); assertEquals(1, title2.length); assertEquals("Hide your heart", title2[0]); // only one object assertFalse(it.hasNext()); it.dispose(); }
diff --git a/src/main/java/hudson/ivy/IvyModule.java b/src/main/java/hudson/ivy/IvyModule.java index d4eacf9..c381348 100644 --- a/src/main/java/hudson/ivy/IvyModule.java +++ b/src/main/java/hudson/ivy/IvyModule.java @@ -1,496 +1,497 @@ /* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, id:cactusman * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.ivy; import hudson.CopyOnWrite; import hudson.Functions; import hudson.Util; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.DependencyGraph; import hudson.model.Descriptor; import hudson.model.Hudson; import hudson.model.Item; import hudson.model.ItemGroup; import hudson.model.JDK; import hudson.model.Job; import hudson.model.Label; import hudson.model.Node; import hudson.model.Resource; import hudson.model.Result; import hudson.model.Saveable; import hudson.model.DependencyGraph.Dependency; import hudson.model.Descriptor.FormException; import hudson.tasks.BuildStepDescriptor; import hudson.tasks.LogRotator; import hudson.tasks.Publisher; import hudson.util.DescribableList; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import org.apache.commons.lang.StringUtils; import org.apache.ivy.core.module.id.ModuleRevisionId; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; import org.kohsuke.stapler.export.Exported; /** * {@link Job} that builds projects based on Ivy. * * @author Timothy Bingaman */ public final class IvyModule extends AbstractIvyProject<IvyModule, IvyBuild> implements Saveable { private static final String IVY_XML_PATH = "ivy.xml"; private DescribableList<Publisher, Descriptor<Publisher>> publishers = new DescribableList<Publisher, Descriptor<Publisher>>(this); /** * Name taken from {@link ModuleRevisionId#getName()}. */ private String displayName; /** * Revision number of this module as of the last build, taken from * {@link ModuleRevisionId#getRevision()}. * * This field can be null if Hudson loaded old data that didn't record this * information, so that situation needs to be handled gracefully. */ private String revision; /** * Ivy branch of this module as of the last build, taken from * {@link ModuleRevisionId#getBranch()}. * * This field can be null if Hudson loaded old data that didn't record this * information, so that situation needs to be handled gracefully. */ private String ivyBranch; private transient ModuleName moduleName; /** * Relative path from the workspace to the ivy descriptor file for this * module. * * Strings like "ivy.xml" (if the ivy.xml file is checked out directly in * the workspace), "abc/ivy.xml", "foo/bar/zot/ivy.xml". */ private String relativePathToDescriptorFromWorkspace; /** * If this module has targets specified by itself. Otherwise leave it null * to use the default targets specified in the parent. */ private String targets; /** * Relative path from the workspace to the ivy descriptor file for this * module. * * Strings like "ivy.xml" (if the ivy.xml file is directly in * the module root), "ivy/ivy.xml", "build/ivy.xml". */ private String relativePathToDescriptorFromModuleRoot; /** * List of modules that this module declares direct dependencies on. */ @CopyOnWrite private volatile Set<ModuleDependency> dependencies; /* package */IvyModule(IvyModuleSet parent, IvyModuleInfo moduleInfo, int firstBuildNumber) throws IOException { super(parent, moduleInfo.name.toFileSystemName()); reconfigure(moduleInfo); updateNextBuildNumber(firstBuildNumber); } /** * {@link IvyModule} follows the same log rotation schedule as its parent. */ @Override public LogRotator getLogRotator() { return getParent().getLogRotator(); } /** * @deprecated Not allowed to configure log rotation per module. */ @Deprecated @Override public void setLogRotator(LogRotator logRotator) { throw new UnsupportedOperationException(); } @Override public boolean supportsLogRotator() { return false; } @Override public boolean isBuildable() { // not buildable if the parent project is disabled return super.isBuildable() && getParent().isBuildable(); } /** * Called to update the module with the new ivy.xml information. * <p> * This method is invoked on {@link IvyModule} that has the matching * {@link ModuleName}. */ /* package */final void reconfigure(IvyModuleInfo moduleInfo) { this.displayName = moduleInfo.displayName; this.revision = moduleInfo.revision; this.ivyBranch = moduleInfo.branch; this.relativePathToDescriptorFromWorkspace = moduleInfo.relativePathToDescriptor; this.dependencies = moduleInfo.dependencies; disabled = false; } @Override protected void doSetName(String name) { moduleName = ModuleName.fromFileSystemName(name); super.doSetName(moduleName.toString()); } @Override public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException { super.onLoad(parent, name); if (publishers == null) publishers = new DescribableList<Publisher, Descriptor<Publisher>>(this); publishers.setOwner(this); if (dependencies == null) { dependencies = Collections.emptySet(); } } /** * Relative path to this module's root directory from the workspace of a * {@link IvyModuleSet}. * * The path separator is normalized to '/'. */ public String getRelativePath() { return relativePathToDescriptorFromWorkspace; } /** * Gets the revision number in the ivy.xml file as of the last build. * * @return This method can return null if Hudson loaded old data that didn't * record this information, so that situation needs to be handled * gracefully. */ public String getRevision() { return revision; } /** * Gets the Ivy branch in the ivy.xml file as of the last build. * * @return This method can return null if Hudson loaded old data that didn't * record this information, so that situation needs to be handled * gracefully. */ public String getIvyBranch() { return ivyBranch; } /** * Gets the list of targets to execute for this module. */ public String getTargets() { if (targets != null) return targets; return getParent().getTargets(); } public String getRelativePathToDescriptorFromModuleRoot() { if (relativePathToDescriptorFromModuleRoot != null) return relativePathToDescriptorFromModuleRoot; return getParent().getRelativePathToDescriptorFromModuleRoot(); } public String getUserConfiguredRelativePathToDescriptorFromModuleRoot() { return relativePathToDescriptorFromModuleRoot; } public String getRelativePathToModuleRoot() { return StringUtils.removeEnd(relativePathToDescriptorFromWorkspace, StringUtils.defaultString(getRelativePathToDescriptorFromModuleRoot(), IVY_XML_PATH)); } /** * Gets the list of targets specified by the user, without taking * inheritance and into account. * * <p> * This is only used to present the UI screen, and in all the other cases * {@link #getTargets()} should be used. */ public String getUserConfiguredTargets() { return targets; } @Override public DescribableList<Publisher, Descriptor<Publisher>> getPublishersList() { if (getParent().isAggregatorStyleBuild()) { return publishers; } DescribableList<Publisher, Descriptor<Publisher>> publishersList = new DescribableList<Publisher, Descriptor<Publisher>>(Saveable.NOOP); try { publishersList.addAll(createModulePublishers()); } catch (IOException e) { LOGGER.warning("Failed to load module publisher list"); } return publishersList; } @Override public JDK getJDK() { // share one setting for the whole module set. return getParent().getJDK(); } @Override protected Class<IvyBuild> getBuildClass() { return IvyBuild.class; } @Override protected IvyBuild newBuild() throws IOException { return super.newBuild(); } public ModuleName getModuleName() { return moduleName; } /** * Gets organisation+name+revision as {@link ModuleDependency}. */ public ModuleDependency asDependency() { return new ModuleDependency(moduleName, Functions.defaulted(revision, ModuleDependency.UNKNOWN), Functions.defaulted(ivyBranch, ModuleDependency.UNKNOWN)); } @Override public String getShortUrl() { return moduleName.toFileSystemName() + '/'; } @Exported(visibility = 2) @Override public String getDisplayName() { return displayName; } @Override public String getPronoun() { return Messages.IvyModule_Pronoun(); } @Override public boolean isNameEditable() { return false; } @Override public IvyModuleSet getParent() { return (IvyModuleSet) super.getParent(); } /** * {@link IvyModule} uses the workspace of the {@link IvyModuleSet}, so it * always needs to be built on the same slave as the parent. */ @Override public Label getAssignedLabel() { Node n = getParent().getLastBuiltOn(); if (n == null) return null; return n.getSelfLabel(); } /** * Workspace of a {@link IvyModule} is a part of the parent's workspace. * <p> * That is, {@Link IvyModuleSet} builds are incompatible with any * {@link IvyModule} builds, whereas {@link IvyModule} builds are compatible * with each other. * * @deprecated as of 1.319 in {@link AbstractProject}. */ @Deprecated @Override public Resource getWorkspaceResource() { return new Resource(getParent().getWorkspaceResource(), getDisplayName() + " workspace"); } @Override public boolean isFingerprintConfigured() { return true; } @Override protected void buildDependencyGraph(DependencyGraph graph) { if (isDisabled() || (getParent().ignoreUpstreamChanges() && getParent().isAggregatorStyleBuild())) return; Map<ModuleDependency, IvyModule> modules = new HashMap<ModuleDependency, IvyModule>(); if (!getParent().ignoreUpstreamChanges()) { for (IvyModule m : Hudson.getInstance().getAllItems(IvyModule.class)) { if (m.isDisabled()) continue; modules.put(m.asDependency(), m); modules.put(m.asDependency().withUnknownRevision(), m); } } // Even if ignoreUpstreamChanges is true we still need to calculate the // dependencies between the modules of this project. Also, in case two // modules with the same name are defined, modules in the same // IvyModuleSet takes precedence. for (IvyModule m : getParent().getModules()) { if (m.isDisabled()) continue; modules.put(m.asDependency(), m); modules.put(m.asDependency().withUnknownRevision(), m); } // if the build style is the aggregator build, define dependencies // against project, // not module. AbstractProject downstream = getParent().isAggregatorStyleBuild() ? getParent() : this; for (ModuleDependency d : dependencies) { IvyModule src = modules.get(d); if (src == null) src = modules.get(d.withUnknownRevision()); if (src == null) continue; AbstractProject upstream; if (src.getParent().isAggregatorStyleBuild()) { upstream = src.getParent(); } else { // Add a virtual dependency from the parent project to the // downstream one to make the // "Block build when upstream project is building" option behave // properly if (!this.getParent().equals(src.getParent()) && !hasDependency(graph, src.getParent(), downstream)) graph.addDependency(new IvyVirtualDependency(src.getParent(), downstream)); upstream = src; } - if (!hasDependency(graph, upstream, downstream)) + // Create the build dependency, ignoring self-referencing or already existing deps + if (upstream != downstream && !hasDependency(graph, upstream, downstream)) graph.addDependency(new IvyThresholdDependency(upstream, downstream, Result.SUCCESS)); } } private boolean hasDependency(DependencyGraph graph, AbstractProject upstream, AbstractProject downstream) { for (Dependency dep : graph.getDownstreamDependencies(upstream)) { if (dep instanceof IvyDependency && dep.getDownstreamProject().equals(downstream)) return true; } return false; } @Override protected void addTransientActionsFromBuild(IvyBuild build, Set<Class> added) { if (build == null) return; List<IvyReporter> list = build.projectActionReporters; if (list == null) return; for (IvyReporter step : list) { if (!added.add(step.getClass())) continue; // already added try { Action a = step.getProjectAction(this); if (a != null) transientActions.add(a); } catch (Exception e) { LOGGER.log(Level.WARNING, "Failed to getProjectAction from " + step + ". Report issue to plugin developers.", e); } } } /** * List of active {@link Publisher}s configured for this module. */ public DescribableList<Publisher, Descriptor<Publisher>> getPublishers() { return publishers; } @Override protected void submit(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException, FormException { super.submit(req, rsp); targets = Util.fixEmptyAndTrim(req.getParameter("targets")); relativePathToDescriptorFromModuleRoot = Util.fixEmptyAndTrim(req.getParameter("relativePathToDescriptorFromModuleRoot")); publishers.rebuild(req,req.getSubmittedForm(),BuildStepDescriptor.filter(Publisher.all(),this.getClass())); // dependency setting might have been changed by the user, so rebuild. Hudson.getInstance().rebuildDependencyGraph(); } @Override protected void performDelete() throws IOException, InterruptedException { super.performDelete(); getParent().onModuleDeleted(this); } /** * Creates a list of {@link Publisher}s to be used for a build of this project. */ protected final List<Publisher> createModulePublishers() { List<Publisher> modulePublisherList = new ArrayList<Publisher>(); getPublishers().addAllTo(modulePublisherList); if (!getParent().isAggregatorStyleBuild()) { getParent().getPublishers().addAllTo(modulePublisherList); } return modulePublisherList; } private static final Logger LOGGER = Logger.getLogger(IvyModule.class.getName()); }
true
true
protected void buildDependencyGraph(DependencyGraph graph) { if (isDisabled() || (getParent().ignoreUpstreamChanges() && getParent().isAggregatorStyleBuild())) return; Map<ModuleDependency, IvyModule> modules = new HashMap<ModuleDependency, IvyModule>(); if (!getParent().ignoreUpstreamChanges()) { for (IvyModule m : Hudson.getInstance().getAllItems(IvyModule.class)) { if (m.isDisabled()) continue; modules.put(m.asDependency(), m); modules.put(m.asDependency().withUnknownRevision(), m); } } // Even if ignoreUpstreamChanges is true we still need to calculate the // dependencies between the modules of this project. Also, in case two // modules with the same name are defined, modules in the same // IvyModuleSet takes precedence. for (IvyModule m : getParent().getModules()) { if (m.isDisabled()) continue; modules.put(m.asDependency(), m); modules.put(m.asDependency().withUnknownRevision(), m); } // if the build style is the aggregator build, define dependencies // against project, // not module. AbstractProject downstream = getParent().isAggregatorStyleBuild() ? getParent() : this; for (ModuleDependency d : dependencies) { IvyModule src = modules.get(d); if (src == null) src = modules.get(d.withUnknownRevision()); if (src == null) continue; AbstractProject upstream; if (src.getParent().isAggregatorStyleBuild()) { upstream = src.getParent(); } else { // Add a virtual dependency from the parent project to the // downstream one to make the // "Block build when upstream project is building" option behave // properly if (!this.getParent().equals(src.getParent()) && !hasDependency(graph, src.getParent(), downstream)) graph.addDependency(new IvyVirtualDependency(src.getParent(), downstream)); upstream = src; } if (!hasDependency(graph, upstream, downstream)) graph.addDependency(new IvyThresholdDependency(upstream, downstream, Result.SUCCESS)); } }
protected void buildDependencyGraph(DependencyGraph graph) { if (isDisabled() || (getParent().ignoreUpstreamChanges() && getParent().isAggregatorStyleBuild())) return; Map<ModuleDependency, IvyModule> modules = new HashMap<ModuleDependency, IvyModule>(); if (!getParent().ignoreUpstreamChanges()) { for (IvyModule m : Hudson.getInstance().getAllItems(IvyModule.class)) { if (m.isDisabled()) continue; modules.put(m.asDependency(), m); modules.put(m.asDependency().withUnknownRevision(), m); } } // Even if ignoreUpstreamChanges is true we still need to calculate the // dependencies between the modules of this project. Also, in case two // modules with the same name are defined, modules in the same // IvyModuleSet takes precedence. for (IvyModule m : getParent().getModules()) { if (m.isDisabled()) continue; modules.put(m.asDependency(), m); modules.put(m.asDependency().withUnknownRevision(), m); } // if the build style is the aggregator build, define dependencies // against project, // not module. AbstractProject downstream = getParent().isAggregatorStyleBuild() ? getParent() : this; for (ModuleDependency d : dependencies) { IvyModule src = modules.get(d); if (src == null) src = modules.get(d.withUnknownRevision()); if (src == null) continue; AbstractProject upstream; if (src.getParent().isAggregatorStyleBuild()) { upstream = src.getParent(); } else { // Add a virtual dependency from the parent project to the // downstream one to make the // "Block build when upstream project is building" option behave // properly if (!this.getParent().equals(src.getParent()) && !hasDependency(graph, src.getParent(), downstream)) graph.addDependency(new IvyVirtualDependency(src.getParent(), downstream)); upstream = src; } // Create the build dependency, ignoring self-referencing or already existing deps if (upstream != downstream && !hasDependency(graph, upstream, downstream)) graph.addDependency(new IvyThresholdDependency(upstream, downstream, Result.SUCCESS)); } }
diff --git a/src/org/apache/fop/layout/LineArea.java b/src/org/apache/fop/layout/LineArea.java index 6393dc607..9aca8b1ee 100644 --- a/src/org/apache/fop/layout/LineArea.java +++ b/src/org/apache/fop/layout/LineArea.java @@ -1,934 +1,937 @@ /*-- $Id$ -- ============================================================================ The Apache Software License, Version 1.1 ============================================================================ Copyright (C) 1999 The Apache Software Foundation. All rights reserved. Redistribution and use in source and binary forms, with or without modifica- tion, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: "This product includes software developed by the Apache Software Foundation (http://www.apache.org/)." Alternately, this acknowledgment may appear in the software itself, if and wherever such third-party acknowledgments normally appear. 4. The names "FOP" and "Apache Software Foundation" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact [email protected]. 5. Products derived from this software may not be called "Apache", nor may "Apache" appear in their name, without prior written permission of the Apache Software Foundation. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLU- DING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This software consists of voluntary contributions made by many individuals on behalf of the Apache Software Foundation and was originally created by James Tauber <[email protected]>. For more information on the Apache Software Foundation, please see <http://www.apache.org/>. */ package org.apache.fop.layout; //fop import org.apache.fop.render.Renderer; import org.apache.fop.messaging.MessageHandler; import org.apache.fop.layout.LeaderArea; import org.apache.fop.datatypes.IDNode; import org.apache.fop.fo.properties.WrapOption; import org.apache.fop.fo.properties.WhiteSpaceCollapse; import org.apache.fop.fo.properties.TextAlign; import org.apache.fop.fo.properties.TextAlignLast; import org.apache.fop.fo.properties.LeaderPattern; import org.apache.fop.fo.properties.Hyphenate; import org.apache.fop.fo.properties.CountryMaker; import org.apache.fop.fo.properties.LanguageMaker; import org.apache.fop.fo.properties.LeaderAlignment; import org.apache.fop.layout.hyphenation.Hyphenation; import org.apache.fop.layout.hyphenation.Hyphenator; //java import java.util.Vector; import java.util.Enumeration; import java.awt.Rectangle; public class LineArea extends Area { protected int lineHeight; protected int halfLeading; protected int nominalFontSize; protected int nominalGlyphHeight; protected int allocationHeight; protected int startIndent; protected int endIndent; private int placementOffset; private FontState currentFontState; // not the nominal, which is // in this.fontState private float red, green, blue; private int wrapOption; private int whiteSpaceCollapse; /*hyphenation*/ protected int hyphenate; protected char hyphenationChar; protected int hyphenationPushCharacterCount; protected int hyphenationRemainCharacterCount; protected String language; protected String country; /* the width of text that has definitely made it into the line area */ protected int finalWidth = 0; /* the position to shift a link rectangle in order to compensate for links embedded within a word*/ protected int embeddedLinkStart = 0; /* the width of the current word so far */ protected int wordWidth = 0; /* values that prev (below) may take */ protected static final int NOTHING = 0; protected static final int WHITESPACE = 1; protected static final int TEXT = 2; /* the character type of the previous character */ protected int prev = NOTHING; /* the position in data[] of the start of the current word */ protected int wordStart; /* the length (in characters) of the current word */ protected int wordLength = 0; /* width of spaces before current word */ protected int spaceWidth = 0; /* the inline areas that have not yet been added to the line because subsequent characters to come (in a different addText) may be part of the same word */ protected Vector pendingAreas = new Vector(); /* the width of the pendingAreas */ protected int pendingWidth = 0; public LineArea(FontState fontState, int lineHeight, int halfLeading, int allocationWidth, int startIndent, int endIndent, LineArea prevLineArea) { super(fontState); this.currentFontState = fontState; this.lineHeight = lineHeight; this.nominalFontSize = fontState.getFontSize(); this.nominalGlyphHeight = fontState.getAscender() - fontState.getDescender(); this.placementOffset = fontState.getAscender(); this.contentRectangleWidth = allocationWidth - startIndent - endIndent; this.fontState = fontState; this.allocationHeight = this.nominalGlyphHeight; this.halfLeading = this.lineHeight - this.allocationHeight; this.startIndent = startIndent; this.endIndent = endIndent; if (prevLineArea != null) { Enumeration e = prevLineArea.pendingAreas.elements(); while (e.hasMoreElements()) { pendingAreas.addElement(e.nextElement()); } pendingWidth = prevLineArea.getPendingWidth(); } } public void render(Renderer renderer) { renderer.renderLineArea(this); } public int addPageNumberCitation(String refid, LinkSet ls) { /* We should add code here to handle the case where the page number doesn't fit on the current line */ //Space must be alloted to the page number, so currently we give it 3 spaces int width = currentFontState.width(32) * 3; PageNumberInlineArea pia = new PageNumberInlineArea(currentFontState, this.red, this.green, this.blue, refid, width); pendingAreas.addElement(pia); pendingWidth += width; wordWidth = 0; prev = TEXT; return -1; } /** * adds text to line area * * @return int character position */ public int addText(char odata[], int start, int end, LinkSet ls, boolean ul) { + // this prevents an array index out of bounds + // which occurs when some text is laid out again. + if(start == -1) return -1; boolean overrun = false; wordStart = start; wordLength = 0; wordWidth = 0; char[] data = new char[odata.length]; for (int count = 0; count < odata.length; count++) { data[count] = odata[count]; } /* iterate over each character */ for (int i = start; i < end; i++) { int charWidth; /* get the character */ char c = data[i]; if (c > 127) { /* this class shouldn't be hard coded */ char d = org.apache.fop.render.pdf.CodePointMapping.map[c]; if (d != 0) { c = data[i] = d; } else { MessageHandler.error("ch" + (int) c + "?"); c = data[i] = '#'; } } charWidth = currentFontState.width(c); if ((c == ' ') || (c == '\n') || (c == '\r') || (c == '\t')) { // whitespace if (prev == WHITESPACE) { // if current & previous are WHITESPACE if (this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE) { if (c == ' ') { spaceWidth += currentFontState.width(32); } else if (c == '\n') { // force line break return i; } else if (c == '\t') { spaceWidth += 8 * currentFontState.width(32); } } // else ignore it } else if (prev == TEXT) { // if current is WHITESPACE and previous TEXT // the current word made it, so // add the space before the current word (if there // was some) if (spaceWidth > 0) { addChild(new InlineSpace(spaceWidth)); finalWidth += spaceWidth; spaceWidth = 0; } // add any pending areas Enumeration e = pendingAreas.elements(); while (e.hasMoreElements()) { Box box = (Box) e.nextElement(); if (box instanceof InlineArea) { if (ls != null) { Rectangle lr = new Rectangle(finalWidth, 0, ((InlineArea) box). getContentWidth(), fontState.getFontSize()); ls.addRect(lr, this); } } addChild(box); } finalWidth += pendingWidth; // reset pending areas array pendingWidth = 0; pendingAreas = new Vector(); // add the current word if (wordLength > 0) { InlineArea ia = new InlineArea(currentFontState, this.red, this.green, this.blue, new String(data, wordStart, wordLength), wordWidth); ia.setUnderlined(ul); addChild(ia); if (ls != null) { Rectangle lr = new Rectangle(finalWidth, 0, ia.getContentWidth(), fontState.getFontSize()); ls.addRect(lr, this); } finalWidth += wordWidth; // reset word width wordWidth = 0; } // deal with this new whitespace following the // word we just added prev = WHITESPACE; embeddedLinkStart = 0; //reset embeddedLinkStart since a space was encountered spaceWidth = currentFontState.width(32); /* here is the place for space-treatment value 'ignore': if (this.spaceTreatment == SpaceTreatment.IGNORE) { // do nothing } else { spaceWidth = currentFontState.width(32); } */ if (this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE) { if (c == '\n') { // force a line break return i; } else if (c == '\t') { spaceWidth = currentFontState.width(32); } } } else { // if current is WHITESPACE and no previous if (this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE) { prev = WHITESPACE; spaceWidth = currentFontState.width(32); } else { // skip over it start++; } } } else { // current is TEXT if (prev == WHITESPACE) { // if current is TEXT and previous WHITESPACE wordWidth = charWidth; if ((finalWidth + spaceWidth + wordWidth) > this.getContentWidth()) { if (overrun) MessageHandler.error(">"); if (this.wrapOption == WrapOption.WRAP) return i; } prev = TEXT; wordStart = i; wordLength = 1; } else if (prev == TEXT) { wordLength++; wordWidth += charWidth; } else { // nothing previous prev = TEXT; wordStart = i; wordLength = 1; wordWidth = charWidth; } if ((finalWidth + spaceWidth + pendingWidth + wordWidth) > this.getContentWidth()) { // BREAK MID WORD if (wordStart == start) { // if couldn't even fit // first word overrun = true; // if not at start of line, return word start // to try again on a new line if (finalWidth > 0) { return wordStart; } } else if (this.wrapOption == WrapOption.WRAP) { if (this.hyphenate == Hyphenate.TRUE) { return this.doHyphenation(data,i,wordStart,this.getContentWidth() - (finalWidth + spaceWidth + pendingWidth)); } else { return wordStart; } } } } } // end of iteration over text if (prev == TEXT) { InlineArea pia = new InlineArea(currentFontState, this.red, this.green, this.blue, new String(data, wordStart, wordLength), wordWidth); pia.setUnderlined(ul); if (ls != null) { Rectangle lr = new Rectangle(finalWidth + spaceWidth + embeddedLinkStart, spaceWidth, pia.getContentWidth(), fontState.getFontSize()); ls.addRect(lr, this); } embeddedLinkStart += wordWidth; pendingAreas.addElement(pia); pendingWidth += wordWidth; wordWidth = 0; } if (overrun) MessageHandler.error(">"); return -1; } /** * adds a Leader; actually the method receives the leader properties * and creates a leader area or an inline area which is appended to * the children of the containing line area. <br> * leader pattern use-content is not implemented. */ public void addLeader(int leaderPattern, int leaderLengthMinimum, int leaderLengthOptimum, int leaderLengthMaximum, int ruleStyle, int ruleThickness, int leaderPatternWidth, int leaderAlignment) { InlineArea leaderPatternArea; int leaderLength; int remainingWidth = this.getContentWidth() - this.getCurrentXPosition(); //checks whether leaderLenghtOptimum fits into rest of line; //should never overflow, asit has been checked already in BlockArea if (remainingWidth < leaderLengthOptimum) { leaderLength = remainingWidth; } else { leaderLength = leaderLengthOptimum; } switch (leaderPattern) { case LeaderPattern.SPACE: //whitespace setting must be false for this int whiteSpaceSetting = this.whiteSpaceCollapse; this.changeWhiteSpaceCollapse(WhiteSpaceCollapse.FALSE); pendingAreas.addElement( this.buildSimpleLeader(32, leaderLength)); this.changeWhiteSpaceCollapse(whiteSpaceSetting); break; case LeaderPattern.RULE: LeaderArea leaderArea = new LeaderArea(fontState, red, green, blue, "", leaderLength, leaderPattern, ruleThickness, ruleStyle); pendingAreas.addElement(leaderArea); break; case LeaderPattern.DOTS: //if the width of a dot is larger than leader-pattern-width //ignore this property if (leaderPatternWidth < this.currentFontState.width(46)) { leaderPatternWidth = 0; } //if value of leader-pattern-width is 'use-font-metrics' (0) if (leaderPatternWidth == 0) { pendingAreas.addElement( this.buildSimpleLeader(46, leaderLength)); } else { //if leader-alignment is used, calculate space to insert before leader //so that all dots will be parallel. if (leaderAlignment == LeaderAlignment.REFERENCE_AREA) { int spaceBeforeLeader = this.getLeaderAlignIndent( leaderLength, leaderPatternWidth); //appending indent space leader-alignment //setting InlineSpace to false, so it is not used in line justification if (spaceBeforeLeader != 0) { pendingAreas.addElement( new InlineSpace(spaceBeforeLeader, false)); pendingWidth += spaceBeforeLeader; //shorten leaderLength, otherwise - in case of //leaderLength=remaining length - it will cut off the end of //leaderlength leaderLength -= spaceBeforeLeader; } } // calculate the space to insert between the dots and create a //inline area with this width InlineSpace spaceBetweenDots = new InlineSpace(leaderPatternWidth - this.currentFontState.width(46), false); leaderPatternArea = new InlineArea(currentFontState, this.red, this.green, this.blue, new String ("."), this.currentFontState.width(46)); int dotsFactor = (int) Math.floor ( ((double) leaderLength) / ((double) leaderPatternWidth)); //add combination of dot + space to fill leader //is there a way to do this in a more effective way? for (int i = 0; i < dotsFactor; i++) { pendingAreas.addElement(leaderPatternArea); pendingAreas.addElement(spaceBetweenDots); } //append at the end some space to fill up to leader length pendingAreas.addElement( new InlineSpace(leaderLength - dotsFactor * leaderPatternWidth)); } break; //leader pattern use-content not implemented. case LeaderPattern.USECONTENT: MessageHandler.errorln( "leader-pattern=\"use-content\" not " + "supported by this version of Fop"); return; } //adds leader length to length of pending inline areas pendingWidth += leaderLength; //sets prev to TEXT and makes so sure, that also blocks only //containing leaders are processed prev = TEXT; } /** * adds pending inline areas to the line area * normally done, when the line area is filled and * added as child to the parent block area */ public void addPending() { if (spaceWidth > 0) { addChild(new InlineSpace(spaceWidth)); finalWidth += spaceWidth; spaceWidth = 0; } Enumeration e = pendingAreas.elements(); while (e.hasMoreElements()) { Box box = (Box) e.nextElement(); addChild(box); } finalWidth += pendingWidth; // reset pending areas array pendingWidth = 0; pendingAreas = new Vector(); } /** * aligns line area * */ public void align(int type) { int padding = 0; switch (type) { case TextAlign.START: // left padding = this.getContentWidth() - finalWidth; endIndent += padding; break; case TextAlign.END: // right padding = this.getContentWidth() - finalWidth; startIndent += padding; break; case TextAlign.CENTER: // center padding = (this.getContentWidth() - finalWidth) / 2; startIndent += padding; endIndent += padding; break; case TextAlign.JUSTIFY: // justify Vector spaceList = new Vector(); int spaceCount = 0; Enumeration e = children.elements(); while (e.hasMoreElements()) { Box b = (Box) e.nextElement(); if (b instanceof InlineSpace) { InlineSpace space = (InlineSpace) b; if (space.getResizeable()) { spaceList.addElement(space); spaceCount++; } } } if (spaceCount > 0) { padding = (this.getContentWidth() - finalWidth) / spaceCount; } else { // no spaces padding = 0; } Enumeration f = spaceList.elements(); while (f.hasMoreElements()) { InlineSpace space2 = (InlineSpace) f.nextElement(); int i = space2.getSize(); space2.setSize(i + padding); } } } public void changeColor(float red, float green, float blue) { this.red = red; this.green = green; this.blue = blue; } public void changeFont(FontState fontState) { this.currentFontState = fontState; } public void changeWhiteSpaceCollapse(int whiteSpaceCollapse) { this.whiteSpaceCollapse = whiteSpaceCollapse; } public void changeWrapOption(int wrapOption) { this.wrapOption = wrapOption; } public int getEndIndent() { return endIndent; } public int getHeight() { return this.allocationHeight; } public int getPlacementOffset() { return this.placementOffset; } public int getStartIndent() { return startIndent; } public boolean isEmpty() { return (prev == 0); } public Vector getPendingAreas() { return pendingAreas; } public int getPendingWidth() { return pendingWidth; } public void setPendingAreas(Vector areas) { pendingAreas = areas; } public void setPendingWidth(int width) { pendingWidth = width; } /** * sets hyphenation related traits: language, country, hyphenate, hyphenation-character * and minimum number of character to remain one the previous line and to be on the * next line. */ public void changeHyphenation(String language, String country, int hyphenate, char hyphenationChar, int hyphenationPushCharacterCount, int hyphenationRemainCharacterCount) { this.language = language; this.country = country; this.hyphenate = hyphenate; this.hyphenationChar = hyphenationChar; this.hyphenationPushCharacterCount = hyphenationPushCharacterCount; this.hyphenationRemainCharacterCount = hyphenationRemainCharacterCount; } /** * creates a leader as String out of the given char and the leader length * and wraps it in an InlineArea which is returned */ private InlineArea buildSimpleLeader(int charNumber, int leaderLength) { int factor = (int) Math.floor (leaderLength / this.currentFontState.width(charNumber)); char [] leaderChars = new char [factor]; char fillChar = (char) charNumber; for (int i = 0; i < factor; i ++) { leaderChars[i] = fillChar; } InlineArea leaderPatternArea = new InlineArea(currentFontState, this.red, this.green, this.blue, new String (leaderChars), leaderLength); return leaderPatternArea; } /** * calculates the width of space which has to be inserted before the * start of the leader, so that all leader characters are aligned. * is used if property leader-align is set. At the moment only the value * for leader-align="reference-area" is supported. * */ private int getLeaderAlignIndent (int leaderLength, int leaderPatternWidth) { //calculate position of used space in line area double position = getCurrentXPosition(); //calculate factor of next leader pattern cycle double nextRepeatedLeaderPatternCycle = Math.ceil(position / leaderPatternWidth); //calculate difference between start of next leader //pattern cycle and already used space double difference = (leaderPatternWidth * nextRepeatedLeaderPatternCycle) - position; return (int) difference; } /** * calculates the used space in this line area */ private int getCurrentXPosition() { return finalWidth + spaceWidth + startIndent + pendingWidth; } /** * extracts a complete word from the character data */ private String getHyphenationWord (char [] characters, int wordStart) { boolean wordendFound = false; int counter = 0; char [] newWord = new char [100]; //create a buffer while ((!wordendFound) && ((wordStart + counter) < characters.length)) { char tk = characters[wordStart+counter]; if (Character.isLetter(tk)) { newWord[counter] = tk; counter++; } else { wordendFound = true; } } return new String (newWord,0,counter); } /** extracts word for hyphenation and calls hyphenation package, * handles cases of inword punctuation and quotation marks at the beginning * of words, but not in a internationalized way */ private int doHyphenation (char [] characters, int position, int wordStart, int remainingWidth) { //check whether the language property has been set if (this.language.equalsIgnoreCase("none")) { MessageHandler.errorln("if property 'hyphenate' is used, a language must be specified"); return wordStart; } /** remaining part string of hyphenation */ StringBuffer remainingString = new StringBuffer(); /** for words with some inword punctuation like / or - */ StringBuffer preString = null; /** char before the word, probably whitespace */ char startChar = ' ' ;//characters[wordStart-1]; /** in word punctuation character */ char inwordPunctuation; /** the complete word handed to the hyphenator */ String wordToHyphenate; //width of hyphenation character int hyphCharWidth = this.currentFontState.width(this.hyphenationChar); remainingWidth -= hyphCharWidth; //handles ' or " at the beginning of the word if (characters[wordStart] == '"' || characters[wordStart] == '\'' ) { remainingString.append(characters[wordStart]); //extracts whole word from string wordToHyphenate = getHyphenationWord(characters,wordStart+1); } else { wordToHyphenate = getHyphenationWord(characters,wordStart); } //if the extracted word is smaller than the remaining width //we have a non letter character inside the word. at the moment //we will only handle hard hyphens and slashes if (getWordWidth(wordToHyphenate)< remainingWidth) { inwordPunctuation = characters[wordStart+wordToHyphenate.length()]; if (inwordPunctuation == '-' || inwordPunctuation == '/' ) { preString = new StringBuffer(wordToHyphenate); preString = preString.append(inwordPunctuation); wordToHyphenate = getHyphenationWord(characters,wordStart+wordToHyphenate.length()+1); remainingWidth -= (getWordWidth(wordToHyphenate) + this.currentFontState.width(inwordPunctuation)); } } //are there any hyphenation points Hyphenation hyph = Hyphenator.hyphenate(language,country,wordToHyphenate,hyphenationRemainCharacterCount,hyphenationPushCharacterCount); //no hyphenation points and no inword non letter character if (hyph == null && preString == null) { if (remainingString.length() > 0) { return wordStart-1; } else { return wordStart; } //no hyphenation points, but a inword non-letter character } else if (hyph == null && preString != null){ remainingString.append(preString); this.addWord(startChar,remainingString); return wordStart + remainingString.length(); //hyphenation points and no inword non-letter character } else if (hyph != null && preString == null) { int index = getFinalHyphenationPoint(hyph,remainingWidth); if (index != -1) { remainingString.append(hyph.getPreHyphenText(index)); remainingString.append(this.hyphenationChar); this.addWord(startChar,remainingString); return wordStart + remainingString.length()-1; } //hyphenation points and a inword non letter character } else if (hyph != null && preString != null) { int index = getFinalHyphenationPoint(hyph,remainingWidth); if (index != -1) { remainingString.append(preString.append(hyph.getPreHyphenText(index))); remainingString.append(this.hyphenationChar); this.addWord(startChar,remainingString); return wordStart + remainingString.length()-1; } else { remainingString.append(preString) ; this.addWord(startChar,remainingString); return wordStart + remainingString.length(); } } return wordStart; } /** calculates the wordWidth using the actual fontstate*/ private int getWordWidth (String word) { int wordLength = word.length(); int width = 0; char [] characters = new char [wordLength]; word.getChars(0,wordLength,characters,0); for (int i = 0; i < wordLength; i++) { width += this.currentFontState.width(characters[i]); } return width; } /** adds a single character to the line area tree*/ public int addCharacter (char data, LinkSet ls, boolean ul) { InlineArea ia = null; int remainingWidth = this.getContentWidth() - this.getCurrentXPosition(); int width = this.currentFontState.width(data); //if it doesn't fit, return if (width > remainingWidth) { return org.apache.fop.fo.flow.Character.DOESNOT_FIT; } else { //if whitespace-collapse == true, discard character if (Character.isSpaceChar(data) && whiteSpaceCollapse == WhiteSpaceCollapse.TRUE) { return org.apache.fop.fo.flow.Character.OK; } //create new InlineArea ia = new InlineArea(currentFontState, this.red, this.green, this.blue, new Character(data).toString(),width); ia.setUnderlined(ul); pendingAreas.addElement(ia); if (Character.isSpaceChar(data)) { this.spaceWidth =+ width; prev = LineArea.WHITESPACE; } else { pendingWidth += width; prev = LineArea.TEXT; } return org.apache.fop.fo.flow.Character.OK; } } /** adds a InlineArea containing the String startChar+wordBuf to the line area children. */ private void addWord (char startChar, StringBuffer wordBuf) { String word = wordBuf.toString(); InlineArea hia; int startCharWidth = this.currentFontState.width(startChar); if (startChar == ' ') { this.addChild(new InlineSpace(startCharWidth)); } else { hia = new InlineArea(currentFontState, this.red, this.green, this.blue, new Character(startChar).toString(),1); this.addChild(hia); } int wordWidth = this.getWordWidth(word); hia = new InlineArea(currentFontState, this.red, this.green, this.blue, word,word.length()); this.addChild(hia); //calculate the space needed finalWidth += startCharWidth + wordWidth ; } /** extracts from a hyphenated word the best (most greedy) fit */ private int getFinalHyphenationPoint(Hyphenation hyph, int remainingWidth) { int [] hyphenationPoints = hyph.getHyphenationPoints(); int numberOfHyphenationPoints = hyphenationPoints.length; int index = -1; String wordBegin = ""; int wordBeginWidth = 0; for (int i = 0;i < numberOfHyphenationPoints; i++){ wordBegin = hyph.getPreHyphenText(i); if (this.getWordWidth(wordBegin) > remainingWidth){ break; } index = i; } return index; } }
true
true
public int addText(char odata[], int start, int end, LinkSet ls, boolean ul) { boolean overrun = false; wordStart = start; wordLength = 0; wordWidth = 0; char[] data = new char[odata.length]; for (int count = 0; count < odata.length; count++) { data[count] = odata[count]; } /* iterate over each character */ for (int i = start; i < end; i++) { int charWidth; /* get the character */ char c = data[i]; if (c > 127) { /* this class shouldn't be hard coded */ char d = org.apache.fop.render.pdf.CodePointMapping.map[c]; if (d != 0) { c = data[i] = d; } else { MessageHandler.error("ch" + (int) c + "?"); c = data[i] = '#'; } } charWidth = currentFontState.width(c); if ((c == ' ') || (c == '\n') || (c == '\r') || (c == '\t')) { // whitespace if (prev == WHITESPACE) { // if current & previous are WHITESPACE if (this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE) { if (c == ' ') { spaceWidth += currentFontState.width(32); } else if (c == '\n') { // force line break return i; } else if (c == '\t') { spaceWidth += 8 * currentFontState.width(32); } } // else ignore it } else if (prev == TEXT) { // if current is WHITESPACE and previous TEXT // the current word made it, so // add the space before the current word (if there // was some) if (spaceWidth > 0) { addChild(new InlineSpace(spaceWidth)); finalWidth += spaceWidth; spaceWidth = 0; } // add any pending areas Enumeration e = pendingAreas.elements(); while (e.hasMoreElements()) { Box box = (Box) e.nextElement(); if (box instanceof InlineArea) { if (ls != null) { Rectangle lr = new Rectangle(finalWidth, 0, ((InlineArea) box). getContentWidth(), fontState.getFontSize()); ls.addRect(lr, this); } } addChild(box); } finalWidth += pendingWidth; // reset pending areas array pendingWidth = 0; pendingAreas = new Vector(); // add the current word if (wordLength > 0) { InlineArea ia = new InlineArea(currentFontState, this.red, this.green, this.blue, new String(data, wordStart, wordLength), wordWidth); ia.setUnderlined(ul); addChild(ia); if (ls != null) { Rectangle lr = new Rectangle(finalWidth, 0, ia.getContentWidth(), fontState.getFontSize()); ls.addRect(lr, this); } finalWidth += wordWidth; // reset word width wordWidth = 0; } // deal with this new whitespace following the // word we just added prev = WHITESPACE; embeddedLinkStart = 0; //reset embeddedLinkStart since a space was encountered spaceWidth = currentFontState.width(32); /* here is the place for space-treatment value 'ignore': if (this.spaceTreatment == SpaceTreatment.IGNORE) { // do nothing } else { spaceWidth = currentFontState.width(32); } */ if (this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE) { if (c == '\n') { // force a line break return i; } else if (c == '\t') { spaceWidth = currentFontState.width(32); } } } else { // if current is WHITESPACE and no previous if (this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE) { prev = WHITESPACE; spaceWidth = currentFontState.width(32); } else { // skip over it start++; } } } else { // current is TEXT if (prev == WHITESPACE) { // if current is TEXT and previous WHITESPACE wordWidth = charWidth; if ((finalWidth + spaceWidth + wordWidth) > this.getContentWidth()) { if (overrun) MessageHandler.error(">"); if (this.wrapOption == WrapOption.WRAP) return i; } prev = TEXT; wordStart = i; wordLength = 1; } else if (prev == TEXT) { wordLength++; wordWidth += charWidth; } else { // nothing previous prev = TEXT; wordStart = i; wordLength = 1; wordWidth = charWidth; } if ((finalWidth + spaceWidth + pendingWidth + wordWidth) > this.getContentWidth()) { // BREAK MID WORD if (wordStart == start) { // if couldn't even fit // first word overrun = true; // if not at start of line, return word start // to try again on a new line if (finalWidth > 0) { return wordStart; } } else if (this.wrapOption == WrapOption.WRAP) { if (this.hyphenate == Hyphenate.TRUE) { return this.doHyphenation(data,i,wordStart,this.getContentWidth() - (finalWidth + spaceWidth + pendingWidth)); } else { return wordStart; } } } } } // end of iteration over text if (prev == TEXT) { InlineArea pia = new InlineArea(currentFontState, this.red, this.green, this.blue, new String(data, wordStart, wordLength), wordWidth); pia.setUnderlined(ul); if (ls != null) { Rectangle lr = new Rectangle(finalWidth + spaceWidth + embeddedLinkStart, spaceWidth, pia.getContentWidth(), fontState.getFontSize()); ls.addRect(lr, this); } embeddedLinkStart += wordWidth; pendingAreas.addElement(pia); pendingWidth += wordWidth; wordWidth = 0; } if (overrun) MessageHandler.error(">"); return -1; }
public int addText(char odata[], int start, int end, LinkSet ls, boolean ul) { // this prevents an array index out of bounds // which occurs when some text is laid out again. if(start == -1) return -1; boolean overrun = false; wordStart = start; wordLength = 0; wordWidth = 0; char[] data = new char[odata.length]; for (int count = 0; count < odata.length; count++) { data[count] = odata[count]; } /* iterate over each character */ for (int i = start; i < end; i++) { int charWidth; /* get the character */ char c = data[i]; if (c > 127) { /* this class shouldn't be hard coded */ char d = org.apache.fop.render.pdf.CodePointMapping.map[c]; if (d != 0) { c = data[i] = d; } else { MessageHandler.error("ch" + (int) c + "?"); c = data[i] = '#'; } } charWidth = currentFontState.width(c); if ((c == ' ') || (c == '\n') || (c == '\r') || (c == '\t')) { // whitespace if (prev == WHITESPACE) { // if current & previous are WHITESPACE if (this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE) { if (c == ' ') { spaceWidth += currentFontState.width(32); } else if (c == '\n') { // force line break return i; } else if (c == '\t') { spaceWidth += 8 * currentFontState.width(32); } } // else ignore it } else if (prev == TEXT) { // if current is WHITESPACE and previous TEXT // the current word made it, so // add the space before the current word (if there // was some) if (spaceWidth > 0) { addChild(new InlineSpace(spaceWidth)); finalWidth += spaceWidth; spaceWidth = 0; } // add any pending areas Enumeration e = pendingAreas.elements(); while (e.hasMoreElements()) { Box box = (Box) e.nextElement(); if (box instanceof InlineArea) { if (ls != null) { Rectangle lr = new Rectangle(finalWidth, 0, ((InlineArea) box). getContentWidth(), fontState.getFontSize()); ls.addRect(lr, this); } } addChild(box); } finalWidth += pendingWidth; // reset pending areas array pendingWidth = 0; pendingAreas = new Vector(); // add the current word if (wordLength > 0) { InlineArea ia = new InlineArea(currentFontState, this.red, this.green, this.blue, new String(data, wordStart, wordLength), wordWidth); ia.setUnderlined(ul); addChild(ia); if (ls != null) { Rectangle lr = new Rectangle(finalWidth, 0, ia.getContentWidth(), fontState.getFontSize()); ls.addRect(lr, this); } finalWidth += wordWidth; // reset word width wordWidth = 0; } // deal with this new whitespace following the // word we just added prev = WHITESPACE; embeddedLinkStart = 0; //reset embeddedLinkStart since a space was encountered spaceWidth = currentFontState.width(32); /* here is the place for space-treatment value 'ignore': if (this.spaceTreatment == SpaceTreatment.IGNORE) { // do nothing } else { spaceWidth = currentFontState.width(32); } */ if (this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE) { if (c == '\n') { // force a line break return i; } else if (c == '\t') { spaceWidth = currentFontState.width(32); } } } else { // if current is WHITESPACE and no previous if (this.whiteSpaceCollapse == WhiteSpaceCollapse.FALSE) { prev = WHITESPACE; spaceWidth = currentFontState.width(32); } else { // skip over it start++; } } } else { // current is TEXT if (prev == WHITESPACE) { // if current is TEXT and previous WHITESPACE wordWidth = charWidth; if ((finalWidth + spaceWidth + wordWidth) > this.getContentWidth()) { if (overrun) MessageHandler.error(">"); if (this.wrapOption == WrapOption.WRAP) return i; } prev = TEXT; wordStart = i; wordLength = 1; } else if (prev == TEXT) { wordLength++; wordWidth += charWidth; } else { // nothing previous prev = TEXT; wordStart = i; wordLength = 1; wordWidth = charWidth; } if ((finalWidth + spaceWidth + pendingWidth + wordWidth) > this.getContentWidth()) { // BREAK MID WORD if (wordStart == start) { // if couldn't even fit // first word overrun = true; // if not at start of line, return word start // to try again on a new line if (finalWidth > 0) { return wordStart; } } else if (this.wrapOption == WrapOption.WRAP) { if (this.hyphenate == Hyphenate.TRUE) { return this.doHyphenation(data,i,wordStart,this.getContentWidth() - (finalWidth + spaceWidth + pendingWidth)); } else { return wordStart; } } } } } // end of iteration over text if (prev == TEXT) { InlineArea pia = new InlineArea(currentFontState, this.red, this.green, this.blue, new String(data, wordStart, wordLength), wordWidth); pia.setUnderlined(ul); if (ls != null) { Rectangle lr = new Rectangle(finalWidth + spaceWidth + embeddedLinkStart, spaceWidth, pia.getContentWidth(), fontState.getFontSize()); ls.addRect(lr, this); } embeddedLinkStart += wordWidth; pendingAreas.addElement(pia); pendingWidth += wordWidth; wordWidth = 0; } if (overrun) MessageHandler.error(">"); return -1; }
diff --git a/src/com/hoos/around/StaticUserInfo.java b/src/com/hoos/around/StaticUserInfo.java index 81ecbd2..0f7749b 100644 --- a/src/com/hoos/around/StaticUserInfo.java +++ b/src/com/hoos/around/StaticUserInfo.java @@ -1,105 +1,105 @@ package com.hoos.around; import java.util.ArrayList; import java.util.HashSet; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.facebook.android.FacebookError; import com.facebook.android.Util; import com.loopj.android.http.JsonHttpResponseHandler; public class StaticUserInfo { static private int user_id; //user id stored in mysql db static private String fb_id; //facebook's user id for logged in user static private HashSet<String> fb_friends = new HashSet<String>(); //list of facebook friends of user static private Boolean logged_in = false; static private Boolean Error = false; static Boolean isLoggedIn() { return logged_in; } static void isLoggedIn(Boolean status) { logged_in = status; } static void setUserID(int id) { logged_in = true; user_id = id; } static int getUserID() { return user_id; } static void unSetID() { user_id = 0; logged_in = false; } public static String getFbID() { return fb_id; } public static void setFbID(String fb_id) { StaticUserInfo.fb_id = fb_id; } public static HashSet<String> getFbFriends() { return fb_friends; } public static void setFbFriends(final HashSet<String> friends) { RestClient.get("/users/view/", null, null, new JsonHttpResponseHandler() { @Override public void onSuccess(JSONArray rsp) { for (int i=0; i<rsp.length(); i++) { - try { - JSONObject user = rsp.getJSONObject(i); - String fb_id = user.optJSONObject("User").getString("fb_id"); - System.out.println("checking " + fb_id); - if (friends.contains(fb_id)) { - System.out.println("f: " + fb_id); - fb_friends.add(fb_id); + try { + JSONObject user = rsp.getJSONObject(i); + String fb_id = user.optJSONObject("User").getString("fb_id"); + System.out.println("checking " + fb_id); + if (friends.contains(fb_id)) { + System.out.println("f: " + fb_id); + fb_friends.add(fb_id); + } + } catch (JSONException e) { + // TODO Auto-generated catch block + Log.d("FACEBOOK_FRIENDS", e.getMessage()); } - } catch (JSONException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } } } @Override public void onFailure(Throwable e, String rsp) { } }); } //checks to see if friend is HoosAround user and if so adds them public static void addFbFriend(String friend) { final String fr = friend; //needs to be final to be used in inner class RestClient.get("/users/fb_id/"+friend, null, null, new JsonHttpResponseHandler() { @Override public void onSuccess(JSONArray rsp) { if (rsp.length()>0) { //friend exists in HoosAround db fb_friends.add(fr); } else { //friend is not HoosAround user } } @Override public void onFailure(Throwable e, String rsp) { Log.d("JSON", rsp); Log.d("JSON", RestClient.getAbsoluteUrl("/users/fb_id/"+fr)); } }); } }
false
true
public static void setFbFriends(final HashSet<String> friends) { RestClient.get("/users/view/", null, null, new JsonHttpResponseHandler() { @Override public void onSuccess(JSONArray rsp) { for (int i=0; i<rsp.length(); i++) { try { JSONObject user = rsp.getJSONObject(i); String fb_id = user.optJSONObject("User").getString("fb_id"); System.out.println("checking " + fb_id); if (friends.contains(fb_id)) { System.out.println("f: " + fb_id); fb_friends.add(fb_id); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } @Override public void onFailure(Throwable e, String rsp) { } }); }
public static void setFbFriends(final HashSet<String> friends) { RestClient.get("/users/view/", null, null, new JsonHttpResponseHandler() { @Override public void onSuccess(JSONArray rsp) { for (int i=0; i<rsp.length(); i++) { try { JSONObject user = rsp.getJSONObject(i); String fb_id = user.optJSONObject("User").getString("fb_id"); System.out.println("checking " + fb_id); if (friends.contains(fb_id)) { System.out.println("f: " + fb_id); fb_friends.add(fb_id); } } catch (JSONException e) { // TODO Auto-generated catch block Log.d("FACEBOOK_FRIENDS", e.getMessage()); } } } @Override public void onFailure(Throwable e, String rsp) { } }); }